use serde::{Deserialize, Serialize};
use crate::message::{Message, Part, Role};
#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema)]
pub struct ContextManager {
pub max_input_tokens: u64,
pub preserve_recent_turns: usize,
}
impl Default for ContextManager {
fn default() -> Self {
Self {
max_input_tokens: 30_000,
preserve_recent_turns: 3,
}
}
}
impl ContextManager {
pub(super) fn truncate_history(&self, history: &mut [Message]) {
if history.is_empty() {
return;
}
let preserve_from = find_preserve_boundary(history, self.preserve_recent_turns);
let start_idx = if history[0].role == Role::System {
1
} else {
0
};
debug_assert!(
preserve_from == 0 || start_idx <= preserve_from,
"start_idx ({start_idx}) > preserve_from ({preserve_from}): \
truncation window would overlap the system message"
);
for msg in history.iter_mut().take(preserve_from).skip(start_idx) {
if msg.role == Role::Tool {
let original_id = msg.id.clone();
let placeholder =
Message::new(Role::Tool).with_contents([Part::text("[context truncated]")]);
*msg = if let Some(id) = original_id {
placeholder.with_id(id)
} else {
placeholder
};
}
}
}
}
fn find_preserve_boundary(history: &[Message], preserve_recent_turns: usize) -> usize {
if preserve_recent_turns == 0 {
return history.len();
}
let mut turns_found = 0usize;
let mut i = history.len();
while i > 0 {
i -= 1;
if history[i].role == Role::System {
continue;
}
if history[i].role == Role::User {
turns_found += 1;
if turns_found >= preserve_recent_turns {
return i;
}
}
}
0
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
datatype::Value,
message::{Message, Part, Role},
};
fn sys() -> Message {
Message::new(Role::System).with_contents([Part::text("system")])
}
fn user(text: &str) -> Message {
Message::new(Role::User).with_contents([Part::text(text)])
}
fn asst(text: &str) -> Message {
Message::new(Role::Assistant).with_contents([Part::text(text)])
}
fn tool_result(id: &str) -> Message {
Message::new(Role::Tool)
.with_id(id)
.with_contents([Part::value(Value::string("ok".to_string()))])
}
fn tool_call_asst(call_id: &str, tool_name: &str) -> Message {
Message::new(Role::Assistant).with_tool_calls([Part::function(
call_id,
tool_name,
Value::null(),
)])
}
#[test]
fn test_preserve_recent_turns_boundary() {
let history = vec![
sys(),
user("u1"),
asst("a1"),
user("u2"),
asst("a2"),
user("u3"),
asst("a3"),
];
let boundary = find_preserve_boundary(&history, 2);
assert_eq!(boundary, 3, "preserve boundary should be at u2 (index 3)");
}
#[test]
fn test_no_change_when_all_within_preserve_window() {
let mut history = vec![sys(), user("u1"), asst("a1"), user("u2"), asst("a2")];
let cm = ContextManager {
max_input_tokens: 30_000,
preserve_recent_turns: 10,
};
let original_len = history.len();
cm.truncate_history(&mut history);
assert_eq!(history.len(), original_len, "nothing should change");
}
#[test]
fn test_tool_placeholder_replacement() {
let mut history = vec![
sys(),
user("u1"),
tool_call_asst("call_1", "my_tool"),
tool_result("call_1"),
user("u2"),
asst("a2"),
];
let cm = ContextManager {
max_input_tokens: 30_000,
preserve_recent_turns: 1,
};
cm.truncate_history(&mut history);
let tool_msg = history.iter().find(|m| m.role == Role::Tool);
assert!(
tool_msg.is_some(),
"Tool message must still exist as placeholder"
);
let tool_msg = tool_msg.unwrap();
assert_eq!(
tool_msg.id.as_deref(),
Some("call_1"),
"tool_use_id must be preserved to avoid Anthropic 400 errors"
);
let content = tool_msg
.contents
.first()
.expect("placeholder must have content");
let val = content
.as_text()
.expect("placeholder content must be a Value part");
assert_eq!(
val, "[context truncated]",
"placeholder content must be '[context truncated]'"
);
}
#[test]
fn test_system_message_never_dropped() {
let mut history = vec![
sys(),
user("u1"),
asst("a1"),
user("u2"),
asst("a2"),
user("u3"),
asst("a3"),
];
let cm = ContextManager {
max_input_tokens: 30_000,
preserve_recent_turns: 1,
};
cm.truncate_history(&mut history);
assert_eq!(
history[0].role,
Role::System,
"System message must always remain at index 0"
);
assert_eq!(history.len(), 7, "no messages should be dropped");
}
#[test]
fn test_preserve_counts_user_messages_not_assistant() {
let history = vec![
sys(),
user("u1"),
asst("a1"),
user("u2"),
tool_call_asst("call_1", "my_tool"),
tool_result("call_1"),
asst("a2"),
];
let boundary = find_preserve_boundary(&history, 2);
assert_eq!(
boundary, 1,
"preserve_recent_turns=2 must keep 2 user turns, landing at u1 (index 1)"
);
}
#[test]
fn test_preserved_messages_untouched() {
let mut history = vec![
sys(),
user("u1"),
asst("a1"),
user("u2"),
tool_call_asst("call_2", "tool_b"),
tool_result("call_2"),
asst("a2"),
];
let cm = ContextManager {
max_input_tokens: 30_000,
preserve_recent_turns: 1,
};
cm.truncate_history(&mut history);
let tool_msg = history
.iter()
.find(|m| m.role == Role::Tool)
.expect("tool result must still be present");
let val = tool_msg
.contents
.first()
.and_then(|p| p.as_value())
.expect("tool result content must be a Value part");
assert_eq!(
val.as_str(),
Some("ok"),
"tool result inside preserve window must not be replaced"
);
}
}