#![deny(unsafe_code)]
use super::atif::STEPS;
use super::usage::{self, Field, Tokens};
use super::usage_agent::count;
use super::{record_clock, Class, Lens, Part, RecordsAt, Summary, Who};
use crate::json::Value;
pub const NAME: &str = "usage-atif";
pub const ABOUT: &str = "ATIF agent trajectories: what each step spent, not what it said";
const FIELDS: [Field; 3] = [Field::In, Field::Out, Field::Read];
#[derive(Default)]
pub struct UsageAtif;
impl Lens for UsageAtif {
fn name(&self) -> &'static str {
NAME
}
fn about(&self) -> &'static str {
ABOUT
}
fn records_at(&self) -> RecordsAt {
RecordsAt::Member(STEPS)
}
fn read(&mut self, v: &Value) -> Option<Summary> {
match v.get("step_id") {
Some(_) => step(v),
None => session(v),
}
}
fn detail(&self, v: &Value) -> Vec<Part> {
let mut out: Vec<Part> = Vec::new();
if let Some(m) = v.get("metrics") {
out.extend(usage::part("tokens", metric_lines(m)));
}
out.extend(usage::part("model", model_lines(v)));
out
}
}
fn metric_lines(m: &Value) -> Vec<String> {
let mut lines: Vec<String> = Vec::new();
for key in ["prompt_tokens", "completion_tokens", "cached_tokens", "total_tokens"] {
lines.extend(usage::exact(m, key));
}
if let Some(extra) = m.get("extra") {
lines.extend(usage::exact(extra, "reasoning_tokens"));
}
lines
}
fn model_lines(v: &Value) -> Vec<String> {
let mut lines: Vec<String> = Vec::new();
lines.extend(usage::named(v, "model_name"));
lines.extend(usage::exact(v, "llm_call_count"));
lines
}
fn step(v: &Value) -> Option<Summary> {
let source = v.get("source").and_then(|s| s.as_str()).unwrap_or("agent");
let (who, actor, class) = match source {
"user" => (Who::User, "user", Class::Message),
_ => (Who::Assistant, "agent", Class::Step),
};
let calls = calls_of(v);
let metrics = read_metrics(v);
let what = match &metrics {
Some(t) => usage::row_text(t, &FIELDS, &action(&calls, source)),
None => source.to_string(),
};
let tokens = metrics.map(|t| t.total()).unwrap_or(0);
Some(
Summary {
class,
who,
actor: actor.to_string(),
time: None,
what,
calls: calls.len(),
tokens,
body: None,
}
.at(record_clock(v)),
)
}
fn session(v: &Value) -> Option<Summary> {
let schema = text(v, "schema_version");
let id = text(v, "session_id");
if schema.is_none() && id.is_none() {
return None;
}
let mut parts: Vec<String> = Vec::new();
if let Some(a) = v.get("agent") {
parts.push(text(a, "name").unwrap_or_else(|| "agent".to_string()));
parts.extend(text(a, "model_name"));
}
parts.extend(schema);
parts.extend(id);
Some(Summary {
class: Class::Message,
who: Who::System,
actor: "session".to_string(),
time: None,
what: parts.join(" \u{b7} "),
calls: 0,
tokens: 0,
body: None,
})
}
fn read_metrics(v: &Value) -> Option<Tokens> {
let m = v.get("metrics")?;
let t = Tokens {
input: count(m, "prompt_tokens"),
output: count(m, "completion_tokens"),
cache_read: count(m, "cached_tokens"),
cache_new: None,
};
match t.any() {
true => Some(t),
false => None,
}
}
fn action(calls: &[String], source: &str) -> String {
match calls.is_empty() {
true => source.to_string(),
false => usage::collapse(calls.to_vec()).join(" \u{b7} "),
}
}
fn calls_of(v: &Value) -> Vec<String> {
let Some(items) = v.get("tool_calls").and_then(|c| c.as_array()) else {
return Vec::new();
};
items.iter().map(call_text).collect()
}
fn call_text(call: &Value) -> String {
let name = text(call, "function_name").unwrap_or_else(|| "tool".to_string());
match super::atif::arg_of(call) {
Some(arg) => format!("{name}({arg})"),
None => name,
}
}
fn text(v: &Value, key: &str) -> Option<String> {
Some(v.get(key)?.as_str()?.to_string())
}
#[cfg(test)]
#[path = "usage_atif_tests.rs"]
mod tests;