agentmux_srv_core/backend/audit_activity/
line.rs1use serde_json::Value;
7
8use super::scrub;
9use crate::backend::rpc_types::AuditCost;
10
11const LINE_MAX: usize = 2 * 1024 * 1024;
13
14#[derive(Debug, Clone, PartialEq)]
16pub struct Parsed {
17 pub kind: &'static str,
18 pub summary: String,
19 pub tool: Option<String>,
20 pub outcome: Option<String>,
21 pub ms: Option<u64>,
22 pub cost: Option<AuditCost>,
23}
24
25fn row(kind: &'static str, summary: String) -> Parsed {
26 Parsed { kind, summary, tool: None, outcome: None, ms: None, cost: None }
27}
28
29pub fn parse(line: &str) -> Vec<Parsed> {
31 let maybe_call = line.contains("\"tool_use\"") || line.contains("\"thinking\"");
32 let maybe_end = line.contains("\"type\":\"result\"") || line.contains("\"type\": \"result\"");
33 if line.len() > LINE_MAX || !(maybe_call || maybe_end) {
34 return Vec::new();
35 }
36 let Ok(value) = serde_json::from_str::<Value>(line) else { return Vec::new() };
37 match value.get("type").and_then(Value::as_str) {
38 Some("assistant") => calls_in(&value),
39 Some("result") => vec![turn_end(&value)],
40 _ => Vec::new(),
41 }
42}
43
44fn calls_in(line: &Value) -> Vec<Parsed> {
45 let Some(blocks) = line.pointer("/message/content").and_then(Value::as_array) else { return Vec::new() };
46 blocks
47 .iter()
48 .filter_map(|block| match block.get("type").and_then(Value::as_str) {
49 Some("tool_use") => {
50 let name = block.get("name").and_then(Value::as_str).filter(|n| !n.is_empty())?;
51 let input = block.get("input").unwrap_or(&Value::Null);
52 Some(Parsed { tool: Some(name.to_string()), ..row("tool", scrub::summarize(name, input)) })
53 }
54 Some("thinking") | Some("redacted_thinking") => Some(row("thought", "thinking".to_string())),
56 _ => None,
57 })
58 .collect()
59}
60
61fn turn_end(line: &Value) -> Parsed {
62 let subtype = line.get("subtype").and_then(Value::as_str).unwrap_or("success");
63 let failed = line.get("is_error").and_then(Value::as_bool).unwrap_or(false) || subtype.starts_with("error");
64 let outcome = if failed { if subtype == "success" { "error" } else { subtype } } else { "success" };
65 let ms = line.get("duration_ms").and_then(Value::as_u64);
66 let secs = ms.map(|m| format!(" in {:.1} s", m as f64 / 1000.0)).unwrap_or_default();
67 let cost = crate::backend::usage_of::turn_total(line).map(|b| AuditCost {
69 input: b.uncached_input + b.cache_write(),
70 cache_read: b.cache_read,
71 output: b.output + b.reasoning,
72 cache_write: Some(b.cache_write()),
73 usd: line.get("total_cost_usd").and_then(Value::as_f64),
74 basis: "measured".to_string(),
75 });
76 Parsed { outcome: Some(outcome.to_string()), ms, cost, ..row("turn", format!("turn ended ({outcome}){secs}")) }
77}