eclipse-cli 0.13.2

Command-line interface for eclipse
//! 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,
        }
    }
}

/// 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();
    let mut line = String::new();
    match std::io::stdin().lock().read_line(&mut line) {
        Ok(_) => Choice::from_line(&line),
        // No answer readable (a closed stdin, 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");
    }
}