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

NodePtyAdapter.ts

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