eclipse-cli 0.13.4

Command-line interface for eclipse
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
//! `/reasoning`: how much the model thinks, and how much of it you see.
//!
//! Two dials, and the issue that asked for them says why they are separate. **Effort** is a
//! request: `[provider] reasoning_effort` until `/reasoning high` overrides it for this process.
//! That half lives in [`eclipse_core::reasoning`] — the ladder, the clamp, and the per-backend
//! policy a manifest declares — because the provider is what puts the number on the wire.
//!
//! **Display** is a screen: whether a reasoning block appears at all, whether it is folded, and how
//! much of it a folded block previews. Nothing here is written to `config.toml`, because a display
//! flag is not behaviour and must not outlive the interface that chose it.
//!
//! The words are one table for both fronts, so `/help`, Tab completion and the two `match` arms
//! cannot drift.

use eclipse_core::reasoning::{self, InForce};

/// What a `/reasoning <word>` changes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Change {
    /// The effort from the next request on, in this process.
    Effort(String),
    /// The effort written to `config.toml` as well: the next process starts with it.
    Global(String),
    /// Forget the session override: the configuration is in force again.
    Reset,
    /// How much of a reasoning block is drawn.
    Display(Mode),
    /// `/reasoning` with nothing after it.
    Report,
}

/// How reasoning is drawn, for this process.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Mode {
    /// Folded to a preview with a count, which is what the interface has always done.
    #[default]
    Folded,
    /// Never folded: the whole block, always.
    Full,
    /// No block at all. The text is still stored in the session — hiding a display is not
    /// discarding what the model said.
    Hidden,
    /// Folded, previewing at most this many characters and one ellipsis.
    Clamp(usize),
}

impl Mode {
    /// One word for the report.
    pub fn word(self) -> String {
        match self {
            Mode::Folded => "folded".to_string(),
            Mode::Full => "full".to_string(),
            Mode::Hidden => "hidden".to_string(),
            Mode::Clamp(n) => format!("clamped at {n} chars"),
        }
    }

    /// Whether a reasoning block is drawn at all.
    pub fn hidden(self) -> bool {
        self == Mode::Hidden
    }

    /// Whether a block that would be folded is drawn whole instead.
    pub fn unfolded(self) -> bool {
        self == Mode::Full
    }

    /// The character cap of a folded block's preview, when one was asked for.
    pub fn clamp(self) -> Option<usize> {
        match self {
            Mode::Clamp(n) => Some(n),
            _ => None,
        }
    }
}

/// Parse the argument of `/reasoning`.
///
/// Accepts one word (`high`), two (`--global high`, `clamp 200`), and the display words. Anything
/// else is `Err` with the word that was not understood, because a typo that silently does nothing
/// is the worst outcome for a knob.
pub fn parse(arg: &str) -> Result<Change, String> {
    let words: Vec<&str> = arg.split_whitespace().collect();
    match words.as_slice() {
        [] => Ok(Change::Report),
        ["show"] | ["full"] => Ok(Change::Display(Mode::Full)),
        ["hide"] => Ok(Change::Display(Mode::Hidden)),
        ["fold"] | ["folded"] => Ok(Change::Display(Mode::Folded)),
        ["default"] | ["reset"] | ["auto"] => Ok(Change::Reset),
        ["clamp", n] => match n.parse::<usize>() {
            Ok(0) => Err("clamp needs a positive number of characters".to_string()),
            Ok(chars) => Ok(Change::Display(Mode::Clamp(chars))),
            Err(_) => Err(format!("{n:?} is not a number of characters")),
        },
        ["clamp"] => Err("clamp needs a number: `/reasoning clamp 200`".to_string()),
        ["--global", level] | ["global", level] => match checked_level(level) {
            Ok(level) => Ok(Change::Global(level)),
            Err(why) => Err(why),
        },
        ["--global"] | ["global"] => {
            Err("--global needs a level: `/reasoning --global high`".to_string())
        }
        [level] => Ok(Change::Effort(checked_level(level)?)),
        [first, ..] => Err(format!("{first:?} is not something /reasoning does")),
    }
}

