Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Per-bot footprint in the health report
milind-soni363025281128
diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 56f7815adf..9415fac6a0 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -579,6 +579,16 @@ never came up, and processes that had to be force-stopped or outlived theirturn. It holds numbers and fixed words only: no command line, path, bot nameor message.+**Per bot.** The same report carries each bot's share, taken from the same+process list (no extra work per bot): its processes, threads, resident memory+(now and at its most since start) and CPU time, counting its engine, what the+engine started (including what outlived its turn in the engine's process group+or session) and its own browser. An engine or browser several bots share (a+shared engine process, a browser profile used by more than one bot) is counted+once as "shared", never against any one bot. The report shows the ten bots+using the most memory; `GET /api/diagnostics/bots` (admin only) lists every+bot. Bot ids and numbers only.+**Bots' cloud computers do not count.** A bot's cloud computer runs at theprovider that hosts it, not in this container, so its desktop and browseruse none of the container's processes or memory. Only the built-in browserdiff --git a/server/drivers/acp/host.ts b/server/drivers/acp/host.tsindex d468573e63..f1d22377dd 100644--- a/server/drivers/acp/host.ts+++ b/server/drivers/acp/host.ts@@ -4,6 +4,7 @@import type { ChildProcessWithoutNullStreams } from "node:child_process";import { engineMemory } from "../../engine-memory.ts";+import { engineOwners } from "../../engine-owners.ts";import { appendNative } from "../native.ts";import { StderrTail } from "./exit-report.ts";import { acpRpcError } from "./rpc-error.ts";@@ -182,13 +183,14 @@ export class AcpHost {this.links.add(link);this.opened += 1;engineMemory.attach(this.child, threadId);+ engineOwners.attach(this.child, threadId);return link;}unlink(link: AcpLink): void {if (!this.links.delete(link)) return;if (!this.links.size) this.#lastOut = link;- if (![...this.links].some((other) => other.threadId === link.threadId)) engineMemory.detach(this.child, link.threadId);+ if (![...this.links].some((other) => other.threadId === link.threadId)) { engineMemory.detach(this.child, link.threadId); engineOwners.detach(this.child, link.threadId); }}#listening(): AcpLink[] {diff --git a/server/engine-owners.ts b/server/engine-owners.tsnew file mode 100644index 0000000000..25a453cb45--- /dev/null+++ b/server/engine-owners.ts@@ -0,0 +1,60 @@+// Which bot each engine process runs for, on every host. engine-memory.ts tracks engines only where turns wait for room;+// this record is kept everywhere so the per-bot footprint (perf/bot-footprint.ts) can name a bot's processes on the+// desktop and on a server without limits too. An engine is recorded when spawnCli starts it inside a turn (the turn's+// scope, crash-guard.ts, names the bot and conversation), and a shared engine process (ACP's) gains and loses+// conversations as their sessions attach and detach. An engine that exits stays on record while anything it started still+// runs in its process group or session, so what outlived its turn is still counted against its bot.+import { currentTurn } from "./crash-guard.ts";++/** One engine process: the conversations it serves now (conversation id to bot id, "" where the turn named none). */+export interface EngineOwner {+ pid: number;+ /** Its start time as the process list shows it (Linux's start tick), where read at spawn: a reused pid is not it. */+ start: string | null;+ threads: ReadonlyMap<string, string>;+ exited: boolean;+}++const MAX_ENTRIES = 4_096;++interface Entry { pid: number; start: string | null; threads: Map<string, string>; exited: boolean }++export class EngineOwners {+ readonly #entries = new Map<number, Entry>();++ /** An engine process spawnCli just started for a bot. Outside a turn (a keep-warm ping, a probe) it serves no+ * conversation yet: it counts as shared until one attaches. */+ track(child: { pid?: number; once(event: "exit", listener: () => void): unknown }, start: string | null): void {+ 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 };+ 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); }+ child.once("exit", () => { if (this.#entries.get(pid) === entry) entry.exited = true; });+ }++ /** A conversation's session now runs in this engine process too (a shared ACP process). */+ attach(child: { pid?: number }, threadId: string): void {+ const entry = child.pid ? this.#entries.get(child.pid) : undefined;+ if (!entry || entry.threads.has(threadId)) return;+ const turn = currentTurn();+ entry.threads.set(threadId, turn?.threadId === threadId ? turn.botId ?? "" : "");+ }++ detach(child: { pid?: number }, threadId: string): void {+ if (child.pid) this.#entries.get(child.pid)?.threads.delete(threadId);+ }++ list(): EngineOwner[] {+ 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);+ }+}++export const engineOwners = new EngineOwners();diff --git a/server/host/bot-footprint-owners.ts b/server/host/bot-footprint-owners.tsnew file mode 100644index 0000000000..7ac4bbfbcb--- /dev/null+++ b/server/host/bot-footprint-owners.ts@@ -0,0 +1,18 @@+// The processes the per-bot footprint (perf/bot-footprint.ts) counts from: every engine spawnCli started for a bot+// (engine-owners.ts) and every running agent-browser daemon (host/browser.ts), each with the bots it serves now.+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. */+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),+ })),+ ...deps.browsers(),+ ];+}diff --git a/server/host/browser.ts b/server/host/browser.tsindex 23525206ea..bbcebf13eb 100644--- a/server/host/browser.ts+++ b/server/host/browser.ts@@ -1,7 +1,7 @@// The bots' browser as the server hosts it: the engine's runtime and live view, which session a bot's browser is, and// the integration a turn mounts. browserEngine.engine picks agent-browser (the default) or the new Chrome engine; a// person's own Chrome (My Chrome) stays on agent-browser either way.-import { existsSync } from "node:fs";+import { existsSync, readFileSync } from "node:fs";import { join } from "node:path";import { setTimeout as sleep } from "node:timers/promises";@@ -468,6 +468,18 @@ 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"));}+ /** 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" }> {+ return [...usedBrowserSessions].flatMap(([session, spec]) => {+ if (chromeTarget(session, spec)) 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 [];+ const botIds = store.bots.filter((bot) => browserSessionsOf(bot.id, bot.browserProfile).includes(session)).map((bot) => bot.id);+ return [{ pid, 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. */function threadBrowser(threadId: string): { session: string | undefined; spec: Spec | undefined } | null {const bot = store.botByThread(threadId);@@ -604,6 +616,6 @@ export function createBrowserHost(deps: BrowserHostDeps) {currentBrowserSession, forgetTemporaryBrowser, myChromeAvailable, lentChromeSummary, usesMyChrome, browserSessionSpec, browserIntegration,browserReady, currentBrowserSpec, loginInput, browserSystemPrompt, signedInSitesRefusal, closeBrowser, browserEngineSwitched,eraseDeletedBrowser, engineSummary, engineBrowsers, browserAudience, browserSessionsOf, signedInSitesTarget, uploadPaths,- eraseAudienceBrowsers,+ eraseAudienceBrowsers, browserOwners,};}diff --git a/server/index.ts b/server/index.tsindex ac2e5ef3e7..3f9c195cbc 100644--- a/server/index.ts+++ b/server/index.ts@@ -642,7 +642,7 @@ import { createPersonReplies } from "./person-replies.ts";import { lendingPerson, lendingPersonKey, personKey, relayedPersonKey } from "./person-key.ts";import { createOutsideLineage, OUTSIDE_STAYS_HERE } from "./host/outside-lineage.ts"; import { OUTSIDE_REFUSAL, outsideRouteRefused } from "./host/outside-fence.ts"; import { createOutsideWrites } from "./host/outside-writes.ts";import { teamAiOwner } from "./host/team-ai-owner.ts"; import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { createTeamAwayHost } from "./host/team-away-host.ts"; import { createPlaceInbox, guestNameIn, placeInboxViewer } from "./host/place-inbox.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";-import { createDevsReports } from "./host/devs-reports.ts"; import { createSettingNudges } from "./host/setting-nudges.ts"; import { createPerfHost } from "./perf/perf-host.ts"; import { createPerfDiagnosticsRoutes } from "./routes/perf-diagnostics.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";+import { createDevsReports } from "./host/devs-reports.ts"; import { createSettingNudges } from "./host/setting-nudges.ts"; import { createPerfHost } from "./perf/perf-host.ts"; import { footprintOwners } from "./host/bot-footprint-owners.ts"; import { engineOwners } from "./engine-owners.ts"; import { createPerfDiagnosticsRoutes } from "./routes/perf-diagnostics.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";import { createCardRequester, linePersonKey } from "./host/thread-person.ts"; import { selfThreadRefusal } from "./host/self-threads.ts"; import { lookedAfterBy } from "./host/looked-after.ts"; import { createActingPeople, HANDED_PEOPLE_FILE, HandedPeople, type HandedRun, keptPrivate, privateHandBack, withPerson } from "./host/acting-person.ts"; import { createTurnCallSignals } from "./host/turn-call-signals.ts";import { createThreadRoutes } from "./routes/threads.ts";import { createWebhookRoutes } from "./routes/webhooks.ts";@@ -2377,7 +2377,7 @@ function cancelDirectTurnDispatch(botId: string, expectedThreadId?: string): Dirconst {browserRuntime, browserLive, usedBrowserSessions, browserSweep, temporaryBrowserSessions,currentBrowserSession, forgetTemporaryBrowser, myChromeAvailable, usesMyChrome, lentChromeSummary, browserSessionSpec, browserIntegration,- browserReady, currentBrowserSpec, loginInput, browserSystemPrompt, closeBrowser, browserEngineSwitched, eraseDeletedBrowser, engineSummary, browserSessionsOf, signedInSitesTarget, uploadPaths, eraseAudienceBrowsers,+ browserReady, currentBrowserSpec, loginInput, browserSystemPrompt, closeBrowser, browserEngineSwitched, eraseDeletedBrowser, engineSummary, browserSessionsOf, signedInSitesTarget, uploadPaths, eraseAudienceBrowsers, browserOwners,} = createBrowserHost({ cfg, language: appLanguage, store: () => store, turnResources, activeInternalGenerationByThread, mintInternalCapability, DESKTOP_MANAGED, CLOUD_HOME, HOSTED_WORKSPACE, PORT, engineMemory, audienceOf: teamHost.browserAudience, ...(CLOUD_TEAM ? { browserBox: (fd: number, ro: readonly string[]) => botBox.browserBox(fd, ro) } : {}), lendRefusal: (turn) => cloudLendingRefusal({ botId: store.botByThread(turn.threadId)?.id ?? "", threadId: turn.threadId, generation: turn.generation }), device: () => deviceLinks.route(CLOUD_HOME_LENDER) ?? sharedComputers.internetAway(CLOUD_HOME_LENDER) ?? { unshared: true as const }, lentChrome: CLOUD_PERSONAL ? { route: () => deviceLinks.chromeRoute(CLOUD_HOME_LENDER), lender: () => sharedComputers.chromeLender(CLOUD_HOME_LENDER) } : undefined });const dataSheets = new DataSheetRegistry({@@ -2789,7 +2789,7 @@ const { stopThreadForPerson, stopOnTypedCommand, restartForPerson } = createPersconst 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(), 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: (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 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) });@@ -9450,7 +9450,7 @@ const appTriggers = createAppTriggerHost({ store, webhooks, webhookBase: () => waudit: (row) => appendDecision(DATA_DIR, { ...row, decision: "auto-approved", source: "routine" }) });tieAutomationsToBots(store, { routines: routines!, webhooks, apps: appTriggers.manager, waits: botWaits });ROUTES.push(appTriggers.routes); ROUTES.unshift(createMoveFreezeRoutes({ freeze: moveFreeze, automationsOff: () => switchAutomationsOff({ routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }), restart: () => { restartRequested = true; gracefulShutdown(); }, busy: createMoveWaits({ bots: () => store.bots, rooms: () => store.groups, answering: (id) => watchdog.answering(id), turn: botHasActiveTurn, runs: () => routines?.listRuns() ?? [], roomWorking: (id) => { const group = store.group(id); return Boolean(group && groupIsWorking(group)); }, handoffs: () => coordinator.active(), exists: (node) => !(!node.parentId && node.groupId ? roomRootProblem(node) : roomHandoffProblem(node)), signingIn: () => providerAuthSessions.active }) }));-ROUTES.push(createPerfDiagnosticsRoutes({ text: perf.text })); ROUTES.push(createLimitResetRoutes({ clock: limitClock, routines: routines!, requests: routineRequests, engineName, threadEngine: (botId, threadId) => turnSelection(botId, threadId)?.instanceId,+ROUTES.push(createPerfDiagnosticsRoutes({ text: perf.text, bots: perf.bots })); ROUTES.push(createLimitResetRoutes({ clock: limitClock, routines: routines!, requests: routineRequests, engineName, threadEngine: (botId, threadId) => turnSelection(botId, threadId)?.instanceId,threadTitle: (botId, threadId) => store.bot(botId) && !store.bot(botId)!.hidden ? store.taskByThread(botId, threadId)?.title ?? null : null,created: (id, auth) => cloudRoutineAuthors?.wrote(id, auth.kind === "session" ? actorKey(auth) : CLOUD_NOBODY_KEY) }));diff --git a/server/perf/bot-footprint.test.ts b/server/perf/bot-footprint.test.tsnew file mode 100644index 0000000000..f308617342--- /dev/null+++ b/server/perf/bot-footprint.test.ts@@ -0,0 +1,197 @@+import { EventEmitter } from "node:events";+import { describe, expect, it } from "vitest";++import { runInTurn } from "../crash-guard.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";+import { PASS, type RouteContext } from "../routes/table.ts";+import { attributeRows, botFootprintLines, createBotFootprints, type FootprintOwner } from "./bot-footprint.ts";+import { parsePsLine, type ProcessRow } from "./process-buckets.ts";+import { linuxProcessList } from "./process-sampler.ts";+import { perfHealth, PERF_HEALTH_MAX_BYTES } from "./perf-report.ts";+import { createTurnTimings } from "./turn-timings.ts";++const MB = 1_048_576;+const PAGE = 4096;++/** /proc/<pid>/stat as the kernel writes it: state, ppid, pgrp, session, …, utime, stime, …, threads, …, starttime, vsize, rss. */+const stat = (pid: number, comm: string, ppid: number, { pgid = pid, sid = pid, cpuTicks = 0, threads = 1, start = 1000 + pid, rssMB = 10, state = "S" } = {}) =>+ `${pid} (${comm}) ${state} ${ppid} ${pgid} ${sid} 0 -1 4194304 100 0 0 0 ${cpuTicks} 0 0 0 20 0 ${threads} 0 ${start} 1000000 ${(rssMB * MB) / PAGE} 18446744073709551615`;++/** A fake /proc: what linuxProcessList reads, and only that (no real /proc on a Mac or Windows test run). */+function fakeProc(lines: Record<number, string>) {+ const files: Record<string, string> = Object.fromEntries(Object.entries(lines).map(([pid, line]) => [`/proc/${pid}/stat`, line]));+ return linuxProcessList((path) => files[path] ?? null, () => Object.keys(lines)).rows;+}++const SERVER = 100;+/** Bot A: engine 200 (a tool server 201, a shell 202 whose background child 203 was adopted by init when the shell exited)+ * and its browser's daemon 500 (a session of its own) with Chrome 501–502. Bot B: engine 300 with a tool server 301.+ * A shared ACP process 400 serving A and B, with a tool server 401; a profile browser 600 that A and B both use, with+ * Chrome 601. The server, init and an unrelated process 900 belong to no bot. */+function server() {+ return fakeProc({+ 1: stat(1, "tini", 0, { pgid: 1, sid: 1 }),+ [SERVER]: stat(SERVER, "node", 1, { pgid: 1, sid: 1, rssMB: 200, threads: 11 }),+ 200: stat(200, "claude", SERVER, { rssMB: 300, threads: 12, cpuTicks: 500 }),+ 201: stat(201, "node", 200, { pgid: 200, sid: 200, rssMB: 50, threads: 7 }),+ 202: stat(202, "bash", 200, { pgid: 200, sid: 200, rssMB: 4 }),+ 203: stat(203, "sleep", 1, { pgid: 200, sid: 200, rssMB: 1 }),+ 300: stat(300, "codex", SERVER, { rssMB: 120, threads: 20, cpuTicks: 100 }),+ 301: stat(301, "node", 300, { pgid: 300, sid: 300, rssMB: 40, threads: 7 }),+ 400: stat(400, "opencode", SERVER, { rssMB: 400, threads: 30 }),+ 401: stat(401, "node", 400, { pgid: 400, sid: 400, rssMB: 30 }),+ 500: stat(500, "agent-browser", 1, { rssMB: 20, threads: 5 }),+ 501: stat(501, "chrome", 500, { pgid: 500, sid: 500, rssMB: 200, threads: 40 }),+ 502: stat(502, "chrome", 501, { pgid: 500, sid: 500, rssMB: 100, threads: 20 }),+ 600: stat(600, "agent-browser", 1, { rssMB: 20 }),+ 601: stat(601, "chrome", 600, { pgid: 600, sid: 600, rssMB: 250 }),+ 900: stat(900, "postgres", 1, { rssMB: 500 }),+ });+}+const OWNERS: FootprintOwner[] = [+ { pid: 200, start: "1200", botIds: ["bot_a"], kind: "engine" },+ { pid: 300, start: "1300", botIds: ["bot_b"], kind: "engine" },+ { pid: 400, start: "1400", botIds: ["bot_a", "bot_b"], kind: "engine" },+ { pid: 500, botIds: ["bot_a"], kind: "browser" },+ { pid: 600, botIds: ["bot_a", "bot_b"], kind: "browser" },+];++describe("a bot's footprint, from a process list", () => {+ it("counts each bot's engine tree, what outlived its parent in the engine's session, and its own browser", () => {+ const { bots, shared } = attributeRows(server(), OWNERS);+ expect(Object.fromEntries([...bots].map(([id, tally]) => [id, { procs: tally.procs, threads: tally.threads, mb: tally.rssBytes / MB, engines: tally.engines, browsers: tally.browsers, pids: tally.pids.sort((a, b) => a - b) }]))).toEqual({+ bot_a: { procs: 7, threads: 12 + 7 + 1 + 1 + 5 + 40 + 20, mb: 300 + 50 + 4 + 1 + 20 + 200 + 100, engines: 1, browsers: 1, pids: [200, 201, 202, 203, 500, 501, 502] },+ bot_b: { procs: 2, threads: 27, mb: 160, engines: 1, browsers: 0, pids: [300, 301] },+ });+ // A process that serves both bots is neither bot's.+ expect(shared).toMatchObject({ procs: 4, rssBytes: (400 + 30 + 20 + 250) * MB, engines: 1, browsers: 1 });+ expect(shared.pids.sort((a, b) => a - b)).toEqual([400, 401, 600, 601]);+ });++ it("never counts another bot's processes: a shared or unknown record makes its tree shared, and a reused pid is no one's", () => {+ const rows = server();+ // Engine 300's pid now belongs to a process that started later: not bot B's engine any more.+ const reused = attributeRows(rows, [{ pid: 300, start: "999", botIds: ["bot_b"], kind: "engine" }]);+ expect(reused.bots.size).toBe(0);+ expect(reused.shared.procs).toBe(0);+ // Two records of one pid naming different bots, or one naming something that is not a bot id: shared.+ const twice = attributeRows(rows, [{ pid: 200, botIds: ["bot_a"], kind: "engine" }, { pid: 200, botIds: ["bot_b"], kind: "engine" }]);+ expect(twice.bots.size).toBe(0);+ expect(twice.shared.procs).toBe(4);+ expect(attributeRows(rows, [{ pid: 300, botIds: ["?"], kind: "engine" }]).bots.size).toBe(0);+ expect(attributeRows(rows, [{ pid: 300, botIds: [], kind: "engine" }]).shared.procs).toBe(2);+ });++ it("still counts what an engine left in its session after the engine itself exited", () => {+ const rows = server().filter((row) => row.pid !== 200);+ const { bots } = attributeRows(rows, OWNERS);+ // 201 and 202 lost their parent too; all three still run in engine 200's session.+ expect(bots.get("bot_a")?.pids.filter((pid) => pid < 500).sort((a, b) => a - b)).toEqual([201, 202, 203]);+ expect(bots.get("bot_a")?.engines).toBe(0);+ });++ it("works from macOS's ps list: groups, no sessions, no thread counts", () => {+ const rows = [+ " 100 1 100 204800 0:01.00 /usr/local/bin/node",+ " 200 100 200 307200 0:05.00 /usr/local/bin/claude",+ " 201 200 200 51200 0:00.50 /usr/local/bin/node",+ " 203 1 200 1024 0:00.00 /bin/sleep",+ " 900 1 900 512000 0:09.00 /usr/local/bin/postgres",+ ].map((line) => parsePsLine(line)!);+ const { bots } = attributeRows(rows, [{ pid: 200, botIds: ["bot_a"], kind: "engine" }]);+ expect(bots.get("bot_a")).toMatchObject({ procs: 3, threads: null, rssBytes: (300 + 50 + 1) * MB, cpuMs: 5_500 });+ });++ it("reports memory first, with each bot's most and its share of a core since the previous sample", () => {+ let clock = 1_800_000_000_000;+ let rows = server();+ const footprints = createBotFootprints({ owners: () => OWNERS, now: () => clock });+ expect(footprints.report().at).toBeNull();+ expect(botFootprintLines(footprints.report())).toEqual(["Per bot: not sampled yet"]);+ footprints.sample(rows);+ clock += 60_000;+ // A minute later: bot B's engine used 30 s of CPU, and bot A's browser closed.+ rows = rows.filter((row) => row.pid < 500 || row.pid >= 600).map((row) => (row.pid === 300 ? { ...row, cpuMs: row.cpuMs + 30_000 } : row));+ footprints.sample(rows);+ const report = footprints.report();+ expect(report).toMatchObject({ at: clock, bots: 2, shown: [+ { id: "bot_a", procs: 4, rssMB: 355, peakMB: 675, cpuPct: 0, engines: 1, browsers: 0 },+ { id: "bot_b", procs: 2, rssMB: 160, peakMB: 160, cpuS: 31, cpuPct: 50 },+ ], shared: { procs: 4, rssMB: 700 } });+ expect(footprints.report(1).shown.map((row) => row.id)).toEqual(["bot_a"]);+ expect(botFootprintLines(report)[0]).toMatch(/^Per bot \(2 with processes running; most memory first\): bot bot_a 4 processes, 21 threads, 355 MB \(most 675 MB\)/);+ });++ 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)) });+ footprints.sample(server());+ expect(pruned).toEqual([[200]]);+ });+});++describe("which bot an engine runs for", () => {+ it("records the turn's bot at spawn, conversations that attach and detach, and keeps an exited engine until pruned", () => {+ const owners = new EngineOwners();+ const child = Object.assign(new EventEmitter(), { pid: 4242 });+ runInTurn({ botId: "bot_a", threadId: "thread_1" }, () => owners.track(child, "777"));+ expect(owners.list()).toEqual([{ pid: 4242, start: "777", threads: new Map([["thread_1", "bot_a"]]), exited: false }]);+ runInTurn({ botId: "bot_b", threadId: "thread_2" }, () => owners.attach(child, "thread_2"));+ owners.attach(child, "thread_3");+ expect([...owners.list()[0]!.threads]).toEqual([["thread_1", "bot_a"], ["thread_2", "bot_b"], ["thread_3", ""]]);+ owners.detach(child, "thread_2");+ child.emit("exit", 0, null);+ expect(owners.list()[0]).toMatchObject({ exited: true });+ owners.prune(new Set([4242]));+ expect(owners.list()).toHaveLength(1);+ owners.prune(new Set([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);+ 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", () => {+ 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 });+ 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);+ });+});++describe("where the footprint shows", () => {+ it("rides in the health report's perf part (ids and numbers only) and shrinks before anything else is dropped", () => {+ const timings = createTurnTimings({ now: () => 1_800_000_000_000 });+ const footprints = createBotFootprints({ owners: () => OWNERS });+ footprints.sample(server());+ const body = perfHealth({ hour: timings.window(), day: timings.day(), live: timings.live(), limits: null, process: null, bots: footprints.report(10) });+ expect(body.bots?.shown.map((row) => Object.keys(row).sort())).toEqual([+ ["browsers", "cpuPct", "cpuS", "engines", "id", "peakMB", "procs", "rssMB", "threads"], ["browsers", "cpuPct", "cpuS", "engines", "id", "peakMB", "procs", "rssMB", "threads"]]);+ expect(JSON.stringify(body.bots)).not.toMatch(/claude|codex|chrome|postgres|node/);+ const many = { at: 1, bots: 100, shared: { procs: 1, threads: 1, rssMB: 1, cpuS: 1, cpuPct: 1, engines: 1, browsers: 1 },+ shown: Array.from({ length: 200 }, (_, index) => ({ id: `bot_${"x".repeat(56)}${index}`, procs: 999, threads: 9999, rssMB: 99999, peakMB: 99999, cpuS: 99999.9, cpuPct: 100, engines: 9, browsers: 1 })) };+ const trimmed = perfHealth({ hour: timings.window(), day: timings.day(), live: timings.live(), limits: null, process: null, bots: many });+ expect(JSON.stringify(trimmed).length).toBeLessThanOrEqual(PERF_HEALTH_MAX_BYTES);+ expect(trimmed.bots?.shown).toHaveLength(3);+ });++ it("answers GET /api/diagnostics/bots with every bot, and passes other requests on", async () => {+ const footprints = createBotFootprints({ owners: () => OWNERS });+ footprints.sample(server());+ 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;+ 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.tsnew file mode 100644index 0000000000..aa3ba54fa5--- /dev/null+++ b/server/perf/bot-footprint.ts@@ -0,0 +1,188 @@+// Each bot's footprint: the processes, threads, resident memory and CPU time of its engine processes and its browser, from+// the process sampler's own list (no read or spawn of its own). A process is a bot's when it is, or descends from, or+// (once its parent has gone) still runs in the process group or session of, an engine or browser process that only that+// bot uses. An engine or browser that+// serves several bots (a shared ACP process, a browser profile several bots use) is "shared" and never counted against+// any one of them; nothing is ever attributed by a process's name. Privacy invariant: bot ids and numbers only.+import { ID } from "./turn-record.ts";+import type { ProcessRow } from "./process-buckets.ts";++/** A process the server started for bots: an engine (spawnCli) or a browser's daemon (its session's pid file). */+export interface FootprintOwner {+ pid: number;+ /** The start the process list shows for it, where known: a pid the system gave to another process since is not it. */+ start?: string | null;+ /** 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";+}++export interface BotTally {+ procs: number;+ /** Null where the process list carries no thread counts (macOS's `ps`). */+ threads: number | null;+ rssBytes: number;+ /** CPU time so far of its processes running now, ms. */+ cpuMs: number;+ /** CPU used since the previous sample by its processes, ms. */+ cpuDeltaMs: number;+ engines: number;+ browsers: number;+ pids: number[];+}++export interface Attribution {+ /** By bot id: its processes. */+ bots: Map<string, BotTally>;+ shared: BotTally;+}++const emptyTally = (): BotTally => ({ procs: 0, threads: 0, rssBytes: 0, cpuMs: 0, cpuDeltaMs: 0, engines: 0, browsers: 0, pids: [] });++/** Whose each row is: a bot's id, SHARED, or undefined for none (the server, its own helpers, anything else). */+export const SHARED = "\0shared";++export function attributeRows(rows: readonly ProcessRow[], owners: readonly FootprintOwner[], previous?: ReadonlyMap<number, { start: string; cpuMs: number }>): Attribution {+ const byPid = new Map(rows.map((row) => [row.pid, row]));+ // 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"] }>();+ for (const owner of owners) {+ const row = byPid.get(owner.pid);+ if (row && owner.start && row.start !== owner.start) continue;+ const ids = [...new Set(owner.botIds)];+ const label = ids.length === 1 && ID.test(ids[0]!) ? ids[0]! : SHARED;+ 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 });+ }+ const labels = new Map<number, string | null>();+ const labelOf = (row: ProcessRow, depth: number): string | null => {+ const known = labels.get(row.pid);+ if (known !== undefined) return known;+ 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;+ if (label === null && row.ppid !== row.pid && depth < 64) {+ const parent = byPid.get(row.ppid);+ if (parent) label = labelOf(parent, depth + 1);+ }+ if (label === null && row.sid !== undefined && row.sid !== row.pid) label = roots.get(row.sid)?.label ?? null;+ if (label === null && row.pgid !== undefined && row.pgid !== row.pid) label = roots.get(row.pgid)?.label ?? null;+ labels.set(row.pid, label);+ return label;+ };+ const out: Attribution = { bots: new Map(), shared: emptyTally() };+ for (const row of rows) {+ const label = labelOf(row, 0);+ if (label === null) continue;+ const tally = label === SHARED ? out.shared : out.bots.get(label) ?? out.bots.set(label, emptyTally()).get(label)!;+ tally.procs += 1;+ tally.threads = tally.threads === null || row.threads === undefined ? null : tally.threads + row.threads;+ tally.rssBytes += row.rssBytes;+ tally.cpuMs += row.cpuMs;+ 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);+ if (root?.kind === "engine") tally.engines += 1;+ else if (root?.kind === "browser") tally.browsers += 1;+ }+ return out;+}++export interface BotFootprintRow {+ id: string;+ procs: number;+ threads: number | null;+ rssMB: number;+ /** The most resident memory seen for this bot since the server started. */+ peakMB: number;+ cpuS: number;+ /** Of one core, over the time since the previous sample. */+ cpuPct: number;+ engines: number;+ browsers: number;+}++export interface BotFootprintReport {+ at: number | null;+ /** Bots with any process running at the last sample. */+ bots: number;+ /** The bots using the most memory first. */+ shown: BotFootprintRow[];+ shared: Omit<BotFootprintRow, "id" | "peakMB">;+}++const MB = 1_048_576;+/** Peaks of bots no longer seen are kept for this many bots at most, the least recently seen dropped first. */+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;+ now?: () => number;+}++export function createBotFootprints(options: BotFootprintsOptions) {+ const now = options.now ?? Date.now;+ const peaks = new Map<string, number>();+ let previous: { at: number; rows: Map<number, { start: string; cpuMs: number }> } | null = null;+ let latest: { at: number; windowMs: number | null; attribution: Attribution } | null = null;++ return {+ /** One process list from the sampler. */+ sample(rows: readonly ProcessRow[]): Attribution {+ const at = now();+ const attribution = attributeRows(rows, options.owners(), previous?.rows);+ for (const [id, tally] of attribution.bots) {+ const peak = Math.max(peaks.get(id) ?? 0, tally.rssBytes);+ // Moved to the end: the least recently seen bots' peaks go first.+ peaks.delete(id);+ peaks.set(id, peak);+ }+ 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);+ }+ return attribution;+ },+ /** The last sample's tallies. */+ latest: () => latest?.attribution ?? null,+ /** `limit`: how many bots to show, the ones using the most memory first; every bot when omitted. */+ report(limit?: number): BotFootprintReport {+ const windowMs = latest?.windowMs ?? null;+ const row = (tally: BotTally) => ({+ procs: tally.procs, threads: tally.threads, rssMB: Math.round(tally.rssBytes / MB), cpuS: Math.round(tally.cpuMs / 100) / 10,+ cpuPct: windowMs === null ? 0 : Math.round((tally.cpuDeltaMs / windowMs) * 100), engines: tally.engines, browsers: tally.browsers,+ });+ const bots = [...latest?.attribution.bots ?? []].sort(([, a], [, b]) => b.rssBytes - a.rssBytes || b.procs - a.procs);+ return {+ at: latest?.at ?? null,+ bots: bots.length,+ shown: bots.slice(0, limit ?? bots.length).map(([id, tally]) => ({ id, ...row(tally), peakMB: Math.round(Math.max(peaks.get(id) ?? 0, tally.rssBytes) / MB) })),+ shared: row(latest?.attribution.shared ?? emptyTally()),+ };+ },+ };+}+export type BotFootprints = ReturnType<typeof createBotFootprints>;++/** The plain line for people: a @devs report and the desktop's diagnostics. */+export function botFootprintLines(report: BotFootprintReport): string[] {+ if (report.at === null) return ["Per bot: not sampled yet"];+ const threads = (count: number | null) => (count === null ? "" : `, ${count} threads`);+ const one = (row: BotFootprintRow) => `bot ${row.id} ${row.procs} processes${threads(row.threads)}, ${row.rssMB} MB (most ${row.peakMB} MB), ${row.cpuS}s CPU, ${row.cpuPct}% now`+ + `${row.engines ? `, ${row.engines} engine${row.engines === 1 ? "" : "s"}` : ""}${row.browsers ? ", browser" : ""}`;+ const shared = report.shared;+ return [+ `Per bot (${report.bots} with processes running; most memory first): ${report.shown.length ? report.shown.map(one).join("; ") : "none"}`,+ ` Shared by several bots: ${shared.procs} processes${threads(shared.threads)}, ${shared.rssMB} MB, ${shared.engines} engines, ${shared.browsers} browsers`,+ ];+}diff --git a/server/perf/perf-host.ts b/server/perf/perf-host.tsindex 490ac139aa..4fcaa7e061 100644--- a/server/perf/perf-host.ts+++ b/server/perf/perf-host.ts@@ -6,6 +6,7 @@ import type { EngineLimitsReport } from "../../shared/limit-reset.ts";import type { RuntimeEvent } from "../contracts.ts";import type { StoreChange } from "../store.ts";import { createLoopStalls, requestArrivedBefore, type LoopStalls } from "./loop-stalls.ts";+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 { createProcessSampler, linuxProcessList, LINUX_SAMPLE_MS, nodeUtilization, OTHER_SAMPLE_MS, psProcessList, type ProcessSampler } from "./process-sampler.ts";@@ -36,8 +37,15 @@ export interface PerfHostDeps {processes?: ProcessHealthRecorder;/** The engine processes the server tracks, with the threads each runs (engine-memory, where turns wait for room). */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;}+/** The health report shows this many bots, the ones using the most memory first; the admin's read shows every one. */+export const BOTS_IN_HEALTH = 10;+/** What a report shows when the recorder failed: diagnostics never fail because of it. */export const PERF_UNAVAILABLE = ["## Performance", "(timings unavailable: the recorder failed; see the server log)"];@@ -85,21 +93,26 @@ export function createPerfHost(deps: PerfHostDeps) {const linux = process.platform === "linux", windows = process.platform === "win32";/** Its two warnings are said once each for the life of the server. */const processes = deps.processes ?? createProcessHealth({ warn: (kind, line) => say(kind, line) });+ const footprints: BotFootprints = createBotFootprints({ owners: () => deps.owners?.() ?? [], ...(deps.pruneOwners ? { prune: deps.pruneOwners } : {}), now });const sampler = deps.sampler ?? createProcessSampler({list: linux ? () => linuxProcessList() : psProcessList, intervalMs: linux ? LINUX_SAMPLE_MS : OTHER_SAMPLE_MS,scope: deps.wholeMachine && linux ? "all" : "tree", utilization: nodeUtilization(), now, engines: enginePids,stalled: (ms) => say("loop", `event loop stalled: the ${linux ? 60 : 300}s sampler fired ${duration(ms)} late`), afterSample: watchHolds,- seen: (rows, buckets) => processes.sample(rows, buckets),+ seen: (rows, buckets) => { processes.sample(rows, buckets); guarded("bots", () => footprints.sample(rows), null); },});if (deps.timer !== false && !windows) sampler.start();const stalls = deps.stalls ?? createLoopStalls();if (deps.timer !== false) stalls.start();if (deps.timer !== false && linux) guarded("limits", () => (deps.log ?? ((line: string) => console.warn(line)))(processes.startLine()), undefined);- const sources = () => ({ hour: timings.window(), day: timings.day(), live: timings.live(), limits: limits(), process: windows ? null : sampler.report(), stalls: guarded("stalls", () => stalls.report(), null), processes: processes.report() });+ const sources = () => ({ hour: timings.window(), day: timings.day(), live: timings.live(), limits: limits(), process: windows ? null : sampler.report(), stalls: guarded("stalls", () => stalls.report(), null), processes: processes.report(),+ bots: windows ? null : guarded("bots", () => footprints.report(BOTS_IN_HEALTH), null) });return {timings,sampler,+ footprints,+ /** Every bot's footprint at the last sample, for the admin's read (routes/perf-diagnostics.ts). */+ bots: (): BotFootprintReport | null => (windows ? null : guarded("bots", () => footprints.report(), null)),noteHeld: (threadId: string, why: "plan-limit" | "memory") => guarded("held", () => timings.noteHeld(threadId, why), undefined),noteFailover: (threadId: string, why: FailoverWhy) => guarded("failover", () => timings.noteFailover(threadId, why), undefined),noteNotStarted: (threadId: string, turnId: string | null, refusal?: Refusal) => guarded("refused", () => timings.noteNotStarted(threadId, turnId, refusal), undefined),diff --git a/server/perf/perf-report.ts b/server/perf/perf-report.tsindex 7c371f5fea..09633f8dec 100644--- a/server/perf/perf-report.ts+++ b/server/perf/perf-report.ts@@ -2,6 +2,7 @@// (plain lines for a @devs report and the desktop's diagnostics). Built only from the turn records' checked fields, the// process buckets and the limit clock's driver kinds, windows and times: nothing else reaches either.import type { EngineLimitsReport } from "../../shared/limit-reset.ts";+import { botFootprintLines, type BotFootprintReport } from "./bot-footprint.ts";import type { DayAggregate } from "./day-ledger.ts";import { SLOW_TURN_MS } from "./day-ledger.ts";import { PHASES, type Phase, type PhaseStats } from "./phases.ts";@@ -30,6 +31,8 @@ export interface PerfSources {stalls?: StallsReport | null;/** How close the server is to its process and memory limits (process-health.ts); null where nothing records it. */processes?: ProcessHealth | null;+ /** Each bot's processes, threads, memory and CPU, the most memory first (bot-footprint.ts); null where not sampled. */+ bots?: BotFootprintReport | null;}/** Engines refusing work, or within 10 points of their limit: driver kind, window, use and reset time only. */@@ -55,8 +58,10 @@ export function perfHealth(sources: PerfSources) {process: sources.process,stalls: sources.stalls ?? null,processes: sources.processes ?? null,+ bots: sources.bots ?? null,};const size = () => JSON.stringify(body).length;+ if (size() > PERF_HEALTH_MAX_BYTES && body.bots) body.bots = { ...body.bots, shown: body.bots.shown.slice(0, 3) };if (size() > PERF_HEALTH_MAX_BYTES && body.process) body.process = { ...body.process, buckets: body.process.buckets.slice(0, 6) };if (size() > PERF_HEALTH_MAX_BYTES) body.h24.tools = body.h24.tools.slice(0, 4);if (size() > PERF_HEALTH_MAX_BYTES) body.live = body.live.slice(0, 2);@@ -64,6 +69,7 @@ export function perfHealth(sources: PerfSources) {if (size() > PERF_HEALTH_MAX_BYTES) body.process = null;if (size() > PERF_HEALTH_MAX_BYTES) body.stalls = null;if (size() > PERF_HEALTH_MAX_BYTES) body.processes = null;+ if (size() > PERF_HEALTH_MAX_BYTES) body.bots = null;return body;}export type PerfHealth = ReturnType<typeof perfHealth>;@@ -131,6 +137,7 @@ export function perfLines(sources: PerfSources, recent: readonly TurnTiming[], r} else lines.push("Processes: not sampled yet");if (sources.stalls) lines.push(...stallLines(sources.stalls));if (sources.processes) lines.push(...processHealthLines(sources.processes));+ if (sources.bots) lines.push(...botFootprintLines(sources.bots));lines.push(recentTitle);lines.push(...(recent.length ? recent.map((turn) => ` ${turnLine(turn)}`) : [" (none)"]));return lines;diff --git a/server/perf/process-buckets.ts b/server/perf/process-buckets.tsindex a457117d15..b64cdf6068 100644--- a/server/perf/process-buckets.ts+++ b/server/perf/process-buckets.ts@@ -17,6 +17,10 @@ export interface ProcessRow {/** Linux: the process's threads, and its state letter ("Z": exited, not yet collected). */threads?: number;state?: string;+ /** Its process group (Linux and macOS) and POSIX session (Linux): an engine leads both, and what it starts stays in them+ * even once its parent has gone. */+ pgid?: number;+ sid?: number;}/** Engine CLIs by executable name, as the drivers' kinds name them. */@@ -89,9 +93,10 @@ export function parseProcStat(pid: number, text: string): ProcessRow | null {const fields = text.slice(close + 2).split(" ");const ppid = Number(fields[1]), user = Number(fields[11]), system = Number(fields[12]), start = fields[19], rss = Number(fields[21]);if (!Number.isInteger(ppid) || !Number.isFinite(user) || !Number.isFinite(system) || !start) return null;- const threads = Number(fields[17]);+ const threads = Number(fields[17]), pgid = Number(fields[2]), sid = Number(fields[3]);return { pid, ppid, name: text.slice(open + 1, close).toLowerCase(), cpuMs: ((user + system) * 1000) / CLOCK_TICKS, rssBytes: (Number.isFinite(rss) ? rss : 0) * PAGE_BYTES, start,- ...(Number.isInteger(threads) && /^[A-Za-z]$/.test(fields[0] ?? "") ? { threads, state: fields[0]! } : {}) };+ ...(Number.isInteger(threads) && /^[A-Za-z]$/.test(fields[0] ?? "") ? { threads, state: fields[0]! } : {}),+ ...(Number.isInteger(pgid) && pgid > 0 ? { pgid } : {}), ...(Number.isInteger(sid) && sid > 0 ? { sid } : {}) };}/** `/proc/self/stat`'s CPU time of children this process waited for, ms. */@@ -109,15 +114,17 @@ export function parsePsTime(text: string): number | null {return ((Number(days ?? 0) * 24 + Number(hours ?? 0)) * 60 + Number(minutes)) * 60_000 + Number(seconds) * 1000;}-/** One line of `ps -axo pid=,ppid=,rss=,time=,comm=`: rss in KiB, comm the executable's path (macOS), last so it may hold spaces. */+/** One line of `ps -axo pid=,ppid=,pgid=,rss=,time=,comm=`: rss in KiB, comm the executable's path (macOS), last so it may+ * hold spaces. The older five-column form (no pgid) is read too. */export function parsePsLine(line: string): ProcessRow | null {- const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+?)\s*$/.exec(line);+ const match = /^\s*(\d+)\s+(\d+)\s+(?:(\d+)\s+)?(\d+)\s+(\d\S*)\s+(.+?)\s*$/.exec(line);if (!match) return null;- const cpuMs = parsePsTime(match[4]!);+ const cpuMs = parsePsTime(match[5]!);if (cpuMs === null) return null;- const path = match[5]!;- const pid = Number(match[1]);- return { pid, ppid: Number(match[2]), name: path.slice(path.lastIndexOf("/") + 1).toLowerCase(), cpuMs, rssBytes: Number(match[3]) * 1024, start: `ps:${pid}` };+ const path = match[6]!;+ const pid = Number(match[1]), pgid = match[3] === undefined ? 0 : Number(match[3]);+ return { pid, ppid: Number(match[2]), name: path.slice(path.lastIndexOf("/") + 1).toLowerCase(), cpuMs, rssBytes: Number(match[4]) * 1024, start: `ps:${pid}`,+ ...(pgid > 0 ? { pgid } : {}) };}/** The cgroup's (or, outside one, the machine's) CPU time so far, ms: cgroup v2's usage_usec, else v1's cpuacct.usage. */diff --git a/server/perf/process-sampler.test.ts b/server/perf/process-sampler.test.tsindex 0e36cb8e28..b4e3b8564e 100644--- a/server/perf/process-sampler.test.ts+++ b/server/perf/process-sampler.test.ts@@ -41,7 +41,7 @@ describe("process buckets, from the executable's name and parent only", () => {});it("parses /proc stat lines (a comm with spaces and parentheses), ps lines and CPU counters", () => {- expect(parseProcStat(42, statLine(42, "Web Content (x)", 7, 150, 50))).toEqual({ pid: 42, ppid: 7, name: "web content (x)", cpuMs: 2_000, rssBytes: 256 * 4096, start: "5555", threads: 1, state: "S" });+ expect(parseProcStat(42, statLine(42, "Web Content (x)", 7, 150, 50))).toEqual({ pid: 42, ppid: 7, name: "web content (x)", cpuMs: 2_000, rssBytes: 256 * 4096, start: "5555", threads: 1, state: "S", pgid: 42, sid: 42 });expect(parseProcStat(1, "garbage")).toBeNull();expect(parseReapedChildrenMs(statLine(1, "node", 0, 0, 0, 1, 300, 200))).toBe(5_000);expect(parsePsTime("1:02.50")).toBe(62_500);@@ -49,6 +49,8 @@ describe("process buckets, from the executable's name and parent only", () => {expect(parsePsTime("nope")).toBeNull();expect(parsePsLine(" 812 1 20480 0:03.10 /Applications/Google Chrome.app/Contents/MacOS/Google Chrome Helper (Renderer)")).toEqual({ pid: 812, ppid: 1, name: "google chrome helper (renderer)", cpuMs: 3_100, rssBytes: 20480 * 1024, start: "ps:812" });+ expect(parsePsLine(" 812 1 640 20480 0:03.10 /Applications/Google Chrome.app/Contents/MacOS/Google Chrome Helper (Renderer)"))+ .toEqual({ pid: 812, ppid: 1, name: "google chrome helper (renderer)", cpuMs: 3_100, rssBytes: 20480 * 1024, start: "ps:812", pgid: 640 });expect(parseCgroupCpuMs("usage_usec 2500000\nuser_usec 1\n", null)).toBe(2_500);expect(parseCgroupCpuMs(null, "7000000000\n")).toBe(7_000);expect(parseCgroupCpuMs(null, null)).toBeNull();diff --git a/server/perf/process-sampler.ts b/server/perf/process-sampler.tsindex cf89773394..d5b1d909fd 100644--- a/server/perf/process-sampler.ts+++ b/server/perf/process-sampler.ts@@ -64,7 +64,7 @@ export function linuxProcessList(read: (path: string) => string | null = readTex/** One `ps` over every process: the fallback where there is no /proc (macOS). */export function psProcessList(): Promise<ProcessList | null> {return new Promise((resolve) => {- execFile("ps", ["-axo", "pid=,ppid=,rss=,time=,comm="], { timeout: 10_000, maxBuffer: 4 * 1024 * 1024, windowsHide: true }, (error, stdout) => {+ execFile("ps", ["-axo", "pid=,ppid=,pgid=,rss=,time=,comm="], { timeout: 10_000, maxBuffer: 4 * 1024 * 1024, windowsHide: true }, (error, stdout) => {if (error) return resolve(null);const rows = stdout.split("\n").flatMap((line) => { const row = parsePsLine(line); return row ? [row] : []; });resolve({ rows, reapedMs: null, totalMs: null });diff --git a/server/procs.ts b/server/procs.tsindex 0885713a87..10db2e19d1 100644--- a/server/procs.ts+++ b/server/procs.ts@@ -17,6 +17,7 @@ import { botBox, type WrappedSpawn } from "./bot-box/box.ts";import type { BoxRequest } from "./bot-box/plan.ts";import { homeProgramsDistrusted, serverMayRunFrom, serverPath } from "./bot-box/program-trust.ts";import { engineMemory } from "./engine-memory.ts";+import { engineOwners } from "./engine-owners.ts";import { ENGINE_TAG_ENV, engineRunTag, engineStopped, recordEngine } from "./engine-records.ts";import { engineHomes } from "./engine-homes/engine-homes.ts";import type { HomedSpawn } from "./engine-homes/layout.ts";@@ -352,6 +353,7 @@ export function spawnCli(if (process.platform !== "win32" && owner === "bot") {rememberEngineSession(child);engineMemory.track(child);+ engineOwners.track(child, child.pid ? linuxTrees.get(child)?.get(child.pid) ?? null : null);}// On Windows a stdin write between taskkill and pipe close errors asynchronously; unlistened, that crashes the harness.diff --git a/server/routes/perf-diagnostics.ts b/server/routes/perf-diagnostics.tsindex 19f91d2a73..d7b0e639a8 100644--- a/server/routes/perf-diagnostics.ts+++ b/server/routes/perf-diagnostics.ts@@ -1,13 +1,18 @@-// GET /api/diagnostics/performance: the performance recorder's plain lines for the desktop's diagnostics export. Admin-// scope (request-auth's default), so on a Cloud home a bot's shell, a service-trust loopback caller, never reaches it.+// GET /api/diagnostics/performance: the performance recorder's plain lines for the desktop's diagnostics export.+// GET /api/diagnostics/bots: every bot's processes, threads, memory and CPU at the last sample (perf/bot-footprint.ts), bot+// ids and numbers only. Both admin scope (request-auth's default), so on a Cloud home a bot's shell, a service-trust+// loopback caller, never reaches them.+import type { BotFootprintReport } from "../perf/bot-footprint.ts";import { PASS, type RouteHandler } from "./table.ts";export const PERF_DIAGNOSTICS_PATH = "/api/diagnostics/performance";+export const BOT_FOOTPRINT_PATH = "/api/diagnostics/bots";-export function createPerfDiagnosticsRoutes(deps: { text(): string }): RouteHandler {+export function createPerfDiagnosticsRoutes(deps: { text(): string; bots?(): BotFootprintReport | null }): RouteHandler {return async ({ res, path, method, json }) => {- if (path !== PERF_DIAGNOSTICS_PATH || method !== "GET") return PASS;+ if (method !== "GET" || (path !== PERF_DIAGNOSTICS_PATH && path !== BOT_FOOTPRINT_PATH)) return PASS;res.setHeader("cache-control", "no-store");+ if (path === BOT_FOOTPRINT_PATH) return json(res, 200, { bots: deps.bots?.() ?? null });return json(res, 200, { text: deps.text() });};}