@greppleai/grip-tui 0.0.0-stage → 0.0.1

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.
Files changed (158) hide show
  1. package/README.md +818 -2
  2. package/dist/autocomplete.d.ts +48 -0
  3. package/dist/autocomplete.d.ts.map +1 -0
  4. package/dist/autocomplete.js +566 -0
  5. package/dist/autocomplete.js.map +1 -0
  6. package/dist/components/alt-screen-flash.d.ts +13 -0
  7. package/dist/components/alt-screen-flash.d.ts.map +1 -0
  8. package/dist/components/alt-screen-flash.js +37 -0
  9. package/dist/components/alt-screen-flash.js.map +1 -0
  10. package/dist/components/box.d.ts +22 -0
  11. package/dist/components/box.d.ts.map +1 -0
  12. package/dist/components/box.js +104 -0
  13. package/dist/components/box.js.map +1 -0
  14. package/dist/components/cancellable-loader.d.ts +22 -0
  15. package/dist/components/cancellable-loader.d.ts.map +1 -0
  16. package/dist/components/cancellable-loader.js +35 -0
  17. package/dist/components/cancellable-loader.js.map +1 -0
  18. package/dist/components/editor.d.ts +292 -0
  19. package/dist/components/editor.d.ts.map +1 -0
  20. package/dist/components/editor.js +1887 -0
  21. package/dist/components/editor.js.map +1 -0
  22. package/dist/components/h-stack.d.ts +7 -0
  23. package/dist/components/h-stack.d.ts.map +1 -0
  24. package/dist/components/h-stack.js +43 -0
  25. package/dist/components/h-stack.js.map +1 -0
  26. package/dist/components/image.d.ts +32 -0
  27. package/dist/components/image.d.ts.map +1 -0
  28. package/dist/components/image.js +76 -0
  29. package/dist/components/image.js.map +1 -0
  30. package/dist/components/input.d.ts +46 -0
  31. package/dist/components/input.d.ts.map +1 -0
  32. package/dist/components/input.js +352 -0
  33. package/dist/components/input.js.map +1 -0
  34. package/dist/components/loader.d.ts +32 -0
  35. package/dist/components/loader.d.ts.map +1 -0
  36. package/dist/components/loader.js +80 -0
  37. package/dist/components/loader.js.map +1 -0
  38. package/dist/components/markdown.d.ts +132 -0
  39. package/dist/components/markdown.d.ts.map +1 -0
  40. package/dist/components/markdown.js +717 -0
  41. package/dist/components/markdown.js.map +1 -0
  42. package/dist/components/scroll-view.d.ts +53 -0
  43. package/dist/components/scroll-view.d.ts.map +1 -0
  44. package/dist/components/scroll-view.js +173 -0
  45. package/dist/components/scroll-view.js.map +1 -0
  46. package/dist/components/select-list.d.ts +50 -0
  47. package/dist/components/select-list.d.ts.map +1 -0
  48. package/dist/components/select-list.js +159 -0
  49. package/dist/components/select-list.js.map +1 -0
  50. package/dist/components/settings-list.d.ts +52 -0
  51. package/dist/components/settings-list.d.ts.map +1 -0
  52. package/dist/components/settings-list.js +187 -0
  53. package/dist/components/settings-list.js.map +1 -0
  54. package/dist/components/spacer.d.ts +12 -0
  55. package/dist/components/spacer.d.ts.map +1 -0
  56. package/dist/components/spacer.js +23 -0
  57. package/dist/components/spacer.js.map +1 -0
  58. package/dist/components/stack.d.ts +32 -0
  59. package/dist/components/stack.d.ts.map +1 -0
  60. package/dist/components/stack.js +122 -0
  61. package/dist/components/stack.js.map +1 -0
  62. package/dist/components/text.d.ts +19 -0
  63. package/dist/components/text.d.ts.map +1 -0
  64. package/dist/components/text.js +89 -0
  65. package/dist/components/text.js.map +1 -0
  66. package/dist/components/truncated-text.d.ts +13 -0
  67. package/dist/components/truncated-text.d.ts.map +1 -0
  68. package/dist/components/truncated-text.js +51 -0
  69. package/dist/components/truncated-text.js.map +1 -0
  70. package/dist/components/v-stack.d.ts +8 -0
  71. package/dist/components/v-stack.d.ts.map +1 -0
  72. package/dist/components/v-stack.js +27 -0
  73. package/dist/components/v-stack.js.map +1 -0
  74. package/dist/editor-component.d.ts +39 -0
  75. package/dist/editor-component.d.ts.map +1 -0
  76. package/dist/editor-component.js +2 -0
  77. package/dist/editor-component.js.map +1 -0
  78. package/dist/fuzzy.d.ts +16 -0
  79. package/dist/fuzzy.d.ts.map +1 -0
  80. package/dist/fuzzy.js +101 -0
  81. package/dist/fuzzy.js.map +1 -0
  82. package/dist/index.d.ts +30 -0
  83. package/dist/index.d.ts.map +1 -0
  84. package/dist/index.js +41 -0
  85. package/dist/index.js.map +1 -0
  86. package/dist/keybindings.d.ts +243 -0
  87. package/dist/keybindings.d.ts.map +1 -0
  88. package/dist/keybindings.js +209 -0
  89. package/dist/keybindings.js.map +1 -0
  90. package/dist/keys.d.ts +184 -0
  91. package/dist/keys.d.ts.map +1 -0
  92. package/dist/keys.js +1053 -0
  93. package/dist/keys.js.map +1 -0
  94. package/dist/kill-ring.d.ts +30 -0
  95. package/dist/kill-ring.d.ts.map +1 -0
  96. package/dist/kill-ring.js +37 -0
  97. package/dist/kill-ring.js.map +1 -0
  98. package/dist/latex.d.ts +10 -0
  99. package/dist/latex.d.ts.map +1 -0
  100. package/dist/latex.js +1406 -0
  101. package/dist/latex.js.map +1 -0
  102. package/dist/layout-node.d.ts +43 -0
  103. package/dist/layout-node.d.ts.map +1 -0
  104. package/dist/layout-node.js +6 -0
  105. package/dist/layout-node.js.map +1 -0
  106. package/dist/layout.d.ts +40 -0
  107. package/dist/layout.d.ts.map +1 -0
  108. package/dist/layout.js +386 -0
  109. package/dist/layout.js.map +1 -0
  110. package/dist/native-modifiers.d.ts +3 -0
  111. package/dist/native-modifiers.d.ts.map +1 -0
  112. package/dist/native-modifiers.js +53 -0
  113. package/dist/native-modifiers.js.map +1 -0
  114. package/dist/stdin-buffer.d.ts +58 -0
  115. package/dist/stdin-buffer.d.ts.map +1 -0
  116. package/dist/stdin-buffer.js +318 -0
  117. package/dist/stdin-buffer.js.map +1 -0
  118. package/dist/terminal-control.d.ts +5 -0
  119. package/dist/terminal-control.d.ts.map +1 -0
  120. package/dist/terminal-control.js +26 -0
  121. package/dist/terminal-control.js.map +1 -0
  122. package/dist/terminal-image.d.ts +112 -0
  123. package/dist/terminal-image.d.ts.map +1 -0
  124. package/dist/terminal-image.js +508 -0
  125. package/dist/terminal-image.js.map +1 -0
  126. package/dist/terminal.d.ts +117 -0
  127. package/dist/terminal.d.ts.map +1 -0
  128. package/dist/terminal.js +490 -0
  129. package/dist/terminal.js.map +1 -0
  130. package/dist/tui-alt-screen.d.ts +114 -0
  131. package/dist/tui-alt-screen.d.ts.map +1 -0
  132. package/dist/tui-alt-screen.js +950 -0
  133. package/dist/tui-alt-screen.js.map +1 -0
  134. package/dist/tui-main-screen.d.ts +52 -0
  135. package/dist/tui-main-screen.d.ts.map +1 -0
  136. package/dist/tui-main-screen.js +511 -0
  137. package/dist/tui-main-screen.js.map +1 -0
  138. package/dist/tui.d.ts +295 -0
  139. package/dist/tui.d.ts.map +1 -0
  140. package/dist/tui.js +868 -0
  141. package/dist/tui.js.map +1 -0
  142. package/dist/undo-stack.d.ts +17 -0
  143. package/dist/undo-stack.d.ts.map +1 -0
  144. package/dist/undo-stack.js +25 -0
  145. package/dist/undo-stack.js.map +1 -0
  146. package/dist/utils.d.ts +96 -0
  147. package/dist/utils.d.ts.map +1 -0
  148. package/dist/utils.js +1106 -0
  149. package/dist/utils.js.map +1 -0
  150. package/dist/word-navigation.d.ts +25 -0
  151. package/dist/word-navigation.d.ts.map +1 -0
  152. package/dist/word-navigation.js +94 -0
  153. package/dist/word-navigation.js.map +1 -0
  154. package/native/darwin/prebuilds/darwin-arm64/darwin-modifiers.node +0 -0
  155. package/native/darwin/prebuilds/darwin-x64/darwin-modifiers.node +0 -0
  156. package/native/win32/prebuilds/win32-arm64/win32-console-mode.node +0 -0
  157. package/native/win32/prebuilds/win32-x64/win32-console-mode.node +0 -0
  158. package/package.json +47 -5
