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_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 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 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 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
240pub 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
264pub 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 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 #[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(¬e));
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 #[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 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 assert_eq!(msgs[1].content, h[0].content);
486 assert_eq!(msgs.last().unwrap().content, h.last().unwrap().content);
487 }
488
489 #[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; 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 #[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 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 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}