bitrouter 1.0.0-alpha.27

BitRouter: an LLM API router. CLI + TUI + assembly library.
Documentation
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
//! PTY terminal backend for native harness panes (TUI_SPEC §8a/§9/§11).
//!
//! [`TerminalBackend`] abstracts the VT emulation core: byte feeding, the
//! cell grid (as ratatui lines), input encoding, and the emulator's write-back
//! responses (DA/DSR answers). The default implementation rides
//! `alacritty_terminal` — TUI_SPEC §11 picked wezterm-term for its input
//! encoder, but wezterm-term is not published to crates.io (a git dependency
//! would make this binary unpublishable). The encoders themselves, however,
//! ARE published, and [`encode_key`] delegates to them: legacy/DECCKM via
//! `termwiz::input::KeyCode::encode`, and — when the inner app pushed kitty
//! keyboard flags (tracked by the emulator, `kitty_keyboard: true`) —
//! `wezterm_input_types::KeyEvent::encode_kitty`, the same encoder wezterm's
//! GUI feeds its own panes. The trait remains §11's escape hatch: a full
//! wezterm-term/libghostty grid can slot in later without touching the TUI.
//!
//! Fidelity mechanics (§9) implemented at this layer:
//! - **Input encoding** follows what the inner app negotiated (kitty flags,
//!   application cursor keys, newline mode); `Ctrl-C` encodes to an
//!   interrupt (`0x03` legacy, `CSI 99;5u` kitty) — it interrupts the inner
//!   agent, it does not quit the manager.
//! - **OSC passthrough**: [`Osc52Scanner`] peels OSC-52 clipboard writes out
//!   of the PTY stream so the host loop can re-emit them verbatim to the
//!   outer terminal (the tmux `allow-passthrough` pattern), capped so a
//!   malicious child can't balloon memory.
//! - **Resize recovery**: [`PtyPane::resize`] resizes the emulator and the
//!   PTY (delivering `SIGWINCH`) whenever the pane rect changes.

use alacritty_terminal::event::{Event, EventListener};
use alacritty_terminal::grid::{Dimensions, Scroll};
use alacritty_terminal::index::Line as TermLine;
use alacritty_terminal::term::{Config, Term, TermMode};
use alacritty_terminal::vte::ansi::{Color as VtColor, NamedColor, Processor, Rgb};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEventKind};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line as TuiLine, Span};
use termwiz::escape::csi::KittyKeyboardFlags;
use termwiz::input::{KeyCodeEncodeModes, KeyboardEncoding};

/// The VT emulation core under a PTY pane. Object-safe so the pane host can
/// swap cores (§11's validation-gated backend decision).
pub trait TerminalBackend: Send {
    /// Feed PTY output bytes into the emulator.
    fn feed(&mut self, bytes: &[u8]);
    /// Resize the emulator grid.
    fn resize(&mut self, cols: u16, rows: u16);
    /// Snapshot the visible grid as styled lines (one per row).
    fn lines(&self, no_color: bool) -> Vec<TuiLine<'static>>;
    /// Encode one key press into the byte sequence the inner app expects,
    /// honoring the emulator's current keyboard modes.
    fn encode_key(&self, key: &KeyEvent) -> Option<Vec<u8>>;
    /// Encode pasted text for the inner app: wrapped in `ESC[200~ … ESC[201~`
    /// when it enabled bracketed paste (DEC 2004), raw bytes otherwise.
    fn encode_paste(&self, text: &str) -> Vec<u8>;
    /// Drain bytes the emulator wants written back to the PTY (device
    /// attribute / status responses) — capability scoping happens here: the
    /// emulator answers with what it actually renders.
    fn drain_responses(&mut self) -> Vec<u8>;
    /// Page the scrollback view: `up` moves toward older output, `page` moves
    /// by a full screen (else `WHEEL_STEP` lines, for the wheel). The host —
    /// not the inner app — owns pane scrollback (TUI_SPEC §9): agent harnesses
    /// like `claude` rely on the terminal to hold history, so the manager must.
    fn scroll(&mut self, up: bool, page: bool);
    /// Jump the view back to the live bottom (display offset 0) — what typing
    /// implies (you cannot type into history).
    fn scroll_to_bottom(&mut self);
    /// Whether the view is pinned above the live bottom (drives the indicator).
    fn is_scrolled(&self) -> bool;
    /// Whether the inner app is on the alternate screen (a full-screen TUI):
    /// there is no scrollback to page, so the host forwards the scroll gesture
    /// as keys instead of paging its own (empty) history.
    fn alt_screen(&self) -> bool;
    /// Whether the inner app has enabled mouse reporting (any of the DECSET
    /// click/drag/motion modes). When it has, the host forwards real pointer
    /// events (`encode_mouse`) instead of synthesizing scroll keys.
    fn mouse_enabled(&self) -> bool;
    /// Encode a pointer event for the inner app in the protocol it negotiated
    /// (SGR 1006 when set, else legacy X10), at **pane-relative 1-based**
    /// `(col, row)`. `None` when the app isn't tracking this event (e.g. bare
    /// motion without any-motion mode) — the caller then does nothing.
    fn encode_mouse(
        &self,
        kind: MouseEventKind,
        col: u16,
        row: u16,
        mods: KeyModifiers,
    ) -> Option<Vec<u8>>;
}

