agentmux_srv_core/backend/
token_cause.rs1use std::collections::hash_map::DefaultHasher;
23use std::collections::HashSet;
24use std::hash::{Hash, Hasher};
25
26use serde_json::Value;
27
28const USES: usize = 64;
30const LINE_MAX: usize = 2 * 1024 * 1024;
32const SEEN: usize = 512;
34const READS: [&str; 5] = ["Read", "Grep", "Glob", "WebFetch", "NotebookRead"];
36const WRITES: [&str; 4] = ["Edit", "Write", "MultiEdit", "NotebookEdit"];
38const ORIGINS: [&str; 8] = ["user", "broadcast", "agent", "service", "schedule", "task", "supervisor", "system"];
40
41pub 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 uses: Vec<(String, String)>,
52 seen: HashSet<(u64, u64)>,
54 repeats: u64,
55 compactions: u64,
56 summary_due: bool,
58}
59
60impl CauseState {
61 pub fn cause(&self) -> &str {
63 &self.cause
64 }
65
66 pub fn take_waste(&mut self) -> (u64, u64) {
68 (std::mem::take(&mut self.repeats), std::mem::take(&mut self.compactions))
69 }
70
71 pub fn see(&mut self, line: &str) {
73 if line.len() > LINE_MAX {
74 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 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 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 fn compacted(&mut self, boundary: bool) {
116 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 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 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 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 fn after_tool(&mut self, cause: String) {
177 self.cause = if self.rebuilt { "rebuilt".to_string() } else { cause };
178 }
179}
180
181fn 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;