supercode-cli 0.4.7

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
//! UX-30 — an interactive arrow-key list picker for the resume/model
//! overlays, built on the SAME raw-`termios` technique `hidden_input.rs`
//! (UX-18) already established: query the current mode with `tcgetattr`,
//! flip the bits we need, restore via an RAII guard on every exit path.
//! This intentionally adds NO new dependency (no `dialoguer`/`inquire`):
//! `libc` is already a direct dep of this crate for exactly this kind of
//! termios work, and a single-column list with ↑/↓/Enter/Esc is well
//! within what ~150 lines of raw ANSI + `read()` can do cleanly — pulling
//! in a whole prompt-toolkit crate (plus ITS transitive tree, plus a
//! fresh `cargo-deny` license/advisory surface to keep track of) for that
//! is more than this ticket's AC asks for.
//!
//! **TTY-gating is load-bearing, not cosmetic.** [`available`] (and the
//! pure decision it wraps, [`should_launch_picker`]) is the ONLY thing
//! standing between a machine/piped/scripted invocation and a picker that
//! blocks forever reading keystrokes nobody sends. Every call site in
//! `main.rs` checks it before ever constructing a picker; [`pick`] also
//! checks it internally (belt-and-suspenders — see `hidden_input.rs`'s
//! same pattern) and returns `Ok(None)` immediately rather than reading if
//! it's somehow called off a non-tty anyway.
//!
//! **Windows (UX-12): degraded, not ported — documented honestly.** The
//! raw-mode internals below (`RawGuard`/`get_termios`/`read_one`/
//! `interpret_key`/`read_escape_sequence`) are Unix-only (`libc::termios` +
//! byte-at-a-time `read(2)` + hand-parsed `CSI` escape sequences). A real
//! Windows port needs `SetConsoleMode` with `ENABLE_VIRTUAL_TERMINAL_INPUT`
//! (so arrow keys arrive as the same `ESC [ A`/`ESC [ B` sequences this
//! module already parses) PLUS a non-blocking peek built from
//! `WaitForSingleObject` + `ReadFile` on the console handle — and that
//! `WaitForSingleObject` peek does NOT have the same "a ready signal means a
//! byte is retrievable without blocking" guarantee `poll(2)` gives on a Unix
//! tty (a console handle can signal on a single keystroke, then a
//! line-mode `ReadFile` blocks for the rest of the line) — exactly the
//! "subtle raw-mode/poll semantics that can't be cleanly gated" this
//! module's own UX-12 assessment flagged as unsafe to port blind. Per
//! UX-12's explicit guidance, this degrades instead: [`available`] reports
//! `false` unconditionally on Windows, which routes every call site in
//! `main.rs` through its already-existing, already-tested "no interactive
//! picker" fallback (the exact same path a piped/non-tty Unix invocation
//! already takes — `resume` demands an explicit session path, `chat`'s
//! `/model` prints "not a terminal — pass --model to switch"). No call site
//! silently hangs or no-ops; every one gives an explicit, actionable
//! message. `run`/`chat`/`--version` and all non-picker functionality are
//! completely unaffected. A real arrow-key picker on Windows is a
//! legitimate follow-on, not attempted here.

use std::io;
#[cfg(unix)]
use std::io::{IsTerminal, Write};
#[cfg(unix)]
use std::os::unix::io::RawFd;

#[cfg(unix)]
use crate::ui;

/// One selectable row: a primary label plus a dim detail string shown
/// alongside it (e.g. a session's age + title, or a model alias's slug).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PickerItem {
    pub label: String,
    pub detail: String,
}

impl PickerItem {
    pub fn new(label: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            detail: detail.into(),
        }
    }
}

/// The pure yes/no this module's TTY-gating boils down to: launch a picker
/// only when BOTH stdin (to read keys) and stdout (to draw it) are real
/// terminals. Factored out from [`available`] so the decision itself is
/// unit-testable without needing an actual terminal (or the absence of
/// one) in the test process.
#[cfg(unix)]
pub fn should_launch_picker(stdin_is_tty: bool, stdout_is_tty: bool) -> bool {
    stdin_is_tty && stdout_is_tty
}

/// Whether an interactive picker can run right now. Every call site in
/// `main.rs` checks this BEFORE building a candidate list or calling
/// [`pick`], so a non-tty/piped/scripted run never launches one — it falls
/// back to the pre-UX-30 arg-driven behavior instead (UX-30 dev/03).
#[cfg(unix)]
pub fn available() -> bool {
    should_launch_picker(io::stdin().is_terminal(), io::stdout().is_terminal())
}

/// Windows: always `false` — see the module doc's "Windows" section for
/// why this is a deliberate, documented degrade rather than an oversight.
#[cfg(windows)]
pub fn available() -> bool {
    false
}

