@visual-z/xeno 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 (180) hide show
  1. package/README.md +498 -0
  2. package/docs/install.md +130 -0
  3. package/package.json +43 -0
  4. package/src/apps/approve.ts +49 -0
  5. package/src/apps/cli.ts +37 -0
  6. package/src/apps/commands.ts +226 -0
  7. package/src/apps/completions.ts +28 -0
  8. package/src/apps/input.ts +297 -0
  9. package/src/apps/render.ts +207 -0
  10. package/src/apps/shell.ts +2353 -0
  11. package/src/apps/startup.ts +1302 -0
  12. package/src/core/benchmark.ts +195 -0
  13. package/src/core/boundary.ts +174 -0
  14. package/src/core/churn.ts +59 -0
  15. package/src/core/completion-review.ts +66 -0
  16. package/src/core/context-policy.ts +60 -0
  17. package/src/core/context-window.ts +54 -0
  18. package/src/core/continuation.ts +114 -0
  19. package/src/core/cycle.ts +17 -0
  20. package/src/core/data-query.ts +201 -0
  21. package/src/core/deadline.ts +39 -0
  22. package/src/core/derive.ts +489 -0
  23. package/src/core/edit-plan.ts +200 -0
  24. package/src/core/environment.ts +29 -0
  25. package/src/core/event-validation.ts +99 -0
  26. package/src/core/events.ts +486 -0
  27. package/src/core/evidence-links.ts +71 -0
  28. package/src/core/evidence.ts +89 -0
  29. package/src/core/execution.ts +12 -0
  30. package/src/core/exhaustive.ts +18 -0
  31. package/src/core/experiment.ts +40 -0
  32. package/src/core/export.ts +169 -0
  33. package/src/core/file-references.ts +35 -0
  34. package/src/core/frontmatter.ts +213 -0
  35. package/src/core/handoff.ts +397 -0
  36. package/src/core/harness-comparison.ts +90 -0
  37. package/src/core/history-query.ts +103 -0
  38. package/src/core/history.ts +100 -0
  39. package/src/core/json-event.ts +135 -0
  40. package/src/core/json-pointer.ts +46 -0
  41. package/src/core/keymap.ts +241 -0
  42. package/src/core/observation-view.ts +87 -0
  43. package/src/core/outcome.ts +45 -0
  44. package/src/core/overflow.ts +59 -0
  45. package/src/core/permissions.ts +182 -0
  46. package/src/core/policy-evaluation.ts +55 -0
  47. package/src/core/progress.ts +101 -0
  48. package/src/core/project.ts +372 -0
  49. package/src/core/prompts.ts +83 -0
  50. package/src/core/queue.ts +60 -0
  51. package/src/core/read-bounds.ts +15 -0
  52. package/src/core/recall-analysis.ts +90 -0
  53. package/src/core/recall-trial.ts +153 -0
  54. package/src/core/response-recovery.ts +46 -0
  55. package/src/core/scheduling.ts +8 -0
  56. package/src/core/settings.ts +174 -0
  57. package/src/core/skills.ts +121 -0
  58. package/src/core/stall.ts +48 -0
  59. package/src/core/text-normalize.ts +81 -0
  60. package/src/core/theme.ts +179 -0
  61. package/src/core/tokens.ts +149 -0
  62. package/src/core/tool-contract.ts +102 -0
  63. package/src/core/tool-input.ts +38 -0
  64. package/src/core/transcript.ts +60 -0
  65. package/src/core/window-trial.ts +65 -0
  66. package/src/core/work-state.ts +103 -0
  67. package/src/core/yaml.ts +282 -0
  68. package/src/index.ts +10 -0
  69. package/src/runtime/auth.ts +255 -0
  70. package/src/runtime/benchmark.ts +187 -0
  71. package/src/runtime/catalog.ts +365 -0
  72. package/src/runtime/evidence-notes.ts +33 -0
  73. package/src/runtime/exec-sessions.ts +214 -0
  74. package/src/runtime/execution-control.ts +39 -0
  75. package/src/runtime/harness-comparison.ts +356 -0
  76. package/src/runtime/history-tools.ts +108 -0
  77. package/src/runtime/loop.ts +1983 -0
  78. package/src/runtime/model.ts +614 -0
  79. package/src/runtime/models-fetch.ts +155 -0
  80. package/src/runtime/oauth-device.ts +86 -0
  81. package/src/runtime/oauth.ts +759 -0
  82. package/src/runtime/openai-responses.ts +286 -0
  83. package/src/runtime/openai.ts +675 -0
  84. package/src/runtime/provider.ts +498 -0
  85. package/src/runtime/recall-trial.ts +226 -0
  86. package/src/runtime/resume.ts +66 -0
  87. package/src/runtime/retry.ts +297 -0
  88. package/src/runtime/tools.ts +1193 -0
  89. package/src/runtime/usage.ts +225 -0
  90. package/src/runtime/window-trial.ts +140 -0
  91. package/src/runtime/working-notes.ts +30 -0
  92. package/src/store/atomic.ts +31 -0
  93. package/src/store/auth-store.ts +50 -0
  94. package/src/store/blobs.ts +142 -0
  95. package/src/store/command.ts +75 -0
  96. package/src/store/config.ts +69 -0
  97. package/src/store/context-files.ts +356 -0
  98. package/src/store/file-index.ts +81 -0
  99. package/src/store/git-branch.ts +35 -0
  100. package/src/store/history-search.ts +19 -0
  101. package/src/store/log.ts +642 -0
  102. package/src/store/models.ts +41 -0
  103. package/src/store/observations.ts +181 -0
  104. package/src/store/query-source.ts +44 -0
  105. package/src/store/recovery.ts +39 -0
  106. package/src/store/replay.ts +63 -0
  107. package/src/store/resources.ts +361 -0
  108. package/src/store/restore.ts +302 -0
  109. package/src/store/search.ts +644 -0
  110. package/src/store/serial.ts +13 -0
  111. package/src/store/sessions.ts +463 -0
  112. package/src/store/trust.ts +69 -0
  113. package/src/store/workspace.ts +256 -0
  114. package/src/store/worktree.ts +233 -0
  115. package/src/tui/ansi.ts +67 -0
  116. package/src/tui/autocomplete.ts +29 -0
  117. package/src/tui/complete.ts +87 -0
  118. package/src/tui/diff.ts +160 -0
  119. package/src/tui/editor.ts +893 -0
  120. package/src/tui/exhaustive.ts +14 -0
  121. package/src/tui/fuzzy.ts +75 -0
  122. package/src/tui/host.ts +223 -0
  123. package/src/tui/input.ts +69 -0
  124. package/src/tui/keys.ts +378 -0
  125. package/src/tui/markdown.ts +17 -0
  126. package/src/tui/render.ts +153 -0
  127. package/src/tui/select.ts +240 -0
  128. package/src/tui/settings.ts +40 -0
  129. package/src/tui/statusline.ts +162 -0
  130. package/src/tui/style.ts +205 -0
  131. package/src/tui/terminal.ts +30 -0
  132. package/src/tui/text.ts +52 -0
  133. package/src/tui/toolview.ts +386 -0
  134. package/src/tui/transcript.ts +71 -0
  135. package/src/tui/tree.ts +405 -0
  136. package/src/tui/width.ts +567 -0
  137. package/src/vendor/pi-tui/LICENSE.upstream +21 -0
  138. package/src/vendor/pi-tui/VENDOR.md +23 -0
  139. package/src/vendor/pi-tui/alt-screen-search.ts +327 -0
  140. package/src/vendor/pi-tui/autocomplete.ts +835 -0
  141. package/src/vendor/pi-tui/components/alt-screen-flash.ts +51 -0
  142. package/src/vendor/pi-tui/components/box.ts +167 -0
  143. package/src/vendor/pi-tui/components/cancellable-loader.ts +40 -0
  144. package/src/vendor/pi-tui/components/editor.ts +2470 -0
  145. package/src/vendor/pi-tui/components/h-stack.ts +44 -0
  146. package/src/vendor/pi-tui/components/image.ts +127 -0
  147. package/src/vendor/pi-tui/components/input.ts +494 -0
  148. package/src/vendor/pi-tui/components/loader.ts +101 -0
  149. package/src/vendor/pi-tui/components/markdown.ts +1015 -0
  150. package/src/vendor/pi-tui/components/mouse-region.ts +33 -0
  151. package/src/vendor/pi-tui/components/scroll-view.ts +224 -0
  152. package/src/vendor/pi-tui/components/select-list.ts +273 -0
  153. package/src/vendor/pi-tui/components/settings-list.ts +328 -0
  154. package/src/vendor/pi-tui/components/spacer.ts +28 -0
  155. package/src/vendor/pi-tui/components/stack.ts +154 -0
  156. package/src/vendor/pi-tui/components/text.ts +107 -0
  157. package/src/vendor/pi-tui/components/truncated-text.ts +65 -0
  158. package/src/vendor/pi-tui/components/v-stack.ts +33 -0
  159. package/src/vendor/pi-tui/editor-component.ts +74 -0
  160. package/src/vendor/pi-tui/fuzzy.ts +138 -0
  161. package/src/vendor/pi-tui/index.ts +156 -0
  162. package/src/vendor/pi-tui/keybindings.ts +320 -0
  163. package/src/vendor/pi-tui/keys.ts +1401 -0
  164. package/src/vendor/pi-tui/kill-ring.ts +46 -0
  165. package/src/vendor/pi-tui/latex.ts +1506 -0
  166. package/src/vendor/pi-tui/layout-node.ts +51 -0
  167. package/src/vendor/pi-tui/layout.ts +449 -0
  168. package/src/vendor/pi-tui/native-modifiers.ts +13 -0
  169. package/src/vendor/pi-tui/native-module-path.ts +31 -0
  170. package/src/vendor/pi-tui/native-platform.ts +63 -0
  171. package/src/vendor/pi-tui/stdin-buffer.ts +444 -0
  172. package/src/vendor/pi-tui/terminal-colors.ts +73 -0
  173. package/src/vendor/pi-tui/terminal-image.ts +696 -0
  174. package/src/vendor/pi-tui/terminal.ts +547 -0
  175. package/src/vendor/pi-tui/tui-alt-screen.ts +1742 -0
  176. package/src/vendor/pi-tui/tui-main-screen.ts +655 -0
  177. package/src/vendor/pi-tui/tui.ts +1456 -0
  178. package/src/vendor/pi-tui/undo-stack.ts +28 -0
  179. package/src/vendor/pi-tui/utils.ts +1345 -0
  180. package/src/vendor/pi-tui/word-navigation.ts +117 -0
