@f5xc-salesdemos/pi-tui 14.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,630 @@
1
+ import { dlopen, FFIType, ptr } from "bun:ffi";
2
+ import * as fs from "node:fs";
3
+ import { $env, logger } from "@f5xc-salesdemos/pi-utils";
4
+ import { setKittyProtocolActive } from "./keys";
5
+ import { StdinBuffer } from "./stdin-buffer";
6
+
7
+ /**
8
+ * Minimal terminal interface for TUI
9
+ */
10
+
11
+ // Track active terminal for emergency cleanup on crash
12
+ let activeTerminal: ProcessTerminal | null = null;
13
+ // Track if a terminal was ever started (for emergency restore logic)
14
+ let terminalEverStarted = false;
15
+
16
+ const STD_INPUT_HANDLE = -10;
17
+ const ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200;
18
+ /**
19
+ * Emergency terminal restore - call this from signal/crash handlers
20
+ * Resets terminal state without requiring access to the ProcessTerminal instance
21
+ */
22
+ export function emergencyTerminalRestore(): void {
23
+ try {
24
+ const terminal = activeTerminal;
25
+ if (terminal) {
26
+ terminal.stop();
27
+ terminal.showCursor();
28
+ } else if (terminalEverStarted) {
29
+ // Blind restore only if we know a terminal was started but lost track of it
30
+ // This avoids writing escape sequences for non-TUI commands (grep, commit, etc.)
31
+ process.stdout.write(
32
+ "\x1b[?2004l" + // Disable bracketed paste
33
+ "\x1b[?2031l" + // Disable Mode 2031 appearance notifications
34
+ "\x1b[<u" + // Pop kitty keyboard protocol
35
+ "\x1b[>4;0m" + // Disable modifyOtherKeys fallback
36
+ "\x1b[?25h", // Show cursor
37
+ );
38
+ if (process.stdin.setRawMode) {
39
+ process.stdin.setRawMode(false);
40
+ }
41
+ }
42
+ } catch {
43
+ // Terminal may already be dead during crash cleanup - ignore errors
44
+ }
45
+ }
46
+ /** Terminal-reported appearance (dark/light mode). */
47
+ export type TerminalAppearance = "dark" | "light";
48
+ export interface Terminal {
49
+ // Start the terminal with input and resize handlers
50
+ start(onInput: (data: string) => void, onResize: () => void): void;
51
+
52
+ // Stop the terminal and restore state
53
+ stop(): void;
54
+
55
+ /**
56
+ * Drain stdin before exiting to prevent Kitty key release events from
57
+ * leaking to the parent shell over slow SSH connections.
58
+ * @param maxMs - Maximum time to drain (default: 1000ms)
59
+ * @param idleMs - Exit early if no input arrives within this time (default: 50ms)
60
+ */
61
+ drainInput(maxMs?: number, idleMs?: number): Promise<void>;
62
+
63
+ // Write output to terminal
64
+ write(data: string): void;
65
+
66
+ // Get terminal dimensions
67
+ get columns(): number;
68
+ get rows(): number;
69
+
70
+ // Whether Kitty keyboard protocol is active
71
+ get kittyProtocolActive(): boolean;
72
+
73
+ // Cursor positioning (relative to current position)
74
+ moveBy(lines: number): void; // Move cursor up (negative) or down (positive) by N lines
75
+
76
+ // Cursor visibility
77
+ hideCursor(): void; // Hide the cursor
78
+ showCursor(): void; // Show the cursor
79
+
80
+ // Clear operations
81
+ clearLine(): void; // Clear current line
82
+ clearFromCursor(): void; // Clear from cursor to end of screen
83
+ clearScreen(): void; // Clear entire screen and move cursor to (0,0)
84
+
85
+ // Title operations
86
+ setTitle(title: string): void; // Set terminal window title
87
+
88
+ /**
89
+ * Register a callback for terminal appearance (dark/light) changes.
90
+ * Detection uses OSC 11 background color query with Mode 2031 as a change trigger.
91
+ * Fires when the detected appearance changes, including the initial detection.
92
+ */
93
+ onAppearanceChange(callback: (appearance: TerminalAppearance) => void): void;
94
+
95
+ /** The last detected terminal appearance, or undefined if not yet known. */
96
+ get appearance(): TerminalAppearance | undefined;
97
+ }
98
+
99
+ /**
100
+ * Real terminal using process.stdin/stdout
101
+ */
102
+ export class ProcessTerminal implements Terminal {
103
+ #wasRaw = false;
104
+ #inputHandler?: (data: string) => void;
105
+ #resizeHandler?: () => void;
106
+ #kittyProtocolActive = false;
107
+ #modifyOtherKeysActive = false;
108
+ #modifyOtherKeysTimeout?: ReturnType<typeof setTimeout>;
109
+ #stdinBuffer?: StdinBuffer;
110
+ #stdinDataHandler?: (data: string) => void;
111
+ #dead = false;
112
+ #writeLogPath = $env.PI_TUI_WRITE_LOG || "";
113
+ #windowsVTInputRestore?: () => void;
114
+ #appearanceCallbacks: Array<(appearance: TerminalAppearance) => void> = [];
115
+ #appearance: TerminalAppearance | undefined;
116
+ #osc11Pending = false;
117
+ #osc11QueryQueued = false;
118
+ #osc11ResponseBuffer = "";
119
+ #pendingDa1Sentinels = 0;
120
+ #osc11PollTimer?: Timer;
121
+ #mode2031Active = false;
122
+ #mode2031DebounceTimer?: Timer;
123
+
124
+ get kittyProtocolActive(): boolean {
125
+ return this.#kittyProtocolActive;
126
+ }
127
+
128
+ get appearance(): TerminalAppearance | undefined {
129
+ return this.#appearance;
130
+ }
131
+
132
+ onAppearanceChange(callback: (appearance: TerminalAppearance) => void): void {
133
+ this.#appearanceCallbacks.push(callback);
134
+ }
135
+
136
+ start(onInput: (data: string) => void, onResize: () => void): void {
137
+ this.#inputHandler = onInput;
138
+ this.#resizeHandler = onResize;
139
+
140
+ // Register for emergency cleanup
141
+ activeTerminal = this;
142
+ terminalEverStarted = true;
143
+
144
+ // Save previous state and enable raw mode
145
+ this.#wasRaw = process.stdin.isRaw || false;
146
+ if (process.stdin.setRawMode) {
147
+ process.stdin.setRawMode(true);
148
+ }
149
+ process.stdin.setEncoding("utf8");
150
+ process.stdin.resume();
151
+
152
+ // Enable bracketed paste mode - terminal will wrap pastes in \x1b[200~ ... \x1b[201~
153
+ this.#safeWrite("\x1b[?2004h");
154
+
155
+ // Set up resize handler immediately
156
+ process.stdout.on("resize", this.#resizeHandler);
157
+
158
+ // Refresh terminal dimensions - they may be stale after suspend/resume
159
+ // (SIGWINCH is lost while process is stopped). Unix only.
160
+ if (process.platform !== "win32") {
161
+ process.kill(process.pid, "SIGWINCH");
162
+ }
163
+
164
+ // On Windows, enable ENABLE_VIRTUAL_TERMINAL_INPUT so the console sends
165
+ // VT escape sequences (e.g. \x1b[Z for Shift+Tab) instead of raw console
166
+ // events that lose modifier information. Must run after setRawMode(true)
167
+ // since that resets console mode flags.
168
+ this.#enableWindowsVTInput();
169
+ // Query and enable Kitty keyboard protocol
170
+ // The query handler intercepts input temporarily, then installs the user's handler
171
+ // See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/
172
+ this.#queryAndEnableKittyProtocol();
173
+
174
+ // Query terminal background color via OSC 11 for dark/light detection.
175
+ // Uses DA1 (Primary Device Attributes) as a sentinel: terminals process
176
+ // sequences in order, so if DA1 arrives before OSC 11 response,
177
+ // the terminal does not support OSC 11. This avoids indefinite hangs.
178
+ // Technique used by Neovim, bat, fish, and terminal-colorsaurus.
179
+ this.#queryBackgroundColor();
180
+
181
+ // Subscribe to Mode 2031 appearance change notifications.
182
+ // When the terminal reports a change, we re-query OSC 11 to get the
183
+ // actual background color (following Neovim convention) with 100ms debounce.
184
+ this.#safeWrite("\x1b[?2031h");
185
+
186
+ // Start periodic OSC 11 re-query for terminals without Mode 2031
187
+ // (Warp, Alacritty, WezTerm, iTerm2). Self-disables once Mode 2031 fires.
188
+ this.#startOsc11Poll();
189
+ }
190
+
191
+ /**
192
+ * On Windows, add ENABLE_VIRTUAL_TERMINAL_INPUT to the stdin console mode
193
+ * so modified keys (for example Shift+Tab) arrive as VT escape sequences.
194
+ */
195
+ #enableWindowsVTInput(): void {
196
+ if (process.platform !== "win32") return;
197
+ this.#restoreWindowsVTInput();
198
+ try {
199
+ const kernel32 = dlopen("kernel32.dll", {
200
+ GetStdHandle: { args: [FFIType.i32], returns: FFIType.ptr },
201
+ GetConsoleMode: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.bool },
202
+ SetConsoleMode: { args: [FFIType.ptr, FFIType.u32], returns: FFIType.bool },
203
+ });
204
+ const handle = kernel32.symbols.GetStdHandle(STD_INPUT_HANDLE);
205
+ const mode = new Uint32Array(1);
206
+ const modePtr = ptr(mode);
207
+ if (!modePtr || !kernel32.symbols.GetConsoleMode(handle, modePtr)) {
208
+ kernel32.close();
209
+ return;
210
+ }
211
+ const originalMode = mode[0]!;
212
+ const vtMode = originalMode | ENABLE_VIRTUAL_TERMINAL_INPUT;
213
+ if (vtMode !== originalMode && !kernel32.symbols.SetConsoleMode(handle, vtMode)) {
214
+ kernel32.close();
215
+ return;
216
+ }
217
+ this.#windowsVTInputRestore = () => {
218
+ try {
219
+ kernel32.symbols.SetConsoleMode(handle, originalMode);
220
+ } finally {
221
+ kernel32.close();
222
+ }
223
+ };
224
+ } catch {
225
+ // bun:ffi unavailable or console API unsupported; keep startup non-fatal.
226
+ }
227
+ }
228
+
229
+ #restoreWindowsVTInput(): void {
230
+ if (process.platform !== "win32") return;
231
+ const restore = this.#windowsVTInputRestore;
232
+ this.#windowsVTInputRestore = undefined;
233
+ if (!restore) return;
234
+ try {
235
+ restore();
236
+ } catch {
237
+ // Ignore restore errors during terminal teardown.
238
+ }
239
+ }
240
+
241
+ /**
242
+ * Set up StdinBuffer to split batched input into individual sequences.
243
+ * This ensures components receive single events, making matchesKey/isKeyRelease work correctly.
244
+ *
245
+ * Also watches for Kitty protocol response and enables it when detected.
246
+ * This is done here (after stdinBuffer parsing) rather than on raw stdin
247
+ * to handle the case where the response arrives split across multiple events.
248
+ */
249
+ #setupStdinBuffer(): void {
250
+ this.#stdinBuffer = new StdinBuffer({ timeout: 10 });
251
+
252
+ // Kitty protocol response pattern: \x1b[?<flags>u
253
+ const kittyResponsePattern = /^\x1b\[\?(\d+)u$/;
254
+
255
+ // Mode 2031 DSR response: \x1b[?997;{1=dark,2=light}n
256
+ const appearanceDsrPattern = /^\x1b\[\?997;([12])n$/;
257
+
258
+ // OSC 11 response: \x1b]11;rgb:RR/GG/BB or rgba:RR/GG/BB, terminated by BEL or ST.
259
+ const osc11ResponsePattern =
260
+ /^\x1b\]11;rgba?:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})(?:\x07|\x1b\\)$/;
261
+
262
+ // DA1 (Primary Device Attributes) response: \x1b[?...c
263
+ const da1ResponsePattern = /^\x1b\[\?[\d;]*c$/;
264
+
265
+ // Forward individual sequences to the input handler
266
+ this.#stdinBuffer.on("data", (sequence: string) => {
267
+ // Check for Kitty protocol response (only if not already enabled)
268
+ if (!this.#kittyProtocolActive) {
269
+ const match = sequence.match(kittyResponsePattern);
270
+ if (match) {
271
+ if (this.#modifyOtherKeysTimeout) {
272
+ clearTimeout(this.#modifyOtherKeysTimeout);
273
+ this.#modifyOtherKeysTimeout = undefined;
274
+ }
275
+ this.#kittyProtocolActive = true;
276
+ setKittyProtocolActive(true);
277
+
278
+ // Enable Kitty keyboard protocol (push flags)
279
+ // Flag 1 = disambiguate escape codes
280
+ // Flag 2 = report event types (press/repeat/release)
281
+ // Flag 4 = report alternate keys
282
+ this.#safeWrite("\x1b[>7u");
283
+ return; // Don't forward protocol response to TUI
284
+ }
285
+ }
286
+
287
+ // DA1 response: swallow our sentinel reply regardless of whether OSC 11
288
+ // already succeeded. Other terminal probes should never see these replies.
289
+ if (da1ResponsePattern.test(sequence) && this.#pendingDa1Sentinels > 0) {
290
+ this.#pendingDa1Sentinels--;
291
+ if (this.#osc11Pending) {
292
+ // DA1 arrived before OSC 11 response: terminal does not support
293
+ // OSC 11. Clear the pending state without starting a queued query
294
+ // (queued query is started below, after sentinel is consumed).
295
+ this.#osc11Pending = false;
296
+ this.#osc11ResponseBuffer = "";
297
+ }
298
+ // Now that this DA1 cycle is complete, start any queued query.
299
+ if (this.#osc11QueryQueued && !this.#dead) {
300
+ this.#osc11QueryQueued = false;
301
+ this.#startOsc11Query();
302
+ }
303
+ return;
304
+ }
305
+
306
+ // OSC 11 replies can be split if the stdin buffer flushes a partial sequence.
307
+ // Accumulate fragments until the BEL/ST terminator arrives, then parse once.
308
+ // If a new escape sequence arrives (not the ST terminator), abort buffering
309
+ // and forward it as normal input so user keystrokes are never swallowed.
310
+ if (this.#osc11Pending && (this.#osc11ResponseBuffer || sequence.startsWith("\x1b]11;"))) {
311
+ if (this.#osc11ResponseBuffer && sequence.startsWith("\x1b") && sequence !== "\x1b\\") {
312
+ // New escape sequence arrived mid-buffer — not an OSC 11 continuation.
313
+ this.#osc11ResponseBuffer = "";
314
+ // Fall through to normal input handling below.
315
+ } else {
316
+ this.#osc11ResponseBuffer += sequence;
317
+ const osc11Match = this.#osc11ResponseBuffer.match(osc11ResponsePattern);
318
+ if (!osc11Match) return;
319
+ const [, rHex, gHex, bHex] = osc11Match;
320
+ this.#osc11Pending = false;
321
+ this.#osc11ResponseBuffer = "";
322
+ this.#handleOsc11Response(rHex!, gHex!, bHex!);
323
+ return;
324
+ }
325
+ }
326
+
327
+ // Mode 2031 change notification: re-query OSC 11 with 100ms debounce
328
+ // (Neovim convention — coalesces rapid notifications during transitions)
329
+ const appearanceMatch = sequence.match(appearanceDsrPattern);
330
+ if (appearanceMatch) {
331
+ if (!this.#mode2031Active) {
332
+ this.#mode2031Active = true;
333
+ this.#stopOsc11Poll();
334
+ }
335
+ if (this.#mode2031DebounceTimer) clearTimeout(this.#mode2031DebounceTimer);
336
+ this.#mode2031DebounceTimer = setTimeout(() => {
337
+ this.#mode2031DebounceTimer = undefined;
338
+ this.#queryBackgroundColor();
339
+ }, 100);
340
+ return;
341
+ }
342
+ if (this.#inputHandler) {
343
+ this.#inputHandler(sequence);
344
+ }
345
+ });
346
+
347
+ // Re-wrap paste content with bracketed paste markers for existing editor handling
348
+ this.#stdinBuffer.on("paste", (content: string) => {
349
+ if (this.#inputHandler) {
350
+ this.#inputHandler(`\x1b[200~${content}\x1b[201~`);
351
+ }
352
+ });
353
+
354
+ // Handler that pipes stdin data through the buffer
355
+ this.#stdinDataHandler = (data: string) => {
356
+ this.#stdinBuffer!.process(data);
357
+ };
358
+ }
359
+
360
+ /**
361
+ * Send OSC 11 background color query followed by DA1 sentinel.
362
+ * DA1 avoids indefinite hangs: if DA1 response arrives before OSC 11,
363
+ * the terminal does not support OSC 11.
364
+ */
365
+ #queryBackgroundColor(): void {
366
+ if (this.#dead) return;
367
+ // Queue if an OSC 11 query is in flight or its DA1 sentinel hasn't been
368
+ // consumed yet. Starting a new query while a DA1 is outstanding would
369
+ // increment the sentinel counter, and the old DA1 arrival would then
370
+ // prematurely clear the new query's pending state.
371
+ if (this.#osc11Pending || this.#pendingDa1Sentinels > 0) {
372
+ this.#osc11QueryQueued = true;
373
+ return;
374
+ }
375
+ this.#startOsc11Query();
376
+ }
377
+
378
+ #startOsc11Query(): void {
379
+ this.#osc11Pending = true;
380
+ this.#osc11ResponseBuffer = "";
381
+ this.#pendingDa1Sentinels++;
382
+ this.#safeWrite("\x1b]11;?\x07"); // OSC 11 query (BEL terminated)
383
+ this.#safeWrite("\x1b[c"); // DA1 sentinel
384
+ }
385
+ /**
386
+ * Parse an OSC 11 background color response and compute BT.601 luminance.
387
+ * Handles 1-, 2-, 3-, and 4-digit XParseColor hex components.
388
+ */
389
+ #handleOsc11Response(rHex: string, gHex: string, bHex: string): void {
390
+ const normalize = (hex: string): number => {
391
+ const value = parseInt(hex, 16);
392
+ if (Number.isNaN(value)) return 0;
393
+ const max = 16 ** hex.length - 1;
394
+ return max > 0 ? value / max : 0;
395
+ };
396
+ const luminance = 0.299 * normalize(rHex) + 0.587 * normalize(gHex) + 0.114 * normalize(bHex);
397
+ const mode: TerminalAppearance = luminance < 0.5 ? "dark" : "light";
398
+ if (mode === this.#appearance) return;
399
+ this.#appearance = mode;
400
+ for (const cb of this.#appearanceCallbacks) {
401
+ try {
402
+ cb(mode);
403
+ } catch {
404
+ /* ignore callback errors */
405
+ }
406
+ }
407
+ }
408
+
409
+ /**
410
+ * Start periodic OSC 11 re-queries for terminals without Mode 2031 (Warp, Alacritty, WezTerm).
411
+ * Self-disables once Mode 2031 fires (push-based is better than polling).
412
+ */
413
+ #startOsc11Poll(): void {
414
+ this.#stopOsc11Poll();
415
+ this.#osc11PollTimer = setInterval(() => {
416
+ if (this.#dead) {
417
+ this.#stopOsc11Poll();
418
+ return;
419
+ }
420
+ this.#queryBackgroundColor();
421
+ }, 2_000);
422
+ this.#osc11PollTimer.unref();
423
+ }
424
+
425
+ #stopOsc11Poll(): void {
426
+ if (this.#osc11PollTimer) {
427
+ clearInterval(this.#osc11PollTimer);
428
+ this.#osc11PollTimer = undefined;
429
+ }
430
+ }
431
+
432
+ /**
433
+ * Query terminal for Kitty keyboard protocol support and enable if available.
434
+ *
435
+ * Sends CSI ? u to query current flags. If terminal responds with CSI ? <flags> u,
436
+ * it supports the protocol and we enable it with CSI > 1 u.
437
+ *
438
+ * The response is detected in setupStdinBuffer's data handler, which properly
439
+ * handles the case where the response arrives split across multiple stdin events.
440
+ */
441
+ #queryAndEnableKittyProtocol(): void {
442
+ this.#setupStdinBuffer();
443
+ process.stdin.on("data", this.#stdinDataHandler!);
444
+ this.#safeWrite("\x1b[?u");
445
+ this.#modifyOtherKeysTimeout = setTimeout(() => {
446
+ this.#modifyOtherKeysTimeout = undefined;
447
+ if (this.#kittyProtocolActive || this.#modifyOtherKeysActive) {
448
+ return;
449
+ }
450
+ this.#safeWrite("\x1b[>4;2m");
451
+ this.#modifyOtherKeysActive = true;
452
+ }, 150);
453
+ }
454
+
455
+ async drainInput(maxMs = 1000, idleMs = 50): Promise<void> {
456
+ if (this.#kittyProtocolActive) {
457
+ // Disable Kitty keyboard protocol first so any late key releases
458
+ // do not generate new Kitty escape sequences.
459
+ this.#safeWrite("\x1b[<u");
460
+ this.#kittyProtocolActive = false;
461
+ setKittyProtocolActive(false);
462
+ }
463
+ if (this.#modifyOtherKeysTimeout) {
464
+ clearTimeout(this.#modifyOtherKeysTimeout);
465
+ this.#modifyOtherKeysTimeout = undefined;
466
+ }
467
+ if (this.#modifyOtherKeysActive) {
468
+ this.#safeWrite("\x1b[>4;0m");
469
+ this.#modifyOtherKeysActive = false;
470
+ }
471
+
472
+ const previousHandler = this.#inputHandler;
473
+ this.#inputHandler = undefined;
474
+
475
+ let lastDataTime = Date.now();
476
+ const onData = () => {
477
+ lastDataTime = Date.now();
478
+ };
479
+
480
+ process.stdin.on("data", onData);
481
+ const endTime = Date.now() + maxMs;
482
+
483
+ try {
484
+ while (true) {
485
+ const now = Date.now();
486
+ const timeLeft = endTime - now;
487
+ if (timeLeft <= 0) break;
488
+ if (now - lastDataTime >= idleMs) break;
489
+ await new Promise(resolve => setTimeout(resolve, Math.min(idleMs, timeLeft)));
490
+ }
491
+ } finally {
492
+ process.stdin.removeListener("data", onData);
493
+ this.#inputHandler = previousHandler;
494
+ }
495
+ }
496
+
497
+ stop(): void {
498
+ // Unregister from emergency cleanup
499
+ if (activeTerminal === this) {
500
+ activeTerminal = null;
501
+ }
502
+
503
+ // Disable bracketed paste mode
504
+ this.#safeWrite("\x1b[?2004l");
505
+
506
+ // Disable Mode 2031 appearance change notifications
507
+ this.#safeWrite("\x1b[?2031l");
508
+ this.#stopOsc11Poll();
509
+ if (this.#mode2031DebounceTimer) {
510
+ clearTimeout(this.#mode2031DebounceTimer);
511
+ this.#mode2031DebounceTimer = undefined;
512
+ }
513
+ this.#appearanceCallbacks = [];
514
+ this.#osc11Pending = false;
515
+ this.#osc11QueryQueued = false;
516
+ this.#osc11ResponseBuffer = "";
517
+ this.#pendingDa1Sentinels = 0;
518
+ this.#mode2031Active = false;
519
+
520
+ // Disable Kitty keyboard protocol if not already done by drainInput()
521
+ if (this.#kittyProtocolActive) {
522
+ this.#safeWrite("\x1b[<u");
523
+ this.#kittyProtocolActive = false;
524
+ setKittyProtocolActive(false);
525
+ }
526
+ if (this.#modifyOtherKeysTimeout) {
527
+ clearTimeout(this.#modifyOtherKeysTimeout);
528
+ this.#modifyOtherKeysTimeout = undefined;
529
+ }
530
+ if (this.#modifyOtherKeysActive) {
531
+ this.#safeWrite("\x1b[>4;0m");
532
+ this.#modifyOtherKeysActive = false;
533
+ }
534
+
535
+ this.#restoreWindowsVTInput();
536
+ // Clean up StdinBuffer
537
+ if (this.#stdinBuffer) {
538
+ this.#stdinBuffer.destroy();
539
+ this.#stdinBuffer = undefined;
540
+ }
541
+
542
+ // Remove event handlers
543
+ if (this.#stdinDataHandler) {
544
+ process.stdin.removeListener("data", this.#stdinDataHandler);
545
+ this.#stdinDataHandler = undefined;
546
+ }
547
+ this.#inputHandler = undefined;
548
+ this.#appearance = undefined;
549
+ if (this.#resizeHandler) {
550
+ process.stdout.removeListener("resize", this.#resizeHandler);
551
+ this.#resizeHandler = undefined;
552
+ }
553
+
554
+ // Pause stdin to prevent any buffered input (e.g., Ctrl+D) from being
555
+ // re-interpreted after raw mode is disabled. This fixes a race condition
556
+ // where Ctrl+D could close the parent shell over SSH.
557
+ process.stdin.pause();
558
+
559
+ // Restore raw mode state
560
+ if (process.stdin.setRawMode) {
561
+ process.stdin.setRawMode(this.#wasRaw);
562
+ }
563
+ }
564
+
565
+ write(data: string): void {
566
+ this.#safeWrite(data);
567
+ if (this.#writeLogPath) {
568
+ try {
569
+ fs.appendFileSync(this.#writeLogPath, data, { encoding: "utf8" });
570
+ } catch {
571
+ // Ignore logging errors
572
+ }
573
+ }
574
+ }
575
+
576
+ #safeWrite(data: string): void {
577
+ if (this.#dead) return;
578
+ try {
579
+ process.stdout.write(data);
580
+ } catch (err) {
581
+ // Any write failure means terminal is dead - no recovery possible
582
+ this.#dead = true;
583
+ logger.warn("terminal is dead - no recovery possible", { error: err, data });
584
+ }
585
+ }
586
+
587
+ get columns(): number {
588
+ return process.stdout.columns || 80;
589
+ }
590
+
591
+ get rows(): number {
592
+ return process.stdout.rows || 24;
593
+ }
594
+
595
+ moveBy(lines: number): void {
596
+ if (lines > 0) {
597
+ // Move down
598
+ this.#safeWrite(`\x1b[${lines}B`);
599
+ } else if (lines < 0) {
600
+ // Move up
601
+ this.#safeWrite(`\x1b[${-lines}A`);
602
+ }
603
+ // lines === 0: no movement
604
+ }
605
+
606
+ hideCursor(): void {
607
+ this.#safeWrite("\x1b[?25l");
608
+ }
609
+
610
+ showCursor(): void {
611
+ this.#safeWrite("\x1b[?25h");
612
+ }
613
+
614
+ clearLine(): void {
615
+ this.#safeWrite("\x1b[K");
616
+ }
617
+
618
+ clearFromCursor(): void {
619
+ this.#safeWrite("\x1b[J");
620
+ }
621
+
622
+ clearScreen(): void {
623
+ this.#safeWrite("\x1b[H\x1b[0J"); // Move to home (1,1) and clear from cursor to end
624
+ }
625
+
626
+ setTitle(title: string): void {
627
+ // OSC 0;title BEL - set terminal window title
628
+ this.#safeWrite(`\x1b]0;${title}\x07`);
629
+ }
630
+ }
package/src/ttyid.ts ADDED
@@ -0,0 +1,66 @@
1
+ import { CString, dlopen, FFIType } from "bun:ffi";
2
+ import * as fs from "node:fs";
3
+ import * as os from "node:os";
4
+
5
+ /** Resolve the TTY device path for stdin (fd 0) via POSIX `ttyname(3)`. */
6
+ export function getTtyPath(): string | null {
7
+ if (os.platform() === "linux") {
8
+ // Linux: /proc/self/fd/0 is a symlink to /dev/pts/N
9
+ try {
10
+ const ttyPath = fs.readlinkSync("/proc/self/fd/0");
11
+ if (ttyPath.startsWith("/dev/")) {
12
+ return ttyPath;
13
+ }
14
+ } catch {
15
+ return null;
16
+ }
17
+ } else if (os.platform() !== "win32") {
18
+ try {
19
+ const libName = os.platform() === "darwin" ? "libSystem.B.dylib" : "libc.so.6";
20
+ const lib = dlopen(libName, {
21
+ ttyname: { args: [FFIType.i32], returns: FFIType.ptr },
22
+ });
23
+ try {
24
+ const result = lib.symbols.ttyname(0);
25
+ return result ? new CString(result).toString() : null;
26
+ } finally {
27
+ lib.close();
28
+ }
29
+ } catch {
30
+ return null;
31
+ }
32
+ }
33
+ return null;
34
+ }
35
+ /**
36
+ * Get a stable identifier for the current terminal.
37
+ * Uses the TTY device path (e.g., /dev/pts/3), falling back to environment
38
+ * variables for terminal multiplexers or terminal emulators.
39
+ * Returns null if no terminal can be identified (e.g., piped input).
40
+ */
41
+ export function getTerminalId(): string | null {
42
+ // TTY device path — most reliable, unique per terminal tab
43
+ if (process.stdin.isTTY) {
44
+ try {
45
+ const ttyPath = getTtyPath();
46
+ if (ttyPath?.startsWith("/dev/")) {
47
+ return ttyPath.slice(5).replace(/\//g, "-"); // /dev/pts/3 -> pts-3
48
+ }
49
+ } catch {}
50
+ }
51
+
52
+ // Fallback to terminal-specific env vars
53
+ const kittyId = process.env.KITTY_WINDOW_ID;
54
+ if (kittyId) return `kitty-${kittyId}`;
55
+
56
+ const tmuxPane = process.env.TMUX_PANE;
57
+ if (tmuxPane) return `tmux-${tmuxPane}`;
58
+
59
+ const terminalSessionId = process.env.TERM_SESSION_ID; // macOS Terminal.app
60
+ if (terminalSessionId) return `apple-${terminalSessionId}`;
61
+
62
+ const wtSession = process.env.WT_SESSION; // Windows Terminal
63
+ if (wtSession) return `wt-${wtSession}`;
64
+
65
+ return null;
66
+ }