/// Cap on rendered rows: keeps the picker on-screen without viewport
/// scrolling, which this minimal implementation doesn't attempt. Callers
/// building the candidate list (`main.rs`) already truncate to this same
/// bound, so the count never silently disagrees with what's shown.
pub const MAX_ITEMS: usize = 20;

#[cfg(unix)]
struct RawGuard {
    fd: RawFd,
    orig: libc::termios,
}

#[cfg(unix)]
impl Drop for RawGuard {
    fn drop(&mut self) {
        // SAFETY: `fd` is the stdin descriptor this guard was built for,
        // `orig` is the termios `tcgetattr` produced for that same fd
        // before `pick` mutated it. Best-effort restore, mirroring
        // `hidden_input.rs::TermiosGuard` — there's nothing more useful to
        // do with a restore failure than leave the terminal as-is.
        unsafe {
            libc::tcsetattr(self.fd, libc::TCSANOW, &self.orig);
        }
    }
}

#[cfg(unix)]
fn get_termios(fd: RawFd) -> io::Result<libc::termios> {
    let mut term = std::mem::MaybeUninit::<libc::termios>::uninit();
    // SAFETY: `term` is a validly-sized out-pointer for `tcgetattr`.
    if unsafe { libc::tcgetattr(fd, term.as_mut_ptr()) } != 0 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: `tcgetattr` above returned success, so `term` is initialized.
    Ok(unsafe { term.assume_init() })
}

#[cfg(unix)]
fn set_termios(fd: RawFd, term: &libc::termios) -> io::Result<()> {
    // SAFETY: `fd` is a valid, open descriptor and `term` a validly
    // initialized termios (either a prior successful `tcgetattr`, or a
    // copy of one with only well-defined bitflag fields changed).
    if unsafe { libc::tcsetattr(fd, libc::TCSANOW, term) } != 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

/// Read exactly one byte from `fd` with whatever blocking/timeout
/// semantics its current termios `VMIN`/`VTIME` establish. `Ok(None)`
/// means "read timed out with zero bytes" (only possible when `VMIN` is
/// 0), never a real EOF-vs-timeout ambiguity on a terminal fd.
#[cfg(unix)]
fn read_one(fd: RawFd) -> io::Result<Option<u8>> {
    let mut buf = [0u8; 1];
    // SAFETY: `buf` is a valid 1-byte out-buffer for `read(2)`, `fd` is
    // open for reading (stdin).
    let n = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, 1) };
    if n < 0 {
        return Err(io::Error::last_os_error());
    }
    if n == 0 {
        return Ok(None);
    }
    Ok(Some(buf[0]))
}

/// What the user did with the picker.
#[cfg(unix)]
enum KeyAction {
    Up,
    Down,
    Select,
    Cancel,
    Ignore,
}

/// Interpret one raw input byte already known to have arrived in "raw,
/// blocking one-byte-at-a-time" mode (`VMIN=1, VTIME=0`). `Esc` is handed
/// off to [`read_escape_sequence`] to disambiguate a bare Escape (cancel)
/// from the start of a `CSI` arrow-key sequence (`ESC [ A`/`ESC [ B`).
#[cfg(unix)]
fn interpret_key(fd: RawFd, b: u8) -> io::Result<KeyAction> {
    match b {
        b'\r' | b'\n' => Ok(KeyAction::Select),
        0x03 => Ok(KeyAction::Cancel), // Ctrl-C (ISIG is off — see `pick`)
        b'q' | b'Q' => Ok(KeyAction::Cancel),
        b'k' | b'K' => Ok(KeyAction::Up), // vim-style bonus alongside arrows
        b'j' | b'J' => Ok(KeyAction::Down),
        0x1b => read_escape_sequence(fd),
        _ => Ok(KeyAction::Ignore),
    }
}

/// After a lone `ESC` (0x1b) byte, peek for the rest of a `CSI` sequence
/// with a short non-blocking window (switches the fd to `VMIN=0, VTIME=1`
/// — a 100ms timeout — for just this peek, then restores blocking
/// single-byte mode). No follow-up byte within that window means the user
/// pressed a bare Escape to cancel, not an arrow key.
#[cfg(unix)]
fn read_escape_sequence(fd: RawFd) -> io::Result<KeyAction> {
    let blocking = get_termios(fd)?;
    let mut peek = blocking;
    peek.c_cc[libc::VMIN] = 0;
    peek.c_cc[libc::VTIME] = 1; // deciseconds — 100ms
    set_termios(fd, &peek)?;
    let next = read_one(fd)?;
    set_termios(fd, &blocking)?; // back to blocking single-byte reads

    if next != Some(b'[') {
        return Ok(KeyAction::Cancel);
    }
    match read_one(fd)? {
        Some(b'A') => Ok(KeyAction::Up),   // ESC [ A — cursor up
        Some(b'B') => Ok(KeyAction::Down), // ESC [ B — cursor down
        _ => Ok(KeyAction::Ignore),        // some other CSI sequence — ignore
    }
}

