Skip to main content

agentmux_srv_core/backend/audit_activity/
line.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Reading one stream-json transcript line for the rows it holds: a tool call, a thinking block or a turn's end.
5
6use serde_json::Value;
7
8use super::scrub;
9use crate::backend::rpc_types::AuditCost;
10
11/// A line longer than this is not read: it is a big tool result, and holds no row.
12const LINE_MAX: usize = 2 * 1024 * 1024;
13
14/// What one line of the transcript says happened.
15#[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
29/// The rows in `line`, none for most lines. A cheap test first: nearly every line is a message or a tool result.
30pub 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            // A marker only: the thought's text is never kept.
55            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    // The turn's sum, read as the ledger reads a call; a shape it does not know is no cost, not a zero one.
68    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}