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

NodePtyAdapter.ts

285 lines9.1 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​
27type NodePtyModuleLoader = () => Promise<typeof import("node-pty")>;
28​
29// node-pty's native addon stays external; single-executables need require to resolve disk modules and spawn helpers.
30const requireForNodePty = NodeModule.createRequire(import.meta.url);
31​
32const loadNodePty: NodePtyModuleLoader = () =>
33 Promise.resolve().then(() => requireForNodePty("node-pty") as typeof import("node-pty"));
34​
35export const NodePtyModuleLoaderRef = Context.Reference<NodePtyModuleLoader>(
36 "server/terminal/NodePtyModuleLoader",
37 { defaultValue: () => loadNodePty },
38);
39​
40let didEnsureSpawnHelperExecutable = false;
41​
42const resolveNodePtySpawnHelperPath = Effect.gen(function* () {
43 const path = yield* Path.Path;
44 const fs = yield* FileSystem.FileSystem;
45 const platform = yield* HostProcess.Platform;
46 const architecture = yield* HostProcess.Architecture;
47​
48 const packageJsonPath = requireForNodePty.resolve("node-pty/package.json");
49 const packageDir = path.dirname(packageJsonPath);
50 const candidates = [
51 path.join(packageDir, "build", "Release", "spawn-helper"),
52 path.join(packageDir, "build", "Debug", "spawn-helper"),
53 path.join(packageDir, "prebuilds", `${platform}-${architecture}`, "spawn-helper"),
54 ];
55​
56 for (const candidate of candidates) {
57 if (yield* fs.exists(candidate)) {
58 return candidate;
59 }
60 }
61 return null;
62}).pipe(Effect.orElseSucceed(() => null));
63​
64const ensureNodePtySpawnHelperExecutable = Effect.fn(function* () {
65 const fs = yield* FileSystem.FileSystem;
66 const platform = yield* HostProcess.Platform;
67 if (platform === "win32") return;
68 if (didEnsureSpawnHelperExecutable) return;
69​
70 const helperPath = yield* resolveNodePtySpawnHelperPath;
71 if (!helperPath) return;
72 didEnsureSpawnHelperExecutable = true;
73​
74 if (!(yield* fs.exists(helperPath))) {
75 return;
76 }
77​
78 yield* fs.chmod(helperPath, 0o755).pipe(Effect.orElseSucceed(() => undefined));
79});
80​
81// node-pty has no public readiness event; ready_datapipe sets pid before our listener.
82// Deferred pipe creation: https://github.com/microsoft/node-pty/pull/885
83const waitForWindowsPid = (
84 process: import("node-pty").IPty,
85 trackedProcess: NodePtyProcess,
86 shell: string,
87) =>
88 Effect.callback<void, PtyAdapter.PtySpawnError>((resume) => {
89 const hasPid = () => Number.isInteger(process.pid) && process.pid > 0;
90 const failure = (cause: unknown) =>
91 Effect.fail(new PtyAdapter.PtySpawnError({ adapter: "node-pty", shell, cause }));
92​
93 if (hasPid()) {
94 resume(Effect.void);
95 return;
96 }
97​
98 if (!("_socket" in process) || !(process._socket instanceof NodeNet.Socket)) {
99 resume(failure(new Error("Windows PTY readiness socket is unavailable.")));
100 return;
101 }
102​
103 const socket = process._socket;
104 const onReady = () => {
105 cleanup();
106 resume(
107 hasPid()
108 ? Effect.void
109 : failure(new Error("Windows PTY became ready without a valid PID.")),
110 );
111 };
112 const onError = (cause: Error) => {
113 cleanup();
114 resume(failure(cause));
115 };
116 const onClose = () => onError(new Error("Windows PTY closed before its PID was available."));
117 let stopExit = () => {};
118 const cleanup = () => {
119 socket.off("ready_datapipe", onReady);
120 socket.off("error", onError);
121 socket.off("close", onClose);
122 stopExit();
123 };
124 socket.once("ready_datapipe", onReady);
125 socket.once("error", onError);
126 socket.once("close", onClose);
127 stopExit = trackedProcess.onExit(({ exitCode }) =>
128 onError(
129 new Error(`Windows PTY exited before its PID was available (exit code ${exitCode}).`),
130 ),
131 );
132 return Effect.sync(cleanup);
133 });
134​
135// The private agent cancels pending connections before a child exists; public kill waits for first output.
136const killStartingWindowsPty = (process: import("node-pty").IPty) =>
137 Effect.try(() => {
138 if (
139 "_agent" in process &&
140 typeof process._agent === "object" &&
141 process._agent !== null &&
142 "kill" in process._agent &&
143 typeof process._agent.kill === "function"
144 ) {
145 process._agent.kill();
146 } else {
147 process.kill();
148 }
149 }).pipe(
150 Effect.catch((error) =>
151 Effect.logWarning("failed to cancel Windows terminal startup", {
152 terminalPid: process.pid,
153 cause: error,
154 }),
155 ),
156 );
157​
158class NodePtyProcess implements PtyAdapter.PtyProcess {
159 private readonly process: import("node-pty").IPty;
160 private readonly platform: NodeJS.Platform;
161 private exitEvent: PtyAdapter.PtyExitEvent | undefined;
162 private readonly exitListeners = new Set<(event: PtyAdapter.PtyExitEvent) => void>();
163 private readonly exitSubscription: import("node-pty").IDisposable;
164​
165 constructor(process: import("node-pty").IPty, platform: NodeJS.Platform) {
166 this.process = process;
167 this.platform = platform;
168 this.exitSubscription = process.onExit((event) => {
169 if (this.exitEvent) return;
170 this.exitEvent = { exitCode: event.exitCode, signal: event.signal ?? null };
171 this.exitSubscription.dispose();
172 for (const listener of this.exitListeners) listener(this.exitEvent);
173 this.exitListeners.clear();
174 });
175 }
176​
177 get pid(): number {
178 return this.process.pid;
179 }
180​
181 write(data: string): void {
182 this.process.write(data);
183 }
184​
185 resize(cols: number, rows: number): void {
186 this.process.resize(cols, rows);
187 }
188​
189 kill(signal?: string): void {
190 // node-pty terminates the Windows process tree without a POSIX signal.
191 this.process.kill(this.platform === "win32" ? undefined : signal);
192 }
193​
194 onData(callback: (data: string) => void): () => void {
195 const disposable = this.process.onData(callback);
196 return () => {
197 disposable.dispose();
198 };
199 }
200​
201 onExit(callback: (event: PtyAdapter.PtyExitEvent) => void): () => void {
202 if (this.exitEvent) {
203 callback(this.exitEvent);
204 return () => {};
205 }
206 this.exitListeners.add(callback);
207 return () => {
208 this.exitListeners.delete(callback);
209 };
210 }
211​
212 disposeExitSubscription(): void {
213 this.exitSubscription.dispose();
214 this.exitListeners.clear();
215 }
217​
218const make = Effect.fn("NodePtyAdapter.make")(function* () {
219 const loadNodePtyModule = yield* NodePtyModuleLoaderRef;
220 const fs = yield* FileSystem.FileSystem;
221 const path = yield* Path.Path;
222 const platform = yield* HostProcess.Platform;
223 const architecture = yield* HostProcess.Architecture;
224​
225 const nodePty = yield* Effect.tryPromise({
226 try: loadNodePtyModule,
227 catch: (cause) =>
228 new NodePtyModuleLoadError({
229 platform,
230 architecture,
231 cause,
232 }),
233 }).pipe(Effect.orDie);
234​
235 const ensureNodePtySpawnHelperExecutableCached = yield* Effect.cached(
236 ensureNodePtySpawnHelperExecutable().pipe(
237 Effect.provideService(FileSystem.FileSystem, fs),
238 Effect.provideService(Path.Path, path),
239 Effect.provideService(HostProcess.Platform, platform),
240 Effect.provideService(HostProcess.Architecture, architecture),
241 Effect.orElseSucceed(() => undefined),
242 ),
243 );
244​
245 return PtyAdapter.PtyAdapter.of({
246 spawn: Effect.fn("NodePtyAdapter.spawn")(function* (input) {
247 yield* ensureNodePtySpawnHelperExecutableCached;
248 // ConPTY ignores node-pty's name option for TERM; set it explicitly to avoid missing/16-color values.
249 const env =
250 platform === "win32" && input.env["TERM"] === undefined
251 ? { ...input.env, TERM: "xterm-256color" }
252 : input.env;
253 const ptyProcess = yield* Effect.try({
254 try: () => {
255 const nativeProcess = nodePty.spawn(input.shell, input.args ?? [], {
256 cwd: input.cwd,
257 cols: input.cols,
258 rows: input.rows,
259 env,
260 name: "xterm-256color",
261 });
262 return { nativeProcess, process: new NodePtyProcess(nativeProcess, platform) };
263 },
264 catch: (cause) =>
265 new PtyAdapter.PtySpawnError({
266 adapter: "node-pty",
267 shell: input.shell,
268 cause,
269 }),
270 });
271 if (platform === "win32") {
272 yield* waitForWindowsPid(ptyProcess.nativeProcess, ptyProcess.process, input.shell).pipe(
273 Effect.onError(() =>
274 Effect.sync(() => ptyProcess.process.disposeExitSubscription()).pipe(
275 Effect.andThen(killStartingWindowsPty(ptyProcess.nativeProcess)),
276 ),
277 ),
278 );
279 }
280 return ptyProcess.process;
281 }),
282 });
283});
284​
285export const layer = Layer.effect(PtyAdapter.PtyAdapter, make());