/// Wheel notch → lines scrolled (a page is the pane height instead).
const WHEEL_STEP: i32 = 3;

/// `alacritty_terminal`-backed [`TerminalBackend`].
pub struct AlacrittyBackend {
    term: Term<Proxy>,
    parser: Processor,
    proxy: Proxy,
}

/// Event listener collecting the emulator's PTY write-backs.
#[derive(Clone)]
struct Proxy {
    responses: std::sync::Arc<std::sync::Mutex<Vec<u8>>>,
}

impl EventListener for Proxy {
    fn send_event(&self, event: Event) {
        if let Event::PtyWrite(text) = event
            && let Ok(mut buf) = self.responses.lock()
        {
            buf.extend_from_slice(text.as_bytes());
        }
    }
}

/// Grid dimensions for the emulator (alacritty's `Dimensions` is in
/// lines/columns with no window pixels — fine for a cell renderer).
struct Size {
    cols: usize,
    rows: usize,
}

impl Dimensions for Size {
    fn total_lines(&self) -> usize {
        self.rows
    }
    fn screen_lines(&self) -> usize {
        self.rows
    }
    fn columns(&self) -> usize {
        self.cols
    }
}

impl AlacrittyBackend {
    pub fn new(cols: u16, rows: u16) -> Self {
        let proxy = Proxy {
            responses: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
        };
        let size = Size {
            cols: cols.max(2) as usize,
            rows: rows.max(1) as usize,
        };
        let config = Config {
            // Let the inner app negotiate the kitty keyboard protocol — the
            // tracked flags drive the wezterm kitty encoder in `encode_key`.
            kitty_keyboard: true,
            ..Config::default()
        };
        Self {
            term: Term::new(config, &size, proxy.clone()),
            parser: Processor::new(),
            proxy,
        }
    }
}

impl TerminalBackend for AlacrittyBackend {
    fn feed(&mut self, bytes: &[u8]) {
        self.parser.advance(&mut self.term, bytes);
    }

    fn resize(&mut self, cols: u16, rows: u16) {
        self.term.resize(Size {
            cols: cols.max(2) as usize,
            rows: rows.max(1) as usize,
        });
    }

