spawn.ts 25 KB

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