1use std::collections::HashMap;
24use std::sync::{LazyLock, Mutex, Once, OnceLock};
25use std::time::Duration;
26
27use serde_json::Value;
28
29use crate::backend::storage::store::Store;
30use crate::backend::token_cause::{self, CauseState};
31use crate::backend::storage::work_spend::{stage_of, CallKnown, CountedCall, SpendAdd, SpendKey, SpendMove};
32use crate::backend::storage::work_waste::{count, ToolGrowth, WasteBatch, WasteCount};
33use crate::backend::usage_of::{usage_of, Buckets, CallKind, CallUsage, Source};
34
35const RING: usize = 32;
37const FLUSH_EVERY: Duration = Duration::from_secs(1);
39const TASK_ACTIONS: [&str; 18] = [
42 "update", "complete", "submit", "ask", "release", "hold", "unhold", "accept", "send_back", "edit", "move", "start", "answer", "cancel", "reopen", "retry",
43 "take_back", "reassign",
44];
45
46pub trait Directory {
48 fn names_of(&self, uid: &str) -> Vec<String>;
51 fn leader_of(&self, uid: &str) -> Option<String>;
53}
54
55struct Live;
57
58impl Directory for Live {
59 fn names_of(&self, uid: &str) -> Vec<String> {
60 let entry = crate::backend::identity_spawn::row_store()
61 .and_then(|s| s.shared_def_registry())
62 .and_then(|r| r.slug_index().ok())
63 .and_then(|index| index.get(uid).map(|e| std::iter::once(e.slug.clone()).chain(e.former.iter().cloned()).collect::<Vec<_>>()));
64 entry.filter(|names| !names.is_empty()).unwrap_or_else(|| vec![uid.to_string()])
65 }
66
67 fn leader_of(&self, uid: &str) -> Option<String> {
68 crate::backend::agent_seat::worker_of(crate::backend::identity_spawn::row_store()?, uid)
69 }
70}
71
72#[derive(Default)]
73struct Inner {
74 zones: HashMap<String, Vec<CountedCall>>,
76 pending: Vec<SpendAdd>,
77 moves: Vec<SpendMove>,
78 dirty: HashMap<(String, String), CountedCall>,
80 inflight: HashMap<(String, String), CountedCall>,
81 causes: HashMap<String, CauseState>,
83 last: HashMap<String, (String, u64)>,
85 waste: WasteBatch,
87}
88
89#[derive(Default)]
90pub struct Ledger {
91 inner: Mutex<Inner>,
92}
93
94static LEDGER: LazyLock<Ledger> = LazyLock::new(Ledger::default);
95static FLUSHER: Once = Once::new();
96
97pub fn note_records(zone: &str, records: &[u8]) {
100 let Some(store) = crate::backend::work_store_handle::get() else { return };
101 LEDGER.note(&store, local_host(), &Live, zone, records, agentmux_common::time::now_ms());
102 start_flusher();
103}
104
105pub fn note_prompt(zone: &str, records: &[u8]) {
107 LEDGER.note_prompt(zone, records);
108}
109
110pub fn note_found(zone: &str, found: &[FoundCall]) {
112 let Some(store) = crate::backend::work_store_handle::get() else { return };
113 LEDGER.note_found(&store, local_host(), &Live, zone, found);
114 start_flusher();
115}
116
117fn local_host() -> &'static str {
118 static HOST: OnceLock<String> = OnceLock::new();
119 HOST.get_or_init(crate::backend::reactive::registry::local_host_label)
120}
121
122fn start_flusher() {
123 FLUSHER.call_once(|| {
124 let _ = std::thread::Builder::new().name("token-ledger".into()).spawn(|| loop {
125 std::thread::sleep(FLUSH_EVERY);
126 if let Some(store) = crate::backend::work_store_handle::get() {
127 LEDGER.flush(&store);
128 }
129 });
130 });
131}
132
133#[derive(Debug, Clone, PartialEq, Eq)]
135pub struct FoundCall {
136 pub id: String,
137 pub at_ms: i64,
138 pub call: CallUsage,
139}
140
141fn provider_of(source: Source) -> &'static str {
142 match source {
143 Source::Claude => "claude",
144 Source::Codex => "codex",
145 Source::Response => "route",
146 }
147}
148
149fn id_of(call: &CallUsage) -> Option<String> {
150 Some(format!("{}|{}", call.message_id.as_deref()?, call.request_id.as_deref().unwrap_or_default()))
151}
152
153fn growth(now: &Buckets, counted: &Buckets) -> Buckets {
155 let up = |a: u64, b: u64| a.saturating_sub(b);
156 Buckets {
157 uncached_input: up(now.uncached_input, counted.uncached_input),
158 cache_read: up(now.cache_read, counted.cache_read),
159 cache_write_5m: up(now.cache_write_5m, counted.cache_write_5m),
160 cache_write_1h: up(now.cache_write_1h, counted.cache_write_1h),
161 output: up(now.output, counted.output),
162 reasoning: up(now.reasoning, counted.reasoning),
163 }
164}
165
166fn highest(a: &Buckets, b: &Buckets) -> Buckets {
167 Buckets {
168 uncached_input: a.uncached_input.max(b.uncached_input),
169 cache_read: a.cache_read.max(b.cache_read),
170 cache_write_5m: a.cache_write_5m.max(b.cache_write_5m),
171 cache_write_1h: a.cache_write_1h.max(b.cache_write_1h),
172 output: a.output.max(b.output),
173 reasoning: a.reasoning.max(b.reasoning),
174 }
175}
176
177struct Placed {
179 work_id: String,
180 stage: String,
181 basis: &'static str,
182}
183
184fn held(store: &Store, names: &[String], at_ms: i64) -> Option<Placed> {
186 let holds = names.iter().find_map(|name| store.work_holds_at(name, at_ms).ok().filter(|h| !h.is_empty()))?;
187 placed(store, holds.first()?, if holds.len() > 1 { "shared" } else { "held" })
188}
189
190fn placed(store: &Store, work_id: &str, basis: &'static str) -> Option<Placed> {
191 let task = store.work_board_get(work_id).ok()??;
192 Some(Placed { work_id: work_id.to_string(), stage: stage_of(&task).to_string(), basis })
193}
194
195fn named_task(line: &str) -> Option<String> {
197 if !line.contains("Tasks") {
198 return None;
199 }
200 let v: Value = serde_json::from_str(line).ok()?;
201 v.pointer("/message/content")?.as_array()?.iter().find_map(|block| {
202 let is_tasks = block.get("type").and_then(Value::as_str) == Some("tool_use") && block.get("name").and_then(Value::as_str).is_some_and(|n| n == "Tasks" || n.ends_with("__Tasks"));
203 let input = block.get("input").filter(|_| is_tasks)?;
204 TASK_ACTIONS.contains(&input.get("action").and_then(Value::as_str)?).then_some(())?;
205 match input.get("id")? {
206 Value::Number(n) => Some(n.to_string()),
207 Value::String(s) if s.len() <= 40 && !s.is_empty() => Some(s.clone()),
208 _ => None,
209 }
210 })
211}
212
213fn day_of(at_ms: i64) -> String {
215 chrono::DateTime::from_timestamp_millis(at_ms).map(|d| d.format("%Y-%m-%d").to_string()).unwrap_or_default()
216}
217
218fn place(store: &Store, dir: &dyn Directory, agent: &str, line: &str, at_ms: i64) -> Placed {
219 if let Some(p) = held(store, &dir.names_of(agent), at_ms) {
220 return p;
221 }
222 if let Some(p) = named_task(line).and_then(|r| store.work_board_get(&r).ok().flatten()).and_then(|t| placed(store, &t.item.id, "named")) {
223 return p;
224 }
225 if let Some(p) = dir.leader_of(agent).and_then(|leader| held(store, &dir.names_of(&leader), at_ms)) {
226 return Placed { basis: "spawned", ..p };
227 }
228 Placed { work_id: String::new(), stage: day_of(at_ms), basis: "unattributed" }
229}
230
231impl Ledger {
232 pub fn note(&self, store: &Store, host: &str, dir: &dyn Directory, zone: &str, records: &[u8], at_ms: i64) -> usize {
234 let Some(agent) = crate::backend::audit_activity::agent_of_zone(zone) else { return 0 };
235 let mut new_calls = 0;
236 for raw in records.split(|b| *b == b'\n') {
237 let Ok(text) = std::str::from_utf8(raw) else { continue };
238 if let Some(call) = usage_of(text) {
239 if let Some(id) = id_of(&call).filter(|_| call.source == Source::Claude) {
241 new_calls += self.count(store, host, dir, (zone, agent), &id, &call, text, at_ms);
242 }
243 }
244 if token_cause::wants(text) {
246 let (repeats, compactions) = {
247 let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
248 let state = inner.causes.entry(zone.to_string()).or_default();
249 state.see(text);
250 state.take_waste()
251 };
252 if repeats + compactions > 0 {
253 self.note_waste(store, dir, agent, at_ms, [(count::REPEAT, repeats), (count::COMPACTION, compactions)]);
254 }
255 }
256 }
257 new_calls
258 }
259
260 pub fn note_prompt(&self, zone: &str, records: &[u8]) {
263 for raw in records.split(|b| *b == b'\n') {
264 let Ok(text) = std::str::from_utf8(raw) else { continue };
265 if token_cause::wants(text) {
266 self.inner.lock().unwrap_or_else(|e| e.into_inner()).causes.entry(zone.to_string()).or_default().see(text);
267 }
268 }
269 }
270
271 fn note_waste<const N: usize>(&self, store: &Store, dir: &dyn Directory, agent: &str, at_ms: i64, counts: [(&'static str, u64); N]) {
273 let p = place(store, dir, agent, "", at_ms);
274 if p.work_id.is_empty() {
275 return;
276 }
277 let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
278 for (name, n) in counts.into_iter().filter(|(_, n)| *n > 0) {
279 inner.waste.counts.push(WasteCount { work_id: p.work_id.clone(), name, n });
280 }
281 }
282
283 pub fn note_found(&self, store: &Store, host: &str, dir: &dyn Directory, zone: &str, found: &[FoundCall]) -> usize {
286 let Some(agent) = crate::backend::audit_activity::agent_of_zone(zone) else { return 0 };
287 found.iter().map(|f| self.count(store, host, dir, (zone, agent), &f.id, &f.call, "", f.at_ms)).sum()
288 }
289
290 #[allow(clippy::too_many_arguments)]
293 fn count(&self, store: &Store, host: &str, dir: &dyn Directory, (zone, agent): (&str, &str), id: &str, call: &CallUsage, text: &str, at_ms: i64) -> usize {
294 let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
295 let add = match recall(&mut inner, store, zone, id) {
296 CallKnown::Counted(mut c) => {
297 let moved = matches!(c.key.basis.as_str(), "unattributed" | "spawned") && rename(&mut inner, store, &mut c, text, at_ms);
300 let grown = growth(&call.buckets, &c.counted);
301 if grown == Buckets::default() && !moved {
302 return 0;
303 }
304 c.counted = highest(&c.counted, &call.buckets);
305 let add = SpendAdd { key: c.key.clone(), calls: 0, buckets: grown, at: at_ms };
306 remember(&mut inner, c);
307 if grown == Buckets::default() {
308 return 0;
309 }
310 add
311 }
312 CallKnown::Unreadable => return 0,
313 CallKnown::No => {
314 let p = place(store, dir, agent, text, at_ms);
315 let cause = if call.kind == CallKind::Subagent { "subagent".to_string() } else { inner.causes.get(zone).map(|c| c.cause().to_string()).unwrap_or_default() };
316 let key = SpendKey {
317 work_id: p.work_id,
318 stage: p.stage,
319 agent: agent.to_string(),
320 host: host.to_string(),
321 provider: provider_of(call.source).to_string(),
322 model: call.model.clone().unwrap_or_default(),
323 cause,
324 basis: p.basis.to_string(),
325 };
326 note_weight(&mut inner, zone, id, &key, call);
327 remember(&mut inner, CountedCall { zone: zone.to_string(), id: id.to_string(), at: at_ms, key: key.clone(), counted: call.buckets });
328 inner.pending.push(SpendAdd { key, calls: 1, buckets: call.buckets, at: at_ms });
329 return 1;
330 }
331 };
332 inner.pending.push(add);
333 0
334 }
335
336 pub fn flush(&self, store: &Store) {
338 let (adds, moves, calls) = {
339 let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
340 if inner.pending.is_empty() && inner.dirty.is_empty() && inner.moves.is_empty() && inner.waste.is_empty() {
341 return;
342 }
343 let calls = std::mem::take(&mut inner.dirty);
344 inner.inflight = calls.clone();
345 (std::mem::take(&mut inner.pending), std::mem::take(&mut inner.moves), calls)
346 };
347 let waste = std::mem::take(&mut self.inner.lock().unwrap_or_else(|e| e.into_inner()).waste);
348 let list: Vec<CountedCall> = calls.values().cloned().collect();
349 let result = store.work_spend_apply(&adds, &moves, &list);
350 let waste_result = if waste.is_empty() { Ok(()) } else { store.work_waste_apply(&waste) };
351 let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
352 inner.inflight.clear();
353 if let Err(e) = waste_result {
354 tracing::warn!(error = %e, "token ledger: waste counts were not written, kept for the next");
355 inner.waste.weights.splice(0..0, waste.weights);
356 inner.waste.counts.splice(0..0, waste.counts);
357 }
358 if let Err(e) = result {
359 tracing::warn!(error = %e, "token ledger: a batch was not written, kept for the next");
360 inner.pending.splice(0..0, adds);
361 inner.moves.splice(0..0, moves);
362 for (k, c) in calls {
363 inner.dirty.entry(k).or_insert(c);
364 }
365 }
366 }
367}
368
369fn note_weight(inner: &mut Inner, zone: &str, id: &str, key: &SpendKey, call: &CallUsage) {
374 if call.kind != CallKind::Main || call.source != Source::Claude {
375 return;
376 }
377 let prompt = call.buckets.prompt();
378 let Some((prev_id, prev_prompt)) = inner.last.insert(zone.to_string(), (id.to_string(), prompt)) else { return };
379 let Some(tool) = key.cause.strip_prefix("tool").map(|rest| rest.strip_prefix(':').unwrap_or("tool")).filter(|t| !t.is_empty()) else { return };
380 if key.work_id.is_empty() || prompt < prev_prompt {
381 return;
382 }
383 let wrote = inner.zones.get(zone).and_then(|ring| ring.iter().find(|c| c.id == prev_id)).map_or(0, |c| c.counted.output + c.counted.reasoning);
384 let growth = prompt.saturating_sub(prev_prompt).saturating_sub(wrote);
385 inner.waste.weights.push(ToolGrowth { work_id: key.work_id.clone(), tool: tool.to_string(), growth });
386}
387
388fn rename(inner: &mut Inner, store: &Store, call: &mut CountedCall, line: &str, at_ms: i64) -> bool {
391 let Some(p) = named_task(line).and_then(|r| store.work_board_get(&r).ok().flatten()).and_then(|t| placed(store, &t.item.id, "named")) else { return false };
392 let to = SpendKey { work_id: p.work_id, stage: p.stage, basis: p.basis.to_string(), ..call.key.clone() };
393 inner.moves.push(SpendMove { from: call.key.clone(), to: to.clone(), calls: 1, buckets: call.counted, at: at_ms });
394 call.key = to;
395 true
396}
397
398fn recall(inner: &mut Inner, store: &Store, zone: &str, id: &str) -> CallKnown {
401 if let Some(c) = inner.zones.get(zone).and_then(|ring| ring.iter().find(|c| c.id == id)) {
402 return CallKnown::Counted(c.clone());
403 }
404 let key = (zone.to_string(), id.to_string());
405 if let Some(c) = inner.dirty.get(&key).or_else(|| inner.inflight.get(&key)) {
406 return CallKnown::Counted(c.clone());
407 }
408 store.work_spend_call(zone, id)
409}
410
411fn remember(inner: &mut Inner, call: CountedCall) {
413 let ring = inner.zones.entry(call.zone.clone()).or_default();
414 ring.retain(|c| c.id != call.id);
415 ring.push(call.clone());
416 if ring.len() > RING {
417 ring.remove(0);
418 }
419 inner.dirty.insert((call.zone.clone(), call.id.clone()), call);
420}
421
422#[cfg(test)]
423#[path = "token_ledger_tests.rs"]
424mod tests;