supercode-cli 0.4.20

supercode — a lightweight, fully-customizable AI coding agent CLI in Rust. Any model via OpenRouter; natively continues Claude Code and Codex sessions.
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! Tiny, zero-dependency terminal styling for supercode's CLI.
//!
//! supercode ships as a single small static binary, so instead of pulling in a
//! color/table/spinner stack we hand-roll the handful of ANSI helpers the CLI
//! needs. Everything degrades cleanly: when output isn't a terminal, or
//! `NO_COLOR` is set, the paint functions return the plain string and the box
//! helpers still draw with Unicode rules (no escape codes).
//!
//! The palette is a small, deliberate set of 24-bit truecolor tones chosen to
//! read well on a dark terminal — a violet brand accent, a teal secondary, and
//! semantic green/amber/red, plus two grays for metadata.
//!
//! Not every terminal understands 24-bit SGR (`38;2;r;g;b`). We detect the
//! terminal's color depth (UX-17: `COLORTERM=truecolor`/`24bit` → 24-bit,
//! otherwise a 256-color-safe terminal → the nearest xterm-256 cube color,
//! `NO_COLOR`/dumb/non-tty → no escapes at all) and route every paint helper
//! through it, so output degrades gracefully instead of emitting raw 24-bit
//! codes a 256-color terminal can't render correctly.

use std::io::IsTerminal;
use std::sync::OnceLock;

// ---- palette (24-bit truecolor) -------------------------------------------

/// SGR foreground prefix for an RGB color.
const fn fg(r: u8, g: u8, b: u8) -> Rgb {
    Rgb(r, g, b)
}

#[derive(Clone, Copy)]
pub struct Rgb(u8, u8, u8);

/// Brand violet — the supercode accent.
pub const ACCENT: Rgb = fg(167, 139, 250); // #A78BFA
/// Secondary teal, for a second emphasis tier.
pub const TEAL: Rgb = fg(45, 212, 191); // #2DD4BF
/// Success green.
pub const OK: Rgb = fg(74, 222, 128); // #4ADE80
/// Warning amber.
pub const WARN: Rgb = fg(251, 191, 36); // #FBBF24
/// Error red.
pub const ERR: Rgb = fg(248, 113, 113); // #F87171
/// Sky blue, used for the "user" role and links.
pub const SKY: Rgb = fg(56, 189, 248); // #38BDF8
/// Muted gray for secondary text.
pub const MUTED: Rgb = fg(161, 161, 170); // zinc-400
/// Dim gray for tertiary / chrome.
pub const DIM: Rgb = fg(113, 113, 122); // zinc-500

// ---- color capability detection --------------------------------------------

/// How many colors the target terminal can render.
///
/// Ordered coarse→fine only in the sense that `None` disables all SGR;
/// `Ansi256` and `TrueColor` are two different *encodings* of the same
/// palette, chosen by [`color_level`].
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ColorLevel {
    /// No SGR at all: `NO_COLOR`, `TERM=dumb`, or output isn't a terminal
    /// (and `CLICOLOR_FORCE` didn't override that).
    None,
    /// 256-color-safe: emit `38;5;N` using the nearest xterm-256 cube color.
    /// This is the safe default for any terminal we can't positively
    /// identify as truecolor-capable.
    Ansi256,
    /// 24-bit-safe: emit `38;2;r;g;b` directly. Only used when the terminal
    /// advertises it via `COLORTERM=truecolor`/`24bit`.
    TrueColor,
}

/// Pure decision function (no I/O), so it's unit-testable without needing a
/// real tty or mutating process env vars.
fn detect_color_level(
    no_color: bool,
    clicolor_force: bool,
    term: Option<&str>,
    colorterm: Option<&str>,
    is_tty: bool,
) -> ColorLevel {
    if no_color {
        return ColorLevel::None;
    }
    if term == Some("dumb") {
        return ColorLevel::None;
    }
    if !clicolor_force && !is_tty {
        return ColorLevel::None;
    }
    match colorterm {
        Some("truecolor") | Some("24bit") => ColorLevel::TrueColor,
        // Everything else (unset, "ansi256", or an unrecognized value) gets
        // the 256-color-safe encoding — this is the graceful-degradation
        // default (UX-17): never assume 24-bit support that wasn't declared.
        _ => ColorLevel::Ansi256,
    }
}

