Skip to main content

rhema_transcript/
summary.rs

1//! The extractive line text: what the view says about messages it does
2//! not carry whole.
3//!
4//! Everything here is mechanical, heads and counts read off the
5//! messages themselves. No model call belongs to the transcript in v1
6//! (spec §7.4): the lines cost no latency and cannot be wrong about
7//! what happened, only short. A later compactor replaces exactly the
8//! text generators below; the addresses stay.
9
10use rhema_core::{Content, Message, Role};
11
12use crate::tree::Range;
13
14/// Byte cap on one quoted head inside a line.
15pub const HEAD_BYTES: usize = 160;
16
17/// Byte cap on one structural line covering a range.
18pub const RANGE_HEAD_BYTES: usize = 300;
19
20/// Byte cap on one user message carried whole in a digest. A user's
21/// instruction is the one thing the block must not paraphrase, so it
22/// stands as written up to this size. Past it the head stands and an
23/// explicit marker states the message's full length, so a cut is
24/// visible and worth a `zoom`.
25pub const USER_BYTES: usize = 8 * 1024;
26
27/// The bytes one image costs the budget. A provider tokenizes an image
28/// by its pixels, not by its base64 length: a 228 KB screenshot is
29/// about two thousand tokens, near the top of the range. Charging the
30/// encoded length would count that screenshot as 57 KB of text, and an
31/// image-heavy turn would flush the block over bytes compaction can
32/// never remove. One image is charged as one small message.
33pub const IMAGE_BYTES: usize = 1024;
34
35/// The bytes a message costs the budget: text, tool-call arguments,
36/// and tool-result content, summed, with each image at [`IMAGE_BYTES`]
37/// instead of its encoded length. This is the unit the view's budget
38/// spends.
39pub fn message_bytes(message: &Message) -> usize {
40    message
41        .content
42        .iter()
43        .map(|content| match content {
44            Content::Text(text) => text.len(),
45            Content::ToolCall(call) => call.name.len() + call.args.to_string().len(),
46            Content::ToolResult(result) => result.content.len() + result.images.len() * IMAGE_BYTES,
47            Content::Image(_) => IMAGE_BYTES,
48        })
49        .sum()
50}
51
52/// The tokens one image stands for: a vision price, not a text
53/// length. A flat figure keeps an image-heavy turn from reading as
54/// millions of tokens; the footer's context gauge prices an image the
55/// same way.
56pub const IMAGE_TOKENS: u64 = 1_000;
57
58/// The tokens a run of text stands for: about four bytes per token.
59/// No tokenizer runs this side of the wire, so every token figure the
60/// Usage page shows is this estimate, and the page marks it as one.
61pub fn text_tokens(bytes: usize) -> u64 {
62    bytes as u64 / 4
63}
64
65/// The estimated tokens a message stands for: its text at about four
66/// bytes per token, each image at [`IMAGE_TOKENS`]. Summed part by
67/// part, so the split can price each category with the same rounding.
68pub fn message_tokens(message: &Message) -> u64 {
69    message
70        .content
71        .iter()
72        .map(|content| match content {
73            Content::Text(text) => text_tokens(text.len()),
74            Content::ToolCall(call) => text_tokens(call.name.len() + call.args.to_string().len()),
75            Content::ToolResult(result) => {
76                text_tokens(result.content.len()) + result.images.len() as u64 * IMAGE_TOKENS
77            }
78            Content::Image(_) => IMAGE_TOKENS,
79        })
80        .sum()
81}
82
83/// `text` on one line, at most `cap` bytes, cut on a char boundary
84/// with an ellipsis when longer.
85pub fn head(text: &str, cap: usize) -> String {
86    let flat = one_line(text);
87    if flat.len() <= cap {
88        return flat;
89    }
90    let mut end = cap;
91    while end > 0 && !flat.is_char_boundary(end) {
92        end -= 1;
93    }
94    format!("{}\u{2026}", &flat[..end])
95}
96
97/// A user message as one digest line: every message, whole, on one
98/// line, cut only past [`USER_BYTES`] and then with a marker carrying
99/// the length it lost. The marker matters: text that disappears with
100/// no sign reads as text that was never there.
101fn user_line(text: &str) -> String {
102    let flat = one_line(text);
103    if flat.len() <= USER_BYTES {
104        return flat;
105    }
106    format!("{} [{} B, cut]", head(&flat, USER_BYTES), flat.len())
107}
108
109/// Newlines and tab runs become single spaces: a line is one line.
110pub fn one_line(text: &str) -> String {
111    let mut flat = String::with_capacity(text.len());
112    let mut gap = false;
113    for ch in text.chars() {
114        if ch == '\n' || ch == '\r' || ch == '\t' {
115            gap = true;
116        } else {
117            if gap && !flat.is_empty() {
118                flat.push(' ');
119            }
120            gap = false;
121            flat.push(ch);
122        }
123    }
124    flat
125}
126
127/// The role's label in a line: `user`, `assistant`, `system`,
128/// `result`.
129fn role_label(role: Role) -> &'static str {
130    match role {
131        Role::User => "user",
132        Role::Assistant => "assistant",
133        Role::System => "system",
134        Role::Tool => "result",
135    }
136}
137
138/// The aggregate parts of a multi-message range, before addressing.
139/// Also the body of the extractive section digest
140/// ([`crate::compact::section_digest`]).
141pub(crate) fn summarize_range(messages: &[Message], range: Range) -> ((usize, usize), String) {
142    let mut user_heads: Vec<String> = Vec::new();
143    let mut assistant_heads: Vec<String> = Vec::new();
144    let mut calls: Vec<(String, usize)> = Vec::new();
145    let mut results = 0usize;
146    let mut failures = 0usize;
147
148    // Assistant heads stay a two-line preview: the range's shape is
149    // what a future reader needs. The user's words come whole below.
150    let push_head = |heads: &mut Vec<String>, text: &str| {
151        if heads.len() < 2 {
152            heads.push(head(text, 80));
153        }
154    };
155    for message in &messages[..range.n.min(messages.len())] {
156        for content in &message.content {
157            match content {
158                Content::Text(text) => {
159                    if message.role == Role::User {
160                        user_heads.push(user_line(text));
161                    } else if message.role == Role::Assistant {
162                        push_head(&mut assistant_heads, text);
163                    }
164                }
165                Content::ToolCall(call) => {
166                    if let Some(seen) = calls.iter_mut().find(|(name, _)| *name == call.name) {
167                        seen.1 += 1;
168                    } else {
169                        calls.push((call.name.clone(), 1));
170                    }
171                }
172                Content::ToolResult(result) => {
173                    results += 1;
174                    failures += usize::from(result.is_error);
175                }
176                // A head quotes text; an image has none.
177                Content::Image(_) => {}
178            }
179        }
180    }
181
182    let mut parts: Vec<String> = Vec::new();
183    parts.extend(user_heads.iter().map(|h| format!("user: {h}")));
184    if !calls.is_empty() {
185        calls.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
186        let named: Vec<String> = calls
187            .iter()
188            .take(3)
189            .map(|(name, count)| format!("{name}\u{d7}{count}"))
190            .collect();
191        let mut tool_line = if results == 0 {
192            // Calls the range opens but its results land elsewhere:
193            // say what was called, not that nothing answered.
194            format!(
195                "{} tool {} ({})",
196                calls.iter().map(|(_, n)| n).sum::<usize>(),
197                if calls.iter().map(|(_, n)| n).sum::<usize>() == 1 {
198                    "call"
199                } else {
200                    "calls"
201                },
202                named.join(", ")
203            )
204        } else {
205            format!(
206                "{} tool {} ({})",
207                results,
208                if results == 1 { "result" } else { "results" },
209                named.join(", ")
210            )
211        };
212        if calls.len() > 3 {
213            tool_line.push_str(", \u{2026}");
214        }
215        parts.push(tool_line);
216    } else if results > 0 {
217        parts.push(format!(
218            "{} tool {}",
219            results,
220            if results == 1 { "result" } else { "results" }
221        ));
222    }
223    if failures > 0 {
224        parts.push(format!("{failures} failed"));
225    }
226    parts.extend(assistant_heads.iter().map(|h| format!("assistant: {h}")));
227    ((range.id, range.n), parts.join("; "))
228}
229
230/// The whole render of one message, as `zoom(id, 1)` returns it: user
231/// and assistant text verbatim, tool calls and results spelled out.
232/// Uncapped, the zoom pages.
233pub fn render_message(message: &Message) -> String {
234    let mut out = String::new();
235    for content in &message.content {
236        match content {
237            Content::Text(text) => {
238                if !out.is_empty() {
239                    out.push('\n');
240                }
241                out.push_str(text);
242            }
243            Content::ToolCall(call) => {
244                if !out.is_empty() {
245                    out.push('\n');
246                }
247                out.push_str(&format!("[calls {}({})]", call.name, call.args));
248            }
249            Content::ToolResult(result) => {
250                if !out.is_empty() {
251                    out.push('\n');
252                }
253                out.push_str(&format!(
254                    "[{}: {}]",
255                    if result.is_error { "failed" } else { "ok" },
256                    result.content
257                ));
258                for image in &result.images {
259                    out.push_str(&format!("\n[image: {}]", image.media_type.as_str()));
260                }
261            }
262            Content::Image(image) => {
263                if !out.is_empty() {
264                    out.push('\n');
265                }
266                out.push_str(&format!("[image: {}]", image.media_type.as_str()));
267            }
268        }
269    }
270    if out.is_empty() {
271        out.push_str(&format!("({} message, empty)", role_label(message.role)));
272    }
273    out
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279    use rhema_core::{ToolCall, ToolResult};
280
281    #[test]
282    fn a_results_images_count_and_describe() {
283        let message = Message {
284            role: Role::Tool,
285            content: vec![Content::ToolResult(
286                ToolResult::success("c1", "out").with_images(vec![rhema_core::Image::new(
287                    rhema_core::ImageMediaType::Png,
288                    "cG5n",
289                )]),
290            )],
291        };
292        // "out" plus one image at its flat budget charge, not the
293        // base64 data's four bytes.
294        assert_eq!(message_bytes(&message), 3 + IMAGE_BYTES);
295        let rendered = render_message(&message);
296        assert!(rendered.contains("[image: image/png]"), "{rendered}");
297    }
298
299    #[test]
300    fn tokens_are_text_over_four_plus_a_flat_image_price() {
301        let message = Message {
302            role: Role::Tool,
303            content: vec![Content::ToolResult(
304                ToolResult::success("c1", "abcdefgh").with_images(vec![
305                    rhema_core::Image::new(rhema_core::ImageMediaType::Png, "a".repeat(4_000_000)),
306                    rhema_core::Image::new(rhema_core::ImageMediaType::Png, "b".repeat(8)),
307                ]),
308            )],
309        };
310        // Eight bytes of text is two tokens; the two images are a
311        // flat price each, whatever their base64 length.
312        assert_eq!(message_tokens(&message), 2 + 2 * IMAGE_TOKENS);
313    }
314
315    #[test]
316    fn an_images_encoded_length_does_not_reach_the_budget() {
317        let tiny = Message {
318            role: Role::Tool,
319            content: vec![Content::ToolResult(
320                ToolResult::success("c1", "").with_images(vec![rhema_core::Image::new(
321                    rhema_core::ImageMediaType::Png,
322                    "a".repeat(4_000_000),
323                )]),
324            )],
325        };
326        // Four megabytes of base64 is one message's worth of context.
327        assert_eq!(message_bytes(&tiny), IMAGE_BYTES);
328    }
329
330    #[test]
331    fn every_user_text_gets_a_line_whole() {
332        let mut messages: Vec<Message> = (0..12)
333            .map(|i| Message::text(Role::User, format!("decision {i}: keep this")))
334            .collect();
335        messages.push(Message::text(Role::Assistant, "done"));
336        let (_, text) = summarize_range(&messages, Range { id: 0, n: 13 });
337        for i in 0..12 {
338            assert!(
339                text.contains(&format!("user: decision {i}: keep this")),
340                "{text}"
341            );
342        }
343        assert!(!text.contains("cut"), "{text}");
344    }
345
346    #[test]
347    fn a_user_text_past_the_cap_says_what_it_lost() {
348        let long = "x".repeat(USER_BYTES + 500);
349        let messages = vec![Message::text(Role::User, long)];
350        let (_, text) = summarize_range(&messages, Range { id: 0, n: 1 });
351        // The whole head, then the marker naming the bytes that did
352        // not fit.
353        let head = format!("user: {}", "x".repeat(USER_BYTES));
354        assert!(
355            text.starts_with(&head),
356            "digest starts wrong: {}",
357            &text[..64]
358        );
359        let marker = format!(" [{} B, cut]", USER_BYTES + 500);
360        assert!(
361            text.ends_with(&marker),
362            "digest ends wrong: len {}",
363            text.len()
364        );
365        assert_eq!(text.len(), head.len() + "\u{2026}".len() + marker.len());
366    }
367
368    #[test]
369    fn heads_cut_on_char_boundaries() {
370        // Each 'é' is two bytes; a byte cap of 5 lands mid-char.
371        let text = "ééééé";
372        let h = head(text, 5);
373        // Cap 5 lands mid-char; the cut backs up to the boundary and
374        // the ellipsis rides on top: "éé" + "…".
375        assert_eq!(h, "\u{e9}\u{e9}\u{2026}");
376        assert_eq!(head("short", 10), "short");
377    }
378
379    #[test]
380    fn one_line_flattens_newlines_but_keeps_inner_spaces() {
381        assert_eq!(one_line("a\nb\r\nc\td"), "a b c d");
382        assert_eq!(one_line("\n\nlead"), "lead");
383    }
384
385    #[test]
386    fn bytes_count_text_arguments_and_results() {
387        let call = Message {
388            role: Role::Assistant,
389            content: vec![
390                Content::Text("running".into()),
391                Content::ToolCall(ToolCall {
392                    id: "c1".into(),
393                    name: "bash".into(),
394                    args: serde_json::json!({ "command": "ls" }),
395                    provider_data: serde_json::Value::Null,
396                }),
397            ],
398        };
399        // "running" (7) + "bash" (4) + {"command":"ls"} (16)
400        assert_eq!(message_bytes(&call), 7 + 4 + 16);
401    }
402
403    #[test]
404    fn a_single_message_renders_whole_for_zoom() {
405        let message = Message {
406            role: Role::Assistant,
407            content: vec![
408                Content::Text("step one".into()),
409                Content::ToolCall(ToolCall {
410                    id: "c9".into(),
411                    name: "edit".into(),
412                    args: serde_json::json!({ "path": "a.rs" }),
413                    provider_data: serde_json::Value::Null,
414                }),
415            ],
416        };
417        let out = render_message(&message);
418        assert_eq!(out, "step one\n[calls edit({\"path\":\"a.rs\"})]");
419    }
420}