use crate::llm::ChatMessage;
#[derive(Debug, Clone, Copy)]
pub struct CompactionConfig {
pub token_threshold: usize,
pub keep_last_messages: usize,
}
pub const COMPACTION_THRESHOLD_FRACTION_PCT: usize = 75;
impl CompactionConfig {
pub fn for_context_window(context_window: usize) -> Self {
Self {
token_threshold: context_window * COMPACTION_THRESHOLD_FRACTION_PCT / 100,
keep_last_messages: 6,
}
}
}
impl Default for CompactionConfig {
fn default() -> Self {
Self {
token_threshold: 6_000,
keep_last_messages: 6,
}
}
}
pub fn estimate_tokens(text: &str) -> usize {
text.chars().count() / 4
}
pub fn estimate_total_tokens(messages: &[ChatMessage]) -> usize {
messages
.iter()
.map(|m| {
let content_tokens = estimate_tokens(m.content.as_deref().unwrap_or_default());
let tool_call_tokens: usize = m
.tool_calls
.iter()
.flatten()
.map(|call| estimate_tokens(&call.function.arguments))
.sum();
content_tokens + tool_call_tokens
})
.sum()
}
pub fn should_compact(messages: &[ChatMessage], cfg: &CompactionConfig) -> bool {
estimate_total_tokens(messages) > cfg.token_threshold
}
pub fn summarize_span(span: &[ChatMessage]) -> String {
if span.is_empty() {
return "[compacted 0 earlier messages]".to_string();
}
let assistant_count = span.iter().filter(|m| m.role == "assistant").count();
let mut tool_names: Vec<&str> = span
.iter()
.filter(|m| m.role == "tool")
.filter_map(|m| m.name.as_deref())
.collect();
tool_names.sort_unstable();
tool_names.dedup();
let tool_count = span.iter().filter(|m| m.role == "tool").count();
let tools_suffix = if tool_names.is_empty() {
String::new()
} else {
format!(" ({})", tool_names.join(", "))
};
format!(
"[compacted {} earlier message{}: {} assistant turn{}, {} tool call{}{}]",
span.len(),
plural_suffix(span.len()),
assistant_count,
plural_suffix(assistant_count),
tool_count,
plural_suffix(tool_count),
tools_suffix,
)
}
fn plural_suffix(n: usize) -> &'static str {
if n == 1 { "" } else { "s" }
}
#[cfg(test)]
mod tests {
use super::*;
fn tool_msg(name: &str) -> ChatMessage {
ChatMessage::tool_result("call_1", name, "result")
}
#[test]
fn default_is_sane() {
let cfg = CompactionConfig::default();
assert!(cfg.token_threshold > 0);
assert!(cfg.keep_last_messages > 0);
}
#[test]
fn estimate_tokens_uses_chars_over_four() {
assert_eq!(estimate_tokens("abcd"), 1);
assert_eq!(estimate_tokens("abcdefgh"), 2);
assert_eq!(estimate_tokens(""), 0);
}
#[test]
fn estimate_total_tokens_sums_content() {
let messages = vec![
ChatMessage::user("abcd"),
ChatMessage::assistant("abcdefgh"),
];
assert_eq!(estimate_total_tokens(&messages), 3);
}
#[test]
fn estimate_total_tokens_sums_tool_call_arguments() {
use crate::llm::{FunctionCall, ToolCall};
let arguments = r#"{"path":"src/main.rs","content":"fn main() {}"}"#;
let messages = vec![ChatMessage {
role: "assistant".into(),
content: None,
tool_calls: Some(vec![ToolCall {
id: "call_1".into(),
kind: "function".into(),
function: FunctionCall {
name: "write_file".into(),
arguments: arguments.into(),
},
}]),
tool_call_id: None,
name: None,
cache_control: None,
}];
assert_eq!(estimate_total_tokens(&messages), estimate_tokens(arguments));
}
#[test]
fn should_compact_triggers_on_large_tool_call_arguments() {
use crate::llm::{FunctionCall, ToolCall};
let big_content = "x".repeat(9_000);
let mut messages = vec![ChatMessage::system("s"), ChatMessage::user("do the thing")];
for i in 0..3 {
messages.push(ChatMessage {
role: "assistant".into(),
content: None,
tool_calls: Some(vec![ToolCall {
id: format!("call_{i}"),
kind: "function".into(),
function: FunctionCall {
name: "write_file".into(),
arguments: format!(r#"{{"content":"{big_content}"}}"#),
},
}]),
tool_call_id: None,
name: None,
cache_control: None,
});
messages.push(ChatMessage::tool_result(
format!("call_{i}"),
"write_file",
"ok",
));
}
assert!(should_compact(&messages, &CompactionConfig::default()));
}
#[test]
fn should_compact_respects_threshold() {
let cfg = CompactionConfig {
token_threshold: 2,
keep_last_messages: 1,
};
let small = vec![ChatMessage::user("ab")];
let large = vec![ChatMessage::user("abcdefghijkl")];
assert!(!should_compact(&small, &cfg));
assert!(should_compact(&large, &cfg));
}
#[test]
fn for_context_window_scales_threshold_proportionally() {
let large = CompactionConfig::for_context_window(200_000);
assert!(
(140_000..=160_000).contains(&large.token_threshold),
"expected ~75% of 200_000, got {}",
large.token_threshold
);
let small = CompactionConfig::for_context_window(8_000);
assert!(
(5_600..=6_400).contains(&small.token_threshold),
"expected ~75% of 8_000, got {}",
small.token_threshold
);
}
#[test]
fn should_compact_does_not_trigger_at_10k_tokens_against_200k_window() {
let messages = vec![ChatMessage::user("x".repeat(40_000))];
assert_eq!(estimate_total_tokens(&messages), 10_000);
let cfg = CompactionConfig::for_context_window(200_000);
assert!(
!should_compact(&messages, &cfg),
"a 10K-token transcript must not compact against a 200K-window model"
);
}
#[test]
fn should_compact_triggers_near_75pct_of_200k_window() {
let messages = vec![ChatMessage::user("x".repeat(601_000))];
let cfg = CompactionConfig::for_context_window(200_000);
assert!(
should_compact(&messages, &cfg),
"a transcript just over 75% of the window must trigger compaction"
);
}
#[test]
fn estimate_total_tokens_units_match_between_content_and_tool_args() {
use crate::llm::{FunctionCall, ToolCall};
let s = "y".repeat(1000);
let content_only = vec![ChatMessage::assistant(s.clone())];
let tool_call_only = vec![ChatMessage {
role: "assistant".into(),
content: None,
tool_calls: Some(vec![ToolCall {
id: "call_1".into(),
kind: "function".into(),
function: FunctionCall {
name: "write_file".into(),
arguments: s.clone(),
},
}]),
tool_call_id: None,
name: None,
cache_control: None,
}];
assert_eq!(
estimate_total_tokens(&content_only),
estimate_total_tokens(&tool_call_only)
);
}
#[test]
fn summarize_span_counts_roles_and_tools() {
let span = vec![
ChatMessage::assistant("thinking"),
tool_msg("bash"),
tool_msg("read_file"),
tool_msg("bash"),
];
let summary = summarize_span(&span);
assert!(summary.contains("4 earlier messages"));
assert!(summary.contains("1 assistant turn"));
assert!(summary.contains("3 tool calls"));
assert!(summary.contains("bash"));
assert!(summary.contains("read_file"));
}
#[test]
fn summarize_span_handles_empty_span() {
assert_eq!(summarize_span(&[]), "[compacted 0 earlier messages]");
}
}