aither-agent 0.4.0

AI agent framework with planning, memory, and tool execution for aither
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
//! Smart context compression for managing conversation history.

use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;

use aither_core::{LanguageModel, llm::Message};
use num_traits::ToPrimitive;

const CONTENT_WITH_URLS_PLACEHOLDER: &str = "{content_with_urls}";
const COMMANDS_PLACEHOLDER: &str = "{commands}";
const DIALOGUE_PLACEHOLDER: &str = "{dialogue}";
const ERRORS_PLACEHOLDER: &str = "{errors}";
const FILE_PATHS_PLACEHOLDER: &str = "{file_paths}";
const RUNNING_JOBS_PLACEHOLDER: &str = "{running_jobs}";

/// Strategy for managing conversation context.
#[derive(Debug, Clone)]
pub enum ContextStrategy {
    /// No compression - keep all messages until context is full, then stop.
    Unlimited,

    /// Smart compression with selective preservation (default).
    Smart(SmartCompressionConfig),
}

impl Default for ContextStrategy {
    fn default() -> Self {
        Self::Smart(SmartCompressionConfig::default())
    }
}

/// Configuration for smart context compression.
#[derive(Debug, Clone)]
pub struct SmartCompressionConfig {
    /// Trigger compression at this fraction of context window (default: 0.7).
    pub trigger_threshold: f32,

    /// Emergency compaction threshold (default: 0.9).
    pub emergency_threshold: f32,

    /// Number of recent messages to always keep verbatim.
    pub preserve_recent: usize,

    /// Types of content to preserve during compression.
    pub preserve: PreserveConfig,

    /// Compression level (trade-off between quality and size).
    pub level: CompressionLevel,
}

impl Default for SmartCompressionConfig {
    fn default() -> Self {
        Self {
            trigger_threshold: 0.7,
            emergency_threshold: 0.9,
            preserve_recent: 8,
            preserve: PreserveConfig::default(),
            level: CompressionLevel::Standard,
        }
    }
}

/// Configuration for what content to preserve during compression.
// Each flag is an independent, orthogonal preservation choice; grouping them
// into an enum would not describe the domain any better.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone)]
pub struct PreserveConfig {
    /// Keep file paths verbatim.
    pub file_paths: bool,
    /// Keep error messages verbatim.
    pub errors: bool,
    /// Keep shell commands verbatim.
    pub commands: bool,
}

impl Default for PreserveConfig {
    fn default() -> Self {
        Self {
            file_paths: true,
            errors: true,
            commands: true,
        }
    }
}

/// Compression aggressiveness level.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum CompressionLevel {
    /// Keep more detail, less compression.
    Light,
    /// Balanced compression.
    #[default]
    Standard,
    /// Maximum compression.
    Aggressive,
}

/// Content extracted and preserved during compression.
#[derive(Debug, Default)]
pub struct PreservedContent {
    /// File paths found in messages.
    pub file_paths: Vec<String>,
    /// Error messages found.
    pub errors: Vec<String>,
    /// Shell commands found.
    pub commands: Vec<String>,
    /// Running background jobs (formatted text).
    /// Only running jobs are preserved - completed jobs are ephemeral.
    pub running_jobs: Option<String>,
}

/// Estimate tokens in a string (rough approximation: ~4 chars per token).
#[must_use]
pub const fn estimate_tokens(content: &str) -> usize {
    content.len() / 4
}

/// Estimate context usage as a fraction of the window.
#[must_use]
pub fn estimate_context_usage(messages: &[Message], context_window: usize) -> f32 {
    let message_tokens: usize = messages.iter().map(|m| estimate_tokens(m.content())).sum();
    let message_tokens = message_tokens.to_f32().unwrap_or(f32::MAX);
    let context_window = context_window.to_f32().unwrap_or(f32::MAX);
    message_tokens / context_window
}

// Prompt templates loaded from files
const COMPRESSION_SYSTEM_PROMPT: &str = include_str!("prompts/compression_system.txt");
const COMPRESSION_USER_TEMPLATE: &str = include_str!("prompts/compression_user.txt");
const COMPRESSION_URLS_TEMPLATE: &str = include_str!("prompts/compression_urls.txt");

/// Result of a compaction operation with URL tracking.
#[derive(Debug, Clone)]
pub struct CompactionResult {
    /// The generated summary text.
    pub summary: String,
    /// URLs that were referenced in the summary (should be written to disk).
    pub referenced_urls: HashSet<String>,
}

/// A pending URL allocation for content that hasn't been written to disk.
#[derive(Debug, Clone)]
pub struct ContentWithUrl {
    /// The content in text form.
    pub content: String,
    /// The allocated URL for this content.
    pub url: String,
}

