UNPKG

@phren/cli

Version:

Knowledge layer for AI agents - CLI, MCP server, and data layer

57 lines (56 loc) • 1.83 kB
import { execFile } from "node:child_process"; import { promisify } from "node:util"; const exec = promisify(execFile); const probes = new Set(); let stopping = false; function track(child, kill) { if (!child.pid) return child; const stop = () => { if (child.exitCode === null && child.signalCode === null) kill(child); child.stdin?.destroy(); child.stdout?.destroy(); child.stderr?.destroy(); }; probes.add(stop); child.once("close", () => probes.delete(stop)); return child; } const forceKill = (child) => { child.kill("SIGKILL"); }; // Only use this for probes started in their own process group. export function killProbeGroup(child) { if (process.platform !== "win32" && child.pid) { try { process.kill(-child.pid, "SIGKILL"); return; } catch { /* Fall back to the direct child. */ } } forceKill(child); } // Only short-lived checks opt in. Pane and worker launchers own their process lifetimes. export function startProbe(start, kill = forceKill) { if (stopping) throw new Error("The Hook is shutting down."); return track(start(), kill); } export async function execProbe(file, args, { input, ...options }) { if (stopping) throw new Error("The Hook is shutting down."); const result = exec(file, args, options); if (result.child) track(result.child, forceKill); if (input !== undefined && result.child?.stdin) { // A command can exit before reading stdin, for example when authentication fails. result.child.stdin.on("error", () => { }); result.child.stdin.end(input); } return result; } export function stopProbes() { stopping = true; for (const stop of probes) stop(); probes.clear(); }