agentmux_srv_core/backend/
usage_of.rs1use serde_json::Value;
25
26const LINE_MAX: usize = 2 * 1024 * 1024;
28
29#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
32pub struct Buckets {
33 pub uncached_input: u64,
35 pub cache_read: u64,
36 pub cache_write_5m: u64,
39 pub cache_write_1h: u64,
40 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum CallKind {
63 Main,
65 Subagent,
67 Compaction,
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum Source {
75 Claude,
76 Codex,
77 Response,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct CallUsage {
83 pub buckets: Buckets,
84 pub reasoning_reported: bool,
86 pub model: Option<String>,
87 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
101pub fn usage_of(line: &str) -> Option<CallUsage> {
103 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
110pub 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 Some("result") | Some("system") | Some("user") => None,
119 None | Some("message") if line.get("usage").is_some() => call_from_message(line, CallKind::Main, Source::Response),
121 _ => None,
122 }
123}
124
125pub 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 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
155pub 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 (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
181fn 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;