1use crate::message::{Message, Role};
20
21const MESSAGE_OVERHEAD: usize = 4;
23
24const 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub struct Trimmed {
61 pub turns: usize,
62 pub messages: usize,
63}
64
65pub 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
77pub 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
90pub const DEFAULT_PROTECT_LAST_N: usize = 20;
93
94#[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 pub fn drops_anything(&self) -> bool {
112 self.tail_start > self.head_end
113 }
114
115 pub fn dropped(&self) -> std::ops::Range<usize> {
117 self.head_end..self.tail_start
118 }
119}
120
121fn 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
144pub fn plan_forced(system: &Message, history: &[Message], protect_last_n: usize) -> Windows {
162 plan(system, history, 0, 0, protect_last_n, true)
166}
167
168pub fn plan_windows(
169 system: &Message,
170 history: &[Message],
171 budget_tokens: usize,
172 fixed_tokens: usize,
173 protect_last_n: usize,
174) -> Windows {
175 plan(
176 system,
177 history,
178 budget_tokens,
179 fixed_tokens,
180 protect_last_n,
181 false,
182 )
183}
184
185fn plan(
193 system: &Message,
194 history: &[Message],
195 budget_tokens: usize,
196 fixed_tokens: usize,
197 protect_last_n: usize,
198 forced: bool,
199) -> Windows {
200 let nothing = Windows::default();
201 if history.is_empty() || (!forced && budget_tokens == 0) {
202 return nothing;
203 }
204 let used = estimate_message_tokens(system) + fixed_tokens;
205 let total: usize = history.iter().map(estimate_message_tokens).sum();
206 if !forced && used + total <= budget_tokens {
207 return nothing;
208 }
209 let starts = turn_starts(history);
210 if starts.len() < 2 {
213 return nothing;
214 }
215
216 let first_end = starts[1];
217 let head_cost: usize = history[..first_end]
218 .iter()
219 .map(estimate_message_tokens)
220 .sum();
221 let reserve = if forced || head_cost * 2 <= budget_tokens {
224 head_cost
225 } else {
226 0
227 };
228
229 let mut tail_start = history.len();
230 let mut tail_used = used;
231 let keep = protect_last_n.max(1);
232 for n in (0..starts.len()).rev() {
233 if starts.len() - n > keep {
234 break;
235 }
236 let cost = turn_cost(history, &starts, n);
237 if !forced && tail_start != history.len() && tail_used + cost + reserve > budget_tokens {
240 break;
241 }
242 tail_used += cost;
243 tail_start = starts[n];
244 }
245
246 let head_end = if reserve > 0
247 && first_end <= tail_start
248 && (forced || head_cost + tail_used <= budget_tokens)
249 {
250 first_end
251 } else {
252 0
253 };
254 if head_end >= tail_start {
255 return nothing;
256 }
257 Windows {
258 head_end,
259 tail_start,
260 dropped: Trimmed {
261 turns: starts
262 .iter()
263 .filter(|&&s| s >= head_end && s < tail_start)
264 .count(),
265 messages: tail_start - head_end,
266 },
267 }
268}
269
270pub fn assemble(
273 system: &Message,
274 history: &[Message],
275 windows: Windows,
276 note: Option<&str>,
277) -> Vec<Message> {
278 let mut sys = system.clone();
279 if let Some(note) = note {
280 sys.content = Some(match sys.content.take() {
281 Some(c) if !c.is_empty() => format!("{c}\n\n{note}"),
282 _ => note.to_string(),
283 });
284 }
285 let head = &history[..windows.head_end.min(history.len())];
286 let tail = &history[windows.tail_start.min(history.len())..];
287 let mut v = Vec::with_capacity(1 + head.len() + tail.len());
288 v.push(sys);
289 v.extend_from_slice(head);
290 v.extend_from_slice(tail);
291 v
292}
293
294pub fn trim_to_budget(
299 system: &Message,
300 history: &[Message],
301 budget_tokens: usize,
302 fixed_tokens: usize,
303) -> (Vec<Message>, Trimmed) {
304 let windows = plan_windows(
305 system,
306 history,
307 budget_tokens,
308 fixed_tokens,
309 DEFAULT_PROTECT_LAST_N,
310 );
311 let note = windows.drops_anything().then(|| trim_note(windows.dropped));
312 (
313 assemble(system, history, windows, note.as_deref()),
314 windows.dropped,
315 )
316}
317
318#[cfg(test)]
319mod tests {
320 use super::*;
321 use crate::message::{FunctionCall, ToolCall};
322
323 fn call(id: &str) -> Message {
324 Message::assistant_tool_calls(
325 None,
326 vec![ToolCall {
327 id: id.into(),
328 kind: "function".into(),
329 function: FunctionCall {
330 name: "shell".into(),
331 arguments: "{}".into(),
332 },
333 }],
334 )
335 }
336
337 fn history(n: usize) -> Vec<Message> {
339 let pad = "x".repeat(40);
340 (0..n)
341 .flat_map(|i| {
342 [
343 Message::user(format!("q{i} {pad}")),
344 call(&format!("c{i}")),
345 Message::tool_result(format!("c{i}"), format!("r{i} {pad}")),
346 Message::assistant(format!("a{i} {pad}")),
347 ]
348 })
349 .collect()
350 }
351
352 fn total(msgs: &[Message]) -> usize {
353 msgs.iter().map(estimate_message_tokens).sum()
354 }
355
356 #[test]
362 fn a_forced_plan_drops_the_middle_of_a_history_that_fits_any_budget() {
363 let history = history(4);
364 let system = Message::system("sys");
365
366 assert!(!plan_windows(&system, &history, 1_000_000, 0, 2).drops_anything());
368
369 let forced = plan_forced(&system, &history, 2);
371 assert!(forced.drops_anything(), "a forced plan drops: {forced:?}");
372 assert_eq!(forced.head_end, 4, "the first turn is kept whole");
373 assert_eq!(forced.tail_start, 8, "the newest two turns are kept");
374 assert_eq!(forced.dropped.turns, 1);
375 assert_eq!(forced.dropped.messages, 4, "one turn is four messages");
376
377 let kept = assemble(&system, &history, forced, None);
378 assert_eq!(kept.len(), 1 + 4 + 8, "system, head, tail");
379 assert!(kept[1].content.as_deref().unwrap_or("").starts_with("q0"));
380 assert!(kept[5].content.as_deref().unwrap_or("").starts_with("q2"));
381 }
382
383 #[test]
386 fn a_forced_plan_of_two_turns_drops_nothing() {
387 let history = history(2);
388 let system = Message::system("sys");
389 let forced = plan_forced(&system, &history, 2);
390 assert!(!forced.drops_anything(), "{forced:?}");
391 assert_eq!(assemble(&system, &history, forced, None).len(), 1 + 8);
392 }
393
394 #[test]
395 fn a_forced_plan_of_an_empty_history_is_empty() {
396 let system = Message::system("sys");
397 assert!(!plan_forced(&system, &[], 3).drops_anything());
398 }
399
400 #[test]
401 fn estimate_is_chars_over_four() {
402 assert_eq!(estimate_text_tokens(""), 0);
403 assert_eq!(estimate_text_tokens("abcd"), 1);
404 assert_eq!(estimate_text_tokens("abcde"), 2);
405 assert_eq!(estimate_text_tokens("ééééé"), 2, "counts chars, not bytes");
406 let m = Message::user("a".repeat(40));
407 assert_eq!(estimate_message_tokens(&m), 10 + MESSAGE_OVERHEAD);
408 assert!(estimate_message_tokens(&call("c1")) > MESSAGE_OVERHEAD);
409 }
410
411 #[test]
412 fn disabled_budget_sends_everything() {
413 let h = history(5);
414 let (msgs, t) = trim_to_budget(&Message::system("sys"), &h, 0, 0);
415 assert_eq!(t, Trimmed::default());
416 assert_eq!(msgs.len(), h.len() + 1);
417 assert_eq!(msgs[0].content.as_deref(), Some("sys"));
418 }
419
420 #[test]
421 fn within_budget_is_untouched() {
422 let h = history(2);
423 let (msgs, t) = trim_to_budget(&Message::system("sys"), &h, 100_000, 0);
424 assert_eq!(t, Trimmed::default());
425 assert_eq!(msgs[0].content.as_deref(), Some("sys"));
426 assert_eq!(&msgs[1..], &h[..]);
427 }
428
429 #[test]
432 fn the_middle_is_dropped_and_named_and_the_system_prompt_stays() {
433 let h = history(6);
434 let sys = Message::system("be helpful");
435 let per_turn = total(&h[..4]);
436 let budget = estimate_message_tokens(&sys) + per_turn * 2 + 5;
437 let (msgs, t) = trim_to_budget(&sys, &h, budget, 0);
438 assert_eq!(
439 t,
440 Trimmed {
441 turns: 4,
442 messages: 16
443 }
444 );
445 assert_eq!(msgs.len(), 1 + 4 + 4, "the ask, then the newest turn");
446 let sys_text = msgs[0].content.as_deref().unwrap();
447 assert!(sys_text.starts_with("be helpful\n\n[trimmed 4 older turns (16 messages)"));
448 assert_eq!(&msgs[1..5], &h[..4], "the ask, verbatim and whole");
449 assert_eq!(&msgs[5..], &h[20..], "the newest turn, in order");
450 assert_eq!(msgs[1].role, Role::User, "never starts mid-turn");
451 assert_eq!(
452 msgs[5].role,
453 Role::User,
454 "and never resumes mid-turn either"
455 );
456 assert!(total(&msgs[1..]) + estimate_message_tokens(&sys) <= budget);
457 }
458
459 #[test]
460 fn tool_calls_stay_paired_with_their_results() {
461 let h = history(8);
462 for budget in (10..400).step_by(7) {
463 let (msgs, _) = trim_to_budget(&Message::system("s"), &h, budget, 0);
464 let calls: Vec<_> = msgs
465 .iter()
466 .flat_map(|m| m.tool_calls.iter().map(|c| c.id.clone()))
467 .collect();
468 let results: Vec<_> = msgs.iter().filter_map(|m| m.tool_call_id.clone()).collect();
469 assert_eq!(calls, results, "budget {budget}");
470 }
471 }
472
473 #[test]
474 fn latest_turn_is_kept_even_when_over_budget() {
475 let h = history(3);
476 let (msgs, t) = trim_to_budget(&Message::system("s"), &h, 1, 0);
477 assert_eq!(t.turns, 2);
478 assert_eq!(&msgs[1..], &h[8..]);
479 assert!(msgs[0]
480 .content
481 .as_deref()
482 .unwrap()
483 .contains("[trimmed 2 older turns"));
484 }
485
486 #[test]
487 fn fixed_tokens_such_as_tool_specs_count_against_the_budget() {
488 let h = history(4);
489 let sys = Message::system("s");
490 let budget = estimate_message_tokens(&sys) + total(&h) + 10;
491 assert_eq!(trim_to_budget(&sys, &h, budget, 0).1, Trimmed::default());
492 let (_, t) = trim_to_budget(&sys, &h, budget, total(&h[..8]));
493 assert!(t.turns >= 2, "{t:?}");
494 }
495
496 #[test]
497 fn single_turn_history_is_never_trimmed() {
498 let h = history(1);
499 let (msgs, t) = trim_to_budget(&Message::system("s"), &h, 1, 0);
500 assert_eq!(t, Trimmed::default());
501 assert_eq!(msgs.len(), 5);
502 }
503
504 #[test]
505 fn plan_and_assemble_match_trim_to_budget() {
506 let h = history(6);
507 let sys = Message::system("s");
508 let budget = estimate_message_tokens(&sys) + total(&h[..4]) * 2 + 5;
509 let w = plan_windows(&sys, &h, budget, 0, DEFAULT_PROTECT_LAST_N);
510 assert_eq!(
511 w,
512 Windows {
513 head_end: 4,
514 tail_start: 20,
515 dropped: Trimmed {
516 turns: 4,
517 messages: 16
518 }
519 },
520 "the ask and the newest turn; the middle pays"
521 );
522 let note = compiled_tail(w.dropped);
523 let msgs = assemble(&sys, &h, w, Some(¬e));
524 assert_eq!(&msgs[1..5], &h[..4]);
525 assert_eq!(&msgs[5..], &h[20..]);
526 let text = msgs[0].content.as_deref().unwrap();
527 assert!(
528 text.starts_with("s\n\n[compiled 4 older turns (16 messages)")
529 && text.contains("one session_search away"),
530 "{text}"
531 );
532 assert!(
533 text.contains("one session_search away"),
534 "the note says how to reach what was left out: {text}"
535 );
536 let off = plan_windows(&sys, &h, 0, 0, DEFAULT_PROTECT_LAST_N);
537 assert_eq!(off, Windows::default());
538 assert_eq!(assemble(&sys, &h, off, None)[0], sys);
539 assert_eq!(assemble(&sys, &h, off, None).len(), h.len() + 1);
540 }
541
542 #[test]
545 fn the_first_turn_is_kept_when_the_tail_leaves_room_for_it() {
546 let h = history(8);
547 let sys = Message::system("s");
548 let budget = estimate_message_tokens(&sys) + total(&h[..4]) * 5;
550 let w = plan_windows(&sys, &h, budget, 0, DEFAULT_PROTECT_LAST_N);
551 assert_eq!(w.head_end, 4, "the first turn, whole");
552 assert_eq!(w.tail_start, 16, "four of the newest turns: {w:?}");
553 assert!(w.dropped.turns >= 1 && w.dropped.messages >= 4, "{w:?}");
554 let msgs = assemble(&sys, &h, w, None);
555 assert_eq!(&msgs[1..5], &h[..4], "the ask is verbatim");
556 assert_eq!(&msgs[5..], &h[w.tail_start..], "then the tail");
557 assert!(total(&msgs[1..]) + estimate_message_tokens(&sys) <= budget);
558 assert_eq!(msgs[1].content, h[0].content);
560 assert_eq!(msgs.last().unwrap().content, h.last().unwrap().content);
561 }
562
563 #[test]
565 fn the_tail_is_at_most_protect_last_n_turns() {
566 let h = history(10);
567 let sys = Message::system("s");
568 let budget = estimate_message_tokens(&sys) + total(&h) + 10; let w = plan_windows(&sys, &h, budget, 0, 20);
570 assert_eq!(w, Windows::default(), "under budget nothing is dropped");
571
572 let budget = estimate_message_tokens(&sys) + total(&h[..4]) * 5;
573 let w = plan_windows(&sys, &h, budget, 0, 2);
574 assert_eq!(
575 w.tail_start, 32,
576 "two turns, whatever the budget could hold: {w:?}"
577 );
578 }
579
580 #[test]
583 fn the_head_gives_way_rather_than_a_turn_being_split() {
584 let h = history(4);
585 let sys = Message::system("s");
586 let budget = estimate_message_tokens(&sys) + total(&h[..4]) + 1;
587 let w = plan_windows(&sys, &h, budget, 0, DEFAULT_PROTECT_LAST_N);
588 assert_eq!(w.head_end, 0, "{w:?}");
589 assert_eq!(w.tail_start, 12, "one turn: the newest is never dropped");
590 let calls: Vec<_> = assemble(&sys, &h, w, None)
591 .iter()
592 .flat_map(|m| m.tool_calls.iter().map(|c| c.id.clone()))
593 .collect();
594 let results: Vec<_> = assemble(&sys, &h, w, None)
595 .iter()
596 .filter_map(|m| m.tool_call_id.clone())
597 .collect();
598 assert_eq!(calls, results);
599 }
600
601 fn picture() -> crate::message::ImagePart {
602 crate::message::ImagePart {
603 name: "shot.png".into(),
604 mime: "image/png".into(),
605 url: "data:image/png;base64,AAAA".into(),
606 seen: None,
607 }
608 }
609
610 #[test]
611 fn a_picture_is_charged_so_a_window_of_them_cannot_overflow_silently() {
612 let mut with_picture = Message::user("q xxxx");
613 let text_only = estimate_message_tokens(&with_picture);
614 with_picture.images.push(picture());
615 let charged = estimate_message_tokens(&with_picture);
616 assert!(
617 charged >= text_only + PICTURE_TOKENS,
618 "a picture costs nothing, so a native turn full of them never plans a compaction: \
619 {text_only} -> {charged}"
620 );
621 let mut described = with_picture.clone();
623 described.images[0].seen = Some("a screenshot of a dashboard ".repeat(10));
624 assert!(estimate_message_tokens(&described) > charged);
625 }
626
627 #[test]
628 fn a_history_of_pictures_plans_a_compaction_it_used_to_miss() {
629 let mut h = history(16);
630 for m in h.iter_mut().filter(|m| m.role == Role::User) {
631 m.images.push(picture());
632 }
633 let text_chars: usize = total(&h) - 16 * PICTURE_TOKENS;
636 let budget = text_chars + 200;
637 let w = plan_windows(
638 &Message::system("sys"),
639 &h,
640 budget,
641 0,
642 DEFAULT_PROTECT_LAST_N,
643 );
644 assert!(
645 w.drops_anything(),
646 "16 pictures were counted as free, so nothing was planned to be dropped"
647 );
648 }
649}