Skip to main content

agentmux_srv_core/backend/
token_ledger.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Counts what an agent's calls used against the Kanban task they belong to, as they pass through `transcript::append`
5//! (`docs/specs/SPEC_TOKEN_ANALYSIS_PER_KANBAN_TASK_2026_11_22.md` sections 4.1 to 4.4). srv counts: no agent
6//! reports or adds up its own tokens.
7//!
8//! One call is one deduplicated message id. Claude writes a call's usage again on each of its content-block lines,
9//! and only the output grows: the first sight of a call counts it, a later line of it adds what grew. Each counted
10//! call is kept (id, where it was counted, what was counted) with the counters in one write, so a replay, a restart
11//! or an upgrade adds nothing twice, however far back it goes. The task and its stage are decided when the call is
12//! counted, never rebuilt later. Counts, ids, model names and times only: nothing of a line is kept.
13//!
14//! Which task a call belongs to, in this order (`basis` of its row):
15//! 1. `held`, or `shared` when the agent held several: the task it held at that time;
16//! 2. `named`: the agent holds none, and the call issued a `Tasks` action naming one (only its number is read);
17//! 3. `spawned`: a worker of a leader that holds one, until the worker takes one of its own;
18//! 4. `unattributed`: none of these. Kept per agent and day with an empty task, never spread over tasks.
19//!
20//! The counters are written in batches, about once a second, by one thread; a crash loses at most the batch not yet
21//! written, together with the ids of its calls.
22
23use 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
35/// How many calls of a zone are kept in memory: the lines of one call are close together.
36const RING: usize = 32;
37/// Written to the ledger this often.
38const FLUSH_EVERY: Duration = Duration::from_secs(1);
39/// The `Tasks` actions that act on a task by number: a call issuing one is working on that task. Not `claim` (it
40/// makes the agent a holder), `get` or `list` (they read), or `enqueue` (it names no task yet).
41const 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
46/// What the ledger needs to know of the world besides the task store.
47pub trait Directory {
48    /// The names the Kanban's history may know an agent by: the transcript zone has its definition uid, and the history
49    /// records the name a task was held under (its slug, or one it had before a rename).
50    fn names_of(&self, uid: &str) -> Vec<String>;
51    /// The definition uid of the leader whose worker `uid` is.
52    fn leader_of(&self, uid: &str) -> Option<String>;
53}
54
55/// The registries of this srv.
56struct 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    /// The calls of each zone seen lately, with what was counted.
75    zones: HashMap<String, Vec<CountedCall>>,
76    pending: Vec<SpendAdd>,
77    moves: Vec<SpendMove>,
78    /// Calls counted or grown and not yet written, and those being written now: a call in either is known.
79    dirty: HashMap<(String, String), CountedCall>,
80    inflight: HashMap<(String, String), CountedCall>,
81    /// What made the next call of each zone (`token_cause.rs`).
82    causes: HashMap<String, CauseState>,
83    /// The latest main call of each zone: its id and how much prompt it held, to tell what grew before the next.
84    last: HashMap<String, (String, u64)>,
85    /// Tool-result weights and waste counts not yet written.
86    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
97/// Counts the calls in `records` (newline-terminated lines an agent wrote to `zone`). Called for every transcript
98/// write of the agent's own output; a line that holds no usage costs a substring test.
99pub 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
105/// Takes in the records srv wrote for a prompt it delivered, for the cause of the call that answers it.
106pub fn note_prompt(zone: &str, records: &[u8]) {
107    LEDGER.note_prompt(zone, records);
108}
109
110/// Counts calls a provider-specific reader found (`FoundCall`), for the agent whose transcript is `zone`.
111pub 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/// A call a provider-specific reader found in the provider's own file: its durable id and when it was made.
134#[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
153/// What grew since `counted`: each bucket's excess over what was counted.
154fn 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
177/// The task a call was counted against, how, and the stage it is in.
178struct Placed {
179    work_id: String,
180    stage: String,
181    basis: &'static str,
182}
183
184/// The task the agent held at `at_ms` (under any of its `names`) and the stage it is in, with whether it held several.
185fn 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
195/// The task a line's `Tasks` call names, as the board numbers it: only the number is read, never the call's text.
196fn 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
213/// The day `at_ms` falls on (UTC), the stage an unattributed row carries.
214fn 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    /// Count the calls in `records`; returns how many were new.
233    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                // Only Claude's lines carry an id that repeats; the other sources join in with their own readers.
240                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            // The call above answers what came before this line; what this line is shapes the next call.
245            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    /// Take in the records srv itself wrote for the agent's prompts (a message it delivered): they shape the cause of
261    /// the call that answers them. No call is counted from them.
262    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    /// Count `counts` of waste against the task the agent holds now; nothing for an agent that holds none.
272    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    /// Count calls a reader found in a provider's own file (`codex_usage.rs`): each has its own durable id and the time
284    /// it was made. Returns how many were new.
285    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    /// Count one call of `id`, or what grew of it. `text` is the line it came from (what a `Tasks` call names), empty
291    /// when there is none. Returns 1 when the call was new.
292    #[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                // A later line of a call that was counted without a task of its own (overhead, or a worker's call
298                // under its leader's) may show the task it names: the call moves there.
299                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    /// Write what has been counted. A write that fails is kept for the next one.
337    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
369/// How much the prompt grew between the zone's previous main call and this new one, when the call follows a tool's
370/// answer: that growth is the size of what the tool returned (less what the previous call itself wrote, which is in
371/// the prompt too). Kept per tool name for the task the call is counted against; never the answer. A prompt that did
372/// not grow (a compaction, a cache that was dropped) says nothing.
373fn 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
388/// Move `call`, counted as overhead, to the task its line names, when it names one: its counts go from the overhead
389/// row to the task's, and what is kept for it says so. Whether it moved.
390fn 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
398/// What is known of the call `id`: in memory (this zone's lately seen calls, or what waits to be written), else in the
399/// ledger. A call found is brought into the zone's recent calls.
400fn 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
411/// Keep `call` as the latest of its id: in its zone's recent calls, and to be written.
412fn 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;