//! Token report for a session file: API usage per request, cache hit rate, and which tool //! results are the most expensive to carry (bytes x requests they were resent in). use crate::session::Session; use hx_ai::{ContentBlock, Role}; use std::collections::HashMap; use std::fmt::Write; /// How `task` was used in the parent session: calls per assistant turn (1 = parent waits on a /// lone child), kinds, and bytes of answers carried back. Empty when `task` was never called. pub fn task_report(s: &Session) -> String { let (mut single, mut batch, mut calls, mut explore, mut bytes) = (0, 0, 0, 0, 0); let mut ids = std::collections::HashSet::new(); for m in s.messages() { let mut n = 0; for b in &m.content { match b { ContentBlock::ToolUse { id, name, input } if name == "task" => { n += 1; ids.insert(id.clone()); if input["kind"].as_str().unwrap_or("explore") == "explore" { explore += 1; } } ContentBlock::ToolResult { tool_use_id, content, .. } if ids.contains(tool_use_id) => bytes += content.len(), _ => {} } } calls += n; match n { 0 => {} 1 => single += 1, _ => batch += 1, } } if calls == 0 { return String::new(); } format!( "task calls: {calls} ({explore} explore, {} general); turns with one task {single}, with several {batch}; answers {bytes} bytes\n", calls - explore ) } /// Append one `claude_cli` tool run to `.claude` (claude runs the tools itself, so they /// are not session messages). Best effort. pub fn log_claude_tool( session: &std::path::Path, name: &str, args: usize, result: usize, err: bool, ) { use std::io::Write; if let Ok(mut f) = std::fs::OpenOptions::new() .create(true) .append(true) .open(session.with_extension("claude")) { let _ = writeln!( f, "{}", serde_json::json!({"name": name, "args": args, "result": result, "error": err}) ); } } /// Tools claude ran itself (`.claude`): calls, errors/blocks, argument and result bytes per tool. pub fn claude_report(session: &std::path::Path) -> String { let Ok(t) = std::fs::read_to_string(session.with_extension("claude")) else { return String::new(); }; let mut by: std::collections::BTreeMap = Default::default(); for v in t .lines() .filter_map(|l| serde_json::from_str::(l).ok()) { let e = by .entry(v["name"].as_str().unwrap_or("?").into()) .or_default(); e[0] += 1; e[1] += u64::from(v["error"] == true); e[2] += v["args"].as_u64().unwrap_or(0); e[3] += v["result"].as_u64().unwrap_or(0); } let mut s = String::from("claude tool calls (run by claude, not in the message history):\n"); for (n, [c, e, a, r]) in by { let _ = writeln!( s, " {n}: {c} calls, {e} errors/blocked, args {a} B, results {r} B" ); } s } /// One line per subagent log in `.sub/` (empty when there are none). /// Auto-mode choices from `.route`: turns per tier, how often the tier was held back /// or forced, and how often the next prompt had to go up again (a pick that was too low). pub fn route_report(session_path: &std::path::Path) -> String { let Ok(t) = std::fs::read_to_string(session_path.with_extension("route")) else { return String::new(); }; let rows: Vec = t .lines() .filter_map(|l| serde_json::from_str(l).ok()) .collect(); if rows.is_empty() { return String::new(); } let rank = |s: &str| { ["fast", "balanced", "deep", "max"] .iter() .position(|x| *x == s) }; let s = |r: &serde_json::Value, k: &str| r[k].as_str().unwrap_or("?").to_string(); let (mut per, mut held, mut forced, mut up) = (HashMap::::new(), 0, 0, 0); for (i, r) in rows.iter().enumerate() { if r["forced"].as_bool() == Some(true) { forced += 1; continue; } let e = per.entry(s(r, "tier")).or_default(); e.0 += 1; e.1 += r["score"].as_i64().unwrap_or(0); held += (s(r, "tier") != s(r, "wanted")) as u32; if let Some(n) = rows.get(i + 1) && n["forced"].as_bool() != Some(true) && rank(&s(n, "tier")) > rank(&s(r, "tier")) { up += 1; } } let mut o = String::from("auto routing:\n"); for t in ["fast", "balanced", "deep", "max"] { if let Some((n, sum)) = per.get(t) { let _ = writeln!( o, " {t}: {n} prompts, mean score {:.1}", *sum as f64 / *n as f64 ); } } let _ = writeln!( o, " held back by hysteresis: {held}, next prompt went up a tier: {up}, forced with @: {forced}" ); o } pub fn sub_report(session_path: &std::path::Path) -> String { let mut files: Vec<_> = std::fs::read_dir(session_path.with_extension("sub")) .into_iter() .flatten() .flatten() .map(|e| e.path()) .filter(|p| p.extension().is_some_and(|x| x == "jsonl")) .collect(); files.sort(); let mut o = String::new(); let mut tot = 0; for p in &files { let Ok(s) = Session::open(p) else { continue }; let (mut n, mut inp, mut out) = (0, 0, 0); for (_, u) in s.usages() { n += 1; inp += u.input_tokens + u.cache_read_tokens + u.cache_write_tokens; out += u.output_tokens; } tot += inp + out; let _ = writeln!( o, " {} requests {n} input {inp} output {out}", p.file_stem().unwrap_or_default().to_string_lossy() ); } if files.is_empty() { return o; } format!( "subagents ({} runs, {tot} tokens, not in the numbers above):\n{o}", files.len() ) } /// Numbers behind the `/stats` dashboard. #[derive(Debug, Default, PartialEq)] pub struct Summary { pub fresh: u64, pub cache_read: u64, pub cache_write: u64, pub output: u64, /// per request: (total input, output, cache hit %) pub reqs: Vec<(u64, u64, u64)>, } pub fn summary(s: &Session) -> Summary { let mut o = Summary::default(); for (_, u) in s.usages() { o.fresh += u.input_tokens; o.cache_read += u.cache_read_tokens; o.cache_write += u.cache_write_tokens; o.output += u.output_tokens; let tot = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens; o.reqs .push((tot, u.output_tokens, 100 * u.cache_read_tokens / tot.max(1))); } o } /// Requests, tokens and cache use per model, plus what model switches cost: the request right /// after a switch (auto mode, `/model`, `@opus`) re-reads the history uncached. Empty with one model. pub fn model_report(s: &Session) -> String { let mut per: Vec<(String, [u64; 5])> = vec![]; let (mut switches, mut lost, mut prev) = (0u64, 0u64, None::<&str>); for (m, u) in s.model_usages() { let m = m.unwrap_or("?"); let i = per.iter().position(|(n, _)| n == m).unwrap_or_else(|| { per.push((m.to_string(), [0; 5])); per.len() - 1 }); let a = &mut per[i].1; a[0] += 1; a[1] += u.input_tokens + u.cache_read_tokens + u.cache_write_tokens; a[2] += u.cache_read_tokens; a[3] += u.cache_write_tokens; a[4] += u.output_tokens; if prev.is_some_and(|p| p != m) { switches += 1; lost += u.cache_write_tokens; } prev = Some(m); } if per.len() < 2 { return String::new(); } let mut o = String::from("models:\n"); for (m, [n, inp, cr, cw, out]) in &per { let _ = writeln!( o, " {m}: {n} requests, input {inp} (cache read {cr}, write {cw}), output {out}" ); } let _ = writeln!( o, " model switches: {switches}, cache written on the first request after a switch: {lost} tok" ); o } pub fn report(s: &Session) -> String { let msgs = s.messages(); let mut o = String::new(); // per-request usage (all entries, so compaction roots are included) let (mut n, mut inp, mut cr, mut cw, mut out) = (0u64, 0u64, 0u64, 0u64, 0u64); let mut last_in = 0; for (_, u) in s.usages() { n += 1; inp += u.input_tokens; cr += u.cache_read_tokens; cw += u.cache_write_tokens; out += u.output_tokens; last_in = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens; } if n == 0 { return "no usage recorded (session predates usage logging)\n".into(); } let total_in = inp + cr + cw; let _ = writeln!( o, "requests {n} input {total_in} (fresh {inp}, cache read {cr}, cache write {cw}) output {out}" ); let _ = writeln!( o, "cache hit {:.0}% of input avg input/request {} last request {last_in}", 100.0 * cr as f64 / total_in.max(1) as f64, total_in / n ); // Requests that wrote a lot of cache: a regular spacing (every 8th turn) points at masking steps, // irregular ones at cache expiry (idle > 5 min) or other prefix changes. let writes: Vec<(usize, u64, u64)> = s .usages() .iter() .enumerate() .map(|(k, (_, u))| (k + 1, u.cache_write_tokens, u.cache_read_tokens)) .collect(); let avg_w = cw / n; let mut big_w: Vec<_> = writes.iter().filter(|w| w.1 > 2 * avg_w.max(1)).collect(); big_w.sort_by_key(|w| std::cmp::Reverse(w.1)); let _ = writeln!( o, "requests writing > 2x the average cache write ({avg_w}): {} of {n}", big_w.len() ); for (k, w, r) in big_w.iter().take(10) { let _ = writeln!(o, " request {k}: write {w}, read {r}"); } // assistant side: bytes the model produced that are resent every request let (mut text_b, mut call_b) = (0usize, 0usize); for m in msgs.iter().filter(|m| m.role == Role::Assistant) { for b in &m.content { match b { ContentBlock::Text { text } => text_b += text.len(), ContentBlock::ToolUse { input, .. } => call_b += input.to_string().len(), _ => {} } } } let _ = writeln!( o, "assistant output kept in history: text {} tok, tool-call arguments {} tok (once)", text_b / 4, call_b / 4 ); // bash calls that ask for approval, by first word: shows which habits break the read-only flow let mut asks: HashMap = HashMap::new(); for m in msgs.iter().filter(|m| m.role == Role::Assistant) { for b in &m.content { if let ContentBlock::ToolUse { name, input, .. } = b && name == "bash" && crate::permit::needs_permit(name, input) { { let c = input["command"].as_str().unwrap_or_default(); *asks .entry(c.split_whitespace().next().unwrap_or("").into()) .or_default() += 1; } } } } if !asks.is_empty() { let mut v: Vec<_> = asks.into_iter().collect(); v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); let list: Vec = v.iter().take(8).map(|(c, n)| format!("{c} {n}")).collect(); let _ = writeln!( o, "approval prompts from bash, by command: {}", list.join(", ") ); } // carried cost of tool results on the current path let mut names: HashMap<&str, &str> = HashMap::new(); for m in &msgs { for b in &m.content { if let ContentBlock::ToolUse { id, name, .. } = b { names.insert(id, name); } } } // Replay the requests: request k sent the messages before the k-th assistant message, masked // the way the agent masks them. sent[i] = bytes of item i summed over the requests carrying it; // raw[i] = same without masking. let len_of = |b: &ContentBlock| match b { ContentBlock::ToolResult { content, .. } => content.len(), _ => 0, }; let masks = s.masks(); let mut sent = vec![0usize; msgs.len()]; let mut raw = vec![0usize; msgs.len()]; for (end, _) in msgs .iter() .enumerate() .filter(|(_, m)| m.role == Role::Assistant) { // boundary the agent recorded for this request; older files used the stepwise rule let masked = crate::window::ContextWindow::masked(&msgs[..end], masks[end]); for (i, m) in masked.iter().enumerate() { let text_len = |m: &hx_ai::Message| { m.content .iter() .map(|b| match b { ContentBlock::Text { text } if m.role == Role::User && i > 0 => text.len(), other => len_of(other), }) .sum::() }; sent[i] += text_len(m); raw[i] += text_len(&msgs[i]); } } // name -> (calls, bytes once, bytes resent as sent, bytes resent unmasked) let mut by: HashMap = HashMap::new(); let mut big: Vec<(usize, usize, String)> = vec![]; for (i, m) in msgs.iter().enumerate() { for b in &m.content { let (name, len) = match b { ContentBlock::ToolResult { tool_use_id, content, .. } => ( names.get(tool_use_id.as_str()).copied().unwrap_or("?"), content.len(), ), ContentBlock::Text { text } if m.role == Role::User && i > 0 => { ("(injected text)", text.len()) } _ => continue, }; let e = by.entry(name.to_string()).or_default(); e.0 += 1; e.1 += len; // a message may hold several results; attribute its total proportionally let share = |tot: usize| { let once = m .content .iter() .map(|b| match b { ContentBlock::Text { text } if m.role == Role::User && i > 0 => text.len(), other => len_of(other), }) .sum::() .max(1); tot * len / once }; e.2 += share(sent[i]); e.3 += share(raw[i]); big.push((share(sent[i]), len, format!("msg {i} {name}"))); } } let mut rows: Vec<_> = by.into_iter().collect(); rows.sort_by_key(|(_, v)| std::cmp::Reverse(v.3)); let _ = writeln!( o, "\ncarried cost on current branch, replaying the request masking (tokens ~ bytes/4):" ); let _ = writeln!( o, "{:<18}{:>6}{:>12}{:>14}{:>16}", "tool", "calls", "tok once", "resent sent", "resent unmasked" ); for (k, (c, b, sent, raw)) in rows { let _ = writeln!( o, "{k:<18}{c:>6}{:>12}{:>14}{:>16}", b / 4, sent / 4, raw / 4 ); } big.sort_by_key(|b| std::cmp::Reverse(b.0)); let _ = writeln!(o, "\ntop 5 single items by resent tokens (as sent):"); for (carried, len, what) in big.into_iter().take(5) { let _ = writeln!(o, " {what}: {} tok once, {} resent", len / 4, carried / 4); } o } #[cfg(test)] mod tests { #[test] fn claude_tools_are_counted() { let p = std::env::temp_dir().join(format!("hx-claude-stats-{}.jsonl", std::process::id())); let c = p.with_extension("claude"); let _ = std::fs::remove_file(&c); assert_eq!(super::claude_report(&p), ""); super::log_claude_tool(&p, "bash", 10, 100, false); super::log_claude_tool(&p, "bash", 10, 20, true); let r = super::claude_report(&p); let _ = std::fs::remove_file(&c); assert!( r.contains("bash: 2 calls, 1 errors/blocked, args 20 B, results 120 B"), "{r}" ); } use super::*; use hx_ai::{Message, Usage}; #[test] fn task_report_counts_lone_and_batched_turns() { let d = tempfile::tempdir().unwrap(); let mut s = Session::open(d.path().join("s.jsonl")).unwrap(); let tu = |id: &str, k: &str| ContentBlock::ToolUse { id: id.into(), name: "task".into(), input: serde_json::json!({"kind": k}), }; for c in [ vec![tu("a", "explore")], vec![tu("b", "explore"), tu("c", "general")], ] { s.append(Message { role: Role::Assistant, content: c, }) .unwrap(); } let r = task_report(&s); assert!(r.contains("task calls: 3 (2 explore, 1 general)"), "{r}"); assert!(r.contains("one task 1, with several 1"), "{r}"); } #[test] fn model_report_counts_switches() { let dir = tempfile::tempdir().unwrap(); let mut s = Session::open(dir.path().join("s.jsonl")).unwrap(); let u = |cr, cw| hx_ai::Usage { input_tokens: 1, output_tokens: 10, cache_read_tokens: cr, cache_write_tokens: cw, }; for (m, usage) in [ ("a", u(0, 100)), ("a", u(100, 5)), ("b", u(0, 120)), ("b", u(120, 5)), ] { s.append_full(hx_ai::Message::user("x"), Some(m.into()), Some(usage)) .unwrap(); } let r = model_report(&s); assert!(r.contains("a: 2 requests"), "{r}"); assert!( r.contains( "model switches: 1, cache written on the first request after a switch: 120 tok" ), "{r}" ); let mut one = Session::open(dir.path().join("o.jsonl")).unwrap(); one.append_full(hx_ai::Message::user("x"), Some("a".into()), Some(u(0, 1))) .unwrap(); assert_eq!(model_report(&one), ""); } #[test] fn report_counts() { let d = tempfile::tempdir().unwrap(); let mut s = Session::open(d.path().join("s.jsonl")).unwrap(); s.append(Message::user("go")).unwrap(); let u = Usage { input_tokens: 10, output_tokens: 5, cache_read_tokens: 90, cache_write_tokens: 0, }; s.append_full( Message { role: Role::Assistant, content: vec![ContentBlock::ToolUse { id: "t".into(), name: "read".into(), input: serde_json::json!({}), }], }, None, Some(u.clone()), ) .unwrap(); s.append(Message { role: Role::User, content: vec![ContentBlock::ToolResult { tool_use_id: "t".into(), content: "x".repeat(4000), is_error: false, }], }) .unwrap(); s.append_full(Message::user("done"), None, Some(u)).unwrap(); let r = report(&s); assert!( r.contains("requests 2") && r.contains("cache hit 90%"), "{r}" ); assert!(r.contains("read") && r.contains("1000"), "{r}"); } #[test] fn replay_applies_masking() { let d = tempfile::tempdir().unwrap(); let mut s = Session::open(d.path().join("s.jsonl")).unwrap(); s.append(Message::user("go")).unwrap(); for i in 0..20 { s.append(Message { role: Role::Assistant, content: vec![ContentBlock::ToolUse { id: format!("t{i}"), name: "bash".into(), input: serde_json::json!({}), }], }) .unwrap(); s.append(Message { role: Role::User, content: vec![ContentBlock::ToolResult { tool_use_id: format!("t{i}"), content: "x".repeat(8000), is_error: false, }], }) .unwrap(); } s.append_full(Message::user("end"), None, Some(Default::default())) .unwrap(); let r = report(&s); let row = r.lines().find(|l| l.starts_with("bash")).unwrap(); let n: Vec = row .split_whitespace() .skip(1) .map(|x| x.parse().unwrap()) .collect(); // calls, once, sent, unmasked assert!(n[2] < n[3] && n[2] > 0, "{row}"); } #[test] fn reports_cache_writes_and_assistant_bytes() { let d = tempfile::tempdir().unwrap(); let mut s = Session::open(d.path().join("s.jsonl")).unwrap(); s.append(Message::user("go")).unwrap(); for i in 0..5 { let u = Usage { cache_write_tokens: if i == 3 { 10_000 } else { 100 }, ..Default::default() }; s.append_full( Message { role: Role::Assistant, content: vec![ContentBlock::Text { text: "y".repeat(400), }], }, None, Some(u), ) .unwrap(); s.append(Message::user("more")).unwrap(); } let r = report(&s); assert!(r.contains("request 4: write 10000"), "{r}"); assert!(r.contains("text 500 tok"), "{r}"); } }