eclipse-core 0.14.0

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
//! How much a model thinks, and where the number goes.
//!
//! Two halves, and the split is the point. **What the user asks for** is one ladder, shared by every
//! backend: `none < minimal < low < medium < high < xhigh < max`. **What a backend accepts** is not
//! knowable from here — llama.cpp takes a graded `reasoning_effort` on some models and ignores it on
//! others, a bool-valued chat-template kwarg is the only switch on a third, and an endpoint may
//! reject a level with a 400 — so it is *declared*, per provider profile and per model, in an
//! editable manifest (see the `[[provider_profile.reasoning]]` table). This module holds the math
//! and the manifest shape; the manifests hold the knowledge.
//!
//! The clamping rule is borrowed from Hermes' `agent/reasoning_effort.clamp_effort`, and the
//! per-model mapping shape from Pi's `thinkingLevelMap` — both are the same idea: a requested level
//! resolves to a level *this* wire has, never upward, and a level that maps to nothing is omitted
//! rather than guessed.

use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

/// The ladder, weakest first. A request is clamped *down* it and never up: a level a backend does
/// not have must not quietly cost more than the one that was asked for.
pub const LADDER: &[&str] = &["none", "minimal", "low", "medium", "high", "xhigh", "max"];

/// The level an install reasons at when nobody said otherwise: the `default` both shipped profiles
/// declare, and the line `config init` writes live into `config.toml`.
///
/// One constant because the two answers are one fact (`#276`). A starter file that says `medium`
/// while the resolver says nothing is the drift that makes a fresh install's read-out contradict
/// its own config — the starter's key is not a second opinion, it is the same answer written down
/// where the operator can see and edit it.
pub const SHIPPED_DEFAULT: &str = "medium";

/// What the read-out says when the next request carries no reasoning field at all.
///
/// Not `(unset)`: after `#276` an unset *file* means the level above, so the only thing left for
/// this label to mean is "nothing goes on the wire" — which is a fact about the backend, not a gap
/// in the configuration, and it should read like one.
pub const NOT_SENT: &str = "not sent";

/// The levels a `/reasoning` argument may name. `none` is here because it is also the off switch on
/// every backend measured so far; a manifest that has no disable maps it to nothing instead.
pub fn is_level(word: &str) -> bool {
    LADDER.contains(&word.trim().to_lowercase().as_str())
}

/// The word that says "put no reasoning field on the wire at all".
///
/// Deliberately *not* a rung of [`LADDER`]: `none` is the off switch — it asks the model to stop
/// thinking and puts a field on the wire — while `omit` sends nothing and leaves the endpoint's own
/// default in charge (`#278`). It is a word in the same place, because the two settings that decide
/// this are the file and the profile, and a second key for one knob would need a precedence rule
/// every surface has to honour forever.
pub const OMIT: &str = "omit";

/// Whether this word is the "send no field" sentinel rather than a level.
pub fn is_omit(word: &str) -> bool {
    word.trim().to_lowercase() == OMIT
}

fn rank(level: &str) -> Option<usize> {
    LADDER.iter().position(|l| *l == level)
}

/// What a backend's reasoning field takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum Kind {
    /// Graded: the level itself goes on the wire (`reasoning_effort: "high"`).
    #[default]
    Level,
    /// A bool-valued switch (`chat_template_kwargs: {enable_thinking: true}`): every graded level
    /// means "on", the off level means "off", and there is nothing in between to send.
    Bool,
}

/// How a backend turns thinking off, which is not the same anywhere.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum OffSwitch {
    /// A level at the policy's field: `off = "none"`.
    Text(String),
    /// A bool at the policy's field: `off = false` for `enable_thinking`.
    Flag(bool),
    /// A whole body fragment, merged as it is: the switch is not at `field` at all.
    Body(serde_json::Value),
}

impl From<&str> for OffSwitch {
    fn from(text: &str) -> Self {
        OffSwitch::Text(text.to_string())
    }
}

impl OffSwitch {
    /// The value to put at the policy's field, when that is the shape it is.
    fn at_field(&self) -> Option<serde_json::Value> {
        match self {
            OffSwitch::Text(s) => Some(serde_json::Value::String(s.clone())),
            OffSwitch::Flag(b) => Some(serde_json::Value::Bool(*b)),
            OffSwitch::Body(_) => None,
        }
    }
}

/// One backend's reasoning policy, as a manifest declares it.
///
/// ```toml
/// [provider_profile.reasoning]
/// field  = "reasoning_effort"     # dotted path on the request body
/// kind   = "level"                # "level" (default) or "bool"
/// off    = "none"                 # level kind: what turns it off
/// levels = ["low", "medium", "high"]
/// map    = { minimal = "low", xhigh = "high" }
/// default = "medium"              # when nothing was set; absent = send nothing
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, Default)]
#[serde(deny_unknown_fields)]
pub struct Policy {
    /// Dotted path into the request body: `reasoning_effort`, or
    /// `chat_template_kwargs.enable_thinking`.
    pub field: String,
    #[serde(default)]
    pub kind: Kind,
    /// What disables reasoning on this backend: a level (`"none"`), a bool for a bool field, or a
    /// body fragment when the switch lives somewhere else entirely
    /// (`chat_template_kwargs = { enable_thinking = false }`). `None` = cannot be switched off.
    #[serde(default)]
    pub off: Option<OffSwitch>,
    /// The off switch to use instead of `off` when the base URL is Ollama itself, because Ollama
    /// ignores `reasoning_effort` on its native port and `think = false` 422s anywhere else.
    #[serde(default)]
    pub ollama_off: Option<OffSwitch>,
    /// The graded levels this wire accepts, weakest first. Empty = it has no graded dial (on/off
    /// only, or nothing at all).
    #[serde(default)]
    pub levels: Vec<String>,
    /// Declared vendor mappings, consulted before the ladder: `minimal = "low"`, `xhigh = "high"`.
    #[serde(default)]
    pub map: BTreeMap<String, String>,
    /// What to send when the user set nothing. Absent = send nothing and let the server default
    /// apply — which is the honest default, because an endpoint's own default is not ours to guess.
    #[serde(default)]
    pub default: Option<String>,
}

