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
//! Asking before a gated tool runs.
//!
//! One decision, three answers, two shapes. The menu exists because of the middle answer:
//! "allow this tool for the rest of the session" is what makes a local agent usable — `date`
//! should not cost a decision every time, and `rm` should.
//!
//! An arrow-key menu is drawn when both ends of the terminal belong to a person. A pipe, a
//! script or a test gets the plain `[y/s/N]` line, because arrow keys on a pipe are nonsense
//! and every CLI test drives stdin that way.

use crate::ui::{self, Style};
use eclipse_core::approvals::{Decision, Pending};
use eclipse_core::tools::Approver;
use std::collections::HashSet;
use std::io::{BufRead, IsTerminal, Write};
use std::sync::{Arc, Mutex};

/// Nobody to ask, and a run that must not answer on the user's behalf: every gated call is
/// deferred, recorded in the session, and the loop stops. This is what `run --approvals-out` puts
/// in place of the prompt, and what a scripted run wants — the alternative, denying, would tell
/// the model a decision was made that nobody made.
pub struct DeferAll;

#[async_trait::async_trait]
impl Approver for DeferAll {
    async fn decide(&self, _: &Pending) -> Decision {
        Decision::Defer
    }
}

/// What the person chose. `Approver` carries only a bool, so `Deny` is `false` and the middle
/// answer is remembered as a side effect on [`SessionAllows`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Choice {
    Once,
    Session,
    Deny,
}

impl Choice {
    /// In the order the menu shows them, with the safe one last so the cursor can rest there.
    pub const ALL: [Choice; 3] = [Choice::Once, Choice::Session, Choice::Deny];

    pub fn label(&self, tool: &str) -> String {
        match self {
            Choice::Once => "Allow once".to_string(),
            Choice::Session => format!("Allow {tool} for this session"),
            Choice::Deny => "Deny".to_string(),
        }
    }

    /// The cursor starts on `Deny`: an accidental Enter must not run a command. One arrow up
    /// is a cheap price for that.
    fn default_index() -> usize {
        Self::ALL.len() - 1
    }

    fn from_line(line: &str) -> Self {
        match line.trim().to_lowercase().as_str() {
            "y" | "yes" => Self::Once,
            "s" | "session" | "a" | "all" => Self::Session,
            _ => Self::Deny,
        }
    }
}

/// Tools allowed for the rest of the interface's life, by name.
///
/// Shared by clone across every turn of a REPL or an interface session, which is the whole
/// point: the answer outlives the run that asked for it.
#[derive(Clone, Default)]
pub struct SessionAllows(Arc<Mutex<HashSet<String>>>);

impl SessionAllows {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn contains(&self, tool: &str) -> bool {
        self.0.lock().map(|s| s.contains(tool)).unwrap_or(false)
    }

    pub fn insert(&self, tool: &str) {
        if let Ok(mut set) = self.0.lock() {
            set.insert(tool.to_string());
        }
    }
}

/// Asks on the terminal, with a menu when there is a person to drive it.
pub struct TtyApprover {
    style: Style,
    session: SessionAllows,
}

impl TtyApprover {
    pub fn new(style: Style, session: SessionAllows) -> Self {
        Self { style, session }
    }
}

#[async_trait::async_trait]
impl Approver for TtyApprover {
    async fn decide(&self, call: &Pending) -> Decision {
        let (tool, summary) = (call.tool.as_str(), call.summary.as_str());
        if self.session.contains(tool) {
            return Decision::Allow;
        }
        let interactive = std::io::stdin().is_terminal() && std::io::stderr().is_terminal();
        let tool_owned = tool.to_string();
        let summary_owned = summary.to_string();
        let style = self.style;
        let choice = tokio::task::spawn_blocking(move || {
            if interactive {
                menu(&style, &tool_owned, &summary_owned)
                    // A terminal that cannot be put in raw mode is not a reason to refuse:
                    // ask the plain question instead.
                    .unwrap_or_else(|| line_prompt(&style, &tool_owned, &summary_owned))
            } else {
                line_prompt(&style, &tool_owned, &summary_owned)
            }
        })
        .await
        .unwrap_or(Choice::Deny);

        if choice == Choice::Session {
            self.session.insert(tool);
        }
        match choice {
            Choice::Deny => Decision::Deny("declined at the prompt".to_string()),
            _ => Decision::Allow,
        }
    }
}

/// One line from the person, from the terminal they are actually at.
///
/// `eclipse run -` reads the task from stdin to EOF, so the first gate after it reads an empty
/// line and reports "declined at the prompt" — a refusal nobody made, told to the model as fact
/// (`#594`). When stdin is not a terminal but the process has one, the question goes to `/dev/tty`
/// and the answer comes from there. With no terminal at all the read returns nothing, which is a
/// refusal for the right reason: nobody was asked.
fn answer_line() -> std::io::Result<String> {
    let mut line = String::new();
    if !std::io::stdin().is_terminal() {
        if let Ok(tty) = std::fs::File::open("/dev/tty") {
            std::io::BufReader::new(tty).read_line(&mut line)?;
            return Ok(line);
        }
    }
    std::io::stdin().lock().read_line(&mut line)?;
    Ok(line)
}

