| 1 | use serde_json::Value; |
| 2 | |
| 3 | use super::{RunEvent, truncate}; |
| 4 | |
| 5 | const DETAIL_LIMIT: usize = 60; |
| 6 | |
| 7 | pub(super) fn parse_line(line: &str, last_text: &mut Option<String>) -> Vec<RunEvent> { |
| 8 | let Ok(value) = serde_json::from_str::<Value>(line) else { |
| 9 | return Vec::new(); |
| 10 | }; |
| 11 | match value.get("type").and_then(Value::as_str) { |
| 12 | Some("tool.execution_start") => vec![RunEvent::Step(step_label(&value))], |
| 13 | Some("assistant.message") => assistant_events(&value, last_text), |
| 14 | Some("result") => result_events(&value, last_text), |
| 15 | _ => Vec::new(), |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | fn assistant_events(value: &Value, last_text: &mut Option<String>) -> Vec<RunEvent> { |
| 20 | let content = value |
| 21 | .pointer("/data/content") |
| 22 | .and_then(Value::as_str) |
| 23 | .unwrap_or(""); |
| 24 | if content.trim().is_empty() { |
| 25 | return Vec::new(); |
| 26 | } |
| 27 | *last_text = Some(content.to_string()); |
| 28 | vec![RunEvent::Text(content.to_string())] |
| 29 | } |
| 30 | |
| 31 | fn result_events(value: &Value, last_text: &Option<String>) -> Vec<RunEvent> { |
| 32 | let mut events = Vec::new(); |
| 33 | if let Some(session_id) = value.get("sessionId").and_then(Value::as_str) { |
| 34 | events.push(RunEvent::SessionId(session_id.to_string())); |
| 35 | } |
| 36 | let exit_code = value.get("exitCode").and_then(Value::as_i64).unwrap_or(0); |
| 37 | match last_text { |
| 38 | Some(text) if exit_code == 0 => events.push(RunEvent::Final(text.clone())), |
| 39 | _ if exit_code != 0 => events.push(RunEvent::Failed(format!( |
| 40 | "agent exited with code {exit_code}" |
| 41 | ))), |
| 42 | _ => events.push(RunEvent::Failed("agent returned no answer".to_string())), |
| 43 | } |
| 44 | events |
| 45 | } |
| 46 | |
| 47 | fn step_label(value: &Value) -> String { |
| 48 | let title = value |
| 49 | .pointer("/data/toolTitle") |
| 50 | .and_then(Value::as_str) |
| 51 | .or_else(|| value.pointer("/data/toolName").and_then(Value::as_str)) |
| 52 | .unwrap_or("Tool"); |
| 53 | match tool_detail(value.pointer("/data/arguments")) { |
| 54 | Some(detail) => format!("{title}: {}", truncate(&detail, DETAIL_LIMIT)), |
| 55 | None => title.to_string(), |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | fn tool_detail(arguments: Option<&Value>) -> Option<String> { |
| 60 | let arguments = arguments?.as_object()?; |
| 61 | ["path", "command"] |
| 62 | .iter() |
| 63 | .find_map(|key| arguments.get(*key).and_then(Value::as_str)) |
| 64 | .or_else(|| arguments.values().find_map(Value::as_str)) |
| 65 | .map(str::to_string) |
| 66 | } |