@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
282 lines • 13.2 kB
JavaScript
import { execFile, execFileSync } from "node:child_process";
const WINDOWS_FILETIME_EPOCH = 116444736000000000n;
export const PROCESS_START_TOLERANCE_MS = 3_000;
/** FILETIME and C/localized lstart/ISO identities share one millisecond representation. */
export function processStartTimeMs(identity) {
if (/^\d+$/.test(identity)) {
const parsed = Number((BigInt(identity) - WINDOWS_FILETIME_EPOCH) / 10000n);
return Number.isFinite(parsed) ? parsed : undefined;
}
// Persisted lstart values, like the C-locale form, describe the host's local timezone.
const localIdentity = identity.trim();
const korean = /^(\d{4})\uB144\s+(\d{1,2})\uC6D4\s+(\d{1,2})\uC77C\s+[\uC6D4\uD654\uC218\uBAA9\uAE08\uD1A0\uC77C]\uC694\uC77C\s+(\d{1,2})\uC2DC\s+(\d{1,2})\uBD84\s+(\d{1,2})\uCD08$/.exec(localIdentity);
const japanese = /^[\u65E5\u6708\u706B\u6C34\u6728\u91D1\u571F](?:\u66DC\u65E5)?\s+(\d{1,2})\/\s*(\d{1,2})\s+(\d{2}):(\d{2}):(\d{2})\s+(\d{4})$/.exec(localIdentity);
const parts = korean
? korean.slice(1)
: japanese
? [japanese[6], japanese[1], japanese[2], japanese[3], japanese[4], japanese[5]]
: undefined;
if (parts === undefined) {
const parsed = Date.parse(identity);
return Number.isFinite(parsed) ? parsed : undefined;
}
const [year = NaN, month = NaN, day = NaN, hour = NaN, minute = NaN, second = NaN] = parts.map(Number);
const parsed = new Date(year, month - 1, day, hour, minute, second, 0);
// A recognized but invalid calendar must not fall back to Date.parse's rollover behavior.
return parsed.getFullYear() === year &&
parsed.getMonth() === month - 1 &&
parsed.getDate() === day &&
parsed.getHours() === hour &&
parsed.getMinutes() === minute &&
parsed.getSeconds() === second
? parsed.getTime()
: undefined;
}
export function sameProcessStartMs(recorded, observed) {
return (recorded !== undefined &&
observed !== undefined &&
Number.isFinite(recorded) &&
Number.isFinite(observed) &&
Math.abs(recorded - observed) <= PROCESS_START_TOLERANCE_MS);
}
export function parseDaemonPidFile(text) {
let parsed;
try {
parsed = JSON.parse(text);
}
catch (error) {
if (error instanceof SyntaxError)
return undefined;
throw error;
}
const unguarded = parsed !== null && isRecord(parsed) && parsed.processStartTime === null;
if (!isRecord(parsed) ||
typeof parsed.pid !== "number" ||
(!unguarded && typeof parsed.processStartTime !== "string")) {
return undefined;
}
if (!Number.isInteger(parsed.pid) || parsed.pid <= 0)
return undefined;
if (unguarded)
return { pid: parsed.pid, processStartTime: null };
if (typeof parsed.processStartTime !== "string" || parsed.processStartTime.trim() === "")
return undefined;
return { pid: parsed.pid, processStartTime: parsed.processStartTime };
}
/** Thrown when a live process refuses to yield an identity after the retry budget. */
export class ProcessIdentityUnreadableError extends Error {
constructor(pid, attempts, cause) {
super(`process identity for live pid ${pid} stayed unreadable after ${attempts} probe attempt(s): ${cause instanceof Error ? cause.message : String(cause)}`);
this.name = "ProcessIdentityUnreadableError";
this.pid = pid;
this.attempts = attempts;
this.cause = cause;
}
}
/**
* True when the pidfile still describes the running process. A probe FAILURE is not
* an answer: on a pid that is no longer live it means "gone" (false); on a live pid it
* is an observation gap — the platform query was starved or exited non-zero — so the
* probe is retried within a bounded budget and only then surfaces as
* ProcessIdentityUnreadableError. It never leaks the raw probe error as a verdict.
*/
export async function processMatchesPidFile(pidFile, readStartTime = readProcessStartTime, isLive = processIsRunning, retry = {}) {
// A record without an identity guard answers only the liveness half of the question: a pid
// that is gone is gone, and a live one stays unknown so it is never claimed or signalled.
if (pidFile.processStartTime === null) {
if (!isLive(pidFile.pid))
return false;
throw new ProcessIdentityUnreadableError(pidFile.pid, 0, new Error("pidfile carries no process identity guard"));
}
const attempts = Math.max(1, retry.attempts ?? 5);
const delayMs = retry.delayMs ?? 200;
let lastError;
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
const current = await readStartTime(pidFile.pid);
if (current !== undefined) {
const recorded = processStartTimeMs(pidFile.processStartTime);
const observed = processStartTimeMs(current);
if (recorded !== undefined && observed !== undefined)
return sameProcessStartMs(recorded, observed);
}
if (!isLive(pidFile.pid))
return false;
lastError = new Error("process identity probe returned no usable identity for a live process");
if (attempt < attempts)
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
catch (error) {
if (!isLive(pidFile.pid))
return false;
lastError = error;
if (attempt < attempts)
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
}
throw new ProcessIdentityUnreadableError(pidFile.pid, attempts, lastError);
}
export async function readProcessIdentity(pid, platform = process.platform, timeoutMs, isLive = processIsLive,
/** Owner records cross launch environments; legacy pidfiles keep their existing local-time format. */
timeZone) {
const command = platform === "win32"
? {
executable: "powershell.exe",
args: [
"-NoProfile",
"-NonInteractive",
"-Command",
`$process = Get-CimInstance Win32_Process -Filter "ProcessId=${String(pid)}" -ErrorAction Stop; if ($null -eq $process) { Write-Output '__SENPI_ABSENT__'; exit 0 }; $process.CreationDate.ToFileTimeUtc().ToString("D", [Globalization.CultureInfo]::InvariantCulture)`,
],
}
: // State and start time from ONE snapshot: an exited, unreaped process (state Z) keeps its start
// time but runs nothing, so it has no identity to match (senpi#4119).
{ executable: "ps", args: ["-o", "stat=,lstart=", "-p", String(pid)] };
return new Promise((resolve) => {
const effectiveTimeoutMs = timeoutMs ?? (platform === "win32" ? 1_000 : undefined);
execFile(command.executable, command.args, {
windowsHide: true,
...(effectiveTimeoutMs === undefined ? {} : { timeout: effectiveTimeoutMs }),
...(platform === "win32" && timeZone === undefined
? {}
: { env: { ...process.env, LC_ALL: "C", LANG: "C", ...(timeZone ? { TZ: timeZone } : {}) } }),
}, (error, stdout) => {
if (error) {
const code = "code" in error ? error.code : undefined;
// ps exits 1 for an unknown pid; on every platform a query that fails against a
// pid that is no longer live has answered the question. Only a failure against a
// LIVE pid is an observation error the caller must treat as unknown.
if ((platform !== "win32" && code === 1) || !isLive(pid)) {
resolve({ kind: "absent" });
return;
}
resolve({ kind: "error", error });
return;
}
const snapshot = stdout.trim();
if (snapshot === "__SENPI_ABSENT__")
return resolve({ kind: "absent" });
const state = platform === "win32" ? "" : (snapshot.split(/\s+/, 1)[0] ?? "");
if (state.startsWith("Z"))
return resolve({ kind: "absent" });
const output = platform === "win32" ? snapshot : snapshot.slice(state.length).trim();
if (!output || (platform === "win32" && !/^\d+$/.test(output)))
return resolve({ kind: "error", error: new Error("invalid process identity output") });
resolve({ kind: "present", identity: timeZone && platform !== "win32" ? `${output} UTC` : output });
}).once("error", (error) => resolve({ kind: "error", error }));
});
}
export async function stopValidatedPid(pidFile, signal) {
if (!(await processMatchesPidFile(pidFile)))
return;
try {
process.kill(pidFile.pid, signal);
}
catch (error) {
if (!isNodeErrorCode(error, "ESRCH"))
throw error;
}
if (signal === "SIGTERM")
await waitForGone(pidFile, 10_000);
if (signal === "SIGKILL")
await waitForGone(pidFile, 2_000);
}
export async function waitForGone(pidFile, timeoutMs) {
const deadline = Date.now() + timeoutMs;
while (Date.now() <= deadline) {
if (!(await processMatchesPidFile(pidFile)))
return true;
await delay(100);
}
return !(await processMatchesPidFile(pidFile));
}
/**
* The live start time of `pid` as one string, or undefined when the process is gone.
* Throws when the probe fails against a live pid.
*
* Probes read in UTC by default: a local-form start time is ambiguous in a DST fall-back
* hour, so a UTC-tagged record compared against a local probe can read one hour off and a
* live child stops counting as a holder (senpi#3067 L1). Legacy local-format records are
* still parsed as local time by `processStartTimeMs`.
*/
export async function readProcessStartTime(pid, platform = process.platform, timeoutMs, timeZone = "UTC") {
return readProcessIdentity(pid, platform, timeoutMs, undefined, timeZone).then((result) => {
if (result.kind === "error")
throw result.error;
return result.kind === "present" ? result.identity : undefined;
});
}
/**
* `processIsLive` minus processes that have exited but are not reaped yet (state Z): a SIGKILLed host
* stays a zombie until its parent's loop, or init, waits on it, and `kill(pid, 0)` still succeeds for it
* (senpi#4119). One `ps` snapshot decides; a probe that fails any other way reads as running, so a
* starved probe on a live process is never taken for a dead one (#1609).
*/
export function processIsRunning(pid) {
if (!processIsLive(pid))
return false;
if (process.platform === "win32")
return true;
try {
const state = execFileSync("ps", ["-o", "stat=", "-p", String(pid)], { encoding: "utf8", timeout: 2_000 });
return !state.trim().startsWith("Z");
}
catch (error) {
if (error instanceof Error && "status" in error && error.status === 1)
return false;
return true;
}
}
export function processIsLive(pid) {
try {
process.kill(pid, 0);
return true;
}
catch (error) {
if (isNodeErrorCode(error, "ESRCH"))
return false;
if (isNodeErrorCode(error, "EPERM"))
return true;
throw error;
}
}
/**
* Wait for a spawned pid's process identity.
*
* Returns `undefined` (UNKNOWN) when the budget is exhausted but the process is still alive:
* budget exhaustion is an OBSERVABILITY failure, not evidence the child failed to start. On a
* loaded Windows runner every `Get-CimInstance` probe can outlive `readProcessIdentity`'s 1s win32
* default, so all ~9 attempts inside a 10s budget time out and throw while the process runs
* normally (PR #1351/#1352 CI, runs 33839093178 / 33842155236). Only a pid that is really gone is
* a startup failure, so callers can distinguish "no identity yet" from "child died".
*/
export async function waitForStartTime(pid, timeoutMs, readStartTime = readProcessStartTime, isLive = processIsLive) {
const deadline = Date.now() + timeoutMs;
while (Date.now() <= deadline) {
let startTime;
try {
startTime = await readStartTime(pid);
}
catch {
// Process identity queries can fail transiently while a Windows process is
// entering the CIM table. Keep the bounded startup wait alive so callers do
// not mistake an observability failure for a child startup failure.
}
if (startTime)
return startTime;
await delay(20);
}
if (isLive(pid))
return undefined;
throw new Error(`spawned daemon pid ${pid} had no process start time`);
}
function delay(ms) {
return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
}
function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isNodeErrorCode(error, code) {
return error instanceof Error && "code" in error && error.code === code;
}
//# sourceMappingURL=process-identity.js.map