1use std::collections::{HashMap, HashSet};
4use std::fmt::Write as _;
5
6use aither_core::{LanguageModel, llm::Message};
7use num_traits::ToPrimitive;
8
9const CONTENT_WITH_URLS_PLACEHOLDER: &str = "{content_with_urls}";
10const COMMANDS_PLACEHOLDER: &str = "{commands}";
11const DIALOGUE_PLACEHOLDER: &str = "{dialogue}";
12const ERRORS_PLACEHOLDER: &str = "{errors}";
13const FILE_PATHS_PLACEHOLDER: &str = "{file_paths}";
14const RUNNING_JOBS_PLACEHOLDER: &str = "{running_jobs}";
15
16#[derive(Debug, Clone)]
18pub enum ContextStrategy {
19 Unlimited,
21
22 Smart(SmartCompressionConfig),
24}
25
26impl Default for ContextStrategy {
27 fn default() -> Self {
28 Self::Smart(SmartCompressionConfig::default())
29 }
30}
31
32#[derive(Debug, Clone)]
34pub struct SmartCompressionConfig {
35 pub trigger_threshold: f32,
37
38 pub emergency_threshold: f32,
40
41 pub preserve_recent: usize,
43
44 pub preserve: PreserveConfig,
46
47 pub level: CompressionLevel,
49}
50
51impl Default for SmartCompressionConfig {
52 fn default() -> Self {
53 Self {
54 trigger_threshold: 0.7,
55 emergency_threshold: 0.9,
56 preserve_recent: 8,
57 preserve: PreserveConfig::default(),
58 level: CompressionLevel::Standard,
59 }
60 }
61}
62
63#[allow(clippy::struct_excessive_bools)]
67#[derive(Debug, Clone)]
68pub struct PreserveConfig {
69 pub file_paths: bool,
71 pub errors: bool,
73 pub commands: bool,
75}
76
77impl Default for PreserveConfig {
78 fn default() -> Self {
79 Self {
80 file_paths: true,
81 errors: true,
82 commands: true,
83 }
84 }
85}
86
87#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
89pub enum CompressionLevel {
90 Light,
92 #[default]
94 Standard,
95 Aggressive,
97}
98
99#[derive(Debug, Default)]
101pub struct PreservedContent {
102 pub file_paths: Vec<String>,
104 pub errors: Vec<String>,
106 pub commands: Vec<String>,
108 pub running_jobs: Option<String>,
111}
112
113#[must_use]
115pub const fn estimate_tokens(content: &str) -> usize {
116 content.len() / 4
117}
118
119#[must_use]
121pub fn estimate_context_usage(messages: &[Message], context_window: usize) -> f32 {
122 let message_tokens: usize = messages.iter().map(|m| estimate_tokens(m.content())).sum();
123 let message_tokens = message_tokens.to_f32().unwrap_or(f32::MAX);
124 let context_window = context_window.to_f32().unwrap_or(f32::MAX);
125 message_tokens / context_window
126}
127
128const COMPRESSION_SYSTEM_PROMPT: &str = include_str!("prompts/compression_system.txt");
130const COMPRESSION_USER_TEMPLATE: &str = include_str!("prompts/compression_user.txt");
131const COMPRESSION_URLS_TEMPLATE: &str = include_str!("prompts/compression_urls.txt");
132
133#[derive(Debug, Clone)]
135pub struct CompactionResult {
136 pub summary: String,
138 pub referenced_urls: HashSet<String>,
140}
141
142#[derive(Debug, Clone)]
144pub struct ContentWithUrl {
145 pub content: String,
147 pub url: String,
149}
150
151impl SmartCompressionConfig {
152 pub const COMPACTION_RESERVE: f32 = 0.2;
154
155 #[must_use]
160 pub fn effective_trigger(&self) -> f32 {
161 self.trigger_threshold - Self::COMPACTION_RESERVE
162 }
163
164 #[must_use]
166 pub fn extract_preserved(&self, messages: &[Message]) -> PreservedContent {
167 let mut preserved = PreservedContent::default();
168
169 for msg in messages {
170 let content = msg.content();
171
172 if self.preserve.file_paths {
173 preserved.file_paths.extend(extract_file_paths(content));
174 }
175
176 if self.preserve.errors {
177 preserved.errors.extend(extract_errors(content));
178 }
179
180 if self.preserve.commands {
181 preserved.commands.extend(extract_commands(content));
182 }
183 }
184
185 preserved
186 }
187
188 #[must_use]
194 pub fn find_stale_tool_calls(&self, messages: &[Message]) -> HashSet<usize> {
195 let mut stale = HashSet::new();
196 let mut file_versions: HashMap<String, usize> = HashMap::new();
197
198 for (idx, msg) in messages.iter().enumerate() {
199 let content = msg.content();
200
201 if is_trivial_result(content) {
203 stale.insert(idx);
204 }
205
206 if (content.contains("read_file") || content.contains("Read"))
208 && let Some(path) = extract_single_path(content)
209 && let Some(&later_idx) = file_versions.get(&path)
210 && later_idx > idx
211 {
212 stale.insert(idx);
213 }
214
215 if (content.contains("write_file")
217 || content.contains("edit_file")
218 || content.contains("Write")
219 || content.contains("Edit"))
220 && let Some(path) = extract_single_path(content)
221 {
222 file_versions.insert(path, idx);
223 }
224 }
225
226 stale
227 }
228
229 pub async fn generate_summary<LLM: LanguageModel>(
235 &self,
236 llm: &LLM,
237 messages: &[Message],
238 preserved: &PreservedContent,
239 ) -> Result<String, LLM::Error> {
240 let running_jobs = preserved
241 .running_jobs
242 .as_ref()
243 .map_or(String::new(), |jobs| {
244 format!("- Running background jobs:\n{jobs}")
245 });
246
247 #[allow(clippy::literal_string_with_formatting_args)]
250 let prompt = COMPRESSION_USER_TEMPLATE
251 .replace(FILE_PATHS_PLACEHOLDER, &preserved.file_paths.join(", "))
252 .replace(ERRORS_PLACEHOLDER, &preserved.errors.join("\n"))
253 .replace(COMMANDS_PLACEHOLDER, &preserved.commands.join("\n"))
254 .replace(RUNNING_JOBS_PLACEHOLDER, &running_jobs)
255 .replace(DIALOGUE_PLACEHOLDER, &format_messages(messages));
256
257 let request = aither_core::llm::oneshot(COMPRESSION_SYSTEM_PROMPT, prompt);
258 let stream = llm.respond(request);
259 aither_core::llm::collect_text(stream).await
260 }
261
262 pub async fn generate_summary_with_urls<LLM: LanguageModel>(
283 &self,
284 llm: &LLM,
285 messages: &[Message],
286 preserved: &PreservedContent,
287 pending_urls: &[ContentWithUrl],
288 ) -> Result<CompactionResult, LLM::Error> {
289 let content_with_urls = format_content_with_urls(messages, pending_urls);
291
292 let running_jobs = preserved
293 .running_jobs
294 .as_ref()
295 .map_or(String::new(), |jobs| {
296 format!("- Running background jobs:\n{jobs}")
297 });
298
299 #[allow(clippy::literal_string_with_formatting_args)]
302 let prompt = COMPRESSION_URLS_TEMPLATE
303 .replace(CONTENT_WITH_URLS_PLACEHOLDER, &content_with_urls)
304 .replace(FILE_PATHS_PLACEHOLDER, &preserved.file_paths.join(", "))
305 .replace(ERRORS_PLACEHOLDER, &preserved.errors.join("\n"))
306 .replace(COMMANDS_PLACEHOLDER, &preserved.commands.join("\n"))
307 .replace(RUNNING_JOBS_PLACEHOLDER, &running_jobs);
308
309 let request = aither_core::llm::oneshot(COMPRESSION_SYSTEM_PROMPT, prompt);
310 let stream = llm.respond(request);
311 let summary = aither_core::llm::collect_text(stream).await?;
312
313 let referenced_urls = extract_referenced_urls(&summary);
315
316 Ok(CompactionResult {
317 summary,
318 referenced_urls,
319 })
320 }
321}
322
323fn extract_file_paths(content: &str) -> Vec<String> {
325 let mut paths = Vec::new();
326
327 for word in content.split_whitespace() {
329 let word = word.trim_matches(|c: char| c == '"' || c == '\'' || c == '`' || c == ',');
330
331 if word.starts_with('/') && word.len() > 1 && !word.contains(' ') {
333 paths.push(word.to_string());
334 }
335
336 if (word.contains('/') || word.contains('.'))
338 && !word.starts_with("http")
339 && !word.contains(' ')
340 && word.len() > 2
341 {
342 let extensions = [
344 ".rs", ".py", ".js", ".ts", ".go", ".java", ".c", ".cpp", ".h", ".md", ".txt",
345 ".json", ".yaml", ".yml", ".toml", ".xml", ".html", ".css",
346 ];
347 if extensions.iter().any(|ext| word.ends_with(ext)) {
348 paths.push(word.to_string());
349 }
350 }
351 }
352
353 paths.sort();
354 paths.dedup();
355 paths
356}
357
358fn extract_single_path(content: &str) -> Option<String> {
360 extract_file_paths(content).into_iter().next()
361}
362
363fn extract_errors(content: &str) -> Vec<String> {
365 let mut errors = Vec::new();
366
367 for line in content.lines() {
369 let lower = line.to_lowercase();
370 if lower.contains("error")
371 || lower.contains("failed")
372 || lower.contains("panic")
373 || lower.contains("exception")
374 {
375 errors.push(line.trim().to_string());
376 }
377 }
378
379 errors
380}
381
382fn extract_commands(content: &str) -> Vec<String> {
384 let mut commands = Vec::new();
385
386 for line in content.lines() {
388 let trimmed = line.trim();
389 if trimmed.starts_with('$') || trimmed.starts_with('>') {
390 commands.push(trimmed.to_string());
391 }
392
393 let cmd_prefixes = [
395 "cargo ", "bun ", "bunx ", "npm ", "git ", "docker ", "make ", "rustc ", "python ",
396 "node ", "go ", "cd ", "ls ", "cat ", "mkdir ", "rm ", "mv ", "cp ",
397 ];
398 if cmd_prefixes.iter().any(|p| trimmed.starts_with(p)) {
399 commands.push(trimmed.to_string());
400 }
401 }
402
403 commands
404}
405
406fn is_trivial_result(result: &str) -> bool {
408 let trivial_patterns = [
409 "ok",
410 "success",
411 "done",
412 "file written",
413 "file saved",
414 "completed",
415 ];
416 let lower = result.to_lowercase();
417 trivial_patterns.iter().any(|t| lower.contains(t)) && result.len() < 50
418}
419
420fn format_messages(messages: &[Message]) -> String {
422 messages
423 .iter()
424 .map(|msg| format!("{:?}: {}", msg.role(), msg.content()))
425 .collect::<Vec<_>>()
426 .join("\n")
427}
428
429fn format_content_with_urls(messages: &[Message], pending_urls: &[ContentWithUrl]) -> String {
433 let mut output = String::new();
434
435 for msg in messages {
436 let content = msg.content();
437
438 let url = pending_urls.iter().find(|p| p.content == content);
440
441 if let Some(url_info) = url {
442 let _ = writeln!(output, "### [URL: {}]\n{}\n", url_info.url, content);
444 } else {
445 let _ = writeln!(output, "### [Inline - {:?}]\n{}\n", msg.role(), content);
447 }
448 }
449
450 output
451}
452
453#[must_use]
468pub fn extract_referenced_urls(summary: &str) -> HashSet<String> {
469 let mut urls = HashSet::new();
470
471 for word in summary.split_whitespace() {
474 let word = word.trim_matches(|c: char| {
476 c == '"' || c == '\'' || c == '`' || c == ',' || c == '.' || c == ')' || c == ']'
477 });
478
479 if word.starts_with("outputs/") {
480 let filename = word.strip_prefix("outputs/").unwrap_or("");
482 if is_valid_output_filename(filename) {
483 urls.insert(word.to_string());
484 }
485 }
486 }
487
488 urls
489}
490
491fn is_valid_output_filename(filename: &str) -> bool {
493 let Some((name, ext)) = filename.rsplit_once('.') else {
495 return false;
496 };
497
498 if ext.is_empty() || !ext.chars().all(|c| c.is_ascii_alphanumeric()) {
500 return false;
501 }
502
503 let parts: Vec<&str> = name.split('-').collect();
505 if parts.len() != 4 {
506 return false;
507 }
508
509 parts
511 .iter()
512 .all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_lowercase()))
513}
514
515#[cfg(test)]
516mod tests {
517 use super::*;
518
519 #[test]
520 fn test_extract_file_paths() {
521 let content = "I modified /Users/user/project/src/main.rs and also checked lib.rs";
522 let paths = extract_file_paths(content);
523 assert!(paths.contains(&"/Users/user/project/src/main.rs".to_string()));
524 assert!(paths.contains(&"lib.rs".to_string()));
525 }
526
527 #[test]
528 fn test_trivial_result() {
529 assert!(is_trivial_result("OK"));
530 assert!(is_trivial_result("File written successfully"));
531 assert!(!is_trivial_result(
532 "This is a long result with actual content that should be preserved"
533 ));
534 }
535
536 #[test]
537 fn test_estimate_tokens() {
538 let content = "This is a test string with some content";
539 let tokens = estimate_tokens(content);
540 assert!(tokens > 0);
541 assert!(tokens < content.len());
542 }
543
544 #[test]
545 fn test_extract_referenced_urls() {
546 let summary = "The agent read config from outputs/amber-oak-swift-river.txt and saved data to outputs/bold-creek-calm-dawn.json.";
547 let urls = extract_referenced_urls(summary);
548 assert_eq!(urls.len(), 2);
549 assert!(urls.contains("outputs/amber-oak-swift-river.txt"));
550 assert!(urls.contains("outputs/bold-creek-calm-dawn.json"));
551 }
552
553 #[test]
554 fn test_extract_urls_with_punctuation() {
555 let summary = r#"See "outputs/jade-mist-clear-pool.txt" for details."#;
557 let urls = extract_referenced_urls(summary);
558 assert!(urls.contains("outputs/jade-mist-clear-pool.txt"));
559 }
560
561 #[test]
562 fn test_invalid_url_patterns() {
563 let summary = "Not valid: outputs/single.txt outputs/two-words.txt outputs/ outputs/one-two-three.txt";
565 let urls = extract_referenced_urls(summary);
566 assert!(urls.is_empty());
567 }
568
569 #[test]
570 fn test_valid_output_filename() {
571 assert!(is_valid_output_filename("amber-oak-swift-river.txt"));
572 assert!(is_valid_output_filename("bold-creek-calm-dawn.json"));
573 assert!(!is_valid_output_filename("single.txt"));
574 assert!(!is_valid_output_filename("two-words.txt"));
575 assert!(!is_valid_output_filename("no-extension"));
576 assert!(!is_valid_output_filename("Upper-Case-Words.txt"));
577 }
578}