fn color_level() -> ColorLevel {
    static LEVEL: OnceLock<ColorLevel> = OnceLock::new();
    *LEVEL.get_or_init(|| {
        detect_color_level(
            std::env::var_os("NO_COLOR").is_some(),
            std::env::var_os("CLICOLOR_FORCE").is_some(),
            std::env::var("TERM").ok().as_deref(),
            std::env::var("COLORTERM").ok().as_deref(),
            // Most styled output goes to stderr; enable when it's a terminal.
            std::io::stderr().is_terminal() || std::io::stdout().is_terminal(),
        )
    })
}

fn color_enabled() -> bool {
    color_level() != ColorLevel::None
}

/// Map a 24-bit RGB triple to the nearest xterm-256 color index (16–255):
/// the 6×6×6 color cube (16–231) or the 24-step grayscale ramp (232–255),
/// whichever is closer in squared Euclidean distance.
fn rgb_to_xterm256(r: u8, g: u8, b: u8) -> u8 {
    const CUBE_STEPS: [u8; 6] = [0, 95, 135, 175, 215, 255];

    fn nearest_cube_level(v: u8) -> (i32, u8) {
        CUBE_STEPS
            .iter()
            .enumerate()
            .map(|(i, &s)| (i as i32, s))
            .min_by_key(|&(_, s)| (s as i32 - v as i32).abs())
            .expect("CUBE_STEPS is non-empty")
    }

    fn dist2(r1: u8, g1: u8, b1: u8, r2: u8, g2: u8, b2: u8) -> i32 {
        let dr = r1 as i32 - r2 as i32;
        let dg = g1 as i32 - g2 as i32;
        let db = b1 as i32 - b2 as i32;
        dr * dr + dg * dg + db * db
    }

    let (rl, rv) = nearest_cube_level(r);
    let (gl, gv) = nearest_cube_level(g);
    let (bl, bv) = nearest_cube_level(b);
    let cube_idx = 16 + 36 * rl + 6 * gl + bl;
    let cube_dist = dist2(r, g, b, rv, gv, bv);

    // 24-step grayscale ramp: index 232..=255, value 8 + 10*step.
    let avg = (r as i32 + g as i32 + b as i32) as f64 / 3.0;
    let gray_step = (((avg - 8.0) / 10.0).round()).clamp(0.0, 23.0) as i32;
    let gray_val = (8 + gray_step * 10) as u8;
    let gray_idx = 232 + gray_step;
    let gray_dist = dist2(r, g, b, gray_val, gray_val, gray_val);

    (if gray_dist < cube_dist {
        gray_idx
    } else {
        cube_idx
    }) as u8
}

/// The SGR foreground fragment for `c` at the detected color level (no
/// leading `\x1b[` / trailing `m` — callers assemble the full sequence so
/// `bold`/`pill` can prefix `1;` or add a paired background).
fn fg_sgr(c: Rgb, level: ColorLevel) -> String {
    match level {
        ColorLevel::TrueColor => format!("38;2;{};{};{}", c.0, c.1, c.2),
        ColorLevel::Ansi256 | ColorLevel::None => {
            format!("38;5;{}", rgb_to_xterm256(c.0, c.1, c.2))
        }
    }
}

fn bg_sgr(c: Rgb, level: ColorLevel) -> String {
    match level {
        ColorLevel::TrueColor => format!("48;2;{};{};{}", c.0, c.1, c.2),
        ColorLevel::Ansi256 | ColorLevel::None => {
            format!("48;5;{}", rgb_to_xterm256(c.0, c.1, c.2))
        }
    }
}

// ---- core paint helpers ----------------------------------------------------

/// Paint `s` with a foreground color (no-op when color is disabled).
pub fn paint(c: Rgb, s: impl AsRef<str>) -> String {
    let s = s.as_ref();
    let level = color_level();
    if level != ColorLevel::None {
        format!("\x1b[{}m{s}\x1b[0m", fg_sgr(c, level))
    } else {
        s.to_string()
    }
}

