#![deny(unsafe_code)]
use super::usage::{self, Field, Tokens};
use super::{record_clock, record_type, Class, Lens, Part, Summary, Who};
use crate::json::Value;
pub const NAME: &str = "usage";
pub const ABOUT: &str = "Claude Code session logs: what each turn spent, not what it said";
const SIDE: char = '\u{21b3}';
#[derive(Default)]
pub struct Usage;
impl Lens for Usage {
fn name(&self) -> &'static str {
NAME
}
fn about(&self) -> &'static str {
ABOUT
}
fn read(&mut self, v: &Value) -> Option<Summary> {
let kind = record_type(v)?;
let time = record_clock(v);
let (who, actor) = speaker(v, kind);
let calls = call_blocks(v).count();
let sum = match read_usage(v) {
Some(t) => Summary {
class: class_of(v, kind),
who,
actor,
time: None,
what: usage::row_text(&t, &Field::ALL, &action(v, kind)),
calls,
tokens: t.total(),
body: None,
},
None => Summary {
class: class_of(v, kind),
who,
actor,
time: None,
what: kind.to_string(),
calls,
tokens: 0,
body: None,
},
};
Some(sum.at(time))
}
fn detail(&self, v: &Value) -> Vec<Part> {
let mut out: Vec<Part> = Vec::new();
if let Some(u) = v.get("message").and_then(|m| m.get("usage")) {
out.extend(usage::part("tokens", token_lines(u)));
out.extend(usage::part("request", request_lines(u)));
}
out.extend(usage::part("model", model_lines(v)));
out.extend(usage::part("envelope", envelope_lines(v)));
out
}
}
fn token_lines(u: &Value) -> Vec<String> {
let mut lines: Vec<String> = Vec::new();
for key in [
"input_tokens",
"output_tokens",
"cache_creation_input_tokens",
"cache_read_input_tokens",
] {
lines.extend(usage::exact(u, key));
}
if let Some(c) = u.get("cache_creation") {
for key in ["ephemeral_5m_input_tokens", "ephemeral_1h_input_tokens"] {
lines.extend(usage::exact(c, key));
}
}
if let Some(d) = u.get("output_tokens_details") {
lines.extend(usage::exact(d, "thinking_tokens"));
}
lines
}
fn request_lines(u: &Value) -> Vec<String> {
let mut lines: Vec<String> = Vec::new();
for key in ["service_tier", "speed"] {
if let Some(text) = u.get(key).and_then(|t| t.as_str()) {
if text != "standard" {
lines.push(usage::line(key, text));
}
}
}
if let Some(n) = u.get("iterations").and_then(|i| i.as_array()).map(|a| a.len()) {
if n > 1 {
lines.push(usage::line("iterations", n));
}
}
lines
}
fn model_lines(v: &Value) -> Vec<String> {
let Some(m) = v.get("message") else {
return Vec::new();
};
["model", "id", "stop_reason"]
.into_iter()
.filter_map(|key| usage::named(m, key))
.collect()
}
fn envelope_lines(v: &Value) -> Vec<String> {
["requestId", "sessionId", "gitBranch", "version"]
.into_iter()
.filter_map(|key| usage::named(v, key))
.collect()
}
fn read_usage(v: &Value) -> Option<Tokens> {
let usage = v.get("message")?.get("usage")?;
let t = Tokens {
input: count(usage, "input_tokens"),
output: count(usage, "output_tokens"),
cache_read: count(usage, "cache_read_input_tokens"),
cache_new: count(usage, "cache_creation_input_tokens"),
};
match t.any() {
true => Some(t),
false => None,
}
}
pub(super) fn count(usage: &Value, key: &str) -> Option<u64> {
u64::try_from(usage.get(key)?.as_number()?.as_i64()?).ok()
}
fn class_of(v: &Value, kind: &str) -> Class {
match kind == "user" && !carries_results(v) {
true => Class::Message,
false => Class::Step,
}
}
fn carries_results(v: &Value) -> bool {
blocks(v).is_some_and(|bs| bs.iter().any(|b| block_type(b) == "tool_result"))
}
fn blocks(v: &Value) -> Option<&[Value]> {
v.get("message")?.get("content")?.as_array()
}
fn block_type(b: &Value) -> &str {
b.get("type").and_then(|t| t.as_str()).unwrap_or("")
}
fn call_blocks(v: &Value) -> impl Iterator<Item = &Value> {
blocks(v)
.unwrap_or(&[])
.iter()
.filter(|b| block_type(b) == "tool_use")
}
fn action(v: &Value, kind: &str) -> String {
let calls: Vec<String> = call_blocks(v).map(call_text).collect();
match calls.is_empty() {
true => kind.to_string(),
false => usage::collapse(calls).join(" \u{b7} "),
}
}
fn call_text(block: &Value) -> String {
let name = block.get("name").and_then(|n| n.as_str()).unwrap_or("tool");
match block.get("input").and_then(super::agent::tool_arg) {
Some(arg) => format!("{name}({arg})"),
None => name.to_string(),
}
}
fn speaker(v: &Value, kind: &str) -> (Who, String) {
let role = v
.get("message")
.and_then(|m| m.get("role"))
.and_then(|r| r.as_str())
.unwrap_or(kind);
let (who, name) = match role {
"user" => (Who::User, "user"),
"assistant" => (Who::Assistant, "assistant"),
_ => (Who::System, "system"),
};
let side = v.get("isSidechain").and_then(|s| s.as_bool()).unwrap_or(false);
let name = match side {
true => format!("{SIDE}{name}"),
false => name.to_string(),
};
(who, name)
}
#[cfg(test)]
#[path = "usage_agent_tests.rs"]
mod tests;