spawn.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. /**
  2. * Process plumbing for the local subprocess service: detached process-tree
  3. * spawn with per-stream stdio dispositions, tail-keep collection with spill
  4. * files, tree-scoped signalling (POSIX groups; Windows taskkill), and the
  5. * SIGTERM→SIGKILL escalation. This layer reacts to an abort signal; callers
  6. * own deadlines, teardown ladders, and cause classification.
  7. * @module dsh-subprocess-local/spawn
  8. */
  9. import { type ChildProcess, spawn, spawnSync } from 'node:child_process'
  10. import type { Readable } from 'node:stream'
  11. import { randomBytes } from 'node:crypto'
  12. import { closeSync, mkdtempSync, openSync, unlinkSync, writeSync } from 'node:fs'
  13. import { tmpdir } from 'node:os'
  14. import { join } from 'node:path'
  15. import { setTimeout as sleepMs } from 'node:timers/promises'
  16. import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess'
  17. import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
  18. import type {
  19. CollectedOutput,
  20. SubprocessCollect,
  21. SubprocessHandle,
  22. SubprocessOutcome,
  23. SubprocessOutputMode,
  24. SubprocessSpawnSpec,
  25. } from '@deepseek-ai/dsh-subprocess'
  26. import { linuxProcessGroupHasLiveMembers } from './process-inspector.ts'
  27. /**
  28. * Build a child environment: explicit caller entries override the scrubbed
  29. * parent base using the target platform's environment-key semantics. A string
  30. * deliberately restores or overrides an entry; an explicit `undefined`
  31. * tombstone removes an ordinary ambient entry.
  32. * @param extra - explicit caller entries and tombstones, merged after the scrub.
  33. * @returns the environment to hand to `spawn` for the child process.
  34. */
  35. export function childEnv(extra?: Readonly<NodeJS.ProcessEnv>): NodeJS.ProcessEnv {
  36. const env = scrubbedParentEnv()
  37. if (process.platform !== 'win32') return { ...env, ...extra }
  38. let entries: [string, string | undefined][] = Object.entries(env)
  39. for (const [key, value] of Object.entries(extra ?? {})) {
  40. const normalized = key.toUpperCase()
  41. entries = entries.filter(([inherited]) => inherited.toUpperCase() !== normalized)
  42. entries.push([key, value])
  43. }
  44. return Object.fromEntries(entries)
  45. }
  46. /** Injectable knobs so tests can exercise spill and platform behavior deterministically. */
  47. export interface SpawnInternals {
  48. /** Directory for spill files (defaults to the OS temp dir). */
  49. spillDir?: string
  50. /** Windows tree-termination runner (defaults to `taskkill /PID <pid> /T /F`). */
  51. taskkill?: (pid: number) => void
  52. /** Host platform override for signalling decisions. */
  53. platform?: NodeJS.Platform
  54. /** Linux process-group member probe (defaults to `/proc` inspection). */
  55. linuxProcessGroupHasLiveMembers?: (processGroupId: number) => boolean | undefined
  56. }
  57. /**
  58. * Local-only synchronous final termination used by the owning service during
  59. * host exit and as the last fallback after failed normal disposal. It is
  60. * intentionally absent from the public subprocess seam.
  61. */
  62. export interface LocalSubprocessHandle extends SubprocessHandle {
  63. /** Force-terminate the current tree synchronously without starting timers or waits. */
  64. terminateForHostExit(): void
  65. }
  66. /**
  67. * Liveness-poll cadence for tree-exit waits. The timer stays ref'd: an
  68. * awaited teardown must keep the event loop alive until the tree really
  69. * exits, or the parent can exit while claiming quiescence and orphan the
  70. * survivors it promised to reap.
  71. */
  72. function sleepTick(): Promise<void> {
  73. return sleepMs(15)
  74. }
  75. let spillCounter = 0
  76. let defaultSpillDir: string | undefined
  77. /**
  78. * The default spill location: a private (0700) per-process directory under
  79. * the OS tmpdir, created lazily. Predictable world-readable paths would let
  80. * other local users read command output or pre-create symlinks.
  81. */
  82. function privateSpillDir(): string {
  83. defaultSpillDir ??= mkdtempSync(join(tmpdir(), 'dsh-subprocess-'))
  84. return defaultSpillDir
  85. }
  86. /**
  87. * Collects one stream with a bounded in-memory tail. With a spill cap, on
  88. * first overflow a spill file is created and every chunk (including those
  89. * already collected) is appended there while the full stream remains within
  90. * the cap; without one, only the in-memory tail is ever retained (the
  91. * diagnostic-tail shape — a language server's stderr).
  92. *
  93. * Tail-keep rationale (pi/OpenCode): errors and final results cluster at the
  94. * end of command output; the spill file covers the head.
  95. */
  96. export class OutputCollector {
  97. private chunks: Buffer[] = []
  98. private bytes = 0
  99. private dropped = false
  100. private spillFd: number | undefined
  101. private spillFile: string | undefined
  102. private spillDisabled: boolean
  103. /** Total bytes ever pushed (not just retained). */
  104. private total = 0
  105. constructor(
  106. private readonly maxBytes: number,
  107. private readonly maxSpillBytes: number | undefined,
  108. private readonly label: string,
  109. private readonly spillDir: string,
  110. ) {
  111. this.spillDisabled = maxSpillBytes === undefined
  112. }
  113. /**
  114. * Ingest one stream chunk, counting it toward the whole-stream total. On
  115. * first overflow of the in-memory cap a spill file is opened (when spilling
  116. * is enabled) and every chunk (already-collected ones included) is appended
  117. * there from then on; the in-memory tail then drops whole chunks from its
  118. * head (or the head of a single over-cap chunk) until it fits the cap again.
  119. * @param chunk - the raw bytes from one stream 'data' event.
  120. */
  121. push(chunk: Buffer): void {
  122. this.total += chunk.length
  123. const overflows = this.bytes + chunk.length > this.maxBytes
  124. if (!this.spillDisabled && (overflows || this.spillFd !== undefined)) this.spillAll(chunk)
  125. this.chunks.push(chunk)
  126. this.bytes += chunk.length
  127. while (this.bytes > this.maxBytes) {
  128. const head = this.chunks[0] as Buffer
  129. const excess = this.bytes - this.maxBytes
  130. if (head.length <= excess) {
  131. // Drop the whole head chunk (length ≥ 1 is guaranteed while over cap).
  132. this.chunks.shift()
  133. this.bytes -= head.length
  134. } else {
  135. // Trim the head so the retained window is byte-exact at the cap — a
  136. // diagnostic tail (an LSP server's stderr) must hold the LAST
  137. // maxBytes regardless of how the stream was chunked.
  138. this.chunks[0] = head.subarray(excess)
  139. this.bytes -= excess
  140. }
  141. this.dropped = true
  142. }
  143. }
  144. /** Open the spill file lazily and append `chunk` (and any prior chunks once). */
  145. private spillAll(chunk: Buffer): void {
  146. if (this.maxSpillBytes !== undefined && this.total > this.maxSpillBytes) {
  147. this.discardSpill()
  148. return
  149. }
  150. if (this.spillFd === undefined) {
  151. // Random suffix + O_EXCL + no-follow-equivalent ('wx' fails on any
  152. // existing path, symlink or not) + owner-only mode: defeats spill-path
  153. // prediction and symlink planting in shared tmp dirs.
  154. this.spillFile = join(
  155. this.spillDir,
  156. `dsh-subprocess-${process.pid}-${++spillCounter}-${randomBytes(6).toString('hex')}-${this.label}.log`,
  157. )
  158. this.spillFd = openSync(this.spillFile, 'wx', 0o600)
  159. for (const prior of this.chunks) writeSync(this.spillFd, prior)
  160. }
  161. writeSync(this.spillFd, chunk)
  162. }
  163. /** Stop spilling and remove the file once it can no longer hold the complete stream. */
  164. private discardSpill(): void {
  165. const fd = this.spillFd
  166. const file = this.spillFile
  167. this.spillFd = undefined
  168. this.spillFile = undefined
  169. this.spillDisabled = true
  170. if (fd !== undefined) {
  171. try {
  172. closeSync(fd)
  173. } catch {
  174. // Retain the descriptor so finalize can retry the failed close.
  175. this.spillFd = fd
  176. }
  177. }
  178. if (file !== undefined) {
  179. try {
  180. unlinkSync(file)
  181. } catch {
  182. // A failed unlink leaves at most maxSpillBytes behind, never an unbounded file.
  183. }
  184. }
  185. }
  186. /**
  187. * Incremental read in whole-stream byte coordinates: returns everything
  188. * pushed since `fromByte`. When `fromByte` has already slid out of the
  189. * in-memory tail window, the read is `lossy` — it returns the whole
  190. * retained tail and the gap is only recoverable from the spill file.
  191. * @param fromByte - whole-stream offset to resume from (a prior read's `nextOffset`; 0 for the first read).
  192. * @returns the delta text, the offset for the next read, the `lossy` flag, and the spill path when one was created.
  193. */
  194. readFrom(fromByte: number): { text: string; nextOffset: number; lossy: boolean; spillPath?: string } {
  195. const windowStart = this.total - this.bytes
  196. const buffer = Buffer.concat(this.chunks)
  197. const lossy = fromByte < windowStart
  198. const slice = lossy ? buffer : buffer.subarray(fromByte - windowStart)
  199. return {
  200. text: slice.toString('utf8'),
  201. nextOffset: this.total,
  202. lossy,
  203. ...this.spillFile !== undefined ? { spillPath: this.spillFile } : {},
  204. }
  205. }
  206. /**
  207. * Close the spill file once the stream has ended. A failed close (delayed
  208. * writeback fault) stops advertising the spill path — the file may be
  209. * missing its tail — while every in-memory read keeps working. Idempotent;
  210. * the spawn path seals both collectors at settlement so reads after exit
  211. * never point at a still-open file.
  212. */
  213. seal(): void {
  214. if (this.spillFd === undefined) return
  215. try {
  216. closeSync(this.spillFd)
  217. } catch {
  218. // A delayed writeback failure makes the spill unreliable; keep the
  219. // in-memory result but stop advertising that file.
  220. this.spillFile = undefined
  221. }
  222. this.spillFd = undefined
  223. }
  224. /**
  225. * Seal the spill file and return the final output.
  226. * @returns the final collected output: tail text, truncation flag, and the spill path when intact.
  227. */
  228. finalize(): CollectedOutput {
  229. this.seal()
  230. return {
  231. text: Buffer.concat(this.chunks).toString('utf8'),
  232. truncated: this.dropped,
  233. ...this.spillFile !== undefined ? { spillPath: this.spillFile } : {},
  234. }
  235. }
  236. }
  237. /**
  238. * Send `sig` to a detached POSIX process group. Never throws: delivery races
  239. * process exit and may run in a timer callback, so failures are contained and
  240. * a non-positive pid is a no-op.
  241. * @param pid - the group leader's pid; non-positive means the spawn failed and the call is a no-op.
  242. * @param sig - the signal to deliver to the whole group.
  243. */
  244. export function killGroup(pid: number, sig: NodeJS.Signals): void {
  245. if (pid <= 0) return
  246. try {
  247. process.kill(-pid, sig)
  248. } catch {
  249. // Swallow: see contract above.
  250. }
  251. }
  252. /**
  253. * Terminate one Windows process tree with `taskkill /T /F`. Contained like
  254. * POSIX group signalling — delivery races tree exit, so an absent tree, a
  255. * nonzero status, or a missing taskkill binary must not break idempotent
  256. * teardown.
  257. * @param pid - root process id; non-positive is a no-op.
  258. */
  259. export function taskkillProcessTree(pid: number): void {
  260. if (pid <= 0) return
  261. // Outcome deliberately unchecked: an already-absent tree (status 128), exit
  262. // races, and a missing taskkill binary (spawnSync reports, never throws) are
  263. // as tolerable here as ESRCH is for a POSIX group signal.
  264. spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore' })
  265. }
  266. /**
  267. * Signal a detached process tree with platform-correct semantics: POSIX
  268. * signals the negative process-group id and falls back to the direct child
  269. * when the group is gone; Windows terminates the tree via taskkill (any
  270. * signal value force-terminates — Node maps signals to TerminateProcess).
  271. */
  272. function signalTree(
  273. platform: NodeJS.Platform,
  274. pid: number,
  275. sig: NodeJS.Signals,
  276. child: ChildProcess,
  277. taskkill: (pid: number) => void,
  278. ): void {
  279. if (platform === 'win32') {
  280. taskkill(pid)
  281. return
  282. }
  283. /* v8 ignore next -- kill/terminate gate on treeAlive(), which is false for pid -1; this guard protects direct callers only. */
  284. if (pid <= 0) return
  285. try {
  286. process.kill(-pid, sig)
  287. } catch {
  288. /* v8 ignore start -- the fallback needs a live child whose group signal fails
  289. (EPERM-style), which POSIX CI cannot stage; the swallow keeps teardown idempotent. */
  290. try {
  291. child.kill(sig)
  292. } catch {
  293. // The direct child already exited; teardown remains idempotent.
  294. }
  295. /* v8 ignore stop */
  296. }
  297. }
  298. /**
  299. * Spawn one isolated detached process tree with the spec's per-stream stdio
  300. * dispositions. Runtime exits resolve `done` as {@link SubprocessOutcome};
  301. * only spawn failures reject.
  302. * @param spec - fully resolved argv, cwd, stdio, grace, cancellation, environment.
  303. * @param internals - test-only spill-directory, platform, and taskkill overrides.
  304. * @returns live subprocess handle.
  305. * @throws when `graceMs` cannot be represented by one Node timer.
  306. */
  307. export function spawnSubprocess(spec: SubprocessSpawnSpec, internals: SpawnInternals = {}): LocalSubprocessHandle {
  308. if (!Number.isFinite(spec.graceMs) || spec.graceMs <= 0 || spec.graceMs > MAX_TIMER_DELAY_MS) {
  309. throw new Error(`subprocess graceMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`)
  310. }
  311. const spillDir = internals.spillDir ?? privateSpillDir()
  312. const platform = internals.platform ?? process.platform
  313. const taskkill = internals.taskkill ?? taskkillProcessTree
  314. const linuxGroupHasLiveMembers = internals.linuxProcessGroupHasLiveMembers ?? linuxProcessGroupHasLiveMembers
  315. if (spec.signal?.aborted) {
  316. throw new Error(`aborted before spawn: ${String(spec.signal.reason ?? 'aborted')}`)
  317. }
  318. const [program, ...args] = spec.argv
  319. if (program === undefined || program.length === 0) {
  320. throw new Error('invalid argv: expected a non-empty program name at argv[0]')
  321. }
  322. const isCollect = (mode: SubprocessOutputMode): mode is SubprocessCollect =>
  323. mode !== 'pipe' && mode !== 'inherit'
  324. const outMode = spec.stdio.stdout
  325. const errMode = spec.stdio.stderr
  326. const stdinMode = spec.stdio.stdin
  327. const env = childEnv(spec.env)
  328. const child = spawn(program, args, {
  329. cwd: spec.cwd,
  330. env,
  331. stdio: [
  332. stdinMode === 'ignore' ? 'ignore' : 'pipe',
  333. outMode === 'inherit' ? 'inherit' : 'pipe',
  334. errMode === 'inherit' ? 'inherit' : 'pipe',
  335. ],
  336. // `detached` gives teardown a tree root on POSIX (its own process group);
  337. // Windows terminates by root pid through taskkill /T instead.
  338. detached: platform !== 'win32',
  339. })
  340. const collectStream = (mode: SubprocessOutputMode, stream: Readable | null, label: string): OutputCollector | undefined => {
  341. if (!isCollect(mode) || stream === null) return undefined
  342. const collector = new OutputCollector(mode.maxBytes, mode.spill?.maxBytes, label, spillDir)
  343. stream.on('data', (chunk: Buffer) => { collector.push(chunk) })
  344. return collector
  345. }
  346. const stdoutCollector = collectStream(outMode, child.stdout, 'stdout')
  347. const stderrCollector = collectStream(errMode, child.stderr, 'stderr')
  348. let graceTimer: ReturnType<typeof setTimeout> | undefined
  349. let treeExitObserved = false
  350. let treeExitObservation: Promise<void> | undefined
  351. let settled = false
  352. // Failed spawns use pid -1 so signalling remains a no-op.
  353. const pid = child.pid ?? -1
  354. /** Whether the detached tree's root (or POSIX group) is still alive. */
  355. const treeAlive = (): boolean => {
  356. /* v8 ignore next -- only a timer callback already queued when the observer settles can enter here;
  357. the guard is the final defense against probing an id after its tree was confirmed absent. */
  358. if (treeExitObserved) return false
  359. if (pid <= 0) return false
  360. if (platform === 'win32') {
  361. // Windows has no group-liveness probe; the direct child's exit is the
  362. // observable boundary (taskkill /T already took the tree with it).
  363. return child.exitCode === null && child.signalCode === null
  364. }
  365. try {
  366. process.kill(-pid, 0)
  367. // A group containing only unreaped zombies still answers kill(0), but
  368. // it can execute no work and cannot be signalled into quiescence. Only
  369. // inspect after direct-child settlement so live-process polls remain a
  370. // syscall rather than repeated process-table scans.
  371. if (settled && platform === 'linux' && linuxGroupHasLiveMembers(pid) === false) return false
  372. return true
  373. } catch (error) {
  374. const code = (error as NodeJS.ErrnoException).code
  375. /* v8 ignore next 2 -- POSIX reports an absent group as ESRCH; child-reaping timing
  376. makes observing the other arm platform-dependent. */
  377. if (code === 'ESRCH') return false
  378. /* v8 ignore start -- EPERM and non-POSIX negative-pid failures are platform defenses; CI runs
  379. tree-lifecycle tests on POSIX hosts where absence reports ESRCH. */
  380. if (code === 'EPERM') return true
  381. return child.exitCode === null && child.signalCode === null
  382. /* v8 ignore stop */
  383. }
  384. }
  385. /**
  386. * Start or reuse the handle's single whole-tree exit observer. The first
  387. * confirmed absence is a permanent no-more-signals boundary: it cancels a
  388. * pending escalation before this process-group id can be reused.
  389. */
  390. const observeTreeExit = (): Promise<void> => {
  391. treeExitObservation ??= (async () => {
  392. while (treeAlive()) await sleepTick()
  393. treeExitObserved = true
  394. if (graceTimer !== undefined) clearTimeout(graceTimer)
  395. graceTimer = undefined
  396. })()
  397. return treeExitObservation
  398. }
  399. // The escalation's tier primitive (not on the handle — terminate() is the
  400. // only consumer-facing termination verb). Guards on TREE liveness, not
  401. // outcome settlement: a TERM-trapping helper can outlive the settled direct
  402. // child and must stay signalable, while a fully-dead tree (possible pid
  403. // reuse) must not be re-signalled by a later tier.
  404. const kill = (sig: NodeJS.Signals): void => {
  405. /* v8 ignore next -- the shared exit observer cancels the ordinary dead-tree timer;
  406. this remains the timer/death race guard and cannot be staged deterministically. */
  407. if (!treeAlive()) return
  408. signalTree(platform, pid, sig, child, taskkill)
  409. }
  410. const terminate = (): void => {
  411. if (treeExitObserved || graceTimer !== undefined) return
  412. // Observe from the first termination tier onward, even when inherited
  413. // pipes delay `done` and no consumer has begun its own teardown wait.
  414. void observeTreeExit()
  415. // oxlint-disable-next-line typescript/no-unnecessary-condition -- observer can record absence before its first await.
  416. if (treeExitObserved) return
  417. kill('SIGTERM')
  418. // The escalation must survive direct-child settlement — the leader dying
  419. // does not mean the tree died — so settle does not clear this timer, and
  420. // kill() re-probes tree liveness before force-killing. It stays ref'd:
  421. // the pending SIGKILL is a commitment, and a parent exiting before it
  422. // fires would orphan a trapped survivor. Self-bounds at graceMs.
  423. graceTimer = setTimeout(() => { kill('SIGKILL') }, spec.graceMs)
  424. }
  425. const terminateForHostExit = (): void => {
  426. kill('SIGKILL')
  427. }
  428. // The caller owns timeout classification; this layer only reacts to abort.
  429. const onAbort = (): void => { terminate() }
  430. spec.signal?.addEventListener('abort', onAbort, { once: true })
  431. // Batch stdin is written and closed up front; process exit and captured
  432. // output remain authoritative, so write errors (EPIPE) are best-effort.
  433. if (typeof stdinMode === 'object' && child.stdin !== null) {
  434. child.stdin.on('error', () => { /* stdin write is best-effort; outcome rides on exit/output. */ })
  435. child.stdin.end(stdinMode.data)
  436. }
  437. const done = new Promise<SubprocessOutcome>((resolve, reject) => {
  438. let pipeDrainTimer: ReturnType<typeof setTimeout> | undefined
  439. const settle = (exitCode: number | null, signal: NodeJS.Signals | null): void => {
  440. if (settled) return
  441. settled = true
  442. // Only harness-collected pipes are force-closed at the drain boundary;
  443. // a 'pipe'-mode stream belongs to the caller and closes with the child.
  444. if (stdoutCollector !== undefined) child.stdout?.destroy()
  445. if (stderrCollector !== undefined) child.stderr?.destroy()
  446. stdoutCollector?.seal()
  447. stderrCollector?.seal()
  448. cleanup()
  449. resolve({ exitCode, signal })
  450. }
  451. child.on('error', (error) => {
  452. // No meaningful close outcome follows a spawn failure.
  453. settled = true
  454. cleanup()
  455. reject(error)
  456. })
  457. child.on('exit', (exitCode, signal) => {
  458. // A surviving descendant that inherited a pipe must not hold the
  459. // outcome open indefinitely: after exit, the same bounded grace that
  460. // governs kills also bounds the close wait.
  461. pipeDrainTimer = setTimeout(() => {
  462. settle(exitCode, signal)
  463. }, spec.graceMs)
  464. })
  465. child.on('close', settle)
  466. function cleanup(): void {
  467. // graceTimer deliberately NOT cleared: the SIGKILL escalation must be
  468. // able to reach tree survivors after the direct child settles.
  469. if (pipeDrainTimer !== undefined) clearTimeout(pipeDrainTimer)
  470. spec.signal?.removeEventListener('abort', onAbort)
  471. }
  472. })
  473. const waitForExit = async (signal?: AbortSignal): Promise<boolean> => {
  474. const observed = observeTreeExit()
  475. if (treeExitObserved) return true
  476. if (signal?.aborted) return false
  477. if (signal === undefined) {
  478. await observed
  479. return true
  480. }
  481. const aborted = Promise.withResolvers<boolean>()
  482. const onAbort = (): void => { aborted.resolve(false) }
  483. signal.addEventListener('abort', onAbort, { once: true })
  484. /* v8 ignore next -- closes the event-loop race between the preceding aborted check and listener registration. */
  485. if (signal.aborted) onAbort()
  486. try {
  487. return await Promise.race([observed.then(() => true), aborted.promise])
  488. } finally {
  489. signal.removeEventListener('abort', onAbort)
  490. }
  491. }
  492. return {
  493. pid,
  494. /* v8 ignore start -- pipe-mode fds exist on every spawn Node returns; the null-coalesces guard a nonconforming ChildProcess only. */
  495. stdin: stdinMode === 'pipe' ? child.stdin ?? undefined : undefined,
  496. stdout: outMode === 'pipe' ? child.stdout ?? undefined : undefined,
  497. stderr: errMode === 'pipe' ? child.stderr ?? undefined : undefined,
  498. /* v8 ignore stop */
  499. collected: {
  500. ...stdoutCollector !== undefined ? { stdout: stdoutCollector } : {},
  501. ...stderrCollector !== undefined ? { stderr: stderrCollector } : {},
  502. },
  503. done,
  504. terminate,
  505. terminateForHostExit,
  506. waitForExit,
  507. }
  508. }