UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

178 lines (177 loc) • 6.41 kB
import { readdirSync, readFileSync, readlinkSync } from "node:fs"; import { execFileSync, spawnSync } from "node:child_process"; import { inheritedHostEnv } from "./secret-env.js"; const PROC_TICKS_PER_SECOND = 100; const ETIME_PATTERN = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/; const PS_TIMEOUT_MS = 2_000; function onProcfs() { return process.platform === "linux"; } function procfsIsOurs() { let self; try { self = readlinkSync("/proc/self"); } catch (err) { return { unreadable: `/proc cannot be read (${err.code ?? "unknown"})` }; } return self === String(process.pid) ? true : { unreadable: `/proc is another pid namespace's (/proc/self names ${JSON.stringify(self)}, this process is ${process.pid})` }; } function statFields(line) { const close = line.lastIndexOf(")"); if (close < 0) return undefined; const fields = line.slice(close + 1).trim().split(/\s+/); return fields.length >= 20 ? fields : undefined; } function etimeSeconds(etime) { const m = ETIME_PATTERN.exec(etime.trim()); if (m === null) return undefined; return Number(m[1] ?? "0") * 86_400 + Number(m[2] ?? "0") * 3_600 + Number(m[3]) * 60 + Number(m[4]); } export function processElapsedMs(pid, uptimeNowMs) { if (process.platform === "win32") return { unreadable: "no process table reader on win32" }; if (onProcfs()) { const ours = procfsIsOurs(); if (ours !== true) return ours; let line; try { line = readFileSync(`/proc/${pid}/stat`, "utf8"); } catch (err) { const code = err.code; if (code === "ENOENT" || code === "ESRCH") return null; return { unreadable: `/proc/<pid>/stat cannot be read (${code ?? "unknown"})` }; } const fields = statFields(line); const ticks = fields === undefined ? NaN : Number(fields[19]); if (!Number.isSafeInteger(ticks) || ticks < 0) return { unreadable: "a /proc/<pid>/stat line carries no start time" }; return uptimeNowMs - (ticks * 1000) / PROC_TICKS_PER_SECOND; } let raw; try { raw = execFileSync("ps", ["-p", String(pid), "-o", "etime="], { encoding: "utf8", timeout: PS_TIMEOUT_MS, stdio: ["ignore", "pipe", "ignore"], env: { ...inheritedHostEnv("scrub"), LC_ALL: "C", LANG: "C" }, }); } catch (err) { if (typeof err.status === "number") return null; return { unreadable: `ps failed (${err.code ?? "unknown"})` }; } const trimmed = raw.trim(); if (trimmed === "") return null; const seconds = etimeSeconds(trimmed); return seconds === undefined ? { unreadable: "ps produced no elapsed time" } : seconds * 1000; } export function readProcessTable(psTimeoutMs = PS_TIMEOUT_MS) { if (process.platform === "win32") return { unreadable: "no process table reader on win32" }; const rows = new Map(); if (onProcfs()) { const ours = procfsIsOurs(); if (ours !== true) return ours; let names; try { names = readdirSync("/proc"); } catch (err) { return { unreadable: `/proc cannot be listed (${err.code ?? "unknown"})` }; } let hidden = 0; for (const name of names) { if (!/^[1-9][0-9]*$/.test(name)) continue; let line; try { line = readFileSync(`/proc/${name}/stat`, "utf8"); } catch (err) { const code = err.code; if (code !== "ENOENT" && code !== "ESRCH") hidden++; continue; } const f = statFields(line); if (f === undefined) { hidden++; continue; } const pid = Number(name); const state = f[0]; rows.set(pid, { pid, ppid: Number(f[1]), pgid: Number(f[2]), exited: state === "Z" || state === "X" || state === "x", mark: `t${f[19]}` }); } return hidden > 0 ? Object.assign(rows, { hidden }) : rows; } let out; try { const result = spawnSync("ps", ["-A", "-o", "pid=", "-o", "ppid=", "-o", "pgid=", "-o", "stat=", "-o", "etime="], { env: { ...inheritedHostEnv("scrub"), LC_ALL: "C", LANG: "C" }, timeout: psTimeoutMs, encoding: "utf8", windowsHide: true, }); if (result.error !== undefined || typeof result.stdout !== "string" || result.status !== 0) { return { unreadable: `ps failed (${result.error?.code ?? `exit ${String(result.status)}`})` }; } out = result.stdout; } catch (err) { return { unreadable: `ps failed (${err.code ?? "unknown"})` }; } for (const line of out.split("\n")) { const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+)\s*$/.exec(line); if (m === null) continue; const pid = Number(m[1]); rows.set(pid, { pid, ppid: Number(m[2]), pgid: Number(m[3]), exited: m[4].startsWith("Z"), mark: `e${m[5]}` }); } return rows; } export function sameProcessMark(then, now) { if (then.startsWith("t") && now.startsWith("t")) return then === now && then.length > 1; if (then.startsWith("e") && now.startsWith("e")) { const a = etimeSeconds(then.slice(1)); const b = etimeSeconds(now.slice(1)); return a !== undefined && b !== undefined && b >= a; } return false; } export function processGroupReading(pgid) { return processGroupReadingIn(readProcessTable(), pgid); } export function processGroupReadingIn(table, pgid) { if (!Number.isSafeInteger(pgid) || pgid <= 0) return "empty"; if (!("unreadable" in table)) { let exited = 0; for (const row of table.values()) { if (row.pgid !== pgid) continue; if (!row.exited) return "running_member"; exited++; } if (exited > 0 && (table.hidden ?? 0) === 0) return "exited_only"; } try { process.kill(-pgid, 0); } catch (err) { if (err.code === "ESRCH") return "empty"; } return "unreadable"; }