/// What one request should carry, and what can be said about it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Wire {
    /// Put this value at the policy's field. `true`/`false` for a bool field, a string for a level.
    Set(serde_json::Value),
    /// Merge this fragment as it is: the switch is a whole table, not one field.
    Body(serde_json::Value),
    /// Send nothing: the backend has no dial for this ask (or no dial at all).
    Omit(Omitted),
}

/// Why nothing is being sent — the sentence `/reasoning` prints instead of pretending.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Omitted {
    /// The policy has no field at all: this model does not reason, or nobody declared how it does.
    NoPolicy,
    /// A graded level was asked of a backend with no graded levels (it has an off switch only).
    NoLevels,
    /// The level resolves to nothing on this wire (its `map` says `null`, or it is not on the
    /// ladder and not in `levels`).
    NotOnThisWire,
    /// Nothing was asked and the policy declares no default.
    NothingAsked,
    /// Somebody decided, deliberately, that this route carries no reasoning field — the `omit`
    /// sentinel, in the file, in a profile's default, or from `/reasoning` for one session
    /// (`#278`). A different sentence from [`Omitted::NothingAsked`]: that one is an absence
    /// nobody chose.
    AskedToOmit,
}

impl Wire {
    /// The body patch this puts on the wire, as one dotted key.
    pub fn body(&self, policy: &Policy) -> serde_json::Value {
        match self {
            Wire::Set(value) => put(&policy.field, value.clone()),
            Wire::Body(fragment) => fragment.clone(),
            Wire::Omit(_) => serde_json::json!({}),
        }
    }
}

/// `{"a.b": v}` as a nested object: `{"a": {"b": v}}`. Public because a profile names the path for
/// anything it places (the reasoning field, `num_ctx`) and there should be one spelling of that.
pub fn field_path(field: &str, value: serde_json::Value) -> serde_json::Value {
    put(field, value)
}

/// `{"a.b": v}` as a nested object: `{"a": {"b": v}}`.
fn put(field: &str, value: serde_json::Value) -> serde_json::Value {
    let mut parts: Vec<&str> = field.split('.').filter(|p| !p.is_empty()).collect();
    let Some(last) = parts.pop() else {
        return serde_json::json!({});
    };
    let mut out = serde_json::json!({ last: value });
    for part in parts.into_iter().rev() {
        out = serde_json::json!({ part: out });
    }
    out
}

impl Policy {
    /// The real OpenAI API's graded vocabulary. No off switch: `reasoning_effort: "none"` is not
    /// something that endpoint accepts, and inventing it would be a 400.
    ///
    /// `default = medium` is what a fresh install reasons at (`#276`): a route nobody configured
    /// still gets a level this wire is known to take, and a route that declares no policy at all
    /// still gets no field. `SHIPPED_DEFAULT` is the same answer the starter file writes live, and
    /// the test below is what keeps the two from drifting apart.
    pub fn openai() -> Self {
        Self {
            field: "reasoning_effort".into(),
            kind: Kind::Level,
            off: None,
            ollama_off: None,
            levels: vec![
                "minimal".into(),
                "low".into(),
                "medium".into(),
                "high".into(),
            ],
            map: BTreeMap::new(),
            default: Some(SHIPPED_DEFAULT.into()),
        }
    }

    /// What a llama.cpp server was measured to take on this fleet: a graded dial on some models,
    /// `none` as the off switch everywhere, `minimal` silently meaning "no thinking", and nothing
    /// above `high`. A model that ignores the graded levels overrides this in a manifest.
    ///
    /// `default = medium` for the reason `openai` declares it; a per-model entry that declares no
    /// default (the off-only gemma shape) sends nothing, which is what a graded level would be
    /// there: a level the server ignores, reported as if it had worked.
    pub fn llamacpp() -> Self {
        let mut map = BTreeMap::new();
        map.insert("minimal".to_string(), "low".to_string());
        map.insert("xhigh".to_string(), "high".to_string());
        map.insert("max".to_string(), "high".to_string());
        Self {
            field: "reasoning_effort".into(),
            kind: Kind::Level,
            off: Some("none".into()),
            ollama_off: None,
            levels: vec!["low".into(), "medium".into(), "high".into()],
            map,
            default: Some(SHIPPED_DEFAULT.into()),
        }
    }

    /// Whether this backend has any reasoning control at all.
    pub fn has_dial(&self) -> bool {
        !self.field.is_empty()
            && (self.off.is_some() || self.ollama_off.is_some() || !self.levels.is_empty())
    }

    /// The off switch as a word, when it is one — `asks_off` compares map targets against it.
    fn off_text(&self) -> Option<&str> {
        match &self.off {
            Some(OffSwitch::Text(text)) => Some(text.as_str()),
            _ => None,
        }
    }

    /// Whether this route can turn thinking off at all (`#293`). The switch in the dashboard's
    /// submenu is one of these: a route without an off draws it disabled, because the alternative
    /// is a control that presses and changes nothing.
    pub fn has_off(&self) -> bool {
        !self.field.is_empty() && (self.off.is_some() || self.ollama_off.is_some())
    }

    /// Whether it has graded levels, as opposed to only off/on.
    pub fn has_levels(&self) -> bool {
        !self.levels.is_empty()
    }

    /// The words this wire takes, as a menu should offer them (`#275`): the graded levels it
    /// declared, plus its off switch when it has one.
    ///
    /// The point of serving this instead of a union spelled in a front end is that a row offered
    /// is a row that works. `openai` has no off switch — `reasoning_effort: "none"` is a 400
    /// there — while `llamacpp` has `none` and only three rungs, and an off-only model can do
    /// nothing but turn thinking off. Empty for a policy with no dial at all, which the menu says
    /// in words instead of listing six dead ones.
    pub fn vocabulary(&self) -> Vec<String> {
        if !self.has_dial() {
            return Vec::new();
        }
        let mut out = self.levels.clone();
        // The off switch is asked for by the word `none` whatever shape it takes — a level, a
        // bool, or a body fragment — because that is the word `asks_off` recognises, and a
        // fragment is not something a person types.
        if self.has_off() && !out.iter().any(|l| l == "none") {
            out.push("none".to_string());
        }
        out
    }

