process-inspector.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /** Platform process-table inspection used for readiness, signals, and teardown. */
  2. import { closeSync, openSync, readFileSync, readdirSync, readSync } from 'node:fs'
  3. import { execFileSync } from 'node:child_process'
  4. import type { PtySignal } from '@deepseek-ai/dsh-pty'
  5. /** PID plus start identity, preventing teardown escalation after PID reuse. */
  6. export interface ProcessIdentity {
  7. pid: number
  8. started: string
  9. }
  10. /** Injectable OS process operations used by one local PTY session. */
  11. export interface ProcessInspector {
  12. foregroundPgid(shellPid: number): number | undefined
  13. isStdinWaiting(pgid: number): boolean
  14. /** Return the root and its current transitive descendants, children first. */
  15. processTree(rootPid: number): ProcessIdentity[]
  16. /** Return whether the exact identity remains a non-quiescent process. */
  17. isAlive(identity: ProcessIdentity): boolean
  18. signalGroup(pgid: number, signal: PtySignal): void
  19. signalProcess(identity: ProcessIdentity, signal: 'SIGTERM' | 'SIGKILL'): void
  20. }
  21. /** Testable boundary around filesystem, process-table, and signal syscalls. */
  22. export interface ProcessInspectorInternals {
  23. readFile(path: string): string
  24. readDir(path: string): string[]
  25. open(path: string): number
  26. read(fd: number, buffer: Buffer, length: number, position: number): number
  27. close(fd: number): void
  28. exec(file: string, args: string[]): string
  29. kill(pid: number, signal: NodeJS.Signals): void
  30. }
  31. /* v8 ignore start -- thin OS bindings; injected logic is unit-tested and real platform composition exercises them. */
  32. const DEFAULT_INTERNALS: ProcessInspectorInternals = {
  33. readFile: path => readFileSync(path, 'utf8'),
  34. readDir: path => readdirSync(path),
  35. open: path => openSync(path, 'r'),
  36. read: (fd, buffer, length, position) => readSync(fd, buffer, 0, length, position),
  37. close: closeSync,
  38. exec: (file, args) => execFileSync(file, args, { encoding: 'utf8' }),
  39. kill: (pid, signal) => process.kill(pid, signal),
  40. }
  41. /* v8 ignore stop */
  42. interface ProcStat {
  43. pid: number
  44. parentPid: number
  45. pgrp: number
  46. session: number
  47. state: string
  48. tpgid: number
  49. started: string
  50. }
  51. /**
  52. * Parse fields used from Linux `/proc/<pid>/stat`, including parenthesized comm text.
  53. * @param text - complete stat line.
  54. * @returns Parsed identity/group fields, or undefined for malformed input.
  55. */
  56. export function parseProcStat(text: string): ProcStat | undefined {
  57. const open = text.indexOf('(')
  58. const close = text.lastIndexOf(')')
  59. if (open <= 0 || close <= open) return undefined
  60. const pid = Number(text.slice(0, open).trim())
  61. const rest = text.slice(close + 2).trim().split(/\s+/)
  62. const state = rest[0] || ''
  63. const parentPid = Number(rest[1])
  64. const pgrp = Number(rest[2])
  65. const session = Number(rest[3])
  66. const tpgid = Number(rest[5])
  67. const started = rest[19]
  68. if (![pid, parentPid, pgrp, session, tpgid].every(Number.isSafeInteger)
  69. || state.length !== 1 || started === undefined) return undefined
  70. return { pid, parentPid, pgrp, session, state, tpgid, started }
  71. }
  72. function readLinuxStat(internals: ProcessInspectorInternals, pid: number): ProcStat | undefined {
  73. try {
  74. return parseProcStat(internals.readFile(`/proc/${pid}/stat`))
  75. } catch (_unreadableProcEntry) {
  76. return undefined
  77. }
  78. }
  79. function numericEntries(internals: ProcessInspectorInternals, path: string): number[] {
  80. try {
  81. return internals.readDir(path).filter(entry => /^\d+$/.test(entry)).map(Number)
  82. } catch (_unreadableProcDirectory) {
  83. return []
  84. }
  85. }
  86. interface SyscallInfo {
  87. number: number
  88. args: number[]
  89. }
  90. function readSyscall(internals: ProcessInspectorInternals, pid: number, tid: number): SyscallInfo | undefined {
  91. try {
  92. const text = internals.readFile(`/proc/${pid}/task/${tid}/syscall`).trim()
  93. if (text === 'running' || text.startsWith('-1 ')) return undefined
  94. const fields = text.split(/\s+/)
  95. const number = Number(fields[0])
  96. const args = fields.slice(1, 7).map(field => Number.parseInt(field, 16))
  97. if (!Number.isSafeInteger(number) || args.some(value => !Number.isSafeInteger(value))) return undefined
  98. return { number, args }
  99. } catch (_unreadableSyscall) {
  100. return undefined
  101. }
  102. }
  103. function readMemory(
  104. internals: ProcessInspectorInternals,
  105. pid: number,
  106. address: number,
  107. length: number,
  108. ): Buffer | undefined {
  109. let fd: number | undefined
  110. try {
  111. fd = internals.open(`/proc/${pid}/mem`)
  112. const buffer = Buffer.alloc(length)
  113. const count = internals.read(fd, buffer, length, address)
  114. return buffer.subarray(0, count)
  115. } catch (_unreadableProcessMemory) {
  116. return undefined
  117. } finally {
  118. if (fd !== undefined) internals.close(fd)
  119. }
  120. }
  121. function fdSetHasStdin(internals: ProcessInspectorInternals, pid: number, address: number): boolean {
  122. return address !== 0 && (readMemory(internals, pid, address, 8)?.[0] ?? 0) % 2 === 1
  123. }
  124. function pollHasStdin(
  125. internals: ProcessInspectorInternals,
  126. pid: number,
  127. address: number,
  128. count: number,
  129. ): boolean {
  130. if (address === 0 || count <= 0) return false
  131. const memory = readMemory(internals, pid, address, Math.min(count, 1024) * 8)
  132. if (memory === undefined) return false
  133. for (let offset = 0; offset + 8 <= memory.length; offset += 8) {
  134. if (memory.readInt32LE(offset) === 0 && (memory.readInt16LE(offset + 4) & 0x001) !== 0) return true
  135. }
  136. return false
  137. }
  138. function epollHasStdin(internals: ProcessInspectorInternals, pid: number, epfd: number): boolean {
  139. try {
  140. return internals.readFile(`/proc/${pid}/fdinfo/${epfd}`)
  141. .split('\n')
  142. .some(line => /^tfd:\s+0\b/.test(line.trim()))
  143. } catch (_unreadableFdInfo) {
  144. return false
  145. }
  146. }
  147. interface SyscallTable {
  148. read: number
  149. select?: number
  150. pselect: number
  151. poll?: number
  152. ppoll: number
  153. epollWait?: number
  154. epollPwait: number
  155. }
  156. const SYSCALLS: Partial<Record<NodeJS.Architecture, SyscallTable>> = {
  157. x64: { read: 0, select: 23, pselect: 270, poll: 7, ppoll: 271, epollWait: 232, epollPwait: 281 },
  158. arm64: { read: 63, pselect: 72, ppoll: 73, epollPwait: 22 },
  159. }
  160. function syscallWaitsOnStdin(
  161. internals: ProcessInspectorInternals,
  162. pid: number,
  163. syscall: SyscallInfo,
  164. table: SyscallTable,
  165. ): boolean {
  166. const [a0 = 0, a1 = 0, a2 = 0] = syscall.args
  167. if (syscall.number === table.read) return a0 === 0
  168. if (syscall.number === table.select || syscall.number === table.pselect) {
  169. return a0 >= 1 && fdSetHasStdin(internals, pid, a1)
  170. }
  171. if (syscall.number === table.poll || syscall.number === table.ppoll) {
  172. return a1 >= 1 && pollHasStdin(internals, pid, a0, a1)
  173. }
  174. if (syscall.number === table.epollWait || syscall.number === table.epollPwait) {
  175. return a2 >= 1 && epollHasStdin(internals, pid, a0)
  176. }
  177. return false
  178. }
  179. abstract class PosixProcessInspector implements ProcessInspector {
  180. constructor(protected readonly internals: ProcessInspectorInternals) {}
  181. abstract foregroundPgid(shellPid: number): number | undefined
  182. abstract isStdinWaiting(pgid: number): boolean
  183. abstract processTree(rootPid: number): ProcessIdentity[]
  184. abstract isAlive(identity: ProcessIdentity): boolean
  185. signalGroup(pgid: number, signal: PtySignal): void {
  186. this.internals.kill(-pgid, signal)
  187. }
  188. signalProcess(identity: ProcessIdentity, signal: 'SIGTERM' | 'SIGKILL'): void {
  189. if (this.isAlive(identity)) this.internals.kill(identity.pid, signal)
  190. }
  191. }
  192. interface ProcessTreeEntry extends ProcessIdentity {
  193. parentPid: number
  194. }
  195. function processTree(entries: ProcessTreeEntry[], rootPid: number): ProcessIdentity[] {
  196. const byPid = new Map(entries.map(entry => [entry.pid, entry]))
  197. const root = byPid.get(rootPid)
  198. if (root === undefined) return []
  199. const byParent = new Map<number, ProcessTreeEntry[]>()
  200. for (const entry of entries) {
  201. const children = byParent.get(entry.parentPid) ?? []
  202. children.push(entry)
  203. byParent.set(entry.parentPid, children)
  204. }
  205. const visited = new Set<number>()
  206. const result: ProcessIdentity[] = []
  207. const visit = (entry: ProcessTreeEntry): void => {
  208. if (visited.has(entry.pid)) return
  209. visited.add(entry.pid)
  210. for (const child of byParent.get(entry.pid) ?? []) visit(child)
  211. result.push({ pid: entry.pid, started: entry.started })
  212. }
  213. visit(root)
  214. return result
  215. }
  216. class LinuxProcessInspector extends PosixProcessInspector {
  217. constructor(
  218. private readonly arch: NodeJS.Architecture,
  219. internals: ProcessInspectorInternals,
  220. ) {
  221. super(internals)
  222. }
  223. foregroundPgid(shellPid: number): number | undefined {
  224. const tpgid = readLinuxStat(this.internals, shellPid)?.tpgid
  225. return tpgid !== undefined && tpgid > 0 ? tpgid : undefined
  226. }
  227. isStdinWaiting(pgid: number): boolean {
  228. const table = SYSCALLS[this.arch]
  229. if (table === undefined) return false
  230. for (const pid of numericEntries(this.internals, '/proc')) {
  231. if (readLinuxStat(this.internals, pid)?.pgrp !== pgid) continue
  232. for (const tid of numericEntries(this.internals, `/proc/${pid}/task`)) {
  233. const syscall = readSyscall(this.internals, pid, tid)
  234. if (syscall !== undefined && syscallWaitsOnStdin(this.internals, pid, syscall, table)) return true
  235. }
  236. }
  237. return false
  238. }
  239. processTree(rootPid: number): ProcessIdentity[] {
  240. const entries = numericEntries(this.internals, '/proc').flatMap((pid) => {
  241. const stat = readLinuxStat(this.internals, pid)
  242. return stat === undefined ? [] : [{ pid, parentPid: stat.parentPid, started: stat.started }]
  243. })
  244. return processTree(entries, rootPid)
  245. }
  246. isAlive(identity: ProcessIdentity): boolean {
  247. const stat = readLinuxStat(this.internals, identity.pid)
  248. return stat?.started === identity.started && !/^[ZXx]$/.test(stat.state)
  249. }
  250. }
  251. interface PsEntry extends ProcessTreeEntry {}
  252. function macProcessTable(internals: ProcessInspectorInternals): PsEntry[] {
  253. return internals.exec('/bin/ps', ['-axo', 'pid=,ppid=,lstart=']).split('\n').flatMap((line) => {
  254. const match = /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(line)
  255. if (match?.[1] === undefined || match[2] === undefined || match[3] === undefined) return []
  256. return [{ pid: Number(match[1]), parentPid: Number(match[2]), started: match[3] }]
  257. })
  258. }
  259. class MacProcessInspector extends PosixProcessInspector {
  260. foregroundPgid(shellPid: number): number | undefined {
  261. try {
  262. const value = Number(this.internals.exec('/bin/ps', ['-o', 'tpgid=', '-p', String(shellPid)]).trim())
  263. return Number.isSafeInteger(value) && value > 0 ? value : undefined
  264. } catch (_missingProcess) {
  265. return undefined
  266. }
  267. }
  268. isStdinWaiting(_pgid: number): boolean {
  269. return false
  270. }
  271. processTree(rootPid: number): ProcessIdentity[] {
  272. return processTree(macProcessTable(this.internals), rootPid)
  273. }
  274. isAlive(identity: ProcessIdentity): boolean {
  275. return macProcessTable(this.internals).some(entry => entry.pid === identity.pid && entry.started === identity.started)
  276. }
  277. }
  278. /**
  279. * Create the supported platform inspector or fail at plugin load.
  280. * @param platform - target Node platform.
  281. * @param arch - target CPU architecture for Linux syscall numbers.
  282. * @param internals - filesystem/process boundary, injectable for deterministic tests.
  283. * @returns Platform process inspector.
  284. */
  285. export function createProcessInspector(
  286. platform: NodeJS.Platform = process.platform,
  287. arch: NodeJS.Architecture = process.arch,
  288. internals: ProcessInspectorInternals = DEFAULT_INTERNALS,
  289. ): ProcessInspector {
  290. if (platform === 'linux') return new LinuxProcessInspector(arch, internals)
  291. if (platform === 'darwin') return new MacProcessInspector(internals)
  292. throw new Error(`pty-local: unsupported platform ${platform}`)
  293. }