|
| 1 | +use echo_system_types::llm::{ContentBlock, LmProvider, Message, MessageContent, Role}; |
| 2 | + |
| 3 | +/// Default context budget in estimated tokens (leaves room for system prompt + response). |
| 4 | +const DEFAULT_CONTEXT_BUDGET: usize = 150_000; |
| 5 | + |
| 6 | +/// How many of the most recent messages to always keep uncompacted. |
| 7 | +const KEEP_RECENT: usize = 20; |
| 8 | + |
| 9 | +/// Minimum messages before compaction is even considered. |
| 10 | +const MIN_MESSAGES_FOR_COMPACTION: usize = 30; |
| 11 | + |
| 12 | +/// Rough chars-per-token estimate for English text. |
| 13 | +const CHARS_PER_TOKEN: usize = 4; |
| 14 | + |
| 15 | +/// Estimate the token count of a single message. |
| 16 | +pub fn estimate_message_tokens(msg: &Message) -> usize { |
| 17 | + let chars = match &msg.content { |
| 18 | + MessageContent::Text(s) => s.len(), |
| 19 | + MessageContent::Blocks(blocks) => blocks |
| 20 | + .iter() |
| 21 | + .map(|block| match block { |
| 22 | + ContentBlock::Text { text } => text.len(), |
| 23 | + ContentBlock::ToolUse { name, input, .. } => name.len() + input.to_string().len(), |
| 24 | + ContentBlock::ToolResult { content, .. } => content.len(), |
| 25 | + }) |
| 26 | + .sum(), |
| 27 | + }; |
| 28 | + // Add overhead for role/structure (~20 tokens) |
| 29 | + (chars / CHARS_PER_TOKEN) + 20 |
| 30 | +} |
| 31 | + |
| 32 | +/// Estimate the total token count of a conversation. |
| 33 | +pub fn estimate_conversation_tokens(conversation: &[Message]) -> usize { |
| 34 | + conversation.iter().map(estimate_message_tokens).sum() |
| 35 | +} |
| 36 | + |
| 37 | +/// Extract text content from a message for summarization purposes. |
| 38 | +fn message_to_text(msg: &Message) -> String { |
| 39 | + match &msg.content { |
| 40 | + MessageContent::Text(s) => s.clone(), |
| 41 | + MessageContent::Blocks(blocks) => blocks |
| 42 | + .iter() |
| 43 | + .filter_map(|block| match block { |
| 44 | + ContentBlock::Text { text } => Some(text.as_str()), |
| 45 | + ContentBlock::ToolUse { name, .. } => Some(name.as_str()), |
| 46 | + ContentBlock::ToolResult { content, .. } => { |
| 47 | + // Truncate large tool results in the summary input |
| 48 | + if content.len() > 500 { |
| 49 | + None |
| 50 | + } else { |
| 51 | + Some(content.as_str()) |
| 52 | + } |
| 53 | + } |
| 54 | + }) |
| 55 | + .collect::<Vec<_>>() |
| 56 | + .join(" "), |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +/// Build a summarization prompt from the messages being compacted. |
| 61 | +fn build_summary_prompt(messages: &[Message]) -> String { |
| 62 | + let mut lines = Vec::new(); |
| 63 | + for msg in messages { |
| 64 | + let role = match msg.role { |
| 65 | + Role::User => "User", |
| 66 | + Role::Assistant => "Assistant", |
| 67 | + }; |
| 68 | + let text = message_to_text(msg); |
| 69 | + if !text.is_empty() { |
| 70 | + // Truncate extremely long messages in the summarization input |
| 71 | + let truncated = if text.len() > 2000 { |
| 72 | + format!("{}...", &text[..1997]) |
| 73 | + } else { |
| 74 | + text |
| 75 | + }; |
| 76 | + lines.push(format!("{}: {}", role, truncated)); |
| 77 | + } |
| 78 | + } |
| 79 | + lines.join("\n") |
| 80 | +} |
| 81 | + |
| 82 | +/// Compact a conversation by summarizing older messages. |
| 83 | +/// |
| 84 | +/// If the conversation is under the token budget or too short, returns it unchanged. |
| 85 | +/// Otherwise, summarizes the oldest messages (keeping the most recent ones intact) |
| 86 | +/// and replaces them with a single summary message. |
| 87 | +pub async fn compact_if_needed( |
| 88 | + conversation: &mut Vec<Message>, |
| 89 | + provider: &dyn LmProvider, |
| 90 | + context_budget: usize, |
| 91 | + max_tokens: u32, |
| 92 | +) { |
| 93 | + let budget = if context_budget > 0 { |
| 94 | + context_budget |
| 95 | + } else { |
| 96 | + DEFAULT_CONTEXT_BUDGET |
| 97 | + }; |
| 98 | + |
| 99 | + // Don't compact small conversations |
| 100 | + if conversation.len() < MIN_MESSAGES_FOR_COMPACTION { |
| 101 | + return; |
| 102 | + } |
| 103 | + |
| 104 | + let total_tokens = estimate_conversation_tokens(conversation); |
| 105 | + if total_tokens <= budget { |
| 106 | + return; |
| 107 | + } |
| 108 | + |
| 109 | + tracing::info!( |
| 110 | + "Context compaction triggered: ~{} tokens (budget {}), {} messages", |
| 111 | + total_tokens, |
| 112 | + budget, |
| 113 | + conversation.len() |
| 114 | + ); |
| 115 | + |
| 116 | + // Split: older messages to summarize, recent messages to keep |
| 117 | + let keep_count = KEEP_RECENT.min(conversation.len()); |
| 118 | + let split_at = conversation.len() - keep_count; |
| 119 | + |
| 120 | + if split_at < 2 { |
| 121 | + // Not enough old messages to summarize — just trim |
| 122 | + let drain_count = conversation.len().saturating_sub(keep_count); |
| 123 | + conversation.drain(..drain_count); |
| 124 | + return; |
| 125 | + } |
| 126 | + |
| 127 | + let old_messages = &conversation[..split_at]; |
| 128 | + let summary_input = build_summary_prompt(old_messages); |
| 129 | + |
| 130 | + let summarize_prompt = format!( |
| 131 | + "Summarize this conversation concisely, preserving key decisions, code context, \ |
| 132 | + task state, and important details. Focus on what matters for continuing the \ |
| 133 | + conversation. Be direct — no preamble.\n\n{}", |
| 134 | + summary_input |
| 135 | + ); |
| 136 | + |
| 137 | + let summary_messages = vec![Message { |
| 138 | + role: Role::User, |
| 139 | + content: MessageContent::Text(summarize_prompt), |
| 140 | + }]; |
| 141 | + |
| 142 | + // Use the same provider to generate the summary |
| 143 | + let summary_text = match provider |
| 144 | + .invoke( |
| 145 | + "You are a concise summarizer. Output only the summary.", |
| 146 | + &summary_messages, |
| 147 | + max_tokens.min(2048), |
| 148 | + None, |
| 149 | + ) |
| 150 | + .await |
| 151 | + { |
| 152 | + Ok(result) => result.text(), |
| 153 | + Err(e) => { |
| 154 | + tracing::warn!( |
| 155 | + "Context compaction failed: {}. Falling back to simple trim.", |
| 156 | + e |
| 157 | + ); |
| 158 | + // Fall back to simple trim |
| 159 | + conversation.drain(..split_at); |
| 160 | + return; |
| 161 | + } |
| 162 | + }; |
| 163 | + |
| 164 | + // Replace old messages with the summary |
| 165 | + conversation.drain(..split_at); |
| 166 | + conversation.insert( |
| 167 | + 0, |
| 168 | + Message { |
| 169 | + role: Role::User, |
| 170 | + content: MessageContent::Text(format!( |
| 171 | + "[Context summary of earlier conversation]\n{}", |
| 172 | + summary_text |
| 173 | + )), |
| 174 | + }, |
| 175 | + ); |
| 176 | + |
| 177 | + let new_tokens = estimate_conversation_tokens(conversation); |
| 178 | + tracing::info!( |
| 179 | + "Compacted {} messages into summary. ~{} → ~{} tokens", |
| 180 | + split_at, |
| 181 | + total_tokens, |
| 182 | + new_tokens |
| 183 | + ); |
| 184 | +} |
0 commit comments