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 — and `#604`: updated when `/reasoning --global`
554    /// writes the file. It used to be left as loaded, so the dial kept saying "config.toml says
555    /// low" about a file that now said something else, and `default` reverted to the old level.
556    configured: std::sync::Mutex<Option<String>>,
557    /// `/reasoning <level>` for this process. `None` = follow the configuration; `Some(None)` =
558    /// follow it *and* ignore it, which is what `/reasoning default` means after a session override.
559    session: std::sync::Mutex<Option<Option<String>>>,
560}
561
562impl Dial {
563    pub fn new(configured: Option<String>) -> Self {
564        Self {
565            configured: std::sync::Mutex::new(clean(configured.as_deref())),
566            session: std::sync::Mutex::new(None),
567        }
568    }
569
570    /// `#604`: what `/reasoning --global <level>` just wrote to the file, so the next report says
571    /// the file's level instead of the one this process started with.
572    pub fn set_configured(&self, level: Option<&str>) {
573        let mut configured = self.configured.lock().unwrap_or_else(|e| e.into_inner());
574        *configured = clean(level);
575    }
576
577    /// What the next request should ask for: the session's override, else the configuration.
578    pub fn effort(&self) -> Option<String> {
579        let session = self.session.lock().unwrap_or_else(|e| e.into_inner());
580        match session.as_ref() {
581            Some(level) => level.clone(),
582            None => self.configured(),
583        }
584    }
585
586    /// `/reasoning <level>`: from the next request on, in this process only.
587    pub fn set_session(&self, level: Option<String>) {
588        let mut session = self.session.lock().unwrap_or_else(|e| e.into_inner());
589        *session = Some(level.map(|l| l.trim().to_lowercase()));
590    }
591
592    /// Drop the override: the configuration is in force again.
593    pub fn clear_session(&self) {
594        let mut session = self.session.lock().unwrap_or_else(|e| e.into_inner());
595        *session = None;
596    }
597
598    /// What was configured, for a report that has to say "the same as the file".
599    pub fn configured(&self) -> Option<String> {
600        self.configured
601            .lock()
602            .unwrap_or_else(|e| e.into_inner())
603            .clone()
604    }
605
606    /// Whether a session override is in force.
607    pub fn overridden(&self) -> bool {
608        self.session
609            .lock()
610            .unwrap_or_else(|e| e.into_inner())
611            .is_some()
612    }
613
614    /// The level in force, with the one clause that makes an override visible: `high`,
615    /// `high (this session; config.toml says low)`, `medium (this backend's default; config.toml
616    /// sets nothing)`, or `not sent`.
617    ///
618    /// This is the read-out's wording and `/reasoning`'s, from one function, so the line under the
619    /// composer cannot claim a level the report does not. Three answers, because a dial has three:
620    /// the session asked (`/reasoning high`), the file asked, or neither did and the route's own
621    /// policy supplies the shipped default (`#276`). `not sent` is the fourth case and a fact, not
622    /// a shrug: the backend takes no level, or nobody declared one, so the field is not on the wire.
623    pub fn in_force(&self) -> String {
624        self.resolution(None).1
625    }
626
627    /// What is in force, and where it came from: `(level, wording)`.
628    ///
629    /// `default` is the route's declared default — [`crate::provider::Reasoning::declared_default`]
630    /// — and it is a parameter rather than a field because a route changes under a live dial
631    /// (`/model`), and a copy taken at construction is how a read-out starts describing a backend
632    /// the session left behind.
633    fn resolution(&self, default: Option<&str>) -> (Option<String>, String) {
634        let session = self.session.lock().unwrap_or_else(|e| e.into_inner());
635        let session_level = session.clone();
636        drop(session);
637        match session_level {
638            // `/reasoning <level>`: the session's own answer, and it says so. `omit` is a word a
639            // session may choose (`#278`), and the report calls the outcome what it is.
640            Some(Some(level)) => {
641                let label = (!is_omit(&level)).then(|| level.clone());
642                let word = shown(label.as_deref());
643                let said = match self.configured() {
644                    Some(configured) if is_omit(&configured) => {
645                        format!("{word} (this session; config.toml asks for no field)")
646                    }
647                    Some(configured) => {
648                        format!("{word} (this session; config.toml says {configured})")
649                    }
650                    None => format!("{word} (this session; config.toml sets nothing)"),
651                };
652                (label, said)
653            }
654            // `/reasoning default` after an override, or an override that asked for nothing:
655            // the session decided, and what it decided is "no field".
656            Some(None) => {
657                let said = match self.configured() {
658                    Some(configured) if is_omit(&configured) => {
659                        format!("{NOT_SENT} (this session; config.toml asks for no field)")
660                    }
661                    Some(configured) => {
662                        format!("{NOT_SENT} (this session; config.toml says {configured})")
663                    }
664                    None => format!("{NOT_SENT} (this session; config.toml sets nothing)"),
665                };
666                (None, said)
667            }
668            None => match self.configured() {
669                Some(configured) if is_omit(&configured) => {
670                    (None, format!("{NOT_SENT} (config.toml asks for no field)"))
671                }
672                Some(configured) => (Some(configured.to_string()), configured.to_string()),
673                // Nobody set it: the route's declared default is the shipped answer, and the
674                // wording says so rather than pretending the file named it.
675                None => match clean(default) {
676                    Some(level) if is_omit(&level) => (
677                        None,
678                        format!("{NOT_SENT} (this backend's default; config.toml sets nothing)"),
679                    ),
680                    Some(level) => (
681                        Some(level.clone()),
682                        format!("{level} (this backend's default; config.toml sets nothing)"),
683                    ),
684                    None => (None, NOT_SENT.to_string()),
685                },
686            },
687        }
688    }
689}
690
691/// What a report calls a level: the level itself, or `not sent` when there is none — which is what
692/// the `omit` sentinel resolves to (`#278`).
693fn shown(level: Option<&str>) -> String {
694    level.unwrap_or(NOT_SENT).to_string()
695}
696
697/// A level as the dial holds them: trimmed, lowercased, empty means absent.
698fn clean(level: Option<&str>) -> Option<String> {
699    level
700        .map(|l| l.trim().to_lowercase())
701        .filter(|l| !l.is_empty())
702}
703
704/// The effort in force, in the forms each surface needs (`#264`).
705///
706/// One struct rather than four parallel strings, because the line under the composer, the
707/// full-screen read-out, `/status` and the dashboard all answer the same question and had all been
708/// answering it differently — three of them by silence.
709#[derive(Debug, Clone, PartialEq, Eq, Default)]
710pub struct InForce {
711    /// `high`, or `not sent` — the read-out's form, short enough for a line that is already full.
712    pub label: String,
713    /// `high (this session; config.toml says low)` — `/reasoning`'s and `/status`'s form.
714    pub in_force: String,
715    /// Whether `/reasoning` moved it for this process.
716    pub session: bool,
717    /// The level came from the backend's declared default, not from the file or the session: the
718    /// one origin a reader would otherwise have to guess at, because nothing in `config.toml` says
719    /// it.
720    pub by_default: bool,
721    /// What that level becomes on the route in force, in the provider's own words. Empty when
722    /// nobody could resolve it — a read-out that filled this in from a table would be the second
723    /// guess `/reasoning` exists to prevent.
724    pub resolved: String,
725}
726
727impl InForce {
728    /// The whole thing in one sentence: the level and its origin, then the field it is sent as.
729    ///
730    /// One formatter, because `/status`, the dashboard's `title` and the full-screen interface's
731    /// tooltip all describe one dial — and three copies of that sentence is how a read-out starts
732    /// disagreeing with a command about the same session (`#264`).
733    pub fn sentence(&self) -> String {
734        if self.resolved.is_empty() {
735            return self.in_force.clone();
736        }
737        // "not sent" is already the whole answer, and the backend's reason stands in for it:
738        // "not sent · on this backend: not sent: nothing asked" is one contradiction too many.
739        if self.label == NOT_SENT {
740            return self.resolved.clone();
741        }
742        format!("{} · on this backend: {}", self.in_force, self.resolved)
743    }
744}
745
746impl Dial {
747    /// The dial's own half of [`InForce`]: what it will ask for, why, and what that becomes.
748    ///
749    /// `default` is the route in force's declared default (`#276`): `Some("medium")` on both
750    /// shipped profiles, `None` for a backend that declares no policy or no default. With no
751    /// session override and no file value, that is the level the next request carries — and the
752    /// label says `not sent`, not a guessed level, when even that is absent.
753    pub fn in_force_report(&self, default: Option<&str>) -> InForce {
754        let (level, in_force) = self.resolution(default);
755        InForce {
756            label: level.clone().unwrap_or_else(|| NOT_SENT.to_string()),
757            by_default: level.is_some() && !self.overridden() && self.configured().is_none(),
758            in_force,
759            session: self.overridden(),
760            resolved: String::new(),
761        }
762    }
763}
764
765/// The whole report for a dial and the route behind it: the one construction every front uses.
766///
767/// `control` is what the next request's route resolves to ([`crate::provider::Reasoning`]), and it
768/// supplies both halves the dial cannot answer alone — the declared default (`#276`) and the
769/// backend's own sentence for what a level becomes. `Agent::reasoning_report()`, the full-screen
770/// read-out and `/reasoning` all call this, so a surface cannot describe the dial differently from
771/// the command that moved it.
772pub fn report_for(dial: &Dial, control: Option<&crate::provider::Reasoning>) -> InForce {
773    let mut report = dial.in_force_report(control.and_then(|c| c.declared_default()));
774    report.resolved = sentence(control, dial.effort().as_deref());
775    report
776}
777
778/// A dial every route of one session shares.
779pub type Shared = std::sync::Arc<Dial>;
780
781/// One sentence for a level, given the control a route resolved to. The single wording for
782/// `/reasoning`, the launch panel and the readout, so a clamp is described the same way wherever it
783/// is reported.
784///
785/// `None` means this agent could not resolve a profile at all — not "no reasoning control", which
786/// is [`crate::provider::Reasoning::Off`].
787pub fn sentence(control: Option<&crate::provider::Reasoning>, level: Option<&str>) -> String {
788    use crate::provider::Reasoning;
789    match control {
790        None => "unknown: this agent has no provider configuration to describe".to_string(),
791        Some(Reasoning::Policy(policy)) => policy.describe(level),
792        Some(Reasoning::Off) => "no reasoning control on this model".to_string(),
793        Some(Reasoning::Undeclared) => match level {
794            Some(_) => "sent as-is (this backend declares no reasoning control)".to_string(),
795            None => "not sent: nothing was asked and nothing is configured".to_string(),
796        },
797    }
798}
799
800#[cfg(test)]
801mod tests {
802    use super::*;
803
804    /// `#278`: the sentinel answers before the ladder, so no policy can clamp it into a level that
805    /// is sent — and the sentence says it was a decision, not an absence.
806    #[test]
807    fn the_omit_sentinel_is_answered_before_the_ladder_and_says_so() {
808        for policy in [Policy::openai(), Policy::llamacpp()] {
809            assert_eq!(
810                policy.resolve(Some(OMIT)),
811                Wire::Omit(Omitted::AskedToOmit),
812                "resolve({OMIT}) on a policy with a dial"
813            );
814        }
815        // A backend with no dial at all keeps its own answer: there is no field for the operator
816        // to omit, and saying "asked for no field" would hide that the model has no control.
817        assert_eq!(
818            Policy::default().resolve(Some(OMIT)),
819            Wire::Omit(Omitted::NoPolicy)
820        );
821        assert_eq!(
822            Policy::openai().describe(Some(OMIT)),
823            "not sent: asked for no field on this route"
824        );
825        // Not a level: nothing may reach it by clamping, and the menu must not offer it (the
826        // vocabulary test above holds that an offered word goes on the wire).
827        assert!(!is_level(OMIT));
828        assert!(is_omit("  OMIT "));
829        assert!(!is_omit("none"));
830        for policy in [Policy::openai(), Policy::llamacpp()] {
831            assert!(!policy.vocabulary().iter().any(|w| w == OMIT), "{policy:?}");
832        }
833    }
834
835    /// A profile may ship the sentinel as its default: the route then carries no field unless a
836    /// session asks for a level, which is how an operator keeps a config quiet without Rust.
837    #[test]
838    fn a_profile_default_of_omit_carries_no_field() {
839        let mut policy = Policy::openai();
840        policy.default = Some(OMIT.to_string());
841        assert_eq!(policy.resolve(None), Wire::Omit(Omitted::AskedToOmit));
842        assert_eq!(
843            policy.describe(None),
844            "not sent: asked for no field on this route"
845        );
846        // And a session still outranks it, which is the point of a default rather than a switch.
847        assert_eq!(
848            policy.resolve(Some("high")),
849            Wire::Set(serde_json::Value::String("high".into()))
850        );
851    }
852
853    /// The read-out's wording for a session that asked for no field: `not sent`, with the file's
854    /// own answer beside it — never the word `omit`, which is a spelling rather than a state.
855    #[test]
856    fn a_session_that_asked_for_no_field_reports_not_sent() {
857        let dial = Dial::new(Some(SHIPPED_DEFAULT.to_string()));
858        dial.set_session(Some(OMIT.to_string()));
859        let report = dial.in_force_report(Some(SHIPPED_DEFAULT));
860        assert_eq!(report.label, NOT_SENT);
861        assert_eq!(
862            report.in_force,
863            format!("{NOT_SENT} (this session; config.toml says {SHIPPED_DEFAULT})")
864        );
865        assert!(report.session);
866
867        // The same word written into the file, with no session override.
868        let configured = Dial::new(Some(OMIT.to_string()));
869        let report = configured.in_force_report(Some(SHIPPED_DEFAULT));
870        assert_eq!(report.label, NOT_SENT);
871        assert_eq!(
872            report.in_force,
873            format!("{NOT_SENT} (config.toml asks for no field)")
874        );
875    }
876
877    /// `#275`: the menu may only offer what the wire takes. `openai` has no off switch —
878    /// `reasoning_effort: "none"` is a 400 there — and `llamacpp` has one, whatever shape it takes.
879    #[test]
880    fn the_vocabulary_is_the_wires_own_and_not_a_union() {
881        assert_eq!(
882            Policy::openai().vocabulary(),
883            vec!["minimal", "low", "medium", "high"],
884            "four rungs, no off switch to offer"
885        );
886        assert_eq!(
887            Policy::llamacpp().vocabulary(),
888            vec!["low", "medium", "high", "none"],
889            "its three rungs, then the word its off switch is asked for by"
890        );
891        assert!(
892            Policy::default().vocabulary().is_empty(),
893            "a policy with no dial has nothing to offer, and saying so is the answer"
894        );
895        // Every word offered resolves to something that goes on the wire: a menu row that cannot
896        // be clicked is the bug this exists to prevent.
897        for policy in [Policy::openai(), Policy::llamacpp()] {
898            for level in policy.vocabulary() {
899                assert!(
900                    !matches!(policy.resolve(Some(&level)), Wire::Omit(_)),
901                    "{level} is offered but refused"
902                );
903            }
904        }
905    }
906
907    #[test]
908    fn the_session_override_wins_over_the_configured_level_until_it_is_cleared() {
909        let dial = Dial::new(Some("low".into()));
910        assert_eq!(dial.effort().as_deref(), Some("low"));
911        assert!(!dial.overridden());
912        dial.set_session(Some(" HIGH ".into()));
913        assert_eq!(
914            dial.effort().as_deref(),
915            Some("high"),
916            "trimmed, lowercased"
917        );
918        assert!(dial.overridden());
919        dial.clear_session();
920        assert_eq!(
921            dial.effort().as_deref(),
922            Some("low"),
923            "the configuration is back in force"
924        );
925        assert!(!dial.overridden());
926    }
927
928    /// `/reasoning default` after a session override asks for *nothing*, which is not the same as
929    /// asking for what the file says.
930    #[test]
931    fn an_explicit_absence_is_a_decision_not_a_fallthrough() {
932        let dial = Dial::new(Some("low".into()));
933        dial.set_session(None);
934        assert_eq!(dial.effort(), None);
935        assert!(dial.overridden(), "the override is still a decision");
936        dial.clear_session();
937        assert_eq!(dial.effort().as_deref(), Some("low"));
938    }
939
940    /// The read-out's wording, from the dial itself: what is in force, whether that is a session
941    /// override, and never a guessed level where nothing was asked (`#276`).
942    #[test]
943    fn in_force_names_the_level_and_says_when_the_session_moved_it() {
944        let dial = Dial::new(Some("low".into()));
945        assert_eq!(dial.in_force(), "low");
946        dial.set_session(Some("high".into()));
947        assert_eq!(dial.in_force(), "high (this session; config.toml says low)");
948        dial.set_session(None);
949        assert_eq!(
950            dial.in_force(),
951            "not sent (this session; config.toml says low)",
952            "asking for nothing is a decision, and no field is what it will send"
953        );
954        dial.clear_session();
955        assert_eq!(dial.in_force(), "low");
956
957        // Nothing configured and a route that declares nothing: `not sent`, not a guessed level.
958        let bare = Dial::new(None);
959        assert_eq!(bare.in_force(), NOT_SENT);
960        bare.set_session(Some("high".into()));
961        assert_eq!(
962            bare.in_force(),
963            "high (this session; config.toml sets nothing)"
964        );
965    }
966
967    /// `#276`: what a fresh install looks like. The file says nothing, the route declares a
968    /// default, and the read-out answers with the level the request will carry — saying where it
969    /// came from, because `config.toml` does not.
970    #[test]
971    fn a_policy_that_declares_a_default_resolves_it_and_says_the_file_did_not() {
972        let bare = Dial::new(None);
973        let report = bare.in_force_report(Some(SHIPPED_DEFAULT));
974        assert_eq!(report.label, SHIPPED_DEFAULT);
975        assert_eq!(
976            report.in_force,
977            "medium (this backend's default; config.toml sets nothing)"
978        );
979        assert!(report.by_default, "the origin is the backend, not the file");
980        assert!(!report.session);
981
982        // The file wins over the default, and the wording goes quiet about it.
983        let filed = Dial::new(Some("low".into())).in_force_report(Some(SHIPPED_DEFAULT));
984        assert_eq!(filed.label, "low");
985        assert_eq!(filed.in_force, "low");
986        assert!(!filed.by_default);
987
988        // A session override wins over both.
989        let dial = Dial::new(None);
990        dial.set_session(Some("high".into()));
991        let over = dial.in_force_report(Some(SHIPPED_DEFAULT));
992        assert_eq!(over.label, "high");
993        assert_eq!(
994            over.in_force,
995            "high (this session; config.toml sets nothing)"
996        );
997        assert!(!over.by_default);
998
999        // A route that declares no default still sends nothing, and the label says so rather
1000        // than claiming the level that is not on its wire.
1001        let undeclared = bare.in_force_report(None);
1002        assert_eq!(undeclared.label, NOT_SENT);
1003        assert_eq!(undeclared.in_force, NOT_SENT);
1004        assert!(!undeclared.by_default);
1005    }
1006
1007    /// The two shipped profiles are the reason `medium` is the answer, and the starter file is the
1008    /// same answer written down. One test, because the alternative is the drift `#245` exists to
1009    /// prevent: a file that says `medium` over a resolver that says nothing.
1010    #[test]
1011    fn the_shipped_profiles_and_the_starter_file_agree_on_the_default() {
1012        for policy in [Policy::openai(), Policy::llamacpp()] {
1013            assert_eq!(
1014                policy.default_effort(),
1015                Some(SHIPPED_DEFAULT),
1016                "a shipped profile declares the level the starter file names"
1017            );
1018            assert_eq!(
1019                policy.resolve(None),
1020                Wire::Set(serde_json::Value::String(SHIPPED_DEFAULT.into())),
1021                "and an unconfigured request carries it"
1022            );
1023        }
1024        let shipped = crate::config::starter_config().expect("the starter config generates");
1025        let starter = crate::config::Config::from_toml_str(&shipped).expect("it parses");
1026        assert_eq!(
1027            starter.provider.reasoning_effort.as_deref(),
1028            Some(SHIPPED_DEFAULT),
1029            "`config init` writes the same level on a live line"
1030        );
1031        assert!(
1032            shipped.contains(&format!("reasoning_effort = \"{SHIPPED_DEFAULT}\"")),
1033            "and it is on a line a person can read"
1034        );
1035    }
1036
1037    #[test]
1038    fn an_unset_configuration_means_no_effort_is_asked_for() {
1039        let dial = Dial::new(None);
1040        assert_eq!(dial.effort(), None);
1041        assert_eq!(dial.configured(), None);
1042        let blank = Dial::new(Some("   ".into()));
1043        assert_eq!(blank.effort(), None, "blank is absent, not a level");
1044    }
1045
1046    fn level_policy(levels: &[&str]) -> Policy {
1047        Policy {
1048            field: "reasoning_effort".into(),
1049            kind: Kind::Level,
1050            off: Some("none".into()),
1051            ollama_off: None,
1052            levels: levels.iter().map(|l| l.to_string()).collect(),
1053            map: BTreeMap::new(),
1054            default: None,
1055        }
1056    }
1057
1058    fn set(value: &str) -> Wire {
1059        Wire::Set(serde_json::Value::String(value.into()))
1060    }
1061
1062    #[test]
1063    fn a_level_the_wire_has_is_sent_verbatim() {
1064        let p = level_policy(&["low", "medium", "high"]);
1065        assert_eq!(p.resolve(Some("high")), set("high"));
1066        assert_eq!(p.resolve(Some("low")), set("low"));
1067    }
1068
1069    /// Clamping goes down, never up: asking for a level a backend does not have must not cost more
1070    /// than asking for one it does.
1071    #[test]
1072    fn a_level_it_does_not_have_clamps_to_the_nearest_weaker_one() {
1073        let three = level_policy(&["low", "medium", "high"]);
1074        assert_eq!(three.resolve(Some("xhigh")), set("high"));
1075        assert_eq!(three.resolve(Some("max")), set("high"));
1076        // Nothing weaker than `low`: the floor is the closest honest answer.
1077        let floor = level_policy(&["medium", "high"]);
1078        assert_eq!(floor.resolve(Some("low")), set("medium"));
1079        // And `minimal` on a wire that starts at `low`.
1080        assert_eq!(three.resolve(Some("minimal")), set("low"));
1081    }
1082
1083    /// `none` is the off switch, not a degradation target — and a wire that cannot be switched off
1084    /// says so rather than sending a level that would look like it had.
1085    #[test]
1086    fn off_is_its_own_answer_and_never_a_clamp_target() {
1087        let p = level_policy(&["low", "medium", "high"]);
1088        assert_eq!(p.resolve(Some("none")), set("none"));
1089        let mut no_off = level_policy(&["low", "high"]);
1090        no_off.off = None;
1091        assert_eq!(
1092            no_off.resolve(Some("none")),
1093            Wire::Omit(Omitted::NotOnThisWire)
1094        );
1095    }
1096
1097    /// A declared mapping wins over the ladder, which is how a vendor's bespoke naming is
1098    /// expressed without inventing a rung for it.
1099    #[test]
1100    fn a_declared_mapping_is_consulted_before_the_ladder() {
1101        let mut p = level_policy(&["low", "high", "max"]);
1102        p.map.insert("medium".into(), "high".into());
1103        p.map.insert("xhigh".into(), "max".into());
1104        assert_eq!(
1105            p.resolve(Some("medium")),
1106            set("high"),
1107            "K3-shaped: the middle rung is `high`"
1108        );
1109        assert_eq!(p.resolve(Some("xhigh")), set("max"));
1110        // A mapping that points at the off value is the off switch.
1111        let mut off_by_map = level_policy(&["low", "high", "max"]);
1112        off_by_map.map.insert("minimal".into(), "none".into());
1113        assert_eq!(off_by_map.resolve(Some("minimal")), set("none"));
1114    }
1115
1116    /// A bool-valued backend has an on and an off, and nothing else; a graded ask is omitted with a
1117    /// reason instead of being sent as `true` and reported as "high".
1118    #[test]
1119    fn a_bool_backend_sends_on_or_off_and_says_when_it_has_no_levels() {
1120        let p = Policy {
1121            field: "chat_template_kwargs.enable_thinking".into(),
1122            kind: Kind::Bool,
1123            // `off = false` in a manifest: the switch is a bool, and the manifest says so instead of
1124            // the code guessing from `kind`.
1125            off: Some(OffSwitch::Flag(false)),
1126            ollama_off: None,
1127            levels: vec!["low".into()],
1128            map: BTreeMap::new(),
1129            default: None,
1130        };
1131        assert_eq!(
1132            p.resolve(Some("high")),
1133            Wire::Set(serde_json::Value::Bool(true))
1134        );
1135        assert_eq!(
1136            p.resolve(Some("none")),
1137            Wire::Set(serde_json::Value::Bool(false))
1138        );
1139        assert_eq!(
1140            p.describe(Some("high")),
1141            "sends thinking on",
1142            "the report says on, not `high`"
1143        );
1144    }
1145
1146    /// A backend with an off switch and no graded dial is the measured shape of gemma on llama.cpp:
1147    /// every level it was sent produced the same number of reasoning tokens.
1148    #[test]
1149    fn an_off_only_backend_refuses_an_enabled_ask_by_name() {
1150        let p = level_policy(&[]);
1151        assert!(p.has_dial() && !p.has_levels());
1152        assert_eq!(p.resolve(Some("high")), Wire::Omit(Omitted::NoLevels));
1153        assert_eq!(p.resolve(Some("none")), set("none"));
1154        assert!(p.describe(Some("high")).contains("no levels"));
1155    }
1156
1157    #[test]
1158    fn a_model_with_no_policy_gets_no_field_at_all() {
1159        let p = Policy::default();
1160        assert!(!p.has_dial());
1161        assert_eq!(p.resolve(Some("high")), Wire::Omit(Omitted::NoPolicy));
1162        assert_eq!(
1163            p.describe(Some("high")),
1164            "no reasoning control on this backend"
1165        );
1166    }
1167
1168    /// Nothing asked and no declared default: send nothing. A default that is *declared* is sent,
1169    /// which is how "an unset effort leaves the endpoint's ceiling in charge" is fixed deliberately
1170    /// rather than by accident.
1171    #[test]
1172    fn an_unasked_level_is_omitted_unless_the_manifest_declares_a_default() {
1173        let mut p = level_policy(&["low", "medium", "high"]);
1174        assert_eq!(p.resolve(None), Wire::Omit(Omitted::NothingAsked));
1175        assert_eq!(p.describe(None).split(':').next(), Some("not sent"));
1176        p.default = Some("medium".into());
1177        assert_eq!(p.resolve(None), set("medium"));
1178        assert_eq!(p.describe(None), "sends medium");
1179    }
1180
1181    /// The field is a dotted path, so a backend that wants a nested object gets one.
1182    #[test]
1183    fn a_dotted_field_becomes_a_nested_body_key() {
1184        let p = Policy {
1185            field: "chat_template_kwargs.enable_thinking".into(),
1186            kind: Kind::Bool,
1187            // `off = false` in a manifest: the switch is a bool, and the manifest says so instead of
1188            // the code guessing from `kind`.
1189            off: Some(OffSwitch::Flag(false)),
1190            ollama_off: None,
1191            levels: Vec::new(),
1192            map: BTreeMap::new(),
1193            default: None,
1194        };
1195        assert_eq!(
1196            p.resolve(Some("none")).body(&p),
1197            serde_json::json!({"chat_template_kwargs": {"enable_thinking": false}})
1198        );
1199        let flat = level_policy(&["high"]);
1200        assert_eq!(
1201            flat.resolve(Some("high")).body(&flat),
1202            serde_json::json!({"reasoning_effort": "high"})
1203        );
1204    }
1205
1206    /// A bespoke level a custom endpoint invented is passed through rather than dropped: the ladder
1207    /// is Hermes'/Pi's vocabulary, not a closed set every server agrees on.
1208    #[test]
1209    fn a_bespoke_level_passes_through_when_the_wire_lists_it() {
1210        let p = level_policy(&["low", "turbo"]);
1211        assert_eq!(p.resolve(Some("turbo")), set("turbo"));
1212        // And one nobody lists is refused with the level named.
1213        assert_eq!(p.resolve(Some("warp")), Wire::Omit(Omitted::NotOnThisWire));
1214        assert!(p.describe(Some("warp")).contains("warp"));
1215    }
1216
1217    #[test]
1218    fn the_ladder_is_ordered_and_answers_what_it_accepts() {
1219        for level in LADDER {
1220            assert!(is_level(level), "{level}");
1221        }
1222        assert!(is_level(" HIGH "), "trimmed and lowercased");
1223        assert!(!is_level("turbo"));
1224        assert!(!is_level(""));
1225    }
1226}