impl SmartCompressionConfig {
    /// Reserve 20% of context for the compaction process itself.
    pub const COMPACTION_RESERVE: f32 = 0.2;

    /// Returns the effective trigger threshold accounting for compaction reserve.
    ///
    /// The actual trigger is lower than `trigger_threshold` to leave room
    /// for the fast LLM to see both URLs and original content during compaction.
    #[must_use]
    pub fn effective_trigger(&self) -> f32 {
        self.trigger_threshold - Self::COMPACTION_RESERVE
    }

    /// Extract content that should be preserved from messages.
    #[must_use]
    pub fn extract_preserved(&self, messages: &[Message]) -> PreservedContent {
        let mut preserved = PreservedContent::default();

        for msg in messages {
            let content = msg.content();

            if self.preserve.file_paths {
                preserved.file_paths.extend(extract_file_paths(content));
            }

            if self.preserve.errors {
                preserved.errors.extend(extract_errors(content));
            }

            if self.preserve.commands {
                preserved.commands.extend(extract_commands(content));
            }
        }

        preserved
    }

    /// Identify indices of stale tool calls that can be safely removed.
    ///
    /// Stale tool calls include:
    /// - Tool results that were just acknowledgments
    /// - Read operations for files that were later modified
    #[must_use]
    pub fn find_stale_tool_calls(&self, messages: &[Message]) -> HashSet<usize> {
        let mut stale = HashSet::new();
        let mut file_versions: HashMap<String, usize> = HashMap::new();

        for (idx, msg) in messages.iter().enumerate() {
            let content = msg.content();

            // Check for trivial results
            if is_trivial_result(content) {
                stale.insert(idx);
            }

            // Track file reads that may be superseded
            if (content.contains("read_file") || content.contains("Read"))
                && let Some(path) = extract_single_path(content)
                && let Some(&later_idx) = file_versions.get(&path)
                && later_idx > idx
            {
                stale.insert(idx);
            }

            // Track file modifications
            if (content.contains("write_file")
                || content.contains("edit_file")
                || content.contains("Write")
                || content.contains("Edit"))
                && let Some(path) = extract_single_path(content)
            {
                file_versions.insert(path, idx);
            }
        }

        stale
    }

    /// Generate a compressed summary of messages.
    ///
    /// # Errors
    ///
    /// Returns an error if the LLM fails to generate a summary.
    pub async fn generate_summary<LLM: LanguageModel>(
        &self,
        llm: &LLM,
        messages: &[Message],
        preserved: &PreservedContent,
    ) -> Result<String, LLM::Error> {
        let running_jobs = preserved
            .running_jobs
            .as_ref()
            .map_or(String::new(), |jobs| {
                format!("- Running background jobs:\n{jobs}")
            });

        // The braces below are template placeholders for `str::replace`, not
        // format arguments.
        #[allow(clippy::literal_string_with_formatting_args)]
        let prompt = COMPRESSION_USER_TEMPLATE
            .replace(FILE_PATHS_PLACEHOLDER, &preserved.file_paths.join(", "))
            .replace(ERRORS_PLACEHOLDER, &preserved.errors.join("\n"))
            .replace(COMMANDS_PLACEHOLDER, &preserved.commands.join("\n"))
            .replace(RUNNING_JOBS_PLACEHOLDER, &running_jobs)
            .replace(DIALOGUE_PLACEHOLDER, &format_messages(messages));

        let request = aither_core::llm::oneshot(COMPRESSION_SYSTEM_PROMPT, prompt);
        let stream = llm.respond(request);
        aither_core::llm::collect_text(stream).await
    }

