Skip to main content

ertangle_adapter/
ansi.rs

1//! Minimal ANSI/escape sequence stripper.
2//!
3//! PTY passthrough receives raw terminal output from agent TUIs (CSI/OSC control codes, cursor movement, colors, etc.).
4//! To keep transcripts readable, we strip them at the adapter layer.
5//!
6//! This is **stateful across chunks**: an escape sequence may be split across two reads.
7
8#[derive(Clone, Copy, PartialEq, Eq)]
9enum State {
10    Ground,
11    Esc,
12    Csi,
13    Osc,
14    OscEsc,
15}
16
17pub struct AnsiStripper {
18    state: State,
19}
20
21impl Default for AnsiStripper {
22    fn default() -> Self {
23        Self::new()
24    }
25}
26
27impl AnsiStripper {
28    pub fn new() -> Self {
29        AnsiStripper {
30            state: State::Ground,
31        }
32    }
33
34    /// Feed a slice of raw bytes and return readable text (with control codes stripped).
35    pub fn feed(&mut self, input: &[u8]) -> String {
36        let mut out: Vec<u8> = Vec::with_capacity(input.len());
37        for &b in input {
38            match self.state {
39                State::Ground => match b {
40                    0x1b => self.state = State::Esc,
41                    b'\n' | b'\t' => out.push(b),
42                    0x0d => {} // drop CR
43                    0x00..=0x08 | 0x0b | 0x0c | 0x0e..=0x1f | 0x7f => {}
44                    _ => out.push(b),
45                },
46                State::Esc => match b {
47                    b'[' => self.state = State::Csi,
48                    b']' | b'P' | b'^' | b'_' => self.state = State::Osc,
49                    _ => self.state = State::Ground,
50                },
51                State::Csi => {
52                    if (0x40..=0x7e).contains(&b) {
53                        self.state = State::Ground;
54                    }
55                }
56                State::Osc => match b {
57                    0x07 => self.state = State::Ground,
58                    0x1b => self.state = State::OscEsc,
59                    _ => {}
60                },
61                State::OscEsc => {
62                    self.state = if b == b'\\' {
63                        State::Ground
64                    } else {
65                        State::Osc
66                    };
67                }
68            }
69        }
70        String::from_utf8_lossy(&out).into_owned()
71    }
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77
78    #[test]
79    fn strips_colors_and_cursor() {
80        let mut s = AnsiStripper::new();
81        let out = s.feed(b"\x1b[31mred\x1b[0m\x1b[2Jdone");
82        assert_eq!(out, "reddone");
83    }
84
85    #[test]
86    fn strips_osc_title() {
87        let mut s = AnsiStripper::new();
88        let out = s.feed(b"\x1b]0;title\x07hello");
89        assert_eq!(out, "hello");
90    }
91
92    #[test]
93    fn handles_sequence_split_across_chunks() {
94        let mut s = AnsiStripper::new();
95        assert_eq!(s.feed(b"a\x1b[3"), "a");
96        assert_eq!(s.feed(b"1mb"), "b");
97    }
98
99    #[test]
100    fn keeps_utf8_and_newlines() {
101        let mut s = AnsiStripper::new();
102        let out = s.feed("héllo\n世界\r\n".as_bytes());
103        assert_eq!(out, "héllo\n世界\n");
104    }
105}