Skip to main content

subspace_client_github/copilot_agent_sessions/
log.rs

1//! The `data:` lines of a Copilot session log, parsed into entries.
2//!
3//! The stream is undocumented, so every line is read defensively: a line
4//! that does not parse, or that carries a shape this module does not know,
5//! is skipped rather than failing the log.
6//!
7//! Each line is a whole message, not a piece of one. A chunk that carries
8//! tool calls and no text is the agent asking for those calls; the same
9//! chunk shape with text is that call's answer, which also arrives as a
10//! `{"role": "tool"}` line. Both the repeated call and the repeated answer
11//! are dropped, so one call and one answer make one row each.
12
13use std::collections::HashSet;
14use std::hash::{DefaultHasher, Hash as _, Hasher as _};
15
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18
19/// One entry of a parsed session log, in the order the log holds them.
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
21pub enum LogEntry {
22    /// What the agent said, as Markdown.
23    Assistant { created: Option<i64>, text: String },
24    /// A tool the agent called, with the arguments it sent. `id` is the
25    /// call id the stream gives.
26    ToolCall {
27        created: Option<i64>,
28        id: String,
29        name: String,
30        arguments: String,
31    },
32    /// A message from the user or from the harness.
33    User { text: String },
34    /// What a tool answered. `name` is empty when the answer arrives
35    /// before, or without, the call it belongs to.
36    ToolResult { name: String, text: String },
37}
38
39/// A parsed session log.
40#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
41pub struct SessionLog {
42    pub entries: Vec<LogEntry>,
43    /// The read stopped at the byte cap, so the log is the start only.
44    pub truncated: bool,
45}
46
47/// What one `data:` line may hold. Every field is optional: the known
48/// shapes share one document type, so an unknown mix still reads.
49#[derive(Debug, Default, Deserialize)]
50struct RawLine {
51    #[serde(default)]
52    created: Option<i64>,
53    #[serde(default)]
54    choices: Vec<RawChoice>,
55    #[serde(default)]
56    role: Option<String>,
57    #[serde(default)]
58    content: Option<Value>,
59}
60
61#[derive(Debug, Default, Deserialize)]
62struct RawChoice {
63    #[serde(default)]
64    delta: RawDelta,
65}
66
67#[derive(Debug, Default, Deserialize)]
68struct RawDelta {
69    #[serde(default)]
70    content: Option<Value>,
71    #[serde(default)]
72    tool_calls: Vec<RawToolCall>,
73}
74
75#[derive(Debug, Deserialize)]
76struct RawToolCall {
77    #[serde(default)]
78    id: String,
79    #[serde(default)]
80    function: Option<RawFunction>,
81}
82
83#[derive(Debug, Deserialize)]
84struct RawFunction {
85    #[serde(default)]
86    name: String,
87    #[serde(default)]
88    arguments: String,
89}
90
91/// The `data:` payloads of an event stream. A truncated read loses its last
92/// line, which is the one the cap cut in half.
93fn data_lines(text: &str, truncated: bool) -> Vec<&str> {
94    let mut lines: Vec<&str> = text
95        .lines()
96        .filter_map(|line| line.strip_prefix("data:"))
97        .map(str::trim)
98        .filter(|line| !line.is_empty() && *line != "[DONE]")
99        .collect();
100    if truncated {
101        lines.pop();
102    }
103    lines
104}
105
106/// Message content, which is either a plain string or a list of parts.
107fn content_text(value: Option<&Value>) -> String {
108    match value {
109        Some(Value::String(text)) => text.clone(),
110        Some(Value::Array(parts)) => parts
111            .iter()
112            .filter_map(|part| part.get("text").and_then(Value::as_str))
113            .collect::<Vec<&str>>()
114            .join(""),
115        _ => String::new(),
116    }
117}
118
119fn digest(text: &str) -> u64 {
120    let mut hasher = DefaultHasher::new();
121    text.hash(&mut hasher);
122    hasher.finish()
123}
124
125/// The call's name and arguments, which the stream repeats in full.
126fn function_of(call: &RawToolCall) -> (&str, &str) {
127    match call.function.as_ref() {
128        Some(function) => (function.name.as_str(), function.arguments.as_str()),
129        None => ("", ""),
130    }
131}
132
133/// The log as it is read: the entries so far, the calls already asked for,
134/// and the answers already shown.
135#[derive(Default)]
136struct Reading {
137    entries: Vec<LogEntry>,
138    calls: Vec<(String, String)>,
139    answered: HashSet<u64>,
140}
141
142impl Reading {
143    /// The name of the call `id` asked for, when that call was seen.
144    fn name_of(&self, id: &str) -> String {
145        self.calls
146            .iter()
147            .find(|(known, _)| known == id)
148            .map(|(_, name)| name.clone())
149            .unwrap_or_default()
150    }
151
152    /// A call the agent asked for. A repeat of a call already asked for is
153    /// dropped: the stream sends each one again with its answer.
154    fn call(&mut self, created: Option<i64>, call: &RawToolCall) {
155        let (name, arguments) = function_of(call);
156        if name.is_empty() || self.calls.iter().any(|(known, _)| known == &call.id) {
157            return;
158        }
159        self.calls.push((call.id.clone(), name.to_owned()));
160        self.entries.push(LogEntry::ToolCall {
161            created,
162            id: call.id.clone(),
163            name: name.to_owned(),
164            arguments: arguments.to_owned(),
165        });
166    }
167
168    /// An answer, from a result chunk or from a `role: tool` line. The same
169    /// text is shown once.
170    fn answer(&mut self, name: String, text: String) {
171        if text.is_empty() || !self.answered.insert(digest(&text)) {
172            return;
173        }
174        self.entries.push(LogEntry::ToolResult { name, text });
175    }
176
177    fn said(&mut self, created: Option<i64>, text: String) {
178        if !text.is_empty() {
179            self.entries.push(LogEntry::Assistant { created, text });
180        }
181    }
182
183    /// One `chat.completion.chunk`: tool calls with no text are what the
184    /// agent asked for, tool calls with text are an answer, and text on its
185    /// own is what the agent said.
186    fn chunk(&mut self, line: &RawLine) {
187        for choice in &line.choices {
188            let text = content_text(choice.delta.content.as_ref());
189            let calls = &choice.delta.tool_calls;
190            match (calls.first(), text.is_empty()) {
191                (Some(first), false) => self.answer(self.name_of(&first.id), text),
192                (Some(_), true) => {
193                    for call in calls {
194                        self.call(line.created, call);
195                    }
196                }
197                (None, _) => self.said(line.created, text),
198            }
199        }
200    }
201
202    /// Adds what one line holds, or nothing when it does not parse.
203    fn line(&mut self, payload: &str) {
204        let Ok(line) = serde_json::from_str::<RawLine>(payload) else {
205            return;
206        };
207        let text = content_text(line.content.as_ref());
208        match line.role.as_deref() {
209            Some("user") if !text.is_empty() => self.entries.push(LogEntry::User { text }),
210            Some("user") => {}
211            Some("tool") => self.answer(String::new(), text),
212            _ => self.chunk(&line),
213        }
214    }
215}
216
217/// The parsed log of an event stream. `truncated` says the read hit its cap.
218pub fn parse_log(text: &str, truncated: bool) -> SessionLog {
219    let mut reading = Reading::default();
220    for payload in data_lines(text, truncated) {
221        reading.line(payload);
222    }
223    SessionLog {
224        entries: reading.entries,
225        truncated,
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use super::{LogEntry, SessionLog, parse_log};
232
233    const FIXTURE: &str = include_str!("../../tests/fixtures/session-log.txt");
234
235    fn names(log: &SessionLog) -> Vec<&str> {
236        log.entries
237            .iter()
238            .map(|entry| match entry {
239                LogEntry::Assistant { .. } => "assistant",
240                LogEntry::ToolCall { .. } => "tool-call",
241                LogEntry::User { .. } => "user",
242                LogEntry::ToolResult { .. } => "tool-result",
243            })
244            .collect()
245    }
246
247    #[test]
248    fn the_known_shapes_become_entries_in_order() {
249        let log = parse_log(FIXTURE, false);
250        assert!(!log.truncated);
251        assert_eq!(
252            names(&log),
253            ["user", "assistant", "tool-call", "tool-result", "assistant"]
254        );
255        assert_eq!(
256            log.entries[0],
257            LogEntry::User {
258                text: "fix the login button".into()
259            }
260        );
261        assert_eq!(
262            log.entries[1],
263            LogEntry::Assistant {
264                created: Some(1_790_000_000),
265                text: "Looking at the login button.".into()
266            }
267        );
268    }
269
270    #[test]
271    fn a_call_the_stream_repeats_with_its_answer_is_one_row() {
272        let log = parse_log(FIXTURE, false);
273        assert_eq!(
274            log.entries[2],
275            LogEntry::ToolCall {
276                created: Some(1_790_000_002),
277                id: "call_1".into(),
278                name: "bash".into(),
279                arguments: r#"{"command":"ls"}"#.into()
280            }
281        );
282        assert_eq!(
283            log.entries[3],
284            LogEntry::ToolResult {
285                name: "bash".into(),
286                text: "README.md\nsrc\n".into()
287            },
288            "the answer chunk and the role:tool line are the same answer"
289        );
290    }
291
292    #[test]
293    fn text_parts_are_joined_and_a_second_answer_is_still_shown() {
294        let log = parse_log(FIXTURE, false);
295        assert_eq!(
296            log.entries[4],
297            LogEntry::Assistant {
298                created: Some(1_790_000_004),
299                text: "Done: the first part and the second part.".into()
300            }
301        );
302    }
303
304    #[test]
305    fn an_answer_without_its_call_is_shown_without_a_tool_name() {
306        let text = "data: {\"role\":\"tool\",\"tool_call_id\":\"call_9\",\"content\":\"done\"}\n";
307        assert_eq!(
308            parse_log(text, false).entries,
309            vec![LogEntry::ToolResult {
310                name: String::new(),
311                text: "done".into()
312            }]
313        );
314    }
315
316    #[test]
317    fn unknown_broken_and_empty_lines_are_skipped() {
318        let text = concat!(
319            "event: ping\n",
320            "data: not json\n",
321            "data: {\"object\":\"something.new\",\"what\":1}\n",
322            "data: [DONE]\n",
323            "\n",
324            "data: {\"role\":\"system\",\"content\":\"\"}\n",
325        );
326        assert!(parse_log(text, false).entries.is_empty());
327    }
328
329    #[test]
330    fn a_truncated_read_drops_its_half_line_and_says_so() {
331        let text = concat!(
332            "data: {\"role\":\"user\",\"content\":\"hello\"}\n",
333            "data: {\"role\":\"user\",\"conte",
334        );
335        let log = parse_log(text, true);
336        assert!(log.truncated);
337        assert_eq!(names(&log), ["user"]);
338        assert_eq!(parse_log(text, false).entries.len(), 1, "half line skipped");
339    }
340}