1use crate::types::{ChatMessage, SessionId};
2
3pub fn first_system_prompt(messages: &[ChatMessage]) -> Option<ChatMessage> {
5 messages.iter().find_map(|msg| match msg {
6 ChatMessage::System {
7 content,
8 ephemeral: false,
9 } => Some(ChatMessage::system(content.clone())),
10 _ => None,
11 })
12}
13
14pub fn estimate_messages_tokens(messages: &[ChatMessage]) -> usize {
16 messages
17 .iter()
18 .map(ContextWindowManager::message_tokens)
19 .sum()
20}
21
22#[derive(Clone, Debug)]
25pub struct ContextWindowManager {
26 pub max_tokens: usize,
27 pub keep_first_n: usize,
29 pub keep_last_n: usize,
31}
32
33impl Default for ContextWindowManager {
34 fn default() -> Self {
35 Self {
36 max_tokens: 128_000,
37 keep_first_n: 1,
38 keep_last_n: 20,
39 }
40 }
41}
42
43impl ContextWindowManager {
44 const IMAGE_OVERHEAD_TOKENS: usize = 85;
46
47 const IMAGE_PIXELS_PER_TOKEN: u64 = 750;
58
59 const IMAGE_UNREADABLE_TOKENS: usize = 3_500;
64
65 pub fn new(max_tokens: usize) -> Self {
66 Self {
67 max_tokens,
68 ..Default::default()
69 }
70 }
71
72 pub fn with_keep_first_n(mut self, n: usize) -> Self {
73 self.keep_first_n = n;
74 self
75 }
76
77 pub fn with_keep_last_n(mut self, n: usize) -> Self {
78 self.keep_last_n = n;
79 self
80 }
81
82 pub fn estimate_tokens(text: &str) -> usize {
85 if text.is_empty() {
86 return 0;
87 }
88 let chars = text.chars().count();
89 let cjk_count = text.chars().filter(|c| is_cjk(*c)).count();
90 let latin_count = chars - cjk_count;
91 (cjk_count as f64 / 1.5 + latin_count as f64 / 4.0).ceil() as usize
93 }
94
95 fn image_tokens(image: &crate::types::ImageAttachment) -> usize {
99 use crate::types::ImageAttachment;
100 let body = match image {
101 ImageAttachment::Url { url, detail: _ } => Self::estimate_tokens(url),
102 ImageAttachment::Base64 {
103 data,
104 media_type,
105 detail: _,
106 } => {
107 let mut tokens = match crate::image_ops::base64_prefix_dims(data) {
108 Some((w, h)) => Self::pixel_tokens(w, h),
109 None => Self::IMAGE_UNREADABLE_TOKENS,
110 };
111 if let Some(mt) = media_type {
112 tokens += Self::estimate_tokens(mt);
113 }
114 tokens
115 }
116 };
117 body + Self::IMAGE_OVERHEAD_TOKENS
118 }
119
120 fn pixel_tokens(w: u32, h: u32) -> usize {
124 let long = u64::from(w.max(h)).max(1);
125 let cap = u64::from(crate::image_ops::MAX_WIRE_LONG_EDGE);
126 let (w, h) = if long > cap {
127 (u64::from(w) * cap / long, u64::from(h) * cap / long)
128 } else {
129 (u64::from(w), u64::from(h))
130 };
131 let pixels = (w * h).max(1);
132 (pixels.div_ceil(Self::IMAGE_PIXELS_PER_TOKEN)) as usize
133 }
134
135 pub(crate) fn user_message_tokens(
138 content: &str,
139 images: &[crate::types::ImageAttachment],
140 ) -> usize {
141 Self::estimate_tokens(content) + images.iter().map(Self::image_tokens).sum::<usize>()
142 }
143
144 pub(crate) fn message_tokens(msg: &ChatMessage) -> usize {
145 match msg {
146 ChatMessage::System { content, .. } => Self::estimate_tokens(content),
147 ChatMessage::User {
148 content, images, ..
149 } => Self::user_message_tokens(content, images),
150 ChatMessage::Assistant {
151 content,
152 reasoning_content,
153 tool_calls,
154 thinking_signature: _,
155 } => {
156 let mut tokens = content.as_deref().map(Self::estimate_tokens).unwrap_or(0);
157 if let Some(rc) = reasoning_content {
158 tokens += Self::estimate_tokens(rc);
159 }
160 if let Some(tc) = tool_calls {
161 for t in tc {
162 tokens += Self::estimate_tokens(&t.name);
163 tokens += Self::estimate_tokens(&t.arguments);
164 tokens += Self::estimate_tokens(&t.id);
165 }
166 }
167 tokens
168 }
169 ChatMessage::Tool {
170 tool_call_id,
171 content,
172 images,
173 ..
174 } => {
175 let mut tokens =
179 Self::estimate_tokens(tool_call_id) + Self::estimate_tokens(content);
180 for img in images {
181 tokens += Self::image_tokens(img);
182 }
183 tokens
184 }
185 ChatMessage::Custom { role, data } => {
186 Self::estimate_tokens(role) + Self::estimate_tokens(&data.to_string())
187 }
188 }
189 }
190
191 pub fn trim(&self, messages: &mut Vec<ChatMessage>) {
198 if messages.is_empty() || self.max_tokens == 0 {
199 return;
200 }
201
202 let total_tokens: usize = messages.iter().map(Self::message_tokens).sum();
203 if total_tokens <= self.max_tokens {
204 return;
205 }
206
207 let keep_first = self.keep_first_n.min(messages.len());
208 let keep_last = self
209 .keep_last_n
210 .min(messages.len().saturating_sub(keep_first));
211
212 let trim_start = keep_first;
214 let trim_end = messages.len().saturating_sub(keep_last);
215 if trim_start >= trim_end {
216 return;
217 }
218
219 let mut current_tokens: usize = total_tokens;
220 let remove_idx = trim_start;
221 let mut trim_end = trim_end;
222
223 while current_tokens > self.max_tokens && remove_idx < trim_end {
224 let removed = Self::message_tokens(&messages[remove_idx]);
225 messages.remove(remove_idx);
226 current_tokens = current_tokens.saturating_sub(removed);
227 trim_end = messages.len().saturating_sub(keep_last);
228 }
229 }
230}
231
232fn is_cjk(c: char) -> bool {
233 matches!(
234 c,
235 '\u{4E00}'..='\u{9FFF}' | '\u{3400}'..='\u{4DBF}' | '\u{3000}'..='\u{303F}' | '\u{FF00}'..='\u{FFEF}' | '\u{3040}'..='\u{309F}' | '\u{30A0}'..='\u{30FF}' | '\u{AC00}'..='\u{D7AF}' )
243}
244
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
252pub enum CompactionKind {
253 Reminder,
255 Fallback,
257 Reset,
259}
260
261impl CompactionKind {
262 pub fn trigger_log(self) -> &'static str {
267 match self {
268 Self::Reminder => "context reminder appended",
269 Self::Fallback => "context fallback appended",
270 Self::Reset => "inline compaction triggered",
271 }
272 }
273
274 pub fn completion_log(self) -> Option<&'static str> {
278 match self {
279 Self::Reminder | Self::Fallback => None,
280 Self::Reset => Some("inline compaction completed (window reset)"),
281 }
282 }
283}
284
285pub struct CompactionOutcome {
287 pub kind: CompactionKind,
288 pub messages: Vec<ChatMessage>,
289}
290
291#[async_trait::async_trait]
300pub trait ContextCompaction: Send + Sync {
301 async fn compact(
311 &self,
312 session_id: &SessionId,
313 messages: &[ChatMessage],
314 ) -> Option<CompactionOutcome>;
315
316 fn token_count_hint(&self, session_id: &SessionId) -> Option<usize>;
321}
322
323#[cfg(test)]
324mod tests {
325 use super::*;
326 use crate::types::{ImageAttachment, ToolCallMessage};
327
328 #[test]
329 fn test_estimate_tokens_empty() {
330 assert_eq!(ContextWindowManager::estimate_tokens(""), 0);
331 }
332
333 #[test]
334 fn test_estimate_tokens_english() {
335 let text = "Hello world this is a test";
336 let tokens = ContextWindowManager::estimate_tokens(text);
337 assert!(tokens > 0 && tokens <= 15);
339 }
340
341 #[test]
342 fn test_estimate_tokens_cjk() {
343 assert_eq!(ContextWindowManager::estimate_tokens("你好世界"), 3);
345 }
346
347 #[test]
348 fn test_estimate_tokens_mixed() {
349 assert_eq!(ContextWindowManager::estimate_tokens("你好hello"), 3);
351 }
352
353 #[test]
354 fn test_message_tokens_user_with_url_image() {
355 let msg = ChatMessage::user_with_images(
356 "pic",
357 vec![ImageAttachment::Url {
358 url: "http://x/a.png".into(),
359 detail: None,
360 }],
361 );
362 let base = ContextWindowManager::message_tokens(&ChatMessage::user("pic"));
363 let t = ContextWindowManager::message_tokens(&msg);
364 assert!(t > base);
365 }
366
367 #[test]
368 fn test_message_tokens_user_with_base64_image() {
369 let msg = ChatMessage::user_with_images(
371 "pic",
372 vec![ImageAttachment::Base64 {
373 data: "abcd".into(),
374 media_type: Some("image/png".into()),
375 detail: None,
376 }],
377 );
378 let base = ContextWindowManager::message_tokens(&ChatMessage::user("pic"));
379 assert!(ContextWindowManager::message_tokens(&msg) > base);
380
381 let msg = ChatMessage::user_with_images(
383 "pic",
384 vec![ImageAttachment::Base64 {
385 data: "abcd".into(),
386 media_type: None,
387 detail: None,
388 }],
389 );
390 assert!(ContextWindowManager::message_tokens(&msg) > base);
391 }
392
393 #[test]
394 fn test_message_tokens_assistant_reasoning_and_tool_calls() {
395 let msg = ChatMessage::Assistant {
396 content: Some("ans".into()),
397 reasoning_content: Some("thinking".into()),
398 tool_calls: Some(vec![ToolCallMessage {
399 id: "tc1".into(),
400 name: "echo".into(),
401 arguments: "{}".into(),
402 }]),
403 thinking_signature: None,
404 };
405 let t = ContextWindowManager::message_tokens(&msg);
406 assert!(t > 0);
407 }
408
409 #[test]
410 fn test_message_tokens_tool_and_custom() {
411 let tool = ChatMessage::tool("tc1", "done");
412 assert!(ContextWindowManager::message_tokens(&tool) > 0);
413
414 let custom = ChatMessage::Custom {
415 role: "artifact".into(),
416 data: serde_json::json!({"x": 1}),
417 };
418 assert!(ContextWindowManager::message_tokens(&custom) > 0);
419 }
420
421 #[test]
429 fn screenshot_images_price_by_pixels_not_base64_length() {
430 let png = crate::image_ops::test_fixtures::noisy_png(1278, 1152);
431 let b64 = crate::image_ops::to_base64(&png);
432 let msg = ChatMessage::user_with_images(
433 "what is in this screenshot?",
434 vec![ImageAttachment::Base64 {
435 data: b64.clone(),
436 media_type: Some("image/png".into()),
437 detail: None,
438 }],
439 );
440 let tokens = ContextWindowManager::message_tokens(&msg);
441 let old_formula = b64.len() / 4;
443 assert!(
444 old_formula > 100_000,
445 "fixture must carry the incident's payload scale, got {old_formula}"
446 );
447 assert!(
448 tokens < 5_000,
449 "one screenshot must cost thousands of tokens, not {tokens} (payload was {old_formula} under the old formula)"
450 );
451 assert!(tokens > 1_500, "the pixel price is real, got {tokens}");
452 }
453
454 #[test]
459 fn tool_result_images_are_counted_too() {
460 let png =
461 crate::image_ops::to_base64(&crate::image_ops::test_fixtures::noisy_png(200, 200));
462 let text_only = ChatMessage::tool("tc1", "done");
463 let with_image = ChatMessage::Tool {
464 tool_call_id: "tc1".into(),
465 name: Some("read_image".into()),
466 content: "done".into(),
467 images: vec![ImageAttachment::Base64 {
468 data: png,
469 media_type: Some("image/png".into()),
470 detail: None,
471 }],
472 };
473 let text_tokens = ContextWindowManager::message_tokens(&text_only);
474 let image_tokens = ContextWindowManager::message_tokens(&with_image);
475 assert!(
476 image_tokens > text_tokens + 100,
477 "tool image must cost its pixels: {text_tokens} vs {image_tokens}"
478 );
479 }
480
481 #[test]
487 fn unreadable_image_payloads_get_the_capped_fallback() {
488 let small: Vec<u8> = b"not an image".to_vec();
489 let mut big = vec![b'x'; 512_000];
490 big.extend_from_slice(b"also not an image");
491 let estimate = |payload: Vec<u8>| {
492 ContextWindowManager::user_message_tokens(
493 "",
494 &[ImageAttachment::Base64 {
495 data: crate::image_ops::to_base64(&payload),
496 media_type: None,
497 detail: None,
498 }],
499 )
500 };
501 let small_est = estimate(small);
502 let big_est = estimate(big);
503 assert_eq!(small_est, big_est, "fallback is size-independent");
504 assert!(
505 (1_000..5_000).contains(&small_est),
506 "fallback is capped: {small_est}"
507 );
508 }
509
510 #[test]
511 fn test_trim_no_trim_needed() {
512 let mgr = ContextWindowManager::new(1000);
513 let mut msgs = vec![
514 ChatMessage::system("You are a helpful assistant."),
515 ChatMessage::user("Hello"),
516 ChatMessage::assistant("Hi there!"),
517 ];
518 let original_len = msgs.len();
519 mgr.trim(&mut msgs);
520 assert_eq!(msgs.len(), original_len);
521 }
522
523 #[test]
524 fn test_trim_keeps_first_and_last() {
525 let mgr = ContextWindowManager::new(8)
526 .with_keep_first_n(1)
527 .with_keep_last_n(2);
528 let mut msgs = vec![
529 ChatMessage::system("system"),
530 ChatMessage::user("message number one"),
531 ChatMessage::assistant("message number two"),
532 ChatMessage::user("message number three"),
533 ChatMessage::assistant("message number four"),
534 ChatMessage::user("message number five"),
535 ChatMessage::assistant("message number six"),
536 ];
537 mgr.trim(&mut msgs);
538 assert_eq!(msgs.len(), 3);
539 assert!(matches!(msgs[0], ChatMessage::System { .. }));
540 }
541}
542
543#[cfg(test)]
544mod proptest_tests {
545 use super::*;
546 use proptest::prelude::*;
547
548 proptest! {
549 #[test]
550 fn estimate_tokens_never_panics(text in ".*") {
551 let tokens = ContextWindowManager::estimate_tokens(&text);
552 assert!(tokens <= text.len() + 1); }
555
556 #[test]
557 fn estimate_tokens_empty_is_zero(text in "[a-z\u{4e00}-\u{9fff}]{0,100}") {
558 if text.is_empty() {
559 assert_eq!(ContextWindowManager::estimate_tokens(&text), 0);
560 } else {
561 assert!(ContextWindowManager::estimate_tokens(&text) > 0);
562 }
563 }
564
565 #[test]
566 fn estimate_tokens_cjk_higher_than_latin_same_len(
567 cjk_text in "[\u{4e00}-\u{9fff}]{1,50}",
568 latin_text in "[a-z]{1,50}",
569 ) {
570 let max_len = cjk_text.chars().count().max(latin_text.chars().count());
572 let cjk_padded: String = cjk_text.chars().cycle().take(max_len).collect();
573 let latin_padded: String = latin_text.chars().cycle().take(max_len).collect();
574 let cjk_tokens = ContextWindowManager::estimate_tokens(&cjk_padded);
575 let latin_tokens = ContextWindowManager::estimate_tokens(&latin_padded);
576 assert!(cjk_tokens >= latin_tokens,
578 "CJK ({}) should use >= tokens than Latin ({}) for {} chars",
579 cjk_tokens, latin_tokens, max_len);
580 }
581
582 #[test]
583 fn trim_preserves_system_prefix(
584 num_messages in 2usize..15,
585 max_tokens in 5usize..50,
586 ) {
587 let mgr = ContextWindowManager {
588 max_tokens,
589 keep_first_n: 1,
590 keep_last_n: 0,
591 };
592 let mut msgs = vec![ChatMessage::system("system prompt")];
593 for i in 0..num_messages {
594 msgs.push(ChatMessage::user(format!("message {}", i)));
595 }
596 mgr.trim(&mut msgs);
597 assert!(!msgs.is_empty());
599 assert!(matches!(msgs[0], ChatMessage::System { .. }));
600 }
601
602 #[test]
603 fn trim_result_within_budget(
604 num_messages in 3usize..15,
605 max_tokens in 10usize..100,
606 ) {
607 let mgr = ContextWindowManager {
608 max_tokens,
609 keep_first_n: 1,
610 keep_last_n: 1,
611 };
612 let mut msgs = vec![ChatMessage::system("sys")];
613 for i in 0..num_messages {
614 msgs.push(ChatMessage::user(format!("msg {}", i)));
615 }
616 let total_before: usize = msgs.iter().map(ContextWindowManager::message_tokens).sum();
617 if total_before > max_tokens {
619 mgr.trim(&mut msgs);
620 let total_after: usize = msgs.iter().map(ContextWindowManager::message_tokens).sum();
621 assert!(total_after <= total_before);
623 }
624 }
625 }
626
627 #[test]
630 fn compaction_kind_log_lines_are_grep_able() {
631 use super::{CompactionKind, CompactionOutcome};
632
633 for kind in [CompactionKind::Reminder, CompactionKind::Fallback] {
635 let trigger = kind.trigger_log();
636 assert!(
637 !trigger.contains("compaction"),
638 "{kind:?} trigger log must not claim compaction: {trigger}"
639 );
640 assert!(
641 kind.completion_log().is_none(),
642 "{kind:?} append is atomic — no completion line"
643 );
644 }
645 let reset = CompactionKind::Reset;
647 assert!(reset.trigger_log().contains("compaction"));
648 let completion = reset.completion_log().expect("reset has a completion line");
649 assert!(completion.contains("compaction"));
650
651 let all = [
653 CompactionKind::Reminder.trigger_log(),
654 CompactionKind::Fallback.trigger_log(),
655 reset.trigger_log(),
656 ];
657 for (i, a) in all.iter().enumerate() {
658 for b in all.iter().skip(i + 1) {
659 assert_ne!(a, b, "trigger log lines must be distinct");
660 }
661 }
662
663 let outcome = CompactionOutcome {
665 kind: CompactionKind::Reminder,
666 messages: vec![ChatMessage::user("nudge")],
667 };
668 assert_eq!(outcome.kind, CompactionKind::Reminder);
669 assert_eq!(outcome.messages.len(), 1);
670 }
671}