/// Whether an argument only changes what is *drawn*, for a front end that draws nothing.
pub fn is_display(arg: &str) -> bool {
    matches!(parse(arg), Ok(Change::Display(_)))
}

fn checked_level(word: &str) -> Result<String, String> {
    let level = word.trim().to_lowercase();
    if reasoning::is_level(&level) || reasoning::is_omit(&level) {
        return Ok(level);
    }
    Err(format!(
        "{word:?} is not a level; the ladder is {}, or {} for no field at all",
        reasoning::LADDER.join(" · "),
        reasoning::OMIT
    ))
}

/// The report `/reasoning` prints: what is in force, and what it becomes on this backend.
///
/// Built from [`InForce`] rather than from the dial plus a sentence: the level, its origin and the
/// backend's answer are one report (`#264`, `#276`), and `/reasoning` is the third surface that
/// describes the same dial — a second formatter here is how the terminal and the read-out start
/// disagreeing about one session.
pub fn report(in_force: &InForce, display: Mode) -> String {
    let mut out = String::new();
    out.push_str(&format!("effort: {}\n", in_force.in_force));
    out.push_str(&format!(
        "  on this backend  {}\n",
        if in_force.resolved.is_empty() {
            "(unknown)"
        } else {
            &in_force.resolved
        }
    ));
    out.push_str(&format!("  display          {}\n", display.word()));
    out.push('\n');
    out.push_str("levels: ");
    out.push_str(&reasoning::LADDER.join(" · "));
    out.push('\n');
    out.push_str(&format!(
        "{}: send no reasoning field at all (not the same as `none`, which turns thinking off)\n",
        reasoning::OMIT
    ));
    out.push_str(
        "note: `/reasoning high` is this session; `--global high` writes config.toml; `default` \n\
         drops the session override; `show` · `hide` · `clamp <n>` change what is drawn",
    );
    out
}

/// Everything `/reasoning` needs and keeps between calls.
///
/// The backend sentence is **not** stored here: it is passed to [`Live::apply`] as a closure, so one
/// implementation serves the plain REPL (which borrows the agent for one call) and the full-screen
/// interface (which owns it for the whole loop) without either of them owning a `'static` copy of
/// something that can change with `/model`.
pub struct Live {
    pub dial: eclipse_core::reasoning::Shared,
    /// `config.toml`, for `--global`.
    pub config: Option<std::path::PathBuf>,
    pub profile: Option<String>,
    /// What this process draws. The plain REPL has no block to fold, and says so.
    pub display: Mode,
}

impl Live {
    pub fn new(
        dial: eclipse_core::reasoning::Shared,
        config: Option<std::path::PathBuf>,
        profile: Option<String>,
    ) -> Self {
        Self {
            dial,
            config,
            profile,
            display: Mode::Folded,
        }
    }

    /// A context with no config file: what a test builds, and what a session started without a
    /// config file has.
    #[cfg(test)]
    pub fn bare(dial: eclipse_core::reasoning::Shared) -> Self {
        Self::new(dial, None, None)
    }