@@ -0,0 +1,117 @@
1
+ export type KeyboardProtocolNegotiationSequence = {
2
+ type: "kitty-flags";
3
+ flags: number;
4
+ } | {
5
+ type: "device-attributes";
6
+ };
7
+ export declare function parseKeyboardProtocolNegotiationSequence(sequence: string): KeyboardProtocolNegotiationSequence | undefined;
8
+ export declare function isAppleTerminalSession(): boolean;
9
+ export declare function normalizeAppleTerminalInput(data: string, isAppleTerminal: boolean, isShiftPressed: boolean): string;
10
+ /**
11
+ * Minimal terminal interface for TUI
12
+ */
13
+ export interface Terminal {
14
+ start(onInput: (data: string) => void, onResize: () => void): void;
15
+ stop(): void;
16
+ /**
17
+ * Drain stdin before exiting to prevent Kitty key release events from
18
+ * leaking to the parent shell over slow SSH connections.
19
+ * @param maxMs - Maximum time to drain (default: 1000ms)
20
+ * @param idleMs - Exit early if no input arrives within this time (default: 50ms)
21
+ */
22
+ drainInput(maxMs?: number, idleMs?: number): Promise<void>;
23
+ write(data: string): void;
24
+ get columns(): number;
25
+ get rows(): number;
26
+ get kittyProtocolActive(): boolean;
27
+ moveBy(lines: number): void;
28
+ hideCursor(): void;
29
+ showCursor(): void;
30
+ clearLine(): void;
31
+ clearFromCursor(): void;
32
+ clearScreen(): void;
33
+ setTitle(title: string): void;
34
+ setProgress(active: boolean): void;
35
+ }
36
+ /**
37
+ * Real terminal using process.stdin/stdout
38
+ */
39
+ export declare class ProcessTerminal implements Terminal {
40
+ private wasRaw;
41
+ private started;
42
+ private inputHandler?;
43
+ private resizeHandler?;
44
+ private _kittyProtocolActive;
45
+ private _modifyOtherKeysActive;
46
+ private keyboardProtocolPushed;
47
+ private keyboardProtocolNegotiationPending;
48
+ private keyboardProtocolLateResponsePending;
49
+ private keyboardProtocolNegotiationBuffer;
50
+ private keyboardProtocolFallbackTimer?;
51
+ private keyboardProtocolBufferFlushTimer?;
52
+ private stdinBuffer?;
53
+ private stdinDataHandler?;
54
+ private progressInterval?;
55
+ private writeLogPath;
56
+ get kittyProtocolActive(): boolean;
57
+ start(onInput: (data: string) => void, onResize: () => void): void;
58
+ private handleInitialKeyboardProtocolInput;
59
+ private handleLateKeyboardProtocolInput;
60
+ private handleBufferedInputSequence;
61
+ /**
62
+ * Set up StdinBuffer to split batched input into individual sequences.
63
+ * This ensures components receive single events, making matchesKey/isKeyRelease work correctly.
64
+ *
65
+ * Also watches for Kitty protocol response and enables it when detected.
66
+ * This is done here (after stdinBuffer parsing) rather than on raw stdin
67
+ * to handle the case where the response arrives split across multiple events.
68
+ */
69
+ private setupStdinBuffer;
70
+ /**
71
+ * Query terminal for Kitty keyboard protocol support and enable it if available.
72
+ *
73
+ * Kitty's progressive enhancement detection requires requesting the desired
74
+ * flags before querying them. The trailing DA query is a sentinel supported by
75
+ * terminals that do not know Kitty keyboard protocol. A short timeout remains
76
+ * as a backup for terminals, PTYs, and SSH sessions that delay, split, or drop
77
+ * the DA response.
78
+ *
79
+ * The requested flags are:
80
+ * - 1 = disambiguate escape codes
81
+ * - 2 = report event types (press/repeat/release)
82
+ * - 4 = report alternate keys (shifted key, base layout key)
83
+ */
84
+ private queryAndEnableKittyProtocol;
85
+ private handleKeyboardProtocolNegotiationSequence;
86
+ private readKeyboardProtocolNegotiationSequence;
87
+ private setKeyboardProtocolNegotiationBuffer;
88
+ private clearKeyboardProtocolNegotiationBuffer;
89
+ private flushKeyboardProtocolNegotiationBufferAsInput;
90
+ private scheduleKeyboardProtocolNegotiationBufferFlush;
91
+ private clearKeyboardProtocolNegotiationBufferFlushTimer;
92
+ private forwardInputSequence;
93
+ private enableModifyOtherKeys;
94
+ private clearKeyboardProtocolFallbackTimer;
95
+ /**
96
+ * On Windows, add ENABLE_VIRTUAL_TERMINAL_INPUT (0x0200) to the stdin
97
+ * console handle so the terminal sends VT sequences for modified keys
98
+ * (e.g. \x1b[Z for Shift+Tab). Without this, libuv's ReadConsoleInputW
99
+ * discards modifier state and Shift+Tab arrives as plain \t.
100
+ */
101
+ private enableWindowsVTInput;
102
+ drainInput(maxMs?: number, idleMs?: number): Promise<void>;
103
+ stop(): void;
104
+ write(data: string): void;
105
+ get columns(): number;
106
+ get rows(): number;
107
+ moveBy(lines: number): void;
108
+ hideCursor(): void;
109
+ showCursor(): void;
110
+ clearLine(): void;
111
+ clearFromCursor(): void;
112
+ clearScreen(): void;
113
+ setTitle(title: string): void;
114
+ setProgress(active: boolean): void;
115
+ private clearProgressInterval;
116
+ }
117
+ //# sourceMappingURL=terminal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"terminal.d.ts","sourceRoot":"","sources":["../src/terminal.ts"],"names":[],"mappings":"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","sourcesContent":["import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { setKittyProtocolActive } from \"./keys.ts\";\nimport { isNativeModifierPressed } from \"./native-modifiers.ts\";\nimport { StdinBuffer } from \"./stdin-buffer.ts\";\nimport { sanitizeTerminalControlPayload } from \"./terminal-control.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 APPLE_TERMINAL_SHIFT_ENTER_SEQUENCE = \"\\x1b[13;2u\";\nconst DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS = 7;\nconst KITTY_KEYBOARD_PROTOCOL_FALLBACK_TIMEOUT_MS = 150;\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, allowBareEscapePrefix: boolean): boolean {\n\treturn (allowBareEscapePrefix && sequence === \"\\x1b\") || 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 normalizeAppleTerminalInput(data: string, isAppleTerminal: boolean, isShiftPressed: boolean): string {\n\tif (isAppleTerminal && data === \"\\r\" && isShiftPressed) return APPLE_TERMINAL_SHIFT_ENTER_SEQUENCE;\n\treturn data;\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\n/**\n * Real terminal using process.stdin/stdout\n */\nexport class ProcessTerminal implements Terminal {\n\tprivate wasRaw = false;\n\tprivate started = 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 keyboardProtocolNegotiationPending = false;\n\tprivate keyboardProtocolLateResponsePending = false;\n\tprivate keyboardProtocolNegotiationBuffer = \"\";\n\tprivate keyboardProtocolFallbackTimer?: ReturnType<typeof setTimeout>;\n\tprivate keyboardProtocolBufferFlushTimer?: ReturnType<typeof setTimeout>;\n\tprivate stdinBuffer?: StdinBuffer;\n\tprivate stdinDataHandler?: (data: string) => void;\n\tprivate progressInterval?: ReturnType<typeof setInterval>;\n\tprivate writeLogPath = (() => {\n\t\tconst env = process.env.GRIP_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\tget kittyProtocolActive(): boolean {\n\t\treturn this._kittyProtocolActive;\n\t}\n\n\tstart(onInput: (data: string) => void, onResize: () => void): void {\n\t\tif (this.started) {\n\t\t\tthis.inputHandler = onInput;\n\t\t\tif (this.resizeHandler !== onResize) {\n\t\t\t\tif (this.resizeHandler) process.stdout.removeListener(\"resize\", this.resizeHandler);\n\t\t\t\tthis.resizeHandler = onResize;\n\t\t\t\tprocess.stdout.on(\"resize\", onResize);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tthis.started = true;\n\t\tthis.inputHandler = onInput;\n\t\tthis.resizeHandler = onResize;\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.setEncoding(\"utf8\");\n\t\tprocess.stdin.resume();\n\n\t\t// Enable bracketed paste mode - terminal will wrap pastes in \\x1b[200~ ... \\x1b[201~\n\t\tprocess.stdout.write(\"\\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 and enable Kitty keyboard protocol\n\t\t// The query handler intercepts input temporarily, then installs the user's handler\n\t\t// See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/\n\t\tthis.queryAndEnableKittyProtocol();\n\t}\n\n\tprivate handleInitialKeyboardProtocolInput(sequence: string): boolean {\n\t\tif (!this.keyboardProtocolNegotiationPending) return false;\n\t\tconst negotiationSequence = this.readKeyboardProtocolNegotiationSequence(sequence, true);\n\t\tif (negotiationSequence === \"pending\") return true;\n\t\treturn this.handleKeyboardProtocolNegotiationSequence(negotiationSequence);\n\t}\n\n\tprivate handleLateKeyboardProtocolInput(sequence: string): boolean {\n\t\tif (!this.keyboardProtocolLateResponsePending) return false;\n\t\tconst negotiationSequence = this.readKeyboardProtocolNegotiationSequence(sequence, false);\n\t\tif (negotiationSequence === \"pending\") {\n\t\t\tthis.scheduleKeyboardProtocolNegotiationBufferFlush();\n\t\t\treturn true;\n\t\t}\n\t\treturn this.handleKeyboardProtocolNegotiationSequence(negotiationSequence);\n\t}\n\n\tprivate handleBufferedInputSequence(sequence: string): void {\n\t\tif (this.handleInitialKeyboardProtocolInput(sequence)) return;\n\t\tif (this.handleLateKeyboardProtocolInput(sequence)) return;\n\t\tthis.forwardInputSequence(sequence);\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({ timeout: 10 });\n\n\t\t// Forward individual sequences to the input handler\n\t\tthis.stdinBuffer.on(\"data\", (sequence) => this.handleBufferedInputSequence(sequence));\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) => {\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. A short timeout remains\n\t * as a backup for terminals, PTYs, and SSH sessions that delay, split, or drop\n\t * the DA response.\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\tthis.keyboardProtocolPushed = true;\n\t\tthis.keyboardProtocolNegotiationPending = true;\n\t\tthis.keyboardProtocolLateResponsePending = false;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tprocess.stdout.write(KITTY_KEYBOARD_PROTOCOL_QUERY);\n\t\tthis.keyboardProtocolFallbackTimer = setTimeout(() => {\n\t\t\tthis.keyboardProtocolFallbackTimer = undefined;\n\t\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\t\tthis.keyboardProtocolLateResponsePending = true;\n\t\t\tif (this.keyboardProtocolNegotiationBuffer === \"\\x1b\") {\n\t\t\t\tthis.flushKeyboardProtocolNegotiationBufferAsInput();\n\t\t\t} else {\n\t\t\t\tthis.scheduleKeyboardProtocolNegotiationBufferFlush();\n\t\t\t}\n\t\t\tthis.enableModifyOtherKeys();\n\t\t}, KITTY_KEYBOARD_PROTOCOL_FALLBACK_TIMEOUT_MS);\n\t}\n\n\tprivate handleKeyboardProtocolNegotiationSequence(\n\t\tnegotiationSequence: KeyboardProtocolNegotiationSequence | undefined,\n\t): boolean {\n\t\tif (!negotiationSequence) return false;\n\t\tif (negotiationSequence.type === \"kitty-flags\") {\n\t\t\tif (negotiationSequence.flags !== 0 && !this._kittyProtocolActive) {\n\t\t\t\tthis._kittyProtocolActive = true;\n\t\t\t\tsetKittyProtocolActive(true);\n\t\t\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\t\t\tthis.keyboardProtocolLateResponsePending = true;\n\t\t\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\t\t\tthis.clearKeyboardProtocolFallbackTimer();\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\tthis.keyboardProtocolLateResponsePending = true;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.clearKeyboardProtocolFallbackTimer();\n\t\tthis.enableModifyOtherKeys();\n\t\treturn true;\n\t}\n\n\tprivate readKeyboardProtocolNegotiationSequence(\n\t\tsequence: string,\n\t\tallowBareEscapePrefix: boolean,\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, allowBareEscapePrefix)) {\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, allowBareEscapePrefix)) {\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 isAppleTerminal = sequence === \"\\r\" && isAppleTerminalSession();\n\t\tconst input = normalizeAppleTerminalInput(\n\t\t\tsequence,\n\t\t\tisAppleTerminal,\n\t\t\tisAppleTerminal && 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\tprocess.stdout.write(\"\\x1b[>4;2m\");\n\t\tthis._modifyOtherKeysActive = true;\n\t}\n\n\tprivate clearKeyboardProtocolFallbackTimer(): void {\n\t\tif (!this.keyboardProtocolFallbackTimer) return;\n\t\tclearTimeout(this.keyboardProtocolFallbackTimer);\n\t\tthis.keyboardProtocolFallbackTimer = undefined;\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. In the npm package native/ is next to dist/; in compiled\n\t\t\t// binary archives native/ is copied next to the executable.\n\t\t\tconst moduleDir = path.dirname(fileURLToPath(import.meta.url));\n\t\t\tconst nativePath = path.join(\"native\", \"win32\", \"prebuilds\", `win32-${arch}`, \"win32-console-mode.node\");\n\t\t\tconst candidates = [\n\t\t\t\tpath.join(moduleDir, \"..\", nativePath),\n\t\t\t\tpath.join(moduleDir, nativePath),\n\t\t\t\tpath.join(path.dirname(process.execPath), nativePath),\n\t\t\t];\n\t\t\tfor (const modulePath of candidates) {\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 =\n\t\t\tthis.keyboardProtocolPushed || this._kittyProtocolActive || this.keyboardProtocolNegotiationPending;\n\t\tthis.keyboardProtocolLateResponsePending = false;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.clearKeyboardProtocolFallbackTimer();\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\tprocess.stdout.write(\"\\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.keyboardProtocolNegotiationPending = false;\n\t\tif (this._modifyOtherKeysActive) {\n\t\t\tprocess.stdout.write(\"\\x1b[>4;0m\");\n\t\t\tthis._modifyOtherKeysActive = false;\n\t\t}\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\tthis.started = false;\n\t\tif (this.clearProgressInterval()) {\n\t\t\tprocess.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);\n\t\t}\n\n\t\t// Disable bracketed paste mode\n\t\tprocess.stdout.write(\"\\x1b[?2004l\");\n\n\t\tconst shouldDisableKittyProtocol =\n\t\t\tthis.keyboardProtocolPushed || this._kittyProtocolActive || this.keyboardProtocolNegotiationPending;\n\t\tthis.keyboardProtocolLateResponsePending = false;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.clearKeyboardProtocolFallbackTimer();\n\n\t\t// Disable Kitty keyboard protocol if not already done by drainInput()\n\t\tif (shouldDisableKittyProtocol) {\n\t\t\tprocess.stdout.write(\"\\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.keyboardProtocolNegotiationPending = false;\n\t\tif (this._modifyOtherKeysActive) {\n\t\t\tprocess.stdout.write(\"\\x1b[>4;0m\");\n\t\t\tthis._modifyOtherKeysActive = false;\n\t\t}\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\tprocess.stdin.setRawMode(this.wasRaw);\n\t\t}\n\t}\n\n\twrite(data: string): void {\n\t\tprocess.stdout.write(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\tprocess.stdout.write(`\\x1b[${lines}B`);\n\t\t} else if (lines < 0) {\n\t\t\t// Move up\n\t\t\tprocess.stdout.write(`\\x1b[${-lines}A`);\n\t\t}\n\t\t// lines === 0: no movement\n\t}\n\n\thideCursor(): void {\n\t\tprocess.stdout.write(\"\\x1b[?25l\");\n\t}\n\n\tshowCursor(): void {\n\t\tprocess.stdout.write(\"\\x1b[?25h\");\n\t}\n\n\tclearLine(): void {\n\t\tprocess.stdout.write(\"\\x1b[K\");\n\t}\n\n\tclearFromCursor(): void {\n\t\tprocess.stdout.write(\"\\x1b[J\");\n\t}\n\n\tclearScreen(): void {\n\t\tprocess.stdout.write(\"\\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\n\t\tprocess.stdout.write(`\\x1b]0;${sanitizeTerminalControlPayload(title)}\\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\tprocess.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);\n\t\t\tif (!this.progressInterval) {\n\t\t\t\tthis.progressInterval = setInterval(() => {\n\t\t\t\t\tprocess.stdout.write(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\tprocess.stdout.write(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"]}
@@ -0,0 +1,490 @@
1
+ import * as fs from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import * as path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { setKittyProtocolActive } from "./keys.js";
6
+ import { isNativeModifierPressed } from "./native-modifiers.js";
7
+ import { StdinBuffer } from "./stdin-buffer.js";
8
+ import { sanitizeTerminalControlPayload } from "./terminal-control.js";
9
+ const cjsRequire = createRequire(import.meta.url);
10
+ const TERMINAL_PROGRESS_KEEPALIVE_MS = 1000;
11
+ const TERMINAL_PROGRESS_ACTIVE_SEQUENCE = "\x1b]9;4;3\x07";
12
+ const TERMINAL_PROGRESS_CLEAR_SEQUENCE = "\x1b]9;4;0\x07";
13
+ const APPLE_TERMINAL_SHIFT_ENTER_SEQUENCE = "\x1b[13;2u";
14
+ const DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS = 7;
15
+ const KITTY_KEYBOARD_PROTOCOL_FALLBACK_TIMEOUT_MS = 150;
16
+ const KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS = 150;
17
+ const KITTY_KEYBOARD_PROTOCOL_QUERY = `\x1b[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1b[?u\x1b[c`;
18
+ export function parseKeyboardProtocolNegotiationSequence(sequence) {
19
+ const kittyFlags = sequence.match(/^\x1b\[\?(\d+)u$/);
20
+ if (kittyFlags) {
21
+ return { type: "kitty-flags", flags: Number.parseInt(kittyFlags[1], 10) };
22
+ }
23
+ if (/^\x1b\[\?[\d;]*c$/.test(sequence)) {
24
+ return { type: "device-attributes" };
25
+ }
26
+ return undefined;
27
+ }
28
+ function isKeyboardProtocolNegotiationSequencePrefix(sequence, allowBareEscapePrefix) {
29
+ return (allowBareEscapePrefix && sequence === "\x1b") || sequence === "\x1b[" || /^\x1b\[\?[\d;]*$/.test(sequence);
30
+ }
31
+ export function isAppleTerminalSession() {
32
+ return process.platform === "darwin" && process.env.TERM_PROGRAM === "Apple_Terminal";
33
+ }
34
+ export function normalizeAppleTerminalInput(data, isAppleTerminal, isShiftPressed) {
35
+ if (isAppleTerminal && data === "\r" && isShiftPressed)
36
+ return APPLE_TERMINAL_SHIFT_ENTER_SEQUENCE;
37
+ return data;
38
+ }
39
+ /**
40
+ * Real terminal using process.stdin/stdout
41
+ */
42
+ export class ProcessTerminal {
43
+ wasRaw = false;
44
+ started = false;
45
+ inputHandler;
46
+ resizeHandler;
47
+ _kittyProtocolActive = false;
48
+ _modifyOtherKeysActive = false;
49
+ keyboardProtocolPushed = false;
50
+ keyboardProtocolNegotiationPending = false;
51
+ keyboardProtocolLateResponsePending = false;
52
+ keyboardProtocolNegotiationBuffer = "";
53
+ keyboardProtocolFallbackTimer;
54
+ keyboardProtocolBufferFlushTimer;
55
+ stdinBuffer;
56
+ stdinDataHandler;
57
+ progressInterval;
58
+ writeLogPath = (() => {
59
+ const env = process.env.GRIP_TUI_WRITE_LOG || "";
60
+ if (!env)
61
+ return "";
62
+ try {
63
+ if (fs.statSync(env).isDirectory()) {
64
+ const now = new Date();
65
+ const 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")}`;
66
+ return path.join(env, `tui-${ts}-${process.pid}.log`);
67
+ }
68
+ }
69
+ catch {
70
+ // Not an existing directory - use as-is (file path)
71
+ }
72
+ return env;
73
+ })();
74
+ get kittyProtocolActive() {
75
+ return this._kittyProtocolActive;
76
+ }
77
+ start(onInput, onResize) {
78
+ if (this.started) {
79
+ this.inputHandler = onInput;
80
+ if (this.resizeHandler !== onResize) {
81
+ if (this.resizeHandler)
82
+ process.stdout.removeListener("resize", this.resizeHandler);
83
+ this.resizeHandler = onResize;
84
+ process.stdout.on("resize", onResize);
85
+ }
86
+ return;
87
+ }
88
+ this.started = true;
89
+ this.inputHandler = onInput;
90
+ this.resizeHandler = onResize;
91
+ // Save previous state and enable raw mode
92
+ this.wasRaw = process.stdin.isRaw || false;
93
+ if (process.stdin.setRawMode) {
94
+ process.stdin.setRawMode(true);
95
+ }
96
+ process.stdin.setEncoding("utf8");
97
+ process.stdin.resume();
98
+ // Enable bracketed paste mode - terminal will wrap pastes in \x1b[200~ ... \x1b[201~
99
+ process.stdout.write("\x1b[?2004h");
100
+ // Set up resize handler immediately
101
+ process.stdout.on("resize", this.resizeHandler);
102
+ // Refresh terminal dimensions - they may be stale after suspend/resume
103
+ // (SIGWINCH is lost while process is stopped). Unix only.
104
+ if (process.platform !== "win32") {
105
+ process.kill(process.pid, "SIGWINCH");
106
+ }
107
+ // On Windows, enable ENABLE_VIRTUAL_TERMINAL_INPUT so the console sends
108
+ // VT escape sequences (e.g. \x1b[Z for Shift+Tab) instead of raw console
109
+ // events that lose modifier information. Must run AFTER setRawMode(true)
110
+ // since that resets console mode flags.
111
+ this.enableWindowsVTInput();
112
+ // Query and enable Kitty keyboard protocol
113
+ // The query handler intercepts input temporarily, then installs the user's handler
114
+ // See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/
115
+ this.queryAndEnableKittyProtocol();
116
+ }
117
+ handleInitialKeyboardProtocolInput(sequence) {
118
+ if (!this.keyboardProtocolNegotiationPending)
119
+ return false;
120
+ const negotiationSequence = this.readKeyboardProtocolNegotiationSequence(sequence, true);
121
+ if (negotiationSequence === "pending")
122
+ return true;
123
+ return this.handleKeyboardProtocolNegotiationSequence(negotiationSequence);
124
+ }
125
+ handleLateKeyboardProtocolInput(sequence) {
126
+ if (!this.keyboardProtocolLateResponsePending)
127
+ return false;
128
+ const negotiationSequence = this.readKeyboardProtocolNegotiationSequence(sequence, false);
129
+ if (negotiationSequence === "pending") {
130
+ this.scheduleKeyboardProtocolNegotiationBufferFlush();
131
+ return true;
132
+ }
133
+ return this.handleKeyboardProtocolNegotiationSequence(negotiationSequence);
134
+ }
135
+ handleBufferedInputSequence(sequence) {
136
+ if (this.handleInitialKeyboardProtocolInput(sequence))
137
+ return;
138
+ if (this.handleLateKeyboardProtocolInput(sequence))
139
+ return;
140
+ this.forwardInputSequence(sequence);
141
+ }
142
+ /**
143
+ * Set up StdinBuffer to split batched input into individual sequences.
144
+ * This ensures components receive single events, making matchesKey/isKeyRelease work correctly.
145
+ *
146
+ * Also watches for Kitty protocol response and enables it when detected.
147
+ * This is done here (after stdinBuffer parsing) rather than on raw stdin
148
+ * to handle the case where the response arrives split across multiple events.
149
+ */
150
+ setupStdinBuffer() {
151
+ this.stdinBuffer = new StdinBuffer({ timeout: 10 });
152
+ // Forward individual sequences to the input handler
153
+ this.stdinBuffer.on("data", (sequence) => this.handleBufferedInputSequence(sequence));
154
+ // Re-wrap paste content with bracketed paste markers for existing editor handling
155
+ this.stdinBuffer.on("paste", (content) => {
156
+ if (this.inputHandler) {
157
+ this.inputHandler(`\x1b[200~${content}\x1b[201~`);
158
+ }
159
+ });
160
+ // Handler that pipes stdin data through the buffer
161
+ this.stdinDataHandler = (data) => {
162
+ this.stdinBuffer.process(data);
163
+ };
164
+ }
165
+ /**
166
+ * Query terminal for Kitty keyboard protocol support and enable it if available.
167
+ *
168
+ * Kitty's progressive enhancement detection requires requesting the desired
169
+ * flags before querying them. The trailing DA query is a sentinel supported by
170
+ * terminals that do not know Kitty keyboard protocol. A short timeout remains
171
+ * as a backup for terminals, PTYs, and SSH sessions that delay, split, or drop
172
+ * the DA response.
173
+ *
174
+ * The requested flags are:
175
+ * - 1 = disambiguate escape codes
176
+ * - 2 = report event types (press/repeat/release)
177
+ * - 4 = report alternate keys (shifted key, base layout key)
178
+ */
179
+ queryAndEnableKittyProtocol() {
180
+ this.setupStdinBuffer();
181
+ process.stdin.on("data", this.stdinDataHandler);
182
+ this.keyboardProtocolPushed = true;
183
+ this.keyboardProtocolNegotiationPending = true;
184
+ this.keyboardProtocolLateResponsePending = false;
185
+ this.clearKeyboardProtocolNegotiationBuffer();
186
+ process.stdout.write(KITTY_KEYBOARD_PROTOCOL_QUERY);
187
+ this.keyboardProtocolFallbackTimer = setTimeout(() => {
188
+ this.keyboardProtocolFallbackTimer = undefined;
189
+ this.keyboardProtocolNegotiationPending = false;
190
+ this.keyboardProtocolLateResponsePending = true;
191
+ if (this.keyboardProtocolNegotiationBuffer === "\x1b") {
192
+ this.flushKeyboardProtocolNegotiationBufferAsInput();
193
+ }
194
+ else {
195
+ this.scheduleKeyboardProtocolNegotiationBufferFlush();
196
+ }
197
+ this.enableModifyOtherKeys();
198
+ }, KITTY_KEYBOARD_PROTOCOL_FALLBACK_TIMEOUT_MS);
199
+ }
200
+ handleKeyboardProtocolNegotiationSequence(negotiationSequence) {
201
+ if (!negotiationSequence)
202
+ return false;
203
+ if (negotiationSequence.type === "kitty-flags") {
204
+ if (negotiationSequence.flags !== 0 && !this._kittyProtocolActive) {
205
+ this._kittyProtocolActive = true;
206
+ setKittyProtocolActive(true);
207
+ this.keyboardProtocolNegotiationPending = false;
208
+ this.keyboardProtocolLateResponsePending = true;
209
+ this.clearKeyboardProtocolNegotiationBuffer();
210
+ this.clearKeyboardProtocolFallbackTimer();
211
+ }
212
+ return true;
213
+ }
214
+ this.keyboardProtocolNegotiationPending = false;
215
+ this.keyboardProtocolLateResponsePending = true;
216
+ this.clearKeyboardProtocolNegotiationBuffer();
217
+ this.clearKeyboardProtocolFallbackTimer();
218
+ this.enableModifyOtherKeys();
219
+ return true;
220
+ }
221
+ readKeyboardProtocolNegotiationSequence(sequence, allowBareEscapePrefix) {
222
+ if (this.keyboardProtocolNegotiationBuffer) {
223
+ const bufferedSequence = this.keyboardProtocolNegotiationBuffer + sequence;
224
+ const negotiationSequence = parseKeyboardProtocolNegotiationSequence(bufferedSequence);
225
+ if (negotiationSequence) {
226
+ this.clearKeyboardProtocolNegotiationBuffer();
227
+ return negotiationSequence;
228
+ }
229
+ if (isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence, allowBareEscapePrefix)) {
230
+ this.setKeyboardProtocolNegotiationBuffer(bufferedSequence);
231
+ return "pending";
232
+ }
233
+ this.flushKeyboardProtocolNegotiationBufferAsInput();
234
+ }
235
+ const negotiationSequence = parseKeyboardProtocolNegotiationSequence(sequence);
236
+ if (negotiationSequence)
237
+ return negotiationSequence;
238
+ if (isKeyboardProtocolNegotiationSequencePrefix(sequence, allowBareEscapePrefix)) {
239
+ this.setKeyboardProtocolNegotiationBuffer(sequence);
240
+ return "pending";
241
+ }
242
+ return undefined;
243
+ }
244
+ setKeyboardProtocolNegotiationBuffer(sequence) {
245
+ this.clearKeyboardProtocolNegotiationBufferFlushTimer();
246
+ this.keyboardProtocolNegotiationBuffer = sequence;
247
+ }
248
+ clearKeyboardProtocolNegotiationBuffer() {
249
+ this.clearKeyboardProtocolNegotiationBufferFlushTimer();
250
+ this.keyboardProtocolNegotiationBuffer = "";
251
+ }
252
+ flushKeyboardProtocolNegotiationBufferAsInput() {
253
+ if (!this.keyboardProtocolNegotiationBuffer)
254
+ return;
255
+ const sequence = this.keyboardProtocolNegotiationBuffer;
256
+ this.clearKeyboardProtocolNegotiationBuffer();
257
+ this.forwardInputSequence(sequence);
258
+ }
259
+ scheduleKeyboardProtocolNegotiationBufferFlush() {
260
+ if (!this.keyboardProtocolNegotiationBuffer || this.keyboardProtocolBufferFlushTimer)
261
+ return;
262
+ this.keyboardProtocolBufferFlushTimer = setTimeout(() => {
263
+ this.keyboardProtocolBufferFlushTimer = undefined;
264
+ this.flushKeyboardProtocolNegotiationBufferAsInput();
265
+ }, KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS);
266
+ }
267
+ clearKeyboardProtocolNegotiationBufferFlushTimer() {
268
+ if (!this.keyboardProtocolBufferFlushTimer)
269
+ return;
270
+ clearTimeout(this.keyboardProtocolBufferFlushTimer);
271
+ this.keyboardProtocolBufferFlushTimer = undefined;
272
+ }
273
+ forwardInputSequence(sequence) {
274
+ if (!this.inputHandler)
275
+ return;
276
+ const isAppleTerminal = sequence === "\r" && isAppleTerminalSession();
277
+ const input = normalizeAppleTerminalInput(sequence, isAppleTerminal, isAppleTerminal && isNativeModifierPressed("shift"));
278
+ this.inputHandler(input);
279
+ }
280
+ enableModifyOtherKeys() {
281
+ if (this._kittyProtocolActive || this._modifyOtherKeysActive)
282
+ return;
283
+ process.stdout.write("\x1b[>4;2m");
284
+ this._modifyOtherKeysActive = true;
285
+ }
286
+ clearKeyboardProtocolFallbackTimer() {
287
+ if (!this.keyboardProtocolFallbackTimer)
288
+ return;
289
+ clearTimeout(this.keyboardProtocolFallbackTimer);
290
+ this.keyboardProtocolFallbackTimer = undefined;
291
+ }
292
+ /**
293
+ * On Windows, add ENABLE_VIRTUAL_TERMINAL_INPUT (0x0200) to the stdin
294
+ * console handle so the terminal sends VT sequences for modified keys
295
+ * (e.g. \x1b[Z for Shift+Tab). Without this, libuv's ReadConsoleInputW
296
+ * discards modifier state and Shift+Tab arrives as plain \t.
297
+ */
298
+ enableWindowsVTInput() {
299
+ if (process.platform !== "win32")
300
+ return;
301
+ try {
302
+ const arch = process.arch;
303
+ if (arch !== "x64" && arch !== "arm64")
304
+ return;
305
+ // Dynamic require so non-Windows and bundled/browser paths never load the
306
+ // native helper. In the npm package native/ is next to dist/; in compiled
307
+ // binary archives native/ is copied next to the executable.
308
+ const moduleDir = path.dirname(fileURLToPath(import.meta.url));
309
+ const nativePath = path.join("native", "win32", "prebuilds", `win32-${arch}`, "win32-console-mode.node");
310
+ const candidates = [
311
+ path.join(moduleDir, "..", nativePath),
312
+ path.join(moduleDir, nativePath),
313
+ path.join(path.dirname(process.execPath), nativePath),
314
+ ];
315
+ for (const modulePath of candidates) {
316
+ try {
317
+ const helper = cjsRequire(modulePath);
318
+ helper.enableVirtualTerminalInput?.();
319
+ return;
320
+ }
321
+ catch {
322
+ // Try the next possible packaging location.
323
+ }
324
+ }
325
+ }
326
+ catch {
327
+ // Native helper not available — Shift+Tab won't be distinguishable from Tab.
328
+ }
329
+ }
330
+ async drainInput(maxMs = 1000, idleMs = 50) {
331
+ const shouldDisableKittyProtocol = this.keyboardProtocolPushed || this._kittyProtocolActive || this.keyboardProtocolNegotiationPending;
332
+ this.keyboardProtocolLateResponsePending = false;
333
+ this.clearKeyboardProtocolNegotiationBuffer();
334
+ this.clearKeyboardProtocolFallbackTimer();
335
+ if (shouldDisableKittyProtocol) {
336
+ // Disable Kitty keyboard protocol first so any late key releases
337
+ // do not generate new Kitty escape sequences.
338
+ process.stdout.write("\x1b[<u");
339
+ this.keyboardProtocolPushed = false;
340
+ this._kittyProtocolActive = false;
341
+ setKittyProtocolActive(false);
342
+ }
343
+ this.keyboardProtocolNegotiationPending = false;
344
+ if (this._modifyOtherKeysActive) {
345
+ process.stdout.write("\x1b[>4;0m");
346
+ this._modifyOtherKeysActive = false;
347
+ }
348
+ const previousHandler = this.inputHandler;
349
+ this.inputHandler = undefined;
350
+ let lastDataTime = Date.now();
351
+ const onData = () => {
352
+ lastDataTime = Date.now();
353
+ };
354
+ process.stdin.on("data", onData);
355
+ const endTime = Date.now() + maxMs;
356
+ try {
357
+ while (true) {
358
+ const now = Date.now();
359
+ const timeLeft = endTime - now;
360
+ if (timeLeft <= 0)
361
+ break;
362
+ if (now - lastDataTime >= idleMs)
363
+ break;
364
+ await new Promise((resolve) => setTimeout(resolve, Math.min(idleMs, timeLeft)));
365
+ }
366
+ }
367
+ finally {
368
+ process.stdin.removeListener("data", onData);
369
+ this.inputHandler = previousHandler;
370
+ }
371
+ }
372
+ stop() {
373
+ this.started = false;
374
+ if (this.clearProgressInterval()) {
375
+ process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);
376
+ }
377
+ // Disable bracketed paste mode
378
+ process.stdout.write("\x1b[?2004l");
379
+ const shouldDisableKittyProtocol = this.keyboardProtocolPushed || this._kittyProtocolActive || this.keyboardProtocolNegotiationPending;
380
+ this.keyboardProtocolLateResponsePending = false;
381
+ this.clearKeyboardProtocolNegotiationBuffer();
382
+ this.clearKeyboardProtocolFallbackTimer();
383
+ // Disable Kitty keyboard protocol if not already done by drainInput()
384
+ if (shouldDisableKittyProtocol) {
385
+ process.stdout.write("\x1b[<u");
386
+ this.keyboardProtocolPushed = false;
387
+ this._kittyProtocolActive = false;
388
+ setKittyProtocolActive(false);
389
+ }
390
+ this.keyboardProtocolNegotiationPending = false;
391
+ if (this._modifyOtherKeysActive) {
392
+ process.stdout.write("\x1b[>4;0m");
393
+ this._modifyOtherKeysActive = false;
394
+ }
395
+ // Clean up StdinBuffer
396
+ if (this.stdinBuffer) {
397
+ this.stdinBuffer.destroy();
398
+ this.stdinBuffer = undefined;
399
+ }
400
+ // Remove event handlers
401
+ if (this.stdinDataHandler) {
402
+ process.stdin.removeListener("data", this.stdinDataHandler);
403
+ this.stdinDataHandler = undefined;
404
+ }
405
+ this.inputHandler = undefined;
406
+ if (this.resizeHandler) {
407
+ process.stdout.removeListener("resize", this.resizeHandler);
408
+ this.resizeHandler = undefined;
409
+ }
410
+ // Pause stdin to prevent any buffered input (e.g., Ctrl+D) from being
411
+ // re-interpreted after raw mode is disabled. This fixes a race condition
412
+ // where Ctrl+D could close the parent shell over SSH.
413
+ process.stdin.pause();
414
+ // Restore raw mode state
415
+ if (process.stdin.setRawMode) {
416
+ process.stdin.setRawMode(this.wasRaw);
417
+ }
418
+ }
419
+ write(data) {
420
+ process.stdout.write(data);
421
+ if (this.writeLogPath) {
422
+ try {
423
+ fs.appendFileSync(this.writeLogPath, data, { encoding: "utf8" });
424
+ }
425
+ catch {
426
+ // Ignore logging errors
427
+ }
428
+ }
429
+ }
430
+ get columns() {
431
+ return process.stdout.columns || Number(process.env.COLUMNS) || 80;
432
+ }
433
+ get rows() {
434
+ return process.stdout.rows || Number(process.env.LINES) || 24;
435
+ }
436
+ moveBy(lines) {
437
+ if (lines > 0) {
438
+ // Move down
439
+ process.stdout.write(`\x1b[${lines}B`);
440
+ }
441
+ else if (lines < 0) {
442
+ // Move up
443
+ process.stdout.write(`\x1b[${-lines}A`);
444
+ }
445
+ // lines === 0: no movement
446
+ }
447
+ hideCursor() {
448
+ process.stdout.write("\x1b[?25l");
449
+ }
450
+ showCursor() {
451
+ process.stdout.write("\x1b[?25h");
452
+ }
453
+ clearLine() {
454
+ process.stdout.write("\x1b[K");
455
+ }
456
+ clearFromCursor() {
457
+ process.stdout.write("\x1b[J");
458
+ }
459
+ clearScreen() {
460
+ process.stdout.write("\x1b[2J\x1b[H"); // Clear screen and move to home (1,1)
461
+ }
462
+ setTitle(title) {
463
+ // OSC 0;title BEL - set terminal window title
464
+ process.stdout.write(`\x1b]0;${sanitizeTerminalControlPayload(title)}\x07`);
465
+ }
466
+ setProgress(active) {
467
+ if (active) {
468
+ // OSC 9;4;3 - indeterminate progress
469
+ process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);
470
+ if (!this.progressInterval) {
471
+ this.progressInterval = setInterval(() => {
472
+ process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);
473
+ }, TERMINAL_PROGRESS_KEEPALIVE_MS);
474
+ }
475
+ }
476
+ else {
477
+ this.clearProgressInterval();
478
+ // OSC 9;4;0 - clear progress
479
+ process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);
480
+ }
481
+ }
482
+ clearProgressInterval() {
483
+ if (!this.progressInterval)
484
+ return false;
485
+ clearInterval(this.progressInterval);
486
+ this.progressInterval = undefined;
487
+ return true;
488
+ }
489
+ }
490
+ //# sourceMappingURL=terminal.js.map