@code-yeongyu/senpi-tui 2026.8.25 → 2026.8.26-2

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.
@@ -9,6 +9,8 @@ export declare function isAppleTerminalSession(): boolean;
9
9
  export declare function normalizeNativeShiftEnterInput(data: string, shouldDetectNativeShiftEnter: boolean, isShiftPressed: boolean): string;
10
10
  export declare function normalizeAppleTerminalInput(data: string, isAppleTerminal: boolean, isShiftPressed: boolean): string;
11
11
  export declare function keyboardEnhancementEnabled(): boolean;
12
+ export declare function __stdinErrorSubscriberCountForTests(): number;
13
+ export declare function __stdinErrorDispatcherInstalledForTests(): boolean;
12
14
  /**
13
15
  * Minimal terminal interface for TUI
14
16
  */
@@ -68,6 +70,8 @@ export declare class ProcessTerminal implements Terminal {
68
70
  private keyboardProtocolBufferFlushTimer?;
69
71
  private stdinBuffer?;
70
72
  private stdinDataHandler?;
73
+ private stdinErrorHandler?;
74
+ private stdinErrorHandlerCleanupTimer?;
71
75
  private progressInterval?;
72
76
  private writeLogPath;
73
77
  constructor(options?: ProcessTerminalOptions);
@@ -119,6 +123,7 @@ export declare class ProcessTerminal implements Terminal {
119
123
  private enableWindowsVTInput;
120
124
  drainInput(maxMs?: number, idleMs?: number): Promise<void>;
121
125
  stop(): void;
126
+ private scheduleStdinErrorHandlerCleanup;
122
127
  write(data: string): void;
123
128
  get columns(): number;
124
129
  get rows(): number;
@@ -1 +1 @@
1
- {"version":3,"file":"terminal.d.ts","sourceRoot":"","sources":["../src/terminal.ts"],"names":[],"mappings":"AAqBA,MAAM,MAAM,mCAAmC,GAC5C;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GACtC;IAAE,IAAI,EAAE,mBAAmB,CAAA;CAAE,CAAC;AAEjC,wBAAgB,wCAAwC,CACvD,QAAQ,EAAE,MAAM,GACd,mCAAmC,GAAG,SAAS,CASjD;AAMD,wBAAgB,sBAAsB,I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A8C;IAQtD,OAAO,CAAC,gDAAgD;IAMxD,OAAO,CAAC,oBAAoB;IAY5B,OAAO,CAAC,qBAAqB;IAM7B,OAAO,CAAC,sBAAsB;IAM9B;;;;;OAKG;IACH,OAAO,CAAC,oBAAoB;IAwBtB,UAAU,CAAC,KAAK,SAAO,EAAE,MAAM,SAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IAsC1D,IAAI,IAAI,IAAI;IAwDZ,OAAO,CAAC,gCAAgC;IAexC,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAWzB,IAAI,OAAO,IAAI,MAAM,CAEpB;IAED,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAW3B,UAAU,IAAI,IAAI;IAIlB,UAAU,IAAI,IAAI;IAIlB,SAAS,IAAI,IAAI;IAIjB,eAAe,IAAI,IAAI;IAIvB,WAAW,IAAI,IAAI;IAInB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAQ7B,WAAW,CAAC,MAAM,EAAE,OAAO,GAAG,IAAI;IAgBlC,OAAO,CAAC,qBAAqB;CAM7B"}
package/dist/terminal.js CHANGED
@@ -14,6 +14,14 @@ const DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS = 7;
14
14
  const DEAD_TERMINAL_ERROR_CODES = new Set(["EIO", "EPIPE", "ENOTCONN"]);
15
15
  // Bun's macOS tty shim can report synchronous ioctl EIO as raw positive errno 5 without a string code.
16
16
  const EIO_ERRNO = 5;
17
+ // Bun's tty shim can also drop both properties and leave the errno only in the message text
18
+ // (`new Error("setRawMode failed with errno: 5")` - no `code`, no `errno`), so the numeric
19
+ // fallback has to read the message. Restricted to errno values that are stable across darwin
20
+ // and linux: EIO (5) and EPIPE (32). ENOTCONN is deliberately excluded because its number
21
+ // differs per platform (57 on darwin, 107 on linux) and a wrong guess would swallow a live error.
22
+ const EPIPE_ERRNO = 32;
23
+ const DEAD_TERMINAL_ERRNOS = new Set([EIO_ERRNO, EPIPE_ERRNO]);
24
+ const ERRNO_IN_MESSAGE_PATTERN = /errno:\s*(\d+)/;
17
25
  const KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS = 150;
18
26
  const KITTY_KEYBOARD_PROTOCOL_QUERY = `\x1b[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1b[?u\x1b[c`;
19
27
  export function parseKeyboardProtocolNegotiationSequence(sequence) {
@@ -51,7 +59,57 @@ function isDeadTerminalError(error) {
51
59
  return false;
52
60
  if ("code" in error && typeof error.code === "string")
53
61
  return DEAD_TERMINAL_ERROR_CODES.has(error.code);
54
- return "errno" in error && error.errno === EIO_ERRNO;
62
+ if ("errno" in error && error.errno === EIO_ERRNO)
63
+ return true;
64
+ const messageErrno = ERRNO_IN_MESSAGE_PATTERN.exec(error.message);
65
+ if (!messageErrno)
66
+ return false;
67
+ return DEAD_TERMINAL_ERRNOS.has(Number.parseInt(messageErrno[1], 10));
68
+ }
69
+ const STDIN_ERROR_HANDLER_GRACE_MS = 250;
70
+ const stdinErrorSubscribers = new Set();
71
+ export function __stdinErrorSubscriberCountForTests() {
72
+ return stdinErrorSubscribers.size;
73
+ }
74
+ export function __stdinErrorDispatcherInstalledForTests() {
75
+ return process.stdin.listeners("error").includes(dispatchStdinError);
76
+ }
77
+ /**
78
+ * A vanished or re-backgrounded controlling terminal fails the next stdin
79
+ * read with EIO; that is the only stdin error this module owns. Node reports
80
+ * it as code "EIO" (errno -5), Bun's macOS tty shim as a bare positive
81
+ * errno 5 — both shapes classify. Any other stdin failure (EBADF, EPIPE, an
82
+ * unexpected platform error) keeps its default EventEmitter propagation so it
83
+ * stays observable instead of being downgraded to a silently ignored error.
84
+ */
85
+ function isTerminalDetachStdinError(err) {
86
+ if (err.code === "EIO")
87
+ return true;
88
+ const errno = err.errno;
89
+ return errno === EIO_ERRNO || errno === -EIO_ERRNO;
90
+ }
91
+ const dispatchStdinError = (err) => {
92
+ if (!isTerminalDetachStdinError(err)) {
93
+ // Our listener must not be the reason a non-EIO error stops propagating.
94
+ // When no other "error" listener exists, EventEmitter would have thrown;
95
+ // rethrowing from inside emit() reproduces that exact contract.
96
+ const hasOtherListener = process.stdin.listeners("error").some((listener) => listener !== dispatchStdinError);
97
+ if (!hasOtherListener)
98
+ throw err;
99
+ return;
100
+ }
101
+ for (const subscriber of stdinErrorSubscribers)
102
+ subscriber(err);
103
+ };
104
+ function subscribeToStdinErrors(subscriber) {
105
+ if (stdinErrorSubscribers.size === 0)
106
+ process.stdin.on("error", dispatchStdinError);
107
+ stdinErrorSubscribers.add(subscriber);
108
+ }
109
+ function unsubscribeFromStdinErrors(subscriber) {
110
+ stdinErrorSubscribers.delete(subscriber);
111
+ if (stdinErrorSubscribers.size === 0)
112
+ process.stdin.removeListener("error", dispatchStdinError);
55
113
  }
56
114
  const DEFAULT_ESCAPE_TIMEOUT_MS = 10;
57
115
  const DEFAULT_SSH_ESCAPE_TIMEOUT_MS = 100;
@@ -161,6 +219,21 @@ export class ProcessTerminal {
161
219
  process.stdin.setRawMode(true);
162
220
  }
163
221
  process.stdin.resume();
222
+ // stdin carries the same hazard as stdout: when the controlling PTY
223
+ // disappears (launcher killed, tmux pane closed, SSH dropped) or this
224
+ // pgrp loses the tty foreground, the next read fails with EIO.
225
+ // `process.stdin` is an EventEmitter, so an unobserved "error" event is
226
+ // rethrown as an uncaught exception that kills the whole agent process.
227
+ if (this.stdinErrorHandlerCleanupTimer) {
228
+ clearTimeout(this.stdinErrorHandlerCleanupTimer);
229
+ this.stdinErrorHandlerCleanupTimer = undefined;
230
+ }
231
+ if (!this.stdinErrorHandler) {
232
+ // Swallow only: the stream stays resumable, so if this pgrp regains
233
+ // the tty foreground the session keeps accepting input.
234
+ this.stdinErrorHandler = () => { };
235
+ subscribeToStdinErrors(this.stdinErrorHandler);
236
+ }
164
237
  // Enable bracketed paste mode - terminal will wrap pastes in \x1b[200~ ... \x1b[201~
165
238
  this.rawWrite("\x1b[?2004h");
166
239
  // Set up resize handler immediately
@@ -445,6 +518,22 @@ export class ProcessTerminal {
445
518
  }
446
519
  }
447
520
  this.removeExternalStdoutGuard();
521
+ this.scheduleStdinErrorHandlerCleanup();
522
+ }
523
+ scheduleStdinErrorHandlerCleanup() {
524
+ if (!this.stdinErrorHandler || this.stdinErrorHandlerCleanupTimer)
525
+ return;
526
+ // Keep the guard armed briefly past stop(): a late PTY failure racing
527
+ // the exit path must not crash the process after the TUI tore down.
528
+ const handler = this.stdinErrorHandler;
529
+ this.stdinErrorHandlerCleanupTimer = setTimeout(() => {
530
+ this.stdinErrorHandlerCleanupTimer = undefined;
531
+ if (this.stdinErrorHandler === handler) {
532
+ this.stdinErrorHandler = undefined;
533
+ unsubscribeFromStdinErrors(handler);
534
+ }
535
+ }, STDIN_ERROR_HANDLER_GRACE_MS);
536
+ this.stdinErrorHandlerCleanupTimer.unref();
448
537
  }
449
538
  write(data) {
450
539
  this.rawWrite(data);
@@ -1 +1 @@
1
- {"version":3,"file":"terminal.js","sourceRoot":"","sources":["../src/terminal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,sBAAsB,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAElD,MAAM,8BAA8B,GAAG,IAAI,CAAC;AAC5C,MAAM,iCAAiC,GAAG,gBAAgB,CAAC;AAC3D,MAAM,gCAAgC,GAAG,gBAAgB,CA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AEO,qBAAqB;QAC5B,IAAI,CAAC,IAAI,CAAC,gBAAgB;YAAE,OAAO,KAAK,CAAC;QACzC,aAAa,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;QACrC,IAAI,CAAC,gBAAgB,GAAG,SAAS,CAAC;QAClC,OAAO,IAAI,CAAC;IACb,CAAC;CACD","sourcesContent":["import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { setKittyProtocolActive } from \"./keys.ts\";\nimport { isNativeModifierPressed } from \"./native-modifiers.ts\";\nimport { getNativeModuleCandidates } from \"./native-module-path.ts\";\nimport { StdinBuffer } from \"./stdin-buffer.ts\";\n\nconst cjsRequire = createRequire(import.meta.url);\n\nconst TERMINAL_PROGRESS_KEEPALIVE_MS = 1000;\nconst TERMINAL_PROGRESS_ACTIVE_SEQUENCE = \"\\x1b]9;4;3\\x07\";\nconst TERMINAL_PROGRESS_CLEAR_SEQUENCE = \"\\x1b]9;4;0\\x07\";\nconst NATIVE_SHIFT_ENTER_SEQUENCE = \"\\x1b[13;2u\";\nconst DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS = 7;\nconst DEAD_TERMINAL_ERROR_CODES = new Set([\"EIO\", \"EPIPE\", \"ENOTCONN\"]);\n// Bun's macOS tty shim can report synchronous ioctl EIO as raw positive errno 5 without a string code.\nconst EIO_ERRNO = 5;\nconst KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS = 150;\nconst KITTY_KEYBOARD_PROTOCOL_QUERY = `\\x1b[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\\x1b[?u\\x1b[c`;\n\nexport type KeyboardProtocolNegotiationSequence =\n\t| { type: \"kitty-flags\"; flags: number }\n\t| { type: \"device-attributes\" };\n\nexport function parseKeyboardProtocolNegotiationSequence(\n\tsequence: string,\n): KeyboardProtocolNegotiationSequence | undefined {\n\tconst kittyFlags = sequence.match(/^\\x1b\\[\\?(\\d+)u$/);\n\tif (kittyFlags) {\n\t\treturn { type: \"kitty-flags\", flags: Number.parseInt(kittyFlags[1]!, 10) };\n\t}\n\tif (/^\\x1b\\[\\?[\\d;]*c$/.test(sequence)) {\n\t\treturn { type: \"device-attributes\" };\n\t}\n\treturn undefined;\n}\n\nfunction isKeyboardProtocolNegotiationSequencePrefix(sequence: string): boolean {\n\treturn sequence === \"\\x1b[\" || /^\\x1b\\[\\?[\\d;]*$/.test(sequence);\n}\n\nexport function isAppleTerminalSession(): boolean {\n\treturn process.platform === \"darwin\" && process.env.TERM_PROGRAM === \"Apple_Terminal\";\n}\n\nexport function normalizeNativeShiftEnterInput(\n\tdata: string,\n\tshouldDetectNativeShiftEnter: boolean,\n\tisShiftPressed: boolean,\n): string {\n\tif (shouldDetectNativeShiftEnter && data === \"\\r\" && isShiftPressed) return NATIVE_SHIFT_ENTER_SEQUENCE;\n\treturn data;\n}\n\nexport function normalizeAppleTerminalInput(data: string, isAppleTerminal: boolean, isShiftPressed: boolean): string {\n\treturn normalizeNativeShiftEnterInput(data, isAppleTerminal, isShiftPressed);\n}\n\nexport function keyboardEnhancementEnabled(): boolean {\n\tconst value = process.env.PI_TUI_KEYBOARD_PROTOCOL;\n\tif (value === undefined) return true;\n\treturn ![\"0\", \"false\", \"no\", \"off\"].includes(value.toLowerCase());\n}\n\nfunction isDeadTerminalError(error: unknown): boolean {\n\tif (!(error instanceof Error)) return false;\n\tif (\"code\" in error && typeof error.code === \"string\") return DEAD_TERMINAL_ERROR_CODES.has(error.code);\n\treturn \"errno\" in error && error.errno === EIO_ERRNO;\n}\n\n/**\n * Minimal terminal interface for TUI\n */\nexport interface Terminal {\n\t// Start the terminal with input and resize handlers\n\tstart(onInput: (data: string) => void, onResize: () => void): void;\n\n\t// Stop the terminal and restore state\n\tstop(): void;\n\n\t/**\n\t * Drain stdin before exiting to prevent Kitty key release events from\n\t * leaking to the parent shell over slow SSH connections.\n\t * @param maxMs - Maximum time to drain (default: 1000ms)\n\t * @param idleMs - Exit early if no input arrives within this time (default: 50ms)\n\t */\n\tdrainInput(maxMs?: number, idleMs?: number): Promise<void>;\n\n\t// Write output to terminal\n\twrite(data: string): void;\n\n\t// Get terminal dimensions\n\tget columns(): number;\n\tget rows(): number;\n\n\t// Whether Kitty keyboard protocol is active\n\tget kittyProtocolActive(): boolean;\n\n\t// Cursor positioning (relative to current position)\n\tmoveBy(lines: number): void; // Move cursor up (negative) or down (positive) by N lines\n\n\t// Cursor visibility\n\thideCursor(): void; // Hide the cursor\n\tshowCursor(): void; // Show the cursor\n\n\t// Clear operations\n\tclearLine(): void; // Clear current line\n\tclearFromCursor(): void; // Clear from cursor to end of screen\n\tclearScreen(): void; // Clear entire screen and move cursor to (0,0)\n\n\t// Title operations\n\tsetTitle(title: string): void; // Set terminal window title\n\n\t// Progress indicator (OSC 9;4)\n\tsetProgress(active: boolean): void;\n}\n\nexport interface ProcessTerminalOptions {\n\t/**\n\t * When set, stdout writes not issued by this terminal are hidden from the\n\t * screen while the terminal is started and forwarded to this handler\n\t * instead. External writes (console.log, libraries) would otherwise\n\t * interleave with frames and desynchronize differential rendering.\n\t */\n\tonExternalStdoutWrite?: (text: string) => void;\n}\n\nconst DEFAULT_ESCAPE_TIMEOUT_MS = 10;\nconst DEFAULT_SSH_ESCAPE_TIMEOUT_MS = 100;\n\n/**\n * Resolve how long to wait for the rest of an escape sequence before\n * dispatching a lone ESC as the Escape key. Legacy Alt+key input is ESC plus\n * another byte, so high-latency transports need a longer reassembly window.\n */\nexport function resolveEscapeTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {\n\tconst configured = Number(env.PI_TUI_ESC_TIMEOUT);\n\tif (Number.isFinite(configured) && configured > 0) {\n\t\treturn configured;\n\t}\n\tif (env.SSH_CONNECTION || env.SSH_TTY) {\n\t\treturn DEFAULT_SSH_ESCAPE_TIMEOUT_MS;\n\t}\n\treturn DEFAULT_ESCAPE_TIMEOUT_MS;\n}\n\n/**\n * Real terminal using process.stdin/stdout\n */\nexport class ProcessTerminal implements Terminal {\n\tprivate wasRaw = false;\n\tprivate onExternalStdoutWrite?: (text: string) => void;\n\tprivate originalStdoutWrite?: typeof process.stdout.write;\n\tprivate rawStdoutWrite?: (data: string) => void;\n\tprivate forwardingExternalWrite = false;\n\tprivate inputHandler?: (data: string) => void;\n\tprivate resizeHandler?: () => void;\n\tprivate _kittyProtocolActive = false;\n\tprivate _modifyOtherKeysActive = false;\n\tprivate keyboardProtocolPushed = false;\n\tprivate keyboardProtocolNegotiationBuffer = \"\";\n\tprivate keyboardProtocolBufferFlushTimer?: ReturnType<typeof setTimeout>;\n\tprivate stdinBuffer?: StdinBuffer;\n\tprivate stdinDataHandler?: (data: string | Buffer) => void;\n\tprivate progressInterval?: ReturnType<typeof setInterval>;\n\tprivate writeLogPath = (() => {\n\t\tconst env = process.env.PI_TUI_WRITE_LOG || \"\";\n\t\tif (!env) return \"\";\n\t\ttry {\n\t\t\tif (fs.statSync(env).isDirectory()) {\n\t\t\t\tconst now = new Date();\n\t\t\t\tconst ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}_${String(now.getHours()).padStart(2, \"0\")}-${String(now.getMinutes()).padStart(2, \"0\")}-${String(now.getSeconds()).padStart(2, \"0\")}`;\n\t\t\t\treturn path.join(env, `tui-${ts}-${process.pid}.log`);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Not an existing directory - use as-is (file path)\n\t\t}\n\t\treturn env;\n\t})();\n\n\tconstructor(options?: ProcessTerminalOptions) {\n\t\tthis.onExternalStdoutWrite = options?.onExternalStdoutWrite;\n\t}\n\n\tget kittyProtocolActive(): boolean {\n\t\treturn this._kittyProtocolActive;\n\t}\n\n\tprivate rawWrite(data: string): void {\n\t\tif (this.rawStdoutWrite) {\n\t\t\tthis.rawStdoutWrite(data);\n\t\t\treturn;\n\t\t}\n\t\tprocess.stdout.write(data);\n\t}\n\n\tprivate installExternalStdoutGuard(): void {\n\t\tconst handler = this.onExternalStdoutWrite;\n\t\tif (!handler || this.originalStdoutWrite) {\n\t\t\treturn;\n\t\t}\n\t\tthis.originalStdoutWrite = process.stdout.write;\n\t\tconst rawWrite = process.stdout.write.bind(process.stdout);\n\t\tthis.rawStdoutWrite = rawWrite;\n\n\t\tprocess.stdout.write = ((\n\t\t\tchunk: string | Uint8Array,\n\t\t\tencodingOrCallback?: BufferEncoding | ((error?: Error | null) => void),\n\t\t\tcallback?: (error?: Error | null) => void,\n\t\t): boolean => {\n\t\t\tconst cb = typeof encodingOrCallback === \"function\" ? encodingOrCallback : callback;\n\t\t\tconst encoding = typeof encodingOrCallback === \"string\" ? encodingOrCallback : undefined;\n\t\t\tconst text = typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString(encoding);\n\t\t\tif (this.forwardingExternalWrite) {\n\t\t\t\trawWrite(text);\n\t\t\t\tcb?.(null);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tthis.forwardingExternalWrite = true;\n\t\t\ttry {\n\t\t\t\thandler(text);\n\t\t\t} catch {\n\t\t\t\trawWrite(text);\n\t\t\t} finally {\n\t\t\t\tthis.forwardingExternalWrite = false;\n\t\t\t}\n\t\t\tcb?.(null);\n\t\t\treturn true;\n\t\t}) as typeof process.stdout.write;\n\t}\n\n\tprivate removeExternalStdoutGuard(): void {\n\t\tif (!this.originalStdoutWrite) {\n\t\t\treturn;\n\t\t}\n\t\tprocess.stdout.write = this.originalStdoutWrite;\n\t\tthis.originalStdoutWrite = undefined;\n\t\tthis.rawStdoutWrite = undefined;\n\t}\n\n\tget modifyOtherKeysActive(): boolean {\n\t\treturn this._modifyOtherKeysActive;\n\t}\n\n\tstart(onInput: (data: string) => void, onResize: () => void): void {\n\t\tthis.installExternalStdoutGuard();\n\t\tthis.inputHandler = onInput;\n\t\tthis.resizeHandler = onResize;\n\n\t\t// Save previous state and enable raw mode\n\t\tthis.wasRaw = process.stdin.isRaw || false;\n\t\tif (process.stdin.setRawMode) {\n\t\t\tprocess.stdin.setRawMode(true);\n\t\t}\n\t\tprocess.stdin.resume();\n\n\t\t// Enable bracketed paste mode - terminal will wrap pastes in \\x1b[200~ ... \\x1b[201~\n\t\tthis.rawWrite(\"\\x1b[?2004h\");\n\n\t\t// Set up resize handler immediately\n\t\tprocess.stdout.on(\"resize\", this.resizeHandler);\n\n\t\t// Refresh terminal dimensions - they may be stale after suspend/resume\n\t\t// (SIGWINCH is lost while process is stopped). Unix only.\n\t\tif (process.platform !== \"win32\") {\n\t\t\tprocess.kill(process.pid, \"SIGWINCH\");\n\t\t}\n\n\t\t// On Windows, enable ENABLE_VIRTUAL_TERMINAL_INPUT so the console sends\n\t\t// VT escape sequences (e.g. \\x1b[Z for Shift+Tab) instead of raw console\n\t\t// events that lose modifier information. Must run AFTER setRawMode(true)\n\t\t// since that resets console mode flags.\n\t\tthis.enableWindowsVTInput();\n\n\t\t// Query Kitty keyboard protocol and fall back to modifyOtherKeys when DA confirms no Kitty response.\n\t\t// See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/\n\t\tthis.queryAndEnableKittyProtocol();\n\t}\n\n\t/**\n\t * Set up StdinBuffer to split batched input into individual sequences.\n\t * This ensures components receive single events, making matchesKey/isKeyRelease work correctly.\n\t *\n\t * Also watches for Kitty protocol response and enables it when detected.\n\t * This is done here (after stdinBuffer parsing) rather than on raw stdin\n\t * to handle the case where the response arrives split across multiple events.\n\t */\n\tprivate setupStdinBuffer(): void {\n\t\tthis.stdinBuffer = new StdinBuffer({ escapeTimeout: resolveEscapeTimeoutMs() });\n\n\t\t// Forward individual sequences to the input handler\n\t\tthis.stdinBuffer.on(\"data\", (sequence) => {\n\t\t\tconst negotiationSequence = this.readKeyboardProtocolNegotiationSequence(sequence);\n\t\t\tif (negotiationSequence === \"pending\") {\n\t\t\t\tthis.scheduleKeyboardProtocolNegotiationBufferFlush();\n\t\t\t\treturn; // Wait briefly for the rest of a split Kitty response.\n\t\t\t}\n\t\t\tif (this.handleKeyboardProtocolNegotiationSequence(negotiationSequence)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.forwardInputSequence(sequence);\n\t\t});\n\n\t\t// Re-wrap paste content with bracketed paste markers for existing editor handling\n\t\tthis.stdinBuffer.on(\"paste\", (content) => {\n\t\t\tif (this.inputHandler) {\n\t\t\t\tthis.inputHandler(`\\x1b[200~${content}\\x1b[201~`);\n\t\t\t}\n\t\t});\n\n\t\t// Handler that pipes stdin data through the buffer\n\t\tthis.stdinDataHandler = (data: string | Buffer) => {\n\t\t\tthis.stdinBuffer!.process(data);\n\t\t};\n\t}\n\n\t/**\n\t * Query terminal for Kitty keyboard protocol support and enable it if available.\n\t *\n\t * Kitty's progressive enhancement detection requires requesting the desired\n\t * flags before querying them. The trailing DA query is a sentinel supported by\n\t * terminals that do not know Kitty keyboard protocol; receiving DA before a\n\t * Kitty response enables modifyOtherKeys fallback without a startup timeout.\n\t *\n\t * The requested flags are:\n\t * - 1 = disambiguate escape codes\n\t * - 2 = report event types (press/repeat/release)\n\t * - 4 = report alternate keys (shifted key, base layout key)\n\t */\n\tprivate queryAndEnableKittyProtocol(): void {\n\t\tthis.setupStdinBuffer();\n\t\tprocess.stdin.on(\"data\", this.stdinDataHandler!);\n\t\tif (!keyboardEnhancementEnabled()) {\n\t\t\treturn;\n\t\t}\n\t\tif (process.env.TMUX !== undefined || process.env.TMUX_PANE !== undefined) {\n\t\t\tthis.enableModifyOtherKeys();\n\t\t}\n\t\tthis.keyboardProtocolPushed = true;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.rawWrite(KITTY_KEYBOARD_PROTOCOL_QUERY);\n\t}\n\n\tprivate handleKeyboardProtocolNegotiationSequence(\n\t\tnegotiationSequence: KeyboardProtocolNegotiationSequence | undefined,\n\t): boolean {\n\t\tif (!negotiationSequence) return false;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tif (negotiationSequence.type === \"kitty-flags\") {\n\t\t\tif (negotiationSequence.flags !== 0) {\n\t\t\t\tthis.disableModifyOtherKeys();\n\t\t\t\tif (!this._kittyProtocolActive) {\n\t\t\t\t\tthis._kittyProtocolActive = true;\n\t\t\t\t\tsetKittyProtocolActive(true);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis.enableModifyOtherKeys();\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (!this._kittyProtocolActive) {\n\t\t\tthis.enableModifyOtherKeys();\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate readKeyboardProtocolNegotiationSequence(\n\t\tsequence: string,\n\t): KeyboardProtocolNegotiationSequence | \"pending\" | undefined {\n\t\tif (this.keyboardProtocolNegotiationBuffer) {\n\t\t\tconst bufferedSequence = this.keyboardProtocolNegotiationBuffer + sequence;\n\t\t\tconst negotiationSequence = parseKeyboardProtocolNegotiationSequence(bufferedSequence);\n\t\t\tif (negotiationSequence) {\n\t\t\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\t\t\treturn negotiationSequence;\n\t\t\t}\n\t\t\tif (isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence)) {\n\t\t\t\tthis.setKeyboardProtocolNegotiationBuffer(bufferedSequence);\n\t\t\t\treturn \"pending\";\n\t\t\t}\n\t\t\tthis.flushKeyboardProtocolNegotiationBufferAsInput();\n\t\t}\n\n\t\tconst negotiationSequence = parseKeyboardProtocolNegotiationSequence(sequence);\n\t\tif (negotiationSequence) return negotiationSequence;\n\t\tif (isKeyboardProtocolNegotiationSequencePrefix(sequence)) {\n\t\t\tthis.setKeyboardProtocolNegotiationBuffer(sequence);\n\t\t\treturn \"pending\";\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate setKeyboardProtocolNegotiationBuffer(sequence: string): void {\n\t\tthis.clearKeyboardProtocolNegotiationBufferFlushTimer();\n\t\tthis.keyboardProtocolNegotiationBuffer = sequence;\n\t}\n\n\tprivate clearKeyboardProtocolNegotiationBuffer(): void {\n\t\tthis.clearKeyboardProtocolNegotiationBufferFlushTimer();\n\t\tthis.keyboardProtocolNegotiationBuffer = \"\";\n\t}\n\n\tprivate flushKeyboardProtocolNegotiationBufferAsInput(): void {\n\t\tif (!this.keyboardProtocolNegotiationBuffer) return;\n\t\tconst sequence = this.keyboardProtocolNegotiationBuffer;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.forwardInputSequence(sequence);\n\t}\n\n\tprivate scheduleKeyboardProtocolNegotiationBufferFlush(): void {\n\t\tif (!this.keyboardProtocolNegotiationBuffer || this.keyboardProtocolBufferFlushTimer) return;\n\t\tthis.keyboardProtocolBufferFlushTimer = setTimeout(() => {\n\t\t\tthis.keyboardProtocolBufferFlushTimer = undefined;\n\t\t\tthis.flushKeyboardProtocolNegotiationBufferAsInput();\n\t\t}, KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS);\n\t}\n\n\tprivate clearKeyboardProtocolNegotiationBufferFlushTimer(): void {\n\t\tif (!this.keyboardProtocolBufferFlushTimer) return;\n\t\tclearTimeout(this.keyboardProtocolBufferFlushTimer);\n\t\tthis.keyboardProtocolBufferFlushTimer = undefined;\n\t}\n\n\tprivate forwardInputSequence(sequence: string): void {\n\t\tif (!this.inputHandler) return;\n\t\tconst shouldDetectNativeShiftEnter =\n\t\t\tsequence === \"\\r\" && (isAppleTerminalSession() || process.platform === \"win32\");\n\t\tconst input = normalizeNativeShiftEnterInput(\n\t\t\tsequence,\n\t\t\tshouldDetectNativeShiftEnter,\n\t\t\tshouldDetectNativeShiftEnter && isNativeModifierPressed(\"shift\"),\n\t\t);\n\t\tthis.inputHandler(input);\n\t}\n\n\tprivate enableModifyOtherKeys(): void {\n\t\tif (this._kittyProtocolActive || this._modifyOtherKeysActive) return;\n\t\tthis.rawWrite(\"\\x1b[>4;2m\");\n\t\tthis._modifyOtherKeysActive = true;\n\t}\n\n\tprivate disableModifyOtherKeys(): void {\n\t\tif (!this._modifyOtherKeysActive) return;\n\t\tthis.rawWrite(\"\\x1b[>4;0m\");\n\t\tthis._modifyOtherKeysActive = false;\n\t}\n\n\t/**\n\t * On Windows, add ENABLE_VIRTUAL_TERMINAL_INPUT (0x0200) to the stdin\n\t * console handle so the terminal sends VT sequences for modified keys\n\t * (e.g. \\x1b[Z for Shift+Tab). Without this, libuv's ReadConsoleInputW\n\t * discards modifier state and Shift+Tab arrives as plain \\t.\n\t */\n\tprivate enableWindowsVTInput(): void {\n\t\tif (process.platform !== \"win32\") return;\n\t\ttry {\n\t\t\tconst arch = process.arch;\n\t\t\tif (arch !== \"x64\" && arch !== \"arm64\") return;\n\n\t\t\t// Dynamic require so non-Windows and bundled/browser paths never load the\n\t\t\t// native helper. Installed packages resolve it from pi-tui; standalone\n\t\t\t// binaries resolve the copy next to the executable.\n\t\t\tconst nativePath = path.join(\"native\", \"win32\", \"prebuilds\", `win32-${arch}`, \"win32-console-mode.node\");\n\t\t\tfor (const modulePath of getNativeModuleCandidates(nativePath)) {\n\t\t\t\ttry {\n\t\t\t\t\tconst helper = cjsRequire(modulePath) as { enableVirtualTerminalInput?: () => boolean };\n\t\t\t\t\thelper.enableVirtualTerminalInput?.();\n\t\t\t\t\treturn;\n\t\t\t\t} catch {\n\t\t\t\t\t// Try the next possible packaging location.\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Native helper not available — Shift+Tab won't be distinguishable from Tab.\n\t\t}\n\t}\n\n\tasync drainInput(maxMs = 1000, idleMs = 50): Promise<void> {\n\t\tconst shouldDisableKittyProtocol = this.keyboardProtocolPushed || this._kittyProtocolActive;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tif (shouldDisableKittyProtocol) {\n\t\t\t// Disable Kitty keyboard protocol first so any late key releases\n\t\t\t// do not generate new Kitty escape sequences.\n\t\t\tthis.rawWrite(\"\\x1b[<u\");\n\t\t\tthis.keyboardProtocolPushed = false;\n\t\t\tthis._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\n\t\tthis.disableModifyOtherKeys();\n\n\t\tconst previousHandler = this.inputHandler;\n\t\tthis.inputHandler = undefined;\n\n\t\tlet lastDataTime = Date.now();\n\t\tconst onData = () => {\n\t\t\tlastDataTime = Date.now();\n\t\t};\n\n\t\tprocess.stdin.on(\"data\", onData);\n\t\tconst endTime = Date.now() + maxMs;\n\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst now = Date.now();\n\t\t\t\tconst timeLeft = endTime - now;\n\t\t\t\tif (timeLeft <= 0) break;\n\t\t\t\tif (now - lastDataTime >= idleMs) break;\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, Math.min(idleMs, timeLeft)));\n\t\t\t}\n\t\t} finally {\n\t\t\tprocess.stdin.removeListener(\"data\", onData);\n\t\t\tthis.inputHandler = previousHandler;\n\t\t}\n\t}\n\n\tstop(): void {\n\t\tif (this.clearProgressInterval()) {\n\t\t\tthis.rawWrite(TERMINAL_PROGRESS_CLEAR_SEQUENCE);\n\t\t}\n\n\t\t// Disable bracketed paste mode\n\t\tthis.rawWrite(\"\\x1b[?2004l\");\n\n\t\tconst shouldDisableKittyProtocol = this.keyboardProtocolPushed || this._kittyProtocolActive;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\n\t\t// Disable Kitty keyboard protocol if not already done by drainInput()\n\t\tif (shouldDisableKittyProtocol) {\n\t\t\tthis.rawWrite(\"\\x1b[<u\");\n\t\t\tthis.keyboardProtocolPushed = false;\n\t\t\tthis._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\n\t\tthis.disableModifyOtherKeys();\n\n\t\t// Clean up StdinBuffer\n\t\tif (this.stdinBuffer) {\n\t\t\tthis.stdinBuffer.destroy();\n\t\t\tthis.stdinBuffer = undefined;\n\t\t}\n\n\t\t// Remove event handlers\n\t\tif (this.stdinDataHandler) {\n\t\t\tprocess.stdin.removeListener(\"data\", this.stdinDataHandler);\n\t\t\tthis.stdinDataHandler = undefined;\n\t\t}\n\t\tthis.inputHandler = undefined;\n\t\tif (this.resizeHandler) {\n\t\t\tprocess.stdout.removeListener(\"resize\", this.resizeHandler);\n\t\t\tthis.resizeHandler = undefined;\n\t\t}\n\n\t\t// Pause stdin to prevent any buffered input (e.g., Ctrl+D) from being\n\t\t// re-interpreted after raw mode is disabled. This fixes a race condition\n\t\t// where Ctrl+D could close the parent shell over SSH.\n\t\tprocess.stdin.pause();\n\n\t\t// Restore raw mode state\n\t\tif (process.stdin.setRawMode) {\n\t\t\ttry {\n\t\t\t\tprocess.stdin.setRawMode(this.wasRaw);\n\t\t\t} catch (error) {\n\t\t\t\tif (!isDeadTerminalError(error)) throw error;\n\t\t\t}\n\t\t}\n\n\t\tthis.removeExternalStdoutGuard();\n\t}\n\n\twrite(data: string): void {\n\t\tthis.rawWrite(data);\n\t\tif (this.writeLogPath) {\n\t\t\ttry {\n\t\t\t\tfs.appendFileSync(this.writeLogPath, data, { encoding: \"utf8\" });\n\t\t\t} catch {\n\t\t\t\t// Ignore logging errors\n\t\t\t}\n\t\t}\n\t}\n\n\tget columns(): number {\n\t\treturn process.stdout.columns || Number(process.env.COLUMNS) || 80;\n\t}\n\n\tget rows(): number {\n\t\treturn process.stdout.rows || Number(process.env.LINES) || 24;\n\t}\n\n\tmoveBy(lines: number): void {\n\t\tif (lines > 0) {\n\t\t\t// Move down\n\t\t\tthis.rawWrite(`\\x1b[${lines}B`);\n\t\t} else if (lines < 0) {\n\t\t\t// Move up\n\t\t\tthis.rawWrite(`\\x1b[${-lines}A`);\n\t\t}\n\t\t// lines === 0: no movement\n\t}\n\n\thideCursor(): void {\n\t\tthis.rawWrite(\"\\x1b[?25l\");\n\t}\n\n\tshowCursor(): void {\n\t\tthis.rawWrite(\"\\x1b[?25h\");\n\t}\n\n\tclearLine(): void {\n\t\tthis.rawWrite(\"\\x1b[K\");\n\t}\n\n\tclearFromCursor(): void {\n\t\tthis.rawWrite(\"\\x1b[J\");\n\t}\n\n\tclearScreen(): void {\n\t\tthis.rawWrite(\"\\x1b[2J\\x1b[H\"); // Clear screen and move to home (1,1)\n\t}\n\n\tsetTitle(title: string): void {\n\t\t// OSC 0;title BEL - set terminal window title. Control characters are\n\t\t// stripped so a title cannot terminate the OSC early and leak the rest\n\t\t// onto the screen.\n\t\tconst sanitizedTitle = title.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/g, \"\");\n\t\tthis.rawWrite(`\\x1b]0;${sanitizedTitle}\\x07`);\n\t}\n\n\tsetProgress(active: boolean): void {\n\t\tif (active) {\n\t\t\t// OSC 9;4;3 - indeterminate progress\n\t\t\tthis.rawWrite(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);\n\t\t\tif (!this.progressInterval) {\n\t\t\t\tthis.progressInterval = setInterval(() => {\n\t\t\t\t\tthis.rawWrite(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);\n\t\t\t\t}, TERMINAL_PROGRESS_KEEPALIVE_MS);\n\t\t\t}\n\t\t} else {\n\t\t\tthis.clearProgressInterval();\n\t\t\t// OSC 9;4;0 - clear progress\n\t\t\tthis.rawWrite(TERMINAL_PROGRESS_CLEAR_SEQUENCE);\n\t\t}\n\t}\n\n\tprivate clearProgressInterval(): boolean {\n\t\tif (!this.progressInterval) return false;\n\t\tclearInterval(this.progressInterval);\n\t\tthis.progressInterval = undefined;\n\t\treturn true;\n\t}\n}\n"]}
1
+ {"version":3,"file":"terminal.js","sourceRoot":"","sources":["../src/terminal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,sBAAsB,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,MAAM,UAAU,GAAG,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;QACtE,uEAAuE;QACvE,mBAAmB;QACnB,MAAM,cAAc,GAAG,KAAK,CAAC,OAAO,CAAC,+BAA+B,EAAE,EAAE,CAAC,CAAC;QAC1E,IAAI,CAAC,QAAQ,CAAC,UAAU,cAAc,MAAM,CAAC,CAAC;IAC/C,CAAC;IAED,WAAW,CAAC,MAAe;QAC1B,IAAI,MAAM,EAAE,CAAC;YACZ,qCAAqC;YACrC,IAAI,CAAC,QAAQ,CAAC,iCAAiC,CAAC,CAAC;YACjD,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC;gBAC5B,IAAI,CAAC,gBAAgB,GAAG,WAAW,CAAC,GAAG,EAAE;oBACxC,IAAI,CAAC,QAAQ,CAAC,iCAAiC,CAAC,CAAC;gBAClD,CAAC,EAAE,8BAA8B,CAAC,CAAC;YACpC,CAAC;QACF,CAAC;aAAM,CAAC;YACP,IAAI,CAAC,qBAAqB,EAAE,CAAC;YAC7B,6BAA6B;YAC7B,IAAI,CAAC,QAAQ,CAAC,gCAAgC,CAAC,CAAC;QACjD,CAAC;IACF,CAAC;IAEO,qBAAqB;QAC5B,IAAI,CAAC,IAAI,CAAC,gBAAgB;YAAE,OAAO,KAAK,CAAC;QACzC,aAAa,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;QACrC,IAAI,CAAC,gBAAgB,GAAG,SAAS,CAAC;QAClC,OAAO,IAAI,CAAC;IACb,CAAC;CACD","sourcesContent":["import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { setKittyProtocolActive } from \"./keys.ts\";\nimport { isNativeModifierPressed } from \"./native-modifiers.ts\";\nimport { getNativeModuleCandidates } from \"./native-module-path.ts\";\nimport { StdinBuffer } from \"./stdin-buffer.ts\";\n\nconst cjsRequire = createRequire(import.meta.url);\n\nconst TERMINAL_PROGRESS_KEEPALIVE_MS = 1000;\nconst TERMINAL_PROGRESS_ACTIVE_SEQUENCE = \"\\x1b]9;4;3\\x07\";\nconst TERMINAL_PROGRESS_CLEAR_SEQUENCE = \"\\x1b]9;4;0\\x07\";\nconst NATIVE_SHIFT_ENTER_SEQUENCE = \"\\x1b[13;2u\";\nconst DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS = 7;\nconst DEAD_TERMINAL_ERROR_CODES = new Set([\"EIO\", \"EPIPE\", \"ENOTCONN\"]);\n// Bun's macOS tty shim can report synchronous ioctl EIO as raw positive errno 5 without a string code.\nconst EIO_ERRNO = 5;\n// Bun's tty shim can also drop both properties and leave the errno only in the message text\n// (`new Error(\"setRawMode failed with errno: 5\")` - no `code`, no `errno`), so the numeric\n// fallback has to read the message. Restricted to errno values that are stable across darwin\n// and linux: EIO (5) and EPIPE (32). ENOTCONN is deliberately excluded because its number\n// differs per platform (57 on darwin, 107 on linux) and a wrong guess would swallow a live error.\nconst EPIPE_ERRNO = 32;\nconst DEAD_TERMINAL_ERRNOS = new Set([EIO_ERRNO, EPIPE_ERRNO]);\nconst ERRNO_IN_MESSAGE_PATTERN = /errno:\\s*(\\d+)/;\nconst KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS = 150;\nconst KITTY_KEYBOARD_PROTOCOL_QUERY = `\\x1b[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\\x1b[?u\\x1b[c`;\n\nexport type KeyboardProtocolNegotiationSequence =\n\t| { type: \"kitty-flags\"; flags: number }\n\t| { type: \"device-attributes\" };\n\nexport function parseKeyboardProtocolNegotiationSequence(\n\tsequence: string,\n): KeyboardProtocolNegotiationSequence | undefined {\n\tconst kittyFlags = sequence.match(/^\\x1b\\[\\?(\\d+)u$/);\n\tif (kittyFlags) {\n\t\treturn { type: \"kitty-flags\", flags: Number.parseInt(kittyFlags[1]!, 10) };\n\t}\n\tif (/^\\x1b\\[\\?[\\d;]*c$/.test(sequence)) {\n\t\treturn { type: \"device-attributes\" };\n\t}\n\treturn undefined;\n}\n\nfunction isKeyboardProtocolNegotiationSequencePrefix(sequence: string): boolean {\n\treturn sequence === \"\\x1b[\" || /^\\x1b\\[\\?[\\d;]*$/.test(sequence);\n}\n\nexport function isAppleTerminalSession(): boolean {\n\treturn process.platform === \"darwin\" && process.env.TERM_PROGRAM === \"Apple_Terminal\";\n}\n\nexport function normalizeNativeShiftEnterInput(\n\tdata: string,\n\tshouldDetectNativeShiftEnter: boolean,\n\tisShiftPressed: boolean,\n): string {\n\tif (shouldDetectNativeShiftEnter && data === \"\\r\" && isShiftPressed) return NATIVE_SHIFT_ENTER_SEQUENCE;\n\treturn data;\n}\n\nexport function normalizeAppleTerminalInput(data: string, isAppleTerminal: boolean, isShiftPressed: boolean): string {\n\treturn normalizeNativeShiftEnterInput(data, isAppleTerminal, isShiftPressed);\n}\n\nexport function keyboardEnhancementEnabled(): boolean {\n\tconst value = process.env.PI_TUI_KEYBOARD_PROTOCOL;\n\tif (value === undefined) return true;\n\treturn ![\"0\", \"false\", \"no\", \"off\"].includes(value.toLowerCase());\n}\n\nfunction isDeadTerminalError(error: unknown): boolean {\n\tif (!(error instanceof Error)) return false;\n\tif (\"code\" in error && typeof error.code === \"string\") return DEAD_TERMINAL_ERROR_CODES.has(error.code);\n\tif (\"errno\" in error && error.errno === EIO_ERRNO) return true;\n\tconst messageErrno = ERRNO_IN_MESSAGE_PATTERN.exec(error.message);\n\tif (!messageErrno) return false;\n\treturn DEAD_TERMINAL_ERRNOS.has(Number.parseInt(messageErrno[1]!, 10));\n}\n\nconst STDIN_ERROR_HANDLER_GRACE_MS = 250;\nconst stdinErrorSubscribers = new Set<(err: Error) => void>();\n\nexport function __stdinErrorSubscriberCountForTests(): number {\n\treturn stdinErrorSubscribers.size;\n}\nexport function __stdinErrorDispatcherInstalledForTests(): boolean {\n\treturn process.stdin.listeners(\"error\").includes(dispatchStdinError);\n}\n\n/**\n * A vanished or re-backgrounded controlling terminal fails the next stdin\n * read with EIO; that is the only stdin error this module owns. Node reports\n * it as code \"EIO\" (errno -5), Bun's macOS tty shim as a bare positive\n * errno 5 — both shapes classify. Any other stdin failure (EBADF, EPIPE, an\n * unexpected platform error) keeps its default EventEmitter propagation so it\n * stays observable instead of being downgraded to a silently ignored error.\n */\nfunction isTerminalDetachStdinError(err: Error): boolean {\n\tif ((err as NodeJS.ErrnoException).code === \"EIO\") return true;\n\tconst errno = (err as NodeJS.ErrnoException).errno;\n\treturn errno === EIO_ERRNO || errno === -EIO_ERRNO;\n}\n\nconst dispatchStdinError = (err: Error): void => {\n\tif (!isTerminalDetachStdinError(err)) {\n\t\t// Our listener must not be the reason a non-EIO error stops propagating.\n\t\t// When no other \"error\" listener exists, EventEmitter would have thrown;\n\t\t// rethrowing from inside emit() reproduces that exact contract.\n\t\tconst hasOtherListener = process.stdin.listeners(\"error\").some((listener) => listener !== dispatchStdinError);\n\t\tif (!hasOtherListener) throw err;\n\t\treturn;\n\t}\n\tfor (const subscriber of stdinErrorSubscribers) subscriber(err);\n};\n\nfunction subscribeToStdinErrors(subscriber: (err: Error) => void): void {\n\tif (stdinErrorSubscribers.size === 0) process.stdin.on(\"error\", dispatchStdinError);\n\tstdinErrorSubscribers.add(subscriber);\n}\n\nfunction unsubscribeFromStdinErrors(subscriber: (err: Error) => void): void {\n\tstdinErrorSubscribers.delete(subscriber);\n\tif (stdinErrorSubscribers.size === 0) process.stdin.removeListener(\"error\", dispatchStdinError);\n}\n\n/**\n * Minimal terminal interface for TUI\n */\nexport interface Terminal {\n\t// Start the terminal with input and resize handlers\n\tstart(onInput: (data: string) => void, onResize: () => void): void;\n\n\t// Stop the terminal and restore state\n\tstop(): void;\n\n\t/**\n\t * Drain stdin before exiting to prevent Kitty key release events from\n\t * leaking to the parent shell over slow SSH connections.\n\t * @param maxMs - Maximum time to drain (default: 1000ms)\n\t * @param idleMs - Exit early if no input arrives within this time (default: 50ms)\n\t */\n\tdrainInput(maxMs?: number, idleMs?: number): Promise<void>;\n\n\t// Write output to terminal\n\twrite(data: string): void;\n\n\t// Get terminal dimensions\n\tget columns(): number;\n\tget rows(): number;\n\n\t// Whether Kitty keyboard protocol is active\n\tget kittyProtocolActive(): boolean;\n\n\t// Cursor positioning (relative to current position)\n\tmoveBy(lines: number): void; // Move cursor up (negative) or down (positive) by N lines\n\n\t// Cursor visibility\n\thideCursor(): void; // Hide the cursor\n\tshowCursor(): void; // Show the cursor\n\n\t// Clear operations\n\tclearLine(): void; // Clear current line\n\tclearFromCursor(): void; // Clear from cursor to end of screen\n\tclearScreen(): void; // Clear entire screen and move cursor to (0,0)\n\n\t// Title operations\n\tsetTitle(title: string): void; // Set terminal window title\n\n\t// Progress indicator (OSC 9;4)\n\tsetProgress(active: boolean): void;\n}\n\nexport interface ProcessTerminalOptions {\n\t/**\n\t * When set, stdout writes not issued by this terminal are hidden from the\n\t * screen while the terminal is started and forwarded to this handler\n\t * instead. External writes (console.log, libraries) would otherwise\n\t * interleave with frames and desynchronize differential rendering.\n\t */\n\tonExternalStdoutWrite?: (text: string) => void;\n}\n\nconst DEFAULT_ESCAPE_TIMEOUT_MS = 10;\nconst DEFAULT_SSH_ESCAPE_TIMEOUT_MS = 100;\n\n/**\n * Resolve how long to wait for the rest of an escape sequence before\n * dispatching a lone ESC as the Escape key. Legacy Alt+key input is ESC plus\n * another byte, so high-latency transports need a longer reassembly window.\n */\nexport function resolveEscapeTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {\n\tconst configured = Number(env.PI_TUI_ESC_TIMEOUT);\n\tif (Number.isFinite(configured) && configured > 0) {\n\t\treturn configured;\n\t}\n\tif (env.SSH_CONNECTION || env.SSH_TTY) {\n\t\treturn DEFAULT_SSH_ESCAPE_TIMEOUT_MS;\n\t}\n\treturn DEFAULT_ESCAPE_TIMEOUT_MS;\n}\n\n/**\n * Real terminal using process.stdin/stdout\n */\nexport class ProcessTerminal implements Terminal {\n\tprivate wasRaw = false;\n\tprivate onExternalStdoutWrite?: (text: string) => void;\n\tprivate originalStdoutWrite?: typeof process.stdout.write;\n\tprivate rawStdoutWrite?: (data: string) => void;\n\tprivate forwardingExternalWrite = false;\n\tprivate inputHandler?: (data: string) => void;\n\tprivate resizeHandler?: () => void;\n\tprivate _kittyProtocolActive = false;\n\tprivate _modifyOtherKeysActive = false;\n\tprivate keyboardProtocolPushed = false;\n\tprivate keyboardProtocolNegotiationBuffer = \"\";\n\tprivate keyboardProtocolBufferFlushTimer?: ReturnType<typeof setTimeout>;\n\tprivate stdinBuffer?: StdinBuffer;\n\tprivate stdinDataHandler?: (data: string | Buffer) => void;\n\tprivate stdinErrorHandler?: (err: Error) => void;\n\tprivate stdinErrorHandlerCleanupTimer?: ReturnType<typeof setTimeout>;\n\tprivate progressInterval?: ReturnType<typeof setInterval>;\n\tprivate writeLogPath = (() => {\n\t\tconst env = process.env.PI_TUI_WRITE_LOG || \"\";\n\t\tif (!env) return \"\";\n\t\ttry {\n\t\t\tif (fs.statSync(env).isDirectory()) {\n\t\t\t\tconst now = new Date();\n\t\t\t\tconst ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}_${String(now.getHours()).padStart(2, \"0\")}-${String(now.getMinutes()).padStart(2, \"0\")}-${String(now.getSeconds()).padStart(2, \"0\")}`;\n\t\t\t\treturn path.join(env, `tui-${ts}-${process.pid}.log`);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Not an existing directory - use as-is (file path)\n\t\t}\n\t\treturn env;\n\t})();\n\n\tconstructor(options?: ProcessTerminalOptions) {\n\t\tthis.onExternalStdoutWrite = options?.onExternalStdoutWrite;\n\t}\n\n\tget kittyProtocolActive(): boolean {\n\t\treturn this._kittyProtocolActive;\n\t}\n\n\tprivate rawWrite(data: string): void {\n\t\tif (this.rawStdoutWrite) {\n\t\t\tthis.rawStdoutWrite(data);\n\t\t\treturn;\n\t\t}\n\t\tprocess.stdout.write(data);\n\t}\n\n\tprivate installExternalStdoutGuard(): void {\n\t\tconst handler = this.onExternalStdoutWrite;\n\t\tif (!handler || this.originalStdoutWrite) {\n\t\t\treturn;\n\t\t}\n\t\tthis.originalStdoutWrite = process.stdout.write;\n\t\tconst rawWrite = process.stdout.write.bind(process.stdout);\n\t\tthis.rawStdoutWrite = rawWrite;\n\n\t\tprocess.stdout.write = ((\n\t\t\tchunk: string | Uint8Array,\n\t\t\tencodingOrCallback?: BufferEncoding | ((error?: Error | null) => void),\n\t\t\tcallback?: (error?: Error | null) => void,\n\t\t): boolean => {\n\t\t\tconst cb = typeof encodingOrCallback === \"function\" ? encodingOrCallback : callback;\n\t\t\tconst encoding = typeof encodingOrCallback === \"string\" ? encodingOrCallback : undefined;\n\t\t\tconst text = typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString(encoding);\n\t\t\tif (this.forwardingExternalWrite) {\n\t\t\t\trawWrite(text);\n\t\t\t\tcb?.(null);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tthis.forwardingExternalWrite = true;\n\t\t\ttry {\n\t\t\t\thandler(text);\n\t\t\t} catch {\n\t\t\t\trawWrite(text);\n\t\t\t} finally {\n\t\t\t\tthis.forwardingExternalWrite = false;\n\t\t\t}\n\t\t\tcb?.(null);\n\t\t\treturn true;\n\t\t}) as typeof process.stdout.write;\n\t}\n\n\tprivate removeExternalStdoutGuard(): void {\n\t\tif (!this.originalStdoutWrite) {\n\t\t\treturn;\n\t\t}\n\t\tprocess.stdout.write = this.originalStdoutWrite;\n\t\tthis.originalStdoutWrite = undefined;\n\t\tthis.rawStdoutWrite = undefined;\n\t}\n\n\tget modifyOtherKeysActive(): boolean {\n\t\treturn this._modifyOtherKeysActive;\n\t}\n\n\tstart(onInput: (data: string) => void, onResize: () => void): void {\n\t\tthis.installExternalStdoutGuard();\n\t\tthis.inputHandler = onInput;\n\t\tthis.resizeHandler = onResize;\n\n\t\t// Save previous state and enable raw mode\n\t\tthis.wasRaw = process.stdin.isRaw || false;\n\t\tif (process.stdin.setRawMode) {\n\t\t\tprocess.stdin.setRawMode(true);\n\t\t}\n\t\tprocess.stdin.resume();\n\n\t\t// stdin carries the same hazard as stdout: when the controlling PTY\n\t\t// disappears (launcher killed, tmux pane closed, SSH dropped) or this\n\t\t// pgrp loses the tty foreground, the next read fails with EIO.\n\t\t// `process.stdin` is an EventEmitter, so an unobserved \"error\" event is\n\t\t// rethrown as an uncaught exception that kills the whole agent process.\n\t\tif (this.stdinErrorHandlerCleanupTimer) {\n\t\t\tclearTimeout(this.stdinErrorHandlerCleanupTimer);\n\t\t\tthis.stdinErrorHandlerCleanupTimer = undefined;\n\t\t}\n\t\tif (!this.stdinErrorHandler) {\n\t\t\t// Swallow only: the stream stays resumable, so if this pgrp regains\n\t\t\t// the tty foreground the session keeps accepting input.\n\t\t\tthis.stdinErrorHandler = () => {};\n\t\t\tsubscribeToStdinErrors(this.stdinErrorHandler);\n\t\t}\n\n\t\t// Enable bracketed paste mode - terminal will wrap pastes in \\x1b[200~ ... \\x1b[201~\n\t\tthis.rawWrite(\"\\x1b[?2004h\");\n\n\t\t// Set up resize handler immediately\n\t\tprocess.stdout.on(\"resize\", this.resizeHandler);\n\n\t\t// Refresh terminal dimensions - they may be stale after suspend/resume\n\t\t// (SIGWINCH is lost while process is stopped). Unix only.\n\t\tif (process.platform !== \"win32\") {\n\t\t\tprocess.kill(process.pid, \"SIGWINCH\");\n\t\t}\n\n\t\t// On Windows, enable ENABLE_VIRTUAL_TERMINAL_INPUT so the console sends\n\t\t// VT escape sequences (e.g. \\x1b[Z for Shift+Tab) instead of raw console\n\t\t// events that lose modifier information. Must run AFTER setRawMode(true)\n\t\t// since that resets console mode flags.\n\t\tthis.enableWindowsVTInput();\n\n\t\t// Query Kitty keyboard protocol and fall back to modifyOtherKeys when DA confirms no Kitty response.\n\t\t// See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/\n\t\tthis.queryAndEnableKittyProtocol();\n\t}\n\n\t/**\n\t * Set up StdinBuffer to split batched input into individual sequences.\n\t * This ensures components receive single events, making matchesKey/isKeyRelease work correctly.\n\t *\n\t * Also watches for Kitty protocol response and enables it when detected.\n\t * This is done here (after stdinBuffer parsing) rather than on raw stdin\n\t * to handle the case where the response arrives split across multiple events.\n\t */\n\tprivate setupStdinBuffer(): void {\n\t\tthis.stdinBuffer = new StdinBuffer({ escapeTimeout: resolveEscapeTimeoutMs() });\n\n\t\t// Forward individual sequences to the input handler\n\t\tthis.stdinBuffer.on(\"data\", (sequence) => {\n\t\t\tconst negotiationSequence = this.readKeyboardProtocolNegotiationSequence(sequence);\n\t\t\tif (negotiationSequence === \"pending\") {\n\t\t\t\tthis.scheduleKeyboardProtocolNegotiationBufferFlush();\n\t\t\t\treturn; // Wait briefly for the rest of a split Kitty response.\n\t\t\t}\n\t\t\tif (this.handleKeyboardProtocolNegotiationSequence(negotiationSequence)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.forwardInputSequence(sequence);\n\t\t});\n\n\t\t// Re-wrap paste content with bracketed paste markers for existing editor handling\n\t\tthis.stdinBuffer.on(\"paste\", (content) => {\n\t\t\tif (this.inputHandler) {\n\t\t\t\tthis.inputHandler(`\\x1b[200~${content}\\x1b[201~`);\n\t\t\t}\n\t\t});\n\n\t\t// Handler that pipes stdin data through the buffer\n\t\tthis.stdinDataHandler = (data: string | Buffer) => {\n\t\t\tthis.stdinBuffer!.process(data);\n\t\t};\n\t}\n\n\t/**\n\t * Query terminal for Kitty keyboard protocol support and enable it if available.\n\t *\n\t * Kitty's progressive enhancement detection requires requesting the desired\n\t * flags before querying them. The trailing DA query is a sentinel supported by\n\t * terminals that do not know Kitty keyboard protocol; receiving DA before a\n\t * Kitty response enables modifyOtherKeys fallback without a startup timeout.\n\t *\n\t * The requested flags are:\n\t * - 1 = disambiguate escape codes\n\t * - 2 = report event types (press/repeat/release)\n\t * - 4 = report alternate keys (shifted key, base layout key)\n\t */\n\tprivate queryAndEnableKittyProtocol(): void {\n\t\tthis.setupStdinBuffer();\n\t\tprocess.stdin.on(\"data\", this.stdinDataHandler!);\n\t\tif (!keyboardEnhancementEnabled()) {\n\t\t\treturn;\n\t\t}\n\t\tif (process.env.TMUX !== undefined || process.env.TMUX_PANE !== undefined) {\n\t\t\tthis.enableModifyOtherKeys();\n\t\t}\n\t\tthis.keyboardProtocolPushed = true;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.rawWrite(KITTY_KEYBOARD_PROTOCOL_QUERY);\n\t}\n\n\tprivate handleKeyboardProtocolNegotiationSequence(\n\t\tnegotiationSequence: KeyboardProtocolNegotiationSequence | undefined,\n\t): boolean {\n\t\tif (!negotiationSequence) return false;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tif (negotiationSequence.type === \"kitty-flags\") {\n\t\t\tif (negotiationSequence.flags !== 0) {\n\t\t\t\tthis.disableModifyOtherKeys();\n\t\t\t\tif (!this._kittyProtocolActive) {\n\t\t\t\t\tthis._kittyProtocolActive = true;\n\t\t\t\t\tsetKittyProtocolActive(true);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis.enableModifyOtherKeys();\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tif (!this._kittyProtocolActive) {\n\t\t\tthis.enableModifyOtherKeys();\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate readKeyboardProtocolNegotiationSequence(\n\t\tsequence: string,\n\t): KeyboardProtocolNegotiationSequence | \"pending\" | undefined {\n\t\tif (this.keyboardProtocolNegotiationBuffer) {\n\t\t\tconst bufferedSequence = this.keyboardProtocolNegotiationBuffer + sequence;\n\t\t\tconst negotiationSequence = parseKeyboardProtocolNegotiationSequence(bufferedSequence);\n\t\t\tif (negotiationSequence) {\n\t\t\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\t\t\treturn negotiationSequence;\n\t\t\t}\n\t\t\tif (isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence)) {\n\t\t\t\tthis.setKeyboardProtocolNegotiationBuffer(bufferedSequence);\n\t\t\t\treturn \"pending\";\n\t\t\t}\n\t\t\tthis.flushKeyboardProtocolNegotiationBufferAsInput();\n\t\t}\n\n\t\tconst negotiationSequence = parseKeyboardProtocolNegotiationSequence(sequence);\n\t\tif (negotiationSequence) return negotiationSequence;\n\t\tif (isKeyboardProtocolNegotiationSequencePrefix(sequence)) {\n\t\t\tthis.setKeyboardProtocolNegotiationBuffer(sequence);\n\t\t\treturn \"pending\";\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate setKeyboardProtocolNegotiationBuffer(sequence: string): void {\n\t\tthis.clearKeyboardProtocolNegotiationBufferFlushTimer();\n\t\tthis.keyboardProtocolNegotiationBuffer = sequence;\n\t}\n\n\tprivate clearKeyboardProtocolNegotiationBuffer(): void {\n\t\tthis.clearKeyboardProtocolNegotiationBufferFlushTimer();\n\t\tthis.keyboardProtocolNegotiationBuffer = \"\";\n\t}\n\n\tprivate flushKeyboardProtocolNegotiationBufferAsInput(): void {\n\t\tif (!this.keyboardProtocolNegotiationBuffer) return;\n\t\tconst sequence = this.keyboardProtocolNegotiationBuffer;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.forwardInputSequence(sequence);\n\t}\n\n\tprivate scheduleKeyboardProtocolNegotiationBufferFlush(): void {\n\t\tif (!this.keyboardProtocolNegotiationBuffer || this.keyboardProtocolBufferFlushTimer) return;\n\t\tthis.keyboardProtocolBufferFlushTimer = setTimeout(() => {\n\t\t\tthis.keyboardProtocolBufferFlushTimer = undefined;\n\t\t\tthis.flushKeyboardProtocolNegotiationBufferAsInput();\n\t\t}, KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS);\n\t}\n\n\tprivate clearKeyboardProtocolNegotiationBufferFlushTimer(): void {\n\t\tif (!this.keyboardProtocolBufferFlushTimer) return;\n\t\tclearTimeout(this.keyboardProtocolBufferFlushTimer);\n\t\tthis.keyboardProtocolBufferFlushTimer = undefined;\n\t}\n\n\tprivate forwardInputSequence(sequence: string): void {\n\t\tif (!this.inputHandler) return;\n\t\tconst shouldDetectNativeShiftEnter =\n\t\t\tsequence === \"\\r\" && (isAppleTerminalSession() || process.platform === \"win32\");\n\t\tconst input = normalizeNativeShiftEnterInput(\n\t\t\tsequence,\n\t\t\tshouldDetectNativeShiftEnter,\n\t\t\tshouldDetectNativeShiftEnter && isNativeModifierPressed(\"shift\"),\n\t\t);\n\t\tthis.inputHandler(input);\n\t}\n\n\tprivate enableModifyOtherKeys(): void {\n\t\tif (this._kittyProtocolActive || this._modifyOtherKeysActive) return;\n\t\tthis.rawWrite(\"\\x1b[>4;2m\");\n\t\tthis._modifyOtherKeysActive = true;\n\t}\n\n\tprivate disableModifyOtherKeys(): void {\n\t\tif (!this._modifyOtherKeysActive) return;\n\t\tthis.rawWrite(\"\\x1b[>4;0m\");\n\t\tthis._modifyOtherKeysActive = false;\n\t}\n\n\t/**\n\t * On Windows, add ENABLE_VIRTUAL_TERMINAL_INPUT (0x0200) to the stdin\n\t * console handle so the terminal sends VT sequences for modified keys\n\t * (e.g. \\x1b[Z for Shift+Tab). Without this, libuv's ReadConsoleInputW\n\t * discards modifier state and Shift+Tab arrives as plain \\t.\n\t */\n\tprivate enableWindowsVTInput(): void {\n\t\tif (process.platform !== \"win32\") return;\n\t\ttry {\n\t\t\tconst arch = process.arch;\n\t\t\tif (arch !== \"x64\" && arch !== \"arm64\") return;\n\n\t\t\t// Dynamic require so non-Windows and bundled/browser paths never load the\n\t\t\t// native helper. Installed packages resolve it from pi-tui; standalone\n\t\t\t// binaries resolve the copy next to the executable.\n\t\t\tconst nativePath = path.join(\"native\", \"win32\", \"prebuilds\", `win32-${arch}`, \"win32-console-mode.node\");\n\t\t\tfor (const modulePath of getNativeModuleCandidates(nativePath)) {\n\t\t\t\ttry {\n\t\t\t\t\tconst helper = cjsRequire(modulePath) as { enableVirtualTerminalInput?: () => boolean };\n\t\t\t\t\thelper.enableVirtualTerminalInput?.();\n\t\t\t\t\treturn;\n\t\t\t\t} catch {\n\t\t\t\t\t// Try the next possible packaging location.\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Native helper not available — Shift+Tab won't be distinguishable from Tab.\n\t\t}\n\t}\n\n\tasync drainInput(maxMs = 1000, idleMs = 50): Promise<void> {\n\t\tconst shouldDisableKittyProtocol = this.keyboardProtocolPushed || this._kittyProtocolActive;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tif (shouldDisableKittyProtocol) {\n\t\t\t// Disable Kitty keyboard protocol first so any late key releases\n\t\t\t// do not generate new Kitty escape sequences.\n\t\t\tthis.rawWrite(\"\\x1b[<u\");\n\t\t\tthis.keyboardProtocolPushed = false;\n\t\t\tthis._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\n\t\tthis.disableModifyOtherKeys();\n\n\t\tconst previousHandler = this.inputHandler;\n\t\tthis.inputHandler = undefined;\n\n\t\tlet lastDataTime = Date.now();\n\t\tconst onData = () => {\n\t\t\tlastDataTime = Date.now();\n\t\t};\n\n\t\tprocess.stdin.on(\"data\", onData);\n\t\tconst endTime = Date.now() + maxMs;\n\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst now = Date.now();\n\t\t\t\tconst timeLeft = endTime - now;\n\t\t\t\tif (timeLeft <= 0) break;\n\t\t\t\tif (now - lastDataTime >= idleMs) break;\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, Math.min(idleMs, timeLeft)));\n\t\t\t}\n\t\t} finally {\n\t\t\tprocess.stdin.removeListener(\"data\", onData);\n\t\t\tthis.inputHandler = previousHandler;\n\t\t}\n\t}\n\n\tstop(): void {\n\t\tif (this.clearProgressInterval()) {\n\t\t\tthis.rawWrite(TERMINAL_PROGRESS_CLEAR_SEQUENCE);\n\t\t}\n\n\t\t// Disable bracketed paste mode\n\t\tthis.rawWrite(\"\\x1b[?2004l\");\n\n\t\tconst shouldDisableKittyProtocol = this.keyboardProtocolPushed || this._kittyProtocolActive;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\n\t\t// Disable Kitty keyboard protocol if not already done by drainInput()\n\t\tif (shouldDisableKittyProtocol) {\n\t\t\tthis.rawWrite(\"\\x1b[<u\");\n\t\t\tthis.keyboardProtocolPushed = false;\n\t\t\tthis._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\n\t\tthis.disableModifyOtherKeys();\n\n\t\t// Clean up StdinBuffer\n\t\tif (this.stdinBuffer) {\n\t\t\tthis.stdinBuffer.destroy();\n\t\t\tthis.stdinBuffer = undefined;\n\t\t}\n\n\t\t// Remove event handlers\n\t\tif (this.stdinDataHandler) {\n\t\t\tprocess.stdin.removeListener(\"data\", this.stdinDataHandler);\n\t\t\tthis.stdinDataHandler = undefined;\n\t\t}\n\t\tthis.inputHandler = undefined;\n\t\tif (this.resizeHandler) {\n\t\t\tprocess.stdout.removeListener(\"resize\", this.resizeHandler);\n\t\t\tthis.resizeHandler = undefined;\n\t\t}\n\n\t\t// Pause stdin to prevent any buffered input (e.g., Ctrl+D) from being\n\t\t// re-interpreted after raw mode is disabled. This fixes a race condition\n\t\t// where Ctrl+D could close the parent shell over SSH.\n\t\tprocess.stdin.pause();\n\n\t\t// Restore raw mode state\n\t\tif (process.stdin.setRawMode) {\n\t\t\ttry {\n\t\t\t\tprocess.stdin.setRawMode(this.wasRaw);\n\t\t\t} catch (error) {\n\t\t\t\tif (!isDeadTerminalError(error)) throw error;\n\t\t\t}\n\t\t}\n\n\t\tthis.removeExternalStdoutGuard();\n\n\t\tthis.scheduleStdinErrorHandlerCleanup();\n\t}\n\n\tprivate scheduleStdinErrorHandlerCleanup(): void {\n\t\tif (!this.stdinErrorHandler || this.stdinErrorHandlerCleanupTimer) return;\n\t\t// Keep the guard armed briefly past stop(): a late PTY failure racing\n\t\t// the exit path must not crash the process after the TUI tore down.\n\t\tconst handler = this.stdinErrorHandler;\n\t\tthis.stdinErrorHandlerCleanupTimer = setTimeout(() => {\n\t\t\tthis.stdinErrorHandlerCleanupTimer = undefined;\n\t\t\tif (this.stdinErrorHandler === handler) {\n\t\t\t\tthis.stdinErrorHandler = undefined;\n\t\t\t\tunsubscribeFromStdinErrors(handler);\n\t\t\t}\n\t\t}, STDIN_ERROR_HANDLER_GRACE_MS);\n\t\tthis.stdinErrorHandlerCleanupTimer.unref();\n\t}\n\n\twrite(data: string): void {\n\t\tthis.rawWrite(data);\n\t\tif (this.writeLogPath) {\n\t\t\ttry {\n\t\t\t\tfs.appendFileSync(this.writeLogPath, data, { encoding: \"utf8\" });\n\t\t\t} catch {\n\t\t\t\t// Ignore logging errors\n\t\t\t}\n\t\t}\n\t}\n\n\tget columns(): number {\n\t\treturn process.stdout.columns || Number(process.env.COLUMNS) || 80;\n\t}\n\n\tget rows(): number {\n\t\treturn process.stdout.rows || Number(process.env.LINES) || 24;\n\t}\n\n\tmoveBy(lines: number): void {\n\t\tif (lines > 0) {\n\t\t\t// Move down\n\t\t\tthis.rawWrite(`\\x1b[${lines}B`);\n\t\t} else if (lines < 0) {\n\t\t\t// Move up\n\t\t\tthis.rawWrite(`\\x1b[${-lines}A`);\n\t\t}\n\t\t// lines === 0: no movement\n\t}\n\n\thideCursor(): void {\n\t\tthis.rawWrite(\"\\x1b[?25l\");\n\t}\n\n\tshowCursor(): void {\n\t\tthis.rawWrite(\"\\x1b[?25h\");\n\t}\n\n\tclearLine(): void {\n\t\tthis.rawWrite(\"\\x1b[K\");\n\t}\n\n\tclearFromCursor(): void {\n\t\tthis.rawWrite(\"\\x1b[J\");\n\t}\n\n\tclearScreen(): void {\n\t\tthis.rawWrite(\"\\x1b[2J\\x1b[H\"); // Clear screen and move to home (1,1)\n\t}\n\n\tsetTitle(title: string): void {\n\t\t// OSC 0;title BEL - set terminal window title. Control characters are\n\t\t// stripped so a title cannot terminate the OSC early and leak the rest\n\t\t// onto the screen.\n\t\tconst sanitizedTitle = title.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/g, \"\");\n\t\tthis.rawWrite(`\\x1b]0;${sanitizedTitle}\\x07`);\n\t}\n\n\tsetProgress(active: boolean): void {\n\t\tif (active) {\n\t\t\t// OSC 9;4;3 - indeterminate progress\n\t\t\tthis.rawWrite(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);\n\t\t\tif (!this.progressInterval) {\n\t\t\t\tthis.progressInterval = setInterval(() => {\n\t\t\t\t\tthis.rawWrite(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);\n\t\t\t\t}, TERMINAL_PROGRESS_KEEPALIVE_MS);\n\t\t\t}\n\t\t} else {\n\t\t\tthis.clearProgressInterval();\n\t\t\t// OSC 9;4;0 - clear progress\n\t\t\tthis.rawWrite(TERMINAL_PROGRESS_CLEAR_SEQUENCE);\n\t\t}\n\t}\n\n\tprivate clearProgressInterval(): boolean {\n\t\tif (!this.progressInterval) return false;\n\t\tclearInterval(this.progressInterval);\n\t\tthis.progressInterval = undefined;\n\t\treturn true;\n\t}\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@code-yeongyu/senpi-tui",
3
- "version": "2026.8.25",
3
+ "version": "2026.8.26-2",
4
4
  "description": "Terminal User Interface library with differential rendering for efficient text-based applications",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",