Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - the Claude SDK's spawn hook takes a ChildProcess-shaped object.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeEvents from "node:events";
4import * as NodeStream from "node:stream";
5
6import * as EffectNodeStream from "@effect/platform-node/NodeStream";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as Stream from "effect/Stream";
10import * as ChildProcess from "effect/process/ChildProcess";
11import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12
13export interface LaunchOptions {
14 readonly cwd?: string | undefined;
15 readonly env?: NodeJS.ProcessEnv | undefined;
16 readonly signal?: AbortSignal | undefined;
17 readonly detached?: boolean | undefined;
18 /** One entry per fd; piped fds past 2 are written by the caller. */
19 readonly stdio: ReadonlyArray<"pipe" | "ignore">;
20}
21
22export type Spawn = (
23 command: string,
24 args: ReadonlyArray<string>,
25 options: LaunchOptions,
26) => NodeChildProcess.ChildProcess | LaunchedChild;
27
28export const spawnNative: Spawn = (command, args, options) =>
29 NodeChildProcess.spawn(command, args, { ...options, stdio: [...options.stdio] });
30
31// Effect reports a signal exit only as this message.
32const SIGNAL_EXIT = /receipt of signal: '(SIG[A-Z0-9]+)'/;
33
34/** A ChildProcess whose streams exist at once and connect when the command starts. */
35class LaunchedChild extends NodeEvents.EventEmitter {
36 pid: number | undefined;
37 exitCode: number | null = null;
38 signalCode: NodeJS.Signals | null = null;
39 killed = false;
40 readonly stdio: ReadonlyArray<NodeStream.PassThrough | null>;
41 pendingSignal: NodeJS.Signals | undefined;
42
43 constructor(stdio: LaunchOptions["stdio"]) {
44 super();
45 this.stdio = stdio.map((mode) => (mode === "pipe" ? new NodeStream.PassThrough() : null));
46 }
47
48 get stdin() {
49 return this.stdio[0] ?? null;
50 }
51
52 get stdout() {
53 return this.stdio[1] ?? null;
54 }
55
56 get stderr() {
57 return this.stdio[2] ?? null;
58 }
59
60 kill(signal: NodeJS.Signals = "SIGTERM"): boolean {
61 if (this.exitCode !== null || this.signalCode !== null) return false;
62 this.killed = true;
63 if (this.pid === undefined) {
64 this.pendingSignal = signal;
65 return true;
66 }
67 try {
68 process.kill(this.pid, signal);
69 return true;
70 } catch {
71 return false;
72 }
73 }
74}
75
76// Output is always read, as a ChildProcess pipe would be; a destroyed reader discards it.
77const write = (target: NodeStream.PassThrough, chunk: Uint8Array) =>
78 Effect.callback<void>((resume) => {
79 if (target.destroyed || target.write(chunk)) return resume(Effect.void);
80 const done = () => {
81 target.off("drain", done).off("close", done);
82 resume(Effect.void);
83 };
84 target.on("drain", done).on("close", done);
85 });
86
87/**
88 * A `child_process.spawn` for callers that must hold the child at once, such as the Claude
89 * SDK's spawn hook, that starts the command through `spawner`. On Linux the server's spawner is
90 * the process launcher, so the server is never forked. `pid` is set when "spawn" fires.
91 */
92export const makeLaunch =
93 (spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]): Spawn =>
94 (command, args, options) => {
95 const child = new LaunchedChild(options.stdio);
96 const { signal } = options;
97 const abort = () => child.kill();
98 if (signal?.aborted) child.kill();
99 else signal?.addEventListener("abort", abort, { once: true });
100 const inputs = child.stdio.flatMap((stream, fd) =>
101 stream !== null && fd !== 1 && fd !== 2 ? [[fd, stream] as const] : [],
102 );
103 const launch = Effect.gen(function* () {
104 const handle = yield* spawner.spawn(
105 ChildProcess.make(command, args, {
106 cwd: options.cwd,
107 env: options.env,
108 detached: options.detached ?? false,
109 stdin: options.stdio[0] ?? "ignore",
110 stdout: options.stdio[1] ?? "ignore",
111 stderr: options.stdio[2] ?? "ignore",
112 additionalFds: Object.fromEntries(
113 inputs.filter(([fd]) => fd > 2).map(([fd]) => [`fd${fd}`, { type: "input" as const }]),
114 ),
115 }),
116 );
117 for (const [fd, stream] of inputs) {
118 // Like a closed pipe, a failed input discards what is written after it.
119 yield* Stream.run(
120 EffectNodeStream.fromReadable({ evaluate: () => stream, onError: () => undefined }),
121 fd === 0 ? handle.stdin : handle.getInputFd(fd),
122 ).pipe(
123 Effect.catch(() => Effect.sync(() => stream.resume())),
124 Effect.forkScoped,
125 );
126 }
127 const outputs = yield* Effect.forEach(
128 [
129 [handle.stdout, child.stdout],
130 [handle.stderr, child.stderr],
131 ] as const,
132 ([output, target]) =>
133 target === null
134 ? Effect.void
135 : Stream.runForEach(output, (chunk) => write(target, chunk)).pipe(
136 Effect.ignore,
137 Effect.ensuring(Effect.sync(() => target.end())),
138 ),
139 { concurrency: "unbounded", discard: true },
140 ).pipe(Effect.forkScoped);
141 child.pid = handle.pid;
142 child.emit("spawn");
143 if (child.pendingSignal !== undefined) child.kill(child.pendingSignal);
144 const [code, exitSignal] = yield* handle.exitCode.pipe(
145 Effect.map((code): [number | null, NodeJS.Signals | null] => [code, null]),
146 Effect.catch((error) =>
147 Effect.succeed<[number | null, NodeJS.Signals | null]>([
148 null,
149 (SIGNAL_EXIT.exec(String((error.cause as Error | undefined)?.message))?.[1] ??
150 "SIGKILL") as NodeJS.Signals,
151 ]),
152 ),
153 );
154 signal?.removeEventListener("abort", abort);
155 child.exitCode = code;
156 child.signalCode = exitSignal;
157 // Node destroys a child's stdin on exit; ending each input closes its pipe.
158 for (const [, stream] of inputs) stream.end();
159 child.emit("exit", code, exitSignal);
160 yield* Fiber.await(outputs);
161 }).pipe(
162 Effect.scoped,
163 Effect.catch((error) =>
164 Effect.sync(() => {
165 signal?.removeEventListener("abort", abort);
166 for (const stream of child.stdio) stream?.end();
167 child.emit("error", error.cause instanceof Error ? error.cause : error);
168 }),
169 ),
170 );
171 Effect.runFork(launch);
172 return child;
173 };