/// Render one row: `"> "` + accent-bold label + dim detail when selected,
/// two-space indent + plain label + dim detail otherwise.
#[cfg(unix)]
fn render_row(item: &PickerItem, selected: bool) -> String {
    if selected {
        format!(
            "{} {}  {}",
            ui::bold(ui::ACCENT, ">"),
            ui::bold(ui::ACCENT, &item.label),
            ui::paint(ui::DIM, &item.detail)
        )
    } else {
        format!("  {}  {}", item.label, ui::paint(ui::DIM, &item.detail))
    }
}

/// Draw the full item list once (used for the initial render).
#[cfg(unix)]
fn draw_initial(out: &mut impl Write, items: &[PickerItem], selected: usize) -> io::Result<()> {
    for (i, item) in items.iter().enumerate() {
        writeln!(out, "\r{}", render_row(item, i == selected))?;
    }
    out.flush()
}

/// Redraw the item list in place: move the cursor back up over every row
/// this picker owns, then rewrite each one (clearing the line first so a
/// shorter new row never leaves stale trailing characters behind).
#[cfg(unix)]
fn redraw(out: &mut impl Write, items: &[PickerItem], selected: usize) -> io::Result<()> {
    write!(out, "\x1b[{}A", items.len())?; // cursor up N lines
    for (i, item) in items.iter().enumerate() {
        writeln!(out, "\r\x1b[2K{}", render_row(item, i == selected))?;
    }
    out.flush()
}

