Open-source, local-first AI agent for real work.
TypeScript agent-toolsai-agentbyokcoding-agentcross-platformdesktop-appdeveloper-toolselectronharnessknowledge-basellmwikilocal-firstmcpplugin-systemprivacy-firstskillstypescriptvettaworkflow-automation
import { execFile } from "node:child_process";
import type { DetachedProcessGroup, DetachedProcessGroupListener } from "../shared/background-command-host.js";
const DEFAULT_POLL_MS = 1_000;
const TERMINATE_GRACE_MS = 2_000;
/** `ps` reports elapsed time with one-second resolution. */
const START_TIME_TOLERANCE_MS = 2_000;
/** True while at least one process we may signal still belongs to the group. */
export function isProcessGroupAlive(processGroupId: number): boolean {
if (process.platform === "win32" || processGroupId <= 1) return false;
try {
process.kill(-processGroupId, 0);
return true;
} catch {
// ESRCH: the group is empty. EPERM: the id now belongs to someone else's processes.
return false;
}
}
/** SIGTERM first so servers can shut down cleanly, SIGKILL whatever is left after a grace period. */
export function terminateProcessGroup(processGroupId: number, graceMs = TERMINATE_GRACE_MS): void {
if (!signalGroup(processGroupId, "SIGTERM")) return;
const timer = setTimeout(() => {
if (isProcessGroupAlive(processGroupId)) signalGroup(processGroupId, "SIGKILL");
}, graceMs);
timer.unref?.();
}
function signalGroup(processGroupId: number, signal: NodeJS.Signals): boolean {
try {
process.kill(-processGroupId, signal);
return true;
} catch {
return false;
}
}
/** Parses `ps` elapsed time (`[[dd-]hh:]mm:ss`) into milliseconds. */
export function parseProcessElapsedTime(value: string): number | undefined {
const match = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(value.trim());
if (!match) return undefined;
const [, days, hours, minutes, seconds] = match;
return (((Number(days ?? 0) * 24 + Number(hours ?? 0)) * 60 + Number(minutes)) * 60 + Number(seconds)) * 1_000;
}
/** Start times (epoch ms) of the processes currently in the group, read from `ps -A -o pgid=,etime=`. */
export function parseProcessGroupStartTimes(psOutput: string, processGroupId: number, now: number): number[] {
const startTimes: number[] = [];
for (const line of psOutput.split("\n")) {
const [group, elapsed] = line.trim().split(/\s+/);
if (Number(group) !== processGroupId || !elapsed) continue;
const elapsedMs = parseProcessElapsedTime(elapsed);
if (elapsedMs !== undefined) startTimes.push(now - elapsedMs);
}
return startTimes;
}
function readProcessGroupStartTimes(processGroupId: number): Promise<number[]> {
return new Promise((resolve) => {
execFile(
"ps",
["-A", "-o", "pgid=,etime="],
{ env: { ...process.env, LC_ALL: "C" }, maxBuffer: 8 * 1024 * 1024 },
(error, stdout) => resolve(error ? [] : parseProcessGroupStartTimes(stdout, processGroupId, Date.now())),
);
});
}
/**
* A process group id can be reused once the group empties. The group only counts as the one we
* adopted when one of its processes was already running at adoption time.
*/
export async function isSameProcessGroup(processGroupId: number, adoptedAt: number): Promise<boolean> {
if (!isProcessGroupAlive(processGroupId)) return false;
const startTimes = await readProcessGroupStartTimes(processGroupId);
return startTimes.some((startedAt) => startedAt <= adoptedAt + START_TIME_TOLERANCE_MS);
}
export interface WatchedDetachedProcessGroup extends DetachedProcessGroup {
/** Output still arriving on pipes the group inherited from the command shell. */
push(text: string): void;
}
/** Polls the group until it empties; buffers output until a listener attaches. */
export function watchDetachedProcessGroup(
processGroupId: number,
adoptedAt: number,
options: { readonly pollMs?: number; readonly onRelease?: () => void } = {},
): WatchedDetachedProcessGroup {
const pending: string[] = [];
let listener: DetachedProcessGroupListener | undefined;
let timer: ReturnType<typeof setInterval> | undefined;
let finished = false;
const end = (): void => {
if (finished) return;
finished = true;
if (timer) clearInterval(timer);
timer = undefined;
listener?.onExit();
};
return {
processGroupId,
adoptedAt,
attach(next) {
if (finished || listener) return;
listener = next;
for (const text of pending.splice(0)) next.onOutput(text);
if (!isProcessGroupAlive(processGroupId)) {
end();
return;
}
timer = setInterval(() => {
if (!isProcessGroupAlive(processGroupId)) end();
}, options.pollMs ?? DEFAULT_POLL_MS);
timer.unref?.();
},
push(text) {
if (finished) return;
if (listener) listener.onOutput(text);
else pending.push(text);
},
stop() {
terminateProcessGroup(processGroupId);
},
release() {
if (finished) return;
finished = true;
if (timer) clearInterval(timer);
timer = undefined;
listener = undefined;
options.onRelease?.();
},
};
}