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
//! Tool output noise filter — cleans tool output before it reaches the LLM.
//!
//! Applied *after* tool execution and truncation, *before* the observation is
//! formatted into the ReAct loop. Reduces token waste from ANSI escape codes,
//! progress bars, duplicate lines, and excessive whitespace.
/// A single filter that transforms tool output text.
pub trait ToolOutputFilter: Send + Sync {
fn name(&self) -> &str;
fn filter(&self, tool_name: &str, output: &str) -> String;
}
/// Ordered chain of filters applied sequentially.
pub struct ToolOutputFilterChain {
filters: Vec<Box<dyn ToolOutputFilter>>,
}
impl ToolOutputFilterChain {
/// Construct the default filter chain used in the ReAct loop.
pub fn default_chain() -> Self {
Self {
filters: vec![
Box::new(AnsiStripper),
Box::new(ProgressLineFilter),
Box::new(DuplicateLineDeduper),
Box::new(WhitespaceNormalizer),
],
}
}
/// Apply all filters in order, returning the cleaned output.
pub fn apply(&self, tool_name: &str, output: &str) -> String {
let mut buf = output.to_string();
for f in &self.filters {
buf = f.filter(tool_name, &buf);
}
buf
}
}
// ── Filter implementations ──────────────────────────────────────────────────
/// Strip ANSI escape sequences (SGR, cursor, erase, etc.).
pub struct AnsiStripper;
impl ToolOutputFilter for AnsiStripper {
fn name(&self) -> &str {
"ansi_stripper"
}
fn filter(&self, _tool_name: &str, output: &str) -> String {
// Match ESC [ ... final_byte and ESC ] ... ST (OSC sequences)
let mut result = String::with_capacity(output.len());
let mut chars = output.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '\x1b' {
// CSI sequence: ESC [
if chars.peek() == Some(&'[') {
chars.next(); // consume '['
// consume until final byte (0x40-0x7E)
while let Some(&c) = chars.peek() {
chars.next();
if c.is_ascii() && (0x40..=0x7E).contains(&(c as u8)) {
break;
}
}
continue;
}
// OSC sequence: ESC ]
if chars.peek() == Some(&']') {
chars.next();
// consume until ST (ESC \) or BEL (\x07)
while let Some(c) = chars.next() {
if c == '\x07' {
break;
}
if c == '\x1b' && chars.peek() == Some(&'\\') {
chars.next();
break;
}
}
continue;
}
// Single-char escape (ESC + one byte)
chars.next();
continue;
}
// Strip carriage return (common in progress output)
if ch == '\r' {
continue;
}
result.push(ch);
}
result
}
}
/// Remove lines that look like progress bars or spinners.
pub struct ProgressLineFilter;
impl ToolOutputFilter for ProgressLineFilter {
fn name(&self) -> &str {
"progress_line_filter"
}
fn filter(&self, _tool_name: &str, output: &str) -> String {
output
.lines()
.filter(|line| {
let trimmed = line.trim();
// Skip lines that are mostly progress bar characters
if trimmed.is_empty() {
return true;
}
let progress_chars = trimmed
.chars()
.filter(|c| {
matches!(
c,
'█' | '▓'
| '▒'
| '░'
| '━'
| '─'
| '┃'
| '│'
| '⠋'
| '⠙'
| '⠹'
| '⠸'
| '⠼'
| '⠴'
| '⠦'
| '⠧'
| '⠇'
| '⠏'
| '/'
| '\\'
| '-'
| '='
| '>'
| '#'
| '.'
| '●'
| '○'
)
})
.count();
let total = trimmed.chars().count();
// If >60% of the line is progress characters and it contains '%', skip it
if total > 5 && progress_chars * 100 / total > 60 {
return false;
}
// Skip lines that are just a percentage update
if trimmed
.chars()
.all(|c| c.is_ascii_digit() || c == '%' || c == '.' || c == ' ')
&& trimmed.contains('%')
{
return false;
}
true
})
.collect::<Vec<_>>()
.join("\n")
}
}
/// Remove consecutive duplicate lines (common in build/test output).
pub struct DuplicateLineDeduper;
impl ToolOutputFilter for DuplicateLineDeduper {
fn name(&self) -> &str {
"duplicate_line_deduper"
}
fn filter(&self, _tool_name: &str, output: &str) -> String {
let mut result = Vec::new();
let mut prev: Option<&str> = None;
let mut dup_count = 0u32;
for line in output.lines() {
if Some(line) == prev {
dup_count += 1;
continue;
}
if dup_count > 0 {
result.push(format!(" [... repeated {dup_count} more time(s)]"));
dup_count = 0;
}
result.push(line.to_string());
prev = Some(line);
}
if dup_count > 0 {
result.push(format!(" [... repeated {dup_count} more time(s)]"));
}
result.join("\n")
}
}
/// Collapse runs of blank lines to max 2, trim trailing whitespace per line.
pub struct WhitespaceNormalizer;
impl ToolOutputFilter for WhitespaceNormalizer {
fn name(&self) -> &str {
"whitespace_normalizer"
}
fn filter(&self, _tool_name: &str, output: &str) -> String {
let mut result = Vec::new();
let mut blank_run = 0u32;
for line in output.lines() {
let trimmed = line.trim_end();
if trimmed.is_empty() {
blank_run += 1;
if blank_run <= 2 {
result.push(String::new());
}
} else {
blank_run = 0;
result.push(trimmed.to_string());
}
}
// Trim trailing blank lines
while result.last().is_some_and(|l| l.is_empty()) {
result.pop();
}
result.join("\n")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ansi_stripper_removes_sgr() {
let input = "\x1b[31mERROR\x1b[0m: something failed";
let chain = ToolOutputFilterChain::default_chain();
let out = chain.apply("test", input);
assert_eq!(out, "ERROR: something failed");
}
#[test]
fn progress_filter_removes_bars() {
let input = "Compiling foo\n███████████████░░░░░ 75%\nDone.";
let filter = ProgressLineFilter;
let out = filter.filter("test", input);
assert!(out.contains("Compiling foo"));
assert!(out.contains("Done."));
assert!(!out.contains("███"));
}
#[test]
fn deduper_collapses_repeats() {
let input = "line1\nline2\nline2\nline2\nline3";
let filter = DuplicateLineDeduper;
let out = filter.filter("test", input);
assert!(out.contains("line2"));
assert!(out.contains("[... repeated 2 more time(s)]"));
assert!(out.contains("line3"));
}
#[test]
fn whitespace_normalizer_collapses_blanks() {
let input = "a\n\n\n\n\nb\n\nc";
let filter = WhitespaceNormalizer;
let out = filter.filter("test", input);
// Max 2 blank lines between a and b
assert_eq!(out, "a\n\n\nb\n\nc");
}
#[test]
fn full_chain_applies_all() {
let input = "\x1b[32mok\x1b[0m\nfoo\nfoo\nfoo\n\n\n\n\nbar";
let chain = ToolOutputFilterChain::default_chain();
let out = chain.apply("test", input);
assert!(out.starts_with("ok"));
assert!(out.contains("[... repeated 2 more time(s)]"));
assert!(out.contains("bar"));
}
}