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)
22pub fn tool_call_names(entry: &serde_json::Value) -> Vec<&str> {
23    fn str_at<'a>(v: &'a serde_json::Value, key: &str) -> Option<&'a str> {
24        v.get(key).and_then(|v| v.as_str())
25    }
26    let blocks_of_type = |block_type: &'static str| {
27        entry
28            .get("message")
29            .and_then(|m| m.get("content"))
30            .and_then(|c| c.as_array())
31            .into_iter()
32            .flatten()
33            .filter(move |b| str_at(b, "type") == Some(block_type))
34            .filter_map(|b| str_at(b, "name"))
35    };
36    match str_at(entry, "type") {
37        Some("assistant") => blocks_of_type("tool_use").collect(),
38        Some("message")
39            if entry.get("message").and_then(|m| str_at(m, "role")) == Some("assistant") =>
40        {
41            blocks_of_type("toolCall").collect()
42        }
43        Some("response_item") => {
44            let Some(payload) = entry.get("payload") else {
45                return Vec::new();
46            };
47            match str_at(payload, "type") {
48                Some("custom_tool_call" | "function_call") => {
49                    str_at(payload, "name").into_iter().collect()
50                }
51                Some("local_shell_call") => vec!["Bash"],
52                _ => Vec::new(),
53            }
54        }
55        _ => Vec::new(),
56    }
57}
58
59/// Count the tool calls in the transcript at `path`, by tool name. The file is
60/// read line by line, so a long session's transcript is never held in memory
61/// whole. A missing or unreadable file counts nothing, and lines that are not
62/// JSON (including invalid UTF-8) are skipped.
63pub fn count_tool_calls(path: &Path) -> HashMap<String, i32> {
64    let mut counts = HashMap::new();
65    let Ok(file) = fs::File::open(path) else {
66        return counts;
67    };
68    for line in BufReader::new(file).split(b'\n').map_while(Result::ok) {
69        let Ok(entry) = serde_json::from_slice::<serde_json::Value>(&line) else {
70            continue;
71        };
72        for name in tool_call_names(&entry) {
73            *counts.entry(name.to_string()).or_insert(0) += 1;
74        }
75    }
76    counts
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82
83    const BASH_CALL: &[u8] =
84        br#"{"type":"assistant","message":{"content":[{"type":"tool_use","name":"Bash"}]}}"#;
85
86    #[test]
87    fn count_tool_calls_skips_lines_that_are_not_json() {
88        let tmp = tempfile::tempdir().unwrap();
89        let path = tmp.path().join("t.jsonl");
90        let bytes = [BASH_CALL, b"\nnot json\n\xff\xfe\n", BASH_CALL].concat();
91        fs::write(&path, bytes).unwrap();
92        assert_eq!(
93            count_tool_calls(&path),
94            HashMap::from([("Bash".to_string(), 2)])
95        );
96    }
97
98    #[test]
99    fn count_tool_calls_of_a_missing_file_is_empty() {
100        assert!(count_tool_calls(Path::new("/nonexistent/t.jsonl")).is_empty());
101    }
102
103    #[test]
104    fn tool_results_are_not_tool_calls() {
105        let result = serde_json::json!({"type":"message","message":{"role":"toolResult","toolName":"bash","content":[{"type":"toolCall","name":"bash"}]}});
106        assert!(tool_call_names(&result).is_empty());
107    }
108}