Skip to main content

agentmux_srv_core/backend/
token_cause.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What made an agent's next call, for the per-task token ledger
5//! (`docs/specs/SPEC_TOKEN_ANALYSIS_PER_KANBAN_TASK_2026_11_22.md` section 4.6): the kind of the event before the call
6//! in the same transcript, from a fixed set. Counts only: the set holds no text, path or value.
7//!
8//! - `user`, `broadcast`, `agent`, `service`, `schedule`, `task`, `supervisor`, `system`: the message the call
9//!   answers, by the origin srv stamped on it (`amx.origin.kind`, `message_origin.rs`). Never read from the text.
10//! - `tool:<name>`: the call follows a tool's result; the name is the tool's (`Read`, `Bash`, `Tasks`), found from
11//!   the `tool_use` the result answers. `tool` when that call is not known (it was before srv started counting).
12//! - `rebuilt`: after a compaction boundary, until a message with a fresh origin: the calls that rebuild the context.
13//! - `subagent` is the ledger's own: a subagent's calls follow the parent's stream and never change this state.
14//! - empty: nothing seen yet (srv started, or the zone is new).
15//!
16//! The same state counts two waste signals, as counts (`take_waste`): a read-only tool called again with the same
17//! target, and a compaction. A target is kept as a hash only, in memory, and dropped when the file is edited or the
18//! context is compacted (a read after either is not a repeat).
19//!
20//! The state is in memory: after a restart the first call of a zone is empty until the next event.
21
22use std::collections::hash_map::DefaultHasher;
23use std::collections::HashSet;
24use std::hash::{Hash, Hasher};
25
26use serde_json::Value;
27
28/// How many tool calls whose result has not come are remembered.
29const USES: usize = 64;
30/// A line this long is a tool's big result, or nothing a message would be.
31const LINE_MAX: usize = 2 * 1024 * 1024;
32/// How many reads are remembered, to tell a repeat from a first read.
33const SEEN: usize = 512;
34/// The tools whose repeat on the same target is a waste signal: they only read.
35const READS: [&str; 5] = ["Read", "Grep", "Glob", "WebFetch", "NotebookRead"];
36/// The tools that change what a read of the same target returns.
37const WRITES: [&str; 4] = ["Edit", "Write", "MultiEdit", "NotebookEdit"];
38/// The origins a message is stamped with (`TriggerKind`, snake case).
39const ORIGINS: [&str; 8] = ["user", "broadcast", "agent", "service", "schedule", "task", "supervisor", "system"];
40
41/// Whether `line` can change the state: a substring test, so most lines cost nothing.
42pub fn wants(line: &str) -> bool {
43    line.contains("\"type\":\"user\"") || line.contains("compact_boundary") || line.contains("\"tool_use\"")
44}
45
46#[derive(Default)]
47pub struct CauseState {
48    cause: String,
49    rebuilt: bool,
50    /// The `tool_use` ids of the main agent's calls, with the tools' names, oldest first.
51    uses: Vec<(String, String)>,
52    /// `(hash of the tool's target, hash of the call)` of the reads made, so an identical call is told from a new one.
53    seen: HashSet<(u64, u64)>,
54    repeats: u64,
55    compactions: u64,
56    /// A compaction's boundary line came and its summary line, which is the same compaction, has not.
57    summary_due: bool,
58}
59
60impl CauseState {
61    /// The cause of a call made now.
62    pub fn cause(&self) -> &str {
63        &self.cause
64    }
65
66    /// The waste counted since the last call to this: `(repeated reads, compactions)`.
67    pub fn take_waste(&mut self) -> (u64, u64) {
68        (std::mem::take(&mut self.repeats), std::mem::take(&mut self.compactions))
69    }
70
71    /// Take in one line of the zone, in order.
72    pub fn see(&mut self, line: &str) {
73        if line.len() > LINE_MAX {
74            // Only a tool's answer is this big.
75            if line.contains("\"type\":\"user\"") {
76                self.after_tool("tool".to_string());
77            }
78            return;
79        }
80        let Ok(v) = serde_json::from_str::<Value>(line) else { return };
81        // A subagent's own events are not what the parent's next call answers.
82        if v.get("parent_tool_use_id").is_some_and(|p| !p.is_null()) || v.get("isSidechain").and_then(Value::as_bool) == Some(true) {
83            return;
84        }
85        let compaction_line = v.get("subtype").and_then(Value::as_str) == Some("compact_boundary") || v.get("isCompactSummary").and_then(Value::as_bool) == Some(true);
86        if !compaction_line {
87            self.summary_due = false;
88        }
89        match v.get("type").and_then(Value::as_str) {
90            Some("assistant") => self.note_uses(&v),
91            Some("user") => self.user(&v),
92            Some("system") if v.get("subtype").and_then(Value::as_str) == Some("compact_boundary") => self.compacted(true),
93            _ => {}
94        }
95    }
96
97    fn note_uses(&mut self, v: &Value) {
98        let Some(blocks) = v.pointer("/message/content").and_then(Value::as_array) else { return };
99        for block in blocks.iter().filter(|b| b.get("type").and_then(Value::as_str) == Some("tool_use")) {
100            let (Some(id), Some(name)) = (block.get("id").and_then(Value::as_str), block.get("name").and_then(Value::as_str)) else { continue };
101            let short = short_name(name).unwrap_or_default();
102            // A record seen again (a replay) is the same tool call: it does not repeat a read.
103            if !self.uses.iter().any(|(i, _)| i == id) {
104                self.note_target(&short, block.get("input"));
105            }
106            self.uses.retain(|(i, _)| i != id);
107            self.uses.push((id.to_string(), short));
108            if self.uses.len() > USES {
109                self.uses.remove(0);
110            }
111        }
112    }
113
114    /// A compaction: the calls after it rebuild the context, and what was read before is read again for good reason.
115    fn compacted(&mut self, boundary: bool) {
116        // The boundary and the summary that follows it are one compaction; a summary alone (a harness that writes no
117        // boundary) is one too.
118        if boundary || !self.summary_due {
119            self.compactions += 1;
120        }
121        self.summary_due = boundary;
122        self.rebuilt = true;
123        self.cause = "rebuilt".to_string();
124        self.seen.clear();
125    }
126
127    /// A read-only tool called again with the target and range it was called with is a repeat; an edit of a target
128    /// makes the next read of it a new one.
129    fn note_target(&mut self, tool: &str, input: Option<&Value>) {
130        let reads = READS.contains(&tool);
131        if !reads && !WRITES.contains(&tool) {
132            return;
133        }
134        let Some(input) = input.and_then(Value::as_object) else { return };
135        let Some((target_key, target)) = ["file_path", "path", "notebook_path", "url", "pattern"].iter().find_map(|k| Some((*k, input.get(*k)?.as_str()?))) else { return };
136        let hash = |parts: &[&str]| {
137            let mut h = DefaultHasher::new();
138            parts.iter().for_each(|p| p.hash(&mut h));
139            h.finish()
140        };
141        let whole = hash(&[target]);
142        if !reads {
143            self.seen.retain(|(t, _)| *t != whole);
144            return;
145        }
146        // Everything but the target (the range, a search's pattern) is part of the call: reading another part of a file is not a repeat.
147        let rest = input.iter().filter(|(k, _)| k.as_str() != target_key).map(|(k, v)| format!("{k}={v}")).collect::<std::collections::BTreeSet<_>>();
148        let call = hash(&[tool, target, &rest.into_iter().collect::<Vec<_>>().join("&")]);
149        if !self.seen.insert((whole, call)) {
150            self.repeats += 1;
151        }
152        if self.seen.len() > SEEN {
153            self.seen.clear();
154        }
155    }
156
157    fn user(&mut self, v: &Value) {
158        let content = v.pointer("/message/content").and_then(Value::as_array);
159        let result = content.and_then(|c| c.iter().find(|b| b.get("type").and_then(Value::as_str) == Some("tool_result")));
160        if let Some(result) = result {
161            let name = result.get("tool_use_id").and_then(Value::as_str).and_then(|id| self.uses.iter().find(|(i, _)| i == id)).map(|(_, n)| n.clone());
162            self.after_tool(name.filter(|n| !n.is_empty()).map_or_else(|| "tool".to_string(), |n| format!("tool:{n}")));
163            return;
164        }
165        // The summary a compaction leaves is the context being rebuilt, not a fresh message.
166        if v.get("isCompactSummary").and_then(Value::as_bool) == Some(true) {
167            self.compacted(false);
168            return;
169        }
170        let origin = v.pointer("/amx/origin/kind").and_then(Value::as_str).filter(|k| ORIGINS.contains(k));
171        self.rebuilt = false;
172        self.cause = origin.unwrap_or_default().to_string();
173    }
174
175    /// A tool's answer: the calls after a compaction stay `rebuilt` until a fresh message.
176    fn after_tool(&mut self, cause: String) {
177        self.cause = if self.rebuilt { "rebuilt".to_string() } else { cause };
178    }
179}
180
181/// A tool's name as the ledger keeps it: an MCP tool is `mcp__<server>__<tool>`, kept as `<tool>`. None for a name with
182/// anything odd in it, so a cause never holds text.
183fn short_name(name: &str) -> Option<String> {
184    let short = name.rsplit("__").next().unwrap_or(name);
185    (!short.is_empty() && short.len() <= 40 && short.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'))).then(|| short.to_string())
186}
187
188#[cfg(test)]
189#[path = "token_cause_tests.rs"]
190mod tests;