Skip to main content

lean_ctx/proxy/
compress.rs

1/// Proxy compression: delegates to the unified `compress_if_beneficial` pipeline.
2///
3/// For shell-like tool results, we attempt to extract a command hint from `$ ...` prefixes
4/// so the pattern engine gets the same routing as CLI and MCP paths.
5pub fn compress_tool_result(content: &str, tool_name: Option<&str>) -> String {
6    if content.trim().is_empty() || content.len() < 200 {
7        return content.to_string();
8    }
9
10    let cmd = infer_command(content, tool_name);
11    crate::shell::compress::engine::compress_if_beneficial(&cmd, content)
12}
13
14fn infer_command(content: &str, tool_name: Option<&str>) -> String {
15    if let Some(cmd) = extract_command_hint(content) {
16        return cmd;
17    }
18
19    if let Some(name) = tool_name {
20        let nl = name.to_lowercase();
21        if nl.contains("bash") || nl.contains("shell") || nl.contains("terminal") {
22            return "shell".to_string();
23        }
24        if nl.contains("search") || nl.contains("grep") || nl.contains("find") {
25            return "grep".to_string();
26        }
27    }
28
29    String::new()
30}
31
32fn extract_command_hint(content: &str) -> Option<String> {
33    for line in content.lines().take(3) {
34        let trimmed = line.trim();
35        if let Some(cmd) = trimmed.strip_prefix("$ ") {
36            return Some(cmd.to_string());
37        }
38        if let Some(cmd) = trimmed.strip_prefix("% ") {
39            return Some(cmd.to_string());
40        }
41    }
42    None
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn short_content_unchanged() {
51        let short = "hello world";
52        assert_eq!(compress_tool_result(short, None), short);
53    }
54
55    #[test]
56    fn empty_content_unchanged() {
57        assert_eq!(compress_tool_result("", None), "");
58        assert_eq!(compress_tool_result("   ", None), "   ");
59    }
60
61    #[test]
62    fn command_hint_extraction() {
63        assert_eq!(
64            extract_command_hint("$ cargo build\nCompiling foo"),
65            Some("cargo build".to_string())
66        );
67        assert_eq!(extract_command_hint("no prefix here"), None);
68    }
69
70    #[test]
71    fn tool_name_inference() {
72        assert_eq!(infer_command("some text", Some("bash_execute")), "shell");
73        assert_eq!(infer_command("some text", Some("search_files")), "grep");
74        assert_eq!(infer_command("some text", Some("unknown_tool")), "");
75    }
76}