@@ -0,0 +1,547 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { setKittyProtocolActive } from "./keys.ts";
4
+ import { isNativeModifierPressed } from "./native-modifiers.ts";
5
+ import { getNativePlatformHelper } from "./native-platform.ts";
6
+ import { StdinBuffer } from "./stdin-buffer.ts";
7
+
8
+ const TERMINAL_PROGRESS_KEEPALIVE_MS = 1000;
9
+ const TERMINAL_PROGRESS_ACTIVE_SEQUENCE = "\x1b]9;4;3\x07";
10
+ const TERMINAL_PROGRESS_CLEAR_SEQUENCE = "\x1b]9;4;0\x07";
11
+ const NATIVE_SHIFT_ENTER_SEQUENCE = "\x1b[13;2u";
12
+ const DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS = 7;
13
+ const KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS = 150;
14
+ const KITTY_KEYBOARD_PROTOCOL_QUERY = `\x1b[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1b[?u\x1b[c`;
15
+
16
+ export type KeyboardProtocolNegotiationSequence =
17
+ | { type: "kitty-flags"; flags: number }
18
+ | { type: "device-attributes" };
19
+
20
+ export function parseKeyboardProtocolNegotiationSequence(
21
+ sequence: string,
22
+ ): KeyboardProtocolNegotiationSequence | undefined {
23
+ const kittyFlags = sequence.match(/^\x1b\[\?(\d+)u$/);
24
+ if (kittyFlags) {
25
+ return { type: "kitty-flags", flags: Number.parseInt(kittyFlags[1]!, 10) };
26
+ }
27
+ if (/^\x1b\[\?[\d;]*c$/.test(sequence)) {
28
+ return { type: "device-attributes" };
29
+ }
30
+ return undefined;
31
+ }
32
+
33
+ function isKeyboardProtocolNegotiationSequencePrefix(sequence: string): boolean {
34
+ return sequence === "\x1b[" || /^\x1b\[\?[\d;]*$/.test(sequence);
35
+ }
36
+
37
+ export function isAppleTerminalSession(): boolean {
38
+ return process.platform === "darwin" && process.env.TERM_PROGRAM === "Apple_Terminal";
39
+ }
40
+
41
+ /**
42
+ * Refresh terminal dimensions on POSIX platforms by sending SIGWINCH to this process.
43
+ * Best-effort: some environments (restricted seccomp or LSM policies) return EACCES
44
+ * for `kill(2)`; in that case the dimensions refresh is skipped rather than crashing.
45
+ */
46
+ export function refreshTerminalDimensions(): void {
47
+ if (process.platform === "win32" || process.pid <= 0) return;
48
+ try {
49
+ process.kill(process.pid, "SIGWINCH");
50
+ } catch {
51
+ // Signal delivery not permitted in this environment; ignore.
52
+ }
53
+ }
54
+
55
+ export function normalizeNativeShiftEnterInput(
56
+ data: string,
57
+ shouldDetectNativeShiftEnter: boolean,
58
+ isShiftPressed: boolean,
59
+ ): string {
60
+ if (shouldDetectNativeShiftEnter && data === "\r" && isShiftPressed) return NATIVE_SHIFT_ENTER_SEQUENCE;
61
+ return data;
62
+ }
63
+
64
+ export function normalizeAppleTerminalInput(data: string, isAppleTerminal: boolean, isShiftPressed: boolean): string {
65
+ return normalizeNativeShiftEnterInput(data, isAppleTerminal, isShiftPressed);
66
+ }
67
+
68
+ /**
69
+ * Minimal terminal interface for TUI
70
+ */
71
+ export interface Terminal {
72
+ // Start the terminal with input and resize handlers
73
+ start(onInput: (data: string) => void, onResize: () => void): void;
74
+
75
+ // Stop the terminal and restore state
76
+ stop(): void;
77
+
78
+ /**
79
+ * Drain stdin before exiting to prevent Kitty key release events from
80
+ * leaking to the parent shell over slow SSH connections.
81
+ * @param maxMs - Maximum time to drain (default: 1000ms)
82
+ * @param idleMs - Exit early if no input arrives within this time (default: 50ms)
83
+ */
84
+ drainInput(maxMs?: number, idleMs?: number): Promise<void>;
85
+
86
+ // Write output to terminal
87
+ write(data: string): void;
88
+
89
+ // Get terminal dimensions
90
+ get columns(): number;
91
+ get rows(): number;
92
+
93
+ // Whether Kitty keyboard protocol is active
94
+ get kittyProtocolActive(): boolean;
95
+
96
+ // Cursor positioning (relative to current position)
97
+ moveBy(lines: number): void; // Move cursor up (negative) or down (positive) by N lines
98
+
99
+ // Cursor visibility
100
+ hideCursor(): void; // Hide the cursor
101
+ showCursor(): void; // Show the cursor
102
+
103
+ // Clear operations
104
+ clearLine(): void; // Clear current line
105
+ clearFromCursor(): void; // Clear from cursor to end of screen
106
+ clearScreen(): void; // Clear entire screen and move cursor to (0,0)
107
+
108
+ // Title operations
109
+ setTitle(title: string): void; // Set terminal window title
110
+
111
+ // Progress indicator (OSC 9;4)
112
+ setProgress(active: boolean): void;
113
+ }
114
+
115
+ const DEFAULT_ESCAPE_TIMEOUT_MS = 10;
116
+ const DEFAULT_SSH_ESCAPE_TIMEOUT_MS = 100;
117
+
118
+ /**
119
+ * Resolve how long to wait for the rest of an escape sequence before
120
+ * dispatching a lone ESC as the Escape key. Legacy Alt+key input is ESC plus
121
+ * another byte, so high-latency transports need a longer reassembly window.
122
+ */
123
+ export function resolveEscapeTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {
124
+ const configured = Number(env.PI_TUI_ESC_TIMEOUT);
125
+ if (Number.isFinite(configured) && configured > 0) {
126
+ return configured;
127
+ }
128
+ if (env.SSH_CONNECTION || env.SSH_TTY) {
129
+ return DEFAULT_SSH_ESCAPE_TIMEOUT_MS;
130
+ }
131
+ return DEFAULT_ESCAPE_TIMEOUT_MS;
132
+ }
133
+
134
+ /**
135
+ * Real terminal using process.stdin/stdout
136
+ */
137
+ export class ProcessTerminal implements Terminal {
138
+ private wasRaw = false;
139
+ private inputHandler?: (data: string) => void;
140
+ private resizeHandler?: () => void;
141
+ private _kittyProtocolActive = false;
142
+ private _modifyOtherKeysActive = false;
143
+ private keyboardProtocolPushed = false;
144
+ private keyboardProtocolNegotiationBuffer = "";
145
+ private keyboardProtocolBufferFlushTimer?: ReturnType<typeof setTimeout>;
146
+ private stdinBuffer?: StdinBuffer;
147
+ private stdinDataHandler?: (data: string) => void;
148
+ private progressInterval?: ReturnType<typeof setInterval>;
149
+ private writeLogPath = (() => {
150
+ const env = process.env.PI_TUI_WRITE_LOG || "";
151
+ if (!env) return "";
152
+ try {
153
+ if (fs.statSync(env).isDirectory()) {
154
+ const now = new Date();
155
+ 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")}`;
156
+ return path.join(env, `tui-${ts}-${process.pid}.log`);
157
+ }
158
+ } catch {
159
+ // Not an existing directory - use as-is (file path)
160
+ }
161
+ return env;
162
+ })();
163
+
164
+ get kittyProtocolActive(): boolean {
165
+ return this._kittyProtocolActive;
166
+ }
167
+
168
+ get modifyOtherKeysActive(): boolean {
169
+ return this._modifyOtherKeysActive;
170
+ }
171
+
172
+ start(onInput: (data: string) => void, onResize: () => void): void {
173
+ this.inputHandler = onInput;
174
+ this.resizeHandler = onResize;
175
+
176
+ // Save previous state and enable raw mode
177
+ this.wasRaw = process.stdin.isRaw || false;
178
+ if (process.stdin.setRawMode) {
179
+ process.stdin.setRawMode(true);
180
+ }
181
+ process.stdin.setEncoding("utf8");
182
+ process.stdin.resume();
183
+
184
+ // Enable bracketed paste mode - terminal will wrap pastes in \x1b[200~ ... \x1b[201~
185
+ process.stdout.write("\x1b[?2004h");
186
+
187
+ // Set up resize handler immediately
188
+ process.stdout.on("resize", this.resizeHandler);
189
+
190
+ // Refresh terminal dimensions - they may be stale after suspend/resume
191
+ // (SIGWINCH is lost while process is stopped). Unix only, best-effort.
192
+ refreshTerminalDimensions();
193
+
194
+ // On Windows, enable ENABLE_VIRTUAL_TERMINAL_INPUT so the console sends
195
+ // VT escape sequences (e.g. \x1b[Z for Shift+Tab) instead of raw console
196
+ // events that lose modifier information. Must run AFTER setRawMode(true)
197
+ // since that resets console mode flags.
198
+ this.enableWindowsVTInput();
199
+
200
+ // Query Kitty keyboard protocol and fall back to modifyOtherKeys when DA confirms no Kitty response.
201
+ // See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/
202
+ this.queryAndEnableKittyProtocol();
203
+ }
204
+
205
+ /**
206
+ * Set up StdinBuffer to split batched input into individual sequences.
207
+ * This ensures components receive single events, making matchesKey/isKeyRelease work correctly.
208
+ *
209
+ * Also watches for Kitty protocol response and enables it when detected.
210
+ * This is done here (after stdinBuffer parsing) rather than on raw stdin
211
+ * to handle the case where the response arrives split across multiple events.
212
+ */
213
+ private setupStdinBuffer(): void {
214
+ this.stdinBuffer = new StdinBuffer({ escapeTimeout: resolveEscapeTimeoutMs() });
215
+
216
+ // Forward individual sequences to the input handler
217
+ this.stdinBuffer.on("data", (sequence) => {
218
+ const negotiationSequence = this.readKeyboardProtocolNegotiationSequence(sequence);
219
+ if (negotiationSequence === "pending") {
220
+ this.scheduleKeyboardProtocolNegotiationBufferFlush();
221
+ return; // Wait briefly for the rest of a split Kitty response.
222
+ }
223
+ if (this.handleKeyboardProtocolNegotiationSequence(negotiationSequence)) {
224
+ return;
225
+ }
226
+
227
+ this.forwardInputSequence(sequence);
228
+ });
229
+
230
+ // Re-wrap paste content with bracketed paste markers for existing editor handling
231
+ this.stdinBuffer.on("paste", (content) => {
232
+ if (this.inputHandler) {
233
+ this.inputHandler(`\x1b[200~${content}\x1b[201~`);
234
+ }
235
+ });
236
+
237
+ // Handler that pipes stdin data through the buffer
238
+ this.stdinDataHandler = (data: string) => {
239
+ this.stdinBuffer!.process(data);
240
+ };
241
+ }
242
+
243
+ /**
244
+ * Query terminal for Kitty keyboard protocol support and enable it if available.
245
+ *
246
+ * Kitty's progressive enhancement detection requires requesting the desired
247
+ * flags before querying them. The trailing DA query is a sentinel supported by
248
+ * terminals that do not know Kitty keyboard protocol; receiving DA before a
249
+ * Kitty response enables modifyOtherKeys fallback without a startup timeout.
250
+ *
251
+ * The requested flags are:
252
+ * - 1 = disambiguate escape codes
253
+ * - 2 = report event types (press/repeat/release)
254
+ * - 4 = report alternate keys (shifted key, base layout key)
255
+ */
256
+ private queryAndEnableKittyProtocol(): void {
257
+ this.setupStdinBuffer();
258
+ process.stdin.on("data", this.stdinDataHandler!);
259
+ this.keyboardProtocolPushed = true;
260
+ this.clearKeyboardProtocolNegotiationBuffer();
261
+ process.stdout.write(KITTY_KEYBOARD_PROTOCOL_QUERY);
262
+ }
263
+
264
+ private handleKeyboardProtocolNegotiationSequence(
265
+ negotiationSequence: KeyboardProtocolNegotiationSequence | undefined,
266
+ ): boolean {
267
+ if (!negotiationSequence) return false;
268
+ this.clearKeyboardProtocolNegotiationBuffer();
269
+ if (negotiationSequence.type === "kitty-flags") {
270
+ if (negotiationSequence.flags !== 0) {
271
+ this.disableModifyOtherKeys();
272
+ if (!this._kittyProtocolActive) {
273
+ this._kittyProtocolActive = true;
274
+ setKittyProtocolActive(true);
275
+ }
276
+ } else {
277
+ this.enableModifyOtherKeys();
278
+ }
279
+ return true;
280
+ }
281
+
282
+ if (!this._kittyProtocolActive) {
283
+ this.enableModifyOtherKeys();
284
+ }
285
+ return true;
286
+ }
287
+
288
+ private readKeyboardProtocolNegotiationSequence(
289
+ sequence: string,
290
+ ): KeyboardProtocolNegotiationSequence | "pending" | undefined {
291
+ if (this.keyboardProtocolNegotiationBuffer) {
292
+ const bufferedSequence = this.keyboardProtocolNegotiationBuffer + sequence;
293
+ const negotiationSequence = parseKeyboardProtocolNegotiationSequence(bufferedSequence);
294
+ if (negotiationSequence) {
295
+ this.clearKeyboardProtocolNegotiationBuffer();
296
+ return negotiationSequence;
297
+ }
298
+ if (isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence)) {
299
+ this.setKeyboardProtocolNegotiationBuffer(bufferedSequence);
300
+ return "pending";
301
+ }
302
+ this.flushKeyboardProtocolNegotiationBufferAsInput();
303
+ }
304
+
305
+ const negotiationSequence = parseKeyboardProtocolNegotiationSequence(sequence);
306
+ if (negotiationSequence) return negotiationSequence;
307
+ if (isKeyboardProtocolNegotiationSequencePrefix(sequence)) {
308
+ this.setKeyboardProtocolNegotiationBuffer(sequence);
309
+ return "pending";
310
+ }
311
+ return undefined;
312
+ }
313
+
314
+ private setKeyboardProtocolNegotiationBuffer(sequence: string): void {
315
+ this.clearKeyboardProtocolNegotiationBufferFlushTimer();
316
+ this.keyboardProtocolNegotiationBuffer = sequence;
317
+ }
318
+
319
+ private clearKeyboardProtocolNegotiationBuffer(): void {
320
+ this.clearKeyboardProtocolNegotiationBufferFlushTimer();
321
+ this.keyboardProtocolNegotiationBuffer = "";
322
+ }
323
+
324
+ private flushKeyboardProtocolNegotiationBufferAsInput(): void {
325
+ if (!this.keyboardProtocolNegotiationBuffer) return;
326
+ const sequence = this.keyboardProtocolNegotiationBuffer;
327
+ this.clearKeyboardProtocolNegotiationBuffer();
328
+ this.forwardInputSequence(sequence);
329
+ }
330
+
331
+ private scheduleKeyboardProtocolNegotiationBufferFlush(): void {
332
+ if (!this.keyboardProtocolNegotiationBuffer || this.keyboardProtocolBufferFlushTimer) return;
333
+ this.keyboardProtocolBufferFlushTimer = setTimeout(() => {
334
+ this.keyboardProtocolBufferFlushTimer = undefined;
335
+ this.flushKeyboardProtocolNegotiationBufferAsInput();
336
+ }, KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS);
337
+ }
338
+
339
+ private clearKeyboardProtocolNegotiationBufferFlushTimer(): void {
340
+ if (!this.keyboardProtocolBufferFlushTimer) return;
341
+ clearTimeout(this.keyboardProtocolBufferFlushTimer);
342
+ this.keyboardProtocolBufferFlushTimer = undefined;
343
+ }
344
+
345
+ private forwardInputSequence(sequence: string): void {
346
+ if (!this.inputHandler) return;
347
+ const shouldDetectNativeShiftEnter =
348
+ sequence === "\r" && (isAppleTerminalSession() || process.platform === "win32");
349
+ const input = normalizeNativeShiftEnterInput(
350
+ sequence,
351
+ shouldDetectNativeShiftEnter,
352
+ shouldDetectNativeShiftEnter && isNativeModifierPressed("shift"),
353
+ );
354
+ this.inputHandler(input);
355
+ }
356
+
357
+ private enableModifyOtherKeys(): void {
358
+ if (this._kittyProtocolActive || this._modifyOtherKeysActive) return;
359
+ process.stdout.write("\x1b[>4;2m");
360
+ this._modifyOtherKeysActive = true;
361
+ }
362
+
363
+ private disableModifyOtherKeys(): void {
364
+ if (!this._modifyOtherKeysActive) return;
365
+ process.stdout.write("\x1b[>4;0m");
366
+ this._modifyOtherKeysActive = false;
367
+ }
368
+
369
+ /**
370
+ * On Windows, add ENABLE_VIRTUAL_TERMINAL_INPUT (0x0200) to the stdin
371
+ * console handle so the terminal sends VT sequences for modified keys
372
+ * (e.g. \x1b[Z for Shift+Tab). Without this, libuv's ReadConsoleInputW
373
+ * discards modifier state and Shift+Tab arrives as plain \t.
374
+ */
375
+ private enableWindowsVTInput(): void {
376
+ if (process.platform !== "win32") return;
377
+ try {
378
+ getNativePlatformHelper()?.enableVirtualTerminalInput?.();
379
+ } catch {
380
+ // Native helper not available — Shift+Tab won't be distinguishable from Tab.
381
+ }
382
+ }
383
+
384
+ async drainInput(maxMs = 1000, idleMs = 50): Promise<void> {
385
+ const shouldDisableKittyProtocol = this.keyboardProtocolPushed || this._kittyProtocolActive;
386
+ this.clearKeyboardProtocolNegotiationBuffer();
387
+ if (shouldDisableKittyProtocol) {
388
+ // Disable Kitty keyboard protocol first so any late key releases
389
+ // do not generate new Kitty escape sequences.
390
+ process.stdout.write("\x1b[<u");
391
+ this.keyboardProtocolPushed = false;
392
+ this._kittyProtocolActive = false;
393
+ setKittyProtocolActive(false);
394
+ }
395
+ this.disableModifyOtherKeys();
396
+
397
+ const previousHandler = this.inputHandler;
398
+ this.inputHandler = undefined;
399
+
400
+ let lastDataTime = Date.now();
401
+ const onData = () => {
402
+ lastDataTime = Date.now();
403
+ };
404
+
405
+ process.stdin.on("data", onData);
406
+ const endTime = Date.now() + maxMs;
407
+
408
+ try {
409
+ while (true) {
410
+ const now = Date.now();
411
+ const timeLeft = endTime - now;
412
+ if (timeLeft <= 0) break;
413
+ if (now - lastDataTime >= idleMs) break;
414
+ await new Promise((resolve) => setTimeout(resolve, Math.min(idleMs, timeLeft)));
415
+ }
416
+ } finally {
417
+ process.stdin.removeListener("data", onData);
418
+ this.inputHandler = previousHandler;
419
+ }
420
+ }
421
+
422
+ stop(): void {
423
+ if (this.clearProgressInterval()) {
424
+ process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);
425
+ }
426
+
427
+ // Disable bracketed paste mode
428
+ process.stdout.write("\x1b[?2004l");
429
+
430
+ const shouldDisableKittyProtocol = this.keyboardProtocolPushed || this._kittyProtocolActive;
431
+ this.clearKeyboardProtocolNegotiationBuffer();
432
+
433
+ // Disable Kitty keyboard protocol if not already done by drainInput()
434
+ if (shouldDisableKittyProtocol) {
435
+ process.stdout.write("\x1b[<u");
436
+ this.keyboardProtocolPushed = false;
437
+ this._kittyProtocolActive = false;
438
+ setKittyProtocolActive(false);
439
+ }
440
+ this.disableModifyOtherKeys();
441
+
442
+ // Clean up StdinBuffer
443
+ if (this.stdinBuffer) {
444
+ this.stdinBuffer.destroy();
445
+ this.stdinBuffer = undefined;
446
+ }
447
+
448
+ // Remove event handlers
449
+ if (this.stdinDataHandler) {
450
+ process.stdin.removeListener("data", this.stdinDataHandler);
451
+ this.stdinDataHandler = undefined;
452
+ }
453
+ this.inputHandler = undefined;
454
+ if (this.resizeHandler) {
455
+ process.stdout.removeListener("resize", this.resizeHandler);
456
+ this.resizeHandler = undefined;
457
+ }
458
+
459
+ // Pause stdin to prevent any buffered input (e.g., Ctrl+D) from being
460
+ // re-interpreted after raw mode is disabled. This fixes a race condition
461
+ // where Ctrl+D could close the parent shell over SSH.
462
+ process.stdin.pause();
463
+
464
+ // Restore raw mode state
465
+ if (process.stdin.setRawMode) {
466
+ process.stdin.setRawMode(this.wasRaw);
467
+ }
468
+ }
469
+
470
+ write(data: string): void {
471
+ process.stdout.write(data);
472
+ if (this.writeLogPath) {
473
+ try {
474
+ fs.appendFileSync(this.writeLogPath, data, { encoding: "utf8" });
475
+ } catch {
476
+ // Ignore logging errors
477
+ }
478
+ }
479
+ }
480
+
481
+ get columns(): number {
482
+ return process.stdout.columns || Number(process.env.COLUMNS) || 80;
483
+ }
484
+
485
+ get rows(): number {
486
+ return process.stdout.rows || Number(process.env.LINES) || 24;
487
+ }
488
+
489
+ moveBy(lines: number): void {
490
+ if (lines > 0) {
491
+ // Move down
492
+ process.stdout.write(`\x1b[${lines}B`);
493
+ } else if (lines < 0) {
494
+ // Move up
495
+ process.stdout.write(`\x1b[${-lines}A`);
496
+ }
497
+ // lines === 0: no movement
498
+ }
499
+
500
+ hideCursor(): void {
501
+ process.stdout.write("\x1b[?25l");
502
+ }
503
+
504
+ showCursor(): void {
505
+ process.stdout.write("\x1b[?25h");
506
+ }
507
+
508
+ clearLine(): void {
509
+ process.stdout.write("\x1b[K");
510
+ }
511
+
512
+ clearFromCursor(): void {
513
+ process.stdout.write("\x1b[J");
514
+ }
515
+
516
+ clearScreen(): void {
517
+ process.stdout.write("\x1b[2J\x1b[H"); // Clear screen and move to home (1,1)
518
+ }
519
+
520
+ setTitle(title: string): void {
521
+ // OSC 0;title BEL - set terminal window title
522
+ process.stdout.write(`\x1b]0;${title}\x07`);
523
+ }
524
+
525
+ setProgress(active: boolean): void {
526
+ if (active) {
527
+ // OSC 9;4;3 - indeterminate progress
528
+ process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);
529
+ if (!this.progressInterval) {
530
+ this.progressInterval = setInterval(() => {
531
+ process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);
532
+ }, TERMINAL_PROGRESS_KEEPALIVE_MS);
533
+ }
534
+ } else {
535
+ this.clearProgressInterval();
536
+ // OSC 9;4;0 - clear progress
537
+ process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);
538
+ }
539
+ }
540
+
541
+ private clearProgressInterval(): boolean {
542
+ if (!this.progressInterval) return false;
543
+ clearInterval(this.progressInterval);
544
+ this.progressInterval = undefined;
545
+ return true;
546
+ }
547
+ }