@m4ike1/ion-tui 0.1.0

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 (196) hide show
  1. package/README.md +114 -0
  2. package/dist/alt-screen-search.d.ts +46 -0
  3. package/dist/alt-screen-search.d.ts.map +1 -0
  4. package/dist/alt-screen-search.js +282 -0
  5. package/dist/alt-screen-search.js.map +1 -0
  6. package/dist/autocomplete.d.ts +75 -0
  7. package/dist/autocomplete.d.ts.map +1 -0
  8. package/dist/autocomplete.js +749 -0
  9. package/dist/autocomplete.js.map +1 -0
  10. package/dist/components/alt-screen-flash.d.ts +13 -0
  11. package/dist/components/alt-screen-flash.d.ts.map +1 -0
  12. package/dist/components/alt-screen-flash.js +37 -0
  13. package/dist/components/alt-screen-flash.js.map +1 -0
  14. package/dist/components/box.d.ts +24 -0
  15. package/dist/components/box.d.ts.map +1 -0
  16. package/dist/components/box.js +133 -0
  17. package/dist/components/box.js.map +1 -0
  18. package/dist/components/cancellable-loader.d.ts +22 -0
  19. package/dist/components/cancellable-loader.d.ts.map +1 -0
  20. package/dist/components/cancellable-loader.js +35 -0
  21. package/dist/components/cancellable-loader.js.map +1 -0
  22. package/dist/components/editor.d.ts +266 -0
  23. package/dist/components/editor.d.ts.map +1 -0
  24. package/dist/components/editor.js +2087 -0
  25. package/dist/components/editor.js.map +1 -0
  26. package/dist/components/h-stack.d.ts +7 -0
  27. package/dist/components/h-stack.d.ts.map +1 -0
  28. package/dist/components/h-stack.js +43 -0
  29. package/dist/components/h-stack.js.map +1 -0
  30. package/dist/components/image.d.ts +28 -0
  31. package/dist/components/image.d.ts.map +1 -0
  32. package/dist/components/image.js +90 -0
  33. package/dist/components/image.js.map +1 -0
  34. package/dist/components/input.d.ts +48 -0
  35. package/dist/components/input.d.ts.map +1 -0
  36. package/dist/components/input.js +417 -0
  37. package/dist/components/input.js.map +1 -0
  38. package/dist/components/loader.d.ts +33 -0
  39. package/dist/components/loader.d.ts.map +1 -0
  40. package/dist/components/loader.js +76 -0
  41. package/dist/components/loader.js.map +1 -0
  42. package/dist/components/markdown.d.ts +103 -0
  43. package/dist/components/markdown.d.ts.map +1 -0
  44. package/dist/components/markdown.js +858 -0
  45. package/dist/components/markdown.js.map +1 -0
  46. package/dist/components/mouse-region.d.ts +12 -0
  47. package/dist/components/mouse-region.d.ts.map +1 -0
  48. package/dist/components/mouse-region.js +21 -0
  49. package/dist/components/mouse-region.js.map +1 -0
  50. package/dist/components/scroll-view.d.ts +68 -0
  51. package/dist/components/scroll-view.d.ts.map +1 -0
  52. package/dist/components/scroll-view.js +199 -0
  53. package/dist/components/scroll-view.js.map +1 -0
  54. package/dist/components/select-list.d.ts +53 -0
  55. package/dist/components/select-list.d.ts.map +1 -0
  56. package/dist/components/select-list.js +206 -0
  57. package/dist/components/select-list.js.map +1 -0
  58. package/dist/components/settings-list.d.ts +60 -0
  59. package/dist/components/settings-list.d.ts.map +1 -0
  60. package/dist/components/settings-list.js +252 -0
  61. package/dist/components/settings-list.js.map +1 -0
  62. package/dist/components/spacer.d.ts +12 -0
  63. package/dist/components/spacer.d.ts.map +1 -0
  64. package/dist/components/spacer.js +23 -0
  65. package/dist/components/spacer.js.map +1 -0
  66. package/dist/components/stack.d.ts +32 -0
  67. package/dist/components/stack.d.ts.map +1 -0
  68. package/dist/components/stack.js +111 -0
  69. package/dist/components/stack.js.map +1 -0
  70. package/dist/components/text.d.ts +19 -0
  71. package/dist/components/text.d.ts.map +1 -0
  72. package/dist/components/text.js +90 -0
  73. package/dist/components/text.js.map +1 -0
  74. package/dist/components/truncated-text.d.ts +13 -0
  75. package/dist/components/truncated-text.d.ts.map +1 -0
  76. package/dist/components/truncated-text.js +51 -0
  77. package/dist/components/truncated-text.js.map +1 -0
  78. package/dist/components/v-stack.d.ts +8 -0
  79. package/dist/components/v-stack.d.ts.map +1 -0
  80. package/dist/components/v-stack.js +26 -0
  81. package/dist/components/v-stack.js.map +1 -0
  82. package/dist/components/virtual-list.d.ts +51 -0
  83. package/dist/components/virtual-list.d.ts.map +1 -0
  84. package/dist/components/virtual-list.js +170 -0
  85. package/dist/components/virtual-list.js.map +1 -0
  86. package/dist/editor-component.d.ts +39 -0
  87. package/dist/editor-component.d.ts.map +1 -0
  88. package/dist/editor-component.js +2 -0
  89. package/dist/editor-component.js.map +1 -0
  90. package/dist/fuzzy.d.ts +16 -0
  91. package/dist/fuzzy.d.ts.map +1 -0
  92. package/dist/fuzzy.js +110 -0
  93. package/dist/fuzzy.js.map +1 -0
  94. package/dist/index.d.ts +34 -0
  95. package/dist/index.d.ts.map +1 -0
  96. package/dist/index.js +46 -0
  97. package/dist/index.js.map +1 -0
  98. package/dist/keybindings.d.ts +366 -0
  99. package/dist/keybindings.d.ts.map +1 -0
  100. package/dist/keybindings.js +331 -0
  101. package/dist/keybindings.js.map +1 -0
  102. package/dist/keys.d.ts +184 -0
  103. package/dist/keys.d.ts.map +1 -0
  104. package/dist/keys.js +1174 -0
  105. package/dist/keys.js.map +1 -0
  106. package/dist/kill-ring.d.ts +28 -0
  107. package/dist/kill-ring.d.ts.map +1 -0
  108. package/dist/kill-ring.js +44 -0
  109. package/dist/kill-ring.js.map +1 -0
  110. package/dist/latex.d.ts +10 -0
  111. package/dist/latex.d.ts.map +1 -0
  112. package/dist/latex.js +1285 -0
  113. package/dist/latex.js.map +1 -0
  114. package/dist/layout-node.d.ts +59 -0
  115. package/dist/layout-node.d.ts.map +1 -0
  116. package/dist/layout-node.js +12 -0
  117. package/dist/layout-node.js.map +1 -0
  118. package/dist/layout.d.ts +42 -0
  119. package/dist/layout.d.ts.map +1 -0
  120. package/dist/layout.js +404 -0
  121. package/dist/layout.js.map +1 -0
  122. package/dist/native-modifiers.d.ts +4 -0
  123. package/dist/native-modifiers.d.ts.map +1 -0
  124. package/dist/native-modifiers.js +13 -0
  125. package/dist/native-modifiers.js.map +1 -0
  126. package/dist/native-module-path.d.ts +7 -0
  127. package/dist/native-module-path.d.ts.map +1 -0
  128. package/dist/native-module-path.js +19 -0
  129. package/dist/native-module-path.js.map +1 -0
  130. package/dist/native-platform.d.ts +18 -0
  131. package/dist/native-platform.d.ts.map +1 -0
  132. package/dist/native-platform.js +42 -0
  133. package/dist/native-platform.js.map +1 -0
  134. package/dist/pty-host.d.ts +224 -0
  135. package/dist/pty-host.d.ts.map +1 -0
  136. package/dist/pty-host.js +347 -0
  137. package/dist/pty-host.js.map +1 -0
  138. package/dist/stdin-buffer.d.ts +56 -0
  139. package/dist/stdin-buffer.d.ts.map +1 -0
  140. package/dist/stdin-buffer.js +366 -0
  141. package/dist/stdin-buffer.js.map +1 -0
  142. package/dist/terminal-colors.d.ts +10 -0
  143. package/dist/terminal-colors.d.ts.map +1 -0
  144. package/dist/terminal-colors.js +59 -0
  145. package/dist/terminal-colors.js.map +1 -0
  146. package/dist/terminal-image.d.ts +118 -0
  147. package/dist/terminal-image.d.ts.map +1 -0
  148. package/dist/terminal-image.js +550 -0
  149. package/dist/terminal-image.js.map +1 -0
  150. package/dist/terminal.d.ts +123 -0
  151. package/dist/terminal.d.ts.map +1 -0
  152. package/dist/terminal.js +442 -0
  153. package/dist/terminal.js.map +1 -0
  154. package/dist/tui-alt-screen.d.ts +165 -0
  155. package/dist/tui-alt-screen.d.ts.map +1 -0
  156. package/dist/tui-alt-screen.js +1515 -0
  157. package/dist/tui-alt-screen.js.map +1 -0
  158. package/dist/tui-main-screen.d.ts +39 -0
  159. package/dist/tui-main-screen.d.ts.map +1 -0
  160. package/dist/tui-main-screen.js +594 -0
  161. package/dist/tui-main-screen.js.map +1 -0
  162. package/dist/tui.d.ts +431 -0
  163. package/dist/tui.d.ts.map +1 -0
  164. package/dist/tui.js +1142 -0
  165. package/dist/tui.js.map +1 -0
  166. package/dist/undo-stack.d.ts +17 -0
  167. package/dist/undo-stack.d.ts.map +1 -0
  168. package/dist/undo-stack.js +25 -0
  169. package/dist/undo-stack.js.map +1 -0
  170. package/dist/utils.d.ts +98 -0
  171. package/dist/utils.d.ts.map +1 -0
  172. package/dist/utils.js +1200 -0
  173. package/dist/utils.js.map +1 -0
  174. package/dist/word-navigation.d.ts +25 -0
  175. package/dist/word-navigation.d.ts.map +1 -0
  176. package/dist/word-navigation.js +96 -0
  177. package/dist/word-navigation.js.map +1 -0
  178. package/native/clipboard.h +170 -0
  179. package/native/darwin/README.md +22 -0
  180. package/native/darwin/build.sh +69 -0
  181. package/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
  182. package/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  183. package/native/darwin/src/darwin-platform.m +93 -0
  184. package/native/linux/README.md +23 -0
  185. package/native/linux/build.sh +65 -0
  186. package/native/linux/prebuilds/linux-arm64/linux-platform-x11.node +0 -0
  187. package/native/linux/prebuilds/linux-x64/linux-platform-x11.node +0 -0
  188. package/native/linux/src/clipboard-worker.h +70 -0
  189. package/native/linux/src/linux-platform-x11.c +274 -0
  190. package/native/napi.h +89 -0
  191. package/native/win32/README.md +31 -0
  192. package/native/win32/build.mjs +232 -0
  193. package/native/win32/prebuilds/win32-arm64/win32-platform.node +0 -0
  194. package/native/win32/prebuilds/win32-x64/win32-platform.node +0 -0
  195. package/native/win32/src/win32-platform.c +241 -0
  196. package/package.json +62 -0
