use std::io::{IsTerminal, Write}; use std::time::Duration; use crate::provider::{Outcome, Sink}; pub fn stdout_is_tty() -> bool { std::io::stdout().is_terminal() } /// Streams to stdout. Colour is used only when stdout is a terminal, so piping /// the output somewhere gives clean text. pub struct Renderer { color: bool, dimmed: bool, wrote_text: bool, } impl Renderer { pub fn new(color: bool) -> Self { Self { color, 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 !self.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!(); } let mut parts = vec![format!("{:.1}s", elapsed.as_secs_f64())]; if let Some(usage) = &outcome.usage { let input = usage.get("prompt_tokens").and_then(|v| v.as_u64()); let output = usage.get("completion_tokens").and_then(|v| v.as_u64()); if let (Some(i), Some(o)) = (input, output) { parts.push(format!("{i} in · {o} out")); } } let line = format!("─ {}", parts.join(" · ")); if self.color { println!("\x1b[2m{line}\x1b[0m"); } else { println!("{line}"); } } }