    /// Generate a compressed summary with URL tracking for tool outputs.
    ///
    /// This method:
    /// 1. Takes messages and their associated pending URLs
    /// 2. Generates a summary that may reference those URLs
    /// 3. Scans the summary to find which URLs were actually referenced
    /// 4. Returns both the summary and the set of referenced URLs
    ///
    /// The caller should only write files for URLs that appear in `referenced_urls`.
    ///
    /// # Arguments
    ///
    /// * `llm` - The fast LLM to use for summary generation
    /// * `messages` - Messages to compress
    /// * `preserved` - Content to preserve verbatim
    /// * `pending_urls` - Map of message content to allocated URLs
    ///
    /// # Errors
    ///
    /// Returns an error if the LLM fails to generate a summary.
    pub async fn generate_summary_with_urls<LLM: LanguageModel>(
        &self,
        llm: &LLM,
        messages: &[Message],
        preserved: &PreservedContent,
        pending_urls: &[ContentWithUrl],
    ) -> Result<CompactionResult, LLM::Error> {
        // Build content with URLs section
        let content_with_urls = format_content_with_urls(messages, pending_urls);

        let running_jobs = preserved
            .running_jobs
            .as_ref()
            .map_or(String::new(), |jobs| {
                format!("- Running background jobs:\n{jobs}")
            });

        // The braces below are template placeholders for `str::replace`, not
        // format arguments.
        #[allow(clippy::literal_string_with_formatting_args)]
        let prompt = COMPRESSION_URLS_TEMPLATE
            .replace(CONTENT_WITH_URLS_PLACEHOLDER, &content_with_urls)
            .replace(FILE_PATHS_PLACEHOLDER, &preserved.file_paths.join(", "))
            .replace(ERRORS_PLACEHOLDER, &preserved.errors.join("\n"))
            .replace(COMMANDS_PLACEHOLDER, &preserved.commands.join("\n"))
            .replace(RUNNING_JOBS_PLACEHOLDER, &running_jobs);

        let request = aither_core::llm::oneshot(COMPRESSION_SYSTEM_PROMPT, prompt);
        let stream = llm.respond(request);
        let summary = aither_core::llm::collect_text(stream).await?;

        // Extract which URLs were actually referenced
        let referenced_urls = extract_referenced_urls(&summary);

        Ok(CompactionResult {
            summary,
            referenced_urls,
        })
    }
}

/// Extract file paths from content.
fn extract_file_paths(content: &str) -> Vec<String> {
    let mut paths = Vec::new();

    // Match common path patterns
    for word in content.split_whitespace() {
        let word = word.trim_matches(|c: char| c == '"' || c == '\'' || c == '`' || c == ',');

        // Unix-style absolute paths
        if word.starts_with('/') && word.len() > 1 && !word.contains(' ') {
            paths.push(word.to_string());
        }

        // Relative paths with extensions
        if (word.contains('/') || word.contains('.'))
            && !word.starts_with("http")
            && !word.contains(' ')
            && word.len() > 2
        {
            // Check for common file extensions
            let extensions = [
                ".rs", ".py", ".js", ".ts", ".go", ".java", ".c", ".cpp", ".h", ".md", ".txt",
                ".json", ".yaml", ".yml", ".toml", ".xml", ".html", ".css",
            ];
            if extensions.iter().any(|ext| word.ends_with(ext)) {
                paths.push(word.to_string());
            }
        }
    }

    paths.sort();
    paths.dedup();
    paths
}

/// Extract a single path from content (for file operation tracking).
fn extract_single_path(content: &str) -> Option<String> {
    extract_file_paths(content).into_iter().next()
}

/// Extract error messages from content.
fn extract_errors(content: &str) -> Vec<String> {
    let mut errors = Vec::new();

    // Look for common error patterns
    for line in content.lines() {
        let lower = line.to_lowercase();
        if lower.contains("error")
            || lower.contains("failed")
            || lower.contains("panic")
            || lower.contains("exception")
        {
            errors.push(line.trim().to_string());
        }
    }

    errors
}

/// Extract shell commands from content.
fn extract_commands(content: &str) -> Vec<String> {
    let mut commands = Vec::new();

    // Look for command patterns (lines starting with $ or common commands)
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with('$') || trimmed.starts_with('>') {
            commands.push(trimmed.to_string());
        }

        // Common command prefixes
        let cmd_prefixes = [
            "cargo ", "bun ", "bunx ", "npm ", "git ", "docker ", "make ", "rustc ", "python ",
            "node ", "go ", "cd ", "ls ", "cat ", "mkdir ", "rm ", "mv ", "cp ",
        ];
        if cmd_prefixes.iter().any(|p| trimmed.starts_with(p)) {
            commands.push(trimmed.to_string());
        }
    }

    commands
}

/// Check if a tool result is trivial (just an acknowledgment).
fn is_trivial_result(result: &str) -> bool {
    let trivial_patterns = [
        "ok",
        "success",
        "done",
        "file written",
        "file saved",
        "completed",
    ];
    let lower = result.to_lowercase();
    trivial_patterns.iter().any(|t| lower.contains(t)) && result.len() < 50
}