    fn lines(&self, no_color: bool) -> Vec<TuiLine<'static>> {
        let cols = self.term.columns();
        let rows = self.term.screen_lines();
        let cursor = self.term.grid().cursor.point;
        let cursor_visible = self.term.mode().contains(TermMode::SHOW_CURSOR);
        // When scrolled into history the display iter yields negative absolute
        // lines (it starts at `Line(-display_offset - 1)`); rebase by the
        // offset so the visible window always maps onto rows `0..screen_lines`.
        // At offset 0 this is a no-op (rebase adds 0) — the live-tail path.
        let offset = self.term.grid().display_offset() as i32;
        // Cell matrix defaulted to spaces; the display iter fills what exists.
        let mut cells: Vec<Vec<Span<'static>>> = (0..rows)
            .map(|_| vec![Span::raw(" ".to_string()); cols])
            .collect();
        for indexed in self.term.grid().display_iter() {
            let point = indexed.point;
            let row = point.line.0 + offset;
            if row < 0 {
                continue; // above the viewport (shouldn't occur after rebase)
            }
            let (row, col) = (row as usize, point.column.0);
            if row >= rows || col >= cols {
                continue;
            }
            let cell = &indexed.cell;
            let mut style = if no_color {
                Style::default()
            } else {
                Style::default().fg(vt_color(cell.fg)).bg(vt_color(cell.bg))
            };
            use alacritty_terminal::term::cell::Flags;
            if cell.flags.contains(Flags::BOLD) {
                style = style.add_modifier(Modifier::BOLD);
            }
            if cell.flags.contains(Flags::ITALIC) {
                style = style.add_modifier(Modifier::ITALIC);
            }
            if cell.flags.contains(Flags::UNDERLINE) {
                style = style.add_modifier(Modifier::UNDERLINED);
            }
            if cell.flags.contains(Flags::INVERSE) {
                style = style.add_modifier(Modifier::REVERSED);
            }
            if cell.flags.contains(Flags::DIM) {
                style = style.add_modifier(Modifier::DIM);
            }
            // The inner app's cursor renders as a reversed cell — the host
            // terminal's real cursor stays with the manager.
            if cursor_visible
                && point.line == TermLine(cursor.line.0)
                && point.column == cursor.column
            {
                style = style.add_modifier(Modifier::REVERSED);
            }
            cells[row][col] = Span::styled(cell.c.to_string(), style);
        }
        cells.into_iter().map(TuiLine::from).collect()
    }

    fn encode_key(&self, key: &KeyEvent) -> Option<Vec<u8>> {
        encode_key(key, self.term.mode())
    }

    fn encode_paste(&self, text: &str) -> Vec<u8> {
        // Normalize CRLF; inner readline-style apps expect \r for Enter-ish
        // behavior only inside bracketed mode, raw \n otherwise is fine.
        let text = text.replace("\r\n", "\n");
        if self.term.mode().contains(TermMode::BRACKETED_PASTE) {
            let mut bytes = b"\x1b[200~".to_vec();
            bytes.extend_from_slice(text.as_bytes());
            bytes.extend_from_slice(b"\x1b[201~");
            bytes
        } else {
            text.into_bytes()
        }
    }

    fn drain_responses(&mut self) -> Vec<u8> {
        match self.proxy.responses.lock() {
            Ok(mut buf) => std::mem::take(&mut *buf),
            Err(_) => Vec::new(),
        }
    }

    fn scroll(&mut self, up: bool, page: bool) {
        let magnitude = if page {
            self.term.screen_lines() as i32
        } else {
            WHEEL_STEP
        };
        // `Scroll::Delta(+n)` moves up into older history, `-n` back down;
        // alacritty clamps to `[0, history_size]`, so over-scroll is a no-op.
        let delta = if up { magnitude } else { -magnitude };
        self.term.scroll_display(Scroll::Delta(delta));
    }

    fn scroll_to_bottom(&mut self) {
        self.term.scroll_display(Scroll::Bottom);
    }

    fn is_scrolled(&self) -> bool {
        self.term.grid().display_offset() != 0
    }

    fn alt_screen(&self) -> bool {
        self.term.mode().contains(TermMode::ALT_SCREEN)
    }

    fn mouse_enabled(&self) -> bool {
        self.term.mode().intersects(TermMode::MOUSE_MODE)
    }

    fn encode_mouse(
        &self,
        kind: MouseEventKind,
        col: u16,
        row: u16,
        mods: KeyModifiers,
    ) -> Option<Vec<u8>> {
        let mode = self.term.mode();
        if !mode.intersects(TermMode::MOUSE_MODE) {
            return None; // the inner app isn't tracking the mouse
        }
        // Button base (low 2 bits), whether this is a release, and whether it
        // carries the motion flag. Events the current tracking mode doesn't
        // report are dropped — sending them would be noise the app didn't ask
        // for (bare motion only under any-motion; drag only under drag/motion).
        let (mut cb, release, motion) = match kind {
            MouseEventKind::Down(b) => (button_code(b), false, false),
            MouseEventKind::Up(b) => (button_code(b), true, false),
            MouseEventKind::Drag(b) => {
                if !mode.intersects(TermMode::MOUSE_DRAG | TermMode::MOUSE_MOTION) {
                    return None;
                }
                (button_code(b), false, true)
            }
            MouseEventKind::Moved => {
                if !mode.contains(TermMode::MOUSE_MOTION) {
                    return None;
                }
                (3, false, true) // 3 = no button held
            }
            MouseEventKind::ScrollUp => (64, false, false),
            MouseEventKind::ScrollDown => (65, false, false),
            MouseEventKind::ScrollLeft => (66, false, false),
            MouseEventKind::ScrollRight => (67, false, false),
        };
        if motion {
            cb += 32;
        }
        // xterm modifier bits: Shift 4, Meta/Alt 8, Control 16.
        if mods.contains(KeyModifiers::SHIFT) {
            cb += 4;
        }
        if mods.contains(KeyModifiers::ALT) {
            cb += 8;
        }
        if mods.contains(KeyModifiers::CONTROL) {
            cb += 16;
        }

        if mode.contains(TermMode::SGR_MOUSE) {
            // ESC [ < Cb ; Px ; Py (M press | m release) — no coordinate cap.
            let suffix = if release { 'm' } else { 'M' };
            Some(format!("\x1b[<{cb};{col};{row}{suffix}").into_bytes())
        } else {
            // Legacy X10: ESC [ M, then (Cb, Px, Py) each +32 as bytes. A
            // release reports the "no button" code (3), keeping modifier/motion
            // bits; coordinates are capped at 223 (255 − 32) by the wire format.
            let cb = if release { (cb & !0b11) | 0b11 } else { cb };
            let byte = |v: u16| (v.min(223) as u8).saturating_add(32);
            Some(vec![0x1b, b'[', b'M', byte(cb), byte(col), byte(row)])
        }
    }
}

/// SGR/X10 base button code (low 2 bits) for a crossterm button.
fn button_code(b: MouseButton) -> u16 {
    match b {
        MouseButton::Left => 0,
        MouseButton::Middle => 1,
        MouseButton::Right => 2,
    }
}