/// The `[y/s/N]` question, for a pipe or a terminal without raw mode.
fn line_prompt(style: &Style, tool: &str, summary: &str) -> Choice {
    let prompt = format!(
        "{} {} {} {} ",
        style.yellow("?"),
        style.bold(&format!("Allow {}:", ui::sanitize(tool, false))),
        ui::sanitize(summary, false),
        style.dim("[y/s/N]")
    );
    let mut err = std::io::stderr();
    let _ = write!(err, "{prompt}");
    let _ = err.flush();
    match answer_line() {
        // A line, or the end of one: a person who pressed enter without a word is a refusal, and
        // `from_line` says so.
        Ok(line) => Choice::from_line(&line),
        // No answer readable (no terminal, a script that died): refusal, never consent.
        Err(_) => Choice::Deny,
    }
}

/// A streak of unreadable terminal events, and the point at which the menu gives up.
///
/// One failure is noise; a run of them is a terminal that is gone, and the caller's line prompt (or
/// a refusal) is the only honest answer left. Kept separate from the loop so the rule can be tested
/// without a PTY that breaks in the middle of a prompt.
#[derive(Debug, Default)]
struct Unreadable(u8);

impl Unreadable {
    /// How many failures in a row before the menu stops and lets the caller fall back.
    const GIVE_UP: u8 = 3;

    /// Record a failure. `true` means stop trying.
    fn failed(&mut self) -> bool {
        self.0 = self.0.saturating_add(1);
        self.0 >= Self::GIVE_UP
    }

    /// Record a key that arrived: the terminal is answering again.
    fn readable(&mut self) {
        self.0 = 0;
    }
}

/// Draw the menu, read keys until one is confirmed. `None` means the terminal would not
/// co-operate and the caller should fall back to the line prompt.
fn menu(style: &Style, tool: &str, summary: &str) -> Option<Choice> {
    use ratatui::crossterm::{
        cursor,
        event::{self, Event, KeyCode, KeyEventKind, KeyModifiers},
        terminal,
    };

    terminal::enable_raw_mode().ok()?;
    let restore = Restore;
    let mut err = std::io::stderr();
    let _ = write!(err, "{}", cursor::Hide);
    let _ = err.flush();

    // A window that reports no size (a bare PTY, some multiplexer panes) still needs a width
    // to cut against: 80 is the conventional guess and beats drawing nothing.
    let width = terminal::size()
        .map(|(w, _)| w as usize)
        .unwrap_or(80)
        .max(20);
    let summary = ui::sanitize(summary, false);
    let summary = one_line(&summary, width.saturating_sub(4));
    let mut selected = Choice::default_index();
    let mut drawn = 0usize;
    // A terminal that will not answer is not a terminal that said yes. `event::read` failing once is
    // ordinary (a resize, a stray escape); failing for ever means the PTY is gone, and redrawing in
    // raw mode on every iteration left the process spinning with the terminal unusable — in the one
    // path that decides whether a dangerous call runs.
    let mut unreadable = Unreadable::default();

    let choice = loop {
        let mut block = String::new();
        block.push_str(&format!(
            "{} {}\r\n",
            style.yellow("?"),
            style.bold(&format!("Allow {}?", ui::sanitize(tool, false)))
        ));
        block.push_str(&format!("  {}\r\n\r\n", style.dim(&summary)));
        for (i, c) in Choice::ALL.iter().enumerate() {
            let row = c.label(tool);
            if i == selected {
                block.push_str(&format!("  {} {}\r\n", style.cyan("›"), style.bold(&row)));
            } else {
                block.push_str(&format!("    {row}\r\n"));
            }
        }
        block.push_str(&format!(
            "\r\n  {}\r\n",
            style.dim("↑↓ move · enter confirm · esc deny")
        ));

        if drawn > 0 {
            let _ = write!(err, "\x1b[{drawn}A\x1b[J");
        }
        let _ = write!(err, "{block}");
        let _ = err.flush();
        drawn = count_lines(&block);

        let key = match event::read() {
            Ok(Event::Key(key)) => {
                unreadable.readable();
                key
            }
            // Not a key event (a resize, focus, paste): nothing to decide, ask again.
            Ok(_) => continue,
            Err(_) => {
                if unreadable.failed() {
                    return None;
                }
                continue;
            }
        };
        if key.kind == KeyEventKind::Release {
            continue;
        }
        match key.code {
            KeyCode::Up | KeyCode::Char('k') | KeyCode::BackTab => {
                selected = selected.checked_sub(1).unwrap_or(Choice::ALL.len() - 1);
            }
            KeyCode::Down | KeyCode::Char('j') | KeyCode::Tab => {
                selected = (selected + 1) % Choice::ALL.len();
            }
            KeyCode::Enter => break Choice::ALL[selected],
            KeyCode::Esc => break Choice::Deny,
            KeyCode::Char('y') | KeyCode::Char('Y') => break Choice::Once,
            KeyCode::Char('n') | KeyCode::Char('N') => break Choice::Deny,
            KeyCode::Char('1') => break Choice::Once,
            KeyCode::Char('2') => break Choice::Session,
            KeyCode::Char('3') => break Choice::Deny,
            KeyCode::Char('c') | KeyCode::Char('d')
                if key.modifiers.contains(KeyModifiers::CONTROL) =>
            {
                break Choice::Deny
            }
            _ => {}
        }
    };

    // Leave the answer behind, the way a printed prompt would have.
    let _ = write!(
        err,
        "\x1b[{drawn}A\x1b[J{} {} {}\r\n",
        style.yellow("?"),
        style.bold(&format!("Allow {}?", ui::sanitize(tool, false))),
        match choice {
            Choice::Once => style.green("allow once"),
            Choice::Session => style.green(&format!("allowed {tool} for this session")),
            Choice::Deny => style.red("deny"),
        }
    );
    drop(restore);
    let _ = write!(err, "{}", cursor::Show);
    let _ = err.flush();
    Some(choice)
}