    /// The effort in force when nothing was asked *and* nothing was configured.
    pub fn default_effort(&self) -> Option<&str> {
        self.default.as_deref()
    }

    /// Resolve a requested level into what this request carries.
    pub fn resolve(&self, requested: Option<&str>) -> Wire {
        self.resolve_at(requested, None)
    }

    /// The same, with the endpoint in hand: Ollama ignores `reasoning_effort` on its native port
    /// and `think = false` 422s everywhere else, so which switch is the off switch is a property of
    /// where the request is going.
    pub fn resolve_at(&self, requested: Option<&str>, base_url: Option<&str>) -> Wire {
        if !self.has_dial() {
            return Wire::Omit(Omitted::NoPolicy);
        }
        let asked = requested
            .map(|r| r.trim().to_lowercase())
            .filter(|r| !r.is_empty());
        let Some(asked) = asked.or_else(|| self.default_effort().map(str::to_string)) else {
            return Wire::Omit(Omitted::NothingAsked);
        };
        // Before the ladder, and before the off switch: the sentinel is not a level any wire is
        // asked to take, it is the absence of the field, so nothing may clamp it into something
        // that is sent.
        if is_omit(&asked) {
            return Wire::Omit(Omitted::AskedToOmit);
        }
        if asks_off(&asked, self) {
            return match self.off_wire(base_url) {
                Some(Wire::Body(fragment)) => Wire::Body(fragment),
                Some(Wire::Set(value)) => Wire::Set(value),
                _ => Wire::Omit(Omitted::NotOnThisWire),
            };
        }
        match self.kind {
            Kind::Bool => match self.on_value() {
                Some(value) => Wire::Set(value),
                None => Wire::Omit(Omitted::NotOnThisWire),
            },
            Kind::Level => {
                if !self.has_levels() {
                    // An off switch and nothing else: an enabled ask has nowhere to go. Sending
                    // the level anyway is how a "high" that changed nothing gets reported as if it
                    // had worked.
                    return Wire::Omit(Omitted::NoLevels);
                }
                match clamp(&asked, self) {
                    Some(level) => Wire::Set(serde_json::Value::String(level)),
                    None => Wire::Omit(Omitted::NotOnThisWire),
                }
            }
        }
    }

    /// A sentence for a report: what this ask becomes on this backend.
    pub fn describe(&self, requested: Option<&str>) -> String {
        if !self.has_dial() {
            return "no reasoning control on this backend".to_string();
        }
        let asked = requested
            .map(|r| r.trim().to_lowercase())
            .filter(|r| !r.is_empty())
            .or_else(|| self.default_effort().map(str::to_string));
        let Some(asked) = asked else {
            return "not sent: nothing asked and this backend declares no default".to_string();
        };
        match self.resolve(Some(&asked)) {
            Wire::Set(serde_json::Value::String(clamped)) if clamped == asked => {
                format!("sends {clamped}")
            }
            // A clamp is said out loud: a report that echoed the request would claim a level this
            // backend does not have.
            Wire::Set(serde_json::Value::String(clamped)) => format!("{asked} → sends {clamped}"),
            Wire::Set(serde_json::Value::Bool(true)) => "sends thinking on".to_string(),
            Wire::Set(serde_json::Value::Bool(false)) => "sends thinking off".to_string(),
            Wire::Set(_) => "sends it".to_string(),
            // The switch is a table, not a level: name the keys rather than the JSON.
            Wire::Body(fragment) => {
                let keys: Vec<String> = fragment
                    .as_object()
                    .map(|o| o.keys().cloned().collect())
                    .unwrap_or_default();
                if keys.is_empty() {
                    format!("{asked} → sends a body fragment")
                } else {
                    format!("{asked} → sends {}", keys.join(", "))
                }
            }
            Wire::Omit(Omitted::NoLevels) => {
                "not sent: this backend has no levels, only on or off".to_string()
            }
            Wire::Omit(Omitted::NotOnThisWire) => {
                format!("not sent: {asked} is not a level this backend takes")
            }
            Wire::Omit(Omitted::NothingAsked) => "not sent: nothing asked".to_string(),
            Wire::Omit(Omitted::AskedToOmit) => {
                "not sent: asked for no field on this route".to_string()
            }
            Wire::Omit(Omitted::NoPolicy) => "no reasoning control on this backend".to_string(),
        }
    }

    /// The switch this endpoint honours, as the wire shape to send.
    fn off_wire(&self, base_url: Option<&str>) -> Option<Wire> {
        let chosen = match (&self.ollama_off, base_url) {
            (Some(switch), Some(url)) if looks_like_ollama(url) => switch,
            _ => self.off.as_ref()?,
        };
        Some(match chosen {
            OffSwitch::Body(fragment) => Wire::Body(fragment.clone()),
            other => Wire::Set(other.at_field()?),
        })
    }

    fn on_value(&self) -> Option<serde_json::Value> {
        match self.kind {
            Kind::Bool => Some(serde_json::Value::Bool(true)),
            Kind::Level => self.levels.first().cloned().map(serde_json::Value::String),
        }
    }
}