/// Map a VT color to ratatui's, preserving truecolor and the 16/256 palettes.
fn vt_color(c: VtColor) -> Color {
    match c {
        VtColor::Spec(Rgb { r, g, b }) => Color::Rgb(r, g, b),
        VtColor::Indexed(i) => Color::Indexed(i),
        VtColor::Named(n) => match n {
            NamedColor::Black => Color::Black,
            NamedColor::Red => Color::Red,
            NamedColor::Green => Color::Green,
            NamedColor::Yellow => Color::Yellow,
            NamedColor::Blue => Color::Blue,
            NamedColor::Magenta => Color::Magenta,
            NamedColor::Cyan => Color::Cyan,
            NamedColor::White => Color::Gray,
            NamedColor::BrightBlack => Color::DarkGray,
            NamedColor::BrightRed => Color::LightRed,
            NamedColor::BrightGreen => Color::LightGreen,
            NamedColor::BrightYellow => Color::LightYellow,
            NamedColor::BrightBlue => Color::LightBlue,
            NamedColor::BrightMagenta => Color::LightMagenta,
            NamedColor::BrightCyan => Color::LightCyan,
            NamedColor::BrightWhite => Color::White,
            NamedColor::Foreground | NamedColor::BrightForeground => Color::Reset,
            NamedColor::Background => Color::Reset,
            _ => Color::Reset,
        },
    }
}

/// Encode a crossterm key event to the inner PTY's expected bytes via
/// **wezterm's encoders** — the piece TUI_SPEC §11 wanted from wezterm-term,
/// available from the published crates: legacy/DECCKM encoding is
/// `termwiz::input::KeyCode::encode`, and when the inner app pushed kitty
/// keyboard flags (tracked by the emulator) the key goes through
/// `wezterm_input_types::KeyEvent::encode_kitty` — exactly what wezterm's
/// GUI feeds its own panes. `Ctrl-C` still encodes to an interrupt (`0x03`
/// legacy / `CSI 99;5u` under kitty) — never a manager quit (§9/§12).
pub fn encode_key(key: &KeyEvent, mode: &TermMode) -> Option<Vec<u8>> {
    let mut mods = map_mods(key.modifiers);
    if key.code == KeyCode::BackTab {
        // crossterm's BackTab is Tab+SHIFT.
        mods |= termwiz::input::Modifiers::SHIFT;
    }

    // Kitty path: the inner app negotiated the protocol — encode with
    // wezterm's kitty encoder, honoring the exact flag set it pushed.
    if mode.intersects(TermMode::KITTY_KEYBOARD_PROTOCOL) {
        let event = wezterm_input_types::KeyEvent {
            key: map_key_kitty(key.code)?,
            modifiers: mods,
            leds: wezterm_input_types::KeyboardLedStatus::empty(),
            repeat_count: 1,
            key_is_down: true,
            raw: None,
            // wezterm-input-types only has this field on Windows.
            #[cfg(windows)]
            win32_uni_char: None,
        };
        let encoded = event.encode_kitty(kitty_flags(mode));
        if !encoded.is_empty() {
            return Some(encoded.into_bytes());
        }
        // Inexpressible without a raw event (rare) — fall through to legacy.
    }

    let modes = KeyCodeEncodeModes {
        encoding: KeyboardEncoding::Xterm,
        application_cursor_keys: mode.contains(TermMode::APP_CURSOR),
        newline_mode: mode.contains(TermMode::LINE_FEED_NEW_LINE),
        // XTMODKEYS (modifyOtherKeys) is not tracked by the emulator; the
        // kitty path supersedes it for the harnesses we host.
        modify_other_keys: None,
    };
    map_key(key.code)?
        .encode(mods, modes, true)
        .ok()
        .filter(|s| !s.is_empty())
        .map(String::into_bytes)
}

/// crossterm key → wezterm-input-types key for the kitty encoder, which
/// (per its own docs) wants Enter/Tab/Escape/Backspace as their `Char`
/// control forms.
fn map_key_kitty(code: KeyCode) -> Option<wezterm_input_types::KeyCode> {
    use wezterm_input_types::KeyCode as Wz;
    Some(match code {
        KeyCode::Char(c) => Wz::Char(c),
        KeyCode::Enter => Wz::Char('\r'),
        KeyCode::Tab | KeyCode::BackTab => Wz::Char('\t'),
        KeyCode::Esc => Wz::Char('\u{1b}'),
        KeyCode::Backspace => Wz::Char('\u{8}'),
        KeyCode::Delete => Wz::Char('\u{7f}'),
        KeyCode::Up => Wz::UpArrow,
        KeyCode::Down => Wz::DownArrow,
        KeyCode::Left => Wz::LeftArrow,
        KeyCode::Right => Wz::RightArrow,
        KeyCode::Home => Wz::Home,
        KeyCode::End => Wz::End,
        KeyCode::PageUp => Wz::PageUp,
        KeyCode::PageDown => Wz::PageDown,
        KeyCode::Insert => Wz::Insert,
        KeyCode::F(n) => Wz::Function(n),
        _ => return None,
    })
}

