agentmux_srv_core/backend/transcript/
kinds.rs1use std::collections::BTreeMap;
20
21use serde::{Deserialize, Serialize};
22
23use crate::backend::storage::filestore::FileStore;
24
25pub const SIDECAR: &str = "output.kinds";
27
28const WINDOW: i64 = 1 << 20;
30const FINGERPRINT_BYTES: i64 = 64;
32const MAX_LINE_BYTES: usize = 64 << 20;
34pub const STEP_BYTES: i64 = 32 << 20;
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum Kind {
40 Messages,
42 Jekts,
44 Thinking,
45 ToolCalls,
46 ToolResults,
47 Other,
49}
50
51pub const KINDS: [(Kind, &str); 6] = [
53 (Kind::Messages, "messages"),
54 (Kind::Jekts, "jekts"),
55 (Kind::Thinking, "thinking"),
56 (Kind::ToolCalls, "tool_calls"),
57 (Kind::ToolResults, "tool_results"),
58 (Kind::Other, "other"),
59];
60
61#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
63pub struct KindBytes {
64 #[serde(default)]
65 pub messages: u64,
66 #[serde(default)]
67 pub jekts: u64,
68 #[serde(default)]
69 pub thinking: u64,
70 #[serde(default)]
71 pub tool_calls: u64,
72 #[serde(default)]
73 pub tool_results: u64,
74 #[serde(default)]
75 pub other: u64,
76}
77
78impl KindBytes {
79 pub fn add(&mut self, kind: Kind, bytes: u64) {
80 *self.slot(kind) += bytes;
81 }
82
83 pub fn get(&self, kind: Kind) -> u64 {
84 match kind {
85 Kind::Messages => self.messages,
86 Kind::Jekts => self.jekts,
87 Kind::Thinking => self.thinking,
88 Kind::ToolCalls => self.tool_calls,
89 Kind::ToolResults => self.tool_results,
90 Kind::Other => self.other,
91 }
92 }
93
94 fn slot(&mut self, kind: Kind) -> &mut u64 {
95 match kind {
96 Kind::Messages => &mut self.messages,
97 Kind::Jekts => &mut self.jekts,
98 Kind::Thinking => &mut self.thinking,
99 Kind::ToolCalls => &mut self.tool_calls,
100 Kind::ToolResults => &mut self.tool_results,
101 Kind::Other => &mut self.other,
102 }
103 }
104
105 pub fn sum(&self) -> u64 {
106 KINDS.iter().map(|(k, _)| self.get(*k)).sum()
107 }
108
109 fn merge(&mut self, other: &KindBytes) {
110 for (k, _) in KINDS {
111 self.add(k, other.get(k));
112 }
113 }
114}
115
116#[derive(Deserialize)]
117struct Line {
118 #[serde(rename = "type", default)]
119 kind: Option<String>,
120 #[serde(default)]
121 message: Option<Message>,
122 #[serde(default)]
123 amx: Option<Amx>,
124}
125
126#[derive(Deserialize)]
127#[serde(untagged)]
128enum Message {
129 Object {
130 #[serde(default)]
131 content: Option<Content>,
132 },
133 Other(serde::de::IgnoredAny),
134}
135
136#[derive(Deserialize)]
137#[serde(untagged)]
138enum Content {
139 Blocks(Vec<Block>),
140 Text(String),
141 Other(serde::de::IgnoredAny),
142}
143
144#[derive(Deserialize)]
145struct Block {
146 #[serde(rename = "type", default)]
147 kind: Option<String>,
148 #[serde(default)]
149 text: Option<String>,
150}
151
152#[derive(Deserialize)]
153struct Amx {
154 #[serde(default)]
155 origin: Option<Origin>,
156}
157
158#[derive(Deserialize)]
159struct Origin {
160 #[serde(default)]
161 kind: Option<String>,
162}
163
164pub fn classify(line: &[u8]) -> Kind {
167 let Ok(rec) = serde_json::from_slice::<Line>(line) else { return Kind::Other };
168 let blocks: &[Block] = match rec.message.as_ref() {
169 Some(Message::Object { content: Some(Content::Blocks(b)) }) => b,
170 _ => &[],
171 };
172 let has = |name: &str| blocks.iter().any(|b| b.kind.as_deref() == Some(name));
173 match rec.kind.as_deref() {
174 Some("assistant") => {
175 if has("tool_use") {
176 Kind::ToolCalls
177 } else if has("thinking") || has("redacted_thinking") {
178 Kind::Thinking
179 } else {
180 Kind::Messages
181 }
182 }
183 Some("user") => {
184 if has("tool_result") {
185 return Kind::ToolResults;
186 }
187 let origin = rec.amx.as_ref().and_then(|a| a.origin.as_ref()).and_then(|o| o.kind.as_deref());
188 let text = match rec.message.as_ref() {
189 Some(Message::Object { content: Some(Content::Text(t)) }) => Some(t.as_str()),
190 _ => blocks.iter().find_map(|b| b.text.as_deref()),
191 };
192 let jekt = match origin {
195 Some("user" | "broadcast") => false,
196 Some(_) => true,
197 None => text.is_some_and(|t| t.starts_with("[JEKT:")),
198 };
199 if jekt {
200 Kind::Jekts
201 } else {
202 Kind::Messages
203 }
204 }
205 _ => Kind::Other,
206 }
207}
208
209fn count_lines(bytes: &[u8], into: &mut KindBytes) -> usize {
212 let mut covered = 0;
213 while let Some(end) = bytes[covered..].iter().position(|&b| b == b'\n') {
214 let line = &bytes[covered..covered + end];
215 into.add(classify(line), end as u64 + 1);
216 covered += end + 1;
217 }
218 covered
219}
220
221#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
223pub struct FileKinds {
224 #[serde(default)]
226 pub scanned: i64,
227 #[serde(default)]
229 pub fp: u64,
230 #[serde(default, flatten)]
231 pub bytes: KindBytes,
232}
233
234#[derive(Debug, Clone, Default, Serialize, Deserialize)]
236struct ZoneKinds {
237 #[serde(default)]
238 files: BTreeMap<String, FileKinds>,
239}
240
241fn fnv(bytes: &[u8]) -> u64 {
242 bytes.iter().fold(0xcbf29ce484222325u64, |h, &b| (h ^ u64::from(b)).wrapping_mul(0x100000001b3))
243}
244
245fn counts(name: &str) -> bool {
249 name == "output" || name == "output.provider" || (name.starts_with("import/") && name.ends_with(".jsonl"))
250}
251
252fn read_zone(store: &FileStore, zone: &str) -> ZoneKinds {
253 store.read_file(zone, SIDECAR).ok().flatten().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
254}
255
256fn zones(store: &FileStore) -> Vec<String> {
258 let mut all = store.zone_ids_with_prefix("agent:").unwrap_or_default();
259 all.extend(store.zone_ids_with_prefix("agent-uid:").unwrap_or_default());
260 all
261}
262
263fn advance(store: &FileStore, zone: &str, name: &str, size: i64, entry: &mut FileKinds, budget: i64) -> i64 {
265 let fingerprint = |upto: i64| -> Option<u64> {
266 let from = (upto - FINGERPRINT_BYTES).max(0);
267 store.read_bytes_db(zone, name, from, upto - from).ok().map(|b| fnv(&b))
268 };
269 if entry.scanned > size || (entry.scanned > 0 && fingerprint(entry.scanned) != Some(entry.fp)) {
270 *entry = FileKinds::default();
271 }
272 let mut read = 0;
273 let mut carry: Vec<u8> = Vec::new();
274 let mut pos = entry.scanned;
275 while pos < size && read < budget {
276 let len = WINDOW.min(size - pos);
277 let Ok(chunk) = store.read_bytes_db(zone, name, pos, len) else { break };
278 pos += len;
279 read += len;
280 carry.extend_from_slice(&chunk);
281 let covered = count_lines(&carry, &mut entry.bytes);
282 entry.scanned += covered as i64;
283 carry.drain(..covered);
284 if carry.len() > MAX_LINE_BYTES {
285 entry.bytes.add(Kind::Other, carry.len() as u64);
286 entry.scanned += carry.len() as i64;
287 carry.clear();
288 }
289 }
290 if read > 0 {
291 entry.fp = fingerprint(entry.scanned).unwrap_or(0);
292 }
293 read
294}
295
296#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
298pub struct StepReport {
299 pub read: i64,
301 pub done: bool,
303}
304
305pub fn step(store: &FileStore, budget: i64) -> StepReport {
308 let mut report = StepReport { read: 0, done: true };
309 for zone in zones(store) {
310 if report.read >= budget {
311 report.done = false;
313 break;
314 }
315 let Ok(files) = store.list_files(&zone) else { continue };
316 let wanted: Vec<_> = files.iter().filter(|f| counts(&f.name)).collect();
317 if wanted.is_empty() {
318 if files.iter().any(|f| f.name == SIDECAR) {
320 if let Err(e) = store.delete_files(&zone, &[SIDECAR]) {
321 tracing::warn!(zone = %zone, error = %e, "history kinds: couldn't remove the counts of a zone with nothing counted");
322 }
323 }
324 continue;
325 }
326 let mut sidecar = read_zone(store, &zone);
327 let mut changed = false;
328 sidecar.files.retain(|name, _| {
329 let keep = wanted.iter().any(|f| &f.name == name);
330 changed |= !keep;
331 keep
332 });
333 for file in wanted {
334 let entry = sidecar.files.entry(file.name.clone()).or_default();
335 let before = *entry;
336 let room = budget - report.read;
337 let read = advance(store, &zone, &file.name, file.size, entry, room);
338 report.read += read;
339 report.done &= read < room;
341 changed |= *entry != before;
343 }
344 if changed {
345 match serde_json::to_vec(&sidecar) {
346 Ok(json) => {
347 if let Err(e) = store.replace_file(&zone, SIDECAR, &json, &[]) {
348 tracing::warn!(zone = %zone, error = %e, "history kinds: couldn't write the counts");
349 }
350 }
351 Err(e) => tracing::warn!(error = %e, "history kinds: couldn't encode the counts"),
352 }
353 }
354 }
355 report
356}
357
358pub fn totals(store: &FileStore) -> KindBytes {
360 let mut total = KindBytes::default();
361 for zone in zones(store) {
362 for entry in read_zone(store, &zone).files.values() {
363 total.merge(&entry.bytes);
364 }
365 }
366 total
367}
368
369#[cfg(test)]
370#[path = "kinds_tests.rs"]
371mod tests;