use std::io::{IsTerminal, Write}; use std::sync::OnceLock; use std::time::Duration; use crate::provider::{Outcome, Sink}; pub fn stdout_is_tty() -> bool { std::io::stdout().is_terminal() } pub fn stdin_is_tty() -> bool { std::io::stdin().is_terminal() } fn color() -> bool { static COLOR: OnceLock = OnceLock::new(); *COLOR.get_or_init(stdout_is_tty) } fn paint(code: &str, text: &str) -> String { if color() { format!("\x1b[{code}m{text}\x1b[0m") } else { text.to_string() } } /// Streams to stdout. Colour is used only when stdout is a terminal, so piping /// the output somewhere gives clean text. pub struct Renderer { dimmed: bool, wrote_text: bool, } impl Renderer { pub fn new() -> Self { Self { dimmed: false, wrote_text: false, } } fn undim(&mut self) { if self.dimmed { print!("\x1b[0m"); self.dimmed = false; } } } impl Sink for Renderer { fn text(&mut self, s: &str) { self.undim(); print!("{s}"); let _ = std::io::stdout().flush(); self.wrote_text = true; } fn reasoning(&mut self, s: &str) { if !color() { return; } if !self.dimmed { print!("\x1b[2m"); self.dimmed = true; } print!("{s}"); let _ = std::io::stdout().flush(); } fn done(&mut self, _outcome: &Outcome, _elapsed: Duration) { self.undim(); if self.wrote_text { println!(); self.wrote_text = false; } } } pub fn tool_line(name: &str, args: &serde_json::Value) { let detail = match name { "bash" => args .get("cmd") .and_then(|v| v.as_str()) .unwrap_or("") .to_string(), "grep" => format!( "{} in {}", args.get("pattern").and_then(|v| v.as_str()).unwrap_or(""), args.get("path").and_then(|v| v.as_str()).unwrap_or(".") ), "glob" => args .get("pattern") .and_then(|v| v.as_str()) .unwrap_or("") .to_string(), _ => args .get("path") .and_then(|v| v.as_str()) .unwrap_or("") .to_string(), }; println!("{} {}", paint("1;36", &format!("● {name}")), detail); let _ = std::io::stdout().flush(); } pub fn tool_result(summary: &str, aborted: bool) { let text = if aborted { "aborted".to_string() } else { crate::provider::truncate(summary.trim(), 100) }; println!(" {} {}", paint("2", "└"), paint("2", &text)); let _ = std::io::stdout().flush(); } pub fn status(steps: usize, elapsed: Duration, outcome: &Outcome) { let mut parts = vec![ if steps == 1 { "1 step".to_string() } else { format!("{steps} steps") }, format!("{:.1}s", elapsed.as_secs_f64()), ]; let (input, output) = outcome.tokens(); if let (Some(i), Some(o)) = (input, output) { parts.push(format!("{i} in · {o} out")); } if let Some(allowance) = outcome.allowance() { if allowance > 0.0 { parts.push(format!("${allowance:.6}")); } } println!("{}", paint("2", &format!("─ {}", parts.join(" · ")))); let _ = std::io::stdout().flush(); } #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Answer { No, Yes, Always, } pub struct Approver { yolo: bool, interactive: bool, edits_allowed: bool, } impl Approver { pub fn new(yolo: bool) -> Self { Self { yolo, interactive: stdin_is_tty(), edits_allowed: false, } } pub fn yolo(&self) -> bool { self.yolo } fn ask(&self, question: &str, allow_always: bool) -> Answer { if self.yolo { return Answer::Yes; } if !self.interactive { println!( "{}", paint("33", " no terminal to ask; denied (use --yolo to allow)") ); return Answer::No; } let hint = if allow_always { "[y/N/a]" } else { "[y/N]" }; print!("\n{} {} ", question, paint("2", hint)); let _ = std::io::stdout().flush(); let mut line = String::new(); if std::io::stdin().read_line(&mut line).unwrap_or(0) == 0 { return Answer::No; } match line.trim().to_ascii_lowercase().as_str() { "y" | "yes" => Answer::Yes, "a" | "always" if allow_always => Answer::Always, _ => Answer::No, } } /// One prompt for the first edit of a session, then silent. pub fn allow_edit(&mut self, path: &str, preview: &str) -> bool { if self.yolo || self.edits_allowed { return true; } println!("{preview}"); match self.ask(&format!("apply this change to {path}?"), true) { Answer::Yes => true, Answer::Always => { self.edits_allowed = true; true } Answer::No => false, } } /// Every call, no memory: the point is seeing the command. pub fn allow_bash(&mut self, cmd: &str) -> bool { if self.yolo { return true; } // Bash prompts every call by design, so "always" is not offered here. self.ask(&format!("run: {}", crate::provider::truncate(cmd, 200)), false) == Answer::Yes } }