Skip to main content

tracevault_cli/
transcript.rs

1//! Tool calls in an agent's transcript, for `tracevault check` (which counts
2//! them) and the stream hook (which keeps a fileless agent's tool calls in a
3//! local log `check` can read).
4//!
5//! The server parses the same schemas in its per-agent adapters
6//! (`tracevault-core/src/agent_adapter/` in visdom-ai-tracing). A schema change
7//! there likely needs one here too, or `check` stops seeing that agent's calls.
8
9use std::collections::HashMap;
10use std::fs;
11use std::io::{BufRead, BufReader};
12use std::path::Path;
13
14/// Names of the tools called in one transcript record, in every transcript
15/// schema a supported agent writes:
16/// - Claude Code: `type: "assistant"`, `message.content[]` blocks of `type: "tool_use"`
17/// - pi (GSD) and OpenCode: `type: "message"`, an assistant `message.content[]`
18///   with blocks of `type: "toolCall"`
19/// - Codex: `type: "response_item"` whose `payload` is a `custom_tool_call` or
20///   `function_call` (named) or a `local_shell_call` (counted as `Bash`, the
21///   name the server gives it)
22/// - Amp: `type: "amp_message"` (the envelope the bundled plugin wraps Amp's
23///   own thread messages in), an assistant `message.content[]` with blocks of
24///   `type: "tool_use"`. Names are Amp's own (`create_file`, `edit_file`,
25///   `shell_command`, `Task`, `create_thread`, ...).
26pub fn tool_call_names(entry: &serde_json::Value) -> Vec<&str> {
27    fn str_at<'a>(v: &'a serde_json::Value, key: &str) -> Option<&'a str> {
28        v.get(key).and_then(|v| v.as_str())
29    }
30    let blocks_of_type = |block_type: &'static str| {
31        entry
32            .get("message")
33            .and_then(|m| m.get("content"))
34            .and_then(|c| c.as_array())
35            .into_iter()
36            .flatten()
37            .filter(move |b| str_at(b, "type") == Some(block_type))
38            .filter_map(|b| str_at(b, "name"))
39    };
40    match str_at(entry, "type") {
41        Some("assistant") => blocks_of_type("tool_use").collect(),
42        Some("amp_message")
43            if entry.get("message").and_then(|m| str_at(m, "role")) == Some("assistant") =>
44        {
45            blocks_of_type("tool_use").collect()
46        }
47        Some("message")
48            if entry.get("message").and_then(|m| str_at(m, "role")) == Some("assistant") =>
49        {
50            blocks_of_type("toolCall").collect()
51        }
52        Some("response_item") => {
53            let Some(payload) = entry.get("payload") else {
54                return Vec::new();
55            };
56            match str_at(payload, "type") {
57                Some("custom_tool_call" | "function_call") => {
58                    str_at(payload, "name").into_iter().collect()
59                }
60                Some("local_shell_call") => vec!["Bash"],
61                _ => Vec::new(),
62            }
63        }
64        _ => Vec::new(),
65    }
66}
67
68/// Count the tool calls in the transcript at `path`, by tool name. The file is
69/// read line by line, so a long session's transcript is never held in memory
70/// whole. A missing or unreadable file counts nothing, and lines that are not
71/// JSON (including invalid UTF-8) are skipped.
72pub fn count_tool_calls(path: &Path) -> HashMap<String, i32> {
73    let mut counts = HashMap::new();
74    let Ok(file) = fs::File::open(path) else {
75        return counts;
76    };
77    for line in BufReader::new(file).split(b'\n').map_while(Result::ok) {
78        let Ok(entry) = serde_json::from_slice::<serde_json::Value>(&line) else {
79            continue;
80        };
81        for name in tool_call_names(&entry) {
82            *counts.entry(name.to_string()).or_insert(0) += 1;
83        }
84    }
85    counts
86}
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91
92    const BASH_CALL: &[u8] =
93        br#"{"type":"assistant","message":{"content":[{"type":"tool_use","name":"Bash"}]}}"#;
94
95    #[test]
96    fn count_tool_calls_skips_lines_that_are_not_json() {
97        let tmp = tempfile::tempdir().unwrap();
98        let path = tmp.path().join("t.jsonl");
99        let bytes = [BASH_CALL, b"\nnot json\n\xff\xfe\n", BASH_CALL].concat();
100        fs::write(&path, bytes).unwrap();
101        assert_eq!(
102            count_tool_calls(&path),
103            HashMap::from([("Bash".to_string(), 2)])
104        );
105    }
106
107    #[test]
108    fn count_tool_calls_of_a_missing_file_is_empty() {
109        assert!(count_tool_calls(Path::new("/nonexistent/t.jsonl")).is_empty());
110    }
111
112    #[test]
113    fn amp_tool_use_blocks_are_tool_calls() {
114        let assistant = serde_json::json!({"type":"amp_message","event":"agent.end","message":{"role":"assistant","content":[
115            {"type":"thinking","thinking":"..."},
116            {"type":"tool_use","id":"TU-1","name":"shell_command","input":{"command":"ls"}},
117            {"type":"tool_use","id":"TU-2","name":"Task","input":{}}
118        ]}});
119        assert_eq!(tool_call_names(&assistant), vec!["shell_command", "Task"]);
120        let result = serde_json::json!({"type":"amp_message","message":{"role":"user","content":[
121            {"type":"tool_result","toolUseID":"TU-1","status":"done","output":"x"}
122        ]}});
123        assert!(tool_call_names(&result).is_empty());
124    }
125
126    #[test]
127    fn tool_results_are_not_tool_calls() {
128        let result = serde_json::json!({"type":"message","message":{"role":"toolResult","toolName":"bash","content":[{"type":"toolCall","name":"bash"}]}});
129        assert!(tool_call_names(&result).is_empty());
130    }
131}