The best way to control Claude Code, Codex and more from any computer or phone

main
ts 929 lines 33.2 KB
Raw
1 /**
2 * Shared Node.js implementation of the child process spawner service.
3 *
4 * This module adapts `node:child_process.spawn` to the Effect
5 * `ChildProcessSpawner` service. Provide {@link layer} to run `ChildProcess`
6 * commands in Node-compatible runtimes: commands get scoped process handles
7 * with stdin sinks, stdout and stderr streams, exit-code waiting,
8 * interruption-time cleanup, process killing, and custom file-descriptor pipes.
9 *
10 * The implementation sits below the command-building API. It validates and
11 * resolves `cwd` through the Effect `FileSystem` and `Path` services,
12 * translates Node errno failures to `PlatformError`, and uses scopes to
13 * terminate referenced children when the owning effect is interrupted or
14 * finalized. Pipelines are flattened by {@link flattenCommand} and spawned one
15 * process at a time, wiring the selected source stream (`stdout`, `stderr`,
16 * `all`, or `fdN`) to the destination `stdin` or `fdN`.
17 *
18 * Scoped release and `kill` wait for the signalled process group. Without
19 * `forceKillAfter`, cleanup waits for the leader to exit with no time limit,
20 * then gives remaining group members up to one second to exit, without
21 * escalating.
22 * With it, cleanup may take the configured duration plus a final one-second
23 * wait after `SIGKILL`. Zombie descendants can consume either full bound. On
24 * Windows, `taskkill` terminates the tree while the leader is running, and
25 * cleanup waits only for the leader's exit. Descendants that outlive the
26 * leader are left running.
27 *
28 * POSIX cleanup targets a numeric process-group ID. If the group disappears
29 * and its ID is reused before cleanup, an unrelated group may be signalled.
30 *
31 * @stability unstable
32 * @since 4.0.0
33 */
34 import type * as Arr from "effect/Array"
35 import * as Deferred from "effect/Deferred"
36 import * as Duration from "effect/Duration"
37 import * as Effect from "effect/Effect"
38 import * as Exit from "effect/Exit"
39 import * as FileSystem from "effect/FileSystem"
40 import * as Layer from "effect/Layer"
41 import * as Path from "effect/Path"
42 import * as PlatformError from "effect/PlatformError"
43 import * as Predicate from "effect/Predicate"
44 import * as ChildProcess from "effect/process/ChildProcess"
45 import type { ChildProcessHandle } from "effect/process/ChildProcessSpawner"
46 import {
47 ChildProcessSpawner,
48 ExitCode,
49 make as makeSpawner,
50 makeHandle,
51 ProcessId
52 } from "effect/process/ChildProcessSpawner"
53 import * as CommandLine from "effect/process/CommandLine"
54 import * as Redacted from "effect/Redacted"
55 import type * as Scope from "effect/Scope"
56 import * as Sink from "effect/Sink"
57 import * as Stream from "effect/Stream"
58 import * as NodeChildProcess from "node:child_process"
59 import { PassThrough, type Writable } from "node:stream"
60 import { buildSpawnOptions } from "./internal/nodeChildProcessSpawner.ts"
61 import { handleErrnoException } from "./internal/utils.ts"
62 import * as NodeSink from "./NodeSink.ts"
63 import * as NodeStream from "./NodeStream.ts"
64
65 const toError = (error: unknown): Error =>
66 error instanceof globalThis.Error
67 ? error
68 : new globalThis.Error(String(error))
69
70 const toPlatformError = (
71 method: string,
72 error: NodeJS.ErrnoException,
73 command: ChildProcess.Command
74 ): PlatformError.PlatformError => {
75 const { commands } = flattenCommand(command)
76 const format = globalThis.process.platform === "win32" ? "windows" : "posix"
77 const commandStr = commands.map((cmd) => CommandLine.display([cmd.command, ...cmd.args], { format })).join(" | ")
78 return handleErrnoException("ChildProcess", method)(error, [commandStr])
79 }
80
81 const unwrap = (value: string | Redacted.Redacted<string>): string =>
82 Redacted.isRedacted(value) ? Redacted.value(value) : value
83
84 // Node's own NUL check throws an error that includes the value, so NUL is
85 // rejected here to keep Redacted values out of errors.
86 const findNulCharacter = (command: ChildProcess.StandardCommand): string | undefined => {
87 if (command.command.includes("\0")) return "The command contains a NUL character"
88 const index = command.args.findIndex((arg) => unwrap(arg).includes("\0"))
89 if (index !== -1) return `Argument ${index + 1} contains a NUL character`
90 for (const [name, value] of Object.entries(command.options.env ?? {})) {
91 if (value !== undefined && unwrap(value).includes("\0")) {
92 return `The environment variable ${name} contains a NUL character`
93 }
94 }
95 return undefined
96 }
97
98 type ExitCodeWithSignal = readonly [code: number | null, signal: NodeJS.Signals | null]
99 type ExitSignal = Deferred.Deferred<ExitCodeWithSignal>
100
101 const processGroupGraceMillis = 1_000
102 const processGroupPollIntervalMillis = 10
103
104 // Buffered writes can fail after the sink has been interrupted and removed its
105 // error listener. Keep a fallback until close, without replacing the sink
106 // listener that propagates errors while it is active.
107 const handleInputErrors = (writable: Writable): void => {
108 const onError = () => {}
109 writable.on("error", onError)
110 writable.once("close", () => writable.off("error", onError))
111 }
112
113 /** Node has recorded the leader's exit, after which its PID may be reused by an unrelated process. */
114 const hasExited = (childProcess: NodeChildProcess.ChildProcess): boolean =>
115 childProcess.exitCode !== null || childProcess.signalCode !== null
116
117 /**
118 * A non-detached leader shares its parent's process group, so once it has
119 * exited there is no group of its own left to signal or poll.
120 */
121 const ownsProcessGroup = (
122 command: ChildProcess.StandardCommand,
123 childProcess: NodeChildProcess.ChildProcess
124 ): boolean => command.options.detached !== false || !hasExited(childProcess)
125
126 /**
127 * The process group exists but has no member that can be signalled, such as
128 * on macOS when its remaining members are zombies.
129 */
130 const isUnsignallableProcessGroup = (error: unknown): boolean =>
131 (error as NodeJS.ErrnoException | undefined)?.code === "EPERM"
132
133 /** The leader has not exited, or a member of its process group still exists. */
134 const isProcessAlive = (
135 command: ChildProcess.StandardCommand,
136 childProcess: NodeChildProcess.ChildProcess
137 ): boolean => {
138 if (!hasExited(childProcess)) {
139 return true
140 }
141 if (globalThis.process.platform === "win32" || !ownsProcessGroup(command, childProcess)) {
142 return false
143 }
144 try {
145 globalThis.process.kill(-childProcess.pid!, 0)
146 return true
147 } catch (error) {
148 return isUnsignallableProcessGroup(error)
149 }
150 }
151
152 const taskkill = (
153 childProcess: NodeChildProcess.ChildProcess,
154 onExit: (error: NodeChildProcess.ExecException | null) => void = () => {}
155 ) => {
156 if (hasExited(childProcess)) {
157 onExit(null)
158 return
159 }
160 NodeChildProcess.execFile(
161 "taskkill",
162 ["/pid", String(childProcess.pid!), "/T", "/F"],
163 { windowsHide: true },
164 onExit
165 )
166 }
167
168 const make = Effect.gen(function*() {
169 const fs = yield* FileSystem.FileSystem
170 const path = yield* Path.Path
171
172 const resolveWorkingDirectory = Effect.fnUntraced(
173 function*(options: ChildProcess.CommandOptions) {
174 if (Predicate.isUndefined(options.cwd)) return undefined
175 // Validate that the specified directory is accessible
176 yield* fs.access(options.cwd)
177 return path.resolve(options.cwd)
178 }
179 )
180
181 const resolveEnvironment = (options: ChildProcess.CommandOptions) => {
182 if (options.env === undefined) return undefined
183 const env: Record<string, string | undefined> = options.extendEnv === true ? { ...globalThis.process.env } : {}
184 for (const [key, value] of Object.entries(options.env)) {
185 if (value === undefined) delete env[key]
186 else env[key] = unwrap(value)
187 }
188 return env
189 }
190
191 const inputToStdioOption = (input: ChildProcess.CommandInput | undefined): NodeChildProcess.IOType | undefined =>
192 Stream.isStream(input) ? "pipe" : input
193
194 const outputToStdioOption = (input: ChildProcess.CommandOutput | undefined): NodeChildProcess.IOType | undefined =>
195 Sink.isSink(input) ? "pipe" : input
196
197 const resolveStdinOption = (options: ChildProcess.CommandOptions): ChildProcess.StdinConfig => {
198 const defaultConfig: ChildProcess.StdinConfig = { stream: "pipe", encoding: "utf-8", endOnDone: true }
199 if (Predicate.isUndefined(options.stdin)) {
200 return defaultConfig
201 }
202 if (typeof options.stdin === "string") {
203 return { ...defaultConfig, stream: options.stdin }
204 }
205 if (Stream.isStream(options.stdin)) {
206 return { ...defaultConfig, stream: options.stdin }
207 }
208 return {
209 stream: options.stdin.stream,
210 encoding: options.stdin.encoding ?? defaultConfig.encoding,
211 endOnDone: options.stdin.endOnDone ?? defaultConfig.endOnDone
212 }
213 }
214
215 const resolveOutputOption = (
216 options: ChildProcess.CommandOptions,
217 streamName: "stdout" | "stderr"
218 ): ChildProcess.StdoutConfig => {
219 const option = options[streamName]
220 if (Predicate.isUndefined(option)) {
221 return { stream: "pipe" }
222 }
223 if (typeof option === "string") {
224 return { stream: option }
225 }
226 if (Sink.isSink(option)) {
227 return { stream: option }
228 }
229 return { stream: option.stream }
230 }
231
232 interface ResolvedAdditionalFd {
233 readonly fd: number
234 readonly config: ChildProcess.AdditionalFdConfig
235 }
236
237 const resolveAdditionalFds = (
238 options: ChildProcess.CommandOptions
239 ): ReadonlyArray<ResolvedAdditionalFd> => {
240 if (Predicate.isUndefined(options.additionalFds)) {
241 return []
242 }
243 const result: Array<ResolvedAdditionalFd> = []
244 for (const [name, config] of Object.entries(options.additionalFds)) {
245 const fd = ChildProcess.parseFdName(name)
246 if (Predicate.isNotUndefined(fd)) {
247 result.push({ fd, config })
248 }
249 }
250 // Sort by fd number to ensure correct ordering
251 return result.sort((a, b) => a.fd - b.fd)
252 }
253
254 const buildStdioArray = (
255 stdinConfig: ChildProcess.StdinConfig,
256 stdoutConfig: ChildProcess.StdoutConfig,
257 stderrConfig: ChildProcess.StderrConfig,
258 additionalFds: ReadonlyArray<ResolvedAdditionalFd>
259 ): NodeChildProcess.StdioOptions => {
260 const stdio: Array<NodeChildProcess.IOType | undefined> = [
261 inputToStdioOption(stdinConfig.stream),
262 outputToStdioOption(stdoutConfig.stream),
263 outputToStdioOption(stderrConfig.stream)
264 ]
265
266 if (additionalFds.length === 0) {
267 return stdio as NodeChildProcess.StdioOptions
268 }
269
270 // Find the maximum fd number to size the array correctly
271 const maxFd = additionalFds.reduce((max, { fd }) => Math.max(max, fd), 2)
272
273 // Fill gaps with "ignore"
274 for (let i = 3; i <= maxFd; i++) {
275 stdio[i] = "ignore"
276 }
277
278 // Set up additional fds as "pipe"
279 for (const { fd } of additionalFds) {
280 stdio[fd] = "pipe"
281 }
282
283 return stdio as NodeChildProcess.StdioOptions
284 }
285
286 // Runs a user-provided input stream into its sink, recording a failure of
287 // the source stream so that it can be surfaced by the process exit code
288 const runInputStream = (
289 stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
290 sink: Sink.Sink<void, Uint8Array, never, PlatformError.PlatformError>,
291 inputFailure: Deferred.Deferred<never, PlatformError.PlatformError>
292 ) => Effect.forkScoped(Stream.run(Stream.tapError(stream, (error) => Deferred.fail(inputFailure, error)), sink))
293
294 const setupAdditionalFds = Effect.fnUntraced(function*(
295 command: ChildProcess.StandardCommand,
296 childProcess: NodeChildProcess.ChildProcess,
297 additionalFds: ReadonlyArray<ResolvedAdditionalFd>,
298 inputFailure: Deferred.Deferred<never, PlatformError.PlatformError>
299 ) {
300 if (additionalFds.length === 0) {
301 return {
302 getInputFd: () => Sink.drain,
303 getOutputFd: () => Stream.empty
304 }
305 }
306
307 const inputSinks = new Map<number, Sink.Sink<void, Uint8Array, never, PlatformError.PlatformError>>()
308 const outputStreams = new Map<number, Stream.Stream<Uint8Array, PlatformError.PlatformError>>()
309
310 const setupInput = (
311 fd: number,
312 nodeStream: NodeChildProcess.ChildProcess["stdio"][number],
313 stream: Stream.Stream<Uint8Array, PlatformError.PlatformError> | undefined
314 ) =>
315 Effect.suspend(() => {
316 let sink: Sink.Sink<void, Uint8Array, never, PlatformError.PlatformError> = Sink.drain
317 if (nodeStream && "write" in nodeStream) {
318 handleInputErrors(nodeStream)
319 sink = NodeSink.fromWritable({
320 evaluate: () => nodeStream,
321 onError: (error) => toPlatformError(`fromWritable(fd${fd})`, toError(error), command)
322 })
323 }
324
325 if (stream) {
326 return Effect.map(runInputStream(stream, sink, inputFailure), () => {
327 inputSinks.set(fd, sink)
328 })
329 }
330
331 inputSinks.set(fd, sink)
332 return Effect.void
333 })
334
335 const setupOutput = (
336 fd: number,
337 nodeStream: NodeChildProcess.ChildProcess["stdio"][number],
338 sink: Sink.Sink<Uint8Array, Uint8Array, never, PlatformError.PlatformError> | undefined
339 ) => {
340 let stream: Stream.Stream<Uint8Array, PlatformError.PlatformError> = Stream.empty
341 if (nodeStream && "read" in nodeStream) {
342 const passThrough = new PassThrough()
343 // Retain errors raised before anyone reads, e.g. a failed write on a
344 // duplex fd, so they neither go uncaught nor leave later readers hanging
345 let error: unknown = undefined
346 passThrough.on("error", (cause) => {
347 error ??= cause
348 })
349 nodeStream.on("error", (cause) => passThrough.destroy(cause))
350 nodeStream.pipe(passThrough)
351 const onError = (cause: unknown) => toPlatformError(`fromReadable(fd${fd})`, toError(cause), command)
352 stream = Stream.suspend(() =>
353 error === undefined
354 ? NodeStream.fromReadable({ evaluate: () => passThrough, onError })
355 : Stream.fail(onError(error))
356 )
357 }
358
359 if (sink) {
360 stream = Stream.transduce(stream, sink)
361 }
362
363 outputStreams.set(fd, stream)
364 }
365
366 for (const { config, fd } of additionalFds) {
367 const nodeStream = childProcess.stdio[fd]
368
369 switch (config.type) {
370 case "input": {
371 yield* setupInput(fd, nodeStream, config.stream)
372 break
373 }
374 case "output": {
375 setupOutput(fd, nodeStream, config.sink)
376 break
377 }
378 case "duplex": {
379 // Keep writing possible after the child closes its write side.
380 if (nodeStream && "allowHalfOpen" in nodeStream) {
381 nodeStream.allowHalfOpen = true
382 }
383 setupOutput(fd, nodeStream, config.sink)
384 yield* setupInput(fd, nodeStream, config.stream)
385 break
386 }
387 }
388 }
389
390 return {
391 getInputFd: (fd: number) => inputSinks.get(fd) ?? Sink.drain,
392 getOutputFd: (fd: number) => outputStreams.get(fd) ?? Stream.empty
393 }
394 })
395
396 const setupChildStdin = (
397 command: ChildProcess.StandardCommand,
398 childProcess: NodeChildProcess.ChildProcess,
399 config: ChildProcess.StdinConfig,
400 inputFailure: Deferred.Deferred<never, PlatformError.PlatformError>
401 ) =>
402 Effect.suspend(() => {
403 // If the child process has a standard input stream, connect it to the
404 // sink that will attached to the process handle
405 let sink: Sink.Sink<void, unknown, never, PlatformError.PlatformError> = Sink.drain
406 if (Predicate.isNotNull(childProcess.stdin)) {
407 handleInputErrors(childProcess.stdin)
408 sink = NodeSink.fromWritable({
409 evaluate: () => childProcess.stdin!,
410 onError: (error) => toPlatformError("fromWritable(stdin)", toError(error), command),
411 endOnDone: config.endOnDone,
412 encoding: config.encoding
413 })
414 }
415
416 // If the user provided a `Stream`, run it into the stdin sink
417 if (Stream.isStream(config.stream)) {
418 return Effect.as(runInputStream(config.stream, sink, inputFailure), sink)
419 }
420
421 return Effect.succeed(sink)
422 })
423
424 const setupChildOutputStreams = (
425 command: ChildProcess.StandardCommand,
426 childProcess: NodeChildProcess.ChildProcess,
427 stdoutConfig: ChildProcess.StdoutConfig,
428 stderrConfig: ChildProcess.StderrConfig
429 ): {
430 stdout: Stream.Stream<Uint8Array, PlatformError.PlatformError>
431 stderr: Stream.Stream<Uint8Array, PlatformError.PlatformError>
432 all: Stream.Stream<Uint8Array, PlatformError.PlatformError>
433 } => {
434 let stdout = childProcess.stdout ?
435 (() => {
436 const passThrough = new PassThrough()
437 childProcess.stdout!.on("error", (error) => passThrough.destroy(error))
438 childProcess.stdout!.pipe(passThrough)
439 return NodeStream.fromReadable({
440 evaluate: () => passThrough,
441 onError: (error) => toPlatformError("fromReadable(stdout)", toError(error), command)
442 })
443 })() :
444 Stream.empty
445 let stderr = childProcess.stderr ?
446 (() => {
447 const passThrough = new PassThrough()
448 childProcess.stderr!.on("error", (error) => passThrough.destroy(error))
449 childProcess.stderr!.pipe(passThrough)
450 return NodeStream.fromReadable({
451 evaluate: () => passThrough,
452 onError: (error) => toPlatformError("fromReadable(stderr)", toError(error), command)
453 })
454 })() :
455 Stream.empty
456
457 if (Sink.isSink(stdoutConfig.stream)) {
458 stdout = Stream.transduce(stdout, stdoutConfig.stream)
459 }
460 if (Sink.isSink(stderrConfig.stream)) {
461 stderr = Stream.transduce(stderr, stderrConfig.stream)
462 }
463
464 const all = Stream.merge(stdout, stderr)
465
466 return { stdout, stderr, all }
467 }
468
469 const spawn = (
470 command: ChildProcess.StandardCommand,
471 spawnOptions: NodeChildProcess.SpawnOptions
472 ) =>
473 Effect.callback<
474 readonly [NodeChildProcess.ChildProcess, ExitSignal],
475 PlatformError.PlatformError
476 >((resume) => {
477 const deferred = Deferred.makeUnsafe<ExitCodeWithSignal>()
478 const handle = NodeChildProcess.spawn(
479 command.command,
480 command.args.map(unwrap),
481 spawnOptions
482 )
483 handle.on("error", (error) => {
484 // Node copies the arguments into `spawnargs`.
485 if (command.args.some(Redacted.isRedacted)) {
486 Object.assign(error, {
487 spawnargs: [command.command, ...command.args.map((arg) => Redacted.isRedacted(arg) ? "<redacted>" : arg)]
488 })
489 }
490 resume(Effect.fail(toPlatformError("spawn", error, command)))
491 })
492 handle.on("exit", (...args) => {
493 Deferred.doneUnsafe(deferred, Exit.succeed(args))
494 })
495 handle.on("spawn", () => {
496 resume(Effect.succeed([handle, deferred]))
497 })
498 return Effect.sync(() => {
499 handle.kill("SIGTERM")
500 })
501 })
502
503 const killProcessGroup = (
504 command: ChildProcess.StandardCommand,
505 childProcess: NodeChildProcess.ChildProcess,
506 signal: NodeJS.Signals
507 ) => {
508 if (globalThis.process.platform === "win32") {
509 return Effect.callback<void, PlatformError.PlatformError>((resume) => {
510 taskkill(childProcess, (error) => {
511 if (error) {
512 resume(Effect.fail(toPlatformError("kill", toError(error), command)))
513 } else {
514 resume(Effect.void)
515 }
516 })
517 })
518 }
519 return Effect.try({
520 try: () => {
521 globalThis.process.kill(-childProcess.pid!, signal)
522 },
523 catch: (error) => toPlatformError("kill", toError(error), command)
524 })
525 }
526
527 const killProcessGroupOnExit = (
528 childProcess: NodeChildProcess.ChildProcess,
529 signal: NodeJS.Signals
530 ): void => {
531 if (globalThis.process.platform === "win32") {
532 // ignore errors during best-effort cleanup
533 taskkill(childProcess)
534 return
535 }
536 try {
537 globalThis.process.kill(-childProcess.pid!, signal)
538 } catch {
539 // ignore errors during best-effort cleanup
540 }
541 }
542
543 const killProcess = (
544 command: ChildProcess.StandardCommand,
545 childProcess: NodeChildProcess.ChildProcess,
546 signal: NodeJS.Signals
547 ) =>
548 Effect.suspend(() => {
549 const killed = childProcess.kill(signal)
550 if (!killed) {
551 const error = new globalThis.Error("Failed to kill child process")
552 return Effect.fail(toPlatformError("kill", error, command))
553 }
554 return Effect.void
555 })
556
557 /** Waits for the leader and its process group, bounded by native time. */
558 const awaitProcessExit = (
559 command: ChildProcess.StandardCommand,
560 childProcess: NodeChildProcess.ChildProcess,
561 timeoutMillis: number
562 ): Effect.Effect<void> =>
563 Effect.callback<void>((resume) => {
564 const deadline = Date.now() + timeoutMillis
565 let timer: NodeJS.Timeout | undefined
566 const stop = () => {
567 clearTimeout(timer)
568 childProcess.removeListener("exit", poll)
569 }
570 const poll = () => {
571 clearTimeout(timer)
572 if (Date.now() >= deadline || !isProcessAlive(command, childProcess)) {
573 stop()
574 resume(Effect.void)
575 return
576 }
577 timer = setTimeout(poll, processGroupPollIntervalMillis)
578 }
579 childProcess.on("exit", poll)
580 poll()
581 return Effect.sync(stop)
582 })
583
584 const terminateProcessGroup = Effect.fnUntraced(function*(
585 command: ChildProcess.StandardCommand,
586 childProcess: NodeChildProcess.ChildProcess,
587 exitSignal: ExitSignal,
588 options: ChildProcess.KillOptions | undefined
589 ) {
590 const signalGroup = (signal: NodeJS.Signals) =>
591 ownsProcessGroup(command, childProcess) ?
592 killProcessGroup(command, childProcess, signal).pipe(
593 Effect.catch((error) =>
594 // Only zombies remain in the exited leader's group, so nothing is left to signal.
595 hasExited(childProcess) && isUnsignallableProcessGroup(error.cause) ?
596 Effect.void :
597 killProcess(command, childProcess, signal)
598 )
599 ) :
600 killProcess(command, childProcess, signal)
601 yield* signalGroup(options?.killSignal ?? "SIGTERM")
602 if (Predicate.isUndefined(options?.forceKillAfter)) {
603 yield* Deferred.await(exitSignal)
604 yield* awaitProcessExit(command, childProcess, processGroupGraceMillis)
605 } else {
606 yield* awaitProcessExit(command, childProcess, Duration.toMillis(options.forceKillAfter))
607 if (isProcessAlive(command, childProcess)) {
608 yield* signalGroup("SIGKILL")
609 yield* awaitProcessExit(command, childProcess, processGroupGraceMillis)
610 }
611 }
612 yield* Deferred.await(exitSignal)
613 })
614
615 /**
616 * Get the appropriate source stream from a process handle based on the
617 * `from` pipe option.
618 */
619 const getSourceStream = (
620 handle: ChildProcessHandle,
621 from: ChildProcess.PipeFromOption | undefined
622 ): Stream.Stream<Uint8Array, PlatformError.PlatformError> => {
623 const fromOption = from ?? "stdout"
624 switch (fromOption) {
625 case "stdout":
626 return handle.stdout
627 case "stderr":
628 return handle.stderr
629 case "all":
630 return handle.all
631 default: {
632 // Handle fd3, fd4, etc.
633 const fd = ChildProcess.parseFdName(fromOption)
634 if (Predicate.isNotUndefined(fd)) {
635 return handle.getOutputFd(fd)
636 }
637 // Fallback to stdout for invalid fd names
638 return handle.stdout
639 }
640 }
641 }
642
643 const spawnCommand: (
644 command: ChildProcess.Command
645 ) => Effect.Effect<
646 ChildProcessHandle,
647 PlatformError.PlatformError,
648 Scope.Scope
649 > = Effect.fnUntraced(function*(cmd) {
650 switch (cmd._tag) {
651 case "StandardCommand": {
652 if (cmd.options.shell !== undefined && cmd.options.shell !== false && cmd.args.length > 0) {
653 return yield* Effect.fail(PlatformError.badArgument({
654 module: "ChildProcess",
655 method: "spawn",
656 description: "The shell option cannot be combined with arguments; pass the whole script as the command"
657 }))
658 }
659 const nulCharacter = findNulCharacter(cmd)
660 if (nulCharacter !== undefined) {
661 return yield* Effect.fail(PlatformError.badArgument({
662 module: "ChildProcess",
663 method: "spawn",
664 description: nulCharacter
665 }))
666 }
667 const stdinConfig = resolveStdinOption(cmd.options)
668 const stdoutConfig = resolveOutputOption(cmd.options, "stdout")
669 const stderrConfig = resolveOutputOption(cmd.options, "stderr")
670 const resolvedAdditionalFds = resolveAdditionalFds(cmd.options)
671 let isReferenced = true
672
673 const cwd = yield* resolveWorkingDirectory(cmd.options)
674 const env = resolveEnvironment(cmd.options)
675 const stdio = buildStdioArray(stdinConfig, stdoutConfig, stderrConfig, resolvedAdditionalFds)
676
677 const [childProcess, exitSignal] = yield* Effect.acquireRelease(
678 spawn(cmd, buildSpawnOptions(cmd.options, { cwd, env, stdio }, process.platform)),
679 Effect.fnUntraced(function*([childProcess, exitSignal]) {
680 const exited = yield* Deferred.isDone(exitSignal)
681 if (exited) {
682 const [code] = yield* Deferred.await(exitSignal)
683 if (code !== 0 && Predicate.isNotNull(code)) {
684 yield* Effect.ignore(terminateProcessGroup(cmd, childProcess, exitSignal, cmd.options))
685 } else if (isReferenced && process.platform !== "win32" && cmd.options.detached !== false) {
686 yield* Effect.ignore(terminateProcessGroup(cmd, childProcess, exitSignal, cmd.options))
687 }
688 return
689 }
690 if (!isReferenced) {
691 return
692 }
693 yield* Effect.ignore(terminateProcessGroup(cmd, childProcess, exitSignal, cmd.options))
694 })
695 )
696
697 const pid = ProcessId(childProcess.pid!)
698 // A non-detached child leaves no process group of its own to clean up.
699 if (cmd.options.detached !== false) {
700 childProcess.on("exit", (code) => {
701 if (code !== 0 && Predicate.isNotNull(code)) {
702 killProcessGroupOnExit(childProcess, cmd.options.killSignal ?? "SIGTERM")
703 }
704 })
705 }
706 const reref = Effect.sync(() => {
707 if (!isReferenced) {
708 childProcess.ref()
709 isReferenced = true
710 }
711 })
712 const unref = Effect.sync(() => {
713 if (isReferenced) {
714 childProcess.unref()
715 isReferenced = false
716 }
717 return reref
718 })
719 const inputFailure = Deferred.makeUnsafe<never, PlatformError.PlatformError>()
720 const stdin = yield* setupChildStdin(cmd, childProcess, stdinConfig, inputFailure)
721 const { all, stderr, stdout } = setupChildOutputStreams(cmd, childProcess, stdoutConfig, stderrConfig)
722 const { getInputFd, getOutputFd } = yield* setupAdditionalFds(
723 cmd,
724 childProcess,
725 resolvedAdditionalFds,
726 inputFailure
727 )
728 const isRunning = Effect.map(Deferred.isDone(exitSignal), (done) => !done)
729 // A failed input stream truncates the input of the child process, so
730 // its failure takes precedence over the exit status and is surfaced
731 // without waiting for the child process to exit
732 const exitCode = Effect.flatMap(
733 Effect.raceFirst(Deferred.await(exitSignal), Deferred.await(inputFailure)),
734 ([code, signal]) => {
735 if (Deferred.isDoneUnsafe(inputFailure)) {
736 return Deferred.await(inputFailure)
737 }
738 if (Predicate.isNotNull(code)) {
739 return Effect.succeed(ExitCode(code))
740 }
741 // If code is `null`, then `signal` must be defined. See the NodeJS
742 // documentation for the `"exit"` event on a `child_process`.
743 // https://nodejs.org/api/child_process.html#child_process_event_exit
744 const error = new globalThis.Error(`Process interrupted due to receipt of signal: '${signal}'`)
745 return Effect.fail(toPlatformError("exitCode", error, cmd))
746 }
747 )
748 const kill = (options?: ChildProcess.KillOptions | undefined) =>
749 terminateProcessGroup(cmd, childProcess, exitSignal, options)
750
751 return makeHandle({
752 pid,
753 exitCode,
754 isRunning,
755 kill,
756 stdin,
757 stdout,
758 stderr,
759 all,
760 getInputFd,
761 getOutputFd,
762 unref
763 })
764 }
765 case "PipedCommand": {
766 const { commands, pipeOptions } = flattenCommand(cmd)
767 const [root, ...pipeline] = commands
768
769 const handles = [yield* spawnCommand(root)]
770
771 for (let i = 0; i < pipeline.length; i++) {
772 const command = pipeline[i]
773 const options = pipeOptions[i] ?? {}
774 const stdinConfig = resolveStdinOption(command.options)
775
776 // Get the appropriate stream from the source based on `from` option
777 const sourceStream = Stream.unwrap(
778 Effect.succeed(getSourceStream(handles[handles.length - 1], options.from))
779 )
780
781 // Determine where to pipe: stdin or custom fd
782 const toOption = options.to ?? "stdin"
783
784 if (toOption === "stdin") {
785 // Pipe to stdin (default behavior)
786 handles.push(
787 yield* spawnCommand(ChildProcess.make(command.command, command.args, {
788 ...command.options,
789 stdin: { ...stdinConfig, stream: sourceStream }
790 }))
791 )
792 } else {
793 // Pipe to custom fd (fd3, fd4, etc.)
794 const fd = ChildProcess.parseFdName(toOption)
795 if (Predicate.isNotUndefined(fd)) {
796 const fdName = ChildProcess.fdName(fd) as `fd${number}`
797 const existingFds = command.options.additionalFds ?? {}
798 const existingFd = existingFds[fdName]
799 const fdConfig: ChildProcess.AdditionalFdConfig = existingFd?.type === "duplex"
800 ? { ...existingFd, stream: sourceStream }
801 : { type: "input", stream: sourceStream }
802 handles.push(
803 yield* spawnCommand(ChildProcess.make(command.command, command.args, {
804 ...command.options,
805 additionalFds: {
806 ...existingFds,
807 [fdName]: fdConfig
808 }
809 }))
810 )
811 } else {
812 // Invalid fd name, fall back to stdin
813 handles.push(
814 yield* spawnCommand(ChildProcess.make(command.command, command.args, {
815 ...command.options,
816 stdin: { ...stdinConfig, stream: sourceStream }
817 }))
818 )
819 }
820 }
821 }
822
823 const handle = handles[handles.length - 1]
824 const kill = (options?: ChildProcess.KillOptions | undefined) =>
825 Effect.forEach([...handles].reverse(), (handle) => Effect.ignore(handle.kill(options)), { discard: true })
826 const unref = Effect.gen(function*() {
827 const rerefs: Array<Effect.Effect<void, PlatformError.PlatformError>> = []
828 for (const handle of handles) {
829 rerefs.push(yield* handle.unref)
830 }
831 return Effect.forEach([...rerefs].reverse(), (reref) => reref, { discard: true })
832 })
833
834 return makeHandle({
835 pid: handle.pid,
836 exitCode: handle.exitCode,
837 isRunning: handle.isRunning,
838 kill,
839 stdin: handles[0].stdin,
840 stdout: handle.stdout,
841 stderr: handle.stderr,
842 all: handle.all,
843 getInputFd: handle.getInputFd,
844 getOutputFd: handle.getOutputFd,
845 unref
846 })
847 }
848 }
849 })
850
851 return makeSpawner(spawnCommand)
852 })
853
854 /**
855 * Layer that provides the `NodeChildProcessSpawner` implementation.
856 *
857 * @stability unstable
858 * @category layers
859 * @since 4.0.0
860 */
861 export const layer: Layer.Layer<
862 ChildProcessSpawner,
863 never,
864 FileSystem.FileSystem | Path.Path
865 > = Layer.effect(ChildProcessSpawner, make)
866
867 // =============================================================================
868 // Internal Helpers
869 // =============================================================================
870
871 /**
872 * Result of flattening a pipeline of commands.
873 *
874 * @stability unstable
875 * @category models
876 * @since 4.0.0
877 */
878 export interface FlattenedPipeline {
879 readonly commands: Arr.NonEmptyReadonlyArray<ChildProcess.StandardCommand>
880 readonly pipeOptions: ReadonlyArray<ChildProcess.PipeOptions>
881 }
882
883 /**
884 * Flattens a `Command` into an array of `StandardCommand`s along with pipe
885 * options for each connection.
886 *
887 * @stability unstable
888 * @category transforming
889 * @since 4.0.0
890 */
891 export const flattenCommand = (
892 command: ChildProcess.Command
893 ): FlattenedPipeline => {
894 const commands: Array<ChildProcess.StandardCommand> = []
895 const pipeOptions: Array<ChildProcess.PipeOptions> = []
896
897 const flatten = (cmd: ChildProcess.Command): void => {
898 switch (cmd._tag) {
899 case "StandardCommand": {
900 commands.push(cmd)
901 break
902 }
903 case "PipedCommand": {
904 // Recursively flatten left side first
905 flatten(cmd.left)
906 // Store the pipe options for this connection
907 pipeOptions.push(cmd.options)
908 // Then flatten right side
909 flatten(cmd.right)
910 break
911 }
912 }
913 }
914
915 flatten(command)
916
917 // The commands array is guaranteed to be non-empty since we always have at
918 // least one command in the input. We validate this at runtime and return a
919 // properly typed tuple.
920 if (commands.length === 0) {
921 // This should never happen given a valid Command input
922 throw new Error("flattenCommand produced empty commands array")
923 }
924
925 const [first, ...rest] = commands
926 const nonEmptyCommands: Arr.NonEmptyReadonlyArray<ChildProcess.StandardCommand> = [first, ...rest]
927
928 return { commands: nonEmptyCommands, pipeOptions }
929 }