1use std::io::{self, Write};
2
3use serde::Serialize;
4use serde_json::Value;
5
6#[derive(Debug, Serialize, Clone, PartialEq, Eq)]
7#[serde(tag = "type")]
8pub enum ProtocolEvent {
9 #[serde(rename = "session")]
10 Session { session_id: String, resumed: bool },
11 #[serde(rename = "assistant_delta")]
12 AssistantDelta { text: String },
13 #[serde(rename = "tool_call")]
14 ToolCall {
15 id: String,
16 name: String,
17 arguments: String,
18 },
19 #[serde(rename = "tool_result")]
20 ToolResult {
21 id: String,
22 name: String,
23 result: Value,
24 },
25 #[serde(rename = "turn_end")]
26 TurnEnd,
27 #[serde(rename = "turn_interrupted")]
28 TurnInterrupted { reason: String, phase: String },
29 #[serde(rename = "error")]
30 Error { message: String },
31}
32
33pub trait EventSink {
35 fn emit_event(&mut self, event: &ProtocolEvent) -> io::Result<()>;
36
37 fn reasoning_started(&mut self) -> io::Result<()> {
40 Ok(())
41 }
42
43 fn skill_instruction_attached(&mut self, _name: &str) -> io::Result<()> {
47 Ok(())
48 }
49
50 fn context_usage(&mut self, _tokens: usize) -> io::Result<()> {
53 Ok(())
54 }
55
56 fn compaction_started(&mut self) -> io::Result<()> {
59 Ok(())
60 }
61
62 fn compaction_finished(
65 &mut self,
66 _tokens_before: usize,
67 _tokens_after: usize,
68 ) -> io::Result<()> {
69 Ok(())
70 }
71}
72
73pub struct ProtocolWriter<W> {
74 writer: W,
75}
76
77impl<W: Write> ProtocolWriter<W> {
78 pub fn new(writer: W) -> Self {
79 Self { writer }
80 }
81
82 pub fn emit(&mut self, event: &ProtocolEvent) -> io::Result<()> {
83 self.emit_serializable(event)
84 }
85
86 pub fn emit_serializable<T: Serialize>(&mut self, record: &T) -> io::Result<()> {
87 serde_json::to_writer(&mut self.writer, record)
88 .map_err(|error| io::Error::other(format!("encode protocol event: {error}")))?;
89 self.writer.write_all(b"\n")?;
90 self.writer.flush()
91 }
92
93 pub fn session(&mut self, session_id: &str, resumed: bool) -> io::Result<()> {
94 self.emit(&ProtocolEvent::Session {
95 session_id: session_id.to_owned(),
96 resumed,
97 })
98 }
99
100 pub fn assistant_delta(&mut self, text: &str) -> io::Result<()> {
101 if text.is_empty() {
102 return Ok(());
103 }
104 self.emit(&ProtocolEvent::AssistantDelta {
105 text: text.to_owned(),
106 })
107 }
108
109 pub fn tool_call(&mut self, id: &str, name: &str, arguments: &str) -> io::Result<()> {
110 self.emit(&ProtocolEvent::ToolCall {
111 id: id.to_owned(),
112 name: name.to_owned(),
113 arguments: arguments.to_owned(),
114 })
115 }
116
117 pub fn tool_result(&mut self, id: &str, name: &str, result: Value) -> io::Result<()> {
118 self.emit(&ProtocolEvent::ToolResult {
119 id: id.to_owned(),
120 name: name.to_owned(),
121 result,
122 })
123 }
124
125 pub fn turn_end(&mut self) -> io::Result<()> {
126 self.emit(&ProtocolEvent::TurnEnd)
127 }
128
129 pub fn turn_interrupted(&mut self, reason: &str, phase: &str) -> io::Result<()> {
130 self.emit(&ProtocolEvent::TurnInterrupted {
131 reason: reason.to_owned(),
132 phase: phase.to_owned(),
133 })
134 }
135
136 pub fn error(&mut self, message: &str) -> io::Result<()> {
137 self.emit(&ProtocolEvent::Error {
138 message: message.to_owned(),
139 })
140 }
141}
142
143impl<W: Write> EventSink for ProtocolWriter<W> {
144 fn emit_event(&mut self, event: &ProtocolEvent) -> io::Result<()> {
145 self.emit(event)
146 }
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152
153 #[test]
154 fn protocol_writer_emits_only_single_line_json_records() {
155 let mut output = Vec::new();
156 {
157 let mut writer = ProtocolWriter::new(&mut output);
158 writer.assistant_delta("line one\nline two").expect("event");
159 writer
160 .tool_result(
161 "call-1",
162 "cmd",
163 serde_json::json!({"stdout":"provider-shape-is-not-forwarded"}),
164 )
165 .expect("result");
166 }
167 let text = String::from_utf8(output).expect("UTF-8");
168 assert_eq!(text.lines().count(), 2);
169 for line in text.lines() {
170 serde_json::from_str::<Value>(line).expect("JSONL record");
171 }
172 assert!(!text.contains("choices"));
173 }
174
175 #[test]
176 fn compaction_frontend_state_is_not_emitted_to_jsonl() {
177 let mut output = Vec::new();
178 let mut writer = ProtocolWriter::new(&mut output);
179 writer.context_usage(100).expect("context usage");
180 writer.compaction_started().expect("compaction start");
181 writer
182 .compaction_finished(100, 20)
183 .expect("compaction finish");
184
185 assert!(output.is_empty());
186 }
187
188 #[test]
189 fn skill_attachment_state_is_not_emitted_to_jsonl() {
190 let mut output = Vec::new();
191 let mut writer = ProtocolWriter::new(&mut output);
192 writer
193 .skill_instruction_attached("release-notes")
194 .expect("non-public TUI state");
195 assert!(output.is_empty());
196 }
197
198 #[test]
199 fn interruption_event_is_a_normalized_json_record() {
200 let event = ProtocolEvent::TurnInterrupted {
201 reason: "user_cancelled".to_owned(),
202 phase: "provider_stream".to_owned(),
203 };
204 let value = serde_json::to_value(event).expect("event JSON");
205 assert_eq!(value["type"], "turn_interrupted");
206 assert_eq!(value["reason"], "user_cancelled");
207 assert_eq!(value["phase"], "provider_stream");
208 assert!(!serde_json::to_string(&value)
209 .expect("serialized event")
210 .contains("choices"));
211 }
212}