/// Is this base URL Ollama *itself* rather than something that merely speaks its wire?
///
/// The native port, or a host name that names Ollama and is not a public domain: a container/service
/// name (`ollama`, `my-ollama`), or one under a private label (`ollama.lan`, `ollama.internal`).
/// `https://ollama.com` is the cloud — it speaks the OpenAI wire, ignores `think` and takes
/// `reasoning_effort: "none"` — so a substring test on the whole URL would get this exactly backwards.
pub fn looks_like_ollama(base_url: &str) -> bool {
    let trimmed = base_url.trim();
    let without_scheme = trimmed
        .split_once("://")
        .map(|(_, rest)| rest)
        .unwrap_or(trimmed);
    let authority = without_scheme
        .split(['/', '?', '#'])
        .next()
        .unwrap_or(without_scheme);
    let authority = authority
        .rsplit_once('@')
        .map_or(authority, |(_, rest)| rest);
    if authority.is_empty() {
        return false;
    }
    let (host, port) = match authority.rsplit_once(':') {
        Some((host, port)) if !port.is_empty() && port.chars().all(|c| c.is_ascii_digit()) => {
            (host, Some(port))
        }
        _ => (authority, None),
    };
    // The native port is Ollama whatever it is called.
    if port == Some("11434") {
        return true;
    }
    let host = host.trim_matches(['[', ']']).to_ascii_lowercase();
    if host.is_empty() || !host.contains("ollama") {
        return false;
    }
    let labels: Vec<&str> = host.split('.').collect();
    // A single label is a container or service name: `ollama`, `my-ollama`.
    if labels.len() == 1 {
        return true;
    }
    // Anything under a private label is on somebody's own network.
    const PRIVATE: [&str; 6] = [
        "local",
        "lan",
        "internal",
        "home",
        "home.arpa",
        "localdomain",
    ];
    labels
        .iter()
        .any(|label| PRIVATE.contains(label) || label.ends_with(".arpa"))
}

/// Whether this ask is the off switch — by name, or by a declared `map` that points at it.
fn asks_off(asked: &str, policy: &Policy) -> bool {
    if asked == "none" {
        return true;
    }
    match (policy.map.get(asked), policy.off_text()) {
        (Some(mapped), Some(off)) => mapped == off,
        _ => false,
    }
}

/// The nearest level this wire has, never stronger than the one asked for.
///
/// Verbatim when supported; a declared `map` wins over the ladder; otherwise the nearest *weaker*
/// supported level, and only when nothing weaker exists the weakest supported one. `none` is never
/// a degradation target: clamping an enabled ask down to it would silently switch thinking off.
fn clamp(asked: &str, policy: &Policy) -> Option<String> {
    // Verbatim against the *declared* list, whatever the levels are called: a custom endpoint's
    // bespoke name (`turbo`) is a level, even though it is not a rung of our ladder.
    if let Some(level) = policy
        .levels
        .iter()
        .find(|level| level.to_lowercase() == asked)
    {
        return Some(level.clone());
    }
    if let Some(mapped) = policy.map.get(asked) {
        let known = policy
            .levels
            .iter()
            .find(|level| level.as_str() == mapped.as_str());
        return Some(known.cloned().unwrap_or_else(|| mapped.clone()));
    }
    // Clamping needs the ladder: only a named rung has a "nearest weaker" one.
    let supported: Vec<&String> = policy
        .levels
        .iter()
        .filter(|level| rank(&level.to_lowercase()).is_some())
        .collect();
    if supported.is_empty() {
        return None;
    }
    let asked_rank = rank(asked)?;
    let mut weaker: Vec<&&String> = supported
        .iter()
        .filter(|level| level.to_lowercase() != "none")
        .filter(|level| {
            rank(&level.to_lowercase())
                .map(|r| r < asked_rank)
                .unwrap_or(false)
        })
        .collect();
    weaker.sort_by_key(|level| rank(&level.to_lowercase()));
    if let Some(best) = weaker.pop() {
        return Some((**best).clone());
    }
    let mut any: Vec<&&String> = supported
        .iter()
        .filter(|level| level.to_lowercase() != "none")
        .collect();
    any.sort_by_key(|level| rank(&level.to_lowercase()));
    any.first().map(|level| (**level).clone())
}

/// The effort a request carries, read **per request**.
///
/// The issue this exists for: `[provider] reasoning_effort` is copied into the client's options when
/// the client is built, so the one moment you want a different level — right after a turn that
/// thought too little — is the one the running session cannot do. So the configured level stays the
/// *default*, and a session override sits in front of it, in an `Arc` shared by every route the
/// session opened.
#[derive(Debug, Default)]
pub struct Dial {
    /// `[provider] reasoning_effort`, as loaded.
    configured: Option<String>,
    /// `/reasoning <level>` for this process. `None` = follow the configuration; `Some(None)` =
    /// follow it *and* ignore it, which is what `/reasoning default` means after a session override.
    session: std::sync::Mutex<Option<Option<String>>>,
}

impl Dial {
    pub fn new(configured: Option<String>) -> Self {
        Self {
            configured: clean(configured.as_deref()),
            session: std::sync::Mutex::new(None),
        }
    }

    /// What the next request should ask for: the session's override, else the configuration.
    pub fn effort(&self) -> Option<String> {
        let session = self.session.lock().unwrap_or_else(|e| e.into_inner());
        match session.as_ref() {
            Some(level) => level.clone(),
            None => self.configured.clone(),
        }
    }

    /// `/reasoning <level>`: from the next request on, in this process only.
    pub fn set_session(&self, level: Option<String>) {
        let mut session = self.session.lock().unwrap_or_else(|e| e.into_inner());
        *session = Some(level.map(|l| l.trim().to_lowercase()));
    }

    /// Drop the override: the configuration is in force again.
    pub fn clear_session(&self) {
        let mut session = self.session.lock().unwrap_or_else(|e| e.into_inner());
        *session = None;
    }

    /// What was configured, for a report that has to say "the same as the file".
    pub fn configured(&self) -> Option<&str> {
        self.configured.as_deref()
    }

    /// Whether a session override is in force.
    pub fn overridden(&self) -> bool {
        self.session
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .is_some()
    }

    /// The level in force, with the one clause that makes an override visible: `high`,
    /// `high (this session; config.toml says low)`, `medium (this backend's default; config.toml
    /// sets nothing)`, or `not sent`.
    ///
    /// This is the read-out's wording and `/reasoning`'s, from one function, so the line under the
    /// composer cannot claim a level the report does not. Three answers, because a dial has three:
    /// the session asked (`/reasoning high`), the file asked, or neither did and the route's own
    /// policy supplies the shipped default (`#276`). `not sent` is the fourth case and a fact, not
    /// a shrug: the backend takes no level, or nobody declared one, so the field is not on the wire.
    pub fn in_force(&self) -> String {
        self.resolution(None).1
    }

