Skip to main content

eclipse_core/
context.rs

1//! Context-window management: bound what is sent to the model per request.
2//!
3//! Sizes are **estimates** (characters / 4, rounded up, plus a few tokens of per-message
4//! framing). Real tokenizers differ by model and language (CJK text and code are usually
5//! far more tokens per character), so treat the budget as a coarse safety rail, not a
6//! guarantee that the endpoint will accept the request.
7//!
8//! Trimming drops whole *turns* (a user message and everything the agent did in answer,
9//! tool calls and their results included) from the oldest end, so a tool call is never
10//! separated from its result. The system prompt and the tool definitions are always
11//! sent, and the latest turn is always kept, even if it alone exceeds the budget. The
12//! stored session is not modified; only the request is shortened.
13//!
14//! What replaces the dropped turns in the system prompt is the compiled handoff
15//! ([`crate::compact`]) and, under it, [`compiled_tail`]'s note about what was left out. The
16//! budget itself uses a character heuristic, so it is a rail rather than a promise: the
17//! handoff's own size is bounded separately by `[context] handoff_chars`.
18
19use crate::message::{Message, Role};
20
21/// Rough per-message overhead (role, separators) in tokens.
22const MESSAGE_OVERHEAD: usize = 4;
23
24/// What one picture costs, before its description is counted.
25///
26/// A picture is not characters. The wire carries a data URL whose base64 length says nothing about
27/// the tokens a model spends on the pixels — a 2 MB JPEG is 2.7 M characters and roughly a thousand
28/// tokens — so counting the URL would overcharge by three orders of magnitude while counting nothing
29/// (which is what this did) lets a native turn grow the window past the budget with no compaction
30/// planned. A flat charge is coarse on purpose and errs high: the estimate only has to plan a
31/// compaction before a request is refused.
32const PICTURE_TOKENS: usize = 900;
33
34pub fn estimate_text_tokens(text: &str) -> usize {
35    text.chars().count().div_ceil(4)
36}
37
38pub fn estimate_message_tokens(m: &Message) -> usize {
39    let mut chars = m.content.as_deref().map_or(0, |c| c.chars().count());
40    for call in &m.tool_calls {
41        chars += call.id.chars().count()
42            + call.function.name.chars().count()
43            + call.function.arguments.chars().count();
44    }
45    let mut tokens = chars.div_ceil(4) + MESSAGE_OVERHEAD;
46    for picture in &m.images {
47        tokens += PICTURE_TOKENS;
48        // The name rides in the request beside the picture, and a stored description is re-sent as
49        // text on a turn that reads it (`#346`) — both are charged where they are spent.
50        tokens += estimate_text_tokens(&picture.name);
51        if let Some(seen) = &picture.seen {
52            tokens += estimate_text_tokens(seen);
53        }
54    }
55    tokens
56}
57
58/// What [`trim_to_budget`] did.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub struct Trimmed {
61    pub turns: usize,
62    pub messages: usize,
63}
64
65/// The note placed in the system prompt in place of dropped turns.
66pub fn trim_note(t: Trimmed) -> String {
67    format!(
68        "[trimmed {} older turn{} ({} message{}) to fit the context budget; \
69         earlier conversation is not shown]",
70        t.turns,
71        if t.turns == 1 { "" } else { "s" },
72        t.messages,
73        if t.messages == 1 { "" } else { "s" },
74    )
75}
76
77/// The line under a compiled handoff: how much it stands in for, and that the handoff itself is
78/// what replaced it — "earlier conversation is not shown" would be a lie once it is.
79pub fn compiled_tail(t: Trimmed) -> String {
80    format!(
81        "[compiled {} older turn{} ({} message{}) into the handoff above; every [#N] row is still \
82         in the session and one session_search away]",
83        t.turns,
84        if t.turns == 1 { "" } else { "s" },
85        t.messages,
86        if t.messages == 1 { "" } else { "s" },
87    )
88}
89
90/// How many turns stay verbatim at the tail when a request has to be shortened. A turn is
91/// a user message and everything the agent did in answer, so twenty is a lot of live state.
92pub const DEFAULT_PROTECT_LAST_N: usize = 20;
93
94/// Which parts of the history a request keeps once it no longer fits: the first turn
95/// (the ask, verbatim — it is the goal, and a summary of it is a guess), the last
96/// `protect_last_n` turns (the live state), and nothing in between.
97///
98/// `history[..head_end]` and `history[tail_start..]` are sent; `history[head_end..tail_start]`
99/// is what does not fit — dropped by [`trim_to_budget`], compiled by the compaction pass.
100/// Nothing is dropped when `tail_start == head_end` (including both zero, which is how "the
101/// whole history fits" is spelled).
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
103pub struct Windows {
104    pub head_end: usize,
105    pub tail_start: usize,
106    pub dropped: Trimmed,
107}
108
109impl Windows {
110    /// True when a request would leave something out.
111    pub fn drops_anything(&self) -> bool {
112        self.tail_start > self.head_end
113    }
114
115    /// The turns that are not sent verbatim.
116    pub fn dropped(&self) -> std::ops::Range<usize> {
117        self.head_end..self.tail_start
118    }
119}
120
121/// Turn starts: the index of every user message, and 0 if the history does not begin with
122/// one (anything before the first user message belongs to the first turn).
123fn turn_starts(history: &[Message]) -> Vec<usize> {
124    let mut starts: Vec<usize> = history
125        .iter()
126        .enumerate()
127        .filter(|(_, m)| m.role == Role::User)
128        .map(|(i, _)| i)
129        .collect();
130    if starts.first() != Some(&0) {
131        starts.insert(0, 0);
132    }
133    starts
134}
135
136fn turn_cost(history: &[Message], starts: &[usize], n: usize) -> usize {
137    let end = starts.get(n + 1).copied().unwrap_or(history.len());
138    history[starts[n]..end]
139        .iter()
140        .map(estimate_message_tokens)
141        .sum()
142}
143
144/// Plan the three windows for one request. Pure arithmetic, no messages are built.
145///
146/// A `budget_tokens` of 0 disables it all; `fixed_tokens` (the tool definitions) counts
147/// against the budget. A history that fits is sent untouched. Past the budget the tail is
148/// filled newest-first — at most `protect_last_n` turns — and the first turn is kept when
149/// there is room for both.
150///
151/// The tail has priority, with one reservation: when the first turn costs no more than half
152/// the budget it is paid for first, so a conversation with slack keeps its goal instead of
153/// spending the last of it on one more recent turn. A first turn that costs more than half
154/// the budget is not reserved for — an enormous pasted prompt is not worth starving the live
155/// state for — and the tail then takes what it can, which is the oldest-turns-go behaviour
156/// this replaced. A turn is never split, so a tool call cannot be separated from its result.
157/// The plan a manual compaction asks for: keep the first turn and the newest `protect_last_n`
158/// turns verbatim and replace everything between them with the handoff, whether or not the
159/// request would have fitted. It is the same calculation with the budget taken out of the
160/// decision, which is why it cannot drift from [`plan_windows`].
161pub fn plan_forced(system: &Message, history: &[Message], protect_last_n: usize) -> Windows {
162    // Half of `usize::MAX` rather than the maximum: the planner adds the tail cost to the used
163    // count, and a budget that cannot be reached must not be one that can overflow.
164    plan_windows(system, history, usize::MAX / 2, 0, protect_last_n)
165}
166
167pub fn plan_windows(
168    system: &Message,
169    history: &[Message],
170    budget_tokens: usize,
171    fixed_tokens: usize,
172    protect_last_n: usize,
173) -> Windows {
174    let nothing = Windows::default();
175    if budget_tokens == 0 || history.is_empty() {
176        return nothing;
177    }
178    let used = estimate_message_tokens(system) + fixed_tokens;
179    let total: usize = history.iter().map(estimate_message_tokens).sum();
180    if used + total <= budget_tokens {
181        return nothing;
182    }
183    let starts = turn_starts(history);
184    // One turn is the whole conversation: the latest turn is never sacrificed, so there is
185    // nothing to choose between.
186    if starts.len() < 2 {
187        return nothing;
188    }
189
190    let first_end = starts[1];
191    let head_cost: usize = history[..first_end]
192        .iter()
193        .map(estimate_message_tokens)
194        .sum();
195    // The ask is paid for first only when it is not the whole point of the budget.
196    let reserve = if head_cost * 2 <= budget_tokens {
197        head_cost
198    } else {
199        0
200    };
201
202    let mut tail_start = history.len();
203    let mut tail_used = used;
204    let keep = protect_last_n.max(1);
205    for n in (0..starts.len()).rev() {
206        if starts.len() - n > keep {
207            break;
208        }
209        let cost = turn_cost(history, &starts, n);
210        // The newest turn is kept unconditionally; older ones only while they fit.
211        if tail_start != history.len() && tail_used + cost + reserve > budget_tokens {
212            break;
213        }
214        tail_used += cost;
215        tail_start = starts[n];
216    }
217
218    let head_end =
219        if reserve > 0 && first_end <= tail_start && head_cost + tail_used <= budget_tokens {
220            first_end
221        } else {
222            0
223        };
224    if head_end >= tail_start {
225        return nothing;
226    }
227    Windows {
228        head_end,
229        tail_start,
230        dropped: Trimmed {
231            turns: starts
232                .iter()
233                .filter(|&&s| s >= head_end && s < tail_start)
234                .count(),
235            messages: tail_start - head_end,
236        },
237    }
238}
239
240/// The request messages: `system` (with `note` appended when given), the head of the history
241/// and then the tail, with the dropped middle left out.
242pub fn assemble(
243    system: &Message,
244    history: &[Message],
245    windows: Windows,
246    note: Option<&str>,
247) -> Vec<Message> {
248    let mut sys = system.clone();
249    if let Some(note) = note {
250        sys.content = Some(match sys.content.take() {
251            Some(c) if !c.is_empty() => format!("{c}\n\n{note}"),
252            _ => note.to_string(),
253        });
254    }
255    let head = &history[..windows.head_end.min(history.len())];
256    let tail = &history[windows.tail_start.min(history.len())..];
257    let mut v = Vec::with_capacity(1 + head.len() + tail.len());
258    v.push(sys);
259    v.extend_from_slice(head);
260    v.extend_from_slice(tail);
261    v
262}
263
264/// Build the request messages: `system`, then as many of the most recent turns of
265/// `history` as fit in `budget_tokens` (after `fixed_tokens`, e.g. the tool definitions).
266/// A `budget_tokens` of 0 disables trimming. When turns are dropped the system message
267/// gets a [`trim_note`] appended, so the model knows the conversation is incomplete.
268pub fn trim_to_budget(
269    system: &Message,
270    history: &[Message],
271    budget_tokens: usize,
272    fixed_tokens: usize,
273) -> (Vec<Message>, Trimmed) {
274    let windows = plan_windows(
275        system,
276        history,
277        budget_tokens,
278        fixed_tokens,
279        DEFAULT_PROTECT_LAST_N,
280    );
281    let note = windows.drops_anything().then(|| trim_note(windows.dropped));
282    (
283        assemble(system, history, windows, note.as_deref()),
284        windows.dropped,
285    )
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291    use crate::message::{FunctionCall, ToolCall};
292
293    fn call(id: &str) -> Message {
294        Message::assistant_tool_calls(
295            None,
296            vec![ToolCall {
297                id: id.into(),
298                kind: "function".into(),
299                function: FunctionCall {
300                    name: "shell".into(),
301                    arguments: "{}".into(),
302                },
303            }],
304        )
305    }
306
307    /// `n` turns of user / tool call / tool result / assistant, each text 40 chars.
308    fn history(n: usize) -> Vec<Message> {
309        let pad = "x".repeat(40);
310        (0..n)
311            .flat_map(|i| {
312                [
313                    Message::user(format!("q{i} {pad}")),
314                    call(&format!("c{i}")),
315                    Message::tool_result(format!("c{i}"), format!("r{i} {pad}")),
316                    Message::assistant(format!("a{i} {pad}")),
317                ]
318            })
319            .collect()
320    }
321
322    fn total(msgs: &[Message]) -> usize {
323        msgs.iter().map(estimate_message_tokens).sum()
324    }
325
326    #[test]
327    fn estimate_is_chars_over_four() {
328        assert_eq!(estimate_text_tokens(""), 0);
329        assert_eq!(estimate_text_tokens("abcd"), 1);
330        assert_eq!(estimate_text_tokens("abcde"), 2);
331        assert_eq!(estimate_text_tokens("ééééé"), 2, "counts chars, not bytes");
332        let m = Message::user("a".repeat(40));
333        assert_eq!(estimate_message_tokens(&m), 10 + MESSAGE_OVERHEAD);
334        assert!(estimate_message_tokens(&call("c1")) > MESSAGE_OVERHEAD);
335    }
336
337    #[test]
338    fn disabled_budget_sends_everything() {
339        let h = history(5);
340        let (msgs, t) = trim_to_budget(&Message::system("sys"), &h, 0, 0);
341        assert_eq!(t, Trimmed::default());
342        assert_eq!(msgs.len(), h.len() + 1);
343        assert_eq!(msgs[0].content.as_deref(), Some("sys"));
344    }
345
346    #[test]
347    fn within_budget_is_untouched() {
348        let h = history(2);
349        let (msgs, t) = trim_to_budget(&Message::system("sys"), &h, 100_000, 0);
350        assert_eq!(t, Trimmed::default());
351        assert_eq!(msgs[0].content.as_deref(), Some("sys"));
352        assert_eq!(&msgs[1..], &h[..]);
353    }
354
355    /// Over budget, the middle goes: the ask stays (it is the goal), the newest turn stays
356    /// (it is the live state), and the drops are named in the system prompt.
357    #[test]
358    fn the_middle_is_dropped_and_named_and_the_system_prompt_stays() {
359        let h = history(6);
360        let sys = Message::system("be helpful");
361        let per_turn = total(&h[..4]);
362        let budget = estimate_message_tokens(&sys) + per_turn * 2 + 5;
363        let (msgs, t) = trim_to_budget(&sys, &h, budget, 0);
364        assert_eq!(
365            t,
366            Trimmed {
367                turns: 4,
368                messages: 16
369            }
370        );
371        assert_eq!(msgs.len(), 1 + 4 + 4, "the ask, then the newest turn");
372        let sys_text = msgs[0].content.as_deref().unwrap();
373        assert!(sys_text.starts_with("be helpful\n\n[trimmed 4 older turns (16 messages)"));
374        assert_eq!(&msgs[1..5], &h[..4], "the ask, verbatim and whole");
375        assert_eq!(&msgs[5..], &h[20..], "the newest turn, in order");
376        assert_eq!(msgs[1].role, Role::User, "never starts mid-turn");
377        assert_eq!(
378            msgs[5].role,
379            Role::User,
380            "and never resumes mid-turn either"
381        );
382        assert!(total(&msgs[1..]) + estimate_message_tokens(&sys) <= budget);
383    }
384
385    #[test]
386    fn tool_calls_stay_paired_with_their_results() {
387        let h = history(8);
388        for budget in (10..400).step_by(7) {
389            let (msgs, _) = trim_to_budget(&Message::system("s"), &h, budget, 0);
390            let calls: Vec<_> = msgs
391                .iter()
392                .flat_map(|m| m.tool_calls.iter().map(|c| c.id.clone()))
393                .collect();
394            let results: Vec<_> = msgs.iter().filter_map(|m| m.tool_call_id.clone()).collect();
395            assert_eq!(calls, results, "budget {budget}");
396        }
397    }
398
399    #[test]
400    fn latest_turn_is_kept_even_when_over_budget() {
401        let h = history(3);
402        let (msgs, t) = trim_to_budget(&Message::system("s"), &h, 1, 0);
403        assert_eq!(t.turns, 2);
404        assert_eq!(&msgs[1..], &h[8..]);
405        assert!(msgs[0]
406            .content
407            .as_deref()
408            .unwrap()
409            .contains("[trimmed 2 older turns"));
410    }
411
412    #[test]
413    fn fixed_tokens_such_as_tool_specs_count_against_the_budget() {
414        let h = history(4);
415        let sys = Message::system("s");
416        let budget = estimate_message_tokens(&sys) + total(&h) + 10;
417        assert_eq!(trim_to_budget(&sys, &h, budget, 0).1, Trimmed::default());
418        let (_, t) = trim_to_budget(&sys, &h, budget, total(&h[..8]));
419        assert!(t.turns >= 2, "{t:?}");
420    }
421
422    #[test]
423    fn single_turn_history_is_never_trimmed() {
424        let h = history(1);
425        let (msgs, t) = trim_to_budget(&Message::system("s"), &h, 1, 0);
426        assert_eq!(t, Trimmed::default());
427        assert_eq!(msgs.len(), 5);
428    }
429
430    #[test]
431    fn plan_and_assemble_match_trim_to_budget() {
432        let h = history(6);
433        let sys = Message::system("s");
434        let budget = estimate_message_tokens(&sys) + total(&h[..4]) * 2 + 5;
435        let w = plan_windows(&sys, &h, budget, 0, DEFAULT_PROTECT_LAST_N);
436        assert_eq!(
437            w,
438            Windows {
439                head_end: 4,
440                tail_start: 20,
441                dropped: Trimmed {
442                    turns: 4,
443                    messages: 16
444                }
445            },
446            "the ask and the newest turn; the middle pays"
447        );
448        let note = compiled_tail(w.dropped);
449        let msgs = assemble(&sys, &h, w, Some(&note));
450        assert_eq!(&msgs[1..5], &h[..4]);
451        assert_eq!(&msgs[5..], &h[20..]);
452        let text = msgs[0].content.as_deref().unwrap();
453        assert!(
454            text.starts_with("s\n\n[compiled 4 older turns (16 messages)")
455                && text.contains("one session_search away"),
456            "{text}"
457        );
458        assert!(
459            text.contains("one session_search away"),
460            "the note says how to reach what was left out: {text}"
461        );
462        let off = plan_windows(&sys, &h, 0, 0, DEFAULT_PROTECT_LAST_N);
463        assert_eq!(off, Windows::default());
464        assert_eq!(assemble(&sys, &h, off, None)[0], sys);
465        assert_eq!(assemble(&sys, &h, off, None).len(), h.len() + 1);
466    }
467
468    /// The ask survives when there is room for it: it is the goal, and a summary of a goal is
469    /// a guess. The middle is what pays.
470    #[test]
471    fn the_first_turn_is_kept_when_the_tail_leaves_room_for_it() {
472        let h = history(8);
473        let sys = Message::system("s");
474        // Room for the first turn plus four of the newest.
475        let budget = estimate_message_tokens(&sys) + total(&h[..4]) * 5;
476        let w = plan_windows(&sys, &h, budget, 0, DEFAULT_PROTECT_LAST_N);
477        assert_eq!(w.head_end, 4, "the first turn, whole");
478        assert_eq!(w.tail_start, 16, "four of the newest turns: {w:?}");
479        assert!(w.dropped.turns >= 1 && w.dropped.messages >= 4, "{w:?}");
480        let msgs = assemble(&sys, &h, w, None);
481        assert_eq!(&msgs[1..5], &h[..4], "the ask is verbatim");
482        assert_eq!(&msgs[5..], &h[w.tail_start..], "then the tail");
483        assert!(total(&msgs[1..]) + estimate_message_tokens(&sys) <= budget);
484        // The drop is in the middle, never a prefix of what is sent.
485        assert_eq!(msgs[1].content, h[0].content);
486        assert_eq!(msgs.last().unwrap().content, h.last().unwrap().content);
487    }
488
489    /// `protect_last_n` bounds the tail even when the budget would pay for more.
490    #[test]
491    fn the_tail_is_at_most_protect_last_n_turns() {
492        let h = history(10);
493        let sys = Message::system("s");
494        let budget = estimate_message_tokens(&sys) + total(&h) + 10; // everything fits
495        let w = plan_windows(&sys, &h, budget, 0, 20);
496        assert_eq!(w, Windows::default(), "under budget nothing is dropped");
497
498        let budget = estimate_message_tokens(&sys) + total(&h[..4]) * 5;
499        let w = plan_windows(&sys, &h, budget, 0, 2);
500        assert_eq!(
501            w.tail_start, 32,
502            "two turns, whatever the budget could hold: {w:?}"
503        );
504    }
505
506    /// When the head cannot be paid for, the old behaviour is what is left: drop the oldest
507    /// turns and say so. Never a half turn.
508    #[test]
509    fn the_head_gives_way_rather_than_a_turn_being_split() {
510        let h = history(4);
511        let sys = Message::system("s");
512        let budget = estimate_message_tokens(&sys) + total(&h[..4]) + 1;
513        let w = plan_windows(&sys, &h, budget, 0, DEFAULT_PROTECT_LAST_N);
514        assert_eq!(w.head_end, 0, "{w:?}");
515        assert_eq!(w.tail_start, 12, "one turn: the newest is never dropped");
516        let calls: Vec<_> = assemble(&sys, &h, w, None)
517            .iter()
518            .flat_map(|m| m.tool_calls.iter().map(|c| c.id.clone()))
519            .collect();
520        let results: Vec<_> = assemble(&sys, &h, w, None)
521            .iter()
522            .filter_map(|m| m.tool_call_id.clone())
523            .collect();
524        assert_eq!(calls, results);
525    }
526
527    fn picture() -> crate::message::ImagePart {
528        crate::message::ImagePart {
529            name: "shot.png".into(),
530            mime: "image/png".into(),
531            url: "data:image/png;base64,AAAA".into(),
532            seen: None,
533        }
534    }
535
536    #[test]
537    fn a_picture_is_charged_so_a_window_of_them_cannot_overflow_silently() {
538        let mut with_picture = Message::user("q xxxx");
539        let text_only = estimate_message_tokens(&with_picture);
540        with_picture.images.push(picture());
541        let charged = estimate_message_tokens(&with_picture);
542        assert!(
543            charged >= text_only + PICTURE_TOKENS,
544            "a picture costs nothing, so a native turn full of them never plans a compaction: \
545             {text_only} -> {charged}"
546        );
547        // A description that will be re-sent as text is charged on top of the pixels.
548        let mut described = with_picture.clone();
549        described.images[0].seen = Some("a screenshot of a dashboard ".repeat(10));
550        assert!(estimate_message_tokens(&described) > charged);
551    }
552
553    #[test]
554    fn a_history_of_pictures_plans_a_compaction_it_used_to_miss() {
555        let mut h = history(16);
556        for m in h.iter_mut().filter(|m| m.role == Role::User) {
557            m.images.push(picture());
558        }
559        // The budget fits this history with the pictures free, which is what the estimator said
560        // before: the plan was "send it all" and the request was refused instead of compacted.
561        let text_chars: usize = total(&h) - 16 * PICTURE_TOKENS;
562        let budget = text_chars + 200;
563        let w = plan_windows(
564            &Message::system("sys"),
565            &h,
566            budget,
567            0,
568            DEFAULT_PROTECT_LAST_N,
569        );
570        assert!(
571            w.drops_anything(),
572            "16 pictures were counted as free, so nothing was planned to be dropped"
573        );
574    }
575}