Skip to content

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

Footprint: a browser counts only once its pid is checked to be the session's daemon; an exited engine's reused pid retires its record

milind-sonid1df93d4fa9b
diff --git a/server/browser-processes.ts b/server/browser-processes.ts
index 080e6f59f9..2d6ec0ef67 100644
--- a/server/browser-processes.ts
+++ b/server/browser-processes.ts
@@ -96,10 +96,7 @@ async function processEnvironment(pid: number): Promise<Map<string, string> | nu
if (listing === null) return null;
entries = listing.trim().split(/\s+/);
}
- return new Map(entries.flatMap((entry) => {
- const match = /^([A-Z_][A-Z0-9_]*)=(.*)$/.exec(entry);
- return match ? [[match[1]!, match[2]!] as const] : [];
- }));
+ return environmentEntries(entries);
}
async function imageOf(pid: number): Promise<string | null> {
@@ -107,21 +104,44 @@ async function imageOf(pid: number): Promise<string | null> {
return row === null ? null : /^"([^"]*)"/.exec(row.trim())?.[1]?.toLowerCase() ?? "";
}
+/** The paths a daemon of `binaryPath` runs as: the path given and, where it resolves elsewhere, the resolved one. */
+export function daemonPaths(binaryPath: string): Set<string> {
+ const paths = new Set([binaryPath]);
+ try { paths.add(realpathSync(binaryPath)); } catch {}
+ return paths;
+}
+
/** agent-browser starts a daemon through the binary's resolved path with AGENT_BROWSER_DAEMON=1 and the session's name, so a
- * pid now running another program, command or session is not it. Read before the close: afterwards Chrome is re-parented. */
+ * pid now running another program, command or session is not it. Unread arguments or environment: not it. */
+export function isBrowserDaemon(paths: ReadonlySet<string>, command: string | null, env: ReadonlyMap<string, string> | null, session: string): boolean {
+ if (!command || ![...paths].some((path) => command === path || command.startsWith(`${path} `))) return false;
+ return env?.get("AGENT_BROWSER_DAEMON") === "1" && env.get("AGENT_BROWSER_SESSION") === session;
+}
+
+/** An environment as /proc/<pid>/environ or `ps -E` lists it: NAME=value entries. */
+export function environmentEntries(entries: readonly string[]): Map<string, string> {
+ return new Map(entries.flatMap((entry) => {
+ const match = /^([A-Z_][A-Z0-9_]*)=(.*)$/.exec(entry);
+ return match ? [[match[1]!, match[2]!] as const] : [];
+ }));
+}
+
+/** Whether `daemon` runs agent-browser's daemon for `session` now (POSIX): its arguments and environment are read again. */
+export async function browserDaemonRuns(binaryPath: string, daemon: number, session: string): Promise<boolean> {
+ if (process.platform === "win32" || !Number.isInteger(daemon) || daemon <= 1 || daemon === process.pid || !processAlive(daemon)) return false;
+ return isBrowserDaemon(daemonPaths(binaryPath), await processArgs(daemon), await processEnvironment(daemon), session);
+}
+
+/** Read before the close: afterwards Chrome is re-parented. */
export async function browserProcessTree(binaryPath: string, daemon: number, session: string): Promise<BrowserProcessTree | null> {
if (!Number.isInteger(daemon) || daemon <= 1 || daemon === process.pid || !processAlive(daemon)) return null;
- const paths = new Set([binaryPath]);
- try { paths.add(realpathSync(binaryPath)); } catch {}
+ const paths = daemonPaths(binaryPath);
if (process.platform === "win32") {
// Windows shows no environments, trees or start times: the image tells the daemon from a later program, and taskkill /T walks the tree.
const image = await imageOf(daemon);
return image && [...paths].some((path) => basename(path).toLowerCase() === image) ? { daemon, members: new Map([[daemon, ""]]), groups: [], image } : null;
}
- const command = await processArgs(daemon);
- if (!command || ![...paths].some((path) => command === path || command.startsWith(`${path} `))) return null;
- const env = await processEnvironment(daemon);
- if (env?.get("AGENT_BROWSER_DAEMON") !== "1" || env.get("AGENT_BROWSER_SESSION") !== session) return null;
+ if (!isBrowserDaemon(paths, await processArgs(daemon), await processEnvironment(daemon), session)) return null;
const table = await processTable();
if (!table?.has(daemon)) return null;
const children = new Map<number, number[]>();
diff --git a/server/engine-owners.ts b/server/engine-owners.ts
index 25a453cb45..8cfa007c5e 100644
--- a/server/engine-owners.ts
+++ b/server/engine-owners.ts
@@ -17,7 +17,7 @@ export interface EngineOwner {
const MAX_ENTRIES = 4_096;
-interface Entry { pid: number; start: string | null; threads: Map<string, string>; exited: boolean }
+interface Entry { pid: number; start: string | null; threads: Map<string, string>; exited: boolean; seenSinceExit: number }
export class EngineOwners {
readonly #entries = new Map<number, Entry>();
@@ -28,7 +28,7 @@ export class EngineOwners {
const pid = child.pid;
if (!pid) return;
const turn = currentTurn();
- const entry: Entry = { pid, start, threads: new Map(turn?.threadId ? [[turn.threadId, turn.botId ?? ""]] : []), exited: false };
+ const entry: Entry = { pid, start, threads: new Map(turn?.threadId ? [[turn.threadId, turn.botId ?? ""]] : []), exited: false, seenSinceExit: 0 };
this.#entries.set(pid, entry);
// Where no process list ever prunes it (no sampler runs), the oldest exited engines go first.
if (this.#entries.size > MAX_ENTRIES) for (const [other, old] of this.#entries) { if (this.#entries.size <= MAX_ENTRIES) break; if (old.exited) this.#entries.delete(other); }
@@ -51,9 +51,22 @@ export class EngineOwners {
return [...this.#entries.values()].map((entry) => ({ pid: entry.pid, start: entry.start, threads: entry.threads, exited: entry.exited }));
}
- /** Forgets exited engines that nothing in `inUse` (the process groups and sessions a process list shows) still names. */
- prune(inUse: ReadonlySet<number>): void {
- for (const [pid, entry] of this.#entries) if (entry.exited && !inUse.has(pid)) this.#entries.delete(pid);
+ /** After each process list: forgets an exited engine that no process, group or session in it still names, and one whose
+ * pid the list shows as another process (the system gave the number on, which it does only once no group or session
+ * still has it: nothing the engine left runs any more). Retired at the first sight, it stays retired: once that other
+ * process exits, its pid is not the engine's again. Where the engine's start was not read (off Linux) the list shows
+ * no start to tell them apart; an exited engine was reaped before it was marked so, and the pid seen in two lists after
+ * that is another process's. */
+ prune(rows: readonly { pid: number; start: string; pgid?: number; sid?: number }[]): void {
+ const inUse = new Set<number>(), starts = new Map<number, string>();
+ for (const row of rows) { inUse.add(row.pid); starts.set(row.pid, row.start); if (row.pgid !== undefined) inUse.add(row.pgid); if (row.sid !== undefined) inUse.add(row.sid); }
+ for (const [pid, entry] of this.#entries) {
+ if (!entry.exited) continue;
+ const start = starts.get(pid);
+ if (!inUse.has(pid)) this.#entries.delete(pid);
+ else if (start === undefined) continue;
+ else if (entry.start !== null ? start !== entry.start : (entry.seenSinceExit += 1) >= 2) this.#entries.delete(pid);
+ }
}
}
diff --git a/server/host/browser-daemons.test.ts b/server/host/browser-daemons.test.ts
new file mode 100644
index 0000000000..acf5204430
--- /dev/null
+++ b/server/host/browser-daemons.test.ts
@@ -0,0 +1,105 @@
+// A browser's pid file counts a process as that bot's browser only once the process is checked to be the session's own
+// agent-browser daemon: a stale file (the volume outlived an OOM kill or a machine stop) never names init, the supervisor,
+// this server or an unrelated program.
+import { spawn, type ChildProcess } from "node:child_process";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { browserDaemonRuns } from "../browser-processes.ts";
+import { attributeRows } from "../perf/bot-footprint.ts";
+import { linuxProcessList } from "../perf/process-sampler.ts";
+import { createBrowserDaemons } from "./browser-daemons.ts";
+
+const MB = 1_048_576, PAGE = 4096;
+const BINARY = "/opt/agent-browser/bin/agent-browser";
+const stat = (pid: number, comm: string, ppid: number, { pgid = pid, sid = pid, start = 1000 + pid, rssMB = 10 } = {}) =>
+ `${pid} (${comm}) S ${ppid} ${pgid} ${sid} 0 -1 4194304 100 0 0 0 0 0 0 0 20 0 1 0 ${start} 1000000 ${(rssMB * MB) / PAGE} 18446744073709551615`;
+
+/** A Cloud after a restart: tini (1) runs the supervisor (50), which runs this server (100); postgres (900) runs beside it;
+ * the session bot-a's daemon is 500 with its Chrome 501. */
+function cloud(overrides: Record<string, string | null> = {}) {
+ const files: Record<string, string | null> = {
+ "/proc/1/stat": stat(1, "tini", 0, { pgid: 1, sid: 1 }), "/proc/1/cmdline": "tini\0--\0supervisor\0", "/proc/1/environ": "HOME=/data\0",
+ "/proc/50/stat": stat(50, "supervisor", 1, { pgid: 1, sid: 1 }), "/proc/50/cmdline": "supervisor\0", "/proc/50/environ": "HOME=/data\0",
+ "/proc/100/stat": stat(100, "node", 50, { pgid: 1, sid: 1, rssMB: 300 }), "/proc/100/cmdline": "node\0server/index.ts\0",
+ "/proc/100/environ": "HOME=/data\0AGENT_BROWSER_SESSION=bot-a\0",
+ "/proc/500/stat": stat(500, "agent-browser", 1), "/proc/500/cmdline": `${BINARY}\0`,
+ "/proc/500/environ": "HOME=/data\0AGENT_BROWSER_DAEMON=1\0AGENT_BROWSER_SESSION=bot-a\0",
+ "/proc/501/stat": stat(501, "chrome", 500, { pgid: 501, sid: 500, rssMB: 400 }),
+ "/proc/900/stat": stat(900, "postgres", 1, { rssMB: 800 }), "/proc/900/cmdline": "postgres\0", "/proc/900/environ": "HOME=/var/lib/postgresql\0",
+ ...overrides,
+ };
+ const read = (path: string) => files[path] ?? null;
+ const rows = linuxProcessList(read, () => Object.keys(files).flatMap((path) => /^\/proc\/(\d+)\/stat$/.exec(path)?.[1] ?? [])).rows;
+ return { read, rows, daemons: createBrowserDaemons({ platform: "linux", read, self: 100, parent: 50 }) };
+}
+
+describe("a browser's daemon, checked before it counts", () => {
+ it("counts the session's own daemon with its start, and so its Chrome", () => {
+ const { daemons, rows } = cloud();
+ const owner = daemons.owner(BINARY, "bot-a", 500);
+ expect(owner).toEqual({ pid: 500, start: "1500" });
+ expect(attributeRows(rows, [{ ...owner!, botIds: ["bot_a"], kind: "browser" }]).bots.get("bot_a")?.pids).toEqual([500, 501]);
+ });
+
+ it("never counts a stale pid file naming init, the supervisor, this server or an unrelated program", () => {
+ const { daemons, rows } = cloud();
+ for (const pid of [1, 50, 100, 900, 4242, 0, -1, Number.NaN]) expect(daemons.owner(BINARY, "bot-a", pid)).toBeNull();
+ // Had the supervisor counted, everything under it (this server among it) would be bot A's.
+ const owners = [50, 100, 900].flatMap((pid) => { const owner = daemons.owner(BINARY, "bot-a", pid); return owner ? [{ ...owner, botIds: ["bot_a"], kind: "browser" as const }] : []; });
+ expect(attributeRows(rows, owners).bots.size).toBe(0);
+ });
+
+ it("refuses another session's daemon, another program at the daemon's pid, and a daemon whose environment can't be read", () => {
+ expect(cloud().daemons.owner(BINARY, "bot-b", 500)).toBeNull();
+ expect(cloud().daemons.owner("/usr/bin/other", "bot-a", 500)).toBeNull();
+ expect(cloud({ "/proc/500/environ": null }).daemons.owner(BINARY, "bot-a", 500)).toBeNull();
+ expect(cloud({ "/proc/500/cmdline": null }).daemons.owner(BINARY, "bot-a", 500)).toBeNull();
+ });
+
+ it("keeps a check with the pid's start: the pid given to another program since is checked again and refused", () => {
+ const files: Record<string, string | null> = {};
+ const base = cloud();
+ let reads = 0;
+ const read = (path: string) => { if (path.endsWith("/environ")) reads += 1; return path in files ? files[path]! : base.read(path); };
+ const daemons = createBrowserDaemons({ platform: "linux", read, self: 100, parent: 50 });
+ expect(daemons.owner(BINARY, "bot-a", 500)).toEqual({ pid: 500, start: "1500" });
+ expect(daemons.owner(BINARY, "bot-a", 500)).toEqual({ pid: 500, start: "1500" });
+ // Read once: a sample (or the memory watchdog every few seconds) reads only the pid's stat line after that.
+ expect(reads).toBe(1);
+ Object.assign(files, { "/proc/500/stat": stat(500, "postgres", 1, { start: 99_999 }), "/proc/500/cmdline": "postgres\0", "/proc/500/environ": "HOME=/x\0" });
+ expect(daemons.owner(BINARY, "bot-a", 500)).toBeNull();
+ expect(reads).toBe(2);
+ });
+});
+
+describe("a browser's daemon, checked on real processes", () => {
+ const started: ChildProcess[] = [];
+ afterEach(() => { for (const child of started.splice(0)) child.kill("SIGKILL"); });
+ const run = (env: Record<string, string>) => {
+ const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { env: { ...process.env, ...env }, stdio: "ignore" });
+ started.push(child);
+ return child;
+ };
+ /** Asks until an answer other than null comes or the deadline passes: off Linux the check runs in the background. */
+ async function settled(ask: () => unknown, ms = 10_000): Promise<unknown> {
+ let answer = ask();
+ for (const end = Date.now() + ms; answer === null && Date.now() < end; answer = ask()) await new Promise((resolve) => setTimeout(resolve, 100));
+ return answer;
+ }
+
+ it.runIf(process.platform !== "win32")("counts a real daemon of the session and not a stale pid file naming another program or this process", async () => {
+ const daemon = run({ AGENT_BROWSER_DAEMON: "1", AGENT_BROWSER_SESSION: "bot-real" });
+ const unrelated = run({});
+ const checked: number[] = [];
+ const daemons = createBrowserDaemons({ check: async (binary, pid, session) => { try { return await browserDaemonRuns(binary, pid, session); } finally { checked.push(pid); } } });
+ expect(await settled(() => daemons.owner(process.execPath, "bot-real", daemon.pid!))).toMatchObject({ pid: daemon.pid });
+ // A stale file naming a running program that is no daemon: once checked (in the background off Linux), refused.
+ expect(daemons.owner(process.execPath, "stale", unrelated.pid!)).toBeNull();
+ if (process.platform !== "linux") await settled(() => (checked.includes(unrelated.pid!) ? true : null));
+ expect(daemons.owner(process.execPath, "stale", unrelated.pid!)).toBeNull();
+ // This server and its parent are never asked about at all.
+ expect(daemons.owner(process.execPath, "self", process.pid)).toBeNull();
+ expect(daemons.owner(process.execPath, "parent", process.ppid)).toBeNull();
+ expect(checked).not.toContain(process.pid);
+ }, 30_000);
+});
diff --git a/server/host/browser-daemons.ts b/server/host/browser-daemons.ts
new file mode 100644
index 0000000000..b0ecebcd35
--- /dev/null
+++ b/server/host/browser-daemons.ts
@@ -0,0 +1,98 @@
+// Which process a bot's agent-browser daemon is, for the per-bot footprint (perf/bot-footprint.ts) and what counts from it.
+// A session's pid file lives in the data folder, which on a Cloud is a volume that outlives the machine: after an OOM kill
+// or a stop, the pid it names may be tini, the supervisor, this server or anything else, and everything under it would
+// count as that bot's browser. So a pid counts only once it is checked to run agent-browser's daemon for that session (the
+// binary's path, AGENT_BROWSER_DAEMON=1 and the session's name in its environment, as browser-processes.ts checks before
+// a close), never this server or one of its ancestors, and the check is kept with the pid's start time: a pid the system
+// has since given to another process is checked again. Linux reads /proc (no spawn, so the sampler and the memory
+// watchdog can ask synchronously); elsewhere `ps` is asked in the background and a session counts from the next sample.
+import { readFileSync } from "node:fs";
+
+import { browserDaemonRuns, daemonPaths, environmentEntries, isBrowserDaemon } from "../browser-processes.ts";
+
+type Read = (path: string) => string | null;
+const readText: Read = (path) => { try { return readFileSync(path, "utf8"); } catch { return null; } };
+
+/** A pid's start tick and parent from its /proc stat line (the fields after the command's last ')'). */
+function statOf(pid: number, read: Read): { start: string; ppid: number } | null {
+ const text = read(`/proc/${pid}/stat`);
+ if (!text) return null;
+ const fields = text.slice(text.lastIndexOf(")") + 2).split(" ");
+ const start = fields[19], ppid = Number(fields[1]);
+ return start && Number.isInteger(ppid) ? { start, ppid } : null;
+}
+
+/** This server and every process above it, up to init: never a bot's browser, whatever a pid file says. */
+function serverLine(platform: NodeJS.Platform, read: Read, self: number, parent: number): Set<number> {
+ const line = new Set([1, self, parent]);
+ if (platform !== "linux") return line;
+ for (let pid = parent, depth = 0; pid > 1 && depth < 32; depth++) {
+ line.add(pid);
+ const next = statOf(pid, read)?.ppid;
+ if (next === undefined || next === pid) break;
+ pid = next;
+ }
+ return line;
+}
+
+export interface BrowserDaemonsOptions {
+ platform?: NodeJS.Platform;
+ read?: Read;
+ /** Elsewhere than Linux: whether the pid runs the session's daemon now (browser-processes.ts browserDaemonRuns). */
+ check?: (binaryPath: string, pid: number, session: string) => Promise<boolean>;
+ self?: number;
+ parent?: number;
+ now?: () => number;
+}
+
+/** How long a check stands where no start time tells a pid's processes apart (macOS): it is made again in the background. */
+const RECHECK_MS = 60_000;
+const MAX_SESSIONS = 1_024;
+
+export function createBrowserDaemons(options: BrowserDaemonsOptions = {}) {
+ const platform = options.platform ?? process.platform, read = options.read ?? readText, now = options.now ?? Date.now;
+ const check = options.check ?? browserDaemonRuns;
+ let excluded: Set<number> | null = null;
+ const server = () => (excluded ??= serverLine(platform, read, options.self ?? process.pid, options.parent ?? process.ppid));
+ /** By session: the pid checked, its start (Linux) or when it was checked (elsewhere), and whether it was the daemon. */
+ const checked = new Map<string, { pid: number; start: string | null; at: number; daemon: boolean }>();
+ const pending = new Set<string>();
+ const remember = (session: string, entry: { pid: number; start: string | null; at: number; daemon: boolean }) => {
+ checked.delete(session);
+ checked.set(session, entry);
+ if (checked.size > MAX_SESSIONS) checked.delete(checked.keys().next().value!);
+ };
+
+ return {
+ /** The daemon `pid` (read from `session`'s pid file) where it is checked to be that session's agent-browser daemon:
+ * with its start time on Linux, so a list that shows the pid with another start does not count it either. */
+ owner(binaryPath: string, session: string, pid: number): { pid: number; start?: string } | null {
+ if (!Number.isInteger(pid) || pid <= 1 || server().has(pid)) return null;
+ const known = checked.get(session);
+ if (platform === "linux") {
+ const stat = statOf(pid, read);
+ if (!stat) return null;
+ if (known?.pid === pid && known.start === stat.start) return known.daemon ? { pid, start: stat.start } : null;
+ const command = read(`/proc/${pid}/cmdline`)?.split("\0").filter(Boolean).join(" ") || null;
+ const environ = read(`/proc/${pid}/environ`);
+ const daemon = isBrowserDaemon(daemonPaths(binaryPath), command, environ === null ? null : environmentEntries(environ.split("\0")), session)
+ // Read again: the pid was not given to another process while its files were read.
+ && statOf(pid, read)?.start === stat.start;
+ remember(session, { pid, start: stat.start, at: now(), daemon });
+ return daemon ? { pid, start: stat.start } : null;
+ }
+ if (platform === "win32") return null;
+ const fresh = known?.pid === pid && now() - known.at < RECHECK_MS;
+ if (!fresh && !pending.has(session)) {
+ pending.add(session);
+ void check(binaryPath, pid, session).catch(() => false)
+ .then((daemon) => remember(session, { pid, start: null, at: now(), daemon }))
+ .finally(() => pending.delete(session));
+ }
+ return known?.pid === pid && known.daemon ? { pid } : null;
+ },
+ /** A session closed: its check goes. */
+ forget(session: string): void { checked.delete(session); },
+ };
+}
+export type BrowserDaemons = ReturnType<typeof createBrowserDaemons>;
diff --git a/server/host/browser.ts b/server/host/browser.ts
index b097a9bf5e..2435c403e4 100644
--- a/server/host/browser.ts
+++ b/server/host/browser.ts
@@ -34,6 +34,7 @@ import { BrowserSweep, browserIdleMs, type BrowserCleanupWireRequest } from "../
import { AudienceBrowsers, audienceBrowserSuffix } from "../browser/audience.ts";
import type { BrowserSitesTarget } from "../browser-sites.ts";
import { namedUploadPaths } from "../browser-upload.ts";
+import { createBrowserDaemons } from "./browser-daemons.ts";
import type { BrowserSitesRef } from "../routes/browser-sites.ts";
import { chromeLauncher } from "../browser/chrome/launcher.ts";
import { LAUNCHER_SECCOMP_FD, browserLanguage, type LauncherBox } from "../browser/chrome/wrapper.ts";
@@ -468,17 +469,20 @@ export function createBrowserHost(deps: BrowserHostDeps) {
if (chromeTarget(session, spec)) return chromeEngine.service.runs(session);
return existsSync(browserDaemonFile(browserRuntimeEnv({ ...spec?.env, AGENT_BROWSER_SESSION: session }), ".pid"));
}
+ const browserDaemons = createBrowserDaemons();
/** Each running agent-browser daemon (its session's pid file) with the bots whose browser it is: one bot's own, or a
* profile's several bots share. For the per-bot footprint (perf/bot-footprint.ts): one small file read a session. */
- function browserOwners(): Array<{ pid: number; botIds: string[]; kind: "browser" }> {
+ function browserOwners(): Array<{ pid: number; start?: string; botIds: string[]; kind: "browser" }> {
return [...usedBrowserSessions].flatMap(([session, spec]) => {
// A browser attached to the person's own Chrome is theirs, not a bot's.
if (chromeTarget(session, spec) || attachesToChrome(spec.env)) return [];
let pid: number;
try { pid = Number(readFileSync(browserDaemonFile(browserRuntimeEnv({ ...spec.env, AGENT_BROWSER_SESSION: session }), ".pid"), "utf8").trim()); } catch { return []; }
- if (!Number.isInteger(pid) || pid <= 1) return [];
+ // Only a pid checked to run this session's daemon (the file may outlive it on a Cloud's volume): browser-daemons.ts.
+ const daemon = browserDaemons.owner(spec.command, session, pid);
+ if (!daemon) return [];
const botIds = store.bots.filter((bot) => browserSessionsOf(bot.id, bot.browserProfile).includes(session)).map((bot) => bot.id);
- return [{ pid, botIds, kind: "browser" as const }];
+ return [{ ...daemon, botIds, kind: "browser" as const }];
});
}
/** The browser a thread's bot would start; a temporary one has no session until its first call. My Chrome is the person's own. */
diff --git a/server/index.ts b/server/index.ts
index 3f9c195cbc..ae7dd2c9c6 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -2789,7 +2789,7 @@ const { stopThreadForPerson, stopOnTypedCommand, restartForPerson } = createPers
const imageTools = createImageToolRoutes({ config: () => cfg, dataDir: DATA_DIR, liveTurn: (threadId) => liveTurnByThread.get(threadId), key: turnAttachmentKey, images: (key) => (turnAttachmentsByTurn.get(key) ?? []).filter((item) => item.kind === "image").length, park: (key, image) => { const saved = saveImage(image.bytes, image.mime); turnAttachmentsByTurn.set(key, [...turnAttachmentsByTurn.get(key) ?? [], { kind: "image", path: saved.path, mime: saved.mime }]); } });
const noAiNotice = createNoAiNotice({ team: CLOUD_TEAM, dataDir: DATA_DIR, people: () => teamOwners.people?.list() ?? [], personName: teamHost.personName, inbox: () => teamMessages.inbox, language: personLanguages.forLine, threadLanguage: conversationLanguage });
const botNameClash = createBotNameClash({ store, people: () => teamMessages.people(), profileName: () => cfg.profile?.name });
-const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, hides: (from, target) => personalReach.hides(from, target), runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const perf = createPerfHost({ dataDir: DATA_DIR, bus, store, limits: () => limitClock.report(), engines: () => engineMemory.enginePids(), owners: footprintOwners({ botOf: (threadId) => store.botByThread(threadId)?.id ?? null, browsers: browserOwners }), pruneOwners: (inUse) => engineOwners.prune(inUse), wholeMachine: Boolean(CLOUD_HOME) }); const settingNudges = createSettingNudges({ dataDir: DATA_DIR, store }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, performance: perf.lines, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });
+const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, hides: (from, target) => personalReach.hides(from, target), runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const perf = createPerfHost({ dataDir: DATA_DIR, bus, store, limits: () => limitClock.report(), engines: () => engineMemory.enginePids(), owners: footprintOwners({ botOf: (threadId) => store.botByThread(threadId)?.id ?? null, browsers: browserOwners }), pruneOwners: (rows) => engineOwners.prune(rows), wholeMachine: Boolean(CLOUD_HOME) }); const settingNudges = createSettingNudges({ dataDir: DATA_DIR, store }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, performance: perf.lines, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });
const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, store, context: selectionContext, threadBusy, saveDefault: saveNewBotModel,
defaults: () => [cfg.defaultModelSelection, cfg.newBotDefaults?.profile.modelSelection], engineName: id => registry.get(id)?.displayName ?? id,
log: line => console.warn(line) });
diff --git a/server/perf/bot-footprint.test.ts b/server/perf/bot-footprint.test.ts
index f7b8e8649e..eacd4dedb1 100644
--- a/server/perf/bot-footprint.test.ts
+++ b/server/perf/bot-footprint.test.ts
@@ -127,7 +127,7 @@ describe("a bot's footprint, from a process list", () => {
it("lets records of exited engines go once nothing runs in their group or session", () => {
const pruned: number[][] = [];
- const footprints = createBotFootprints({ owners: () => OWNERS, prune: (inUse) => pruned.push([...inUse].filter((pid) => pid === 200 || pid === 777)) });
+ const footprints = createBotFootprints({ owners: () => OWNERS, prune: (rows) => pruned.push(rows.map((row) => row.pid).filter((pid) => pid === 200 || pid === 777)) });
footprints.sample(server());
expect(pruned).toEqual([[200]]);
});
@@ -145,9 +145,10 @@ describe("which bot an engine runs for", () => {
owners.detach(child, "thread_2");
child.emit("exit", 0, null);
expect(owners.list()[0]).toMatchObject({ exited: true });
- owners.prune(new Set([4242]));
+ // Something it left still runs in its session.
+ owners.prune([{ pid: 4300, start: "900", pgid: 4242, sid: 4242 }]);
expect(owners.list()).toHaveLength(1);
- owners.prune(new Set([1]));
+ owners.prune([{ pid: 1, start: "1" }]);
expect(owners.list()).toHaveLength(0);
// Outside a turn (a keep-warm ping): no conversation, so shared until one attaches.
owners.track(Object.assign(new EventEmitter(), { pid: 4243 }), null);
@@ -179,6 +180,36 @@ describe("which bot an engine runs for", () => {
expect(attributeRows([{ pid: 30, ppid: 1, name: "claude", cpuMs: 0, rssBytes: MB, start: "s" }], visited).shared.procs).toBe(1);
});
+ it("retires an exited engine the first time its pid shows as another process, and keeps it retired once that one exits", () => {
+ const owners = new EngineOwners();
+ const child = Object.assign(new EventEmitter(), { pid: 200 });
+ runInTurn({ botId: "bot_a", threadId: "thread_a" }, () => owners.track(child, "1200"));
+ const list = footprintOwners({ botOf: () => "bot_a", browsers: () => [], engines: owners });
+ child.emit("exit", 0, null);
+ // What the engine left still runs in its session: kept.
+ const left = fakeProc({ [SERVER]: stat(SERVER, "node", 1, { pgid: 1, sid: 1 }), 203: stat(203, "sleep", 1, { pgid: 200, sid: 200 }) });
+ owners.prune(left);
+ expect(attributeRows(left, list()).bots.get("bot_a")?.pids).toEqual([203]);
+ // Later the system gives 200 to another program, which leads its own session and starts a child there.
+ const reused = fakeProc({ 200: stat(200, "postgres", 1, { start: 99_000 }), 210: stat(210, "postgres", 200, { pgid: 200, sid: 200 }) });
+ owners.prune(reused);
+ expect(owners.list()).toHaveLength(0);
+ // That program exits, its child (adopted by init) still in session 200: nothing of it is bot A's.
+ const after = fakeProc({ 210: stat(210, "postgres", 1, { pgid: 200, sid: 200 }) });
+ owners.prune(after);
+ expect(attributeRows(after, list()).bots.size).toBe(0);
+ // Off Linux no start was read: the pid seen in two lists after the engine was reaped is another process's.
+ const mac = new EngineOwners();
+ const engine = Object.assign(new EventEmitter(), { pid: 300 });
+ runInTurn({ botId: "bot_b", threadId: "thread_b" }, () => mac.track(engine, null));
+ engine.emit("exit", 0, null);
+ const row = { pid: 300, start: "ps:300", pgid: 300 };
+ mac.prune([row]);
+ expect(mac.list()).toHaveLength(1);
+ mac.prune([row]);
+ expect(mac.list()).toHaveLength(0);
+ });
+
it("never names a process by an exited engine's pid, which may be another process's now", () => {
const rows: ProcessRow[] = [
{ pid: 200, ppid: 1, name: "postgres", cpuMs: 0, rssBytes: MB, start: "ps:200", pgid: 200 },
diff --git a/server/perf/bot-footprint.ts b/server/perf/bot-footprint.ts
index 1547d8b723..962106c823 100644
--- a/server/perf/bot-footprint.ts
+++ b/server/perf/bot-footprint.ts
@@ -126,8 +126,8 @@ const MAX_PEAKS = 1_000;
export interface BotFootprintsOptions {
owners: () => readonly FootprintOwner[];
- /** After each sample: the process groups and sessions the list shows, so records of exited engines can go. */
- prune?: (inUse: ReadonlySet<number>) => void;
+ /** After each sample, with its list: records of exited engines that list no longer needs can go (engine-owners.ts). */
+ prune?: (rows: readonly ProcessRow[]) => void;
now?: () => number;
}
@@ -151,11 +151,7 @@ export function createBotFootprints(options: BotFootprintsOptions) {
while (peaks.size > MAX_PEAKS) peaks.delete(peaks.keys().next().value!);
latest = { at, windowMs: previous ? Math.max(1, at - previous.at) : null, attribution };
previous = { at, rows: new Map(rows.map((row) => [row.pid, { start: row.start, cpuMs: row.cpuMs }])) };
- if (options.prune) {
- const inUse = new Set<number>();
- for (const row of rows) { inUse.add(row.pid); if (row.pgid !== undefined) inUse.add(row.pgid); if (row.sid !== undefined) inUse.add(row.sid); }
- options.prune(inUse);
- }
+ options.prune?.(rows);
return attribution;
},
/** The last sample's tallies. */
diff --git a/server/perf/perf-host.ts b/server/perf/perf-host.ts
index 4fcaa7e061..0c96378d95 100644
--- a/server/perf/perf-host.ts
+++ b/server/perf/perf-host.ts
@@ -9,6 +9,7 @@ import { createLoopStalls, requestArrivedBefore, type LoopStalls } from "./loop-
import { createBotFootprints, type BotFootprintReport, type BotFootprints, type FootprintOwner } from "./bot-footprint.ts";
import { duration, limitHolds, perfHealth, perfLines, turnLine, type PerfHealth } from "./perf-report.ts";
import { createProcessHealth, type ProcessHealthRecorder } from "./process-health.ts";
+import type { ProcessRow } from "./process-buckets.ts";
import { createProcessSampler, linuxProcessList, LINUX_SAMPLE_MS, nodeUtilization, OTHER_SAMPLE_MS, psProcessList, type ProcessSampler } from "./process-sampler.ts";
import type { FailoverWhy } from "./turn-record.ts";
import { createTurnTimings, type Refusal, type SlowNote, type TurnTimings } from "./turn-timings.ts";
@@ -39,8 +40,8 @@ export interface PerfHostDeps {
engines?: () => ReadonlyArray<{ pid: number; threads: readonly string[] }>;
/** The engine and browser processes the server started for bots, with the bots each serves (bot-footprint.ts). */
owners?: () => readonly FootprintOwner[];
- /** After each sample: the process groups and sessions still in use, so records of exited engines can go. */
- pruneOwners?: (inUse: ReadonlySet<number>) => void;
+ /** After each sample, with its process list: records of exited engines it no longer needs can go. */
+ pruneOwners?: (rows: readonly ProcessRow[]) => void;
}
/** The health report shows this many bots, the ones using the most memory first; the admin's read shows every one. */