/// Paint `s` bold + colored.
pub fn bold(c: Rgb, s: impl AsRef<str>) -> String {
    let s = s.as_ref();
    let level = color_level();
    if level != ColorLevel::None {
        format!("\x1b[1;{}m{s}\x1b[0m", fg_sgr(c, level))
    } else {
        s.to_string()
    }
}

/// Plain bold (no color), for headings on minimal palettes.
pub fn bold_plain(s: impl AsRef<str>) -> String {
    let s = s.as_ref();
    if color_enabled() {
        format!("\x1b[1m{s}\x1b[0m")
    } else {
        s.to_string()
    }
}

// ---- semantic glyphs -------------------------------------------------------

/// A high-contrast pill: colored background, near-black text. Use sparingly for
/// the one thing that must pop (a missing key, a failure).
pub fn pill(bg: Rgb, s: impl AsRef<str>) -> String {
    let s = s.as_ref();
    let level = color_level();
    if level != ColorLevel::None {
        const NEAR_BLACK: Rgb = Rgb(24, 24, 27);
        format!(
            "\x1b[1;{};{}m {s} \x1b[0m",
            bg_sgr(bg, level),
            fg_sgr(NEAR_BLACK, level)
        )
    } else {
        format!("[{s}]")
    }
}

/// A green ✓ / red ✗ status mark.
pub fn mark(ok: bool) -> String {
    if ok {
        paint(OK, "")
    } else {
        paint(ERR, "")
    }
}

/// The supercode logo mark.
pub fn logo_mark() -> String {
    bold(ACCENT, "")
}

// ---- panels & rules --------------------------------------------------------

const RULE_WIDTH: usize = 60;

/// A titled top rule: `╭─ title ─────────────╮`, accent title, dim chrome.
pub fn panel_top(title: &str) -> String {
    // A clean "header + underline rule" — an accent bar, a bold title, and a
    // full-width dim rule beneath. (No corner hooks: half-drawn boxes read as
    // rendering glitches; a straight rule reads as an intentional divider.)
    format!(
        "{} {}\n{}",
        paint(ACCENT, ""),
        bold_plain(title),
        paint(DIM, "".repeat(RULE_WIDTH)),
    )
}

/// The closing rule that brackets a panel's content.
pub fn panel_bottom() -> String {
    paint(DIM, "".repeat(RULE_WIDTH))
}

/// A section heading: a small accent bar + bold label.
pub fn section(title: &str) -> String {
    format!("{} {}", paint(ACCENT, ""), bold_plain(title))
}

/// An aligned key/value row used inside panels.
pub fn kv(key: &str, val: impl AsRef<str>) -> String {
    format!("  {}  {}", paint(MUTED, format!("{key:<12}")), val.as_ref())
}

/// A key/value row prefixed by a dim info glyph (neutral, not a status).
pub fn kv_info(key: &str, val: impl AsRef<str>) -> String {
    format!(
        "  {}  {}  {}",
        paint(DIM, ""),
        paint(MUTED, format!("{key:<12}")),
        val.as_ref()
    )
}

/// A key/value row with a blank icon slot, so its label aligns with rows that
/// do have a status/info glyph (keeps the text column's vertical rhythm).
pub fn kv_blank(key: &str, val: impl AsRef<str>) -> String {
    format!(
        "     {}  {}",
        paint(MUTED, format!("{key:<12}")),
        val.as_ref()
    )
}

