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};
pub struct DeferAll;
#[async_trait::async_trait]
impl Approver for DeferAll {
async fn decide(&self, _: &Pending) -> Decision {
Decision::Defer
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Choice {
Once,
Session,
Deny,
}
impl Choice {
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(),
}
}
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,
}
}
}
#[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());
}
}
}
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)
.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,
}
}
}
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)
}
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() {
Ok(line) => Choice::from_line(&line),
Err(_) => Choice::Deny,
}
}
#[derive(Debug, Default)]
struct Unreadable(u8);
impl Unreadable {
const GIVE_UP: u8 = 3;
fn failed(&mut self) -> bool {
self.0 = self.0.saturating_add(1);
self.0 >= Self::GIVE_UP
}
fn readable(&mut self) {
self.0 = 0;
}
}
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();
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;
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
}
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
}
_ => {}
}
};
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)
}
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()
}
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);
for other in ["", "\n", "maybe", "yes please", "0"] {
assert_eq!(Choice::from_line(other), Choice::Deny, "{other:?}");
}
}
#[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");
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");
}
}