@deepseek-ai/dsh-subprocess-local 0.2.2-rc.1 → 0.2.2-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.i18n.yaml +4 -4
  2. package/README.md +2 -2
  3. package/README.zh.md +2 -2
  4. package/lib/index.js +27 -13
  5. package/lib/{runner-launch-B2zsQ1Dz.js → runner-launch-CKTiL8M8.js} +41 -14
  6. package/lib/runner.js +8 -12
  7. package/lib/types/bin.d.ts.map +1 -0
  8. package/lib/types/bin.js.map +1 -0
  9. package/lib/types/control-spawn.d.ts.map +1 -0
  10. package/lib/types/control-spawn.js.map +1 -0
  11. package/lib/types/index.d.ts.map +1 -0
  12. package/lib/types/index.js.map +1 -0
  13. package/lib/types/linux-execve.d.ts +1 -1
  14. package/lib/types/linux-execve.d.ts.map +1 -0
  15. package/lib/types/linux-execve.js.map +1 -0
  16. package/lib/types/linux-scope-selector.d.ts.map +1 -0
  17. package/lib/types/linux-scope-selector.js.map +1 -0
  18. package/lib/types/linux-scope.d.ts.map +1 -0
  19. package/lib/types/linux-scope.js.map +1 -0
  20. package/lib/types/managed-owner.d.ts.map +1 -0
  21. package/lib/types/managed-owner.js.map +1 -0
  22. package/lib/types/output.d.ts.map +1 -0
  23. package/lib/types/output.js.map +1 -0
  24. package/lib/types/process-inspector.d.ts +9 -5
  25. package/lib/types/process-inspector.d.ts.map +1 -0
  26. package/lib/types/process-inspector.js.map +1 -0
  27. package/lib/types/runner-launch.d.ts +1 -1
  28. package/lib/types/runner-launch.d.ts.map +1 -0
  29. package/lib/types/runner-launch.js.map +1 -0
  30. package/lib/types/runner-protocol.d.ts +2 -0
  31. package/lib/types/runner-protocol.d.ts.map +1 -0
  32. package/lib/types/runner-protocol.js.map +1 -0
  33. package/lib/types/shell-activity.d.ts.map +1 -0
  34. package/lib/types/shell-activity.js.map +1 -0
  35. package/lib/types/spawn-runner.d.ts +2 -1
  36. package/lib/types/spawn-runner.d.ts.map +1 -0
  37. package/lib/types/spawn-runner.js.map +1 -0
  38. package/lib/types/spawn.d.ts +2 -2
  39. package/lib/types/spawn.d.ts.map +1 -0
  40. package/lib/types/spawn.js.map +1 -0
  41. package/lib/types/terminal.d.ts.map +1 -0
  42. package/lib/types/terminal.js.map +1 -0
  43. package/lib/types/windows-inspector.d.ts.map +1 -0
  44. package/lib/types/windows-inspector.js.map +1 -0
  45. package/lib/types/windows-job.d.ts.map +1 -0
  46. package/lib/types/windows-job.js.map +1 -0
  47. package/package.json +12 -9
  48. package/src/bin.ts +25 -0
  49. package/src/control-spawn.ts +35 -0
  50. package/src/index.ts +387 -0
  51. package/src/linux-execve.ts +92 -0
  52. package/src/linux-scope-selector.ts +101 -0
  53. package/src/linux-scope.ts +726 -0
  54. package/src/managed-owner.ts +56 -0
  55. package/src/output.ts +313 -0
  56. package/src/process-inspector.ts +560 -0
  57. package/src/runner-launch.ts +315 -0
  58. package/src/runner-protocol.ts +281 -0
  59. package/src/shell-activity.ts +131 -0
  60. package/src/spawn-runner.ts +488 -0
  61. package/src/spawn.ts +500 -0
  62. package/src/terminal.ts +479 -0
  63. package/src/windows-inspector.ts +346 -0
  64. package/src/windows-job.ts +269 -0
