Skip to content

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

Footprint: a group's room and another bot's turn make an engine shared; an exited engine's pid names nothing; a browser on the person's own Chrome is not a bot's

milind-soni00f765a4fe67
diff --git a/server/host/bot-footprint-owners.ts b/server/host/bot-footprint-owners.ts
index 7ac4bbfbcb..0bdd808714 100644
--- a/server/host/bot-footprint-owners.ts
+++ b/server/host/bot-footprint-owners.ts
@@ -3,15 +3,20 @@
import { engineOwners as allEngineOwners, type EngineOwners } from "../engine-owners.ts";
import type { FootprintOwner } from "../perf/bot-footprint.ts";
-/** Where a conversation's bot can't be told (deleted since, a group's), its engine counts as shared: never one bot's. */
+/** Where a conversation's bot can't be told (deleted since, a group's: several bots take turns in one), its engine counts
+ * as shared: never one bot's. */
const UNKNOWN = "?";
export function footprintOwners(deps: { botOf: (threadId: string) => string | null; browsers: () => readonly FootprintOwner[]; engines?: Pick<EngineOwners, "list"> }): () => FootprintOwner[] {
const engines = deps.engines ?? allEngineOwners;
return () => [
...engines.list().map((engine): FootprintOwner => ({
- pid: engine.pid, start: engine.start, kind: "engine",
- botIds: [...engine.threads].map(([threadId, botId]) => botId || deps.botOf(threadId) || UNKNOWN),
+ pid: engine.pid, start: engine.start, kind: "engine", ...(engine.exited ? { exited: true } : {}),
+ // The conversation's own bot, as the store says; a turn of another bot in it (a group's room) makes it shared.
+ botIds: [...engine.threads].flatMap(([threadId, turnBot]) => {
+ const owner = deps.botOf(threadId) ?? UNKNOWN;
+ return turnBot && turnBot !== owner ? [owner, turnBot] : [owner];
+ }),
})),
...deps.browsers(),
];
diff --git a/server/host/browser.ts b/server/host/browser.ts
index bbcebf13eb..b097a9bf5e 100644
--- a/server/host/browser.ts
+++ b/server/host/browser.ts
@@ -472,7 +472,8 @@ export function createBrowserHost(deps: BrowserHostDeps) {
* 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" }> {
return [...usedBrowserSessions].flatMap(([session, spec]) => {
- if (chromeTarget(session, spec)) return [];
+ // 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 [];
diff --git a/server/perf/bot-footprint.test.ts b/server/perf/bot-footprint.test.ts
index f308617342..f7b8e8649e 100644
--- a/server/perf/bot-footprint.test.ts
+++ b/server/perf/bot-footprint.test.ts
@@ -2,6 +2,7 @@ import { EventEmitter } from "node:events";
import { describe, expect, it } from "vitest";
import { runInTurn } from "../crash-guard.ts";
+import { requiredScope, serviceAllowed } from "../request-auth.ts";
import { EngineOwners } from "../engine-owners.ts";
import { footprintOwners } from "../host/bot-footprint-owners.ts";
import { BOT_FOOTPRINT_PATH, createPerfDiagnosticsRoutes } from "../routes/perf-diagnostics.ts";
@@ -153,18 +154,39 @@ describe("which bot an engine runs for", () => {
expect(owners.list()[0]?.threads.size).toBe(0);
});
- it("names a conversation's bot from the store, and an engine with a conversation of no known bot is shared", () => {
+ it("names a conversation's bot from the store; a group's room, a turn of another bot, or no known bot makes it shared", () => {
const owners = new EngineOwners();
const child = Object.assign(new EventEmitter(), { pid: 10 });
owners.track(child, null);
owners.attach(child, "thread_known");
const browsers: FootprintOwner[] = [{ pid: 11, botIds: ["bot_z"], kind: "browser" }];
- const list = footprintOwners({ botOf: (threadId) => (threadId === "thread_known" ? "bot_k" : null), browsers: () => browsers, engines: owners });
+ const botOf = (threadId: string) => (threadId === "thread_known" || threadId === "thread_k2" ? "bot_k" : null);
+ const list = footprintOwners({ botOf, browsers: () => browsers, engines: owners });
expect(list()).toEqual([{ pid: 10, start: null, kind: "engine", botIds: ["bot_k"] }, browsers[0]]);
owners.attach(child, "thread_gone");
expect(list()[0]?.botIds).toEqual(["bot_k", "?"]);
const rows: ProcessRow[] = [{ pid: 10, ppid: 1, name: "opencode", cpuMs: 0, rssBytes: MB, start: "s" }];
expect(attributeRows(rows, list()).bots.size).toBe(0);
+ // A group's room: several bots take turns in one conversation, which belongs to no bot.
+ const room = new EngineOwners();
+ runInTurn({ botId: "bot_k", threadId: "group_thread" }, () => room.track(Object.assign(new EventEmitter(), { pid: 20 }), null));
+ expect(footprintOwners({ botOf, browsers: () => [], engines: room })()[0]?.botIds).toEqual(["?", "bot_k"]);
+ // A turn of another bot in a bot's own conversation.
+ const visit = new EngineOwners();
+ runInTurn({ botId: "bot_v", threadId: "thread_k2" }, () => visit.track(Object.assign(new EventEmitter(), { pid: 30 }), null));
+ const visited = footprintOwners({ botOf, browsers: () => [], engines: visit })();
+ expect(visited[0]?.botIds).toEqual(["bot_k", "bot_v"]);
+ expect(attributeRows([{ pid: 30, ppid: 1, name: "claude", cpuMs: 0, rssBytes: MB, start: "s" }], visited).shared.procs).toBe(1);
+ });
+
+ 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 },
+ { pid: 201, ppid: 1, name: "sleep", cpuMs: 0, rssBytes: MB, start: "ps:201", pgid: 777 },
+ ];
+ const { bots } = attributeRows(rows, [{ pid: 200, botIds: ["bot_a"], kind: "engine", exited: true }, { pid: 777, botIds: ["bot_a"], kind: "engine", exited: true }]);
+ expect(bots.get("bot_a")?.pids).toEqual([201]);
+ expect(bots.get("bot_a")?.engines).toBe(0);
});
});
@@ -190,6 +212,9 @@ describe("where the footprint shows", () => {
const route = createPerfDiagnosticsRoutes({ text: () => "", bots: () => footprints.report() });
const sent: unknown[] = [];
const context = (path: string, method = "GET") => ({ path, method, res: { setHeader: () => undefined }, json: (_res: unknown, status: number, body: unknown) => { sent.push({ status, body }); } }) as unknown as RouteContext;
+ // Admin only: never a client session, never a bot's shell on service-trust loopback.
+ expect(requiredScope("GET", BOT_FOOTPRINT_PATH)).toBe("admin");
+ expect(serviceAllowed("GET", BOT_FOOTPRINT_PATH)).toBe(false);
expect(await route(context(BOT_FOOTPRINT_PATH, "POST"))).toBe(PASS);
await route(context(BOT_FOOTPRINT_PATH));
expect(sent).toEqual([{ status: 200, body: { bots: footprints.report() } }]);
diff --git a/server/perf/bot-footprint.ts b/server/perf/bot-footprint.ts
index aa3ba54fa5..1547d8b723 100644
--- a/server/perf/bot-footprint.ts
+++ b/server/perf/bot-footprint.ts
@@ -15,6 +15,8 @@ export interface FootprintOwner {
/** The bots it serves now. One: that bot's. More, none, or one that is not a bot id: shared. */
botIds: readonly string[];
kind: "engine" | "browser";
+ /** It has exited: its pid may be another process's now, but its group and session still name what it left. */
+ exited?: boolean;
}
export interface BotTally {
@@ -47,6 +49,8 @@ export function attributeRows(rows: readonly ProcessRow[], owners: readonly Foot
// A leader the list shows with another start is another process now; one the list no longer shows (an engine that
// exited) still names its group and session: the system gives no new process a number that still names one.
const roots = new Map<number, { label: string; kind: FootprintOwner["kind"] }>();
+ /** Leaders still running as themselves: only these name the process with their pid; the others name groups and sessions. */
+ const live = new Set<number>();
for (const owner of owners) {
const row = byPid.get(owner.pid);
if (row && owner.start && row.start !== owner.start) continue;
@@ -55,6 +59,7 @@ export function attributeRows(rows: readonly ProcessRow[], owners: readonly Foot
const known = roots.get(owner.pid);
// Two records of one pid disagreeing about its bot: shared, never either bot's.
roots.set(owner.pid, { label: known && known.label !== label ? SHARED : label, kind: owner.kind });
+ if (!owner.exited) live.add(owner.pid);
}
const labels = new Map<number, string | null>();
const labelOf = (row: ProcessRow, depth: number): string | null => {
@@ -63,7 +68,7 @@ export function attributeRows(rows: readonly ProcessRow[], owners: readonly Foot
labels.set(row.pid, null);
// Its own record first, then the nearest recorded ancestor, then (for what outlived its parent and was adopted by an
// init) the session and group it still runs in.
- let label: string | null = roots.get(row.pid)?.label ?? null;
+ let label: string | null = live.has(row.pid) ? roots.get(row.pid)?.label ?? null : null;
if (label === null && row.ppid !== row.pid && depth < 64) {
const parent = byPid.get(row.ppid);
if (parent) label = labelOf(parent, depth + 1);
@@ -85,7 +90,7 @@ export function attributeRows(rows: readonly ProcessRow[], owners: readonly Foot
const before = previous?.get(row.pid);
if (previous) tally.cpuDeltaMs += before && before.start === row.start && row.cpuMs >= before.cpuMs ? row.cpuMs - before.cpuMs : row.cpuMs;
tally.pids.push(row.pid);
- const root = roots.get(row.pid);
+ const root = live.has(row.pid) ? roots.get(row.pid) : undefined;
if (root?.kind === "engine") tally.engines += 1;
else if (root?.kind === "browser") tally.browsers += 1;
}