infinity_agent_cli/sanitize.rs
1//! Sanitizing of externally sourced text before it reaches the terminal.
2
3use std::borrow::Cow;
4
5/// Parser state for [`strip_ansi`], mirroring the escape-sequence states of
6/// a VT parser (<https://vt100.net/emu/dec_ansi_parser>) closely enough to
7/// find the end of each sequence.
8enum State {
9 /// Plain text.
10 Ground,
11 /// Seen ESC, deciding the sequence type from the next byte.
12 Esc,
13 /// Inside `ESC` + intermediate bytes (an nF sequence), waiting for the
14 /// final byte.
15 EscIntermediate,
16 /// Inside a CSI sequence (`ESC [`), waiting for the final byte.
17 Csi,
18 /// Inside an OSC/DCS/SOS/PM/APC string, waiting for BEL or ST (`ESC \`).
19 EscString,
20 /// Seen ESC inside an [`State::EscString`]: either the start of the ST
21 /// terminator or an aborting new escape sequence.
22 EscStringEsc,
23}
24
25/// Strip ANSI escape sequences and non-whitespace control characters from
26/// text that originates outside the TUI (tool results, model output,
27/// subscription events, subprocess output, ...).
28///
29/// The inline viewport tracks the cursor position by parsing everything it
30/// prints (see `OutputTracker` in `inline_viewport`), and deliberately
31/// understands only the small set of sequences the TUI itself emits —
32/// anything else panics as a bug in our code. External text can contain
33/// arbitrary escape sequences (e.g. `cat`ing a file with captured TUI
34/// output), so it must be sanitized before printing.
35///
36/// Removes:
37/// * CSI sequences (`ESC [ … final`), including SGR styling;
38/// * OSC/DCS/SOS/PM/APC string sequences (terminated by BEL or `ESC \`);
39/// * all other escape sequences (`ESC` + intermediates + final byte);
40/// * C0 control characters and DEL, except `\t`, `\n`, and `\r`.
41pub fn strip_ansi(text: &str) -> Cow<'_, str> {
42 let needs_stripping = text
43 .bytes()
44 .any(|b| (b < 0x20 && b != b'\t' && b != b'\n' && b != b'\r') || b == 0x7f);
45 if !needs_stripping {
46 return Cow::Borrowed(text);
47 }
48
49 // Dispatch for a byte following ESC (from ground or aborting a string).
50 let after_esc = |ch: char| match ch {
51 '[' => State::Csi,
52 // OSC / DCS / SOS / PM / APC: consume until BEL or ST.
53 ']' | 'P' | 'X' | '^' | '_' => State::EscString,
54 '\x20'..='\x2f' => State::EscIntermediate,
55 // Any other byte completes a two-byte sequence (e.g. `ESC 7`).
56 _ => State::Ground,
57 };
58
59 let mut out = String::with_capacity(text.len());
60 let mut state = State::Ground;
61 for ch in text.chars() {
62 state = match state {
63 State::Ground => match ch {
64 '\x1b' => State::Esc,
65 '\t' | '\n' | '\r' => {
66 out.push(ch);
67 State::Ground
68 }
69 '\x00'..='\x1f' | '\x7f' => State::Ground,
70 _ => {
71 out.push(ch);
72 State::Ground
73 }
74 },
75 State::Esc => after_esc(ch),
76 State::EscIntermediate => match ch {
77 '\x20'..='\x2f' => State::EscIntermediate,
78 _ => State::Ground, // final byte
79 },
80 State::Csi => match ch {
81 '\x40'..='\x7e' => State::Ground, // final byte
82 _ => State::Csi, // parameter/intermediate bytes
83 },
84 State::EscString => match ch {
85 '\x07' => State::Ground, // BEL terminator
86 '\x1b' => State::EscStringEsc,
87 _ => State::EscString,
88 },
89 State::EscStringEsc => match ch {
90 '\\' => State::Ground, // ST terminator
91 // ESC not starting ST aborts the string and begins a new
92 // escape sequence (matching VT parser behavior).
93 _ => after_esc(ch),
94 },
95 };
96 }
97 Cow::Owned(out)
98}
99
100#[cfg(test)]
101mod tests {
102 use super::*;
103
104 #[test]
105 fn plain_text_is_borrowed() {
106 assert!(matches!(
107 strip_ansi("hello world\nwith\ttabs\r\n"),
108 Cow::Borrowed(_)
109 ));
110 }
111
112 #[test]
113 fn strips_sgr() {
114 assert_eq!(strip_ansi("a \x1b[31mred\x1b[0m word"), "a red word");
115 }
116
117 #[test]
118 fn strips_cursor_movement() {
119 assert_eq!(strip_ansi("\x1b[2J\x1b[10;20Htext\x1b[1A"), "text");
120 }
121
122 #[test]
123 fn strips_osc_with_bel_terminator() {
124 assert_eq!(strip_ansi("\x1b]0;window title\x07after"), "after");
125 }
126
127 #[test]
128 fn strips_osc_with_st_terminator() {
129 assert_eq!(
130 strip_ansi("\x1b]8;;http://x\x1b\\link\x1b]8;;\x1b\\"),
131 "link"
132 );
133 }
134
135 #[test]
136 fn strips_dcs_string() {
137 assert_eq!(strip_ansi("\x1bPq#0;2;0;0;0\x1b\\after"), "after");
138 }
139
140 #[test]
141 fn esc_aborts_unterminated_osc() {
142 // An ESC that doesn't start ST aborts the string and starts a new
143 // sequence; the text after that sequence is kept.
144 assert_eq!(strip_ansi("\x1b]0;title\x1b[31mred"), "red");
145 }
146
147 #[test]
148 fn strips_two_byte_escapes() {
149 assert_eq!(strip_ansi("\x1b7saved\x1b8restored\x1bc"), "savedrestored");
150 }
151
152 #[test]
153 fn strips_nf_sequences() {
154 // Designate character set: ESC + intermediate + final.
155 assert_eq!(strip_ansi("\x1b(Btext"), "text");
156 }
157
158 #[test]
159 fn strips_control_chars_keeps_whitespace() {
160 assert_eq!(strip_ansi("a\x00b\x08c\td\ne\rf\x7fg"), "abc\td\ne\rfg");
161 }
162
163 #[test]
164 fn keeps_unicode() {
165 assert_eq!(strip_ansi("\x1b[1m✓ naïve 日本語\x1b[m"), "✓ naïve 日本語");
166 }
167}