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() && std::env::var_os("NO_COLOR").is_none() && std::env::var("TERM") .map(|term| term != "dumb") .unwrap_or(true) }) } 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. /// /// Generic over the writer so the line-break rules can be tested without a /// terminal: a reasoning stream does not always end with a newline, and the /// answer must not be appended to the same line as the thinking. pub struct Renderer { out: W, color: bool, dimmed: bool, line_dirty: bool, } impl Renderer { pub fn new() -> Self { Self { out: std::io::stdout(), color: color(), dimmed: false, line_dirty: false, } } } impl Renderer { pub fn with_color(out: W, color: bool) -> Self { Self { out, color, dimmed: false, line_dirty: false, } } fn close_reasoning(&mut self) { if !self.dimmed { return; } let _ = write!(self.out, "\x1b[0m"); if self.line_dirty { let _ = writeln!(self.out); self.line_dirty = false; } self.dimmed = false; } } impl Sink for Renderer { fn text(&mut self, s: &str) { self.close_reasoning(); let _ = write!(self.out, "{s}"); let _ = self.out.flush(); self.line_dirty = !s.ends_with('\n'); } fn reasoning(&mut self, s: &str) { if !self.color { return; } if !self.dimmed { let _ = write!(self.out, "\x1b[2m"); self.dimmed = true; } let _ = write!(self.out, "{s}"); let _ = self.out.flush(); self.line_dirty = !s.ends_with('\n'); } fn done(&mut self, _outcome: &Outcome, _elapsed: Duration) { self.close_reasoning(); if self.line_dirty { let _ = writeln!(self.out); self.line_dirty = false; } let _ = self.out.flush(); } } pub fn tool_line(step: usize, name: &str, args: &serde_json::Value, include_detail: bool) { 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(), }; let head = paint("1;36", &format!("● [{step}] {name}")); if include_detail && !detail.is_empty() { println!("{head} {detail}"); } else { println!("{head}"); } 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(); } #[derive(Debug, Default, Clone, Copy)] pub struct Summary { pub writes: usize, pub commands: usize, pub denied: usize, } pub fn status(steps: usize, elapsed: Duration, outcome: &Outcome, summary: &Summary) { let mut parts = vec![ if steps == 1 { "1 step".to_string() } else { format!("{steps} steps") }, format!("{:.1}s", elapsed.as_secs_f64()), ]; if summary.writes > 0 { parts.push(format!( "{} write{}", summary.writes, if summary.writes == 1 { "" } else { "s" } )); } if summary.commands > 0 { parts.push(format!( "{} command{}", summary.commands, if summary.commands == 1 { "" } else { "s" } )); } if summary.denied > 0 { parts.push(format!("{} denied", summary.denied)); } 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(); // Typeahead from before the prompt appeared must not answer it: a "y" // typed during streaming would otherwise approve a command unseen. unsafe { libc::tcflush(libc::STDIN_FILENO, libc::TCIFLUSH); } let mut line = String::new(); if std::io::stdin().read_line(&mut line).unwrap_or(0) == 0 { return Answer::No; } // Ctrl-C during the prompt arrives as a signal, not a keystroke. if crate::signal::CANCEL.load(std::sync::atomic::Ordering::Relaxed) { 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}"); // The path is already on the tool line above. let _ = path; match self.ask("apply this change?", true) { Answer::Yes => true, Answer::Always => { self.edits_allowed = true; true } Answer::No => false, } } /// True when the next bash call will actually be shown to a human, which is /// the only case where the command appears in the prompt rather than the /// tool line. pub fn will_prompt_bash(&self) -> bool { !self.yolo && self.interactive } /// 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 } } #[cfg(test)] mod tests { use super::*; fn rendered(color: bool, run: impl FnOnce(&mut Renderer>)) -> String { let mut renderer = Renderer::with_color(Vec::new(), color); run(&mut renderer); String::from_utf8(renderer.out).unwrap() } #[test] fn the_answer_starts_on_its_own_line_after_reasoning() { let text = rendered(true, |renderer| { renderer.reasoning("thinking without a newline"); renderer.text("the answer"); renderer.done(&Outcome::default(), Duration::ZERO); }); assert_eq!( text, "\u{1b}[2mthinking without a newline\u{1b}[0m\nthe answer\n" ); } #[test] fn reasoning_that_already_ended_with_a_newline_gets_no_blank_line() { let text = rendered(true, |renderer| { renderer.reasoning("thinking\n"); renderer.text("answer"); renderer.done(&Outcome::default(), Duration::ZERO); }); assert_eq!(text, "\u{1b}[2mthinking\n\u{1b}[0manswer\n"); } #[test] fn reasoning_alone_still_ends_the_line() { let text = rendered(true, |renderer| { renderer.reasoning("only thinking"); renderer.done(&Outcome::default(), Duration::ZERO); }); assert_eq!(text, "\u{1b}[2monly thinking\u{1b}[0m\n"); } #[test] fn reasoning_is_dropped_when_colour_is_off() { let text = rendered(false, |renderer| { renderer.reasoning("invisible"); renderer.text("answer"); renderer.done(&Outcome::default(), Duration::ZERO); }); assert_eq!(text, "answer\n"); } }