use std::fmt::Write as _;
use crate::{Message, Provider, Result};
const SUMMARY_RESERVE_TOKENS: u64 = 32_768;
const BYTES_PER_TOKEN: u64 = 4;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CompactSettings {
pub context_window: u64,
}
impl CompactSettings {
#[must_use]
pub const fn threshold(&self) -> u64 {
self.context_window.saturating_sub(SUMMARY_RESERVE_TOKENS)
}
}
#[must_use]
pub const fn should_compact(settings: &CompactSettings, tokens: u64) -> bool {
tokens >= settings.threshold()
}
#[must_use]
pub fn estimate_tokens(messages: &[Message]) -> u64 {
let mut bytes: u64 = 0;
for message in messages {
bytes = bytes.saturating_add(message_bytes(message));
}
bytes / BYTES_PER_TOKEN
}
fn message_bytes(message: &Message) -> u64 {
let mut bytes = byte_len(message.text());
if let Message::Assistant { tool_calls, .. } = message {
for call in tool_calls {
bytes = bytes.saturating_add(byte_len(&call.name));
bytes = bytes.saturating_add(byte_len(&call.arguments));
}
}
bytes
}
fn byte_len(text: &str) -> u64 {
u64::try_from(text.len()).unwrap_or(u64::MAX)
}
#[must_use]
pub fn summary_request_messages<'a>(
history: &'a [Message],
settings: &CompactSettings,
) -> &'a [Message] {
let budget = settings
.threshold()
.saturating_sub(SUMMARY_RESERVE_TOKENS)
.saturating_mul(BYTES_PER_TOKEN);
let mut used: u64 = 0;
let mut start = history.len();
for (index, message) in history.iter().enumerate().rev() {
let cost = message_bytes(message);
if used.saturating_add(cost) > budget && start != history.len() {
break;
}
used = used.saturating_add(cost);
start = index;
}
history.get(start..).unwrap_or_default()
}
const SUMMARIZER_SYSTEM_PROMPT: &str = "\
You summarize a coding session so it can continue without the earlier messages. \
Write what was asked, what was done, what was decided, and what is still open. \
Keep file paths, commands, and names exact. Do not add advice or commentary. \
Answer with the summary alone.";
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CompactionOutcome {
NotNeeded,
Summarized(String),
Refused(String),
}
pub async fn summarize_if_needed(
provider: &dyn Provider,
settings: &CompactSettings,
history: &[Message],
) -> CompactionOutcome {
if !should_compact(settings, estimate_tokens(history)) {
return CompactionOutcome::NotNeeded;
}
match summarize_history(provider, summary_request_messages(history, settings)).await {
Ok(summary) if summary.trim().is_empty() => {
CompactionOutcome::Refused("the summariser answered with nothing".to_owned())
}
Ok(summary) => CompactionOutcome::Summarized(summary),
Err(error) => CompactionOutcome::Refused(error.to_string()),
}
}
pub async fn summarize_history(provider: &dyn Provider, history: &[Message]) -> Result<String> {
let request = vec![Message::user(format!(
"Summarize this session.\n\n{}",
render_transcript(history)
))];
let mut sink = crate::DiscardSink;
let turn = provider
.send(SUMMARIZER_SYSTEM_PROMPT, &request, &[], &mut sink)
.await?;
Ok(turn.text)
}
pub async fn summarize_now(
provider: &dyn Provider,
settings: &CompactSettings,
history: &[Message],
) -> Result<String> {
summarize_history(provider, summary_request_messages(history, settings)).await
}
fn render_transcript(history: &[Message]) -> String {
let mut out = String::new();
for message in history {
let _ = writeln!(out, "{}: {}", message.role().as_str(), message.text());
if let Message::Assistant { tool_calls, .. } = message {
for call in tool_calls {
let _ = writeln!(out, " called {}({})", call.name, call.arguments);
}
}
}
out
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::as_conversions,
clippy::arithmetic_side_effects
)]
use super::{
CompactSettings, CompactionOutcome, SUMMARY_RESERVE_TOKENS, estimate_tokens,
should_compact, summarize_if_needed, summary_request_messages,
};
use crate::{AssistantToolCall, Message, Turn};
struct Refuses;
#[async_trait::async_trait]
impl crate::Provider for Refuses {
async fn send(
&self,
_system: &str,
_history: &[Message],
_tools: &[crate::ToolDef],
_sink: &mut (dyn crate::TextSink + Send),
) -> crate::Result<Turn> {
Err(crate::Error::Provider(
"maximum context length exceeded".to_owned(),
))
}
}
fn branch(count: usize, size: usize) -> Vec<Message> {
(0..count)
.map(|_| Message::user("x".repeat(size)))
.collect()
}
#[test]
fn a_summary_request_carries_only_what_fits() {
let settings = CompactSettings {
context_window: 200_000,
};
let history = branch(20, 40_000);
assert!(
estimate_tokens(&history) >= settings.threshold(),
"the branch is due a summary: {}",
estimate_tokens(&history)
);
let fitted = summary_request_messages(&history, &settings);
assert!(
fitted.len() < history.len() && fitted.len() > 1,
"clamped part way, not to a single message: {} of {}",
fitted.len(),
history.len()
);
assert!(
estimate_tokens(fitted) <= settings.threshold(),
"what is sent must fit: {} against {}",
estimate_tokens(fitted),
settings.threshold()
);
assert_eq!(
fitted.last().map(|m| m.text().len()),
Some(40_000),
"the newest message is always kept"
);
}
#[test]
fn a_branch_that_fits_is_not_shortened() {
let settings = CompactSettings {
context_window: 200_000,
};
let history = branch(3, 100);
assert_eq!(summary_request_messages(&history, &settings), &history[..]);
}
struct SaysNothing;
#[async_trait::async_trait]
impl crate::Provider for SaysNothing {
async fn send(
&self,
_system: &str,
_history: &[Message],
_tools: &[crate::ToolDef],
_sink: &mut (dyn crate::TextSink + Send),
) -> crate::Result<Turn> {
Ok(Turn::default())
}
}
#[tokio::test]
async fn an_empty_summary_is_a_refusal_rather_than_a_silent_loss() {
let settings = CompactSettings {
context_window: 40_000,
};
let history = branch(40, 4_000);
let outcome = summarize_if_needed(&SaysNothing, &settings, &history).await;
assert!(
matches!(outcome, CompactionOutcome::Refused(_)),
"an empty summary must not shadow the branch: {outcome:?}"
);
}
#[test]
fn a_branch_smaller_than_the_budget_still_yields_its_last_message() {
let settings = CompactSettings {
context_window: 4_096,
};
let history = branch(2, 8_000);
let fitted = summary_request_messages(&history, &settings);
assert_eq!(fitted.len(), 1);
}
#[tokio::test]
async fn a_refused_summariser_is_reported_rather_than_propagated() {
let settings = CompactSettings {
context_window: 40_000,
};
let history = branch(40, 4_000);
let outcome = summarize_if_needed(&Refuses, &settings, &history).await;
assert!(
matches!(outcome, CompactionOutcome::Refused(_)),
"a refusal must be a variant, not an error: {outcome:?}"
);
let CompactionOutcome::Refused(reason) = &outcome else {
return;
};
assert!(
reason.contains("maximum context length"),
"the provider's own reason is kept: {reason}"
);
}
#[tokio::test]
async fn a_branch_that_does_not_need_compaction_sends_nothing() {
let settings = CompactSettings {
context_window: 200_000,
};
let outcome = summarize_if_needed(&Refuses, &settings, &branch(3, 100)).await;
assert_eq!(outcome, CompactionOutcome::NotNeeded);
}
#[test]
fn the_threshold_leaves_room_below_the_window() {
let settings = CompactSettings {
context_window: 200_000,
};
assert_eq!(settings.threshold(), 200_000 - SUMMARY_RESERVE_TOKENS);
}
#[test]
fn a_window_smaller_than_the_reserve_has_a_zero_threshold() {
assert_eq!(CompactSettings { context_window: 10 }.threshold(), 0);
}
#[test]
fn compaction_is_due_at_the_threshold_not_only_after_it() {
let settings = CompactSettings {
context_window: 100_000,
};
assert!(!should_compact(&settings, settings.threshold() - 1));
assert!(should_compact(&settings, settings.threshold()));
}
#[test]
fn an_empty_conversation_costs_nothing() {
assert_eq!(estimate_tokens(&[]), 0);
}
#[test]
fn four_bytes_are_roughly_one_token() {
assert_eq!(estimate_tokens(&[Message::user("x".repeat(400))]), 100);
}
#[test]
fn tool_arguments_count_toward_the_size() {
let call = AssistantToolCall {
id: "c1".to_owned(),
name: "read".to_owned(),
arguments: "{\"path\":\"a\"}".to_owned(),
};
let with = estimate_tokens(&[Message::assistant_with_calls("", vec![call])]);
let without = estimate_tokens(&[Message::assistant("")]);
assert!(with > without, "{with} should exceed {without}");
}
}