@@ -0,0 +1,123 @@
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
+ /**
10
+ * Refresh terminal dimensions on POSIX platforms by sending SIGWINCH to this process.
11
+ * Best-effort: some environments (restricted seccomp or LSM policies) return EACCES
12
+ * for `kill(2)`; in that case the dimensions refresh is skipped rather than crashing.
13
+ */
14
+ export declare function refreshTerminalDimensions(): void;
15
+ export declare function normalizeNativeShiftEnterInput(data: string, shouldDetectNativeShiftEnter: boolean, isShiftPressed: boolean): string;
16
+ export declare function normalizeAppleTerminalInput(data: string, isAppleTerminal: boolean, isShiftPressed: boolean): string;
17
+ /**
18
+ * Minimal terminal interface for TUI
19
+ */
20
+ export interface Terminal {
21
+ start(onInput: (data: string) => void, onResize: () => void): void;
22
+ stop(): void;
23
+ /**
24
+ * Drain stdin before exiting to prevent Kitty key release events from
25
+ * leaking to the parent shell over slow SSH connections.
26
+ * @param maxMs - Maximum time to drain (default: 1000ms)
27
+ * @param idleMs - Exit early if no input arrives within this time (default: 50ms)
28
+ */
29
+ drainInput(maxMs?: number, idleMs?: number): Promise<void>;
30
+ write(data: string): void;
31
+ get columns(): number;
32
+ get rows(): number;
33
+ get kittyProtocolActive(): boolean;
34
+ moveBy(lines: number): void;
35
+ hideCursor(): void;
36
+ showCursor(): void;
37
+ clearLine(): void;
38
+ clearFromCursor(): void;
39
+ clearScreen(): void;
40
+ setTitle(title: string): void;
41
+ setProgress(active: boolean): void;
42
+ }
43
+ /**
44
+ * Resolve how long to wait for the rest of an escape sequence before
45
+ * dispatching a lone ESC as the Escape key. Legacy Alt+key input is ESC plus
46
+ * another byte, so high-latency transports need a longer reassembly window.
47
+ */
48
+ export declare function resolveEscapeTimeoutMs(env?: NodeJS.ProcessEnv): number;
49
+ /**
50
+ * Real terminal using process.stdin/stdout
51
+ */
52
+ export declare class ProcessTerminal implements Terminal {
53
+ private wasRaw;
54
+ private inputHandler?;
55
+ private resizeHandler?;
56
+ private _kittyProtocolActive;
57
+ private _modifyOtherKeysActive;
58
+ private keyboardProtocolPushed;
59
+ private keyboardProtocolNegotiationBuffer;
60
+ private keyboardProtocolBufferFlushTimer?;
61
+ private stdinBuffer?;
62
+ private stdinDataHandler?;
63
+ private progressInterval?;
64
+ private writeLogPath;
65
+ get kittyProtocolActive(): boolean;
66
+ get modifyOtherKeysActive(): boolean;
67
+ start(onInput: (data: string) => void, onResize: () => void): void;
68
+ /**
69
+ * Set up StdinBuffer to split batched input into individual sequences.
70
+ * This ensures components receive single events, making matchesKey/isKeyRelease work correctly.
71
+ *
72
+ * Also watches for Kitty protocol response and enables it when detected.
73
+ * This is done here (after stdinBuffer parsing) rather than on raw stdin
74
+ * to handle the case where the response arrives split across multiple events.
75
+ */
76
+ private setupStdinBuffer;
77
+ /**
78
+ * Query terminal for Kitty keyboard protocol support and enable it if available.
79
+ *
80
+ * Kitty's progressive enhancement detection requires requesting the desired
81
+ * flags before querying them. The trailing DA query is a sentinel supported by
82
+ * terminals that do not know Kitty keyboard protocol; receiving DA before a
83
+ * Kitty response enables modifyOtherKeys fallback without a startup timeout.
84
+ *
85
+ * The requested flags are:
86
+ * - 1 = disambiguate escape codes
87
+ * - 2 = report event types (press/repeat/release)
88
+ * - 4 = report alternate keys (shifted key, base layout key)
89
+ */
90
+ private queryAndEnableKittyProtocol;
91
+ private handleKeyboardProtocolNegotiationSequence;
92
+ private readKeyboardProtocolNegotiationSequence;
93
+ private setKeyboardProtocolNegotiationBuffer;
94
+ private clearKeyboardProtocolNegotiationBuffer;
95
+ private flushKeyboardProtocolNegotiationBufferAsInput;
96
+ private scheduleKeyboardProtocolNegotiationBufferFlush;
97
+ private clearKeyboardProtocolNegotiationBufferFlushTimer;
98
+ private forwardInputSequence;
99
+ private enableModifyOtherKeys;
100
+ private disableModifyOtherKeys;
101
+ /**
102
+ * On Windows, add ENABLE_VIRTUAL_TERMINAL_INPUT (0x0200) to the stdin
103
+ * console handle so the terminal sends VT sequences for modified keys
104
+ * (e.g. \x1b[Z for Shift+Tab). Without this, libuv's ReadConsoleInputW
105
+ * discards modifier state and Shift+Tab arrives as plain \t.
106
+ */
107
+ private enableWindowsVTInput;
108
+ drainInput(maxMs?: number, idleMs?: number): Promise<void>;
109
+ stop(): void;
110
+ write(data: string): void;
111
+ get columns(): number;
112
+ get rows(): number;
113
+ moveBy(lines: number): void;
114
+ hideCursor(): void;
115
+ showCursor(): void;
116
+ clearLine(): void;
117
+ clearFromCursor(): void;
118
+ clearScreen(): void;
119
+ setTitle(title: string): void;
120
+ setProgress(active: boolean): void;
121
+ private clearProgressInterval;
122
+ }
123
+ //# 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 * as path from \"node:path\";\nimport { setKittyProtocolActive } from \"./keys.ts\";\nimport { isNativeModifierPressed } from \"./native-modifiers.ts\";\nimport { getNativePlatformHelper } from \"./native-platform.ts\";\nimport { StdinBuffer } from \"./stdin-buffer.ts\";\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 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\n/**\n * Refresh terminal dimensions on POSIX platforms by sending SIGWINCH to this process.\n * Best-effort: some environments (restricted seccomp or LSM policies) return EACCES\n * for `kill(2)`; in that case the dimensions refresh is skipped rather than crashing.\n */\nexport function refreshTerminalDimensions(): void {\n\tif (process.platform === \"win32\" || process.pid <= 0) return;\n\ttry {\n\t\tprocess.kill(process.pid, \"SIGWINCH\");\n\t} catch {\n\t\t// Signal delivery not permitted in this environment; ignore.\n\t}\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\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\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.ION_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 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) => void;\n\tprivate progressInterval?: ReturnType<typeof setInterval>;\n\tprivate writeLogPath = (() => {\n\t\tconst env = process.env.ION_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\tget modifyOtherKeysActive(): boolean {\n\t\treturn this._modifyOtherKeysActive;\n\t}\n\n\tstart(onInput: (data: string) => void, onResize: () => void): void {\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.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, best-effort.\n\t\trefreshTerminalDimensions();\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) => {\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\tthis.keyboardProtocolPushed = true;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tprocess.stdout.write(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\tprocess.stdout.write(\"\\x1b[>4;2m\");\n\t\tthis._modifyOtherKeysActive = true;\n\t}\n\n\tprivate disableModifyOtherKeys(): void {\n\t\tif (!this._modifyOtherKeysActive) return;\n\t\tprocess.stdout.write(\"\\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\tgetNativePlatformHelper()?.enableVirtualTerminalInput?.();\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\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.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\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 = 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\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.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\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;${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,442 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { setKittyProtocolActive } from "./keys.js";
4
+ import { isNativeModifierPressed } from "./native-modifiers.js";
5
+ import { getNativePlatformHelper } from "./native-platform.js";
6
+ import { StdinBuffer } from "./stdin-buffer.js";
7
+ const TERMINAL_PROGRESS_KEEPALIVE_MS = 1000;
8
+ const TERMINAL_PROGRESS_ACTIVE_SEQUENCE = "\x1b]9;4;3\x07";
9
+ const TERMINAL_PROGRESS_CLEAR_SEQUENCE = "\x1b]9;4;0\x07";
10
+ const NATIVE_SHIFT_ENTER_SEQUENCE = "\x1b[13;2u";
11
+ const DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS = 7;
12
+ const KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS = 150;
13
+ const KITTY_KEYBOARD_PROTOCOL_QUERY = `\x1b[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1b[?u\x1b[c`;
14
+ export function parseKeyboardProtocolNegotiationSequence(sequence) {
15
+ const kittyFlags = sequence.match(/^\x1b\[\?(\d+)u$/);
16
+ if (kittyFlags) {
17
+ return { type: "kitty-flags", flags: Number.parseInt(kittyFlags[1], 10) };
18
+ }
19
+ if (/^\x1b\[\?[\d;]*c$/.test(sequence)) {
20
+ return { type: "device-attributes" };
21
+ }
22
+ return undefined;
23
+ }
24
+ function isKeyboardProtocolNegotiationSequencePrefix(sequence) {
25
+ return sequence === "\x1b[" || /^\x1b\[\?[\d;]*$/.test(sequence);
26
+ }
27
+ export function isAppleTerminalSession() {
28
+ return process.platform === "darwin" && process.env.TERM_PROGRAM === "Apple_Terminal";
29
+ }
30
+ /**
31
+ * Refresh terminal dimensions on POSIX platforms by sending SIGWINCH to this process.
32
+ * Best-effort: some environments (restricted seccomp or LSM policies) return EACCES
33
+ * for `kill(2)`; in that case the dimensions refresh is skipped rather than crashing.
34
+ */
35
+ export function refreshTerminalDimensions() {
36
+ if (process.platform === "win32" || process.pid <= 0)
37
+ return;
38
+ try {
39
+ process.kill(process.pid, "SIGWINCH");
40
+ }
41
+ catch {
42
+ // Signal delivery not permitted in this environment; ignore.
43
+ }
44
+ }
45
+ export function normalizeNativeShiftEnterInput(data, shouldDetectNativeShiftEnter, isShiftPressed) {
46
+ if (shouldDetectNativeShiftEnter && data === "\r" && isShiftPressed)
47
+ return NATIVE_SHIFT_ENTER_SEQUENCE;
48
+ return data;
49
+ }
50
+ export function normalizeAppleTerminalInput(data, isAppleTerminal, isShiftPressed) {
51
+ return normalizeNativeShiftEnterInput(data, isAppleTerminal, isShiftPressed);
52
+ }
53
+ const DEFAULT_ESCAPE_TIMEOUT_MS = 10;
54
+ const DEFAULT_SSH_ESCAPE_TIMEOUT_MS = 100;
55
+ /**
56
+ * Resolve how long to wait for the rest of an escape sequence before
57
+ * dispatching a lone ESC as the Escape key. Legacy Alt+key input is ESC plus
58
+ * another byte, so high-latency transports need a longer reassembly window.
59
+ */
60
+ export function resolveEscapeTimeoutMs(env = process.env) {
61
+ const configured = Number(env.ION_TUI_ESC_TIMEOUT);
62
+ if (Number.isFinite(configured) && configured > 0) {
63
+ return configured;
64
+ }
65
+ if (env.SSH_CONNECTION || env.SSH_TTY) {
66
+ return DEFAULT_SSH_ESCAPE_TIMEOUT_MS;
67
+ }
68
+ return DEFAULT_ESCAPE_TIMEOUT_MS;
69
+ }
70
+ /**
71
+ * Real terminal using process.stdin/stdout
72
+ */
73
+ export class ProcessTerminal {
74
+ wasRaw = false;
75
+ inputHandler;
76
+ resizeHandler;
77
+ _kittyProtocolActive = false;
78
+ _modifyOtherKeysActive = false;
79
+ keyboardProtocolPushed = false;
80
+ keyboardProtocolNegotiationBuffer = "";
81
+ keyboardProtocolBufferFlushTimer;
82
+ stdinBuffer;
83
+ stdinDataHandler;
84
+ progressInterval;
85
+ writeLogPath = (() => {
86
+ const env = process.env.ION_TUI_WRITE_LOG || "";
87
+ if (!env)
88
+ return "";
89
+ try {
90
+ if (fs.statSync(env).isDirectory()) {
91
+ const now = new Date();
92
+ 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")}`;
93
+ return path.join(env, `tui-${ts}-${process.pid}.log`);
94
+ }
95
+ }
96
+ catch {
97
+ // Not an existing directory - use as-is (file path)
98
+ }
99
+ return env;
100
+ })();
101
+ get kittyProtocolActive() {
102
+ return this._kittyProtocolActive;
103
+ }
104
+ get modifyOtherKeysActive() {
105
+ return this._modifyOtherKeysActive;
106
+ }
107
+ start(onInput, onResize) {
108
+ this.inputHandler = onInput;
109
+ this.resizeHandler = onResize;
110
+ // Save previous state and enable raw mode
111
+ this.wasRaw = process.stdin.isRaw || false;
112
+ if (process.stdin.setRawMode) {
113
+ process.stdin.setRawMode(true);
114
+ }
115
+ process.stdin.setEncoding("utf8");
116
+ process.stdin.resume();
117
+ // Enable bracketed paste mode - terminal will wrap pastes in \x1b[200~ ... \x1b[201~
118
+ process.stdout.write("\x1b[?2004h");
119
+ // Set up resize handler immediately
120
+ process.stdout.on("resize", this.resizeHandler);
121
+ // Refresh terminal dimensions - they may be stale after suspend/resume
122
+ // (SIGWINCH is lost while process is stopped). Unix only, best-effort.
123
+ refreshTerminalDimensions();
124
+ // On Windows, enable ENABLE_VIRTUAL_TERMINAL_INPUT so the console sends
125
+ // VT escape sequences (e.g. \x1b[Z for Shift+Tab) instead of raw console
126
+ // events that lose modifier information. Must run AFTER setRawMode(true)
127
+ // since that resets console mode flags.
128
+ this.enableWindowsVTInput();
129
+ // Query Kitty keyboard protocol and fall back to modifyOtherKeys when DA confirms no Kitty response.
130
+ // See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/
131
+ this.queryAndEnableKittyProtocol();
132
+ }
133
+ /**
134
+ * Set up StdinBuffer to split batched input into individual sequences.
135
+ * This ensures components receive single events, making matchesKey/isKeyRelease work correctly.
136
+ *
137
+ * Also watches for Kitty protocol response and enables it when detected.
138
+ * This is done here (after stdinBuffer parsing) rather than on raw stdin
139
+ * to handle the case where the response arrives split across multiple events.
140
+ */
141
+ setupStdinBuffer() {
142
+ this.stdinBuffer = new StdinBuffer({ escapeTimeout: resolveEscapeTimeoutMs() });
143
+ // Forward individual sequences to the input handler
144
+ this.stdinBuffer.on("data", (sequence) => {
145
+ const negotiationSequence = this.readKeyboardProtocolNegotiationSequence(sequence);
146
+ if (negotiationSequence === "pending") {
147
+ this.scheduleKeyboardProtocolNegotiationBufferFlush();
148
+ return; // Wait briefly for the rest of a split Kitty response.
149
+ }
150
+ if (this.handleKeyboardProtocolNegotiationSequence(negotiationSequence)) {
151
+ return;
152
+ }
153
+ this.forwardInputSequence(sequence);
154
+ });
155
+ // Re-wrap paste content with bracketed paste markers for existing editor handling
156
+ this.stdinBuffer.on("paste", (content) => {
157
+ if (this.inputHandler) {
158
+ this.inputHandler(`\x1b[200~${content}\x1b[201~`);
159
+ }
160
+ });
161
+ // Handler that pipes stdin data through the buffer
162
+ this.stdinDataHandler = (data) => {
163
+ this.stdinBuffer.process(data);
164
+ };
165
+ }
166
+ /**
167
+ * Query terminal for Kitty keyboard protocol support and enable it if available.
168
+ *
169
+ * Kitty's progressive enhancement detection requires requesting the desired
170
+ * flags before querying them. The trailing DA query is a sentinel supported by
171
+ * terminals that do not know Kitty keyboard protocol; receiving DA before a
172
+ * Kitty response enables modifyOtherKeys fallback without a startup timeout.
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.clearKeyboardProtocolNegotiationBuffer();
184
+ process.stdout.write(KITTY_KEYBOARD_PROTOCOL_QUERY);
185
+ }
186
+ handleKeyboardProtocolNegotiationSequence(negotiationSequence) {
187
+ if (!negotiationSequence)
188
+ return false;
189
+ this.clearKeyboardProtocolNegotiationBuffer();
190
+ if (negotiationSequence.type === "kitty-flags") {
191
+ if (negotiationSequence.flags !== 0) {
192
+ this.disableModifyOtherKeys();
193
+ if (!this._kittyProtocolActive) {
194
+ this._kittyProtocolActive = true;
195
+ setKittyProtocolActive(true);
196
+ }
197
+ }
198
+ else {
199
+ this.enableModifyOtherKeys();
200
+ }
201
+ return true;
202
+ }
203
+ if (!this._kittyProtocolActive) {
204
+ this.enableModifyOtherKeys();
205
+ }
206
+ return true;
207
+ }
208
+ readKeyboardProtocolNegotiationSequence(sequence) {
209
+ if (this.keyboardProtocolNegotiationBuffer) {
210
+ const bufferedSequence = this.keyboardProtocolNegotiationBuffer + sequence;
211
+ const negotiationSequence = parseKeyboardProtocolNegotiationSequence(bufferedSequence);
212
+ if (negotiationSequence) {
213
+ this.clearKeyboardProtocolNegotiationBuffer();
214
+ return negotiationSequence;
215
+ }
216
+ if (isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence)) {
217
+ this.setKeyboardProtocolNegotiationBuffer(bufferedSequence);
218
+ return "pending";
219
+ }
220
+ this.flushKeyboardProtocolNegotiationBufferAsInput();
221
+ }
222
+ const negotiationSequence = parseKeyboardProtocolNegotiationSequence(sequence);
223
+ if (negotiationSequence)
224
+ return negotiationSequence;
225
+ if (isKeyboardProtocolNegotiationSequencePrefix(sequence)) {
226
+ this.setKeyboardProtocolNegotiationBuffer(sequence);
227
+ return "pending";
228
+ }
229
+ return undefined;
230
+ }
231
+ setKeyboardProtocolNegotiationBuffer(sequence) {
232
+ this.clearKeyboardProtocolNegotiationBufferFlushTimer();
233
+ this.keyboardProtocolNegotiationBuffer = sequence;
234
+ }
235
+ clearKeyboardProtocolNegotiationBuffer() {
236
+ this.clearKeyboardProtocolNegotiationBufferFlushTimer();
237
+ this.keyboardProtocolNegotiationBuffer = "";
238
+ }
239
+ flushKeyboardProtocolNegotiationBufferAsInput() {
240
+ if (!this.keyboardProtocolNegotiationBuffer)
241
+ return;
242
+ const sequence = this.keyboardProtocolNegotiationBuffer;
243
+ this.clearKeyboardProtocolNegotiationBuffer();
244
+ this.forwardInputSequence(sequence);
245
+ }
246
+ scheduleKeyboardProtocolNegotiationBufferFlush() {
247
+ if (!this.keyboardProtocolNegotiationBuffer || this.keyboardProtocolBufferFlushTimer)
248
+ return;
249
+ this.keyboardProtocolBufferFlushTimer = setTimeout(() => {
250
+ this.keyboardProtocolBufferFlushTimer = undefined;
251
+ this.flushKeyboardProtocolNegotiationBufferAsInput();
252
+ }, KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS);
253
+ }
254
+ clearKeyboardProtocolNegotiationBufferFlushTimer() {
255
+ if (!this.keyboardProtocolBufferFlushTimer)
256
+ return;
257
+ clearTimeout(this.keyboardProtocolBufferFlushTimer);
258
+ this.keyboardProtocolBufferFlushTimer = undefined;
259
+ }
260
+ forwardInputSequence(sequence) {
261
+ if (!this.inputHandler)
262
+ return;
263
+ const shouldDetectNativeShiftEnter = sequence === "\r" && (isAppleTerminalSession() || process.platform === "win32");
264
+ const input = normalizeNativeShiftEnterInput(sequence, shouldDetectNativeShiftEnter, shouldDetectNativeShiftEnter && isNativeModifierPressed("shift"));
265
+ this.inputHandler(input);
266
+ }
267
+ enableModifyOtherKeys() {
268
+ if (this._kittyProtocolActive || this._modifyOtherKeysActive)
269
+ return;
270
+ process.stdout.write("\x1b[>4;2m");
271
+ this._modifyOtherKeysActive = true;
272
+ }
273
+ disableModifyOtherKeys() {
274
+ if (!this._modifyOtherKeysActive)
275
+ return;
276
+ process.stdout.write("\x1b[>4;0m");
277
+ this._modifyOtherKeysActive = false;
278
+ }
279
+ /**
280
+ * On Windows, add ENABLE_VIRTUAL_TERMINAL_INPUT (0x0200) to the stdin
281
+ * console handle so the terminal sends VT sequences for modified keys
282
+ * (e.g. \x1b[Z for Shift+Tab). Without this, libuv's ReadConsoleInputW
283
+ * discards modifier state and Shift+Tab arrives as plain \t.
284
+ */
285
+ enableWindowsVTInput() {
286
+ if (process.platform !== "win32")
287
+ return;
288
+ try {
289
+ getNativePlatformHelper()?.enableVirtualTerminalInput?.();
290
+ }
291
+ catch {
292
+ // Native helper not available — Shift+Tab won't be distinguishable from Tab.
293
+ }
294
+ }
295
+ async drainInput(maxMs = 1000, idleMs = 50) {
296
+ const shouldDisableKittyProtocol = this.keyboardProtocolPushed || this._kittyProtocolActive;
297
+ this.clearKeyboardProtocolNegotiationBuffer();
298
+ if (shouldDisableKittyProtocol) {
299
+ // Disable Kitty keyboard protocol first so any late key releases
300
+ // do not generate new Kitty escape sequences.
301
+ process.stdout.write("\x1b[<u");
302
+ this.keyboardProtocolPushed = false;
303
+ this._kittyProtocolActive = false;
304
+ setKittyProtocolActive(false);
305
+ }
306
+ this.disableModifyOtherKeys();
307
+ const previousHandler = this.inputHandler;
308
+ this.inputHandler = undefined;
309
+ let lastDataTime = Date.now();
310
+ const onData = () => {
311
+ lastDataTime = Date.now();
312
+ };
313
+ process.stdin.on("data", onData);
314
+ const endTime = Date.now() + maxMs;
315
+ try {
316
+ while (true) {
317
+ const now = Date.now();
318
+ const timeLeft = endTime - now;
319
+ if (timeLeft <= 0)
320
+ break;
321
+ if (now - lastDataTime >= idleMs)
322
+ break;
323
+ await new Promise((resolve) => setTimeout(resolve, Math.min(idleMs, timeLeft)));
324
+ }
325
+ }
326
+ finally {
327
+ process.stdin.removeListener("data", onData);
328
+ this.inputHandler = previousHandler;
329
+ }
330
+ }
331
+ stop() {
332
+ if (this.clearProgressInterval()) {
333
+ process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);
334
+ }
335
+ // Disable bracketed paste mode
336
+ process.stdout.write("\x1b[?2004l");
337
+ const shouldDisableKittyProtocol = this.keyboardProtocolPushed || this._kittyProtocolActive;
338
+ this.clearKeyboardProtocolNegotiationBuffer();
339
+ // Disable Kitty keyboard protocol if not already done by drainInput()
340
+ if (shouldDisableKittyProtocol) {
341
+ process.stdout.write("\x1b[<u");
342
+ this.keyboardProtocolPushed = false;
343
+ this._kittyProtocolActive = false;
344
+ setKittyProtocolActive(false);
345
+ }
346
+ this.disableModifyOtherKeys();
347
+ // Clean up StdinBuffer
348
+ if (this.stdinBuffer) {
349
+ this.stdinBuffer.destroy();
350
+ this.stdinBuffer = undefined;
351
+ }
352
+ // Remove event handlers
353
+ if (this.stdinDataHandler) {
354
+ process.stdin.removeListener("data", this.stdinDataHandler);
355
+ this.stdinDataHandler = undefined;
356
+ }
357
+ this.inputHandler = undefined;
358
+ if (this.resizeHandler) {
359
+ process.stdout.removeListener("resize", this.resizeHandler);
360
+ this.resizeHandler = undefined;
361
+ }
362
+ // Pause stdin to prevent any buffered input (e.g., Ctrl+D) from being
363
+ // re-interpreted after raw mode is disabled. This fixes a race condition
364
+ // where Ctrl+D could close the parent shell over SSH.
365
+ process.stdin.pause();
366
+ // Restore raw mode state
367
+ if (process.stdin.setRawMode) {
368
+ process.stdin.setRawMode(this.wasRaw);
369
+ }
370
+ }
371
+ write(data) {
372
+ process.stdout.write(data);
373
+ if (this.writeLogPath) {
374
+ try {
375
+ fs.appendFileSync(this.writeLogPath, data, { encoding: "utf8" });
376
+ }
377
+ catch {
378
+ // Ignore logging errors
379
+ }
380
+ }
381
+ }
382
+ get columns() {
383
+ return process.stdout.columns || Number(process.env.COLUMNS) || 80;
384
+ }
385
+ get rows() {
386
+ return process.stdout.rows || Number(process.env.LINES) || 24;
387
+ }
388
+ moveBy(lines) {
389
+ if (lines > 0) {
390
+ // Move down
391
+ process.stdout.write(`\x1b[${lines}B`);
392
+ }
393
+ else if (lines < 0) {
394
+ // Move up
395
+ process.stdout.write(`\x1b[${-lines}A`);
396
+ }
397
+ // lines === 0: no movement
398
+ }
399
+ hideCursor() {
400
+ process.stdout.write("\x1b[?25l");
401
+ }
402
+ showCursor() {
403
+ process.stdout.write("\x1b[?25h");
404
+ }
405
+ clearLine() {
406
+ process.stdout.write("\x1b[K");
407
+ }
408
+ clearFromCursor() {
409
+ process.stdout.write("\x1b[J");
410
+ }
411
+ clearScreen() {
412
+ process.stdout.write("\x1b[2J\x1b[H"); // Clear screen and move to home (1,1)
413
+ }
414
+ setTitle(title) {
415
+ // OSC 0;title BEL - set terminal window title
416
+ process.stdout.write(`\x1b]0;${title}\x07`);
417
+ }
418
+ setProgress(active) {
419
+ if (active) {
420
+ // OSC 9;4;3 - indeterminate progress
421
+ process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);
422
+ if (!this.progressInterval) {
423
+ this.progressInterval = setInterval(() => {
424
+ process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);
425
+ }, TERMINAL_PROGRESS_KEEPALIVE_MS);
426
+ }
427
+ }
428
+ else {
429
+ this.clearProgressInterval();
430
+ // OSC 9;4;0 - clear progress
431
+ process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);
432
+ }
433
+ }
434
+ clearProgressInterval() {
435
+ if (!this.progressInterval)
436
+ return false;
437
+ clearInterval(this.progressInterval);
438
+ this.progressInterval = undefined;
439
+ return true;
440
+ }
441
+ }
442
+ //# sourceMappingURL=terminal.js.map