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
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
//! Minimal terminal styling: ANSI colors, disabled when not a TTY or `NO_COLOR` is set.

use crate::markdown;
use eclipse_core::runtime::{AgentEvent, JudgementStatus, MemoryStatus};
use std::io::{IsTerminal, Write};
use std::sync::Mutex;

#[derive(Clone, Copy)]
pub struct Style {
    pub color: bool,
    /// Whether the stream is a terminal. Layout decisions that would pollute a pipe (the
    /// startup panel, the status line) key off this, not off colour.
    pub tty: bool,
}

impl Style {
    pub fn for_stdout() -> Self {
        Self::detect(std::io::stdout().is_terminal())
    }

    pub fn for_stderr() -> Self {
        Self::detect(std::io::stderr().is_terminal())
    }

    fn detect(is_tty: bool) -> Self {
        Self {
            color: is_tty && std::env::var_os("NO_COLOR").is_none(),
            tty: is_tty,
        }
    }

    /// Apply `[cli] color`. `Some(false)` never colours. `Some(true)` colours whenever the
    /// stream is a terminal, overriding `NO_COLOR` — that variable is a default, and a
    /// setting in your config is an instruction. `None` keeps the detected decision.
    pub fn with_color_pref(mut self, pref: Option<bool>) -> Self {
        match pref {
            Some(false) => self.color = false,
            Some(true) => self.color = self.tty,
            None => {}
        }
        self
    }

    /// Colour on, terminal assumed. For a test that asserts what a *person* sees — the escapes
    /// included — which `plain()` cannot, and `for_stdout()` will not when stdout is a pipe.
    /// Compiled only for tests: nothing in a run needs a style that lies about its terminal.
    #[cfg(test)]
    pub fn coloured() -> Self {
        Self {
            color: true,
            tty: true,
        }
    }

    /// No colour, no terminal: what a test, a pipe, or a caller that does its own styling
    /// (the TUI) sees.
    pub fn plain() -> Self {
        Self {
            color: false,
            tty: false,
        }
    }

    fn paint(&self, code: &str, s: &str) -> String {
        if self.color {
            format!("\x1b[{code}m{s}\x1b[0m")
        } else {
            s.to_string()
        }
    }

    pub fn bold(&self, s: &str) -> String {
        self.paint("1", s)
    }
    pub fn dim(&self, s: &str) -> String {
        self.paint("2", s)
    }
    pub fn red(&self, s: &str) -> String {
        self.paint("31", s)
    }
    pub fn green(&self, s: &str) -> String {
        self.paint("32", s)
    }
    pub fn yellow(&self, s: &str) -> String {
        self.paint("33", s)
    }
    pub fn cyan(&self, s: &str) -> String {
        self.paint("36", s)
    }
    /// The brand amber: the rings, labels and the context bar. 256-colour 214 is the closest
    /// stable step to the logo's `#FFB45E`; truecolor would be prettier and less portable.
    pub fn amber(&self, s: &str) -> String {
        if self.color {
            format!("\x1b[38;5;214m{s}\x1b[0m")
        } else {
            s.to_string()
        }
    }
}

#[derive(Default)]
struct PrintState {
    /// Streamed text is on stdout without its trailing newline yet.
    line_open: bool,
    /// The current model reply was already printed as deltas.
    streamed: bool,
    /// Markdown mode only: the incomplete last line, held back until its newline
    /// arrives (or the reply ends) because each line is rendered as a unit.
    pending: String,
    md: markdown::Renderer,
}

impl PrintState {
    /// Write the held-back partial line (markdown mode) and end any open line.
    fn close_line(&mut self, out: &mut dyn Write) {
        if !self.pending.is_empty() {
            let line = std::mem::take(&mut self.pending);
            let _ = writeln!(out, "{}", self.md.line(&line));
        } else if self.line_open {
            let _ = writeln!(out);
        }
        self.line_open = false;
    }
}

/// Renders agent events: assistant text goes to stdout (incrementally when the
/// provider streams), tool activity to stderr. With `markdown` on (the CLI enables it
/// only when stdout is a colour terminal) assistant text is rendered as approximate
/// ANSI markdown, one complete line at a time; otherwise it is printed as-is.
pub struct EventPrinter {
    err_style: Style,
    markdown: bool,
    state: Mutex<PrintState>,
}

impl EventPrinter {
    pub fn new(err_style: Style) -> Self {
        Self {
            err_style,
            markdown: false,
            state: Mutex::default(),
        }
    }

