Open History to see the last commit
1/**
2 * Strip terminal escape sequences from captured CLI stdout.
3 *
4 * OpenCode's CLI (and potentially other provider CLIs) can emit OSC title
5 * sequences (`ESC ]0;<title> BEL` / `ESC \`) and ANSI CSI color codes directly
6 * to stdout, even when stdout is a pipe. When T3 Code captures that output
7 * via `ChildProcessSpawner`, those bytes pollute structured parsing — e.g.
8 * `opencode agent list` becomes `\x1b]0;t3code: ready\x07build (primary)`
9 * instead of `build (primary)`, causing the agent inventory to store a
10 * polluted id that later fails with `Agent not found`.
11 *
12 * This is defensive for any provider CLI; the regexes are intentionally
13 * permissive and also handle Ghostty/Zsh title integrations that can leak
14 * through `shell: true` spawns.
15 */
16const OSC_RE = /\x1b\].*?(?:\x07|\x1b\\)/g;
17const CSI_RE = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
18const CHARSET_RE = /\x1b[()][A-Za-z0-9]/g;
19const SINGLE_ESC_RE = /\x1b[@-Z\\-_]/g;
20
21export function stripTerminalEscapes(input: string): string {
22 if (!input || input.indexOf("\x1b") === -1) {
23 return input;
24 }
25 return input
26 .replace(OSC_RE, "")
27 .replace(CSI_RE, "")
28 .replace(CHARSET_RE, "")
29 .replace(SINGLE_ESC_RE, "");
30}
31
32/**
33 * Strip escapes and also trim the result. Useful for single-value fields
34 * like agent/variant names that should never contain control bytes.
35 */
36export function sanitizeTerminalValue(input: string): string {
37 return stripTerminalEscapes(input).trim();
38}