package/src/spawn.ts ADDED
@@ -0,0 +1,500 @@
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
+
11
+ import { type ChildProcess, type SpawnOptions, spawn, spawnSync } from 'node:child_process'
12
+ import type { Readable } from 'node:stream'
13
+ import { setTimeout as sleepMs } from 'node:timers/promises'
14
+ import { scrubbedParentEnv, SubprocessError } from '@deepseek-ai/dsh-subprocess'
15
+ import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
16
+ import type {
17
+ SubprocessCollect,
18
+ SubprocessHandle,
19
+ SubprocessOutcome,
20
+ SubprocessOutputMode,
21
+ SubprocessSpawnSpec,
22
+ } from '@deepseek-ai/dsh-subprocess'
23
+ import type { BoundProcessOwner, ManagedProcessLaunch } from './managed-owner.ts'
24
+ import { waitWithAbort } from './managed-owner.ts'
25
+ import { controlEnvironment, controlPipe } from './control-spawn.ts'
26
+ import { SUBPROCESS_CONTROL_FD } from '@deepseek-ai/dsh-subprocess/control'
27
+ import { linuxProcessGroupLiveMember } from './process-inspector.ts'
28
+ import { OutputCollector, prepareManagedProcessBinding, type SpillFailureReporter } from './output.ts'
29
+
30
+ type SpawnProcess = (
31
+ program: string,
32
+ args: readonly string[],
33
+ options: SpawnOptions,
34
+ ) => ChildProcess
35
+
36
+ /**
37
+ * Build a child environment: explicit caller entries override the scrubbed
38
+ * parent base using the target platform's environment-key semantics. A string
39
+ * deliberately restores or overrides an entry; an explicit `undefined`
40
+ * tombstone removes an ordinary ambient entry.
41
+ * @param extra - explicit caller entries and tombstones, merged after the scrub.
42
+ * @returns the environment to hand to `spawn` for the child process.
43
+ */
44
+ export function childEnv(extra?: Readonly<NodeJS.ProcessEnv>): NodeJS.ProcessEnv {
45
+ const env = scrubbedParentEnv()
46
+ if (process.platform !== 'win32') return { ...env, ...extra }
47
+ let entries: [string, string | undefined][] = Object.entries(env)
48
+ for (const [key, value] of Object.entries(extra ?? {})) {
49
+ const normalized = key.toUpperCase()
50
+ entries = entries.filter(([inherited]) => inherited.toUpperCase() !== normalized)
51
+ entries.push([key, value])
52
+ }
53
+ return Object.fromEntries(entries)
54
+ }
55
+
56
+ /** Injectable process, spill, and platform operations. */
57
+ export interface SpawnInternals {
58
+ /** Process spawner (defaults to `node:child_process` `spawn`). */
59
+ spawn?: SpawnProcess
60
+ /** Directory for spill files (defaults to the OS temp dir). */
61
+ spillDir?: string
62
+ /** Receives spill open/write failures; the runtime supplies its plugin logger, bare callers get a stderr line. */
63
+ onSpillFailure?: SpillFailureReporter
64
+ /** Windows tree-termination runner (defaults to `taskkill /PID <pid> /T /F`). */
65
+ taskkill?: (pid: number) => void
66
+ /** Host platform override for signalling decisions. */
67
+ platform?: NodeJS.Platform
68
+ /** Linux process-group live-member probe (defaults to `/proc` inspection); receives the member PID it last returned. */
69
+ linuxProcessGroupLiveMember?: (processGroupId: number, knownMember: number | undefined) => number | false | undefined
70
+ }
71
+
72
+ /**
73
+ * Local-only synchronous final termination used by the owning service during
74
+ * host exit and as the last fallback after failed normal disposal. It is
75
+ * intentionally absent from the public subprocess seam.
76
+ */
77
+ export interface LocalSubprocessHandle extends SubprocessHandle {
78
+ /** Force-terminate the current tree synchronously without starting timers or waits. */
79
+ terminateForHostExit(): void
80
+ }
81
+
82
+ /**
83
+ * Liveness-poll cadence for tree-exit waits. The timer stays ref'd: an
84
+ * awaited teardown must keep the event loop alive until the tree really
85
+ * exits, or the parent can exit while claiming quiescence and orphan the
86
+ * survivors it promised to reap.
87
+ */
88
+ function sleepTick(): Promise<void> {
89
+ return sleepMs(15)
90
+ }
91
+
92
+ /**
93
+ * Send `sig` to a detached POSIX process group. Never throws: delivery races
94
+ * process exit and may run in a timer callback, so failures are contained and
95
+ * a missing pid is a no-op.
96
+ * @param pid - the group leader's pid, when the spawn published one.
97
+ * @param sig - the signal to deliver to the whole group.
98
+ */
99
+ export function killGroup(pid: number | undefined, sig: NodeJS.Signals): void {
100
+ if (pid === undefined) return
101
+ try {
102
+ process.kill(-pid, sig)
103
+ } catch {
104
+ // Swallow: see contract above.
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Terminate one Windows process tree with `taskkill /T /F`. Contained like
110
+ * POSIX group signalling — delivery races tree exit, so an absent tree, a
111
+ * nonzero status, or a missing taskkill binary must not break idempotent
112
+ * teardown.
113
+ * @param pid - root process id, when the spawn published one.
114
+ */
115
+ export function taskkillProcessTree(pid: number | undefined): void {
116
+ if (pid === undefined || pid <= 0) return
117
+ // Outcome deliberately unchecked: an already-absent tree (status 128), exit
118
+ // races, and a missing taskkill binary (spawnSync reports, never throws) are
119
+ // as tolerable here as ESRCH is for a POSIX group signal.
120
+ spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], {
121
+ stdio: 'ignore',
122
+ windowsHide: true,
123
+ })
124
+ }
125
+
126
+ /**
127
+ * Signal a detached process tree with platform-correct semantics: POSIX
128
+ * signals the negative process-group id and falls back to the direct child
129
+ * when the group is gone; Windows terminates the tree via taskkill (any
130
+ * signal value force-terminates — Node maps signals to TerminateProcess).
131
+ */
132
+ function signalTree(
133
+ platform: NodeJS.Platform,
134
+ pid: number | undefined,
135
+ sig: NodeJS.Signals,
136
+ child: ChildProcess,
137
+ taskkill: (pid: number) => void,
138
+ ): void {
139
+ /* v8 ignore next -- kill/terminate gate on treeAlive(), which is false without a pid; this guard protects direct callers only. */
140
+ if (pid === undefined) return
141
+ if (platform === 'win32') {
142
+ taskkill(pid)
143
+ return
144
+ }
145
+ try {
146
+ process.kill(-pid, sig)
147
+ } catch {
148
+ /* v8 ignore start -- the fallback needs a live child whose group signal fails
149
+ (EPERM-style), which POSIX CI cannot stage; the swallow keeps teardown idempotent. */
150
+ try {
151
+ child.kill(sig)
152
+ } catch {
153
+ // The direct child already exited; teardown remains idempotent.
154
+ }
155
+ /* v8 ignore stop */
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Validate the synchronous portion of one ordinary spawn request.
161
+ * @param spec - exact target request.
162
+ * @throws when grace, cancellation, or argv is invalid before launch.
163
+ */
164
+ export function validateSubprocessSpec(spec: SubprocessSpawnSpec): void {
165
+ if (!Number.isFinite(spec.graceMs) || spec.graceMs <= 0 || spec.graceMs > MAX_TIMER_DELAY_MS) {
166
+ throw new Error(`subprocess graceMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`)
167
+ }
168
+ if (spec.signal?.aborted) {
169
+ let reason = 'aborted'
170
+ try {
171
+ reason = String(spec.signal.reason ?? reason)
172
+ } catch {
173
+ // Arbitrary caller-owned reasons cannot escape the stable Error boundary.
174
+ }
175
+ // Named as a cancellation so the tool registry classifies it as the caller's abort.
176
+ const error = new Error(`aborted before spawn: ${reason}`)
177
+ error.name = 'AbortError'
178
+ throw error
179
+ }
180
+ const [program] = spec.argv
181
+ if (program === undefined || program.length === 0) {
182
+ throw new SubprocessError('invalid argv: expected a non-empty program name at argv[0]', 'SUBPROCESS_INVALID_ARGV')
183
+ }
184
+ }
185
+
186
+ function directChildResult(child: ChildProcess): Promise<SubprocessOutcome> {
187
+ return new Promise((resolve, reject) => {
188
+ let completed = false
189
+ child.once('error', (error) => {
190
+ /* v8 ignore next -- ChildProcess may report a later operational error after its
191
+ terminal exit event; the first terminal event owns the result. */
192
+ if (completed) return
193
+ completed = true
194
+ reject(error)
195
+ })
196
+ child.once('exit', (exitCode, signal) => {
197
+ /* v8 ignore next -- a spawn/kill error may be followed by exit; a Promise can publish only the first terminal event. */
198
+ if (completed) return
199
+ completed = true
200
+ resolve({ exitCode, signal })
201
+ })
202
+ })
203
+ }
204
+
205
+ function fallbackOwner(
206
+ platform: NodeJS.Platform,
207
+ pid: number | undefined,
208
+ child: ChildProcess,
209
+ taskkill: (pid: number) => void,
210
+ linuxGroupLiveMember: (processGroupId: number, knownMember: number | undefined) => number | false | undefined,
211
+ direct: Promise<SubprocessOutcome>,
212
+ ): BoundProcessOwner {
213
+ let stopped = false
214
+ let directSettled = false
215
+ let observation: Promise<void> | undefined
216
+ let liveMember: number | undefined
217
+ void direct.then(
218
+ () => { directSettled = true },
219
+ () => { directSettled = true },
220
+ )
221
+
222
+ const alive = (): boolean => {
223
+ if (stopped || pid === undefined) return false
224
+ if (platform === 'win32') return child.exitCode === null && child.signalCode === null
225
+ try {
226
+ process.kill(-pid, 0)
227
+ if (directSettled && platform === 'linux') {
228
+ const member = linuxGroupLiveMember(pid, liveMember)
229
+ if (member === false) return false
230
+ if (member !== undefined) liveMember = member
231
+ }
232
+ return true
233
+ } catch (error) {
234
+ const code = (error as NodeJS.ErrnoException).code
235
+ if (code === 'ESRCH') return false
236
+ /* v8 ignore start -- EPERM and non-POSIX negative-pid failures are platform defenses. */
237
+ if (code === 'EPERM') return true
238
+ return child.exitCode === null && child.signalCode === null
239
+ /* v8 ignore stop */
240
+ }
241
+ }
242
+
243
+ return {
244
+ signal: (signal) => {
245
+ if (!alive()) {
246
+ stopped = true
247
+ return
248
+ }
249
+ signalTree(platform, pid, signal, child, taskkill)
250
+ },
251
+ waitForExit: async () => {
252
+ /* v8 ignore next -- bindManagedProcess memoizes this owner wait; the guard only
253
+ protects direct internal re-entry after signal() observed absence. */
254
+ if (stopped) return
255
+ observation ??= (async () => {
256
+ while (alive()) await sleepTick()
257
+ stopped = true
258
+ })()
259
+ await observation
260
+ },
261
+ terminateForHostExit: () => {
262
+ if (stopped) return
263
+ signalTree(platform, pid, 'SIGKILL', child, taskkill)
264
+ },
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Bind platform launch facts to the existing stdio, outcome, abort, and termination lifecycle.
270
+ * @param spec - fully resolved argv, cwd, stdio, grace, cancellation, environment.
271
+ * @param launch - platform streams, direct outcome, and managed-range owner.
272
+ * @param internals - spill-directory override and spill failure reporter.
273
+ * @returns live subprocess handle.
274
+ */
275
+ export function bindManagedProcess(
276
+ spec: SubprocessSpawnSpec,
277
+ launch: ManagedProcessLaunch,
278
+ internals: Pick<SpawnInternals, 'spillDir' | 'onSpillFailure'> = {},
279
+ ): LocalSubprocessHandle {
280
+ const { spillDir, onSpillFailure } = prepareManagedProcessBinding(internals)
281
+ const { stdin, stdout, stderr } = launch
282
+
283
+ const isCollect = (mode: SubprocessOutputMode): mode is SubprocessCollect =>
284
+ mode !== 'pipe' && mode !== 'inherit'
285
+ const outMode = spec.stdio.stdout
286
+ const errMode = spec.stdio.stderr
287
+ const stdinMode = spec.stdio.stdin
288
+
289
+ const collectStream = (mode: SubprocessOutputMode, stream: Readable | null, label: string): OutputCollector | undefined => {
290
+ if (!isCollect(mode) || stream === null) return undefined
291
+ const collector = new OutputCollector(
292
+ mode.maxBytes,
293
+ label,
294
+ mode.spill === undefined ? undefined : { maxBytes: mode.spill.maxBytes, dir: spillDir, onFailure: onSpillFailure },
295
+ )
296
+ stream.on('data', (chunk: Buffer) => { collector.push(chunk) })
297
+ return collector
298
+ }
299
+ const stdoutCollector = collectStream(outMode, stdout, 'stdout')
300
+ const stderrCollector = collectStream(errMode, stderr, 'stderr')
301
+ const observeOutputStream = (mode: SubprocessOutputMode, stream: Readable | null): Promise<void> | undefined => {
302
+ if (mode === 'inherit' || stream === null || stream.readableEnded || stream.destroyed) return undefined
303
+ return new Promise((resolve) => {
304
+ const settle = (): void => {
305
+ stream.off('end', settle)
306
+ stream.off('close', settle)
307
+ stream.off('error', settle)
308
+ resolve()
309
+ }
310
+ stream.once('end', settle)
311
+ stream.once('close', settle)
312
+ stream.once('error', settle)
313
+ })
314
+ }
315
+ const stdoutClosed = observeOutputStream(outMode, stdout)
316
+ const stderrClosed = observeOutputStream(errMode, stderr)
317
+ const outputStreamsClosed = Promise.all([stdoutClosed, stderrClosed])
318
+ const stopCollectors = (): void => {
319
+ if (stdoutCollector !== undefined) stdout?.destroy()
320
+ if (stderrCollector !== undefined) stderr?.destroy()
321
+ stdoutCollector?.seal()
322
+ stderrCollector?.seal()
323
+ }
324
+
325
+ let graceTimer: ReturnType<typeof setTimeout> | undefined
326
+ let terminationStarted = false
327
+ let rangeExitObserved = false
328
+ let rangeExitObservation: Promise<void> | undefined
329
+ let settled = false
330
+
331
+ const scheduleOwnerCleanup = (): boolean => {
332
+ if (launch.owner.cleanup === undefined) return false
333
+ queueMicrotask(() => { void done.finally(() => { launch.owner.cleanup?.() }).catch(() => {}) })
334
+ return true
335
+ }
336
+
337
+ /**
338
+ * Start or reuse the handle's managed-range exit observer. A failed read
339
+ * before direct settlement can be retried. Once direct settlement permits
340
+ * cleanup, retain a failed observation because removing its private evidence
341
+ * must not turn a later wait into a false success. The first confirmed
342
+ * absence is the permanent no-more-signals boundary and cancels pending
343
+ * escalation before stale identity can be used.
344
+ */
345
+ const observeRangeExit = (): Promise<void> => {
346
+ rangeExitObservation ??= (async () => {
347
+ await launch.owner.waitForExit()
348
+ rangeExitObserved = true
349
+ if (graceTimer !== undefined) clearTimeout(graceTimer)
350
+ graceTimer = undefined
351
+ spec.signal?.removeEventListener('abort', onAbort)
352
+ scheduleOwnerCleanup()
353
+ })().catch((error: unknown) => {
354
+ if (!settled || !scheduleOwnerCleanup()) rangeExitObservation = undefined
355
+ throw error
356
+ })
357
+ return rangeExitObservation
358
+ }
359
+
360
+ const kill = (sig: 'SIGTERM' | 'SIGKILL', cancellationReason?: unknown): void => {
361
+ if (rangeExitObserved) return
362
+ launch.owner.signal(sig, cancellationReason)
363
+ }
364
+
365
+ const terminateWithReason = (cancellationReason: unknown): void => {
366
+ if (rangeExitObserved || terminationStarted) return
367
+ terminationStarted = true
368
+ // Keep the shared observation rejection available to waitForExit() without
369
+ // leaking an unhandled rejection when a caller only invokes terminate().
370
+ void observeRangeExit().catch(() => {})
371
+ kill('SIGTERM', cancellationReason)
372
+ graceTimer = setTimeout(() => {
373
+ graceTimer = undefined
374
+ kill('SIGKILL')
375
+ }, spec.graceMs)
376
+ }
377
+
378
+ const terminate = (): void => {
379
+ terminateWithReason(new Error('subprocess terminated before target start'))
380
+ }
381
+
382
+ const terminateForHostExit = (): void => {
383
+ launch.owner.terminateForHostExit()
384
+ }
385
+
386
+ // The caller owns timeout classification; this layer only reacts to abort.
387
+ const onAbort = (): void => { terminateWithReason(spec.signal?.reason) }
388
+ spec.signal?.addEventListener('abort', onAbort, { once: true })
389
+
390
+ // Batch stdin is written and closed up front; process exit and captured
391
+ // output remain authoritative, so write errors (EPIPE) are best-effort.
392
+ if (typeof stdinMode === 'object' && stdin !== null) {
393
+ stdin.on('error', () => { /* stdin write is best-effort; outcome rides on exit/output. */ })
394
+ stdin.end(stdinMode.data)
395
+ }
396
+
397
+ const done = new Promise<SubprocessOutcome>((resolve, reject) => {
398
+ let pipeDrainTimer: ReturnType<typeof setTimeout> | undefined
399
+ const settle = (outcome: SubprocessOutcome): void => {
400
+ if (settled) return
401
+ settled = true
402
+ // Only harness-collected pipes are force-closed at the drain boundary;
403
+ // a 'pipe'-mode stream belongs to the caller and closes with the child.
404
+ stopCollectors()
405
+ cleanup()
406
+ resolve(outcome)
407
+ }
408
+ const fail = (error: unknown): void => {
409
+ settled = true
410
+ terminate()
411
+ stopCollectors()
412
+ cleanup()
413
+ // Preserve the exact parent-local AbortSignal reason, including null or undefined.
414
+ // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- Exact cancellation reason is the contract.
415
+ reject(error)
416
+ }
417
+ launch.direct.then((outcome) => {
418
+ if (stdoutClosed === undefined && stderrClosed === undefined) {
419
+ settle(outcome)
420
+ return
421
+ }
422
+ pipeDrainTimer = setTimeout(() => { settle(outcome) }, spec.graceMs)
423
+ void outputStreamsClosed.then(() => { settle(outcome) })
424
+ }, fail)
425
+ function cleanup(): void {
426
+ // graceTimer deliberately NOT cleared: forced termination must still
427
+ // reach range survivors after the spawned command settles.
428
+ if (pipeDrainTimer !== undefined) clearTimeout(pipeDrainTimer)
429
+ }
430
+ })
431
+
432
+ const waitForExit = async (signal?: AbortSignal): Promise<boolean> => {
433
+ if (rangeExitObserved) return true
434
+ return waitWithAbort(observeRangeExit(), signal)
435
+ }
436
+
437
+ return {
438
+ /* v8 ignore start -- pipe-mode streams exist on every conforming launch;
439
+ the null-coalesces guard an internal adapter defect only. */
440
+ stdin: stdinMode === 'pipe' ? stdin ?? undefined : undefined,
441
+ stdout: outMode === 'pipe' ? stdout ?? undefined : undefined,
442
+ stderr: errMode === 'pipe' ? stderr ?? undefined : undefined,
443
+ control: launch.control,
444
+ /* v8 ignore stop */
445
+ collected: {
446
+ ...stdoutCollector !== undefined ? { stdout: stdoutCollector } : {},
447
+ ...stderrCollector !== undefined ? { stderr: stderrCollector } : {},
448
+ },
449
+ done,
450
+ terminate,
451
+ terminateForHostExit,
452
+ waitForExit,
453
+ }
454
+ }
455
+
456
+ /**
457
+ * Spawn one detached PGID/taskkill fallback and bind the common lifecycle.
458
+ * @param spec - fully resolved argv, cwd, stdio, grace, cancellation, environment.
459
+ * @param internals - test-only spill-directory, platform, and taskkill overrides.
460
+ * @returns live subprocess handle.
461
+ */
462
+ export function spawnSubprocess(spec: SubprocessSpawnSpec, internals: SpawnInternals = {}): LocalSubprocessHandle {
463
+ const binding = prepareManagedProcessBinding(internals)
464
+ const platform = internals.platform ?? process.platform
465
+ const [program, ...args] = spec.argv
466
+ const stdio: import('node:child_process').StdioOptions = [
467
+ spec.stdio.stdin === 'ignore' ? 'ignore' : 'pipe',
468
+ spec.stdio.stdout === 'inherit' ? 'inherit' : 'pipe',
469
+ spec.stdio.stderr === 'inherit' ? 'inherit' : 'pipe',
470
+ ]
471
+ if (spec.stdio.control === 'pipe') {
472
+ while (stdio.length < SUBPROCESS_CONTROL_FD) stdio.push('ignore')
473
+ stdio.push('overlapped')
474
+ }
475
+ const child = (internals.spawn ?? spawn)(program as string, args, {
476
+ cwd: spec.cwd,
477
+ env: controlEnvironment(childEnv(spec.env), spec.stdio.control),
478
+ stdio,
479
+ detached: platform !== 'win32',
480
+ windowsHide: platform === 'win32',
481
+ })
482
+ const direct = directChildResult(child)
483
+ const pid = child.pid
484
+ const owner = fallbackOwner(
485
+ platform,
486
+ pid,
487
+ child,
488
+ internals.taskkill ?? taskkillProcessTree,
489
+ internals.linuxProcessGroupLiveMember ?? linuxProcessGroupLiveMember,
490
+ direct,
491
+ )
492
+ return bindManagedProcess(spec, {
493
+ stdin: child.stdin,
494
+ stdout: child.stdout,
495
+ stderr: child.stderr,
496
+ control: controlPipe(child, spec.stdio.control),
497
+ direct,
498
+ owner,
499
+ }, binding)
500
+ }