spawn.ts 26 KB

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