use std::{
io::{IsTerminal, Write},
sync::mpsc::Sender,
};
use haest::{LoopEvent, StopReason, ToolCall, Usage};
use serde_json::{Value, json};
pub struct Renderer<O: Write, E: Write> {
out: O,
err: E,
json: bool,
color: bool,
open_line: bool,
shown_error: Option<String>,
above: Option<Sender<String>>,
}
const DIM: &str = "\x1b[2m";
const RED: &str = "\x1b[31m";
const YELLOW: &str = "\x1b[33m";
const RESET: &str = "\x1b[0m";
impl Renderer<std::io::Stdout, std::io::Stderr> {
pub fn terminal(json: bool) -> Self {
let color = std::io::stderr().is_terminal();
Renderer::new(std::io::stdout(), std::io::stderr(), json, color)
}
}
impl<O: Write, E: Write> Renderer<O, E> {
pub fn new(out: O, err: E, json: bool, color: bool) -> Self {
Self {
out,
err,
json,
color,
open_line: false,
shown_error: None,
above: None,
}
}
pub fn set_above(&mut self, above: Option<Sender<String>>) {
self.above = above;
}
pub fn prompting(&self) -> bool {
self.above.is_some()
}
fn paint(&self, color: &str, text: &str) -> String {
if self.color {
format!("{color}{text}{RESET}")
} else {
text.to_string()
}
}
fn end_line(&mut self) {
if self.open_line {
let _ = writeln!(self.out);
let _ = self.out.flush();
self.open_line = false;
}
}
fn note(&mut self, color: &str, text: &str) {
self.end_line();
let line = self.paint(color, text);
match &self.above {
Some(above) if above.send(line.clone()).is_ok() => {}
_ => {
let _ = writeln!(self.err, "{line}");
}
}
}
pub fn event(&mut self, ev: &LoopEvent) {
if self.json {
if let Ok(line) = serde_json::to_string(ev) {
self.json_line(line);
}
return;
}
match ev {
LoopEvent::TextDelta { text } => {
let _ = write!(self.out, "{text}");
let _ = self.out.flush();
self.open_line = !text.ends_with('\n');
}
LoopEvent::ToolResult {
call,
output,
duration_ms,
..
} => {
let color = if output.is_error { RED } else { DIM };
self.note(color, &result_line(call, output.is_error, *duration_ms));
}
LoopEvent::Guard { text } => self.note(YELLOW, &format!("! {text}")),
LoopEvent::Assistant { message } => {
if let Some(err) = &message.error_message {
self.note(RED, &format!("model call failed: {err}"));
}
self.shown_error = message.error_message.clone();
}
LoopEvent::TurnEnd {
stop_reason, error, ..
} => {
self.end_line();
let shown = self.shown_error.take();
match (error, *stop_reason == StopReason::Error) {
(Some(e), true) if shown.as_ref() != Some(e) => {
self.note(RED, &format!("turn failed: {e}"));
}
(Some(e), false) => self.note(YELLOW, &format!("turn stopped: {e}")),
_ => {}
}
if *stop_reason == StopReason::Aborted {
self.note(YELLOW, "interrupted");
}
}
LoopEvent::User { .. }
| LoopEvent::ModelStart { .. }
| LoopEvent::ThinkingDelta { .. }
| LoopEvent::ToolCallStart { .. } => {}
}
}
pub fn usage(&mut self, usage: &Usage, total_usd: Option<f64>) {
if self.json {
return;
}
let mut line = format!(
"{} in / {} out tokens",
usage.input + usage.cache_read + usage.cache_write,
usage.output
);
if let Some(c) = usage.cost_usd {
line.push_str(&format!(", ${c:.4}"));
}
if let Some(t) = total_usd {
line.push_str(&format!(" (session ${t:.4})"));
}
self.note(DIM, &line);
}
pub fn notice(&mut self, level: Level, text: &str) {
if self.json {
return self
.json_line(json!({"type": "notice", "level": level.as_str(), "text": text}));
}
let color = match level {
Level::Info => DIM,
Level::Warning => YELLOW,
Level::Error => RED,
};
self.note(color, text);
}
pub fn ask(&mut self, question: &str) {
if self.json {
return self.json_line(json!({"type": "ask", "text": question}));
}
self.end_line();
let text = self.paint(YELLOW, question);
let _ = write!(self.err, "{text}");
let _ = self.err.flush();
}
fn json_line(&mut self, line: impl std::fmt::Display) {
let _ = writeln!(self.out, "{line}");
let _ = self.out.flush();
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Level {
Info,
Warning,
Error,
}
impl Level {
fn as_str(self) -> &'static str {
match self {
Level::Info => "info",
Level::Warning => "warning",
Level::Error => "error",
}
}
}
pub fn result_line(call: &ToolCall, is_error: bool, duration_ms: u64) -> String {
let mark = if is_error { "x" } else { "-" };
format!("{mark} {} ({duration_ms} ms)", call_summary(call))
}
fn call_summary(call: &ToolCall) -> String {
const KEYS: [&str; 7] = [
"path",
"file_path",
"command",
"pattern",
"url",
"query",
"description",
];
let arg = KEYS
.iter()
.find_map(|k| call.input.get(*k).and_then(Value::as_str))
.or_else(|| call.input.values().find_map(Value::as_str))
.unwrap_or("");
let arg: String = arg.lines().next().unwrap_or("").chars().take(80).collect();
if arg.is_empty() {
call.name.clone()
} else {
format!("{} {arg}", call.name)
}
}
#[cfg(test)]
pub(crate) mod tests;