/// Format messages for compression prompt.
fn format_messages(messages: &[Message]) -> String {
    messages
        .iter()
        .map(|msg| format!("{:?}: {}", msg.role(), msg.content()))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Format messages with their associated URLs for compression.
///
/// Each message is formatted with its URL header (if it has one).
fn format_content_with_urls(messages: &[Message], pending_urls: &[ContentWithUrl]) -> String {
    let mut output = String::new();

    for msg in messages {
        let content = msg.content();

        // Check if this message content has a pending URL
        let url = pending_urls.iter().find(|p| p.content == content);

        if let Some(url_info) = url {
            // Format with URL header
            let _ = writeln!(output, "### [URL: {}]\n{}\n", url_info.url, content);
        } else {
            // Format without URL (inline content)
            let _ = writeln!(output, "### [Inline - {:?}]\n{}\n", msg.role(), content);
        }
    }

    output
}

/// Extract output URLs referenced in a summary.
///
/// Scans the summary for URL patterns like "outputs/word-word-word-word.ext"
/// and returns the set of all found URLs.
///
/// # Example
///
/// ```rust,ignore
/// use aither_agent::compression::extract_referenced_urls;
///
/// let summary = "The agent read config from outputs/amber-oak-swift-river.txt and saved data.";
/// let urls = extract_referenced_urls(summary);
/// assert!(urls.contains("outputs/amber-oak-swift-river.txt"));
/// ```
#[must_use]
pub fn extract_referenced_urls(summary: &str) -> HashSet<String> {
    let mut urls = HashSet::new();

    // Match pattern: outputs/word-word-word-word.extension
    // Words are lowercase letters only, separated by hyphens
    for word in summary.split_whitespace() {
        // Clean up surrounding punctuation
        let word = word.trim_matches(|c: char| {
            c == '"' || c == '\'' || c == '`' || c == ',' || c == '.' || c == ')' || c == ']'
        });

        if word.starts_with("outputs/") {
            // Validate the pattern: outputs/word-word-word-word.ext
            let filename = word.strip_prefix("outputs/").unwrap_or("");
            if is_valid_output_filename(filename) {
                urls.insert(word.to_string());
            }
        }
    }

    urls
}

/// Check if a filename matches the word-word-word-word.ext pattern.
fn is_valid_output_filename(filename: &str) -> bool {
    // Split by extension
    let Some((name, ext)) = filename.rsplit_once('.') else {
        return false;
    };

    // Extension should be alphanumeric
    if ext.is_empty() || !ext.chars().all(|c| c.is_ascii_alphanumeric()) {
        return false;
    }

    // Name should be word-word-word-word (4 lowercase words separated by hyphens)
    let parts: Vec<&str> = name.split('-').collect();
    if parts.len() != 4 {
        return false;
    }

    // Each part should be non-empty lowercase letters
    parts
        .iter()
        .all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_lowercase()))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_file_paths() {
        let content = "I modified /Users/user/project/src/main.rs and also checked lib.rs";
        let paths = extract_file_paths(content);
        assert!(paths.contains(&"/Users/user/project/src/main.rs".to_string()));
        assert!(paths.contains(&"lib.rs".to_string()));
    }

    #[test]
    fn test_trivial_result() {
        assert!(is_trivial_result("OK"));
        assert!(is_trivial_result("File written successfully"));
        assert!(!is_trivial_result(
            "This is a long result with actual content that should be preserved"
        ));
    }

    #[test]
    fn test_estimate_tokens() {
        let content = "This is a test string with some content";
        let tokens = estimate_tokens(content);
        assert!(tokens > 0);
        assert!(tokens < content.len());
    }

    #[test]
    fn test_extract_referenced_urls() {
        let summary = "The agent read config from outputs/amber-oak-swift-river.txt and saved data to outputs/bold-creek-calm-dawn.json.";
        let urls = extract_referenced_urls(summary);
        assert_eq!(urls.len(), 2);
        assert!(urls.contains("outputs/amber-oak-swift-river.txt"));
        assert!(urls.contains("outputs/bold-creek-calm-dawn.json"));
    }

    #[test]
    fn test_extract_urls_with_punctuation() {
        // URLs at end of sentence or in quotes
        let summary = r#"See "outputs/jade-mist-clear-pool.txt" for details."#;
        let urls = extract_referenced_urls(summary);
        assert!(urls.contains("outputs/jade-mist-clear-pool.txt"));
    }

    #[test]
    fn test_invalid_url_patterns() {
        // These should NOT be extracted
        let summary = "Not valid: outputs/single.txt outputs/two-words.txt outputs/ outputs/one-two-three.txt";
        let urls = extract_referenced_urls(summary);
        assert!(urls.is_empty());
    }

    #[test]
    fn test_valid_output_filename() {
        assert!(is_valid_output_filename("amber-oak-swift-river.txt"));
        assert!(is_valid_output_filename("bold-creek-calm-dawn.json"));
        assert!(!is_valid_output_filename("single.txt"));
        assert!(!is_valid_output_filename("two-words.txt"));
        assert!(!is_valid_output_filename("no-extension"));
        assert!(!is_valid_output_filename("Upper-Case-Words.txt"));
    }
}