Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Keep Hermes' shared gateway running when one Hermes conversation stops

Bugfixer 26eac5069c7fa
diff --git a/server/kill-tree.test.ts b/server/kill-tree.test.ts
index fa367a096e..b146b53add 100644
--- a/server/kill-tree.test.ts
+++ b/server/kill-tree.test.ts
@@ -120,6 +120,44 @@ describe("killCliTree", () => {
}
});
+ it.runIf(process.platform === "linux").each([true, false])("leaves a gateway the CLI started to outlive it, and that gateway's own children, running (gateway command: %s)", async (isGateway) => {
+ const gateway = `
+ const s = require('node:child_process').spawn(process.execPath, ['-e', ${JSON.stringify(`console.log(process.pid); ${IDLE}`)}], { stdio: ['ignore', 'pipe', 'ignore'] });
+ s.stdout.once('data', (pid) => console.log(process.pid + ' ' + String(pid).trim()));
+ ${IDLE};
+ `;
+ // Hermes starts it as `python -m hermes_cli.main gateway run --quiet --idle-exit`; any other command with the same
+ // inherited variable is still stopped.
+ const gatewayArgs = ['-e', gateway, ...(isGateway ? ['gateway', 'run', '--quiet'] : [])];
+ const parent = spawnCli(process.execPath, ["-e", `
+ const c = require('node:child_process').spawn(process.execPath, ${JSON.stringify(gatewayArgs)}, {
+ detached: true, stdio: ['ignore', 'pipe', 'ignore'], env: { ...process.env, HERMES_GATEWAY_DETACHED: '1' },
+ });
+ c.stdout.once('data', (pids) => process.stdout.write(pids));
+ ${IDLE};
+ `], { stdio: ["pipe", "pipe", "pipe"] });
+ let kept: number[] = [];
+ try {
+ kept = await new Promise<number[]>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error("the gateway did not report its pids")), 5_000);
+ let line = "";
+ parent.stdout.on("data", (chunk) => {
+ line += String(chunk);
+ if (!line.includes("\n")) return;
+ clearTimeout(timer);
+ resolve(line.trim().split(" ").map(Number));
+ });
+ });
+ expect(kept).toHaveLength(2);
+ captureCliTree(parent);
+ await expect(killCliTree(parent, 80)).resolves.toBe(true);
+ expect(kept.map(alive)).toEqual([isGateway, isGateway]);
+ } finally {
+ await killCliTree(parent, 0);
+ for (const pid of kept) if (alive(pid)) try { process.kill(pid, "SIGKILL"); } catch {}
+ }
+ }, 20_000);
+
it.skipIf(process.platform === "win32")("escalates ignored TERM and shares concurrent stop attempts", async () => {
const child = spawnCli(process.execPath, ["-e", STUBBORN], { stdio: ["pipe", "pipe", "pipe"] });
try {
diff --git a/server/procs.ts b/server/procs.ts
index 72a7f75296..2def936d3d 100644
--- a/server/procs.ts
+++ b/server/procs.ts
@@ -60,7 +60,7 @@ export function assertSafeCliArgv(
const cliGroups = new WeakSet<ChildProcess>();
const stopping = new WeakMap<ChildProcess, Promise<boolean>>();
-type LinuxProcess = { pid: number; parent: number; start: string; state: string };
+type LinuxProcess = { pid: number; parent: number; start: string; state: string; session?: number };
const linuxTrees = new WeakMap<ChildProcess, Map<number, string>>();
const PS_ROW = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.+?)\s*$/;
@@ -104,7 +104,7 @@ function linuxProcess(pid: number, file = `/proc/${pid}/stat`): LinuxProcess | n
const state = fields[0];
const parent = Number(fields[1]);
if (!start || !state || !Number.isInteger(parent)) throw new Error("Unreadable Linux process identity");
- return { pid, parent, start, state };
+ return { pid, parent, start, state, session: Number(fields[3]) };
}
/** /proc/<pid>/task/<tid>/children needs CONFIG_PROC_CHILDREN (CONFIG_CHECKPOINT_RESTORE before Linux 4.2); a kernel built without it, or gVisor, has no such file. */
@@ -131,6 +131,19 @@ function linuxChildren(pid: number): number[] | null {
return children;
}
+/** A daemon a CLI starts on purpose to outlive it, in a session of its own: Hermes' shared gateway, which every other
+ * conversation's `hermes acp` on the same profile attaches to. A stop leaves it and its own children out of the tree. */
+function outlivesLauncher({ pid, session }: LinuxProcess): boolean {
+ if (session !== pid) return false;
+ try {
+ const argv = readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0");
+ if (!argv.some((word, at) => word === "gateway" && argv[at + 1] === "run")) return false;
+ return readFileSync(`/proc/${pid}/environ`, "utf8").split("\0").includes("HERMES_GATEWAY_DETACHED=1");
+ } catch {
+ return false;
+ }
+}
+
function isLinuxProcess(pid: number, start: string): boolean {
try { return linuxProcess(pid)?.start === start; } catch { return false; }
}
@@ -163,7 +176,7 @@ function addLinuxDescendants(tree: Map<number, string>): boolean {
let current: LinuxProcess | null;
try { current = linuxProcess(pid); } catch { return false; }
if (!current || current.parent !== parent) return false;
- if (tree.get(pid) === current.start) continue;
+ if (tree.get(pid) === current.start || outlivesLauncher(current)) continue;
tree.set(pid, current.start);
queue.push([pid, current.start]);
}
@@ -192,6 +205,7 @@ function addDescendantsFromEveryProcess(tree: Map<number, string>): void {
discovered = false;
for (const current of snapshot.values()) {
if (current.pid === process.pid || !parents.has(current.parent) || tree.get(current.pid) === current.start) continue;
+ if (outlivesLauncher(current)) continue;
tree.set(current.pid, current.start);
parents.add(current.pid);
discovered = true;