Skip to main content

agentmux_srv_core/backend/
usage_of.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The one reading of a provider's usage, for every place srv counts tokens
5//! (`docs/specs/SPEC_TOKEN_ANALYSIS_PER_KANBAN_TASK_2026_11_22.md` section 4.5): the Audit, the context meter and
6//! the agents translator read through it, and the per-task ledger counts from it.
7//!
8//! [`usage_of`] takes one output line and returns the call it reports, in six buckets that never overlap: fresh
9//! input, cache read, cache write (5 minutes and 1 hour), output and reasoning. A line that reports no usage, or in a
10//! shape this does not know, returns `None`: **not reported is never zero**. Nothing of the line is kept: no text, no
11//! tool input, no path.
12//!
13//! Shapes read (the fixtures in `usage_of_tests.rs` are lines of each):
14//! - **Claude stream-json**: an `assistant` frame, or a `stream_event` holding `message_start`; `parent_tool_use_id`
15//!   (or `isSidechain`) marks a subagent's call. The same call is repeated per content block with the same message
16//!   id, and only `output_tokens` grows: counting once per message id is the counter's job.
17//! - **Codex session file**: an `event_msg` `token_count`, from its `last_token_usage`. Cached tokens are inside
18//!   `input_tokens` there, so they are taken out of it here.
19//! - **A model response** (a route model's, through the gateway): a Messages response body, or a `message_start`
20//!   event of its stream.
21//!
22//! A turn's `result` line is not a call (its usage is the turn's sum): [`turn_total`] reads that.
23
24use serde_json::Value;
25
26/// A line longer than this is a big tool result and reports no call.
27const LINE_MAX: usize = 2 * 1024 * 1024;
28
29/// What a call used, in buckets that never overlap. The inclusive totals (OpenTelemetry's `input_tokens`) are sums
30/// of these.
31#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
32pub struct Buckets {
33    /// Input not read from or written to the cache.
34    pub uncached_input: u64,
35    pub cache_read: u64,
36    /// Cache writes of the 5-minute kind. A response that does not separate the two kinds is counted here, the
37    /// provider's default lifetime.
38    pub cache_write_5m: u64,
39    pub cache_write_1h: u64,
40    /// Output without the reasoning that a provider reports apart.
41    pub output: u64,
42    pub reasoning: u64,
43}
44
45impl Buckets {
46    pub fn cache_write(&self) -> u64 {
47        self.cache_write_5m + self.cache_write_1h
48    }
49
50    /// The whole prompt of the call: what its context held.
51    pub fn prompt(&self) -> u64 {
52        self.uncached_input + self.cache_read + self.cache_write()
53    }
54
55    pub fn total(&self) -> u64 {
56        self.prompt() + self.output + self.reasoning
57    }
58}
59
60/// Whose call it is.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum CallKind {
63    /// The agent's own call.
64    Main,
65    /// A subagent's call, inside its parent's stream.
66    Subagent,
67    /// The call that summarises a conversation. One line cannot say so: the reader that follows the compaction
68    /// markers sets it (`CallUsage::as_compaction`).
69    Compaction,
70}
71
72/// Which shape the line had; a counter of lines it could not read is kept per source, so a provider's change shows.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum Source {
75    Claude,
76    Codex,
77    Response,
78}
79
80/// One call, as its line reports it.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct CallUsage {
83    pub buckets: Buckets,
84    /// The provider reports reasoning apart from output (so a `0` in `buckets.reasoning` is a count, not a gap).
85    pub reasoning_reported: bool,
86    pub model: Option<String>,
87    /// The id that repeats across the lines of one call.
88    pub message_id: Option<String>,
89    pub request_id: Option<String>,
90    pub kind: CallKind,
91    pub source: Source,
92}
93
94impl CallUsage {
95    pub fn as_compaction(mut self) -> Self {
96        self.kind = CallKind::Compaction;
97        self
98    }
99}
100
101/// The call that `line` reports, if it reports one.
102pub fn usage_of(line: &str) -> Option<CallUsage> {
103    // A cheap test first: nearly every line is a message or a tool result.
104    if line.len() > LINE_MAX || !(line.contains("\"usage\"") || line.contains("token_count")) {
105        return None;
106    }
107    usage_of_value(&serde_json::from_str::<Value>(line).ok()?)
108}
109
110/// [`usage_of`] for a line already parsed.
111pub fn usage_of_value(line: &Value) -> Option<CallUsage> {
112    match line.get("type").and_then(Value::as_str) {
113        Some("assistant") => claude_call(line, line.get("message")?),
114        Some("stream_event") if line.pointer("/event/type").and_then(Value::as_str) == Some("message_start") => claude_call(line, line.pointer("/event/message")?),
115        Some("message_start") => call_from_message(line.get("message")?, CallKind::Main, Source::Response),
116        Some("event_msg") => codex_call(line.get("payload")?),
117        // A turn's end holds the turn's sum, not a call.
118        Some("result") | Some("system") | Some("user") => None,
119        // A response body: `{"model", "usage"}` with no frame type, or `"type":"message"`.
120        None | Some("message") if line.get("usage").is_some() => call_from_message(line, CallKind::Main, Source::Response),
121        _ => None,
122    }
123}
124
125/// A turn's sum, from the `usage` of its `result` line.
126pub fn turn_total(result_line: &Value) -> Option<Buckets> {
127    buckets_of(result_line.get("usage")?).map(|(buckets, _)| buckets)
128}
129
130fn claude_call(frame: &Value, message: &Value) -> Option<CallUsage> {
131    let sub = frame.get("parent_tool_use_id").is_some_and(|p| !p.is_null()) || frame.get("isSidechain").and_then(Value::as_bool) == Some(true);
132    let mut call = call_from_message(message, if sub { CallKind::Subagent } else { CallKind::Main }, Source::Claude)?;
133    call.request_id = ["requestId", "request_id"].iter().find_map(|k| frame.get(*k)).and_then(Value::as_str).map(str::to_string);
134    Some(call)
135}
136
137fn call_from_message(message: &Value, kind: CallKind, source: Source) -> Option<CallUsage> {
138    let model = message.get("model").and_then(Value::as_str).filter(|m| !m.is_empty());
139    // The CLI's own stand-in for a call that never reached the API (a rate-limit answer): no spend.
140    if model == Some("<synthetic>") {
141        return None;
142    }
143    let (buckets, reasoning_reported) = buckets_of(message.get("usage")?)?;
144    Some(CallUsage {
145        buckets,
146        reasoning_reported,
147        model: model.map(str::to_string),
148        message_id: message.get("id").and_then(Value::as_str).filter(|i| !i.is_empty()).map(str::to_string),
149        request_id: None,
150        kind,
151        source,
152    })
153}
154
155/// The buckets of an Anthropic-style `usage` object, and whether it reports reasoning apart. `None` when it holds
156/// none of the four counts: a field that is missing among them is 0, an object with none of them is not a reading.
157pub fn buckets_of(usage: &Value) -> Option<(Buckets, bool)> {
158    let usage = usage.as_object()?;
159    let count = |key: &str| usage.get(key).and_then(Value::as_u64);
160    let (input, output, read, written) = (count("input_tokens"), count("output_tokens"), count("cache_read_input_tokens"), count("cache_creation_input_tokens"));
161    let split = usage.get("cache_creation").and_then(Value::as_object).map(|s| {
162        let part = |key: &str| s.get(key).and_then(Value::as_u64).unwrap_or(0);
163        (part("ephemeral_5m_input_tokens"), part("ephemeral_1h_input_tokens"))
164    });
165    if input.is_none() && output.is_none() && read.is_none() && written.is_none() && split.is_none() {
166        return None;
167    }
168    let (w5, w1) = match (split, written) {
169        // Whatever the split does not account for is of the default kind.
170        (Some((w5, w1)), Some(total)) => (w5 + total.saturating_sub(w5 + w1), w1),
171        (Some(split), None) => split,
172        (None, total) => (total.unwrap_or(0), 0),
173    };
174    let thinking = usage.get("output_tokens_details").and_then(|d| d.get("thinking_tokens")).and_then(Value::as_u64);
175    let output = output.unwrap_or(0);
176    let reasoning = thinking.unwrap_or(0).min(output);
177    let buckets = Buckets { uncached_input: input.unwrap_or(0), cache_read: read.unwrap_or(0), cache_write_5m: w5, cache_write_1h: w1, output: output - reasoning, reasoning };
178    Some((buckets, thinking.is_some()))
179}
180
181/// A Codex `token_count`: the last call's usage. `info` is null before the first call, and a repeated event is the
182/// counter's to ignore (it carries no id).
183fn codex_call(payload: &Value) -> Option<CallUsage> {
184    if payload.get("type").and_then(Value::as_str) != Some("token_count") {
185        return None;
186    }
187    let last = payload.pointer("/info/last_token_usage")?.as_object()?;
188    let count = |key: &str| last.get(key).and_then(Value::as_u64);
189    let input = count("input_tokens")?;
190    let (cached, written) = (count("cached_input_tokens").unwrap_or(0), count("cache_write_input_tokens").unwrap_or(0));
191    let output = count("output_tokens").unwrap_or(0);
192    let reasoning = count("reasoning_output_tokens");
193    let reasoning_n = reasoning.unwrap_or(0).min(output);
194    let buckets = Buckets {
195        uncached_input: input.saturating_sub(cached + written),
196        cache_read: cached,
197        cache_write_5m: written,
198        cache_write_1h: 0,
199        output: output - reasoning_n,
200        reasoning: reasoning_n,
201    };
202    Some(CallUsage { buckets, reasoning_reported: reasoning.is_some(), model: None, message_id: None, request_id: None, kind: CallKind::Main, source: Source::Codex })
203}
204
205#[cfg(test)]
206#[path = "usage_of_tests.rs"]
207mod tests;