Skip to main content

aither_agent/
compression.rs

1//! Smart context compression for managing conversation history.
2
3use 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/// Strategy for managing conversation context.
17#[derive(Debug, Clone)]
18pub enum ContextStrategy {
19    /// No compression - keep all messages until context is full, then stop.
20    Unlimited,
21
22    /// Smart compression with selective preservation (default).
23    Smart(SmartCompressionConfig),
24}
25
26impl Default for ContextStrategy {
27    fn default() -> Self {
28        Self::Smart(SmartCompressionConfig::default())
29    }
30}
31
32/// Configuration for smart context compression.
33#[derive(Debug, Clone)]
34pub struct SmartCompressionConfig {
35    /// Trigger compression at this fraction of context window (default: 0.7).
36    pub trigger_threshold: f32,
37
38    /// Emergency compaction threshold (default: 0.9).
39    pub emergency_threshold: f32,
40
41    /// Number of recent messages to always keep verbatim.
42    pub preserve_recent: usize,
43
44    /// Types of content to preserve during compression.
45    pub preserve: PreserveConfig,
46
47    /// Compression level (trade-off between quality and size).
48    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/// Configuration for what content to preserve during compression.
64// Each flag is an independent, orthogonal preservation choice; grouping them
65// into an enum would not describe the domain any better.
66#[allow(clippy::struct_excessive_bools)]
67#[derive(Debug, Clone)]
68pub struct PreserveConfig {
69    /// Keep file paths verbatim.
70    pub file_paths: bool,
71    /// Keep error messages verbatim.
72    pub errors: bool,
73    /// Keep shell commands verbatim.
74    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/// Compression aggressiveness level.
88#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
89pub enum CompressionLevel {
90    /// Keep more detail, less compression.
91    Light,
92    /// Balanced compression.
93    #[default]
94    Standard,
95    /// Maximum compression.
96    Aggressive,
97}
98
99/// Content extracted and preserved during compression.
100#[derive(Debug, Default)]
101pub struct PreservedContent {
102    /// File paths found in messages.
103    pub file_paths: Vec<String>,
104    /// Error messages found.
105    pub errors: Vec<String>,
106    /// Shell commands found.
107    pub commands: Vec<String>,
108    /// Running background jobs (formatted text).
109    /// Only running jobs are preserved - completed jobs are ephemeral.
110    pub running_jobs: Option<String>,
111}
112
113/// Estimate tokens in a string (rough approximation: ~4 chars per token).
114#[must_use]
115pub const fn estimate_tokens(content: &str) -> usize {
116    content.len() / 4
117}
118
119/// Estimate context usage as a fraction of the window.
120#[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
128// Prompt templates loaded from files
129const 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/// Result of a compaction operation with URL tracking.
134#[derive(Debug, Clone)]
135pub struct CompactionResult {
136    /// The generated summary text.
137    pub summary: String,
138    /// URLs that were referenced in the summary (should be written to disk).
139    pub referenced_urls: HashSet<String>,
140}
141
142/// A pending URL allocation for content that hasn't been written to disk.
143#[derive(Debug, Clone)]
144pub struct ContentWithUrl {
145    /// The content in text form.
146    pub content: String,
147    /// The allocated URL for this content.
148    pub url: String,
149}
150
151impl SmartCompressionConfig {
152    /// Reserve 20% of context for the compaction process itself.
153    pub const COMPACTION_RESERVE: f32 = 0.2;
154
155    /// Returns the effective trigger threshold accounting for compaction reserve.
156    ///
157    /// The actual trigger is lower than `trigger_threshold` to leave room
158    /// for the fast LLM to see both URLs and original content during compaction.
159    #[must_use]
160    pub fn effective_trigger(&self) -> f32 {
161        self.trigger_threshold - Self::COMPACTION_RESERVE
162    }
163
164    /// Extract content that should be preserved from messages.
165    #[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    /// Identify indices of stale tool calls that can be safely removed.
189    ///
190    /// Stale tool calls include:
191    /// - Tool results that were just acknowledgments
192    /// - Read operations for files that were later modified
193    #[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            // Check for trivial results
202            if is_trivial_result(content) {
203                stale.insert(idx);
204            }
205
206            // Track file reads that may be superseded
207            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            // Track file modifications
216            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    /// Generate a compressed summary of messages.
230    ///
231    /// # Errors
232    ///
233    /// Returns an error if the LLM fails to generate a summary.
234    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        // The braces below are template placeholders for `str::replace`, not
248        // format arguments.
249        #[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    /// Generate a compressed summary with URL tracking for tool outputs.
263    ///
264    /// This method:
265    /// 1. Takes messages and their associated pending URLs
266    /// 2. Generates a summary that may reference those URLs
267    /// 3. Scans the summary to find which URLs were actually referenced
268    /// 4. Returns both the summary and the set of referenced URLs
269    ///
270    /// The caller should only write files for URLs that appear in `referenced_urls`.
271    ///
272    /// # Arguments
273    ///
274    /// * `llm` - The fast LLM to use for summary generation
275    /// * `messages` - Messages to compress
276    /// * `preserved` - Content to preserve verbatim
277    /// * `pending_urls` - Map of message content to allocated URLs
278    ///
279    /// # Errors
280    ///
281    /// Returns an error if the LLM fails to generate a summary.
282    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        // Build content with URLs section
290        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        // The braces below are template placeholders for `str::replace`, not
300        // format arguments.
301        #[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        // Extract which URLs were actually referenced
314        let referenced_urls = extract_referenced_urls(&summary);
315
316        Ok(CompactionResult {
317            summary,
318            referenced_urls,
319        })
320    }
321}
322
323/// Extract file paths from content.
324fn extract_file_paths(content: &str) -> Vec<String> {
325    let mut paths = Vec::new();
326
327    // Match common path patterns
328    for word in content.split_whitespace() {
329        let word = word.trim_matches(|c: char| c == '"' || c == '\'' || c == '`' || c == ',');
330
331        // Unix-style absolute paths
332        if word.starts_with('/') && word.len() > 1 && !word.contains(' ') {
333            paths.push(word.to_string());
334        }
335
336        // Relative paths with extensions
337        if (word.contains('/') || word.contains('.'))
338            && !word.starts_with("http")
339            && !word.contains(' ')
340            && word.len() > 2
341        {
342            // Check for common file extensions
343            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
358/// Extract a single path from content (for file operation tracking).
359fn extract_single_path(content: &str) -> Option<String> {
360    extract_file_paths(content).into_iter().next()
361}
362
363/// Extract error messages from content.
364fn extract_errors(content: &str) -> Vec<String> {
365    let mut errors = Vec::new();
366
367    // Look for common error patterns
368    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
382/// Extract shell commands from content.
383fn extract_commands(content: &str) -> Vec<String> {
384    let mut commands = Vec::new();
385
386    // Look for command patterns (lines starting with $ or common commands)
387    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        // Common command prefixes
394        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
406/// Check if a tool result is trivial (just an acknowledgment).
407fn 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
420/// Format messages for compression prompt.
421fn 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
429/// Format messages with their associated URLs for compression.
430///
431/// Each message is formatted with its URL header (if it has one).
432fn 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        // Check if this message content has a pending URL
439        let url = pending_urls.iter().find(|p| p.content == content);
440
441        if let Some(url_info) = url {
442            // Format with URL header
443            let _ = writeln!(output, "### [URL: {}]\n{}\n", url_info.url, content);
444        } else {
445            // Format without URL (inline content)
446            let _ = writeln!(output, "### [Inline - {:?}]\n{}\n", msg.role(), content);
447        }
448    }
449
450    output
451}
452
453/// Extract output URLs referenced in a summary.
454///
455/// Scans the summary for URL patterns like "outputs/word-word-word-word.ext"
456/// and returns the set of all found URLs.
457///
458/// # Example
459///
460/// ```rust,ignore
461/// use aither_agent::compression::extract_referenced_urls;
462///
463/// let summary = "The agent read config from outputs/amber-oak-swift-river.txt and saved data.";
464/// let urls = extract_referenced_urls(summary);
465/// assert!(urls.contains("outputs/amber-oak-swift-river.txt"));
466/// ```
467#[must_use]
468pub fn extract_referenced_urls(summary: &str) -> HashSet<String> {
469    let mut urls = HashSet::new();
470
471    // Match pattern: outputs/word-word-word-word.extension
472    // Words are lowercase letters only, separated by hyphens
473    for word in summary.split_whitespace() {
474        // Clean up surrounding punctuation
475        let word = word.trim_matches(|c: char| {
476            c == '"' || c == '\'' || c == '`' || c == ',' || c == '.' || c == ')' || c == ']'
477        });
478
479        if word.starts_with("outputs/") {
480            // Validate the pattern: outputs/word-word-word-word.ext
481            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
491/// Check if a filename matches the word-word-word-word.ext pattern.
492fn is_valid_output_filename(filename: &str) -> bool {
493    // Split by extension
494    let Some((name, ext)) = filename.rsplit_once('.') else {
495        return false;
496    };
497
498    // Extension should be alphanumeric
499    if ext.is_empty() || !ext.chars().all(|c| c.is_ascii_alphanumeric()) {
500        return false;
501    }
502
503    // Name should be word-word-word-word (4 lowercase words separated by hyphens)
504    let parts: Vec<&str> = name.split('-').collect();
505    if parts.len() != 4 {
506        return false;
507    }
508
509    // Each part should be non-empty lowercase letters
510    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        // URLs at end of sentence or in quotes
556        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        // These should NOT be extracted
564        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}