Skip to main content

telos_agent/agent/compaction/
mod.rs

1//! Conversation compaction — keep the working context small enough to fit.
2//!
3//! Two levels of compaction are provided:
4//! - [`message_truncation`] — per-message truncation.
5//! - [`history_summary`] — history-level summarisation.
6//!
7//! The runtime applies both during turns started by [`AgentRuntime`](crate::AgentRuntime).
8
9pub mod history_summary;
10pub mod message_truncation;
11
12use crate::model::message::{ContentBlock, Message};
13use crate::model::provider::ModelProvider;
14
15pub use history_summary::{HistoryCompactionStrategy, SummaryHistoryCompaction};
16pub use message_truncation::{
17    ContentCompressor, MessageTruncationConfig, MessageTruncationResult, TruncationCompressor,
18    truncate_message,
19};
20
21/// Sum estimated token counts across every block in `messages`.
22pub(crate) fn estimate_message_tokens(messages: &[Message], provider: &dyn ModelProvider) -> usize {
23    messages
24        .iter()
25        .flat_map(|message| message.blocks.iter())
26        .map(|block| match block {
27            ContentBlock::Text(text) => provider.estimate_tokens(&text.text),
28            ContentBlock::Thinking(thinking) => provider.estimate_tokens(&thinking.text),
29            ContentBlock::ToolCall(call) => {
30                provider.estimate_tokens(&call.name)
31                    + provider.estimate_tokens(&call.arguments.to_string())
32            }
33            ContentBlock::ToolResult(result) => {
34                provider.estimate_tokens(&result.content.to_string())
35            }
36        })
37        .sum()
38}