    pub fn with_markdown(mut self, on: bool) -> Self {
        self.markdown = on;
        self
    }

    pub fn handle(&self, event: &AgentEvent) {
        self.handle_to(event, &mut std::io::stdout(), &mut std::io::stderr());
    }

    /// Terminate a half-printed streamed line, e.g. after an error mid-reply.
    pub fn finish(&self) {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        let mut out = std::io::stdout();
        state.close_line(&mut out);
        state.md.reset();
        let _ = out.flush();
    }

    pub fn handle_to(&self, event: &AgentEvent, out: &mut dyn Write, err: &mut dyn Write) {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        let style = self.err_style;
        match event {
            AgentEvent::Delta(text) => {
                let text = sanitize(text, true);
                if self.markdown {
                    state.pending.push_str(&text);
                    while let Some(nl) = state.pending.find('\n') {
                        let line: String = state.pending.drain(..=nl).collect();
                        let rendered = state.md.line(line.trim_end_matches('\n'));
                        let _ = writeln!(out, "{rendered}");
                    }
                } else {
                    let _ = write!(out, "{text}");
                    state.line_open = true;
                }
                let _ = out.flush();
                state.streamed = true;
            }
            AgentEvent::Message(text) => {
                if !state.streamed {
                    let text = sanitize(text, true);
                    if self.markdown {
                        let _ = writeln!(out, "{}", markdown::render(&text));
                    } else {
                        let _ = writeln!(out, "{text}");
                    }
                } else {
                    state.close_line(out);
                }
                *state = PrintState::default();
            }
            // A printer writes the lines in order, so it needs no id (`#366`).
            AgentEvent::ToolCall {
                name, arguments, ..
            } => {
                state.close_line(out);
                *state = PrintState::default();
                let _ = writeln!(
                    err,
                    "{}",
                    style.dim(&format!("→ {name}({})", clip(arguments, 100)))
                );
            }
            AgentEvent::ContextTrimmed {
                turns,
                messages,
                memory,
                judgement,
            } => {
                state.close_line(out);
                *state = PrintState::default();
                let said = |j: &JudgementStatus| -> String {
                    match j {
                        JudgementStatus::Off => String::new(),
                        JudgementStatus::Used { bullets } => format!(
                            "; judgement: {bullets} grounded bullet{} added by the aux route",
                            if *bullets == 1 { "" } else { "s" }
                        ),
                        JudgementStatus::Rejected(e) => {
                            format!("; judgement rejected ({})", clip(e, 100))
                        }
                        JudgementStatus::Failed(e) => {
                            format!("; judgement failed ({})", clip(e, 100))
                        }
                    }
                };
                let how = match memory {
                    MemoryStatus::Reused => {
                        "; reused from this session's memory, no recompile".to_string()
                    }
                    MemoryStatus::Saved => "; saved to this session's memory".to_string(),
                    MemoryStatus::SaveFailed(e) => {
                        format!("; could not save session memory ({})", clip(e, 100))
                    }
                    MemoryStatus::NotUsed => String::new(),
                };
                let line = format!(
                    "[context: {turns} older turn(s), {messages} message(s) replaced by the compiled handoff to fit provider.context_budget_tokens{how}{}]",
                    said(judgement)
                );
                let _ = writeln!(err, "{}", style.dim(&line));
            }
            AgentEvent::SchemaRejected { error, retrying } => {
                state.close_line(out);
                *state = PrintState::default();
                let what = if *retrying {
                    "did not match the schema; asking once more with the error"
                } else {
                    "still does not match the schema"
                };
                let _ = writeln!(
                    err,
                    "{}",
                    style.dim(&format!("[reply {what}: {}]", clip(error, 160)))
                );
            }
            // Reasoning and tool-call argument fragments are for the TUI; the REPL reply
            // is prose, and printing fragments here would garble it.
            AgentEvent::ReasoningDelta(_) | AgentEvent::ToolCallDelta { .. } => {}
            // The status line owns this: printing here would fight with the prompt.
            AgentEvent::TurnStats { .. } => {}
            AgentEvent::ToolResult {
                output, is_error, ..
            } => {
                let line = format!("  {}", clip(output, 100));
                let _ = writeln!(
                    err,
                    "{}",
                    if *is_error {
                        style.red(&line)
                    } else {
                        style.dim(&line)
                    }
                );
            }
        }
    }
}