    /// What is in force, and where it came from: `(level, wording)`.
    ///
    /// `default` is the route's declared default — [`crate::provider::Reasoning::declared_default`]
    /// — and it is a parameter rather than a field because a route changes under a live dial
    /// (`/model`), and a copy taken at construction is how a read-out starts describing a backend
    /// the session left behind.
    fn resolution(&self, default: Option<&str>) -> (Option<String>, String) {
        let session = self.session.lock().unwrap_or_else(|e| e.into_inner());
        let session_level = session.clone();
        drop(session);
        match session_level {
            // `/reasoning <level>`: the session's own answer, and it says so. `omit` is a word a
            // session may choose (`#278`), and the report calls the outcome what it is.
            Some(Some(level)) => {
                let label = (!is_omit(&level)).then(|| level.clone());
                let word = shown(label.as_deref());
                let said = match self.configured() {
                    Some(configured) if is_omit(configured) => {
                        format!("{word} (this session; config.toml asks for no field)")
                    }
                    Some(configured) => {
                        format!("{word} (this session; config.toml says {configured})")
                    }
                    None => format!("{word} (this session; config.toml sets nothing)"),
                };
                (label, said)
            }
            // `/reasoning default` after an override, or an override that asked for nothing:
            // the session decided, and what it decided is "no field".
            Some(None) => {
                let said = match self.configured() {
                    Some(configured) if is_omit(configured) => {
                        format!("{NOT_SENT} (this session; config.toml asks for no field)")
                    }
                    Some(configured) => {
                        format!("{NOT_SENT} (this session; config.toml says {configured})")
                    }
                    None => format!("{NOT_SENT} (this session; config.toml sets nothing)"),
                };
                (None, said)
            }
            None => match self.configured() {
                Some(configured) if is_omit(configured) => {
                    (None, format!("{NOT_SENT} (config.toml asks for no field)"))
                }
                Some(configured) => (Some(configured.to_string()), configured.to_string()),
                // Nobody set it: the route's declared default is the shipped answer, and the
                // wording says so rather than pretending the file named it.
                None => match clean(default) {
                    Some(level) if is_omit(&level) => (
                        None,
                        format!("{NOT_SENT} (this backend's default; config.toml sets nothing)"),
                    ),
                    Some(level) => (
                        Some(level.clone()),
                        format!("{level} (this backend's default; config.toml sets nothing)"),
                    ),
                    None => (None, NOT_SENT.to_string()),
                },
            },
        }
    }
}

/// What a report calls a level: the level itself, or `not sent` when there is none — which is what
/// the `omit` sentinel resolves to (`#278`).
fn shown(level: Option<&str>) -> String {
    level.unwrap_or(NOT_SENT).to_string()
}

/// A level as the dial holds them: trimmed, lowercased, empty means absent.
fn clean(level: Option<&str>) -> Option<String> {
    level
        .map(|l| l.trim().to_lowercase())
        .filter(|l| !l.is_empty())
}

/// The effort in force, in the forms each surface needs (`#264`).
///
/// One struct rather than four parallel strings, because the line under the composer, the
/// full-screen read-out, `/status` and the dashboard all answer the same question and had all been
/// answering it differently — three of them by silence.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct InForce {
    /// `high`, or `not sent` — the read-out's form, short enough for a line that is already full.
    pub label: String,
    /// `high (this session; config.toml says low)` — `/reasoning`'s and `/status`'s form.
    pub in_force: String,
    /// Whether `/reasoning` moved it for this process.
    pub session: bool,
    /// The level came from the backend's declared default, not from the file or the session: the
    /// one origin a reader would otherwise have to guess at, because nothing in `config.toml` says
    /// it.
    pub by_default: bool,
    /// What that level becomes on the route in force, in the provider's own words. Empty when
    /// nobody could resolve it — a read-out that filled this in from a table would be the second
    /// guess `/reasoning` exists to prevent.
    pub resolved: String,
}

impl InForce {
    /// The whole thing in one sentence: the level and its origin, then the field it is sent as.
    ///
    /// One formatter, because `/status`, the dashboard's `title` and the full-screen interface's
    /// tooltip all describe one dial — and three copies of that sentence is how a read-out starts
    /// disagreeing with a command about the same session (`#264`).
    pub fn sentence(&self) -> String {
        if self.resolved.is_empty() {
            return self.in_force.clone();
        }
        // "not sent" is already the whole answer, and the backend's reason stands in for it:
        // "not sent · on this backend: not sent: nothing asked" is one contradiction too many.
        if self.label == NOT_SENT {
            return self.resolved.clone();
        }
        format!("{} · on this backend: {}", self.in_force, self.resolved)
    }
}

impl Dial {
    /// The dial's own half of [`InForce`]: what it will ask for, why, and what that becomes.
    ///
    /// `default` is the route in force's declared default (`#276`): `Some("medium")` on both
    /// shipped profiles, `None` for a backend that declares no policy or no default. With no
    /// session override and no file value, that is the level the next request carries — and the
    /// label says `not sent`, not a guessed level, when even that is absent.
    pub fn in_force_report(&self, default: Option<&str>) -> InForce {
        let (level, in_force) = self.resolution(default);
        InForce {
            label: level.clone().unwrap_or_else(|| NOT_SENT.to_string()),
            by_default: level.is_some() && !self.overridden() && self.configured().is_none(),
            in_force,
            session: self.overridden(),
            resolved: String::new(),
        }
    }
}

/// The whole report for a dial and the route behind it: the one construction every front uses.
///
/// `control` is what the next request's route resolves to ([`crate::provider::Reasoning`]), and it
/// supplies both halves the dial cannot answer alone — the declared default (`#276`) and the
/// backend's own sentence for what a level becomes. `Agent::reasoning_report()`, the full-screen
/// read-out and `/reasoning` all call this, so a surface cannot describe the dial differently from
/// the command that moved it.
pub fn report_for(dial: &Dial, control: Option<&crate::provider::Reasoning>) -> InForce {
    let mut report = dial.in_force_report(control.and_then(|c| c.declared_default()));
    report.resolved = sentence(control, dial.effort().as_deref());
    report
}

