UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

223 lines (222 loc) • 9.23 kB
import { readlinkSync } from "node:fs"; import { hostname, uptime } from "node:os"; import { hrtime } from "node:process"; import { deliverEngineNotice } from "./engine-notice.js"; import { processElapsedMs } from "./process-table.js"; const UNCHECKABLE_TEXT = Object.freeze({ another_host: "it was written on another host", another_pid_namespace: "it was written in another pid namespace (another container)", pid_namespace_unrecorded: "it names no pid namespace (another container may have written it)", start_time_unknown: "no start time can be compared, so a process now holding that pid may be another one", probe_refused: "the process table refused the question", }); export function uncheckableProcessText(why) { return UNCHECKABLE_TEXT[why]; } const START_TIME_TOLERANCE_MS = 2_000; const START_TIME_PROBE_PRECISION_MS = 250; const PID_NAMESPACE_LINK = "/proc/self/ns/pid"; let cachedHostname; let cachedPidNamespace; let selfFingerprint; let startTimeProbeUnavailable = false; function thisHost() { return (cachedHostname ??= hostname()); } function uptimeMs() { try { return Math.round(uptime() * 1000); } catch { return null; } } function ownPidNamespace() { if (cachedPidNamespace === undefined) { try { const link = readlinkSync(PID_NAMESPACE_LINK); cachedPidNamespace = typeof link === "string" && link !== "" ? link : null; } catch { cachedPidNamespace = null; } } return cachedPidNamespace; } function hasPidNamespaces() { return process.platform === "linux"; } function announceStartTimeDegrade(reason) { if (startTimeProbeUnavailable) return; startTimeProbeUnavailable = true; deliverEngineNotice(undefined, { code: "config.process_start_time_unavailable", message: `[sema] this host cannot report process start times (${reason}), so a record naming a process — a file store's ` + `directory lock, a run claim, a memory writer's session account — is judged by PID ALONE. A record left behind ` + `by a crashed process whose pid the OS has since handed to an unrelated process then reads as a LIVE owner: a ` + `lock or claim stays refused until it is removed by hand, and a writer's account stays open until its session ` + `resumes or the host closes it.`, detail: { reason }, }); } const START_TIME_PROBE_ATTEMPTS = 3; function probeStartTimes(pid) { let last = "imprecise"; for (let attempt = 0; attempt < START_TIME_PROBE_ATTEMPTS; attempt++) { const reading = probeStartTimesOnce(pid); if (reading !== "imprecise" && reading !== "impossible") return reading; last = reading; } if (last === "impossible" && pid === process.pid && process.platform === "linux") announceStartTimeDegrade("this process's own start time reads as no start a process could have had"); return null; } function probeStartTimesOnce(pid) { if (startTimeProbeUnavailable) return null; const knownToExist = pid === process.pid; if (process.platform === "win32") { announceStartTimeDegrade("no ps(1) on win32"); return null; } const monotonicBefore = hrtime.bigint(); const wallBefore = Date.now(); const uptimeBefore = uptimeMs(); if (uptimeBefore === null) { announceStartTimeDegrade("the host refused its uptime"); return null; } const elapsed = processElapsedMs(pid, uptimeBefore); if (elapsed !== null && typeof elapsed === "object") { announceStartTimeDegrade(elapsed.unreadable); return null; } if (elapsed === null) { if (knownToExist) announceStartTimeDegrade("the process table has no row for this very process"); return null; } const latency = Number(hrtime.bigint() - monotonicBefore) / 1e6; const wallDelta = Date.now() - wallBefore; if (latency > START_TIME_PROBE_PRECISION_MS) return "imprecise"; if (Math.abs(wallDelta - latency) > START_TIME_PROBE_PRECISION_MS) return "imprecise"; const elapsedMs = elapsed; const startedAtMs = Math.round((wallBefore - elapsedMs) / 1000) * 1000; const startedSinceBootMs = Math.round((uptimeBefore - elapsedMs) / 1000) * 1000; const starts = startsOf(startedAtMs, startedSinceBootMs, wallBefore, uptimeBefore); if (starts.wall === null || starts.boot === null) return "impossible"; return { startedAtMs: starts.wall, startedSinceBootMs: starts.boot }; } export function processFingerprint(pid) { const host = thisHost(); const pidNs = ownPidNamespace(); const of = (id, probed) => ({ pid: id, startedAtMs: probed?.startedAtMs ?? null, startedSinceBootMs: probed?.startedSinceBootMs ?? null, host, ...(pidNs !== null ? { pidNs } : {}), }); if (pid === undefined || pid === process.pid) { if (selfFingerprint === undefined || selfFingerprint.startedAtMs === null) { const answer = of(process.pid, probeStartTimes(process.pid)); if (answer.startedAtMs === null) return answer; selfFingerprint = answer; } return selfFingerprint; } if (processFingerprint().startedAtMs === null) return of(pid, null); return of(pid, probeStartTimes(pid)); } function signalProbe(pid) { try { process.kill(pid, 0); return "present"; } catch (err) { const code = err.code; if (code === "ESRCH") return "absent"; return code === "EPERM" ? "present" : "refused"; } } function isMeasure(value) { return typeof value === "number" && Number.isFinite(value) && value >= 0; } const NO_STARTS = Object.freeze({ wall: null, boot: null }); function startsOf(startedAtMs, startedSinceBootMs, wallNow, uptimeNow) { const wall = isMeasure(startedAtMs) ? startedAtMs : null; const boot = isMeasure(startedSinceBootMs) ? startedSinceBootMs : null; if (wall === null || boot === null) return { wall, boot }; const bootBeforeEpoch = wall - boot < -START_TIME_TOLERANCE_MS; const startedInTwoBoots = uptimeNow !== null && boot - uptimeNow > START_TIME_TOLERANCE_MS && wall - (wallNow - uptimeNow) > START_TIME_TOLERANCE_MS; return bootBeforeEpoch || startedInTwoBoots ? NO_STARTS : { wall, boot }; } const GONE = Object.freeze({ state: "gone" }); const RUNNING = Object.freeze({ state: "running" }); function uncheckable(why) { return { state: "uncheckable", why }; } export function processCensus(options) { const singleProcessTable = options?.singleProcessTable === true; const signalled = new Map(); const observed = new Map(); const signal = (pid) => { let answer = signalled.get(pid); if (answer === undefined) { answer = signalProbe(pid); signalled.set(pid, answer); } return answer; }; const observe = (pid) => { let fp = observed.get(pid); if (fp === undefined) { fp = processFingerprint(pid); observed.set(pid, fp); } return fp; }; return { verdict(record) { if (typeof record.host === "string" && record.host !== "" && record.host !== thisHost()) return uncheckable("another_host"); const own = ownPidNamespace(); const recorded = typeof record.pidNs === "string" && record.pidNs !== "" ? record.pidNs : null; if (recorded === null && !singleProcessTable && (own !== null || hasPidNamespaces())) return uncheckable("pid_namespace_unrecorded"); if ((recorded ?? own) !== own) return uncheckable("another_pid_namespace"); const answer = signal(record.pid); if (answer === "absent") return GONE; if (answer === "refused") return uncheckable("probe_refused"); const wallNow = Date.now(); const up = uptimeMs(); const starts = startsOf(record.startedAtMs, record.startedSinceBootMs, wallNow, up); if (starts.wall === null && starts.boot === null) return uncheckable("start_time_unknown"); const now = observe(record.pid); const falsified = (was, seen) => was !== null && seen !== null && seen - was > START_TIME_TOLERANCE_MS; const bootIsOver = starts.boot !== null && up !== null && starts.boot - up > START_TIME_TOLERANCE_MS; const wallSaysGone = falsified(starts.wall, now.startedAtMs); const uptimeSaysGone = falsified(starts.boot, now.startedSinceBootMs) || bootIsOver; if (wallSaysGone && uptimeSaysGone) return GONE; const compared = (starts.wall !== null && now.startedAtMs !== null) || (starts.boot !== null && now.startedSinceBootMs !== null); return compared ? RUNNING : uncheckable("start_time_unknown"); }, }; } export function isProcessLive(record) { return processCensus().verdict(record).state !== "gone"; }