export interface ProcessSignalTarget { off(signal: NodeJS.Signals, listener: () => void): unknown; on(signal: NodeJS.Signals, listener: () => void): unknown; } export interface TerminalInput { isRaw?: boolean; isTTY?: boolean; setRawMode?(enabled: boolean): unknown; } export interface TerminalOutput { isTTY?: boolean; write(value: string): unknown; } /** * Inherited child output can enable terminal-emulator interaction modes that * termios raw-mode restoration cannot observe. Disable the common mouse and * focus protocols before returning to the shell so later input stays local to * the prompt. */ export const DISABLE_TERMINAL_INTERACTIONS = [ "\u001B[?9l", "\u001B[?1000l", "\u001B[?1002l", "\u001B[?1003l", "\u001B[?1004l", "\u001B[?1005l", "\u001B[?1006l", "\u001B[?1015l", "\u001B[?1016l", ].join(""); /** * Capture only state that Node can restore portably. The returned cleanup is * idempotent because startup errors and signal propagation can converge on the * same teardown path. */ export function captureTerminalState( input: TerminalInput, output: TerminalOutput, ): () => void { const initialRawMode = input.isTTY === true && typeof input.isRaw === "boolean" && typeof input.setRawMode === "function" ? input.isRaw : null; const interactive = input.isTTY === true && output.isTTY === true; let restored = false; return () => { if (restored) return; restored = true; if (initialRawMode !== null) { try { // A child sharing this TTY can change termios without updating the // parent ReadStream's isRaw property, so always reapply the snapshot. input.setRawMode?.(initialRawMode); } catch { // A closing or detached TTY must not prevent process cleanup. } } if (interactive) { try { output.write(DISABLE_TERMINAL_INTERACTIONS); } catch { // The terminal may already be detached during shutdown. } } }; }