spawn.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. /**
  2. * Process plumbing for the local subprocess service: ordinary process launch
  3. * with per-stream stdio dispositions, tail-keep collection with spill
  4. * files, provider-owned range signalling, and common termination scheduling.
  5. * POSIX owners stage TERM before KILL; Windows owners terminate immediately.
  6. * This layer reacts to an abort signal; callers own deadlines, teardown
  7. * ladders, and cause classification.
  8. * @module dsh-subprocess-local/spawn
  9. */
  10. import { type ChildProcess, spawn, spawnSync } from 'node:child_process'
  11. import type { Readable } from 'node:stream'
  12. import { randomBytes } from 'node:crypto'
  13. import { closeSync, mkdtempSync, openSync, unlinkSync, writeSync } from 'node:fs'
  14. import { tmpdir } from 'node:os'
  15. import { join } from 'node:path'
  16. import { setTimeout as sleepMs } from 'node:timers/promises'
  17. import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess'
  18. import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
  19. import type {
  20. CollectedOutput,
  21. SubprocessCollect,
  22. SubprocessHandle,
  23. SubprocessOutcome,
  24. SubprocessOutputMode,
  25. SubprocessSpawnSpec,
  26. } from '@deepseek-ai/dsh-subprocess'
  27. import type { BoundProcessOwner, ManagedProcessLaunch } from './managed-owner.ts'
  28. import { waitWithAbort } from './managed-owner.ts'
  29. import { linuxProcessGroupHasLiveMembers } from './process-inspector.ts'
  30. /**
  31. * Build a child environment: explicit caller entries override the scrubbed
  32. * parent base using the target platform's environment-key semantics. A string
  33. * deliberately restores or overrides an entry; an explicit `undefined`
  34. * tombstone removes an ordinary ambient entry.
  35. * @param extra - explicit caller entries and tombstones, merged after the scrub.
  36. * @returns the environment to hand to `spawn` for the child process.
  37. */
  38. export function childEnv(extra?: Readonly<NodeJS.ProcessEnv>): NodeJS.ProcessEnv {
  39. const env = scrubbedParentEnv()
  40. if (process.platform !== 'win32') return { ...env, ...extra }
  41. let entries: [string, string | undefined][] = Object.entries(env)
  42. for (const [key, value] of Object.entries(extra ?? {})) {
  43. const normalized = key.toUpperCase()
  44. entries = entries.filter(([inherited]) => inherited.toUpperCase() !== normalized)
  45. entries.push([key, value])
  46. }
  47. return Object.fromEntries(entries)
  48. }
  49. /** Injectable knobs so tests can exercise spill and platform behavior deterministically. */
  50. export interface SpawnInternals {
  51. /** Directory for spill files (defaults to the OS temp dir). */
  52. spillDir?: string
  53. /** Windows tree-termination runner (defaults to `taskkill /PID <pid> /T /F`). */
  54. taskkill?: (pid: number) => void
  55. /** Host platform override for signalling decisions. */
  56. platform?: NodeJS.Platform
  57. /** Linux process-group member probe (defaults to `/proc` inspection). */
  58. linuxProcessGroupHasLiveMembers?: (processGroupId: number) => boolean | undefined
  59. /** Test seam for the per-spawn Linux native prerequisite check. */
  60. linuxNativeAvailable?: () => boolean
  61. /** Test seam for the per-spawn Windows native prerequisite check. */
  62. windowsNativeAvailable?: () => boolean
  63. }
  64. /**
  65. * Local-only synchronous final termination used by the owning service during
  66. * host exit and as the last fallback after failed normal disposal. It is
  67. * intentionally absent from the public subprocess seam.
  68. */
  69. export interface LocalSubprocessHandle extends SubprocessHandle {
  70. /** Force-terminate the current tree synchronously without starting timers or waits. */
  71. terminateForHostExit(): void
  72. }
  73. /**
  74. * Liveness-poll cadence for tree-exit waits. The timer stays ref'd: an
  75. * awaited teardown must keep the event loop alive until the tree really
  76. * exits, or the parent can exit while claiming quiescence and orphan the
  77. * survivors it promised to reap.
  78. */
  79. function sleepTick(): Promise<void> {
  80. return sleepMs(15)
  81. }
  82. let spillCounter = 0
  83. let defaultSpillDir: string | undefined
  84. /**
  85. * The default spill location: a private (0700) per-process directory under
  86. * the OS tmpdir, created lazily. Predictable world-readable paths would let
  87. * other local users read command output or pre-create symlinks.
  88. */
  89. function privateSpillDir(): string {
  90. defaultSpillDir ??= mkdtempSync(join(tmpdir(), 'dsh-subprocess-'))
  91. return defaultSpillDir
  92. }
  93. /**
  94. * Prepare fallible output storage before starting a managed native process.
  95. * @param internals - optional caller-owned spill directory.
  96. * @returns binding inputs whose spill directory is ready for use.
  97. */
  98. export function prepareManagedProcessBinding(
  99. internals: Pick<SpawnInternals, 'spillDir'> = {},
  100. ): { spillDir: string } {
  101. return { spillDir: internals.spillDir ?? privateSpillDir() }
  102. }
  103. /**
  104. * Collects one stream with a bounded in-memory tail. With a spill cap, on
  105. * first overflow a spill file is created and every chunk (including those
  106. * already collected) is appended there while the full stream remains within
  107. * the cap; without one, only the in-memory tail is ever retained (the
  108. * diagnostic-tail shape — a language server's stderr).
  109. *
  110. * Tail-keep rationale (pi/OpenCode): errors and final results cluster at the
  111. * end of command output; the spill file covers the head.
  112. */
  113. export class OutputCollector {
  114. private chunks: Buffer[] = []
  115. private bytes = 0
  116. private dropped = false
  117. private spillFd: number | undefined
  118. private spillFile: string | undefined
  119. private spillDisabled: boolean
  120. /** Total bytes ever pushed (not just retained). */
  121. private total = 0
  122. constructor(
  123. private readonly maxBytes: number,
  124. private readonly maxSpillBytes: number | undefined,
  125. private readonly label: string,
  126. private readonly spillDir: string,
  127. ) {
  128. this.spillDisabled = maxSpillBytes === undefined
  129. }
  130. /**
  131. * Ingest one stream chunk, counting it toward the whole-stream total. On
  132. * first overflow of the in-memory cap a spill file is opened (when spilling
  133. * is enabled) and every chunk (already-collected ones included) is appended
  134. * there from then on; the in-memory tail then drops whole chunks from its
  135. * head (or the head of a single over-cap chunk) until it fits the cap again.
  136. * @param chunk - the raw bytes from one stream 'data' event.
  137. */
  138. push(chunk: Buffer): void {
  139. this.total += chunk.length
  140. const overflows = this.bytes + chunk.length > this.maxBytes
  141. if (!this.spillDisabled && (overflows || this.spillFd !== undefined)) this.spillAll(chunk)
  142. this.chunks.push(chunk)
  143. this.bytes += chunk.length
  144. while (this.bytes > this.maxBytes) {
  145. const head = this.chunks[0] as Buffer
  146. const excess = this.bytes - this.maxBytes
  147. if (head.length <= excess) {
  148. // Drop the whole head chunk (length ≥ 1 is guaranteed while over cap).
  149. this.chunks.shift()
  150. this.bytes -= head.length
  151. } else {
  152. // Trim the head so the retained window is byte-exact at the cap — a
  153. // diagnostic tail (an LSP server's stderr) must hold the LAST
  154. // maxBytes regardless of how the stream was chunked.
  155. this.chunks[0] = head.subarray(excess)
  156. this.bytes -= excess
  157. }
  158. this.dropped = true
  159. }
  160. }
  161. /** Open the spill file lazily and append `chunk` (and any prior chunks once). */
  162. private spillAll(chunk: Buffer): void {
  163. if (this.maxSpillBytes !== undefined && this.total > this.maxSpillBytes) {
  164. this.discardSpill()
  165. return
  166. }
  167. if (this.spillFd === undefined) {
  168. // Random suffix + O_EXCL + no-follow-equivalent ('wx' fails on any
  169. // existing path, symlink or not) + owner-only mode: defeats spill-path
  170. // prediction and symlink planting in shared tmp dirs.
  171. this.spillFile = join(
  172. this.spillDir,
  173. `dsh-subprocess-${process.pid}-${++spillCounter}-${randomBytes(6).toString('hex')}-${this.label}.log`,
  174. )
  175. this.spillFd = openSync(this.spillFile, 'wx', 0o600)
  176. for (const prior of this.chunks) writeSync(this.spillFd, prior)
  177. }
  178. writeSync(this.spillFd, chunk)
  179. }
  180. /** Stop spilling and remove the file once it can no longer hold the complete stream. */
  181. private discardSpill(): void {
  182. const fd = this.spillFd
  183. const file = this.spillFile
  184. this.spillFd = undefined
  185. this.spillFile = undefined
  186. this.spillDisabled = true
  187. if (fd !== undefined) {
  188. try {
  189. closeSync(fd)
  190. } catch {
  191. // Retain the descriptor so finalize can retry the failed close.
  192. this.spillFd = fd
  193. }
  194. }
  195. if (file !== undefined) {
  196. try {
  197. unlinkSync(file)
  198. } catch {
  199. // A failed unlink leaves at most maxSpillBytes behind, never an unbounded file.
  200. }
  201. }
  202. }
  203. /**
  204. * Incremental read in whole-stream byte coordinates: returns everything
  205. * pushed since `fromByte`. When `fromByte` has already slid out of the
  206. * in-memory tail window, the read is `lossy` — it returns the whole
  207. * retained tail and the gap is only recoverable from the spill file.
  208. * @param fromByte - whole-stream offset to resume from (a prior read's `nextOffset`; 0 for the first read).
  209. * @returns the delta text, the offset for the next read, the `lossy` flag, and the spill path when one was created.
  210. */
  211. readFrom(fromByte: number): { text: string; nextOffset: number; lossy: boolean; spillPath?: string } {
  212. const windowStart = this.total - this.bytes
  213. const buffer = Buffer.concat(this.chunks)
  214. const lossy = fromByte < windowStart
  215. const slice = lossy ? buffer : buffer.subarray(fromByte - windowStart)
  216. return {
  217. text: slice.toString('utf8'),
  218. nextOffset: this.total,
  219. lossy,
  220. ...this.spillFile !== undefined ? { spillPath: this.spillFile } : {},
  221. }
  222. }
  223. /**
  224. * Close the spill file once the stream has ended. A failed close (delayed
  225. * writeback fault) stops advertising the spill path — the file may be
  226. * missing its tail — while every in-memory read keeps working. Idempotent;
  227. * the spawn path seals both collectors at settlement so reads after exit
  228. * never point at a still-open file.
  229. */
  230. seal(): void {
  231. if (this.spillFd === undefined) return
  232. try {
  233. closeSync(this.spillFd)
  234. } catch {
  235. // A delayed writeback failure makes the spill unreliable; keep the
  236. // in-memory result but stop advertising that file.
  237. this.spillFile = undefined
  238. }
  239. this.spillFd = undefined
  240. }
  241. /**
  242. * Seal the spill file and return the final output.
  243. * @returns the final collected output: tail text, truncation flag, and the spill path when intact.
  244. */
  245. finalize(): CollectedOutput {
  246. this.seal()
  247. return {
  248. text: Buffer.concat(this.chunks).toString('utf8'),
  249. truncated: this.dropped,
  250. ...this.spillFile !== undefined ? { spillPath: this.spillFile } : {},
  251. }
  252. }
  253. }
  254. /**
  255. * Send `sig` to a detached POSIX process group. Never throws: delivery races
  256. * process exit and may run in a timer callback, so failures are contained and
  257. * a missing pid is a no-op.
  258. * @param pid - the group leader's pid, when the spawn published one.
  259. * @param sig - the signal to deliver to the whole group.
  260. */
  261. export function killGroup(pid: number | undefined, sig: NodeJS.Signals): void {
  262. if (pid === undefined) return
  263. try {
  264. process.kill(-pid, sig)
  265. } catch {
  266. // Swallow: see contract above.
  267. }
  268. }
  269. /**
  270. * Terminate one Windows process tree with `taskkill /T /F`. Contained like
  271. * POSIX group signalling — delivery races tree exit, so an absent tree, a
  272. * nonzero status, or a missing taskkill binary must not break idempotent
  273. * teardown.
  274. * @param pid - root process id, when the spawn published one.
  275. */
  276. export function taskkillProcessTree(pid: number | undefined): void {
  277. if (pid === undefined) return
  278. // Outcome deliberately unchecked: an already-absent tree (status 128), exit
  279. // races, and a missing taskkill binary (spawnSync reports, never throws) are
  280. // as tolerable here as ESRCH is for a POSIX group signal.
  281. spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore' })
  282. }
  283. /**
  284. * Signal a detached process tree with platform-correct semantics: POSIX
  285. * signals the negative process-group id and falls back to the direct child
  286. * when the group is gone; Windows terminates the tree via taskkill (any
  287. * signal value force-terminates — Node maps signals to TerminateProcess).
  288. */
  289. function signalTree(
  290. platform: NodeJS.Platform,
  291. pid: number | undefined,
  292. sig: NodeJS.Signals,
  293. child: ChildProcess,
  294. taskkill: (pid: number) => void,
  295. ): void {
  296. /* v8 ignore next -- kill/terminate gate on treeAlive(), which is false without a pid; this guard protects direct callers only. */
  297. if (pid === undefined) return
  298. if (platform === 'win32') {
  299. taskkill(pid)
  300. return
  301. }
  302. try {
  303. process.kill(-pid, sig)
  304. } catch {
  305. /* v8 ignore start -- the fallback needs a live child whose group signal fails
  306. (EPERM-style), which POSIX CI cannot stage; the swallow keeps teardown idempotent. */
  307. try {
  308. child.kill(sig)
  309. } catch {
  310. // The direct child already exited; teardown remains idempotent.
  311. }
  312. /* v8 ignore stop */
  313. }
  314. }
  315. /**
  316. * Validate the synchronous portion of one ordinary spawn request.
  317. * @param spec - exact target request.
  318. * @throws when grace, cancellation, or argv is invalid before launch.
  319. */
  320. export function validateSubprocessSpec(spec: SubprocessSpawnSpec): void {
  321. if (!Number.isFinite(spec.graceMs) || spec.graceMs <= 0 || spec.graceMs > MAX_TIMER_DELAY_MS) {
  322. throw new Error(`subprocess graceMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`)
  323. }
  324. if (spec.signal?.aborted) {
  325. throw spec.signal.reason
  326. }
  327. const [program] = spec.argv
  328. if (program === undefined || program.length === 0) {
  329. throw new Error('invalid argv: expected a non-empty program name at argv[0]')
  330. }
  331. }
  332. function directChildResult(child: ChildProcess): Promise<SubprocessOutcome> {
  333. return new Promise((resolve, reject) => {
  334. let completed = false
  335. child.once('error', (error) => {
  336. /* v8 ignore next -- ChildProcess may report a later operational error after its
  337. terminal exit event; the first terminal event owns the result. */
  338. if (completed) return
  339. completed = true
  340. reject(error)
  341. })
  342. child.once('exit', (exitCode, signal) => {
  343. /* v8 ignore next -- a spawn/kill error may be followed by exit; a Promise can publish only the first terminal event. */
  344. if (completed) return
  345. completed = true
  346. resolve({ exitCode, signal })
  347. })
  348. })
  349. }
  350. function fallbackOwner(
  351. platform: NodeJS.Platform,
  352. pid: number | undefined,
  353. child: ChildProcess,
  354. taskkill: (pid: number) => void,
  355. linuxGroupHasLiveMembers: (processGroupId: number) => boolean | undefined,
  356. direct: Promise<SubprocessOutcome>,
  357. ): BoundProcessOwner {
  358. let stopped = false
  359. let directSettled = false
  360. let observation: Promise<void> | undefined
  361. void direct.then(
  362. () => { directSettled = true },
  363. () => { directSettled = true },
  364. )
  365. const alive = (): boolean => {
  366. if (stopped || pid === undefined) return false
  367. if (platform === 'win32') return child.exitCode === null && child.signalCode === null
  368. try {
  369. process.kill(-pid, 0)
  370. if (directSettled && platform === 'linux' && linuxGroupHasLiveMembers(pid) === false) return false
  371. return true
  372. } catch (error) {
  373. const code = (error as NodeJS.ErrnoException).code
  374. if (code === 'ESRCH') return false
  375. /* v8 ignore start -- EPERM and non-POSIX negative-pid failures are platform defenses. */
  376. if (code === 'EPERM') return true
  377. return child.exitCode === null && child.signalCode === null
  378. /* v8 ignore stop */
  379. }
  380. }
  381. return {
  382. signal: (signal) => {
  383. if (!alive()) {
  384. stopped = true
  385. return
  386. }
  387. signalTree(platform, pid, signal, child, taskkill)
  388. },
  389. waitForExit: async () => {
  390. /* v8 ignore next -- bindManagedProcess memoizes this owner wait; the guard only
  391. protects direct internal re-entry after signal() observed absence. */
  392. if (stopped) return
  393. observation ??= (async () => {
  394. while (alive()) await sleepTick()
  395. stopped = true
  396. })()
  397. await observation
  398. },
  399. terminateForHostExit: () => {
  400. if (stopped) return
  401. signalTree(platform, pid, 'SIGKILL', child, taskkill)
  402. },
  403. }
  404. }
  405. /**
  406. * Bind platform launch facts to the existing stdio, outcome, abort, and termination lifecycle.
  407. * @param spec - fully resolved argv, cwd, stdio, grace, cancellation, environment.
  408. * @param launch - platform streams, direct outcome, and managed-range owner.
  409. * @param internals - test-only spill-directory override.
  410. * @returns live subprocess handle.
  411. */
  412. export function bindManagedProcess(
  413. spec: SubprocessSpawnSpec,
  414. launch: ManagedProcessLaunch,
  415. internals: Pick<SpawnInternals, 'spillDir'> = {},
  416. ): LocalSubprocessHandle {
  417. const { spillDir } = prepareManagedProcessBinding(internals)
  418. const { stdin, stdout, stderr } = launch
  419. const isCollect = (mode: SubprocessOutputMode): mode is SubprocessCollect =>
  420. mode !== 'pipe' && mode !== 'inherit'
  421. const outMode = spec.stdio.stdout
  422. const errMode = spec.stdio.stderr
  423. const stdinMode = spec.stdio.stdin
  424. const collectStream = (mode: SubprocessOutputMode, stream: Readable | null, label: string): OutputCollector | undefined => {
  425. if (!isCollect(mode) || stream === null) return undefined
  426. const collector = new OutputCollector(mode.maxBytes, mode.spill?.maxBytes, label, spillDir)
  427. stream.on('data', (chunk: Buffer) => { collector.push(chunk) })
  428. return collector
  429. }
  430. const stdoutCollector = collectStream(outMode, stdout, 'stdout')
  431. const stderrCollector = collectStream(errMode, stderr, 'stderr')
  432. const observeOutputStream = (mode: SubprocessOutputMode, stream: Readable | null): Promise<void> | undefined => {
  433. if (mode === 'inherit' || stream === null || stream.readableEnded || stream.destroyed) return undefined
  434. return new Promise((resolve) => {
  435. const settle = (): void => {
  436. stream.off('end', settle)
  437. stream.off('close', settle)
  438. stream.off('error', settle)
  439. resolve()
  440. }
  441. stream.once('end', settle)
  442. stream.once('close', settle)
  443. stream.once('error', settle)
  444. })
  445. }
  446. const stdoutClosed = observeOutputStream(outMode, stdout)
  447. const stderrClosed = observeOutputStream(errMode, stderr)
  448. const outputStreamsClosed = Promise.all([stdoutClosed, stderrClosed])
  449. const stopCollectors = (): void => {
  450. if (stdoutCollector !== undefined) stdout?.destroy()
  451. if (stderrCollector !== undefined) stderr?.destroy()
  452. stdoutCollector?.seal()
  453. stderrCollector?.seal()
  454. }
  455. let graceTimer: ReturnType<typeof setTimeout> | undefined
  456. let terminationStarted = false
  457. let rangeExitObserved = false
  458. let rangeExitObservation: Promise<void> | undefined
  459. let settled = false
  460. const scheduleOwnerCleanup = (): boolean => {
  461. if (launch.owner.cleanup === undefined) return false
  462. queueMicrotask(() => { void done.finally(() => { launch.owner.cleanup?.() }).catch(() => {}) })
  463. return true
  464. }
  465. /**
  466. * Start or reuse the handle's managed-range exit observer. A failed read
  467. * before direct settlement can be retried. Once direct settlement permits
  468. * cleanup, retain a failed observation because removing its private evidence
  469. * must not turn a later wait into a false success. The first confirmed
  470. * absence is the permanent no-more-signals boundary and cancels pending
  471. * escalation before stale identity can be used.
  472. */
  473. const observeRangeExit = (): Promise<void> => {
  474. rangeExitObservation ??= (async () => {
  475. await launch.owner.waitForExit()
  476. rangeExitObserved = true
  477. if (graceTimer !== undefined) clearTimeout(graceTimer)
  478. graceTimer = undefined
  479. spec.signal?.removeEventListener('abort', onAbort)
  480. scheduleOwnerCleanup()
  481. })().catch((error: unknown) => {
  482. if (!settled || !scheduleOwnerCleanup()) rangeExitObservation = undefined
  483. throw error
  484. })
  485. return rangeExitObservation
  486. }
  487. const kill = (sig: 'SIGTERM' | 'SIGKILL', cancellationReason?: unknown): void => {
  488. if (rangeExitObserved) return
  489. launch.owner.signal(sig, cancellationReason)
  490. }
  491. const terminateWithReason = (cancellationReason: unknown): void => {
  492. if (rangeExitObserved || terminationStarted) return
  493. terminationStarted = true
  494. // Keep the shared observation rejection available to waitForExit() without
  495. // leaking an unhandled rejection when a caller only invokes terminate().
  496. void observeRangeExit().catch(() => {})
  497. kill('SIGTERM', cancellationReason)
  498. graceTimer = setTimeout(() => {
  499. graceTimer = undefined
  500. kill('SIGKILL')
  501. }, spec.graceMs)
  502. }
  503. const terminate = (): void => {
  504. terminateWithReason(new Error('subprocess terminated before target start'))
  505. }
  506. const terminateForHostExit = (): void => {
  507. launch.owner.terminateForHostExit()
  508. }
  509. // The caller owns timeout classification; this layer only reacts to abort.
  510. const onAbort = (): void => { terminateWithReason(spec.signal?.reason) }
  511. spec.signal?.addEventListener('abort', onAbort, { once: true })
  512. if (spec.signal?.aborted === true) onAbort()
  513. // Batch stdin is written and closed up front; process exit and captured
  514. // output remain authoritative, so write errors (EPIPE) are best-effort.
  515. if (typeof stdinMode === 'object' && stdin !== null) {
  516. stdin.on('error', () => { /* stdin write is best-effort; outcome rides on exit/output. */ })
  517. stdin.end(stdinMode.data)
  518. }
  519. const done = new Promise<SubprocessOutcome>((resolve, reject) => {
  520. let pipeDrainTimer: ReturnType<typeof setTimeout> | undefined
  521. const settle = (outcome: SubprocessOutcome): void => {
  522. if (settled) return
  523. settled = true
  524. // Only harness-collected pipes are force-closed at the drain boundary;
  525. // a 'pipe'-mode stream belongs to the caller and closes with the child.
  526. stopCollectors()
  527. cleanup()
  528. resolve(outcome)
  529. }
  530. const fail = (error: unknown): void => {
  531. settled = true
  532. terminate()
  533. stopCollectors()
  534. cleanup()
  535. // Preserve the exact parent-local AbortSignal reason, including null or undefined.
  536. // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- Exact cancellation reason is the contract.
  537. reject(error)
  538. }
  539. launch.direct.then((outcome) => {
  540. if (stdoutClosed === undefined && stderrClosed === undefined) {
  541. settle(outcome)
  542. return
  543. }
  544. pipeDrainTimer = setTimeout(() => { settle(outcome) }, spec.graceMs)
  545. void outputStreamsClosed.then(() => { settle(outcome) })
  546. }, fail)
  547. function cleanup(): void {
  548. // graceTimer deliberately NOT cleared: forced termination must still
  549. // reach range survivors after the spawned command settles.
  550. if (pipeDrainTimer !== undefined) clearTimeout(pipeDrainTimer)
  551. }
  552. })
  553. const waitForExit = async (signal?: AbortSignal): Promise<boolean> => {
  554. if (rangeExitObserved) return true
  555. return waitWithAbort(observeRangeExit(), signal)
  556. }
  557. return {
  558. /* v8 ignore start -- pipe-mode streams exist on every conforming launch;
  559. the null-coalesces guard an internal adapter defect only. */
  560. stdin: stdinMode === 'pipe' ? stdin ?? undefined : undefined,
  561. stdout: outMode === 'pipe' ? stdout ?? undefined : undefined,
  562. stderr: errMode === 'pipe' ? stderr ?? undefined : undefined,
  563. /* v8 ignore stop */
  564. collected: {
  565. ...stdoutCollector !== undefined ? { stdout: stdoutCollector } : {},
  566. ...stderrCollector !== undefined ? { stderr: stderrCollector } : {},
  567. },
  568. done,
  569. terminate,
  570. terminateForHostExit,
  571. waitForExit,
  572. }
  573. }
  574. /**
  575. * Spawn one detached PGID/taskkill fallback and bind the common lifecycle.
  576. * @param spec - fully resolved argv, cwd, stdio, grace, cancellation, environment.
  577. * @param internals - test-only spill-directory, platform, and taskkill overrides.
  578. * @returns live subprocess handle.
  579. */
  580. export function spawnSubprocess(spec: SubprocessSpawnSpec, internals: SpawnInternals = {}): LocalSubprocessHandle {
  581. const binding = prepareManagedProcessBinding(internals)
  582. const platform = internals.platform ?? process.platform
  583. const [program, ...args] = spec.argv
  584. const child = spawn(program as string, args, {
  585. cwd: spec.cwd,
  586. env: childEnv(spec.env),
  587. stdio: [
  588. spec.stdio.stdin === 'ignore' ? 'ignore' : 'pipe',
  589. spec.stdio.stdout === 'inherit' ? 'inherit' : 'pipe',
  590. spec.stdio.stderr === 'inherit' ? 'inherit' : 'pipe',
  591. ],
  592. detached: platform !== 'win32',
  593. })
  594. const direct = directChildResult(child)
  595. const pid = child.pid
  596. const owner = fallbackOwner(
  597. platform,
  598. pid,
  599. child,
  600. internals.taskkill ?? taskkillProcessTree,
  601. internals.linuxProcessGroupHasLiveMembers ?? linuxProcessGroupHasLiveMembers,
  602. direct,
  603. )
  604. return bindManagedProcess(spec, {
  605. stdin: child.stdin,
  606. stdout: child.stdout,
  607. stderr: child.stderr,
  608. direct,
  609. owner,
  610. }, binding)
  611. }