/// Restores the terminal however the menu is left, panics included.
struct Restore;

impl Drop for Restore {
    fn drop(&mut self) {
        let _ = ratatui::crossterm::terminal::disable_raw_mode();
    }
}

fn count_lines(block: &str) -> usize {
    block.matches("\r\n").count()
}

/// The second line and beyond never fit a menu: keep the head, say it was cut.
fn one_line(text: &str, width: usize) -> String {
    let flat = text.split_whitespace().collect::<Vec<_>>().join(" ");
    if flat.chars().count() > width {
        format!(
            "{}…",
            flat.chars()
                .take(width.saturating_sub(1))
                .collect::<String>()
        )
    } else {
        flat
    }
}

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

    #[test]
    fn the_plain_prompt_reads_the_three_answers_and_defaults_to_no() {
        assert_eq!(Choice::from_line("y\n"), Choice::Once);
        assert_eq!(Choice::from_line(" YES "), Choice::Once);
        assert_eq!(Choice::from_line("s"), Choice::Session);
        assert_eq!(Choice::from_line("session"), Choice::Session);
        assert_eq!(Choice::from_line("n"), Choice::Deny);
        // Anything unrecognised, including an empty line, is a refusal.
        for other in ["", "\n", "maybe", "yes please", "0"] {
            assert_eq!(Choice::from_line(other), Choice::Deny, "{other:?}");
        }
    }

    /// A terminal that stops answering must not spin: the menu gives up after a short run of
    /// failures and leaves it to the line prompt, and one good key means it was a hiccup.
    #[test]
    fn a_terminal_that_stops_answering_is_given_up_on_but_hiccups_are_not() {
        let mut streak = Unreadable::default();
        assert!(!streak.failed(), "one failure is not a verdict");
        assert!(!streak.failed(), "nor two");
        assert!(streak.failed(), "three in a row and the menu stops");

        // A key in between resets the count: a resize during a prompt is not a broken terminal.
        let mut streak = Unreadable::default();
        for _ in 0..10 {
            assert!(!streak.failed());
            assert!(!streak.failed());
            streak.readable();
        }
    }

    #[test]
    fn the_menu_starts_on_deny_and_names_the_answer_per_tool() {
        assert_eq!(Choice::ALL[Choice::default_index()], Choice::Deny);
        assert_eq!(Choice::Once.label("shell"), "Allow once");
        assert_eq!(
            Choice::Session.label("shell"),
            "Allow shell for this session"
        );
        assert_eq!(Choice::Deny.label("shell"), "Deny");
    }

    #[test]
    fn a_session_answer_outlives_the_run_that_asked_for_it() {
        let allows = SessionAllows::new();
        assert!(!allows.contains("shell"));
        let cloned = allows.clone();
        allows.insert("shell");
        assert!(
            cloned.contains("shell"),
            "the clone shares the set — that is the point"
        );
        assert!(!cloned.contains("write_file"), "per tool, not per session");
    }

    #[test]
    fn a_long_summary_is_flattened_and_cut() {
        let cut = one_line("write\n   a   file\twith content", 12);
        assert!(!cut.contains('\n'), "{cut}");
        assert!(cut.ends_with('…'), "{cut}");
        assert_eq!(cut.chars().count(), 12);
        assert_eq!(one_line("short", 40), "short");
    }
}