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/// The images one message holds: tool-result images and bare image
84/// parts. The count the view's image cap spends, and nothing else:
85/// an image's bytes and tokens are the flat charges above.
86pub fn message_images(message: &Message) -> usize {
87    message
88        .content
89        .iter()
90        .map(|content| match content {
91            Content::ToolResult(result) => result.images.len(),
92            Content::Image(_) => 1,
93            _ => 0,
94        })
95        .sum()
96}
97
98/// `text` on one line, at most `cap` bytes, cut on a char boundary
99/// with an ellipsis when longer.
100pub fn head(text: &str, cap: usize) -> String {
101    let flat = one_line(text);
102    if flat.len() <= cap {
103        return flat;
104    }
105    let mut end = cap;
106    while end > 0 && !flat.is_char_boundary(end) {
107        end -= 1;
108    }
109    format!("{}\u{2026}", &flat[..end])
110}
111
112/// A user message as one digest line: every message, whole, on one
113/// line, cut only past [`USER_BYTES`] and then with a marker carrying
114/// the length it lost. The marker matters: text that disappears with
115/// no sign reads as text that was never there.
116fn user_line(text: &str) -> String {
117    let flat = one_line(text);
118    if flat.len() <= USER_BYTES {
119        return flat;
120    }
121    format!("{} [{} B, cut]", head(&flat, USER_BYTES), flat.len())
122}
123
124/// Newlines and tab runs become single spaces: a line is one line.
125pub fn one_line(text: &str) -> String {
126    let mut flat = String::with_capacity(text.len());
127    let mut gap = false;
128    for ch in text.chars() {
129        if ch == '\n' || ch == '\r' || ch == '\t' {
130            gap = true;
131        } else {
132            if gap && !flat.is_empty() {
133                flat.push(' ');
134            }
135            gap = false;
136            flat.push(ch);
137        }
138    }
139    flat
140}
141
142/// The role's label in a line: `user`, `assistant`, `system`,
143/// `result`.
144fn role_label(role: Role) -> &'static str {
145    match role {
146        Role::User => "user",
147        Role::Assistant => "assistant",
148        Role::System => "system",
149        Role::Tool => "result",
150    }
151}
152
153/// The aggregate parts of a multi-message range, before addressing.
154/// Also the body of the extractive section digest
155/// ([`crate::compact::section_digest`]).
156pub(crate) fn summarize_range(messages: &[Message], range: Range) -> ((usize, usize), String) {
157    let mut user_heads: Vec<String> = Vec::new();
158    let mut assistant_heads: Vec<String> = Vec::new();
159    let mut calls: Vec<(String, usize)> = Vec::new();
160    let mut results = 0usize;
161    let mut failures = 0usize;
162    let mut images = 0usize;
163
164    // Assistant heads stay a two-line preview: the range's shape is
165    // what a future reader needs. The user's words come whole below.
166    let push_head = |heads: &mut Vec<String>, text: &str| {
167        if heads.len() < 2 {
168            heads.push(head(text, 80));
169        }
170    };
171    for message in &messages[..range.n.min(messages.len())] {
172        for content in &message.content {
173            match content {
174                Content::Text(text) => {
175                    if message.role == Role::User {
176                        user_heads.push(user_line(text));
177                    } else if message.role == Role::Assistant {
178                        push_head(&mut assistant_heads, text);
179                    }
180                }
181                Content::ToolCall(call) => {
182                    if let Some(seen) = calls.iter_mut().find(|(name, _)| *name == call.name) {
183                        seen.1 += 1;
184                    } else {
185                        calls.push((call.name.clone(), 1));
186                    }
187                }
188                Content::ToolResult(result) => {
189                    results += 1;
190                    failures += usize::from(result.is_error);
191                    images += result.images.len();
192                }
193                // A head quotes text; an image has none. It still
194                // counts: a digest that skips the images it covers
195                // hides what zoom is there to reopen.
196                Content::Image(_) => images += 1,
197            }
198        }
199    }
200
201    let mut parts: Vec<String> = Vec::new();
202    parts.extend(user_heads.iter().map(|h| format!("user: {h}")));
203    if !calls.is_empty() {
204        calls.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
205        let named: Vec<String> = calls
206            .iter()
207            .take(3)
208            .map(|(name, count)| format!("{name}\u{d7}{count}"))
209            .collect();
210        let mut tool_line = if results == 0 {
211            // Calls the range opens but its results land elsewhere:
212            // say what was called, not that nothing answered.
213            format!(
214                "{} tool {} ({})",
215                calls.iter().map(|(_, n)| n).sum::<usize>(),
216                if calls.iter().map(|(_, n)| n).sum::<usize>() == 1 {
217                    "call"
218                } else {
219                    "calls"
220                },
221                named.join(", ")
222            )
223        } else {
224            format!(
225                "{} tool {} ({})",
226                results,
227                if results == 1 { "result" } else { "results" },
228                named.join(", ")
229            )
230        };
231        if calls.len() > 3 {
232            tool_line.push_str(", \u{2026}");
233        }
234        parts.push(tool_line);
235    } else if results > 0 {
236        parts.push(format!(
237            "{} tool {}",
238            results,
239            if results == 1 { "result" } else { "results" }
240        ));
241    }
242    if failures > 0 {
243        parts.push(format!("{failures} failed"));
244    }
245    if images > 0 {
246        parts.push(format!(
247            "{images} {}",
248            if images == 1 { "image" } else { "images" }
249        ));
250    }
251    parts.extend(assistant_heads.iter().map(|h| format!("assistant: {h}")));
252    ((range.id, range.n), parts.join("; "))
253}
254
255/// The whole render of one message, as `zoom(id, 1)` returns it: user
256/// and assistant text verbatim, tool calls and results spelled out.
257/// Uncapped, the zoom pages.
258pub fn render_message(message: &Message) -> String {
259    let mut out = String::new();
260    for content in &message.content {
261        match content {
262            Content::Text(text) => {
263                if !out.is_empty() {
264                    out.push('\n');
265                }
266                out.push_str(text);
267            }
268            Content::ToolCall(call) => {
269                if !out.is_empty() {
270                    out.push('\n');
271                }
272                out.push_str(&format!("[calls {}({})]", call.name, call.args));
273            }
274            Content::ToolResult(result) => {
275                if !out.is_empty() {
276                    out.push('\n');
277                }
278                out.push_str(&format!(
279                    "[{}: {}]",
280                    if result.is_error { "failed" } else { "ok" },
281                    result.content
282                ));
283                for image in &result.images {
284                    out.push_str(&format!("\n[image: {}]", image.media_type.as_str()));
285                }
286            }
287            Content::Image(image) => {
288                if !out.is_empty() {
289                    out.push('\n');
290                }
291                out.push_str(&format!("[image: {}]", image.media_type.as_str()));
292            }
293        }
294    }
295    if out.is_empty() {
296        out.push_str(&format!("({} message, empty)", role_label(message.role)));
297    }
298    out
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304    use rhema_core::{ToolCall, ToolResult};
305
306    #[test]
307    fn a_results_images_count_and_describe() {
308        let message = Message {
309            annotations: Default::default(),
310            role: Role::Tool,
311            content: vec![Content::ToolResult(
312                ToolResult::success("c1", "out").with_images(vec![rhema_core::Image::new(
313                    rhema_core::ImageMediaType::Png,
314                    "cG5n",
315                )]),
316            )],
317        };
318        // "out" plus one image at its flat budget charge, not the
319        // base64 data's four bytes.
320        assert_eq!(message_bytes(&message), 3 + IMAGE_BYTES);
321        let rendered = render_message(&message);
322        assert!(rendered.contains("[image: image/png]"), "{rendered}");
323    }
324
325    #[test]
326    fn tokens_are_text_over_four_plus_a_flat_image_price() {
327        let message = Message {
328            annotations: Default::default(),
329            role: Role::Tool,
330            content: vec![Content::ToolResult(
331                ToolResult::success("c1", "abcdefgh").with_images(vec![
332                    rhema_core::Image::new(rhema_core::ImageMediaType::Png, "a".repeat(4_000_000)),
333                    rhema_core::Image::new(rhema_core::ImageMediaType::Png, "b".repeat(8)),
334                ]),
335            )],
336        };
337        // Eight bytes of text is two tokens; the two images are a
338        // flat price each, whatever their base64 length.
339        assert_eq!(message_tokens(&message), 2 + 2 * IMAGE_TOKENS);
340    }
341
342    /// The cap's unit: tool-result images and bare image parts count,
343    /// text does not. The digest names the same figure, so a range's
344    /// line says what zoom would bring back.
345    #[test]
346    fn the_image_count_is_its_own_figure() {
347        let user = Message {
348            annotations: Default::default(),
349            role: Role::User,
350            content: vec![
351                Content::Text("look".into()),
352                Content::Image(rhema_core::Image::new(
353                    rhema_core::ImageMediaType::Png,
354                    "cG5n",
355                )),
356            ],
357        };
358        let result = Message {
359            annotations: Default::default(),
360            role: Role::Tool,
361            content: vec![Content::ToolResult(
362                ToolResult::success("c1", "out").with_images(vec![
363                    rhema_core::Image::new(rhema_core::ImageMediaType::Png, "YQ"),
364                    rhema_core::Image::new(rhema_core::ImageMediaType::Png, "Yg"),
365                ]),
366            )],
367        };
368        assert_eq!(message_images(&user), 1);
369        assert_eq!(message_images(&result), 2);
370        let messages = vec![user, result];
371        let ((id, n), text) = summarize_range(&messages, Range { id: 0, n: 2 });
372        assert_eq!((id, n), (0, 2));
373        assert!(text.contains("3 images"), "{text}");
374    }
375
376    #[test]
377    fn an_images_encoded_length_does_not_reach_the_budget() {
378        let tiny = Message {
379            annotations: Default::default(),
380            role: Role::Tool,
381            content: vec![Content::ToolResult(
382                ToolResult::success("c1", "").with_images(vec![rhema_core::Image::new(
383                    rhema_core::ImageMediaType::Png,
384                    "a".repeat(4_000_000),
385                )]),
386            )],
387        };
388        // Four megabytes of base64 is one message's worth of context.
389        assert_eq!(message_bytes(&tiny), IMAGE_BYTES);
390    }
391
392    #[test]
393    fn every_user_text_gets_a_line_whole() {
394        let mut messages: Vec<Message> = (0..12)
395            .map(|i| Message::text(Role::User, format!("decision {i}: keep this")))
396            .collect();
397        messages.push(Message::text(Role::Assistant, "done"));
398        let (_, text) = summarize_range(&messages, Range { id: 0, n: 13 });
399        for i in 0..12 {
400            assert!(
401                text.contains(&format!("user: decision {i}: keep this")),
402                "{text}"
403            );
404        }
405        assert!(!text.contains("cut"), "{text}");
406    }
407
408    #[test]
409    fn a_user_text_past_the_cap_says_what_it_lost() {
410        let long = "x".repeat(USER_BYTES + 500);
411        let messages = vec![Message::text(Role::User, long)];
412        let (_, text) = summarize_range(&messages, Range { id: 0, n: 1 });
413        // The whole head, then the marker naming the bytes that did
414        // not fit.
415        let head = format!("user: {}", "x".repeat(USER_BYTES));
416        assert!(
417            text.starts_with(&head),
418            "digest starts wrong: {}",
419            &text[..64]
420        );
421        let marker = format!(" [{} B, cut]", USER_BYTES + 500);
422        assert!(
423            text.ends_with(&marker),
424            "digest ends wrong: len {}",
425            text.len()
426        );
427        assert_eq!(text.len(), head.len() + "\u{2026}".len() + marker.len());
428    }
429
430    #[test]
431    fn heads_cut_on_char_boundaries() {
432        // Each 'é' is two bytes; a byte cap of 5 lands mid-char.
433        let text = "ééééé";
434        let h = head(text, 5);
435        // Cap 5 lands mid-char; the cut backs up to the boundary and
436        // the ellipsis rides on top: "éé" + "…".
437        assert_eq!(h, "\u{e9}\u{e9}\u{2026}");
438        assert_eq!(head("short", 10), "short");
439    }
440
441    #[test]
442    fn one_line_flattens_newlines_but_keeps_inner_spaces() {
443        assert_eq!(one_line("a\nb\r\nc\td"), "a b c d");
444        assert_eq!(one_line("\n\nlead"), "lead");
445    }
446
447    #[test]
448    fn bytes_count_text_arguments_and_results() {
449        let call = Message {
450            annotations: Default::default(),
451            role: Role::Assistant,
452            content: vec![
453                Content::Text("running".into()),
454                Content::ToolCall(ToolCall {
455                    id: "c1".into(),
456                    name: "bash".into(),
457                    args: serde_json::json!({ "command": "ls" }),
458                    provider_data: serde_json::Value::Null,
459                }),
460            ],
461        };
462        // "running" (7) + "bash" (4) + {"command":"ls"} (16)
463        assert_eq!(message_bytes(&call), 7 + 4 + 16);
464    }
465
466    #[test]
467    fn a_single_message_renders_whole_for_zoom() {
468        let message = Message {
469            annotations: Default::default(),
470            role: Role::Assistant,
471            content: vec![
472                Content::Text("step one".into()),
473                Content::ToolCall(ToolCall {
474                    id: "c9".into(),
475                    name: "edit".into(),
476                    args: serde_json::json!({ "path": "a.rs" }),
477                    provider_data: serde_json::Value::Null,
478                }),
479            ],
480        };
481        let out = render_message(&message);
482        assert_eq!(out, "step one\n[calls edit({\"path\":\"a.rs\"})]");
483    }
484}