    /// Run one `/reasoning ...` and return what to print.
    ///
    /// `describe` is asked for the level that will be in force *after* this call — which is why it
    /// takes the level rather than reading a field. `now` is the dial's whole report, for the arms
    /// that describe the state rather than change it; both are closures for the same reason
    /// (the backend and the route can change under a live dial, `/model` being the way).
    pub fn apply(
        &mut self,
        arg: &str,
        describe: &dyn Fn(Option<&str>) -> String,
        now: &dyn Fn() -> InForce,
    ) -> Result<String, String> {
        match parse(arg)? {
            Change::Report => Ok(report(&now(), self.display)),
            Change::Effort(level) => {
                self.dial.set_session(Some(level.clone()));
                Ok(format!(
                    "effort: {level}\n  {}\nnote: this session only — `--global {level}` writes \
                     config.toml and starts the next process with it",
                    describe(Some(&level))
                ))
            }
            Change::Global(level) => {
                let Some(path) = self.config.clone() else {
                    return Err(
                        "no config file to write: this session was started without one".to_string(),
                    );
                };
                crate::settings_cli::set_one(
                    &path,
                    self.profile.as_deref(),
                    "provider.reasoning_effort",
                    &level,
                )?;
                self.dial.set_session(Some(level.clone()));
                Ok(format!(
                    "effort: {level} — written to {}, and in force here\n  {}",
                    path.display(),
                    describe(Some(&level))
                ))
            }
            Change::Reset => {
                self.dial.clear_session();
                let now = now();
                let tail = match (self.dial.configured(), now.by_default) {
                    (Some(_), _) => "config.toml is in charge".to_string(),
                    (None, true) => format!(
                        "nothing is configured, so `{}` is what this backend sends by default",
                        now.label
                    ),
                    (None, false) => format!(
                        "nothing is configured and this backend declares no default, so {}",
                        reasoning::NOT_SENT
                    ),
                };
                Ok(format!(
                    "effort: {} — the session override is gone; {tail}",
                    now.label
                ))
            }
            Change::Display(mode) => {
                self.display = mode;
                Ok(match mode {
                    Mode::Hidden => {
                        "reasoning: hidden — no block is drawn; it is still stored in the session"
                            .to_string()
                    }
                    Mode::Full => "reasoning: shown whole — never folded".to_string(),
                    Mode::Folded => "reasoning: folded to a preview with a count".to_string(),
                    Mode::Clamp(n) => {
                        format!("reasoning: folded, previewing {n} characters and an ellipsis")
                    }
                })
            }
        }
    }
}

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

    #[test]
    fn one_word_is_a_level_and_the_display_words_are_their_own() {
        assert_eq!(parse("high"), Ok(Change::Effort("high".into())));
        assert_eq!(parse("  HIGH  "), Ok(Change::Effort("high".into())));
        assert_eq!(parse(""), Ok(Change::Report));
        for (word, mode) in [
            ("show", Mode::Full),
            ("full", Mode::Full),
            ("hide", Mode::Hidden),
            ("fold", Mode::Folded),
            ("folded", Mode::Folded),
            ("clamp 200", Mode::Clamp(200)),
        ] {
            assert_eq!(parse(word), Ok(Change::Display(mode)), "{word}");
        }
        assert_eq!(parse("default"), Ok(Change::Reset));
        assert_eq!(parse("--global high"), Ok(Change::Global("high".into())));
    }

    /// `#278`: `omit` is accepted where a level goes, in both forms, and the report says what it
    /// separates it from.
    #[test]
    fn omit_is_a_word_slash_reasoning_accepts() {
        assert_eq!(parse("omit"), Ok(Change::Effort("omit".into())));
        assert_eq!(parse("  OMIT "), Ok(Change::Effort("omit".into())));
        assert_eq!(parse("--global omit"), Ok(Change::Global("omit".into())));
        let shown = report(
            &InForce {
                label: "not sent".into(),
                in_force: "not sent (this session; config.toml says medium)".into(),
                session: true,
                by_default: false,
                resolved: "not sent: asked for no field on this route".into(),
            },
            Mode::Folded,
        );
        assert!(shown.contains("omit"), "{shown}");
        assert!(
            shown.contains("not the same as `none`"),
            "the two words are told apart where a person picks one: {shown}"
        );
    }

    /// A typo that silently does nothing is the worst outcome for a knob, so every refusal names
    /// the word and, for a level, the ladder.
    #[test]
    fn a_word_it_does_not_know_is_refused_with_the_ladder() {
        let why = parse("turbo").unwrap_err();
        assert!(why.contains("turbo"), "{why}");
        assert!(why.contains("xhigh"), "the ladder is spelled: {why}");
        assert!(
            parse("").is_ok(),
            "no argument is the report, not a refusal"
        );
        assert!(parse("clamp").unwrap_err().contains("clamp 200"));
        assert!(parse("clamp 0").unwrap_err().contains("positive"));
        assert!(parse("clamp lots").unwrap_err().contains("lots"));
        assert!(parse("--global").unwrap_err().contains("needs a level"));
    }

    /// A report built the way the live session builds one: the dial plus the route's declared
    /// default, which is what `/reasoning` and the read-out share.
    fn report_of(dial: &Dial, default: Option<&str>) -> InForce {
        dial.in_force_report(default)
    }

    #[test]
    fn the_report_names_the_session_override_only_when_there_is_one() {
        let dial = Dial::new(Some("low".into()));
        let mut quiet = report_of(&dial, None);
        quiet.resolved = "sends low".into();
        let quiet = report(&quiet, Mode::Folded);
        assert!(quiet.contains("effort: low\n"), "{quiet}");
        assert!(
            !quiet.contains("(this session"),
            "the steady state stays quiet — the note at the bottom is instructions, not state: \
             {quiet}"
        );
        dial.set_session(Some("high".into()));
        let loud = report(&report_of(&dial, None), Mode::Folded);
        assert!(
            loud.contains("effort: high (this session; config.toml says low)"),
            "{loud}"
        );
        assert!(loud.contains("display          folded"), "{loud}");
        assert!(loud.contains("clamp <n>"), "{loud}");
    }

    /// The backend sentence is the policy's, not this module's: a level the wire clamps is reported
    /// as clamped, and a backend with no dial says so.
    #[test]
    fn the_backend_sentence_comes_from_the_policy() {
        // The two closures `/reasoning` is handed: the sentence for a level, and the dial's whole
        // report. Both read the same route, which is the point of a session that can `/model`.
        fn say(
            policy: Option<reasoning::Policy>,
        ) -> (impl Fn(Option<&str>) -> String, impl Fn() -> InForce) {
            let policy = std::sync::Arc::new(policy);
            let describe = {
                let policy = policy.clone();
                move |level: Option<&str>| match policy.as_ref() {
                    Some(policy) => policy.describe(level),
                    None => "sent as-is (this backend declares no reasoning control)".to_string(),
                }
            };
            let now = move || InForce {
                resolved: match policy.as_ref() {
                    Some(policy) => policy.describe(None),
                    None => "sent as-is (this backend declares no reasoning control)".to_string(),
                },
                ..InForce::default()
            };
            (describe, now)
        }

        let policy = reasoning::Policy::llamacpp();
        let mut clamped = Live::bare(std::sync::Arc::new(Dial::new(None)));
        let (describe, now) = say(Some(policy));
        let said = clamped.apply("xhigh", &describe, &now).unwrap();
        assert!(said.contains("effort: xhigh"), "{said}");
        assert!(said.contains("xhigh → sends high"), "{said}");
        assert!(said.contains("--global xhigh"), "{said}");

        let off_only = reasoning::Policy {
            field: "reasoning_effort".into(),
            levels: Vec::new(),
            off: Some("none".into()),
            ..Default::default()
        };
        let (describe, now) = say(Some(off_only));
        let mut said = Live::bare(std::sync::Arc::new(Dial::new(None)))
            .apply("high", &describe, &now)
            .unwrap();
        assert!(said.contains("no levels"), "{said}");
        let (describe, now) = say(None);
        said = Live::bare(std::sync::Arc::new(Dial::new(None)))
            .apply("high", &describe, &now)
            .unwrap();
        assert!(said.contains("sent as-is"), "{said}");
    }
    /// A route that declares no default and a file that sets nothing: the report says nothing goes
    /// on the wire — the same answer the request body gives — instead of inventing the shipped
    /// level or leaving a bare `(unset)` to mean two different things (`#276`).
    #[test]
    fn an_unset_effort_says_nothing_is_sent_rather_than_naming_a_default() {
        let dial = Dial::new(None);
        let mut report = dial.in_force_report(None);
        report.resolved = "not sent: nothing asked and this backend declares no default".into();
        let said = super::report(&report, Mode::Hidden);
        assert!(said.contains("effort: not sent\n"), "{said}");
        assert!(
            said.contains("not sent: nothing asked and this backend declares no default"),
            "the backend's reason is the sentence: {said}"
        );
        assert!(said.contains("display          hidden"), "{said}");

        // The shipped case: the file says nothing and the backend declares medium.
        let shipped = dial.in_force_report(Some(reasoning::SHIPPED_DEFAULT));
        let said = super::report(&shipped, Mode::Hidden);
        assert!(
            said.contains("effort: medium (this backend's default; config.toml sets nothing)"),
            "{said}"
        );
    }
}