Skip to main content

agentmux_srv_core/backend/transcript/
kinds.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a conversation's history is made of: how many bytes are the person's and the agent's messages,
5//! jekts, thinking, tool calls and tool results
6//! (`SPEC_CONVERSATION_HISTORY_ONE_TOTAL_AND_COMPRESSION_AT_THE_BOUNDARY_2026_11_30.md` section 3).
7//!
8//! The panel breaks its one total into these kinds. Counting them by decoding the history on every
9//! request would read gigabytes, so each zone keeps a small sidecar, [`SIDECAR`]: for each line-oriented
10//! file (the transcript, the provider's copy, the session files imported whole) the logical bytes
11//! of each kind up to a byte offset, with a fingerprint of the bytes just before that offset. The
12//! owner srv moves the offsets forward a budget at a time ([`step`]), so a file is read once and
13//! afterwards only what was appended since. A file that was rewritten (its fingerprint no longer
14//! matches, or it is shorter than the offset) is counted again from its start.
15//!
16//! Counted in logical bytes, exactly. The panel applies each kind's share to the stored total
17//! (`history_usage.rs`), so the numbers it shows are about, not exact: kinds compress differently.
18
19use std::collections::BTreeMap;
20
21use serde::{Deserialize, Serialize};
22
23use crate::backend::storage::filestore::FileStore;
24
25/// The per-zone file the counts are kept in.
26pub const SIDECAR: &str = "output.kinds";
27
28/// Bytes read and decoded per window while counting.
29const WINDOW: i64 = 1 << 20;
30/// How many bytes before the offset make the fingerprint.
31const FINGERPRINT_BYTES: i64 = 64;
32/// A line this long is counted as `other` without decoding it, so a runaway line cannot hold memory.
33const MAX_LINE_BYTES: usize = 64 << 20;
34/// Bytes a pass counts at most (the owner's loop runs it again every few seconds while work is left).
35pub const STEP_BYTES: i64 = 32 << 20;
36
37/// What a line of a conversation is.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum Kind {
40    /// What a person and the agent said to each other.
41    Messages,
42    /// Messages another agent, a service, a schedule or AgentMux itself sent.
43    Jekts,
44    Thinking,
45    ToolCalls,
46    ToolResults,
47    /// Everything else: system lines, results, rate limits, command lifecycle, fragments.
48    Other,
49}
50
51/// The kinds in the order the panel lists them, with the key each goes by on the wire.
52pub 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/// Logical bytes per kind.
62#[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
164/// What kind of line `line` (one NDJSON record, without its newline) is. A line that is not a
165/// record is `Other`.
166pub 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            // A person (in the pane, or by broadcast) wrote the message unless the record says another
193            // sender did. Lines from before the origin was recorded show a jekt by its marker line.
194            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
209/// Count every complete line of `bytes` into `into`; returns how many bytes that covered, which ends
210/// after the last newline.
211fn 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/// The counts for one file, up to `scanned`.
222#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
223pub struct FileKinds {
224    /// Bytes counted: the start of the first line not counted.
225    #[serde(default)]
226    pub scanned: i64,
227    /// FNV-1a of the [`FINGERPRINT_BYTES`] bytes before `scanned`.
228    #[serde(default)]
229    pub fp: u64,
230    #[serde(default, flatten)]
231    pub bytes: KindBytes,
232}
233
234/// A zone's sidecar: its files' counts by name.
235#[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
245/// Whether the history of `name` is counted: the transcript, the provider's copy of it, and the
246/// session files imported whole from a provider. The sidecars (indexes, the compaction map) and the
247/// other files are not conversation.
248fn 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
256/// The zones that hold history.
257fn 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
263/// Count `name` from where its sidecar entry stands, at most `budget` bytes. Returns the bytes read.
264fn 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/// What a [`step`] did.
297#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
298pub struct StepReport {
299    /// Bytes of history decoded.
300    pub read: i64,
301    /// Every counted file is counted up to its end (but for an unfinished last line).
302    pub done: bool,
303}
304
305/// Count history forward, `budget` bytes at most, a file at a time. Only the srv that owns the store
306/// calls this; the sidecar is written once per zone, and only when it changed.
307pub 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            // The budget ran out before the last zone: more may be left.
312            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            // Nothing is counted here any more (the conversation was archived): its counts go too.
319            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            // The budget ended this file's count: the next step goes on (once more at most if it ended exactly at the end).
340            report.done &= read < room;
341            // A last line with no newline yet is read again each pass and changes nothing: no write for that.
342            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
358/// The counted bytes of every zone, by kind, and how many bytes they cover.
359pub 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;