/// Escape control characters so model- or tool-supplied text cannot drive the terminal
/// (colour codes, cursor moves, `\r` overwrites that could disguise an approval prompt).
/// Newlines and tabs are kept unless `keep_layout` is false.
pub fn sanitize(s: &str, keep_layout: bool) -> String {
    s.chars()
        .flat_map(|c| {
            let escape = c.is_control() && !(keep_layout && (c == '\n' || c == '\t'));
            let (plain, escaped) = if escape {
                (None, Some(c.escape_default()))
            } else {
                (Some(c), None)
            };
            plain.into_iter().chain(escaped.into_iter().flatten())
        })
        .collect()
}

/// Clip to `max` chars on a single line, appending an ellipsis if cut.
pub fn clip(s: &str, max: usize) -> String {
    let one_line = sanitize(&s.split_whitespace().collect::<Vec<_>>().join(" "), false);
    if one_line.chars().count() <= max {
        one_line
    } else {
        let cut: String = one_line.chars().take(max).collect();
        format!("{cut}…")
    }
}

pub use eclipse_core::session::format_utc;

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

    #[test]
    fn a_colour_setting_beats_what_the_stream_suggests() {
        // On a terminal, detection says yes; the config can still say no.
        assert!(!Style::detect(true).with_color_pref(Some(false)).color);
        // `Some(true)` colours only because the stream can carry it: forcing ANSI into a
        // pipe would corrupt exactly the output a script is parsing.
        assert!(Style::detect(true).with_color_pref(Some(true)).color);
        assert!(!Style::detect(false).with_color_pref(Some(true)).color);
        // None leaves the decision where detection put it.
        assert!(Style::detect(true).with_color_pref(None).color);
        assert!(!Style::detect(false).with_color_pref(None).color);
    }

    #[test]
    fn plain_style_has_no_escapes() {
        let s = Style::plain();
        assert_eq!(s.red("x"), "x");
        assert!(Style {
            color: true,
            tty: true
        }
        .red("x")
        .contains("\x1b[31m"));
    }

    #[test]
    fn clip_flattens_and_truncates() {
        assert_eq!(clip("a\n b", 10), "a b");
        assert_eq!(clip("abcdef", 3), "abc…");
    }

    fn render(events: &[AgentEvent]) -> (String, String) {
        let printer = EventPrinter::new(Style::plain());
        let (mut out, mut err) = (Vec::new(), Vec::new());
        for e in events {
            printer.handle_to(e, &mut out, &mut err);
        }
        (
            String::from_utf8(out).unwrap(),
            String::from_utf8(err).unwrap(),
        )
    }

    #[test]
    fn streamed_reply_is_printed_once_with_one_newline() {
        let (out, _) = render(&[
            AgentEvent::Delta("Hel".into()),
            AgentEvent::Delta("lo\x1b[2J".into()),
            AgentEvent::Message("Hello\x1b[2J".into()),
        ]);
        assert_eq!(out, "Hello\\u{1b}[2J\n");
    }

    #[test]
    fn unstreamed_reply_is_printed_from_the_final_message() {
        let (out, err) = render(&[AgentEvent::Message("whole".into())]);
        assert_eq!((out.as_str(), err.as_str()), ("whole\n", ""));
    }

    #[test]
    fn streamed_preamble_is_closed_before_tool_activity() {
        let (out, err) = render(&[
            AgentEvent::Delta("let me look".into()),
            AgentEvent::ToolCall {
                call_id: "c1".into(),
                name: "read_file".into(),
                arguments: "{}".into(),
            },
            AgentEvent::Message("done".into()),
        ]);
        assert_eq!(out, "let me look\ndone\n");
        assert!(err.contains("→ read_file({})"));
    }

    #[test]
    fn context_trimming_is_reported_on_stderr() {
        let (out, err) = render(&[AgentEvent::ContextTrimmed {
            turns: 3,
            messages: 12,
            memory: MemoryStatus::NotUsed,
            judgement: JudgementStatus::Off,
        }]);
        assert_eq!(out, "");
        assert!(
            err.contains("3 older turn(s)")
                && err.contains("12 message(s)")
                && err.contains("compiled handoff")
                && !err.contains("model-written summary"),
            "{err}"
        );
    }

    #[test]
    fn the_judgement_pass_is_reported_where_it_stands_or_why_it_did_not() {
        let event = |j| AgentEvent::ContextTrimmed {
            turns: 2,
            messages: 8,
            memory: MemoryStatus::NotUsed,
            judgement: j,
        };
        let (_, used) = render(&[event(JudgementStatus::Used { bullets: 3 })]);
        assert!(
            used.contains("2 older turn(s)")
                && used.contains("compiled handoff")
                && used.contains("3 grounded bullets added by the aux route"),
            "{used}"
        );
        let (_, rejected) = render(&[event(JudgementStatus::Rejected(
            "1 bullet(s) named something the digest does not contain\x1b[2J".into(),
        ))]);
        assert!(
            rejected.contains("judgement rejected (1 bullet(s)")
                && rejected.contains("compiled handoff"),
            "{rejected}"
        );
        assert!(!rejected.contains('\x1b'), "error text is escaped");
        let (_, off) = render(&[event(JudgementStatus::Off)]);
        assert!(
            off.contains("compiled handoff") && !off.contains("judgement"),
            "off says nothing about a pass that did not run: {off}"
        );
    }

    fn render_md(events: &[AgentEvent]) -> String {
        let printer = EventPrinter::new(Style::plain()).with_markdown(true);
        let (mut out, mut err) = (Vec::new(), Vec::new());
        for e in events {
            printer.handle_to(e, &mut out, &mut err);
        }
        String::from_utf8(out).unwrap()
    }

    #[test]
    fn markdown_off_never_emits_ansi_even_for_markdown_text() {
        let (out, _) = render(&[
            AgentEvent::Delta("# T\n**b** `c`\n".into()),
            AgentEvent::Message("# T\n**b** `c`\n".into()),
        ]);
        assert!(!out.contains('\x1b'), "{out:?}");
        assert!(out.starts_with("# T\n**b** `c`\n"));
        let (out, _) = render(&[AgentEvent::Message("**b**".into())]);
        assert_eq!(out, "**b**\n");
    }

    #[test]
    fn markdown_streams_whole_lines_and_renders_them() {
        let out = render_md(&[
            AgentEvent::Delta("# Ti".into()),
            AgentEvent::Delta("tle\nsome **bo".into()),
            AgentEvent::Delta("ld** text\n- item".into()),
            AgentEvent::Message("# Title\nsome **bold** text\n- item".into()),
        ]);
        assert_eq!(
            out,
            "\x1b[1;4;36mTitle\x1b[0m\nsome \x1b[1mbold\x1b[0m text\n\x1b[36m•\x1b[0m item\n"
        );
    }

    #[test]
    fn markdown_holds_back_a_partial_line_until_it_is_complete() {
        let printer = EventPrinter::new(Style::plain()).with_markdown(true);
        let (mut out, mut err) = (Vec::new(), Vec::new());
        printer.handle_to(&AgentEvent::Delta("half **li".into()), &mut out, &mut err);
        assert!(out.is_empty(), "nothing printed before the newline");
        printer.handle_to(&AgentEvent::Delta("ne**".into()), &mut out, &mut err);
        assert!(out.is_empty());
        printer.handle_to(
            &AgentEvent::Message("half **line**".into()),
            &mut out,
            &mut err,
        );
        assert_eq!(String::from_utf8(out).unwrap(), "half \x1b[1mline\x1b[0m\n");
    }

    #[test]
    fn markdown_unstreamed_reply_and_fence_state_do_not_leak_between_replies() {
        let out = render_md(&[
            AgentEvent::Message("```\n*x*".into()),
            AgentEvent::Message("*y*".into()),
        ]);
        assert_eq!(
            out,
            "\x1b[2m```\x1b[0m\n\x1b[33m*x*\x1b[0m\n\x1b[3my\x1b[0m\n"
        );
    }

    #[test]
    fn markdown_flushes_partial_line_before_tool_activity_and_escapes_controls() {
        let out = render_md(&[
            AgentEvent::Delta("look \x1b[2J**now**".into()),
            AgentEvent::ToolCall {
                call_id: "c1".into(),
                name: "t".into(),
                arguments: "{}".into(),
            },
        ]);
        assert!(out.ends_with('\n'));
        assert!(!out.contains("\x1b[2J"), "{out:?}");
        assert!(out.contains("\\u{1b}[2J"));
    }

    #[test]
    fn sanitize_escapes_terminal_control_sequences() {
        assert_eq!(sanitize("a\x1b[2Jb\rc", true), "a\\u{1b}[2Jb\\rc");
        assert_eq!(sanitize("l1\n\tl2", true), "l1\n\tl2");
        assert_eq!(sanitize("l1\nl2", false), "l1\\nl2");
        assert!(!clip("\x1b[31mred", 20).contains('\x1b'));
    }
}