Skip to main content

phi_agent/render/
mod.rs

1pub mod json_stream;
2pub mod null;
3pub mod terminal;
4
5pub use json_stream::JsonStreamRenderer;
6pub use null::NullRenderer;
7pub use terminal::TerminalRenderer;
8
9use std::io::{self, Write};
10
11use agent_base::{AgentResult, RuntimeEvent};
12
13/// Event renderer: converts RuntimeEvents into a specific output format.
14///
15/// Each renderer is a pure consumer — it only reads events and produces
16/// output, without modifying Agent state.
17pub trait EventRenderer: Send {
18    /// Process one runtime event.
19    fn render(&mut self, event: RuntimeEvent) -> AgentResult<()>;
20
21    /// End of current turn — renderer may flush / output summary.
22    fn finish_turn(&mut self) -> AgentResult<()>;
23
24    /// End of entire session.
25    fn finish_session(&mut self) -> AgentResult<()> {
26        Ok(())
27    }
28}
29
30/// Output format
31#[derive(Clone, Debug)]
32pub enum OutputFormat {
33    /// Rich terminal output (with colors and emoji)
34    Terminal { show_thinking: bool, show_tool_args: bool, color: bool },
35    /// One JSON object per line
36    Json,
37    /// No output
38    Quiet,
39}
40
41/// Create the corresponding renderer for a given output format.
42///
43/// `writer` defaults to stdout (CLI scenario). Web consumers can pass a
44/// custom writer (e.g. a WebSocket sink).
45pub fn create_renderer(format: &OutputFormat, writer: Option<Box<dyn Write + Send>>) -> Box<dyn EventRenderer> {
46    match format {
47        OutputFormat::Terminal { show_thinking, show_tool_args, color } => {
48            let w = writer.unwrap_or_else(|| Box::new(io::stdout()));
49            Box::new(TerminalRenderer::new(*show_thinking, *show_tool_args, *color, w))
50        },
51        OutputFormat::Json => {
52            let w = writer.unwrap_or_else(|| Box::new(io::stdout()));
53            Box::new(JsonStreamRenderer::new(w))
54        },
55        OutputFormat::Quiet => Box::new(NullRenderer),
56    }
57}
58
59/// Create a renderer using stdout (backward-compatible).
60pub fn create_stdout_renderer(format: &OutputFormat) -> Box<dyn EventRenderer> {
61    create_renderer(format, None)
62}