Open History to see the last commit
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 }
25}
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 }
34}
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
167class NodePtyProcess implements PtyAdapter.PtyProcess {
168 private readonly process: import("node-pty").IPty;
169 private readonly platform: NodeJS.Platform;
170 private exitEvent: PtyAdapter.PtyExitEvent | undefined;
171 private readonly exitListeners = new Set<(event: PtyAdapter.PtyExitEvent) => void>();
172 private readonly exitSubscription: import("node-pty").IDisposable;
173
174 constructor(process: import("node-pty").IPty, platform: NodeJS.Platform) {
175 this.process = process;
176 this.platform = platform;
177 this.exitSubscription = process.onExit((event) => {
178 if (this.exitEvent) return;
179 this.exitEvent = { exitCode: event.exitCode, signal: event.signal ?? null };
180 this.exitSubscription.dispose();
181 for (const listener of this.exitListeners) listener(this.exitEvent);
182 this.exitListeners.clear();
183 });
184 }
185
186 get pid(): number {
187 return this.process.pid;
188 }
189
190 write(data: string | Buffer): void {
191 this.process.write(data);
192 }
193
194 resize(cols: number, rows: number): void {
195 this.process.resize(cols, rows);
196 }
197
198 kill(signal?: string): void {
199 // node-pty terminates the Windows process tree without a POSIX signal.
200 this.process.kill(this.platform === "win32" ? undefined : signal);
201 }
202
203 onData(callback: (data: string) => void): () => void {
204 const disposable = this.process.onData(callback);
205 return () => {
206 disposable.dispose();
207 };
208 }
209
210 onExit(callback: (event: PtyAdapter.PtyExitEvent) => void): () => void {
211 if (this.exitEvent) {
212 callback(this.exitEvent);
213 return () => {};
214 }
215 this.exitListeners.add(callback);
216 return () => {
217 this.exitListeners.delete(callback);
218 };
219 }
220
221 disposeExitSubscription(): void {
222 this.exitSubscription.dispose();
223 this.exitListeners.clear();
224 }
225}
226
227const make = Effect.fn("NodePtyAdapter.make")(function* () {
228 const loadNodePtyModule = yield* NodePtyModuleLoaderRef;
229 const fs = yield* FileSystem.FileSystem;
230 const path = yield* Path.Path;
231 const platform = yield* HostProcess.Platform;
232 const architecture = yield* HostProcess.Architecture;
233
234 const nodePty = yield* Effect.tryPromise({
235 try: loadNodePtyModule,
236 catch: (cause) =>
237 new NodePtyModuleLoadError({
238 platform,
239 architecture,
240 cause,
241 }),
242 }).pipe(Effect.orDie);
243
244 const ensureSpawnHelperExecutable = ensureNodePtySpawnHelperExecutable().pipe(
245 Effect.provideService(FileSystem.FileSystem, fs),
246 Effect.provideService(Path.Path, path),
247 Effect.provideService(HostProcess.Platform, platform),
248 Effect.provideService(HostProcess.Architecture, architecture),
249 Effect.orElseSucceed(() => undefined),
250 // Terminal startup runs uninterruptibly; a stalled helper check must not hold its locks.
251 Effect.interruptible,
252 Effect.timeoutOrElse({ duration: "5 seconds", orElse: () => Effect.void }),
253 );
254
255 return PtyAdapter.PtyAdapter.of({
256 spawn: Effect.fn("NodePtyAdapter.spawn")(function* (input) {
257 yield* ensureSpawnHelperExecutable;
258 // ConPTY ignores node-pty's name option for TERM; set it explicitly to avoid missing/16-color values.
259 const env =
260 platform === "win32" && input.env["TERM"] === undefined
261 ? { ...input.env, TERM: "xterm-256color" }
262 : input.env;
263 const ptyProcess = yield* Effect.try({
264 try: () => {
265 const nativeProcess = nodePty.spawn(input.shell, input.args ?? [], {
266 cwd: input.cwd,
267 cols: input.cols,
268 rows: input.rows,
269 env,
270 name: "xterm-256color",
271 });
272 return { nativeProcess, process: new NodePtyProcess(nativeProcess, platform) };
273 },
274 catch: (cause) =>
275 new PtyAdapter.PtySpawnError({
276 adapter: "node-pty",
277 shell: input.shell,
278 cause,
279 }),
280 });
281 if (platform === "win32") {
282 yield* waitForWindowsPid(ptyProcess.nativeProcess, ptyProcess.process, input.shell).pipe(
283 Effect.onError(() =>
284 Effect.sync(() => ptyProcess.process.disposeExitSubscription()).pipe(
285 Effect.andThen(killStartingWindowsPty(ptyProcess.nativeProcess)),
286 ),
287 ),
288 );
289 }
290 return ptyProcess.process;
291 }),
292 });
293});
294
295export const layer = Layer.effect(PtyAdapter.PtyAdapter, make());