@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
@@ -0,0 +1,560 @@
1
+ /** Platform process-table inspection for terminal readiness, signals, and teardown. */
2
+
3
+ import { closeSync, openSync, readFileSync, readdirSync, readlinkSync, readSync, statSync } from 'node:fs'
4
+ import { execFileSync } from 'node:child_process'
5
+ import type { SubprocessTerminalSignal } from '@deepseek-ai/dsh-subprocess'
6
+ import { createWindowsProcessInspector } from './windows-inspector.ts'
7
+
8
+ /** PID plus start identity, preventing teardown escalation after PID reuse. */
9
+ export interface ProcessIdentity {
10
+ pid: number
11
+ started: string
12
+ }
13
+
14
+ interface FileStatus {
15
+ readonly rdev: number
16
+ isCharacterDevice(): boolean
17
+ }
18
+
19
+ /**
20
+ * One observation of the platform process table, shared by every question a
21
+ * single readiness poll or teardown pass asks.
22
+ *
23
+ * The table is read at most once, on the first question that needs it — a
24
+ * `/bin/ps` fork on macOS, a `/proc` walk on Linux, a Toolhelp32 enumeration on
25
+ * Windows. Later questions never re-read it, which is what keeps a poll's cost
26
+ * independent of how many descendants the running command spawned. Windows
27
+ * liveness needs no table at all: wait state is a per-handle question there, so
28
+ * a snapshot asked only for liveness never enumerates.
29
+ *
30
+ * A snapshot answers what the process table showed, which is what batch
31
+ * filtering wants and what signalling must not use: {@link ProcessInspector.isAlive}
32
+ * is the fence a signal takes, because it reads current state instead.
33
+ */
34
+ export interface ProcessSnapshot {
35
+ /** Whether the process-table scan omitted no unreadable rows; absent means unverified. */
36
+ readonly complete?: boolean
37
+ /**
38
+ * Return the root and its transitive descendants as observed, children first.
39
+ * @param rootPid - tree root to descend from.
40
+ * @returns Observed root and descendants, children before parents.
41
+ */
42
+ tree(rootPid: number): ProcessIdentity[]
43
+ /**
44
+ * Return observed members of one POSIX process session.
45
+ * @param sessionId - POSIX session identifier.
46
+ * @returns Observed session members, empty where the platform's table omits session ids.
47
+ */
48
+ session(sessionId: number): ProcessIdentity[]
49
+ /**
50
+ * Return whether the exact identity was a non-quiescent process.
51
+ * @param identity - PID plus start identity to match.
52
+ * @returns Whether that exact identity — not merely that PID — was running.
53
+ */
54
+ alive(identity: ProcessIdentity): boolean
55
+ }
56
+
57
+ /** Injectable OS process operations used by one local PTY session. */
58
+ export interface ProcessInspector {
59
+ foregroundPgid(shellPid: number): number | undefined
60
+ /**
61
+ * Report whether the foreground group waits on the terminal shell's stdin.
62
+ *
63
+ * @param pgid Foreground process-group identifier.
64
+ * @param shellPid Persistent terminal shell process identifier.
65
+ * @returns Whether a group member is blocked reading the shell's terminal input.
66
+ */
67
+ isStdinWaiting(pgid: number, shellPid: number): boolean
68
+ /**
69
+ * Read the process table once and answer tree, session, and liveness from it.
70
+ * @returns A process-table observation whose reads are shared.
71
+ * @throws when the platform process table cannot be enumerated.
72
+ */
73
+ snapshot(): ProcessSnapshot
74
+ /**
75
+ * Return whether the exact identity is a non-quiescent process right now.
76
+ *
77
+ * Reads the narrowest per-identity source the platform offers rather than a
78
+ * whole table, so a signalling round can re-check every target without
79
+ * paying for a scan. Callers filtering many members at once want
80
+ * {@link ProcessSnapshot.alive} instead.
81
+ *
82
+ * @param identity - PID plus start identity to match.
83
+ * @returns Whether that exact identity — not merely that PID — is running.
84
+ */
85
+ isAlive(identity: ProcessIdentity): boolean
86
+ signalGroup(pgid: number, signal: SubprocessTerminalSignal): void
87
+ /**
88
+ * Signal one exact process identity, fenced against PID reuse.
89
+ *
90
+ * The fence reads current state immediately before the signal. An observation
91
+ * taken earlier in the same round cannot stand in for it: the observation
92
+ * preserves the original PID-to-start-time pairing, so a recycled PID would
93
+ * still match and take a signal meant for the process that exited.
94
+ *
95
+ * @param identity - PID plus start identity to signal.
96
+ * @param signal - termination signal to deliver.
97
+ */
98
+ signalProcess(identity: ProcessIdentity, signal: 'SIGTERM' | 'SIGKILL'): void
99
+ }
100
+
101
+ /** Testable boundary around filesystem, process-table, and signal syscalls. */
102
+ export interface ProcessInspectorInternals {
103
+ readFile(path: string): string
104
+ readDir(path: string): string[]
105
+ readLink(path: string): string
106
+ stat(path: string): FileStatus
107
+ open(path: string): number
108
+ read(fd: number, buffer: Buffer, length: number, position: number): number
109
+ close(fd: number): void
110
+ exec(file: string, args: string[]): string
111
+ kill(pid: number, signal: NodeJS.Signals): void
112
+ }
113
+
114
+ /* v8 ignore start -- thin OS bindings; injected logic is unit-tested and real platform composition exercises them. */
115
+ const DEFAULT_INTERNALS: ProcessInspectorInternals = {
116
+ readFile: path => readFileSync(path, 'utf8'),
117
+ readDir: path => readdirSync(path),
118
+ readLink: path => readlinkSync(path, 'utf8'),
119
+ stat: path => statSync(path),
120
+ open: path => openSync(path, 'r'),
121
+ read: (fd, buffer, length, position) => readSync(fd, buffer, 0, length, position),
122
+ close: closeSync,
123
+ exec: (file, args) => execFileSync(file, args, { encoding: 'utf8' }),
124
+ kill: (pid, signal) => process.kill(pid, signal),
125
+ }
126
+ /* v8 ignore stop */
127
+
128
+ interface ProcStat {
129
+ pid: number
130
+ parentPid: number
131
+ pgrp: number
132
+ session: number
133
+ state: string
134
+ ttyDevice: number
135
+ tpgid: number
136
+ started: string
137
+ }
138
+
139
+ /**
140
+ * Parse fields used from Linux `/proc/<pid>/stat`, including parenthesized comm text.
141
+ * @param text - complete stat line.
142
+ * @returns Parsed identity/group fields, or undefined for malformed input.
143
+ */
144
+ export function parseProcStat(text: string): ProcStat | undefined {
145
+ const open = text.indexOf('(')
146
+ const close = text.lastIndexOf(')')
147
+ if (open <= 0 || close <= open) return undefined
148
+ const pid = Number(text.slice(0, open).trim())
149
+ const rest = text.slice(close + 2).trim().split(/\s+/)
150
+ const state = rest[0] || ''
151
+ const parentPid = Number(rest[1])
152
+ const pgrp = Number(rest[2])
153
+ const session = Number(rest[3])
154
+ const ttyDevice = Number(rest[4])
155
+ const tpgid = Number(rest[5])
156
+ const started = rest[19]
157
+ if (![pid, parentPid, pgrp, session, ttyDevice, tpgid].every(Number.isSafeInteger)
158
+ || state.length !== 1 || started === undefined) return undefined
159
+ return { pid, parentPid, pgrp, session, state, ttyDevice, tpgid, started }
160
+ }
161
+
162
+ function readLinuxStat(internals: ProcessInspectorInternals, pid: number): ProcStat | undefined {
163
+ try {
164
+ return parseProcStat(internals.readFile(`/proc/${pid}/stat`))
165
+ } catch (_unreadableProcEntry) {
166
+ return undefined
167
+ }
168
+ }
169
+
170
+ // `/proc/<pid>/stat` renders tty_nr as a signed 32-bit device number, while
171
+ // Node exposes the same st_rdev bits as a nonnegative number.
172
+ function linuxDeviceNumber(value: number): number {
173
+ return value >>> 0
174
+ }
175
+
176
+ // `/dev/tty` reports the alias device instead of the selected PTY through stat,
177
+ // so its owning process's tty_nr is the only comparable terminal identity.
178
+ function readLinuxTerminalDevice(
179
+ internals: ProcessInspectorInternals,
180
+ pid: number,
181
+ ttyDevice: number,
182
+ tid?: number,
183
+ ): number | undefined {
184
+ const terminalDevice = linuxDeviceNumber(ttyDevice)
185
+ if (terminalDevice === 0) return undefined
186
+ const path = tid === undefined ? `/proc/${pid}/fd/0` : `/proc/${pid}/task/${tid}/fd/0`
187
+ try {
188
+ const target = internals.readLink(path)
189
+ if (target === '/dev/tty') return terminalDevice
190
+ const status = internals.stat(path)
191
+ return status.isCharacterDevice() && linuxDeviceNumber(status.rdev) === terminalDevice
192
+ ? terminalDevice
193
+ : undefined
194
+ } catch (_unreadableStdinDevice) {
195
+ return undefined
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Find an executing member of a Linux process group. `false` means the group
201
+ * contains only zombie/dead entries; `undefined` means the process table could
202
+ * not prove either outcome. A still-executing `knownMember` is returned from
203
+ * its own stat entry without enumerating `/proc`, so repeated polls of a
204
+ * long-lived group cost one file read instead of one per host process.
205
+ * @param processGroupId - POSIX process-group id to inspect.
206
+ * @param knownMember - member PID returned by an earlier call, if any.
207
+ * @param internals - injectable process-table operations.
208
+ * @returns An executing member's PID; `false` when every group entry is
209
+ * zombie/dead; `undefined` when `/proc` is unreadable or lists no group entry.
210
+ */
211
+ export function linuxProcessGroupLiveMember(
212
+ processGroupId: number,
213
+ knownMember?: number,
214
+ internals: ProcessInspectorInternals = DEFAULT_INTERNALS,
215
+ ): number | false | undefined {
216
+ if (knownMember !== undefined) {
217
+ const known = readLinuxStat(internals, knownMember)
218
+ if (known?.pgrp === processGroupId && !quiescent(known.state)) return knownMember
219
+ }
220
+ let entries: string[]
221
+ try {
222
+ entries = internals.readDir('/proc')
223
+ } catch (_unreadableProcDirectory) {
224
+ return undefined
225
+ }
226
+ let matched = false
227
+ for (const entry of entries) {
228
+ if (!/^\d+$/.test(entry)) continue
229
+ const stat = readLinuxStat(internals, Number(entry))
230
+ if (stat?.pgrp !== processGroupId) continue
231
+ matched = true
232
+ if (!quiescent(stat.state)) return stat.pid
233
+ }
234
+ return matched ? false : undefined
235
+ }
236
+
237
+ function numericEntries(internals: ProcessInspectorInternals, path: string): number[] | undefined {
238
+ try {
239
+ return internals.readDir(path).filter(entry => /^\d+$/.test(entry)).map(Number)
240
+ } catch (_unreadableProcDirectory) {
241
+ return undefined
242
+ }
243
+ }
244
+
245
+ interface SyscallInfo {
246
+ number: number
247
+ args: number[]
248
+ }
249
+
250
+ function readSyscall(internals: ProcessInspectorInternals, pid: number, tid: number): SyscallInfo | undefined {
251
+ try {
252
+ const text = internals.readFile(`/proc/${pid}/task/${tid}/syscall`).trim()
253
+ if (text === 'running' || text.startsWith('-1 ')) return undefined
254
+ const fields = text.split(/\s+/)
255
+ const number = Number(fields[0])
256
+ const args = fields.slice(1, 7).map(field => Number.parseInt(field, 16))
257
+ if (!Number.isSafeInteger(number) || args.some(value => !Number.isSafeInteger(value))) return undefined
258
+ return { number, args }
259
+ } catch (_unreadableSyscall) {
260
+ return undefined
261
+ }
262
+ }
263
+
264
+ function readMemory(
265
+ internals: ProcessInspectorInternals,
266
+ pid: number,
267
+ address: number,
268
+ length: number,
269
+ ): Buffer | undefined {
270
+ let fd: number | undefined
271
+ try {
272
+ fd = internals.open(`/proc/${pid}/mem`)
273
+ const buffer = Buffer.alloc(length)
274
+ const count = internals.read(fd, buffer, length, address)
275
+ return buffer.subarray(0, count)
276
+ } catch (_unreadableProcessMemory) {
277
+ return undefined
278
+ } finally {
279
+ if (fd !== undefined) internals.close(fd)
280
+ }
281
+ }
282
+
283
+ function fdSetHasStdin(internals: ProcessInspectorInternals, pid: number, address: number): boolean {
284
+ return address !== 0 && (readMemory(internals, pid, address, 8)?.[0] ?? 0) % 2 === 1
285
+ }
286
+
287
+ function pollHasStdin(
288
+ internals: ProcessInspectorInternals,
289
+ pid: number,
290
+ address: number,
291
+ count: number,
292
+ ): boolean {
293
+ if (address === 0 || count <= 0) return false
294
+ const memory = readMemory(internals, pid, address, Math.min(count, 1024) * 8)
295
+ if (memory === undefined) return false
296
+ for (let offset = 0; offset + 8 <= memory.length; offset += 8) {
297
+ if (memory.readInt32LE(offset) === 0 && (memory.readInt16LE(offset + 4) & 0x001) !== 0) return true
298
+ }
299
+ return false
300
+ }
301
+
302
+ function epollHasStdin(internals: ProcessInspectorInternals, pid: number, tid: number, epfd: number): boolean {
303
+ try {
304
+ return internals.readFile(`/proc/${pid}/task/${tid}/fdinfo/${epfd}`)
305
+ .split('\n')
306
+ .some(line => /^tfd:\s+0\b/.test(line.trim()))
307
+ } catch (_unreadableFdInfo) {
308
+ return false
309
+ }
310
+ }
311
+
312
+ interface SyscallTable {
313
+ read: number
314
+ select?: number
315
+ pselect: number
316
+ poll?: number
317
+ ppoll: number
318
+ epollWait?: number
319
+ epollPwait: number
320
+ }
321
+
322
+ const SYSCALLS: Partial<Record<NodeJS.Architecture, SyscallTable>> = {
323
+ x64: { read: 0, select: 23, pselect: 270, poll: 7, ppoll: 271, epollWait: 232, epollPwait: 281 },
324
+ arm64: { read: 63, pselect: 72, ppoll: 73, epollPwait: 22 },
325
+ }
326
+
327
+ const SUPPORTED_SYSCALL_TABLES = Object.values(SYSCALLS)
328
+
329
+ // `/proc/<pid>/task/<tid>/syscall` uses the kernel ABI's numbers. User-mode
330
+ // emulation can therefore expose a supported table different from process.arch.
331
+ function linuxSyscallTables(arch: NodeJS.Architecture): readonly SyscallTable[] | undefined {
332
+ const primary = SYSCALLS[arch]
333
+ if (primary === undefined) return undefined
334
+ return [primary, ...SUPPORTED_SYSCALL_TABLES.filter(table => table !== primary)]
335
+ }
336
+
337
+ function syscallWaitsOnStdin(
338
+ internals: ProcessInspectorInternals,
339
+ pid: number,
340
+ tid: number,
341
+ syscall: SyscallInfo,
342
+ tables: readonly SyscallTable[],
343
+ ): boolean {
344
+ const [a0 = 0, a1 = 0, a2 = 0] = syscall.args
345
+ for (const table of tables) {
346
+ if (syscall.number === table.read) return a0 === 0
347
+ if (syscall.number === table.select || syscall.number === table.pselect) {
348
+ return a0 >= 1 && fdSetHasStdin(internals, pid, a1)
349
+ }
350
+ if (syscall.number === table.poll || syscall.number === table.ppoll) {
351
+ return a1 >= 1 && pollHasStdin(internals, pid, a0, a1)
352
+ }
353
+ if (syscall.number === table.epollWait || syscall.number === table.epollPwait) {
354
+ return a2 >= 1 && epollHasStdin(internals, pid, tid, a0)
355
+ }
356
+ }
357
+ return false
358
+ }
359
+
360
+ abstract class PosixProcessInspector implements ProcessInspector {
361
+ constructor(protected readonly internals: ProcessInspectorInternals) {}
362
+
363
+ abstract foregroundPgid(shellPid: number): number | undefined
364
+ abstract isStdinWaiting(pgid: number, shellPid: number): boolean
365
+ abstract snapshot(): ProcessSnapshot
366
+ abstract isAlive(identity: ProcessIdentity): boolean
367
+
368
+ signalGroup(pgid: number, signal: SubprocessTerminalSignal): void {
369
+ this.internals.kill(-pgid, signal)
370
+ }
371
+
372
+ signalProcess(identity: ProcessIdentity, signal: 'SIGTERM' | 'SIGKILL'): void {
373
+ if (this.isAlive(identity)) this.internals.kill(identity.pid, signal)
374
+ }
375
+ }
376
+
377
+ interface ProcessTreeEntry extends ProcessIdentity {
378
+ parentPid: number
379
+ }
380
+
381
+ /** One process-table row, carrying the fields a platform's table exposes. */
382
+ interface ProcessRow extends ProcessTreeEntry {
383
+ /** POSIX session identifier, or undefined where the table omits it. */
384
+ session: number | undefined
385
+ /** Single-letter process state, or undefined where the table omits it. */
386
+ state: string | undefined
387
+ }
388
+
389
+ // Zombie and dead states answer "present in the table" but never "still
390
+ // running"; a table without a state column can only report presence.
391
+ function quiescent(state: string | undefined): boolean {
392
+ return state !== undefined && /^[ZXx]$/.test(state)
393
+ }
394
+
395
+ class PosixProcessSnapshot implements ProcessSnapshot {
396
+ private readonly byPid: Map<number, ProcessRow>
397
+
398
+ constructor(private readonly rows: ProcessRow[], readonly complete: boolean) {
399
+ this.byPid = new Map(rows.map(row => [row.pid, row]))
400
+ }
401
+
402
+ tree(rootPid: number): ProcessIdentity[] {
403
+ return processTree(this.rows, rootPid)
404
+ }
405
+
406
+ session(sessionId: number): ProcessIdentity[] {
407
+ return this.rows.flatMap(row =>
408
+ row.session === sessionId ? [{ pid: row.pid, started: row.started }] : [])
409
+ }
410
+
411
+ alive(identity: ProcessIdentity): boolean {
412
+ const row = this.byPid.get(identity.pid)
413
+ return row?.started === identity.started && !quiescent(row.state)
414
+ }
415
+ }
416
+
417
+ function processTree(entries: ProcessTreeEntry[], rootPid: number): ProcessIdentity[] {
418
+ const byPid = new Map(entries.map(entry => [entry.pid, entry]))
419
+ const root = byPid.get(rootPid)
420
+ if (root === undefined) return []
421
+ const byParent = new Map<number, ProcessTreeEntry[]>()
422
+ for (const entry of entries) {
423
+ const children = byParent.get(entry.parentPid) ?? []
424
+ children.push(entry)
425
+ byParent.set(entry.parentPid, children)
426
+ }
427
+ const visited = new Set<number>()
428
+ const result: ProcessIdentity[] = []
429
+ const visit = (entry: ProcessTreeEntry): void => {
430
+ if (visited.has(entry.pid)) return
431
+ visited.add(entry.pid)
432
+ for (const child of byParent.get(entry.pid) ?? []) visit(child)
433
+ result.push({ pid: entry.pid, started: entry.started })
434
+ }
435
+ visit(root)
436
+ return result
437
+ }
438
+
439
+ class LinuxProcessInspector extends PosixProcessInspector {
440
+ constructor(
441
+ private readonly arch: NodeJS.Architecture,
442
+ internals: ProcessInspectorInternals,
443
+ ) {
444
+ super(internals)
445
+ }
446
+
447
+ foregroundPgid(shellPid: number): number | undefined {
448
+ const tpgid = readLinuxStat(this.internals, shellPid)?.tpgid
449
+ return tpgid !== undefined && tpgid > 0 ? tpgid : undefined
450
+ }
451
+
452
+ isStdinWaiting(pgid: number, shellPid: number): boolean {
453
+ const tables = linuxSyscallTables(this.arch)
454
+ if (tables === undefined) return false
455
+ const shell = readLinuxStat(this.internals, shellPid)
456
+ if (shell === undefined) return false
457
+ const terminalDevice = readLinuxTerminalDevice(this.internals, shellPid, shell.ttyDevice)
458
+ if (terminalDevice === undefined) return false
459
+ for (const pid of numericEntries(this.internals, '/proc') ?? []) {
460
+ const process = readLinuxStat(this.internals, pid)
461
+ if (process?.pgrp !== pgid) continue
462
+ for (const tid of numericEntries(this.internals, `/proc/${pid}/task`) ?? []) {
463
+ const syscall = readSyscall(this.internals, pid, tid)
464
+ if (syscall !== undefined
465
+ && syscallWaitsOnStdin(this.internals, pid, tid, syscall, tables)
466
+ && readLinuxTerminalDevice(this.internals, pid, process.ttyDevice, tid) === terminalDevice) return true
467
+ }
468
+ }
469
+ return false
470
+ }
471
+
472
+ isAlive(identity: ProcessIdentity): boolean {
473
+ const stat = readLinuxStat(this.internals, identity.pid)
474
+ return stat?.started === identity.started && !quiescent(stat.state)
475
+ }
476
+
477
+ snapshot(): ProcessSnapshot {
478
+ const pids = numericEntries(this.internals, '/proc')
479
+ if (pids === undefined) throw new Error('Cannot inspect processes: /proc directory is unreadable')
480
+ let complete = true
481
+ const rows = pids.flatMap((pid) => {
482
+ const stat = readLinuxStat(this.internals, pid)
483
+ if (stat === undefined) complete = false
484
+ return stat === undefined ? [] : [{
485
+ pid,
486
+ parentPid: stat.parentPid,
487
+ started: stat.started,
488
+ session: stat.session,
489
+ state: stat.state,
490
+ }]
491
+ })
492
+ return new PosixProcessSnapshot(rows, complete)
493
+ }
494
+
495
+ }
496
+
497
+ // `ps` exposes neither the session id nor a state column in this format, so a
498
+ // macOS row can answer presence and parentage but never session membership.
499
+ function macProcessTable(internals: ProcessInspectorInternals): { rows: ProcessRow[]; complete: boolean } {
500
+ let complete = true
501
+ const rows = internals.exec('/bin/ps', ['-axo', 'pid=,ppid=,lstart=']).split('\n').flatMap((line) => {
502
+ const match = /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(line)
503
+ if (match?.[1] === undefined || match[2] === undefined || match[3] === undefined) {
504
+ if (line.trim().length > 0) complete = false
505
+ return []
506
+ }
507
+ return [{
508
+ pid: Number(match[1]),
509
+ parentPid: Number(match[2]),
510
+ started: match[3],
511
+ session: undefined,
512
+ state: undefined,
513
+ }]
514
+ })
515
+ return { rows, complete }
516
+ }
517
+
518
+ class MacProcessInspector extends PosixProcessInspector {
519
+ foregroundPgid(shellPid: number): number | undefined {
520
+ try {
521
+ const value = Number(this.internals.exec('/bin/ps', ['-o', 'tpgid=', '-p', String(shellPid)]).trim())
522
+ return Number.isSafeInteger(value) && value > 0 ? value : undefined
523
+ } catch (_missingProcess) {
524
+ return undefined
525
+ }
526
+ }
527
+
528
+ isStdinWaiting(_pgid: number, _shellPid: number): boolean {
529
+ return false
530
+ }
531
+
532
+ isAlive(identity: ProcessIdentity): boolean {
533
+ return macProcessTable(this.internals).rows
534
+ .some(entry => entry.pid === identity.pid && entry.started === identity.started)
535
+ }
536
+
537
+ snapshot(): ProcessSnapshot {
538
+ const table = macProcessTable(this.internals)
539
+ return new PosixProcessSnapshot(table.rows, table.complete)
540
+ }
541
+
542
+ }
543
+
544
+ /**
545
+ * Create the supported platform inspector or fail at plugin load.
546
+ * @param platform - target Node platform.
547
+ * @param arch - target CPU architecture for Linux syscall numbers.
548
+ * @param internals - filesystem/process boundary, injectable for deterministic tests.
549
+ * @returns Platform process inspector.
550
+ */
551
+ export function createProcessInspector(
552
+ platform: NodeJS.Platform = process.platform,
553
+ arch: NodeJS.Architecture = process.arch,
554
+ internals: ProcessInspectorInternals = DEFAULT_INTERNALS,
555
+ ): ProcessInspector {
556
+ if (platform === 'linux') return new LinuxProcessInspector(arch, internals)
557
+ if (platform === 'darwin') return new MacProcessInspector(internals)
558
+ if (platform === 'win32') return createWindowsProcessInspector()
559
+ throw new Error(`subprocess-local: terminal inspection is unsupported on platform ${platform}`)
560
+ }