aien-sovereign-core
Autonomous sovereign intelligence engine and runtime core for NVIDIA DGX Spark
Brought by drakestapleton
aien-sovereign-core / crates / aien-cli / src / compaction.rs
| 1 | use serde::{Deserialize, Serialize}; |
| 2 | use serde_json::{json, Value}; |
| 3 | use chrono::Utc; |
| 4 | |
| 5 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 6 | pub struct CompactionStats { |
| 7 | pub initial_tokens: usize, |
| 8 | pub compacted_tokens: usize, |
| 9 | pub pruned_messages_count: usize, |
| 10 | pub pruned_tool_bytes: usize, |
| 11 | } |
| 12 | |
| 13 | pub struct ContextCompactor { |
| 14 | pub max_tokens: usize, |
| 15 | pub trigger_threshold: usize, |
| 16 | pub target_tokens: usize, |
| 17 | } |
| 18 | |
| 19 | impl Default for ContextCompactor { |
| 20 | fn default() -> Self { |
| 21 | Self { |
| 22 | max_tokens: 24_000, |
| 23 | trigger_threshold: 18_000, |
| 24 | target_tokens: 10_000, |
| 25 | } |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | impl ContextCompactor { |
| 30 | pub fn new(max_tokens: usize, trigger_threshold: usize, target_tokens: usize) -> Self { |
| 31 | Self { |
| 32 | max_tokens, |
| 33 | trigger_threshold, |
| 34 | target_tokens, |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | /// Fast token estimator (~3.5 characters per token) |
| 39 | pub fn estimate_tokens(messages: &[Value]) -> usize { |
| 40 | let mut total_chars = 0; |
| 41 | for m in messages { |
| 42 | if let Some(content) = m.get("content").and_then(Value::as_str) { |
| 43 | total_chars += content.len(); |
| 44 | } |
| 45 | } |
| 46 | (total_chars as f64 / 3.5).ceil() as usize |
| 47 | } |
| 48 | |
| 49 | /// Evaluates if compaction is needed and performs safe pruning and summarizing |
| 50 | pub fn compact_if_needed(&self, messages: &mut Vec<Value>) -> Option<CompactionStats> { |
| 51 | let current_tokens = Self::estimate_tokens(messages); |
| 52 | if current_tokens < self.trigger_threshold || messages.len() <= 6 { |
| 53 | return None; |
| 54 | } |
| 55 | |
| 56 | let initial_tokens = current_tokens; |
| 57 | let mut pruned_bytes = 0; |
| 58 | |
| 59 | // Pass 1: Prune oversized tool responses in older turns (keep last 4 messages intact) |
| 60 | let protect_tail = 4; |
| 61 | let middle_end = if messages.len() > protect_tail { messages.len() - protect_tail } else { 2 }; |
| 62 | |
| 63 | for i in 2..middle_end { |
| 64 | if let Some(content) = messages[i].get("content").and_then(Value::as_str) { |
| 65 | if content.contains("<tool_response") && content.len() > 600 { |
| 66 | let tool_name = if let Some(start) = content.find("name=\"") { |
| 67 | let sub = &content[start + 6..]; |
| 68 | sub.split('"').next().unwrap_or("tool") |
| 69 | } else { |
| 70 | "tool" |
| 71 | }; |
| 72 | |
| 73 | let pruned_snippet = if content.len() > 100 { |
| 74 | &content[..80] |
| 75 | } else { |
| 76 | content |
| 77 | }; |
| 78 | |
| 79 | let compacted = format!( |
| 80 | "<tool_response name=\"{}\">\n[PRUNED_TOOL_OUTPUT: Original {} bytes compacted for context budget. Snippet: {}...]\n</tool_response>", |
| 81 | tool_name, |
| 82 | content.len(), |
| 83 | pruned_snippet.trim() |
| 84 | ); |
| 85 | |
| 86 | pruned_bytes += content.len().saturating_sub(compacted.len()); |
| 87 | messages[i]["content"] = json!(compacted); |
| 88 | } |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | let tokens_after_pass1 = Self::estimate_tokens(messages); |
| 93 | if tokens_after_pass1 <= self.target_tokens { |
| 94 | return Some(CompactionStats { |
| 95 | initial_tokens, |
| 96 | compacted_tokens: tokens_after_pass1, |
| 97 | pruned_messages_count: 0, |
| 98 | pruned_tool_bytes: pruned_bytes, |
| 99 | }); |
| 100 | } |
| 101 | |
| 102 | // Pass 2: If still over budget, summarize intermediate conversational turns |
| 103 | // Keep index 0 (system prompt) and index 1 (initial grounding) |
| 104 | // Group middle messages (index 2..middle_end) into a single concise recap block |
| 105 | let mut recap_lines = Vec::new(); |
| 106 | let mut pruned_msgs = 0; |
| 107 | |
| 108 | for i in 2..middle_end { |
| 109 | let role = messages[i].get("role").and_then(Value::as_str).unwrap_or("unknown"); |
| 110 | let content = messages[i].get("content").and_then(Value::as_str).unwrap_or(""); |
| 111 | let first_line = content.lines().next().unwrap_or("").chars().take(80).collect::<String>(); |
| 112 | recap_lines.push(format!("- [{}]: {}", role, first_line)); |
| 113 | pruned_msgs += 1; |
| 114 | } |
| 115 | |
| 116 | let recap_content = format!( |
| 117 | "<context_compaction_recap timestamp=\"{}\">\nCompacted {} historical turns for token budget:\n{}\n</context_compaction_recap>", |
| 118 | Utc::now().to_rfc3339(), |
| 119 | pruned_msgs, |
| 120 | recap_lines.join("\n") |
| 121 | ); |
| 122 | |
| 123 | // Splice middle messages out and replace with the recap block |
| 124 | let tail: Vec<Value> = messages.drain(middle_end..).collect(); |
| 125 | messages.truncate(2); |
| 126 | messages.push(json!({ |
| 127 | "role": "user", |
| 128 | "content": recap_content |
| 129 | })); |
| 130 | messages.extend(tail); |
| 131 | |
| 132 | let final_tokens = Self::estimate_tokens(messages); |
| 133 | |
| 134 | Some(CompactionStats { |
| 135 | initial_tokens, |
| 136 | compacted_tokens: final_tokens, |
| 137 | pruned_messages_count: pruned_msgs, |
| 138 | pruned_tool_bytes: pruned_bytes, |
| 139 | }) |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | #[cfg(test)] |
| 144 | mod tests { |
| 145 | use super::*; |
| 146 | |
| 147 | #[test] |
| 148 | fn test_context_compactor_pruning() { |
| 149 | let compactor = ContextCompactor::new(2000, 1000, 500); |
| 150 | |
| 151 | let mut messages = vec![ |
| 152 | json!({"role": "system", "content": "You are AIEN."}), |
| 153 | json!({"role": "user", "content": "Initiation grounding."}), |
| 154 | json!({"role": "user", "content": format!("<tool_response name=\"run_command\">\n{}\n</tool_response>", "X".repeat(5000))}), |
| 155 | json!({"role": "assistant", "content": "Tool processed."}), |
| 156 | json!({"role": "user", "content": "Next step."}), |
| 157 | json!({"role": "assistant", "content": "Final response."}), |
| 158 | json!({"role": "user", "content": "Keep this turn."}), |
| 159 | ]; |
| 160 | |
| 161 | let stats = compactor.compact_if_needed(&mut messages); |
| 162 | assert!(stats.is_some()); |
| 163 | let s = stats.unwrap(); |
| 164 | assert!(s.compacted_tokens < s.initial_tokens); |
| 165 | assert!(s.pruned_tool_bytes > 0); |
| 166 | } |
| 167 | } |