/// Run an interactive arrow-key picker over `items`, prefixed by `header`.
/// Returns `Ok(Some(index))` for a selection (Enter), `Ok(None)` for a
/// cancel (Esc/`q`/Ctrl-C) or if the terminal isn't actually available
/// (see module docs — callers are expected to have already checked
/// [`available`]; this is a defensive second check, not the primary gate).
///
/// `items` must be non-empty; an empty slice returns `Ok(None)` without
/// touching the terminal at all (nothing to pick from).
pub fn pick(header: &str, items: &[PickerItem]) -> io::Result<Option<usize>> {
    if items.is_empty() || !available() {
        return Ok(None);
    }

    #[cfg(unix)]
    {
        let fd = libc::STDIN_FILENO;
        let orig = get_termios(fd)?;
        let mut raw = orig;
        // ICANON off: read byte-at-a-time instead of line-buffered. ECHO off:
        // arrow/enter/escape keystrokes never echo raw bytes to the screen —
        // this picker draws its own representation. ISIG off: Ctrl-C arrives
        // as byte 0x03 (handled as Cancel above) instead of raising SIGINT —
        // deliberately different from `hidden_input.rs`'s choice to leave
        // ISIG on: THIS runs before any turn/agent work exists to interrupt,
        // so a clean in-picker cancel (terminal restored by `RawGuard::drop`)
        // is strictly better here than killing the whole process.
        raw.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
        raw.c_cc[libc::VMIN] = 1;
        raw.c_cc[libc::VTIME] = 0;
        set_termios(fd, &raw)?;
        let _guard = RawGuard { fd, orig };

        let mut out = io::stdout();
        if !header.is_empty() {
            writeln!(out, "{}", ui::bold(ui::ACCENT, header))?;
        }
        writeln!(
            out,
            "{}",
            ui::paint(
                ui::DIM,
                "  ↑/↓ or j/k to move · Enter to select · Esc/q to cancel"
            )
        )?;

        let mut selected = 0usize;
        draw_initial(&mut out, items, selected)?;

        loop {
            // `read_one` under this loop's blocking `VMIN=1, VTIME=0` termios
            // returns `None` ONLY on a genuine EOF (see its doc comment) —
            // never a spurious "no key yet" wakeup for a real interactive
            // user, whose call simply blocks until a byte arrives. A
            // driverless pty whose write end has gone away (e.g. `--yes`
            // under `script`/`ssh -tt`/expect-style automation on a fresh
            // install, with nobody ever typing) hits this on every read —
            // `read()` returns 0 immediately and forever — so looping here
            // with `continue` was an unbounded, CPU-spinning hang. Treat a
            // genuine EOF as Cancel, same as Esc/q/Ctrl-C, so every caller of
            // `pick` (not just onboarding) gets a bounded return instead.
            let Some(b) = read_one(fd)? else {
                return Ok(None);
            };
            match interpret_key(fd, b)? {
                KeyAction::Up => {
                    selected = selected.checked_sub(1).unwrap_or(items.len() - 1);
                    redraw(&mut out, items, selected)?;
                }
                KeyAction::Down => {
                    selected = (selected + 1) % items.len();
                    redraw(&mut out, items, selected)?;
                }
                KeyAction::Select => return Ok(Some(selected)),
                KeyAction::Cancel => return Ok(None),
                KeyAction::Ignore => {}
            }
        }
        // `_guard` drops here (or on any early return above), restoring the
        // original termios on every exit path — including a panic unwind.
    }
    #[cfg(windows)]
    {
        // Unreachable at runtime: `available()` is unconditionally `false`
        // on Windows (see module doc "Windows" section), so the guard
        // clause above already returned. Kept as a safe fallback (not a
        // panic) purely so this function type-checks for Windows targets.
        let _ = header;
        Ok(None)
    }
}

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

    #[test]
    fn gating_requires_both_stdin_and_stdout_tty() {
        assert!(should_launch_picker(true, true));
        assert!(!should_launch_picker(false, true));
        assert!(!should_launch_picker(true, false));
        assert!(!should_launch_picker(false, false));
    }

    /// `pick`'s main loop now maps `read_one`'s `Ok(None)` straight to
    /// Cancel instead of the old `else { continue }` (an unbounded,
    /// CPU-spinning loop on a driverless pty whose write end has gone
    /// away — every read there returns EOF immediately and forever). A
    /// real pty isn't safely constructible in this in-process test binary
    /// (see `available_is_false_under_the_test_harness`'s doc comment —
    /// repointing fd 0 stomps process-global state shared with every
    /// other concurrently-running test); a plain `pipe(2)` is, and it
    /// exercises the exact primitive the loop's fix depends on: closing
    /// the write end makes a read of the read end return a genuine,
    /// immediate `Ok(0)` (EOF, not a hang) — `read_one` must report that
    /// as `Ok(None)`, which the CLI-level, real-pty proof (`--yes` under
    /// a driverless pty, `crates/cli/tests/onboarding_cli.rs`) then
    /// relies on this loop turning into `Cancel` rather than spinning.
    #[test]
    fn read_one_reports_a_closed_pipe_as_eof_not_a_hang() {
        let mut fds = [0i32; 2];
        // SAFETY: `fds` is a valid 2-element out-array for `pipe(2)`.
        let rc = unsafe { libc::pipe(fds.as_mut_ptr()) };
        assert_eq!(rc, 0, "pipe(2) failed: {}", io::Error::last_os_error());
        let (read_fd, write_fd) = (fds[0], fds[1]);
        // SAFETY: `write_fd` was just returned open by `pipe(2)` above and
        // not used anywhere else yet; closing it is what makes the read
        // end observe EOF instead of blocking for a writer that'll never
        // come.
        unsafe { libc::close(write_fd) };
        let result = read_one(read_fd);
        // SAFETY: `read_fd` was returned open by `pipe(2)` above; `pick`'s
        // real callers instead restore termios via `RawGuard` — there's
        // no termios on a plain pipe fd here to worry about.
        unsafe { libc::close(read_fd) };
        assert!(
            matches!(result, Ok(None)),
            "expected Ok(None) (EOF) on a closed pipe's read end, got {result:?}"
        );
    }

    #[test]
    fn picker_item_new_stores_both_fields() {
        let item = PickerItem::new("alias", "vendor/slug");
        assert_eq!(item.label, "alias");
        assert_eq!(item.detail, "vendor/slug");
    }

    #[test]
    fn render_row_marks_the_selected_row_and_only_that_one() {
        let item = PickerItem::new("sess-1", "2m ago");
        let sel = render_row(&item, true);
        let unsel = render_row(&item, false);
        assert_ne!(sel, unsel);
        assert!(unsel.contains("sess-1"));
        assert!(sel.contains("sess-1"));
    }

    /// Under `cargo test`, stdin/stdout are captured pipes, never a real
    /// terminal — so `available()` is deterministically `false` here.
    /// This is itself the non-tty-gating proof for the process-global
    /// `is_terminal()` wrapper: see `crates/cli/tests/picker_available_cli.rs`
    /// for the real-binary-level, CI-enforced proof that a caller actually
    /// SKIPS the picker (and doesn't hang) when this is false, and
    /// `UX-30.md` for the real-PTY manual check that the picker DOES run
    /// (and DOES navigate/select) when it's true — the same split
    /// `hidden_input.rs` documents for the same reason (a safe in-process
    /// test can't repoint fd 0 at a pty without stomping process-global
    /// state shared with every other test running concurrently in this
    /// binary).
    #[test]
    fn available_is_false_under_the_test_harness() {
        assert!(!available());
    }
}