Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NodePtyAdapter.ts

389 lines12.5 KB

1import * as NodeModule from "node:module";
2import * as NodeNet from "node:net";
3​
4import * as Context from "effect/Context";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Path from "effect/Path";
9import * as Schema from "effect/Schema";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11​
12import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
13​
14export class NodePtyModuleLoadError extends Schema.TaggedError<NodePtyModuleLoadError>()(
15 "NodePtyModuleLoadError",
16 {
17 platform: Schema.String,
18 architecture: Schema.String,
19 cause: Schema.Defect(),
20 },
21) {
22 override get message(): string {
23 return `Failed to load node-pty for ${this.platform}-${this.architecture}.`;
24 }
26​
27class NodePtyCancelError extends Schema.TaggedError<NodePtyCancelError>()("NodePtyCancelError", {
28 terminalPid: Schema.Number,
29 cause: Schema.Defect(),
30}) {
31 override get message(): string {
32 return `Failed to cancel Windows terminal startup for ${this.terminalPid}.`;
33 }
35​
36type NodePtyModuleLoader = () => Promise<typeof import("node-pty")>;
37​
38// node-pty's native addon stays external; single-executables need require to resolve disk modules and spawn helpers.
39const requireForNodePty = NodeModule.createRequire(import.meta.url);
40​
41const loadNodePty: NodePtyModuleLoader = () =>
42 Promise.resolve().then(() => requireForNodePty("node-pty") as typeof import("node-pty"));
43​
44export const NodePtyModuleLoaderRef = Context.Reference<NodePtyModuleLoader>(
45 "server/terminal/NodePtyModuleLoader",
46 { defaultValue: () => loadNodePty },
47);
48​
49let didEnsureSpawnHelperExecutable = false;
50​
51const resolveNodePtySpawnHelperPath = Effect.gen(function* () {
52 const path = yield* Path.Path;
53 const fs = yield* FileSystem.FileSystem;
54 const platform = yield* HostProcess.Platform;
55 const architecture = yield* HostProcess.Architecture;
56​
57 const packageJsonPath = requireForNodePty.resolve("node-pty/package.json");
58 const packageDir = path.dirname(packageJsonPath);
59 const candidates = [
60 path.join(packageDir, "build", "Release", "spawn-helper"),
61 path.join(packageDir, "build", "Debug", "spawn-helper"),
62 path.join(packageDir, "prebuilds", `${platform}-${architecture}`, "spawn-helper"),
63 ];
64​
65 for (const candidate of candidates) {
66 if (yield* fs.exists(candidate)) {
67 return candidate;
68 }
69 }
70 return null;
71}).pipe(Effect.orElseSucceed(() => null));
72​
73const ensureNodePtySpawnHelperExecutable = Effect.fn(function* () {
74 const fs = yield* FileSystem.FileSystem;
75 const platform = yield* HostProcess.Platform;
76 if (platform === "win32") return;
77 if (didEnsureSpawnHelperExecutable) return;
78​
79 const helperPath = yield* resolveNodePtySpawnHelperPath;
80 if (helperPath && (yield* fs.exists(helperPath))) {
81 yield* fs.chmod(helperPath, 0o755).pipe(Effect.orElseSucceed(() => undefined));
82 }
83 // Set only after the repair finishes, so a check cut off by the spawn deadline runs again.
84 didEnsureSpawnHelperExecutable = true;
85});
86​
87// node-pty has no public readiness event; ready_datapipe sets pid before our listener.
88// Deferred pipe creation: https://github.com/microsoft/node-pty/pull/885
89const waitForWindowsPid = (
90 process: import("node-pty").IPty,
91 trackedProcess: NodePtyProcess,
92 shell: string,
93) =>
94 Effect.callback<void, PtyAdapter.PtySpawnError>((resume) => {
95 const hasPid = () => Number.isInteger(process.pid) && process.pid > 0;
96 const failure = (cause: unknown) =>
97 Effect.fail(new PtyAdapter.PtySpawnError({ adapter: "node-pty", shell, cause }));
98​
99 if (hasPid()) {
100 resume(Effect.void);
101 return;
102 }
103​
104 if (!("_socket" in process) || !(process._socket instanceof NodeNet.Socket)) {
105 resume(failure(new Error("Windows PTY readiness socket is unavailable.")));
106 return;
107 }
108​
109 const socket = process._socket;
110 const onReady = () => {
111 cleanup();
112 resume(
113 hasPid()
114 ? Effect.void
115 : failure(new Error("Windows PTY became ready without a valid PID.")),
116 );
117 };
118 const onError = (cause: Error) => {
119 cleanup();
120 resume(failure(cause));
121 };
122 const onClose = () => onError(new Error("Windows PTY closed before its PID was available."));
123 let stopExit = () => {};
124 const cleanup = () => {
125 socket.off("ready_datapipe", onReady);
126 socket.off("error", onError);
127 socket.off("close", onClose);
128 stopExit();
129 };
130 socket.once("ready_datapipe", onReady);
131 socket.once("error", onError);
132 socket.once("close", onClose);
133 stopExit = trackedProcess.onExit(({ exitCode }) =>
134 onError(
135 new Error(`Windows PTY exited before its PID was available (exit code ${exitCode}).`),
136 ),
137 );
138 return Effect.sync(cleanup);
139 });
140​
141// The private agent cancels pending connections before a child exists; public kill waits for first output.
142const killStartingWindowsPty = (process: import("node-pty").IPty) =>
143 Effect.try({
144 try: () => {
145 if (
146 "_agent" in process &&
147 typeof process._agent === "object" &&
148 process._agent !== null &&
149 "kill" in process._agent &&
150 typeof process._agent.kill === "function"
151 ) {
152 process._agent.kill();
153 } else {
154 process.kill();
155 }
156 },
157 catch: (cause) => new NodePtyCancelError({ terminalPid: process.pid, cause }),
158 }).pipe(
159 Effect.catch((error) =>
160 Effect.logWarning("failed to cancel Windows terminal startup", {
161 terminalPid: process.pid,
162 cause: error,
163 }),
164 ),
165 );
166​
167const MAX_PENDING_STARTUP_SEQUENCE = 256;
168const LEADING_STARTUP_SEQUENCE =
169 /^(?:\u001b\[[\x20-\x3f]*[\x40-\x7e]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\))/;
170const INCOMPLETE_STARTUP_SEQUENCE = /^\u001b(?:\[[\x20-\x3f]*|\][^\u0007\u001b]*\u001b?)?$/;
171​
172const isAlternateScreenEnter = (sequence: string) =>
173 sequence.startsWith("\u001b[?") &&
174 sequence.endsWith("h") &&
175 sequence
176 .slice(3, -1)
177 .split(";")
178 .some((part) => {
179 const mode = Number(part);
180 return mode === 47 || mode === 1047 || mode === 1049;
181 });
182​
183// ConPTY initializes every new PTY with CSI 2 J, which erases active viewport rows in place
184// instead of scrolling them into scrollback, wiping the tail of restored session history.
185// Rewriting that initial erase to CSI 22 J preserves active rows in scrollback on Ghostty
186// while remaining a no-op on an empty screen.
187function createWindowsInitialClearRewriter() {
188 let done = false;
189 let pending = "";
190​
191 const push = (chunk: string): string => {
192 if (done) return chunk;
193 const input = pending + chunk;
194 pending = "";
195 let index = 0;
196​
197 while (index < input.length) {
198 const rest = input.slice(index);
199 const match = LEADING_STARTUP_SEQUENCE.exec(rest);
200 if (match) {
201 const sequence = match[0];
202 if (sequence === "\u001b[2J") {
203 done = true;
204 return `${input.slice(0, index)}\u001b[22J${input.slice(index + sequence.length)}`;
205 }
206 if (isAlternateScreenEnter(sequence)) {
207 done = true;
208 return input;
209 }
210 index += sequence.length;
211 continue;
212 }
213 if (rest.length <= MAX_PENDING_STARTUP_SEQUENCE && INCOMPLETE_STARTUP_SEQUENCE.test(rest)) {
214 pending = rest;
215 return input.slice(0, index);
216 }
217 done = true;
218 return input;
219 }
220​
221 return input;
222 };
223​
224 const flush = (): string => {
225 done = true;
226 const remainder = pending;
227 pending = "";
228 return remainder;
229 };
230​
231 return { push, flush };
233​
234class NodePtyProcess implements PtyAdapter.PtyProcess {
235 private readonly process: import("node-pty").IPty;
236 private readonly platform: NodeJS.Platform;
237 private exitEvent: PtyAdapter.PtyExitEvent | undefined;
238 private readonly dataFlushers = new Set<() => void>();
239 private readonly exitListeners = new Set<(event: PtyAdapter.PtyExitEvent) => void>();
240 private readonly exitSubscription: import("node-pty").IDisposable;
241​
242 constructor(process: import("node-pty").IPty, platform: NodeJS.Platform) {
243 this.process = process;
244 this.platform = platform;
245 this.exitSubscription = process.onExit((event) => {
246 if (this.exitEvent) return;
247 this.exitEvent = { exitCode: event.exitCode, signal: event.signal ?? null };
248 this.exitSubscription.dispose();
249 for (const flush of this.dataFlushers) flush();
250 this.dataFlushers.clear();
251 for (const listener of this.exitListeners) listener(this.exitEvent);
252 this.exitListeners.clear();
253 });
254 }
255​
256 get pid(): number {
257 return this.process.pid;
258 }
259​
260 get device(): string | undefined {
261 return "ptsName" in this.process && typeof this.process.ptsName === "string"
262 ? this.process.ptsName
263 : undefined;
264 }
265​
266 write(data: string | Buffer): void {
267 this.process.write(data);
268 }
269​
270 resize(cols: number, rows: number): void {
271 this.process.resize(cols, rows);
272 }
273​
274 kill(signal?: string): void {
275 // node-pty terminates the Windows process tree without a POSIX signal.
276 this.process.kill(this.platform === "win32" ? undefined : signal);
277 }
278​
279 onData(callback: (data: string) => void): () => void {
280 if (this.platform !== "win32") {
281 const disposable = this.process.onData(callback);
282 return () => {
283 disposable.dispose();
284 };
285 }
286​
287 const rewriter = createWindowsInitialClearRewriter();
288 const flush = () => {
289 const tail = rewriter.flush();
290 if (tail.length > 0) callback(tail);
291 };
292 this.dataFlushers.add(flush);
293 const disposable = this.process.onData((data) => {
294 const rewritten = rewriter.push(data);
295 if (rewritten.length > 0) callback(rewritten);
296 });
297 return () => {
298 this.dataFlushers.delete(flush);
299 disposable.dispose();
300 };
301 }
302​
303 onExit(callback: (event: PtyAdapter.PtyExitEvent) => void): () => void {
304 if (this.exitEvent) {
305 callback(this.exitEvent);
306 return () => {};
307 }
308 this.exitListeners.add(callback);
309 return () => {
310 this.exitListeners.delete(callback);
311 };
312 }
313​
314 disposeExitSubscription(): void {
315 this.exitSubscription.dispose();
316 this.dataFlushers.clear();
317 this.exitListeners.clear();
318 }
320​
321const make = Effect.fn("NodePtyAdapter.make")(function* () {
322 const loadNodePtyModule = yield* NodePtyModuleLoaderRef;
323 const fs = yield* FileSystem.FileSystem;
324 const path = yield* Path.Path;
325 const platform = yield* HostProcess.Platform;
326 const architecture = yield* HostProcess.Architecture;
327​
328 const nodePty = yield* Effect.tryPromise({
329 try: loadNodePtyModule,
330 catch: (cause) =>
331 new NodePtyModuleLoadError({
332 platform,
333 architecture,
334 cause,
335 }),
336 }).pipe(Effect.orDie);
337​
338 const ensureSpawnHelperExecutable = ensureNodePtySpawnHelperExecutable().pipe(
339 Effect.provideService(FileSystem.FileSystem, fs),
340 Effect.provideService(Path.Path, path),
341 Effect.provideService(HostProcess.Platform, platform),
342 Effect.provideService(HostProcess.Architecture, architecture),
343 Effect.orElseSucceed(() => undefined),
344 // Terminal startup runs uninterruptibly; a stalled helper check must not hold its locks.
345 Effect.interruptible,
346 Effect.timeoutOrElse({ duration: "5 seconds", orElse: () => Effect.void }),
347 );
348​
349 return PtyAdapter.PtyAdapter.of({
350 spawn: Effect.fn("NodePtyAdapter.spawn")(function* (input) {
351 yield* ensureSpawnHelperExecutable;
352 // ConPTY ignores node-pty's name option for TERM; set it explicitly to avoid missing/16-color values.
353 const env =
354 platform === "win32" && input.env["TERM"] === undefined
355 ? { ...input.env, TERM: "xterm-256color" }
356 : input.env;
357 const ptyProcess = yield* Effect.try({
358 try: () => {
359 const nativeProcess = nodePty.spawn(input.shell, input.args ?? [], {
360 cwd: input.cwd,
361 cols: input.cols,
362 rows: input.rows,
363 env,
364 name: "xterm-256color",
365 });
366 return { nativeProcess, process: new NodePtyProcess(nativeProcess, platform) };
367 },
368 catch: (cause) =>
369 new PtyAdapter.PtySpawnError({
370 adapter: "node-pty",
371 shell: input.shell,
372 cause,
373 }),
374 });
375 if (platform === "win32") {
376 yield* waitForWindowsPid(ptyProcess.nativeProcess, ptyProcess.process, input.shell).pipe(
377 Effect.onError(() =>
378 Effect.sync(() => ptyProcess.process.disposeExitSubscription()).pipe(
379 Effect.andThen(killStartingWindowsPty(ptyProcess.nativeProcess)),
380 ),
381 ),
382 );
383 }
384 return ptyProcess.process;
385 }),
386 });
387});
388​
389export const layer = Layer.effect(PtyAdapter.PtyAdapter, make());