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

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 +14 -11
  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
@@ -0,0 +1,479 @@
1
+ /** Local node-pty terminal-process implementation for the subprocess seam. */
2
+
3
+ import { Buffer } from 'node:buffer'
4
+ import { constants } from 'node:os'
5
+ import { PassThrough } from 'node:stream'
6
+ import type { IDisposable, IPty } from 'node-pty'
7
+ import type {
8
+ SubprocessOutcome,
9
+ SubprocessTerminalActivity,
10
+ SubprocessTerminalForeground,
11
+ SubprocessTerminalHandle,
12
+ SubprocessTerminalSignal,
13
+ } from '@deepseek-ai/dsh-subprocess'
14
+ import type { BoundProcessOwner } from './managed-owner.ts'
15
+ import type { ProcessIdentity, ProcessInspector, ProcessSnapshot } from './process-inspector.ts'
16
+ import type { ShellActivity } from './shell-activity.ts'
17
+
18
+ function delay(ms: number, signal?: AbortSignal): Promise<void> {
19
+ return new Promise((resolve) => {
20
+ const finish = (): void => {
21
+ clearTimeout(timer)
22
+ signal?.removeEventListener('abort', finish)
23
+ resolve()
24
+ }
25
+ const timer = setTimeout(finish, ms)
26
+ signal?.addEventListener('abort', finish, { once: true })
27
+ })
28
+ }
29
+
30
+ async function raceWithDelay<T, U>(operation: Promise<T>, ms: number, timeout: U): Promise<T | U> {
31
+ const controller = new AbortController()
32
+ try {
33
+ return await Promise.race([
34
+ operation,
35
+ delay(ms, controller.signal).then(() => timeout),
36
+ ])
37
+ } finally {
38
+ controller.abort()
39
+ }
40
+ }
41
+
42
+ function signalName(number: number | undefined): NodeJS.Signals | null {
43
+ if (number === undefined || number === 0) return null
44
+ for (const [name, value] of Object.entries(constants.signals)) {
45
+ if (value === number) return name as NodeJS.Signals
46
+ }
47
+ return null
48
+ }
49
+
50
+ /**
51
+ * A local terminal whose native managed range or fallback process-session
52
+ * ownership stays below the PTY backend.
53
+ * The seam's terminate() promise — no write, inspection, or signal in flight
54
+ * after settlement — holds here without operation tracking only because every
55
+ * handle call completes synchronously under the hood (node-pty write, ps-based
56
+ * inspection). A first genuinely asynchronous step in any handle call must add
57
+ * the tracking a remote provider needs.
58
+ */
59
+ export class LocalTerminalHandle implements SubprocessTerminalHandle {
60
+ readonly pid: number
61
+ readonly output = new PassThrough()
62
+ readonly done: Promise<SubprocessOutcome>
63
+
64
+ private readonly outcome = Promise.withResolvers<SubprocessOutcome>()
65
+ private readonly dataDisposable: IDisposable
66
+ private readonly exitDisposable: IDisposable
67
+ private cleanup: Promise<void> | undefined
68
+ private managedOwnerCleaned = false
69
+ private exited = false
70
+ private outputPaused = false
71
+ private trackedDescendants: ProcessIdentity[] = []
72
+ private activityRevision = 0
73
+ private activityKey = ''
74
+ private quiescent = false
75
+ private managedRangeEmpty = false
76
+ /** The spawned shell's start identity; scans stop adopting members once the root pid no longer carries it. */
77
+ private readonly rootIdentity: ProcessIdentity | undefined
78
+
79
+ /**
80
+ * @param terminal - allocated node-pty process.
81
+ * @param inspector - platform process/session operations.
82
+ * @param graceMs - TERM-to-KILL and exit-wait grace.
83
+ * @param platform - host platform; defaults to the running platform, injectable for deterministic tests.
84
+ */
85
+ constructor(
86
+ private readonly terminal: IPty,
87
+ private readonly inspector: ProcessInspector,
88
+ private readonly graceMs: number,
89
+ private readonly platform: NodeJS.Platform = process.platform,
90
+ private readonly managedOwner?: BoundProcessOwner,
91
+ private readonly resolveManagedOutcome?: (outcome: SubprocessOutcome) => SubprocessOutcome,
92
+ private readonly shellActivity?: Pick<ShellActivity, 'inspect' | 'invalidate' | 'dispose'>,
93
+ private readonly onQuiescence?: () => void,
94
+ private readonly observeShellExit = false,
95
+ ) {
96
+ this.pid = terminal.pid
97
+ try { this.rootIdentity = inspector.snapshot().tree(this.pid).find(member => member.pid === this.pid) }
98
+ catch (_rootIdentityUnavailable) { this.rootIdentity = undefined }
99
+ this.done = this.outcome.promise
100
+ const resume = (): void => {
101
+ if (!this.outputPaused) return
102
+ this.outputPaused = false
103
+ if (!this.exited) terminal.resume()
104
+ }
105
+ this.output.on('drain', resume)
106
+ this.output.once('close', () => { this.output.off('drain', resume) })
107
+ this.dataDisposable = terminal.onData((data) => {
108
+ if (!this.output.write(Buffer.from(data, 'utf8')) && this.cleanup === undefined && !this.outputPaused) {
109
+ this.outputPaused = true
110
+ terminal.pause()
111
+ }
112
+ })
113
+ this.exitDisposable = terminal.onExit(({ exitCode, signal: exitSignal }) => {
114
+ if (this.exited) return
115
+ this.exited = true
116
+ if (this.managedOwner !== undefined && this.observeShellExit) {
117
+ void this.managedOwner.waitForExit().then(() => { this.managedRangeEmpty = true }).catch(() => {
118
+ // Failed range observation cannot authorize idle reclamation.
119
+ })
120
+ }
121
+ this.output.end()
122
+ const outcome = {
123
+ exitCode: exitSignal === undefined || exitSignal === 0 ? exitCode : null,
124
+ signal: signalName(exitSignal),
125
+ }
126
+ try {
127
+ this.outcome.resolve(this.resolveManagedOutcome?.(outcome) ?? outcome)
128
+ } catch (error) {
129
+ this.outcome.reject(error)
130
+ }
131
+ })
132
+ }
133
+
134
+ /** Whether node-pty has not yet published the top-level exit event. */
135
+ get running(): boolean {
136
+ return !this.exited
137
+ }
138
+
139
+ // node-pty writes synchronously; the seam returns a promise for remote transports.
140
+ // oxlint-disable-next-line typescript/require-await -- Preserve promise rejection semantics at the async provider contract.
141
+ async write(data: string): Promise<void> {
142
+ if (this.exited) throw new Error('terminal process has exited')
143
+ this.shellActivity?.invalidate()
144
+ this.terminal.write(data)
145
+ }
146
+
147
+ // oxlint-disable-next-line typescript/require-await -- Provider operations share promise rejection semantics.
148
+ async resize(cols: number, rows: number): Promise<void> {
149
+ if (this.exited) throw new Error('terminal process has exited')
150
+ this.terminal.resize(cols, rows)
151
+ }
152
+
153
+ // Local inspection is synchronous; the seam returns a promise for remote transports.
154
+ // oxlint-disable-next-line typescript/require-await -- Preserve promise rejection semantics at the async provider contract.
155
+ async inspectForeground(): Promise<SubprocessTerminalForeground | undefined> {
156
+ this.descendants(this.inspector.snapshot())
157
+ const processGroupId = this.inspector.foregroundPgid(this.pid)
158
+ if (processGroupId === undefined) return undefined
159
+ return {
160
+ processGroupId,
161
+ inputWaiting: this.inspector.isStdinWaiting(processGroupId, this.pid),
162
+ }
163
+ }
164
+
165
+ // oxlint-disable-next-line typescript/require-await -- Local inspection is synchronous; SSH shares this promise interface.
166
+ async inspectActivity(): Promise<SubprocessTerminalActivity> {
167
+ let state: SubprocessTerminalActivity['state'] = this.quiescent ? 'idle' : 'unknown'
168
+ let revision = 0
169
+ if (!this.quiescent) {
170
+ try {
171
+ const shell = this.shellActivity?.inspect(this.pid) ?? { state: 'unknown' as const, revision: 0 }
172
+ revision = shell.revision
173
+ const observed = this.inspector.snapshot()
174
+ const descendants = this.descendants(observed)
175
+ const root = observed.tree(this.pid).find(member => member.pid === this.pid)
176
+ if (this.exited && this.managedRangeEmpty) state = 'idle'
177
+ else if (descendants.length > 0) state = 'busy'
178
+ else if (this.exited && this.managedOwner === undefined && this.platform === 'linux' && observed.complete === true && root === undefined) {
179
+ state = observed.session(this.pid).some(member => observed.alive(member)) ? 'busy' : 'idle'
180
+ }
181
+ else if (observed.complete === true && root?.started === this.rootIdentity?.started && root !== undefined) {
182
+ const foreground = this.inspector.foregroundPgid(this.pid)
183
+ state = foreground === undefined ? 'unknown' : foreground === this.pid ? shell.state : 'busy'
184
+ if (state === 'idle' && this.managedOwner !== undefined) {
185
+ const tasks = this.managedOwner.inspectTaskCount?.()
186
+ state = tasks === undefined || tasks < 1 ? 'unknown' : tasks === 1 ? 'idle' : 'busy'
187
+ }
188
+ }
189
+ } catch (_incompleteActivityObservation) { state = 'unknown' }
190
+ }
191
+ const key = `${revision}:${state}`
192
+ if (key !== this.activityKey) { this.activityKey = key; this.activityRevision++ }
193
+ return { state, revision: this.activityRevision }
194
+ }
195
+
196
+ async signalForeground(signal: SubprocessTerminalSignal): Promise<number> {
197
+ this.shellActivity?.invalidate()
198
+ const foreground = await this.inspectForeground()
199
+ if (foreground === undefined) {
200
+ throw new Error(`cannot resolve foreground process group for terminal ${this.pid}`)
201
+ }
202
+ if (signal === 'SIGKILL' && foreground.processGroupId === this.pid) {
203
+ throw new Error('refusing to SIGKILL the terminal shell; terminate the terminal session instead')
204
+ }
205
+ if (this.platform === 'win32') {
206
+ if (signal === 'SIGINT') {
207
+ // Windows has no process-group signalling: a `\x03` input write is the
208
+ // Ctrl-C delivery path the console host turns into a console-wide
209
+ // CTRL_C event for attached processes. node-pty's signal kills throw on Windows, so
210
+ // no signal ever reaches the inspector.
211
+ this.terminal.write('\x03')
212
+ return foreground.processGroupId
213
+ }
214
+ if (signal === 'SIGTSTP' || signal === 'SIGHUP') {
215
+ throw new Error(`signal ${signal} is unsupported on Windows; only SIGINT, SIGTERM, and SIGKILL are available`)
216
+ }
217
+ }
218
+ this.inspector.signalGroup(foreground.processGroupId, signal)
219
+ return foreground.processGroupId
220
+ }
221
+
222
+ terminate(): Promise<void> {
223
+ if (this.cleanup !== undefined) return this.cleanup
224
+ if (this.outputPaused) { this.outputPaused = false; this.terminal.resume() }
225
+ const cleanup = this.closeOnce().then(() => {
226
+ this.quiescent = true
227
+ this.shellActivity?.dispose()
228
+ this.onQuiescence?.()
229
+ })
230
+ this.cleanup = cleanup
231
+ void cleanup.catch(() => { this.cleanup = undefined })
232
+ return cleanup
233
+ }
234
+
235
+ /**
236
+ * Force-terminate the observable session synchronously during Node's exit
237
+ * event. This does not claim quiescence and does not replace terminate().
238
+ */
239
+ terminateForHostExit(): void {
240
+ this.forceStopDescendants()
241
+ this.forceStopShell()
242
+ this.forceStopDescendants()
243
+ this.managedOwner?.terminateForHostExit()
244
+ }
245
+
246
+ private forceStopShell(): void {
247
+ if (this.exited) return
248
+ if (this.rootIdentity !== undefined) {
249
+ try {
250
+ this.inspector.signalProcess(this.rootIdentity, 'SIGKILL')
251
+ } catch (_rootExitedDuringHostExit) {
252
+ // Exact identity signalling contains both exit races and PID reuse.
253
+ }
254
+ return
255
+ }
256
+ try {
257
+ this.terminal.kill('SIGKILL')
258
+ } catch (_unidentifiedShellExitedDuringHostExit) {
259
+ // Without a captured identity, node-pty is the only root kill primitive.
260
+ }
261
+ }
262
+
263
+ private survivors(members: ProcessIdentity[], observed: ProcessSnapshot): ProcessIdentity[] {
264
+ return members.filter(member => observed.alive(member))
265
+ }
266
+
267
+ private descendants(observed: ProcessSnapshot): ProcessIdentity[] {
268
+ // Adopt newly scanned members only while the numeric root pid provably
269
+ // still carries the spawned shell's start identity: after the shell dies,
270
+ // a recycled pid's tree and session must not donate an unrelated
271
+ // process's children to this session's signalling. Already-adopted
272
+ // members keep their own start identities, which every signal rechecks.
273
+ const tree = observed.tree(this.pid)
274
+ const root = tree.find(member => member.pid === this.pid)
275
+ const rootVerified = this.rootIdentity !== undefined
276
+ && root !== undefined
277
+ && root.started === this.rootIdentity.started
278
+ this.trackedDescendants = this.survivors(this.unionMembers(
279
+ this.trackedDescendants,
280
+ ...rootVerified ? [tree, observed.session(this.pid)] : [],
281
+ ).filter(member => member.pid !== this.pid), observed)
282
+ return this.trackedDescendants
283
+ }
284
+
285
+ private async waitForMembers(members: ProcessIdentity[]): Promise<ProcessIdentity[]> {
286
+ if (members.length === 0) return []
287
+ const until = Date.now() + this.graceMs
288
+ let survivors = this.survivors(members, this.inspector.snapshot())
289
+ while (survivors.length > 0 && Date.now() < until) {
290
+ await delay(Math.min(25, Math.max(1, until - Date.now())))
291
+ survivors = this.survivors(members, this.inspector.snapshot())
292
+ }
293
+ return survivors
294
+ }
295
+
296
+ private signalMembers(members: ProcessIdentity[], signal: 'SIGTERM' | 'SIGKILL'): void {
297
+ for (const member of members) {
298
+ try {
299
+ // Each signal reads its own identity fence, inside this try: a failed
300
+ // read must cost one target, never the rest of a teardown round.
301
+ this.inspector.signalProcess(member, signal)
302
+ } catch (_alreadyExitedDuringSignal) {
303
+ // The exact process identity is rechecked; a same-tick exit is success.
304
+ }
305
+ }
306
+ }
307
+
308
+ private forceStopDescendants(): void {
309
+ let members = this.trackedDescendants
310
+ try {
311
+ members = this.descendants(this.inspector.snapshot())
312
+ } catch (_processTableUnavailableDuringHostExit) {
313
+ // Preserve already-captured identities when a final process-table scan fails.
314
+ }
315
+ this.signalMembers(members, 'SIGKILL')
316
+ }
317
+
318
+ private unionMembers(...groups: ProcessIdentity[][]): ProcessIdentity[] {
319
+ const members: ProcessIdentity[] = []
320
+ const seen = new Set<string>()
321
+ for (const group of groups) {
322
+ for (const member of group) {
323
+ const key = `${member.pid}:${member.started}`
324
+ if (seen.has(key)) continue
325
+ seen.add(key)
326
+ members.push(member)
327
+ }
328
+ }
329
+ return members
330
+ }
331
+
332
+ private async stopDescendants(): Promise<ProcessIdentity[]> {
333
+ const captured = this.descendants(this.inspector.snapshot())
334
+ this.signalMembers(captured, 'SIGTERM')
335
+ const capturedSurvivors = await this.waitForMembers(captured)
336
+ const members = this.unionMembers(capturedSurvivors, this.descendants(this.inspector.snapshot()))
337
+ this.signalMembers(members, 'SIGKILL')
338
+ const survivors = await this.waitForMembers(members)
339
+ const observed = this.inspector.snapshot()
340
+ return this.survivors(this.unionMembers(survivors, this.descendants(observed)), observed)
341
+ }
342
+
343
+ private async stopShell(): Promise<void> {
344
+ if (this.platform === 'win32') {
345
+ await this.stopShellWindows()
346
+ return
347
+ }
348
+ if (!this.exited) {
349
+ try {
350
+ this.terminal.kill('SIGTERM')
351
+ } catch (_topLevelAlreadyExitedDuringTerm) {
352
+ // The exit callback is authoritative.
353
+ }
354
+ await Promise.race([this.done.then(() => undefined), delay(this.graceMs)])
355
+ }
356
+ if (!this.exited) {
357
+ try {
358
+ this.terminal.kill('SIGKILL')
359
+ } catch (_topLevelAlreadyExitedDuringKill) {
360
+ // The exit callback is authoritative.
361
+ }
362
+ await Promise.race([this.done.then(() => undefined), delay(this.graceMs)])
363
+ }
364
+ if (!this.exited) throw new Error(`terminal cleanup failed; surviving pid: ${this.pid}`)
365
+ }
366
+
367
+ private async stopShellWindows(): Promise<void> {
368
+ // node-pty's Windows kill(signal) throws ("Signals not supported on
369
+ // windows"), and its bare kill() reaches the console host by a per-host
370
+ // path: Windows' own host goes through a console-list agent that fails when
371
+ // the parent has no console, while the bundled OpenConsole runs a native
372
+ // kill plus conout teardown. taskkill tree escalation is the teardown path,
373
+ // fenced on the shell's start identity like every descendant; a root
374
+ // identity miss falls back to the bare kill. taskkill termination also does
375
+ // not reliably fire node-pty's exit notification, so the tiers verify the
376
+ // shell's absence through the inspector instead of waiting on `done` alone.
377
+ const shellGone = (): boolean =>
378
+ this.exited || (this.rootIdentity !== undefined && !this.inspector.isAlive(this.rootIdentity))
379
+ if (!shellGone() && this.rootIdentity !== undefined) {
380
+ this.inspector.signalProcess(this.rootIdentity, 'SIGTERM')
381
+ await this.waitForWindowsShellExit()
382
+ }
383
+ if (!shellGone() && this.rootIdentity === undefined) {
384
+ try {
385
+ this.terminal.kill()
386
+ } catch (_topLevelAlreadyExitedDuringKill) {
387
+ // The exit callback is authoritative.
388
+ }
389
+ await Promise.race([this.done.then(() => undefined), delay(this.graceMs)])
390
+ }
391
+ if (!shellGone() && this.rootIdentity !== undefined) {
392
+ this.inspector.signalProcess(this.rootIdentity, 'SIGKILL')
393
+ await this.waitForWindowsShellExit()
394
+ }
395
+ if (!shellGone()) throw new Error(`terminal cleanup failed; surviving pid: ${this.pid}`)
396
+ }
397
+
398
+ private async waitForWindowsShellExit(): Promise<void> {
399
+ const until = Date.now() + this.graceMs
400
+ while (!this.exited && Date.now() < until) {
401
+ if (this.rootIdentity !== undefined && !this.inspector.isAlive(this.rootIdentity)) return
402
+ await delay(Math.min(25, Math.max(1, until - Date.now())))
403
+ }
404
+ }
405
+
406
+ private async closeOnce(): Promise<void> {
407
+ if (this.managedOwner !== undefined) {
408
+ try {
409
+ await this.closeManagedRange(this.managedOwner)
410
+ this.dataDisposable.dispose()
411
+ this.exitDisposable.dispose()
412
+ } finally {
413
+ void this.done.finally(() => { this.cleanupManagedOwner(this.managedOwner as BoundProcessOwner) }).catch(() => {})
414
+ }
415
+ return
416
+ }
417
+ let survivors = await this.stopDescendants()
418
+ if (survivors.length > 0) {
419
+ throw new Error(`terminal cleanup failed; surviving pids: ${survivors.map(member => member.pid).join(', ')}`)
420
+ }
421
+ await this.stopShell()
422
+ survivors = await this.stopDescendants()
423
+ if (survivors.length > 0) {
424
+ throw new Error(`terminal cleanup failed; surviving pids: ${survivors.map(member => member.pid).join(', ')}`)
425
+ }
426
+ this.settleExitIfGone()
427
+ this.dataDisposable.dispose()
428
+ this.exitDisposable.dispose()
429
+ }
430
+
431
+ private cleanupManagedOwner(owner: BoundProcessOwner): void {
432
+ if (this.managedOwnerCleaned) return
433
+ this.managedOwnerCleaned = true
434
+ owner.cleanup?.()
435
+ }
436
+
437
+ private async closeManagedRange(owner: BoundProcessOwner): Promise<void> {
438
+ owner.signal('SIGTERM')
439
+ const observation = owner.waitForExit()
440
+ const first = await raceWithDelay(observation.then(
441
+ () => ({ kind: 'stopped' as const }),
442
+ (error: unknown) => ({ kind: 'failed' as const, error }),
443
+ ), this.graceMs, { kind: 'timeout' as const })
444
+ if (first.kind !== 'stopped') {
445
+ owner.signal('SIGKILL')
446
+ if (first.kind === 'failed') {
447
+ // The observation failure is still authoritative, but force cleanup
448
+ // and a fresh final observation must be attempted before exposing it.
449
+ try {
450
+ await owner.waitForExit()
451
+ } catch (finalError: unknown) {
452
+ throw new AggregateError([first.error, finalError], 'terminal managed-range cleanup failed')
453
+ }
454
+ throw first.error
455
+ }
456
+ await observation
457
+ }
458
+ if (!this.exited) {
459
+ await raceWithDelay(this.done.then(() => undefined), this.graceMs, undefined)
460
+ }
461
+ if (!this.exited) throw new Error(`terminal cleanup failed; surviving pid: ${this.pid}`)
462
+ }
463
+
464
+ private settleExitIfGone(): void {
465
+ // An externally taskkilled Windows shell may never fire node-pty's exit
466
+ // notification (its console-list agent fails without a parent console),
467
+ // which would leave `done` — and every consumer awaiting it — unsettled
468
+ // forever. Teardown has just verified the shell's absence through the
469
+ // inspector, so a missing exit event is itself the outcome.
470
+ if (this.platform !== 'win32') return
471
+ if (this.exited) return
472
+ /* v8 ignore next -- stopShellWindows() verified the shell is gone or threw;
473
+ the identity re-check is a defensive fence for a future caller. */
474
+ if (this.rootIdentity !== undefined && this.inspector.isAlive(this.rootIdentity)) return
475
+ this.exited = true
476
+ this.output.end()
477
+ this.outcome.resolve({ exitCode: null, signal: null })
478
+ }
479
+ }