/// A key/value row prefixed by a status mark.
pub fn kv_status(ok: bool, key: &str, val: impl AsRef<str>) -> String {
    format!(
        "  {}  {}  {}",
        mark(ok),
        paint(MUTED, format!("{key:<12}")),
        val.as_ref()
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    // ---- UX-17 dev/01, dev/02, dev/03: color-level decision -----------

    #[test]
    fn no_color_wins_over_everything_else() {
        // dev/03: NO_COLOR gating holds regardless of tty/COLORTERM/force.
        assert_eq!(
            detect_color_level(true, true, Some("xterm-256color"), Some("truecolor"), true),
            ColorLevel::None
        );
    }

    #[test]
    fn dumb_term_disables_color() {
        assert_eq!(
            detect_color_level(false, false, Some("dumb"), None, true),
            ColorLevel::None
        );
    }

    #[test]
    fn non_tty_disables_color_without_force() {
        // dev/03: piped/non-tty output stays plain.
        assert_eq!(
            detect_color_level(false, false, Some("xterm-256color"), None, false),
            ColorLevel::None
        );
    }

    #[test]
    fn clicolor_force_enables_color_on_non_tty() {
        // dev/03: CLICOLOR_FORCE gating still holds after the change.
        assert_eq!(
            detect_color_level(false, true, Some("xterm-256color"), None, false),
            ColorLevel::Ansi256
        );
    }

    #[test]
    fn unset_colorterm_on_256_term_degrades_to_ansi256() {
        // dev/01: COLORTERM unset + TERM=xterm-256color -> 256-color, not truecolor.
        assert_eq!(
            detect_color_level(false, false, Some("xterm-256color"), None, true),
            ColorLevel::Ansi256
        );
    }

    #[test]
    fn colorterm_truecolor_selects_truecolor() {
        // dev/02: COLORTERM=truecolor -> 24-bit.
        assert_eq!(
            detect_color_level(
                false,
                false,
                Some("xterm-256color"),
                Some("truecolor"),
                true
            ),
            ColorLevel::TrueColor
        );
    }

    #[test]
    fn colorterm_24bit_selects_truecolor() {
        assert_eq!(
            detect_color_level(false, false, Some("xterm-256color"), Some("24bit"), true),
            ColorLevel::TrueColor
        );
    }

    #[test]
    fn unrecognized_colorterm_value_degrades_to_ansi256() {
        // An unknown COLORTERM value must not be trusted as truecolor.
        assert_eq!(
            detect_color_level(false, false, Some("xterm"), Some("bogus"), true),
            ColorLevel::Ansi256
        );
    }

    // ---- rgb_to_xterm256: nearest-cube / grayscale-ramp mapping -------

    #[test]
    fn xterm256_pure_black_and_white() {
        assert_eq!(rgb_to_xterm256(0, 0, 0), 16); // cube origin, not gray-ramp
        assert_eq!(rgb_to_xterm256(255, 255, 255), 231); // cube far corner
    }

    #[test]
    fn xterm256_mid_gray_uses_grayscale_ramp() {
        // A neutral mid-gray should land in the 232-255 grayscale ramp, not
        // the color cube, and should be closer to the ramp's own value.
        let idx = rgb_to_xterm256(128, 128, 128);
        assert!((232..=255).contains(&idx), "expected gray ramp, got {idx}");
    }

    #[test]
    fn xterm256_palette_colors_land_in_valid_range() {
        // Every UX-17 fixture color must downsample into a valid 256-color
        // index (16-255: cube or grayscale ramp — never a reserved 0-15).
        for c in [ACCENT, TEAL, OK, WARN, ERR, SKY, MUTED, DIM] {
            let idx = rgb_to_xterm256(c.0, c.1, c.2);
            assert!(
                idx >= 16,
                "{:?} mapped to reserved index {idx}",
                (c.0, c.1, c.2)
            );
        }
    }

    #[test]
    fn xterm256_is_deterministic() {
        assert_eq!(
            rgb_to_xterm256(167, 139, 250),
            rgb_to_xterm256(167, 139, 250)
        );
    }

    // ---- paint()/bold()/pill() route through the detected level -------
    // (color_level() reads real env+tty via a OnceLock, so these smoke-test
    // the plain-text fallback path, which is deterministic under `cargo test`
    // where stdout/stderr are captured pipes, i.e. non-tty -> ColorLevel::None.)

    #[test]
    fn paint_is_plain_when_color_disabled_by_non_tty() {
        // Under `cargo test`, stdout/stderr are non-tty pipes and NO_COLOR
        // isn't guaranteed set, so this exercises the same "no escapes on a
        // non-terminal" path proven live in STEP 1's piped repro.
        if !color_enabled() {
            assert_eq!(paint(ACCENT, "hi"), "hi");
            assert_eq!(bold(ACCENT, "hi"), "hi");
            assert_eq!(pill(OK, "hi"), "[hi]");
        }
    }
}