/// A dial every route of one session shares.
pub type Shared = std::sync::Arc<Dial>;

/// One sentence for a level, given the control a route resolved to. The single wording for
/// `/reasoning`, the launch panel and the readout, so a clamp is described the same way wherever it
/// is reported.
///
/// `None` means this agent could not resolve a profile at all — not "no reasoning control", which
/// is [`crate::provider::Reasoning::Off`].
pub fn sentence(control: Option<&crate::provider::Reasoning>, level: Option<&str>) -> String {
    use crate::provider::Reasoning;
    match control {
        None => "unknown: this agent has no provider configuration to describe".to_string(),
        Some(Reasoning::Policy(policy)) => policy.describe(level),
        Some(Reasoning::Off) => "no reasoning control on this model".to_string(),
        Some(Reasoning::Undeclared) => match level {
            Some(_) => "sent as-is (this backend declares no reasoning control)".to_string(),
            None => "not sent: nothing was asked and nothing is configured".to_string(),
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `#278`: the sentinel answers before the ladder, so no policy can clamp it into a level that
    /// is sent — and the sentence says it was a decision, not an absence.
    #[test]
    fn the_omit_sentinel_is_answered_before_the_ladder_and_says_so() {
        for policy in [Policy::openai(), Policy::llamacpp()] {
            assert_eq!(
                policy.resolve(Some(OMIT)),
                Wire::Omit(Omitted::AskedToOmit),
                "resolve({OMIT}) on a policy with a dial"
            );
        }
        // A backend with no dial at all keeps its own answer: there is no field for the operator
        // to omit, and saying "asked for no field" would hide that the model has no control.
        assert_eq!(
            Policy::default().resolve(Some(OMIT)),
            Wire::Omit(Omitted::NoPolicy)
        );
        assert_eq!(
            Policy::openai().describe(Some(OMIT)),
            "not sent: asked for no field on this route"
        );
        // Not a level: nothing may reach it by clamping, and the menu must not offer it (the
        // vocabulary test above holds that an offered word goes on the wire).
        assert!(!is_level(OMIT));
        assert!(is_omit("  OMIT "));
        assert!(!is_omit("none"));
        for policy in [Policy::openai(), Policy::llamacpp()] {
            assert!(!policy.vocabulary().iter().any(|w| w == OMIT), "{policy:?}");
        }
    }

    /// A profile may ship the sentinel as its default: the route then carries no field unless a
    /// session asks for a level, which is how an operator keeps a config quiet without Rust.
    #[test]
    fn a_profile_default_of_omit_carries_no_field() {
        let mut policy = Policy::openai();
        policy.default = Some(OMIT.to_string());
        assert_eq!(policy.resolve(None), Wire::Omit(Omitted::AskedToOmit));
        assert_eq!(
            policy.describe(None),
            "not sent: asked for no field on this route"
        );
        // And a session still outranks it, which is the point of a default rather than a switch.
        assert_eq!(
            policy.resolve(Some("high")),
            Wire::Set(serde_json::Value::String("high".into()))
        );
    }

    /// The read-out's wording for a session that asked for no field: `not sent`, with the file's
    /// own answer beside it — never the word `omit`, which is a spelling rather than a state.
    #[test]
    fn a_session_that_asked_for_no_field_reports_not_sent() {
        let dial = Dial::new(Some(SHIPPED_DEFAULT.to_string()));
        dial.set_session(Some(OMIT.to_string()));
        let report = dial.in_force_report(Some(SHIPPED_DEFAULT));
        assert_eq!(report.label, NOT_SENT);
        assert_eq!(
            report.in_force,
            format!("{NOT_SENT} (this session; config.toml says {SHIPPED_DEFAULT})")
        );
        assert!(report.session);

        // The same word written into the file, with no session override.
        let configured = Dial::new(Some(OMIT.to_string()));
        let report = configured.in_force_report(Some(SHIPPED_DEFAULT));
        assert_eq!(report.label, NOT_SENT);
        assert_eq!(
            report.in_force,
            format!("{NOT_SENT} (config.toml asks for no field)")
        );
    }

    /// `#275`: the menu may only offer what the wire takes. `openai` has no off switch —
    /// `reasoning_effort: "none"` is a 400 there — and `llamacpp` has one, whatever shape it takes.
    #[test]
    fn the_vocabulary_is_the_wires_own_and_not_a_union() {
        assert_eq!(
            Policy::openai().vocabulary(),
            vec!["minimal", "low", "medium", "high"],
            "four rungs, no off switch to offer"
        );
        assert_eq!(
            Policy::llamacpp().vocabulary(),
            vec!["low", "medium", "high", "none"],
            "its three rungs, then the word its off switch is asked for by"
        );
        assert!(
            Policy::default().vocabulary().is_empty(),
            "a policy with no dial has nothing to offer, and saying so is the answer"
        );
        // Every word offered resolves to something that goes on the wire: a menu row that cannot
        // be clicked is the bug this exists to prevent.
        for policy in [Policy::openai(), Policy::llamacpp()] {
            for level in policy.vocabulary() {
                assert!(
                    !matches!(policy.resolve(Some(&level)), Wire::Omit(_)),
                    "{level} is offered but refused"
                );
            }
        }
    }

    #[test]
    fn the_session_override_wins_over_the_configured_level_until_it_is_cleared() {
        let dial = Dial::new(Some("low".into()));
        assert_eq!(dial.effort().as_deref(), Some("low"));
        assert!(!dial.overridden());
        dial.set_session(Some(" HIGH ".into()));
        assert_eq!(
            dial.effort().as_deref(),
            Some("high"),
            "trimmed, lowercased"
        );
        assert!(dial.overridden());
        dial.clear_session();
        assert_eq!(
            dial.effort().as_deref(),
            Some("low"),
            "the configuration is back in force"
        );
        assert!(!dial.overridden());
    }

    /// `/reasoning default` after a session override asks for *nothing*, which is not the same as
    /// asking for what the file says.
    #[test]
    fn an_explicit_absence_is_a_decision_not_a_fallthrough() {
        let dial = Dial::new(Some("low".into()));
        dial.set_session(None);
        assert_eq!(dial.effort(), None);
        assert!(dial.overridden(), "the override is still a decision");
        dial.clear_session();
        assert_eq!(dial.effort().as_deref(), Some("low"));
    }

    /// The read-out's wording, from the dial itself: what is in force, whether that is a session
    /// override, and never a guessed level where nothing was asked (`#276`).
    #[test]
    fn in_force_names_the_level_and_says_when_the_session_moved_it() {
        let dial = Dial::new(Some("low".into()));
        assert_eq!(dial.in_force(), "low");
        dial.set_session(Some("high".into()));
        assert_eq!(dial.in_force(), "high (this session; config.toml says low)");
        dial.set_session(None);
        assert_eq!(
            dial.in_force(),
            "not sent (this session; config.toml says low)",
            "asking for nothing is a decision, and no field is what it will send"
        );
        dial.clear_session();
        assert_eq!(dial.in_force(), "low");

        // Nothing configured and a route that declares nothing: `not sent`, not a guessed level.
        let bare = Dial::new(None);
        assert_eq!(bare.in_force(), NOT_SENT);
        bare.set_session(Some("high".into()));
        assert_eq!(
            bare.in_force(),
            "high (this session; config.toml sets nothing)"
        );
    }

    /// `#276`: what a fresh install looks like. The file says nothing, the route declares a
    /// default, and the read-out answers with the level the request will carry — saying where it
    /// came from, because `config.toml` does not.
    #[test]
    fn a_policy_that_declares_a_default_resolves_it_and_says_the_file_did_not() {
        let bare = Dial::new(None);
        let report = bare.in_force_report(Some(SHIPPED_DEFAULT));
        assert_eq!(report.label, SHIPPED_DEFAULT);
        assert_eq!(
            report.in_force,
            "medium (this backend's default; config.toml sets nothing)"
        );
        assert!(report.by_default, "the origin is the backend, not the file");
        assert!(!report.session);

        // The file wins over the default, and the wording goes quiet about it.
        let filed = Dial::new(Some("low".into())).in_force_report(Some(SHIPPED_DEFAULT));
        assert_eq!(filed.label, "low");
        assert_eq!(filed.in_force, "low");
        assert!(!filed.by_default);

        // A session override wins over both.
        let dial = Dial::new(None);
        dial.set_session(Some("high".into()));
        let over = dial.in_force_report(Some(SHIPPED_DEFAULT));
        assert_eq!(over.label, "high");
        assert_eq!(
            over.in_force,
            "high (this session; config.toml sets nothing)"
        );
        assert!(!over.by_default);

        // A route that declares no default still sends nothing, and the label says so rather
        // than claiming the level that is not on its wire.
        let undeclared = bare.in_force_report(None);
        assert_eq!(undeclared.label, NOT_SENT);
        assert_eq!(undeclared.in_force, NOT_SENT);
        assert!(!undeclared.by_default);
    }

    /// The two shipped profiles are the reason `medium` is the answer, and the starter file is the
    /// same answer written down. One test, because the alternative is the drift `#245` exists to
    /// prevent: a file that says `medium` over a resolver that says nothing.
    #[test]
    fn the_shipped_profiles_and_the_starter_file_agree_on_the_default() {
        for policy in [Policy::openai(), Policy::llamacpp()] {
            assert_eq!(
                policy.default_effort(),
                Some(SHIPPED_DEFAULT),
                "a shipped profile declares the level the starter file names"
            );
            assert_eq!(
                policy.resolve(None),
                Wire::Set(serde_json::Value::String(SHIPPED_DEFAULT.into())),
                "and an unconfigured request carries it"
            );
        }
        let shipped = crate::config::starter_config().expect("the starter config generates");
        let starter = crate::config::Config::from_toml_str(&shipped).expect("it parses");
        assert_eq!(
            starter.provider.reasoning_effort.as_deref(),
            Some(SHIPPED_DEFAULT),
            "`config init` writes the same level on a live line"
        );
        assert!(
            shipped.contains(&format!("reasoning_effort = \"{SHIPPED_DEFAULT}\"")),
            "and it is on a line a person can read"
        );
    }

    #[test]
    fn an_unset_configuration_means_no_effort_is_asked_for() {
        let dial = Dial::new(None);
        assert_eq!(dial.effort(), None);
        assert_eq!(dial.configured(), None);
        let blank = Dial::new(Some("   ".into()));
        assert_eq!(blank.effort(), None, "blank is absent, not a level");
    }

    fn level_policy(levels: &[&str]) -> Policy {
        Policy {
            field: "reasoning_effort".into(),
            kind: Kind::Level,
            off: Some("none".into()),
            ollama_off: None,
            levels: levels.iter().map(|l| l.to_string()).collect(),
            map: BTreeMap::new(),
            default: None,
        }
    }

    fn set(value: &str) -> Wire {
        Wire::Set(serde_json::Value::String(value.into()))
    }

    #[test]
    fn a_level_the_wire_has_is_sent_verbatim() {
        let p = level_policy(&["low", "medium", "high"]);
        assert_eq!(p.resolve(Some("high")), set("high"));
        assert_eq!(p.resolve(Some("low")), set("low"));
    }

    /// Clamping goes down, never up: asking for a level a backend does not have must not cost more
    /// than asking for one it does.
    #[test]
    fn a_level_it_does_not_have_clamps_to_the_nearest_weaker_one() {
        let three = level_policy(&["low", "medium", "high"]);
        assert_eq!(three.resolve(Some("xhigh")), set("high"));
        assert_eq!(three.resolve(Some("max")), set("high"));
        // Nothing weaker than `low`: the floor is the closest honest answer.
        let floor = level_policy(&["medium", "high"]);
        assert_eq!(floor.resolve(Some("low")), set("medium"));
        // And `minimal` on a wire that starts at `low`.
        assert_eq!(three.resolve(Some("minimal")), set("low"));
    }

    /// `none` is the off switch, not a degradation target — and a wire that cannot be switched off
    /// says so rather than sending a level that would look like it had.
    #[test]
    fn off_is_its_own_answer_and_never_a_clamp_target() {
        let p = level_policy(&["low", "medium", "high"]);
        assert_eq!(p.resolve(Some("none")), set("none"));
        let mut no_off = level_policy(&["low", "high"]);
        no_off.off = None;
        assert_eq!(
            no_off.resolve(Some("none")),
            Wire::Omit(Omitted::NotOnThisWire)
        );
    }

    /// A declared mapping wins over the ladder, which is how a vendor's bespoke naming is
    /// expressed without inventing a rung for it.
    #[test]
    fn a_declared_mapping_is_consulted_before_the_ladder() {
        let mut p = level_policy(&["low", "high", "max"]);
        p.map.insert("medium".into(), "high".into());
        p.map.insert("xhigh".into(), "max".into());
        assert_eq!(
            p.resolve(Some("medium")),
            set("high"),
            "K3-shaped: the middle rung is `high`"
        );
        assert_eq!(p.resolve(Some("xhigh")), set("max"));
        // A mapping that points at the off value is the off switch.
        let mut off_by_map = level_policy(&["low", "high", "max"]);
        off_by_map.map.insert("minimal".into(), "none".into());
        assert_eq!(off_by_map.resolve(Some("minimal")), set("none"));
    }

    /// A bool-valued backend has an on and an off, and nothing else; a graded ask is omitted with a
    /// reason instead of being sent as `true` and reported as "high".
    #[test]
    fn a_bool_backend_sends_on_or_off_and_says_when_it_has_no_levels() {
        let p = Policy {
            field: "chat_template_kwargs.enable_thinking".into(),
            kind: Kind::Bool,
            // `off = false` in a manifest: the switch is a bool, and the manifest says so instead of
            // the code guessing from `kind`.
            off: Some(OffSwitch::Flag(false)),
            ollama_off: None,
            levels: vec!["low".into()],
            map: BTreeMap::new(),
            default: None,
        };
        assert_eq!(
            p.resolve(Some("high")),
            Wire::Set(serde_json::Value::Bool(true))
        );
        assert_eq!(
            p.resolve(Some("none")),
            Wire::Set(serde_json::Value::Bool(false))
        );
        assert_eq!(
            p.describe(Some("high")),
            "sends thinking on",
            "the report says on, not `high`"
        );
    }

    /// A backend with an off switch and no graded dial is the measured shape of gemma on llama.cpp:
    /// every level it was sent produced the same number of reasoning tokens.
    #[test]
    fn an_off_only_backend_refuses_an_enabled_ask_by_name() {
        let p = level_policy(&[]);
        assert!(p.has_dial() && !p.has_levels());
        assert_eq!(p.resolve(Some("high")), Wire::Omit(Omitted::NoLevels));
        assert_eq!(p.resolve(Some("none")), set("none"));
        assert!(p.describe(Some("high")).contains("no levels"));
    }

    #[test]
    fn a_model_with_no_policy_gets_no_field_at_all() {
        let p = Policy::default();
        assert!(!p.has_dial());
        assert_eq!(p.resolve(Some("high")), Wire::Omit(Omitted::NoPolicy));
        assert_eq!(
            p.describe(Some("high")),
            "no reasoning control on this backend"
        );
    }

    /// Nothing asked and no declared default: send nothing. A default that is *declared* is sent,
    /// which is how "an unset effort leaves the endpoint's ceiling in charge" is fixed deliberately
    /// rather than by accident.
    #[test]
    fn an_unasked_level_is_omitted_unless_the_manifest_declares_a_default() {
        let mut p = level_policy(&["low", "medium", "high"]);
        assert_eq!(p.resolve(None), Wire::Omit(Omitted::NothingAsked));
        assert_eq!(p.describe(None).split(':').next(), Some("not sent"));
        p.default = Some("medium".into());
        assert_eq!(p.resolve(None), set("medium"));
        assert_eq!(p.describe(None), "sends medium");
    }

    /// The field is a dotted path, so a backend that wants a nested object gets one.
    #[test]
    fn a_dotted_field_becomes_a_nested_body_key() {
        let p = Policy {
            field: "chat_template_kwargs.enable_thinking".into(),
            kind: Kind::Bool,
            // `off = false` in a manifest: the switch is a bool, and the manifest says so instead of
            // the code guessing from `kind`.
            off: Some(OffSwitch::Flag(false)),
            ollama_off: None,
            levels: Vec::new(),
            map: BTreeMap::new(),
            default: None,
        };
        assert_eq!(
            p.resolve(Some("none")).body(&p),
            serde_json::json!({"chat_template_kwargs": {"enable_thinking": false}})
        );
        let flat = level_policy(&["high"]);
        assert_eq!(
            flat.resolve(Some("high")).body(&flat),
            serde_json::json!({"reasoning_effort": "high"})
        );
    }

    /// A bespoke level a custom endpoint invented is passed through rather than dropped: the ladder
    /// is Hermes'/Pi's vocabulary, not a closed set every server agrees on.
    #[test]
    fn a_bespoke_level_passes_through_when_the_wire_lists_it() {
        let p = level_policy(&["low", "turbo"]);
        assert_eq!(p.resolve(Some("turbo")), set("turbo"));
        // And one nobody lists is refused with the level named.
        assert_eq!(p.resolve(Some("warp")), Wire::Omit(Omitted::NotOnThisWire));
        assert!(p.describe(Some("warp")).contains("warp"));
    }

    #[test]
    fn the_ladder_is_ordered_and_answers_what_it_accepts() {
        for level in LADDER {
            assert!(is_level(level), "{level}");
        }
        assert!(is_level(" HIGH "), "trimmed and lowercased");
        assert!(!is_level("turbo"));
        assert!(!is_level(""));
    }
}