/// The emulator's kitty keyboard state → termwiz's flag set (1:1 bits).
fn kitty_flags(mode: &TermMode) -> KittyKeyboardFlags {
    let mut flags = KittyKeyboardFlags::NONE;
    flags.set(
        KittyKeyboardFlags::DISAMBIGUATE_ESCAPE_CODES,
        mode.contains(TermMode::DISAMBIGUATE_ESC_CODES),
    );
    flags.set(
        KittyKeyboardFlags::REPORT_EVENT_TYPES,
        mode.contains(TermMode::REPORT_EVENT_TYPES),
    );
    flags.set(
        KittyKeyboardFlags::REPORT_ALTERNATE_KEYS,
        mode.contains(TermMode::REPORT_ALTERNATE_KEYS),
    );
    flags.set(
        KittyKeyboardFlags::REPORT_ALL_KEYS_AS_ESCAPE_CODES,
        mode.contains(TermMode::REPORT_ALL_KEYS_AS_ESC),
    );
    flags.set(
        KittyKeyboardFlags::REPORT_ASSOCIATED_TEXT,
        mode.contains(TermMode::REPORT_ASSOCIATED_TEXT),
    );
    flags
}

/// crossterm key → termwiz key. `None` = a key we deliberately don't forward
/// (media keys, bare modifiers).
fn map_key(code: KeyCode) -> Option<termwiz::input::KeyCode> {
    use termwiz::input::KeyCode as Tw;
    Some(match code {
        KeyCode::Char(c) => Tw::Char(c),
        KeyCode::Enter => Tw::Enter,
        KeyCode::Tab | KeyCode::BackTab => Tw::Tab,
        KeyCode::Backspace => Tw::Backspace,
        KeyCode::Esc => Tw::Escape,
        KeyCode::Up => Tw::UpArrow,
        KeyCode::Down => Tw::DownArrow,
        KeyCode::Left => Tw::LeftArrow,
        KeyCode::Right => Tw::RightArrow,
        KeyCode::Home => Tw::Home,
        KeyCode::End => Tw::End,
        KeyCode::PageUp => Tw::PageUp,
        KeyCode::PageDown => Tw::PageDown,
        KeyCode::Insert => Tw::Insert,
        KeyCode::Delete => Tw::Delete,
        KeyCode::F(n) => Tw::Function(n),
        _ => return None,
    })
}

/// crossterm modifiers → termwiz modifiers.
fn map_mods(m: KeyModifiers) -> termwiz::input::Modifiers {
    use termwiz::input::Modifiers as Tw;
    let mut out = Tw::NONE;
    if m.contains(KeyModifiers::SHIFT) {
        out |= Tw::SHIFT;
    }
    if m.contains(KeyModifiers::ALT) {
        out |= Tw::ALT;
    }
    if m.contains(KeyModifiers::CONTROL) {
        out |= Tw::CTRL;
    }
    if m.contains(KeyModifiers::SUPER) {
        out |= Tw::SUPER;
    }
    out
}

/// OSC-52 sequences beyond this are dropped, not forwarded (herdr's cap —
/// keeps a malicious child from ballooning the splitter).
const OSC52_CAP: usize = 256 * 1024;

/// Byte-level splitter that recognizes OSC-52 (clipboard) sequences in the
/// PTY output stream so the host can re-emit them verbatim to the outer
/// terminal — the tmux `allow-passthrough` pattern. Stateful across chunk
/// boundaries.
#[derive(Default)]
pub struct Osc52Scanner {
    /// In-progress sequence bytes (from `ESC ]` on), when inside a candidate.
    pending: Vec<u8>,
    state: ScanState,
}

#[derive(Default, PartialEq)]
enum ScanState {
    #[default]
    Ground,
    /// Saw ESC; deciding.
    Esc,
    /// Inside `ESC ] …` collecting until BEL or ST.
    Osc,
    /// Inside OSC and saw ESC (potential ST terminator).
    OscEsc,
}

impl Osc52Scanner {
    /// Scan one output chunk; returns any complete OSC-52 sequences found
    /// (each verbatim, terminator included) for re-emission.
    pub fn scan(&mut self, bytes: &[u8]) -> Vec<Vec<u8>> {
        let mut found = Vec::new();
        for &b in bytes {
            match self.state {
                ScanState::Ground => {
                    if b == 0x1b {
                        self.state = ScanState::Esc;
                    }
                }
                ScanState::Esc => {
                    if b == b']' {
                        self.state = ScanState::Osc;
                        self.pending.clear();
                        self.pending.extend_from_slice(&[0x1b, b']']);
                    } else {
                        self.state = ScanState::Ground;
                    }
                }
                ScanState::Osc => {
                    if self.pending.len() > OSC52_CAP {
                        // Too big: abandon (never forward unbounded data).
                        self.pending.clear();
                        self.state = ScanState::Ground;
                    } else if b == 0x07 {
                        self.pending.push(b);
                        self.finish(&mut found);
                    } else if b == 0x1b {
                        self.state = ScanState::OscEsc;
                    } else {
                        self.pending.push(b);
                    }
                }
                ScanState::OscEsc => {
                    if b == b'\\' {
                        self.pending.extend_from_slice(&[0x1b, b'\\']);
                        self.finish(&mut found);
                    } else {
                        // Not ST — the OSC was aborted.
                        self.pending.clear();
                        self.state = ScanState::Ground;
                        if b == b']' {
                            // …and a new OSC starts.
                            self.state = ScanState::Osc;
                            self.pending.extend_from_slice(&[0x1b, b']']);
                        }
                    }
                }
            }
        }
        found
    }

    fn finish(&mut self, found: &mut Vec<Vec<u8>>) {
        let seq = std::mem::take(&mut self.pending);
        self.state = ScanState::Ground;
        // Only clipboard (OSC 52) is forwarded; titles/hyperlinks render
        // inside the pane and must not leak to the outer terminal.
        if seq.get(2..5) == Some(b"52;") {
            found.push(seq);
        }
    }
}

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

    fn text(backend: &AlacrittyBackend) -> String {
        backend
            .lines(true)
            .iter()
            .map(|l| {
                l.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn feed_renders_text_into_the_grid() {
        let mut b = AlacrittyBackend::new(20, 4);
        b.feed(b"hello\r\nworld");
        let t = text(&b);
        assert!(t.contains("hello"), "{t:?}");
        assert!(t.contains("world"), "{t:?}");
    }

    #[test]
    fn scrollback_pages_reveal_history_and_snap_back() {
        // 4 visible rows; feed 20 numbered lines so 16 land in history.
        let mut b = AlacrittyBackend::new(20, 4);
        for i in 0..20 {
            b.feed(format!("L{i}\r\n").as_bytes());
        }
        assert!(!b.is_scrolled(), "starts pinned to the live bottom");
        let bottom = text(&b);
        assert!(bottom.contains("L19"), "latest output visible: {bottom:?}");
        assert!(
            !bottom.contains("L0 "),
            "oldest not visible yet: {bottom:?}"
        );

        // Page up past the top (clamped): the oldest line comes into view and
        // the rebased renderer places it without dropping it as "negative".
        for _ in 0..6 {
            b.scroll(true, true);
        }
        assert!(b.is_scrolled(), "view is pinned into history");
        let top = text(&b);
        assert!(top.contains("L0"), "oldest output now visible: {top:?}");
        assert!(!top.contains("L19"), "live tail scrolled away: {top:?}");

        // Snapping to the bottom follows the live tail again.
        b.scroll_to_bottom();
        assert!(!b.is_scrolled(), "back at the live bottom");
        assert!(text(&b).contains("L19"), "latest output visible again");
    }

    #[test]
    fn alt_screen_flag_tracks_the_inner_app() {
        let mut b = AlacrittyBackend::new(20, 4);
        assert!(!b.alt_screen(), "main screen by default");
        b.feed(b"\x1b[?1049h"); // enter alternate screen
        assert!(b.alt_screen(), "alt screen negotiated");
        b.feed(b"\x1b[?1049l"); // leave it
        assert!(!b.alt_screen(), "back to the main screen");
    }

    #[test]
    fn mouse_enabled_tracks_reporting_modes() {
        let mut b = AlacrittyBackend::new(20, 4);
        assert!(!b.mouse_enabled(), "off until negotiated");
        b.feed(b"\x1b[?1000h"); // click tracking
        assert!(b.mouse_enabled());
        b.feed(b"\x1b[?1000l");
        assert!(!b.mouse_enabled(), "cleared when the app disables it");
    }

    #[test]
    fn sgr_mouse_encodes_wheel_click_and_modifiers() {
        let mut b = AlacrittyBackend::new(40, 10);
        assert_eq!(
            b.encode_mouse(MouseEventKind::ScrollUp, 5, 3, KeyModifiers::NONE),
            None,
            "nothing to encode until the app tracks the mouse"
        );
        // claude's set: any-motion tracking + SGR encoding.
        b.feed(b"\x1b[?1003h\x1b[?1006h");
        assert_eq!(
            b.encode_mouse(MouseEventKind::ScrollUp, 5, 3, KeyModifiers::NONE),
            Some(b"\x1b[<64;5;3M".to_vec()),
            "wheel up is button 64 at pane-relative coords"
        );
        assert_eq!(
            b.encode_mouse(MouseEventKind::ScrollDown, 5, 3, KeyModifiers::NONE),
            Some(b"\x1b[<65;5;3M".to_vec())
        );
        assert_eq!(
            b.encode_mouse(
                MouseEventKind::Down(MouseButton::Left),
                1,
                1,
                KeyModifiers::NONE
            ),
            Some(b"\x1b[<0;1;1M".to_vec()),
            "press ends in M"
        );
        assert_eq!(
            b.encode_mouse(
                MouseEventKind::Up(MouseButton::Left),
                1,
                1,
                KeyModifiers::NONE
            ),
            Some(b"\x1b[<0;1;1m".to_vec()),
            "release ends in m"
        );
        assert_eq!(
            b.encode_mouse(
                MouseEventKind::Down(MouseButton::Left),
                2,
                2,
                KeyModifiers::CONTROL
            ),
            Some(b"\x1b[<16;2;2M".to_vec()),
            "Ctrl adds 16"
        );
        assert_eq!(
            b.encode_mouse(MouseEventKind::Moved, 4, 4, KeyModifiers::NONE),
            Some(b"\x1b[<35;4;4M".to_vec()),
            "bare motion is no-button (3) + motion flag (32)"
        );
    }

    #[test]
    fn mouse_events_gate_on_the_negotiated_tracking_mode() {
        let mut b = AlacrittyBackend::new(40, 10);
        b.feed(b"\x1b[?1000h\x1b[?1006h"); // click-only + SGR
        assert_eq!(
            b.encode_mouse(MouseEventKind::Moved, 3, 3, KeyModifiers::NONE),
            None,
            "no bare motion under click-only tracking"
        );
        assert_eq!(
            b.encode_mouse(
                MouseEventKind::Drag(MouseButton::Left),
                3,
                3,
                KeyModifiers::NONE
            ),
            None,
            "no drag under click-only tracking"
        );
        b.feed(b"\x1b[?1002h"); // enable drag tracking
        assert_eq!(
            b.encode_mouse(
                MouseEventKind::Drag(MouseButton::Left),
                3,
                3,
                KeyModifiers::NONE
            ),
            Some(b"\x1b[<32;3;3M".to_vec()),
            "drag now reports button 0 + motion flag 32"
        );
    }

    #[test]
    fn legacy_mouse_encodes_without_sgr() {
        let mut b = AlacrittyBackend::new(40, 10);
        b.feed(b"\x1b[?1000h"); // click tracking, no SGR
        // ESC [ M then (Cb, Px, Py) each +32: wheel-up 64→96, (1,1)→(33,33).
        assert_eq!(
            b.encode_mouse(MouseEventKind::ScrollUp, 1, 1, KeyModifiers::NONE),
            Some(vec![0x1b, b'[', b'M', 96, 33, 33])
        );
        // A release reports the no-button code 3 → 3+32 = 35.
        assert_eq!(
            b.encode_mouse(
                MouseEventKind::Up(MouseButton::Left),
                1,
                1,
                KeyModifiers::NONE
            ),
            Some(vec![0x1b, b'[', b'M', 35, 33, 33])
        );
    }

    #[test]
    fn sgr_colors_map_to_ratatui() {
        let mut b = AlacrittyBackend::new(20, 2);
        b.feed(b"\x1b[31mred\x1b[0m plain");
        let lines = b.lines(false);
        let red = &lines[0].spans[0];
        assert_eq!(red.content.as_ref(), "r");
        assert_eq!(red.style.fg, Some(Color::Red));
    }

    #[test]
    fn paste_brackets_only_when_the_inner_app_asked() {
        let mut backend = AlacrittyBackend::new(20, 4);
        assert_eq!(
            backend.encode_paste("a\r\nb"),
            b"a\nb".to_vec(),
            "raw (CRLF-normalized) without DEC 2004"
        );
        backend.feed(b"\x1b[?2004h");
        assert_eq!(
            backend.encode_paste("hi"),
            b"\x1b[200~hi\x1b[201~".to_vec(),
            "wrapped once the inner app enables bracketed paste"
        );
    }

    #[test]
    fn resize_reflows_the_grid() {
        let mut b = AlacrittyBackend::new(10, 3);
        b.feed(b"0123456789");
        b.resize(20, 5);
        assert_eq!(b.lines(true).len(), 5, "grid tracks the new size");
        b.feed(b"\x1b[1;1Hafter-resize");
        assert!(text(&b).contains("after-resize"));
    }

    #[test]
    fn device_attribute_queries_are_answered() {
        let mut b = AlacrittyBackend::new(10, 3);
        b.feed(b"\x1b[c"); // primary DA query
        let resp = b.drain_responses();
        assert!(
            resp.starts_with(b"\x1b[?"),
            "emulator answers DA so the inner app never probes the void: {resp:?}"
        );
        assert!(b.drain_responses().is_empty(), "drained");
    }

    #[test]
    fn ctrl_c_encodes_to_interrupt_not_quit() {
        let key = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
        assert_eq!(encode_key(&key, &TermMode::default()), Some(vec![0x03]));
    }

    #[test]
    fn arrows_honor_application_cursor_mode() {
        let up = KeyEvent::from(KeyCode::Up);
        assert_eq!(
            encode_key(&up, &TermMode::default()),
            Some(b"\x1b[A".to_vec())
        );
        // Drive DECCKM through the emulator, not a hand-set flag: the inner
        // app enables application cursor keys and the encoder follows.
        let mut b = AlacrittyBackend::new(20, 4);
        b.feed(b"\x1b[?1h");
        assert_eq!(b.encode_key(&up), Some(b"\x1bOA".to_vec()));
        // Modified arrows always use the CSI 1;<mod> form.
        let ctrl_up = KeyEvent::new(KeyCode::Up, KeyModifiers::CONTROL);
        assert_eq!(b.encode_key(&ctrl_up), Some(b"\x1b[1;5A".to_vec()));
    }

    #[test]
    fn plain_and_alt_keys_encode() {
        let m = TermMode::default();
        let a = KeyEvent::from(KeyCode::Char('a'));
        assert_eq!(encode_key(&a, &m), Some(b"a".to_vec()));
        let alt_a = KeyEvent::new(KeyCode::Char('a'), KeyModifiers::ALT);
        assert_eq!(encode_key(&alt_a, &m), Some(vec![0x1b, b'a']));
        let enter = KeyEvent::from(KeyCode::Enter);
        assert_eq!(encode_key(&enter, &m), Some(vec![b'\r']));
        let del = KeyEvent::from(KeyCode::Delete);
        assert_eq!(encode_key(&del, &m), Some(b"\x1b[3~".to_vec()));
        let f5 = KeyEvent::from(KeyCode::F(5));
        assert_eq!(encode_key(&f5, &m), Some(b"\x1b[15~".to_vec()));
        let utf8 = KeyEvent::from(KeyCode::Char('é'));
        assert_eq!(encode_key(&utf8, &m), Some("é".as_bytes().to_vec()));
        let shift_tab = KeyEvent::new(KeyCode::BackTab, KeyModifiers::NONE);
        assert_eq!(encode_key(&shift_tab, &m), Some(b"\x1b[Z".to_vec()));
    }

    #[test]
    fn kitty_negotiation_switches_the_encoder() {
        // The herdr-#106 class of bug this swap retires: the inner app pushes
        // kitty keyboard flags; the encoder must follow what was negotiated.
        let mut b = AlacrittyBackend::new(20, 4);
        let shift_enter = KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT);
        let ctrl_c = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);

        // Legacy: Shift-Enter is indistinguishable from Enter; Ctrl-C is 0x03.
        assert_eq!(b.encode_key(&shift_enter), Some(vec![b'\r']));
        assert_eq!(b.encode_key(&ctrl_c), Some(vec![0x03]));

        // The inner app pushes DISAMBIGUATE_ESCAPE_CODES (kitty flag 1).
        b.feed(b"\x1b[>1u");
        assert_eq!(
            b.encode_key(&shift_enter),
            Some(b"\x1b[13;2u".to_vec()),
            "Shift-Enter becomes expressible under kitty"
        );
        assert_eq!(
            b.encode_key(&ctrl_c),
            Some(b"\x1b[99;5u".to_vec()),
            "Ctrl-C is CSI-u encoded — still an interrupt to the app"
        );
        // Plain text stays plain under DISAMBIGUATE alone.
        let a = KeyEvent::from(KeyCode::Char('a'));
        assert_eq!(b.encode_key(&a), Some(b"a".to_vec()));

        // The app pops its flags on exit: back to legacy encoding.
        b.feed(b"\x1b[<u");
        assert_eq!(b.encode_key(&shift_enter), Some(vec![b'\r']));
        assert_eq!(b.encode_key(&ctrl_c), Some(vec![0x03]));
    }

    #[test]
    fn osc52_scanner_extracts_clipboard_sequences_across_chunks() {
        let mut sc = Osc52Scanner::default();
        // Split mid-sequence to prove statefulness.
        let seq = b"\x1b]52;c;aGVsbG8=\x07";
        let found1 = sc.scan(&seq[..7]);
        assert!(found1.is_empty(), "incomplete — nothing forwarded yet");
        let found2 = sc.scan(&seq[7..]);
        assert_eq!(found2, vec![seq.to_vec()], "forwarded verbatim");
    }

    #[test]
    fn osc52_scanner_ignores_titles_and_respects_st_terminator() {
        let mut sc = Osc52Scanner::default();
        assert!(
            sc.scan(b"\x1b]0;window title\x07").is_empty(),
            "titles stay inside the pane"
        );
        let st = b"\x1b]52;c;YQ==\x1b\\";
        assert_eq!(sc.scan(st), vec![st.to_vec()], "ST-terminated form");
    }

    #[test]
    fn osc52_scanner_drops_oversized_sequences() {
        let mut sc = Osc52Scanner::default();
        let mut big = b"\x1b]52;c;".to_vec();
        big.extend(std::iter::repeat_n(b'A', OSC52_CAP + 10));
        big.push(0x07);
        assert!(sc.scan(&big).is_empty(), "capped, never ballooned");
        // Scanner recovers for the next sequence.
        let ok = b"\x1b]52;c;YQ==\x07";
        assert_eq!(sc.scan(ok), vec![ok.to_vec()]);
    }
}