Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cap: stop engines only, their conversations' browsers after them; short means memory itself
milind-soni968e3822ef66
diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 5f49be8d08..375859e0b2 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -613,11 +613,13 @@ the desktop app included); `auto` is the default (watch only) and `off` turnsthe watching off. Even then it acts only while the server is short ofmemory, only on the bot using the most, and in steps: first what the botleft running and its idle engines; then, measured again and still over, its-largest busy engine or browser. A turn whose engine is stopped ends with a+largest busy engine. The browser of a stopped engine's conversation is+closed once that turn lets it go. A turn whose engine is stopped ends with aline saying the bot used more memory than this computer allows for one bot.Engines and browsers several bots share, and a process other conversations-may join, are never stopped this way; on a Team Cloud only the browser that-was over is closed, never the same bot's browsers for other members. The+may join, are never stopped this way; on a Team Cloud only the stopped+conversation's own browser is closed, never the same bot's browsers for+other members. Theserver watches by reading its process list; it logs at start whether thehost also offers a systemd scope or a delegated cgroup, which are not usedyet.diff --git a/server/bot-memory-cap.test.ts b/server/bot-memory-cap.test.tsindex 76d9a8ba0b..e8073cb0fe 100644--- a/server/bot-memory-cap.test.ts+++ b/server/bot-memory-cap.test.ts@@ -57,11 +57,13 @@ describe("the cap's setting", () => {it("reads pressure from engine-memory where the gate runs, else from memory directly", () => {const host = (availableGB: number) => () => ({ totalBytes: 16 * GB, availableBytes: availableGB * GB, swapFreeBytes: 0, oomKills: 0, fullStall10: 0 });- expect(capPressure({ enabled: true, roomFactor: () => 0.2, shortOfRoom: () => true }, host(1))).toEqual({ room: 0.2, short: true, freeBytes: GB });- expect(capPressure({ enabled: false, roomFactor: () => 1, shortOfRoom: () => false }, host(12))).toMatchObject({ room: 1, short: false });+ expect(capPressure({ enabled: true, roomFactor: () => 0.2 }, host(1))).toEqual({ room: 0.2, short: true, freeBytes: GB });+ // The pids limit alone lowers the room factor, never "short": a stopped turn's line says memory ran short.+ expect(capPressure({ enabled: true, roomFactor: () => 0.1 }, host(12))).toEqual({ room: 0.1, short: false, freeBytes: 12 * GB });+ expect(capPressure({ enabled: false, roomFactor: () => 1 }, host(12))).toMatchObject({ room: 1, short: false });// 1 GB free of 16 GB: below the 1.6 GB floor, so short; a tenth of the room.- expect(capPressure({ enabled: false, roomFactor: () => 1, shortOfRoom: () => false }, host(1))).toMatchObject({ room: 0.1, short: true });- expect(capPressure({ enabled: false, roomFactor: () => 1, shortOfRoom: () => false }, () => null)).toEqual({ room: 1, short: false, freeBytes: null });+ expect(capPressure({ enabled: false, roomFactor: () => 1 }, host(1))).toMatchObject({ room: 0.1, short: true });+ expect(capPressure({ enabled: false, roomFactor: () => 1 }, () => null)).toEqual({ room: 1, short: false, freeBytes: null });});});@@ -94,14 +96,14 @@ function dog(rows: () => ProcessRow[], options: {mode?: CapSetting["mode"]; pressure?: () => CapPressure; busy?: ReadonlySet<string>; owners?: () => FootprintOwner[];pss?: (pid: number) => number | null; startOf?: (pid: number) => string | null;} = {}) {- const signals: string[] = [], closed: string[] = [], logs: string[] = [];+ const signals: string[] = [], closed: string[][] = [], logs: string[] = [];let clock = 1_800_000_000_000, pssReads = 0;const pss = options.pss ?? ((pid: number) => rows().find((row) => row.pid === pid)?.rssBytes ?? null);const watchdog = new BotMemoryWatchdog({cap: () => ({ mode: options.mode ?? "enforce", bytes: 1000 * MB }), list: rows, owners: options.owners ?? (() => OWNERS), pressure: options.pressure ?? (() => SHORT),pss: (pid) => { pssReads += 1; return pss(pid); }, startOf: options.startOf ?? ((pid) => `s${pid}`), graceMs: 0, now: () => clock,busy: (threadId) => (options.busy ?? new Set(["tb", "ta"])).has(threadId),- signal: (pid, value) => signals.push(`${value} ${pid}`), closeBrowser: async (session) => { closed.push(session); }, log: (line) => logs.push(line),+ signal: (pid, value) => signals.push(`${value} ${pid}`), closeBrowsers: async (threadIds) => { closed.push([...threadIds]); }, log: (line) => logs.push(line),});return { watchdog, signals, closed, logs, pssReads: () => pssReads, advance: (ms: number) => { clock += ms; }, now: () => clock };}@@ -188,7 +190,7 @@ describe("an opt-in cap (a number of MB set)", () => {// Memory short and over on a second look: the first step.expect((await h.watchdog.check()).map((event) => event.action)).toEqual(["idle"]);expect(h.signals).toEqual(["SIGTERM 310", "SIGTERM 311", "SIGTERM 321", "SIGKILL 310", "SIGKILL 311", "SIGKILL 321"]);- expect(h.closed).toEqual([]);+ expect(h.closed).toEqual([["tc", "td"]]);// Those gone, one engine of 1,600 MB and its browser: still over. The next step waits for a new measure.sizes = { a: 1200, b: 1600, b2: 0, orphan: 0 };h.signals.length = 0;@@ -196,21 +198,29 @@ describe("an opt-in cap (a number of MB set)", () => {h.advance(5_000);expect((await h.watchdog.check()).map((event) => event.action)).toEqual(["engine"]);expect(h.signals).toEqual(["SIGTERM 300", "SIGTERM 301", "SIGKILL 300", "SIGKILL 301"]);- expect(h.closed).toEqual([]);+ // Its browser goes with the conversation whose engine stopped, once that turn lets it go: never a step of its own.+ expect(h.closed).toEqual([["tc", "td"], ["tb"]]);expect(h.watchdog.stops()).toBe(2);expect(h.logs.at(-1)).toMatch(/^memory: bot bot_b uses 1700 MB \(proportional\), over the 1000 MB .*: stopping its largest busy engine$/);});- it("acts on the bot using the most only, and closes a browser by its session alone when that is the largest", async () => {- // Both far over with memory short: due at once. Bot B (2,000 MB) over bot A (1,500 MB): bot B only; its browser is- // larger than its busy engine.+ it("acts on the bot using the most only, and stops an engine even when its browser is larger (the browser goes with it)", async () => {+ // Both far over with memory short: due at once. Bot B (2,000 MB) over bot A (1,500 MB): bot B only. Its browser+ // (1,400 MB) is larger than its busy engine, but a browser a running turn holds can't be closed: the engine goes,+ // and its conversation's browser with it.const h = dog(() => processes({ a: 1500, b: 600, browser: 1400 }));const [event, ...more] = await h.watchdog.check();expect(more).toEqual([]);- expect(event).toMatchObject({ botId: "bot_b", action: "browser" });+ expect(event).toMatchObject({ botId: "bot_b", action: "engine" });await h.watchdog.closed();- expect(h.closed).toEqual(["bot-b"]);- expect(h.signals).toEqual([]);+ expect(h.closed).toEqual([["tb"]]);+ expect(h.signals).toEqual(["SIGTERM 300", "SIGTERM 301", "SIGKILL 300", "SIGKILL 301"]);+ // Its browser never closes (the turn still holds it): the next step is an engine again, never the browser.+ h.advance(10_000);+ await h.watchdog.check();+ expect((await h.watchdog.check()).map((step) => step.action)).toEqual(["engine"]);+ // Bot A, over too, is left alone while bot B uses more.+ expect(h.signals.some((line) => /\b20[01]$/.test(line))).toBe(false);});it("stops at once only far over with memory short, and with room factor alone waits the window", async () => {@@ -224,13 +234,18 @@ describe("an opt-in cap (a number of MB set)", () => {expect((await near.watchdog.check()).map((event) => event.action)).toEqual(["engine"]);});- it("never stops an engine other conversations may join, even when it is the bot's largest", async () => {+ it("never stops an engine other conversations may join, even when it is the bot's largest, and says so when that is all", async () => {const owners = () => OWNERS.map((owner) => (owner.pid === 300 ? { ...owner, shareable: true } : owner));const h = dog(() => processes({ b: 1600, b2: 400 }), { owners, busy: new Set(["tb", "tc"]) });await h.watchdog.check();h.advance(OVER_FOR_MS);await h.watchdog.check();expect(h.signals).toEqual(["SIGTERM 310", "SIGTERM 311", "SIGKILL 310", "SIGKILL 311"]);+ const only = dog(() => processes({ b: 1600 }), { owners, busy: new Set(["tb"]) });+ expect((await only.watchdog.check()).map((event) => event.action)).toEqual(["nothing"]);+ for (let look = 0; look < 5; look++) { only.advance(OVER_FOR_MS); expect(await only.watchdog.check()).toEqual([]); }+ expect(only.signals).toEqual([]);+ expect(only.watchdog.stops()).toBe(0);});it("signals nothing whose start can't be read now, and kills only what is still the bot's after the grace", async () => {diff --git a/server/bot-memory-cap.ts b/server/bot-memory-cap.tsindex 099e3fc86a..6fc4e6d6e2 100644--- a/server/bot-memory-cap.ts+++ b/server/bot-memory-cap.ts@@ -2,8 +2,9 @@// recorded ("would have stopped": its measured memory, the cap, its engines, the room left) in the health report's perf// part and the server log, and nothing is signalled or closed. Only a number of MB set in OMB_BOT_MEMORY_MAX_MB makes it// act, and then only when the server is short of memory, only on the bot using the most, and in steps: what the bot left-// running and its idle engines first, then (measured again, still over) its largest busy engine or browser, never all at-// once. A process several bots share, or one other conversations may join, is never stopped.+// running and its idle engines first, then (measured again, still over) its largest busy engine, never all at once; a+// stopped engine's conversations then have their browsers closed. A process several bots share, or one other+// conversations may join, is never stopped.//// The design's ladder is a systemd scope, then a delegated cgroup v2, then this server's own watchdog, then nothing (the// desktop). The kernel rungs are probed and reported but not used yet: putting each bot's processes in a cgroup of its@@ -121,8 +122,8 @@ export interface CapEvent {/** Whether the server was short of memory then: the opt-in cap acts only then. */pressure: boolean;/** logged: watch only (the default); held: an opt-in cap with room to spare; idle: stopped what it left running and its- * idle engines; engine: stopped its largest busy engine; browser: closed its largest browser. */- action: "logged" | "held" | "idle" | "engine" | "browser";+ * idle engines; engine: stopped its largest busy engine; nothing: all it runs may serve other conversations. */+ action: "logged" | "held" | "idle" | "engine" | "nothing";}/** An engine stopped for its bot's memory: the conversations it ran, for the line their turn ends with. */@@ -137,8 +138,9 @@ export interface WatchdogOptions {owners: () => readonly FootprintOwner[];pressure: () => CapPressure;pss?: (pid: number) => number | null;- /** Closes one browser session the way a memory stop closes one (its sign-ins saved). */- closeBrowser?: (session: string) => Promise<void>;+ /** Closes the browsers of these conversations (their stopped engines') the way a memory stop closes one: its sign-ins+ * saved, once no turn holds it. */+ closeBrowsers?: (threadIds: readonly string[]) => Promise<void>;signal?: (pid: number, signal: NodeJS.Signals) => void;/** What each pid's start is now (Linux's start tick): only the process that was read is signalled. */startOf?: (pid: number) => string | null;@@ -256,16 +258,21 @@ export class BotMemoryWatchdog {const top = due[0]!;if (top.id !== largest?.id) return [];const over = this.#over.get(top.id)!;- const units = [...top.tally.units.values()].filter((unit) => !unit.shareable);+ // Only engines are stopped: a browser goes with the engines of its conversations (it is closed once their turn lets+ // it go), so a browser a running turn holds is never the step, and a Team Cloud's other members keep theirs.+ const engines = [...top.tally.units.values()].filter((unit) => unit.kind === "engine" && !unit.shareable);const busy = this.#options.busy ?? ((threadId: string) => runningTurns.has(threadId));- const first = over.stepped ? [] : units.filter((unit) => unit.kind === "engine" && (unit.exited || !unit.threads.some(busy)));- let step: { action: CapEvent["action"]; units: FootprintUnit[] };- if (first.length) step = { action: "idle", units: first };- else {- const size = (unit: FootprintUnit) => unit.pids.reduce((sum, pid) => sum + (top.sizes.get(pid) ?? 0), 0);- const largest = units.filter((unit) => !unit.exited).sort((a, b) => size(b) - size(a))[0];- if (!largest) return [];- step = { action: largest.kind === "browser" ? "browser" : "engine", units: [largest] };+ const first = over.stepped ? [] : engines.filter((unit) => unit.exited || !unit.threads.some(busy));+ const size = (unit: FootprintUnit) => unit.pids.reduce((sum, pid) => sum + (top.sizes.get(pid) ?? 0), 0);+ const largestBusy = engines.filter((unit) => !unit.exited).sort((a, b) => size(b) - size(a))[0];+ const step = first.length ? { action: "idle" as const, units: first } : largestBusy ? { action: "engine" as const, units: [largestBusy] } : null;+ if (!step) {+ // All it runs is shared or may be joined by other conversations: nothing it may stop, written down once.+ if (over.logged) return [];+ over.logged = true;+ const noted = event(top, "nothing");+ this.#note(noted, "nothing it may stop (its engines may serve other conversations)");+ return [noted];}// The next step waits for a new measure past the window (or memory still short on two looks).over.stepped = true;@@ -273,19 +280,17 @@ export class BotMemoryWatchdog {over.looks = 0;const done = event(top, step.action);this.#stops += 1;- this.#note(done, step.action === "idle" ? `stopping what it left running and its idle engines (${step.units.length})`- : step.action === "engine" ? "stopping its largest busy engine" : "closing its largest browser");+ this.#note(done, step.action === "idle" ? `stopping what it left running and its idle engines (${step.units.length})` : "stopping its largest busy engine");for (const unit of step.units) {- if (unit.kind === "engine" && !unit.exited) this.#stopped.set(unit.root, { at: now, pid: unit.root, threads: [...unit.threads], botId: top.id, usedBytes: top.used, capBytes: top.cap });+ if (!unit.exited) this.#stopped.set(unit.root, { at: now, pid: unit.root, threads: [...unit.threads], botId: top.id, usedBytes: top.used, capBytes: top.cap });}for (const [pid, stop] of this.#stopped) if (now - stop.at > EXPLAIN_FOR_MS) this.#stopped.delete(pid);- const browsers = step.units.filter((unit) => unit.kind === "browser");- const engines = step.units.filter((unit) => unit.kind === "engine");const starts = new Map(rows.map((row) => [row.pid, row.start]));- // The browser closes on its own time (it waits for the stopped turn to let it go): the next look does not wait.- const closing = browsers.map((unit) => (unit.session !== undefined && this.#options.closeBrowser ? this.#options.closeBrowser(unit.session).catch(() => undefined) : Promise.resolve()));- await this.#signalUnits(top.id, engines, starts);- this.#acting = Promise.all(closing);+ await this.#signalUnits(top.id, step.units, starts);+ // Their conversations' browsers close on their own time (each waits for its stopped turn to let it go): the next look+ // does not wait.+ const threads = [...new Set(step.units.flatMap((unit) => unit.threads))];+ this.#acting = threads.length && this.#options.closeBrowsers ? this.#options.closeBrowsers(threads).catch(() => undefined) : Promise.resolve();return [done];}@@ -342,7 +347,7 @@ export class BotMemoryWatchdog {return stop !== undefined && stop.threads.includes(threadId) && at - stop.at <= EXPLAIN_FOR_MS;}- /** Resolves once the last step's browser close has finished: for tests. */+ /** Resolves once the last step's browsers have closed: for tests. */closed(): Promise<unknown> { return this.#acting; }/** Steps taken since the server started (the opt-in cap only). */@@ -428,7 +433,7 @@ let report: () => CapReport = () => ({ mb: null, mode: null, rung: "none", offer* each look, as the most turns at once may change (a plan's limit arrives after start). */export function startBotMemoryCap(deps: {gate: GateHost; turns: () => number | undefined; owners: () => readonly FootprintOwner[]; botName: (botId: string) => string;- closeBrowser: (session: string) => Promise<void>; list: () => readonly ProcessRow[]; startOf: (pid: number) => string | null; pressure: () => CapPressure;+ closeBrowsers: (threadIds: readonly string[]) => Promise<void>; list: () => readonly ProcessRow[]; startOf: (pid: number) => string | null; pressure: () => CapPressure;env?: NodeJS.ProcessEnv; memoryBytes?: number; log?: (line: string) => void; platform?: NodeJS.Platform;}): BotMemoryWatchdog | null {const env = deps.env ?? process.env, log = deps.log ?? ((line: string) => console.warn(line));@@ -436,7 +441,7 @@ export function startBotMemoryCap(deps: {const cap = () => botMemoryCap(env, { gate: deps.gate, memoryBytes: deps.memoryBytes ?? boxMemory().bytes, ...(deps.turns() === undefined ? {} : { turns: deps.turns() }) },(line) => { if (!warned) { warned = true; log(`memory: ${line}`); } });const first = cap(), ladder = capLadder(first, { platform: deps.platform ?? process.platform });- const dog = ladder.rung === "watchdog" ? new BotMemoryWatchdog({ cap, list: deps.list, owners: deps.owners, pressure: deps.pressure, pss: (pid) => pssBytes(pid), closeBrowser: deps.closeBrowser, startOf: deps.startOf, log }) : null;+ const dog = ladder.rung === "watchdog" ? new BotMemoryWatchdog({ cap, list: deps.list, owners: deps.owners, pressure: deps.pressure, pss: (pid) => pssBytes(pid), closeBrowsers: deps.closeBrowsers, startOf: deps.startOf, log }) : null;report = () => {const now = dog ? cap() : null;return { mb: now ? mb(now.bytes) : null, mode: now?.mode ?? null, rung: dog ? ladder.rung : "none", offered: ladder.offered, stops: dog?.stops() ?? 0, flagged: dog?.flagged() ?? 0, events: dog?.events() ?? [] };diff --git a/server/host/bot-memory-cap-host.ts b/server/host/bot-memory-cap-host.tsindex 381cd5bbfe..d57ba2653d 100644--- a/server/host/bot-memory-cap-host.ts+++ b/server/host/bot-memory-cap-host.ts@@ -14,20 +14,22 @@ const startOf = (pid: number): string | null => {try { return parseProcStat(pid, readFileSync(`/proc/${pid}/stat`, "utf8"))?.start ?? null; } catch { return null; }};-/** The room the watchdog weighs: engine-memory's own signals where turns wait for room; elsewhere (an explicit cap on a- * server without the gate) the same arithmetic from the memory read directly, so an opt-in cap still sees a shortage. */-export function capPressure(memory: Pick<EngineMemory, "enabled" | "roomFactor" | "shortOfRoom"> = engineMemory, read: () => HostMemory | null = () => readHostMemory()): CapPressure {+/** The room the watchdog weighs: engine-memory's room factor where turns wait for room (memory's and the pids limit's);+ * elsewhere (an explicit cap on a server without the gate) the same arithmetic from memory read directly. Short means+ * memory itself, below the floor admission keeps (never only the pids limit): the line a stopped turn ends with says so. */+export function capPressure(memory: Pick<EngineMemory, "enabled" | "roomFactor"> = engineMemory, read: () => HostMemory | null = () => readHostMemory()): CapPressure {const host = read();const free = host ? host.availableBytes + host.swapFreeBytes / 2 : null;- if (memory.enabled) return { room: memory.roomFactor(), short: memory.shortOfRoom(), freeBytes: free };+ const floor = host ? Math.max(320 * MB, host.totalBytes * 0.1) : 0;+ const short = host !== null && free !== null && free < floor;+ if (memory.enabled) return { room: memory.roomFactor(), short, freeBytes: free };if (!host || free === null) return { room: 1, short: false, freeBytes: null };- const floor = Math.max(320 * MB, host.totalBytes * 0.1);- return { room: Math.min(1, Math.max(0.1, (free - floor) / (host.totalBytes / 2))), short: free < floor, freeBytes: free };+ return { room: Math.min(1, Math.max(0.1, (free - floor) / (host.totalBytes / 2))), short, freeBytes: free };}-export function startBotMemoryCapHost(deps: { owners: () => readonly FootprintOwner[]; botName: (botId: string) => string | undefined; closeBrowser: (session: string) => Promise<void> }): BotMemoryWatchdog | null {+export function startBotMemoryCapHost(deps: { owners: () => readonly FootprintOwner[]; botName: (botId: string) => string | undefined; closeBrowsers: (threadIds: readonly string[]) => Promise<void> }): BotMemoryWatchdog | null {return startBotMemoryCap({gate: gateHost(), turns: () => engineMemory.most(), owners: deps.owners, botName: (botId) => deps.botName(botId) ?? "This bot",- closeBrowser: deps.closeBrowser, list: () => linuxProcessList().rows, startOf, pressure: () => capPressure(),+ closeBrowsers: deps.closeBrowsers, list: () => linuxProcessList().rows, startOf, pressure: () => capPressure(),});}diff --git a/server/host/browser-daemons.ts b/server/host/browser-daemons.tsindex b0ecebcd35..80d760140d 100644--- a/server/host/browser-daemons.ts+++ b/server/host/browser-daemons.ts@@ -91,8 +91,6 @@ export function createBrowserDaemons(options: BrowserDaemonsOptions = {}) {}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.tsindex dc217e0579..1e96071be8 100644--- a/server/host/browser.ts+++ b/server/host/browser.ts@@ -497,11 +497,19 @@ export function createBrowserHost(deps: BrowserHostDeps) {return [{ ...daemon, session, botIds, kind: "browser" as const }];});}- /** Closes one browser session the memory cap stopped (bot-memory-cap.ts), as one stopped for memory is: only that- * session, so on a Team Cloud the same bot's browsers for other members stay open; never one on the person's own Chrome. */- async function closeCapBrowser(session: string): Promise<void> {- const spec = usedBrowserSessions.get(session);- if (spec && !chromeTarget(session, spec) && !attachesToChrome(spec.env)) await closeForMemory(session, spec);+ /** Closes the browsers of the conversations whose engine the memory cap stopped (bot-memory-cap.ts), as one stopped for+ * memory is: each conversation's own session, so on a Team Cloud the same bot's browsers for other members stay open;+ * never one on the person's own Chrome, never a profile another bot uses. */+ async function closeCapBrowsers(threadIds: readonly string[]): Promise<void> {+ const sessions = new Map<string, Spec>();+ for (const threadId of threadIds) {+ const browser = threadBrowser(threadId), botId = store.botByThread(threadId)?.id;+ const { session, spec } = browser ?? {};+ if (session === undefined || !spec || chromeTarget(session, spec) || attachesToChrome(spec.env)) continue;+ if (store.bots.some((other) => other.id !== botId && browserSessionsOf(other.id, other.browserProfile).includes(session))) continue;+ sessions.set(session, spec);+ }+ await Promise.all([...sessions].map(([session, spec]) => closeForMemory(session, spec)));}/** 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 {@@ -639,6 +647,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, browserOwners, closeCapBrowser,+ eraseAudienceBrowsers, browserOwners, closeCapBrowsers,};}diff --git a/server/index.ts b/server/index.tsindex 02ba051be7..25af86e504 100644--- a/server/index.ts+++ b/server/index.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, browserOwners, closeCapBrowser,+ browserReady, currentBrowserSpec, loginInput, browserSystemPrompt, closeBrowser, browserEngineSwitched, eraseDeletedBrowser, engineSummary, browserSessionsOf, signedInSitesTarget, uploadPaths, eraseAudienceBrowsers, browserOwners, closeCapBrowsers,} = 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 botProcessOwners = footprintOwners({ botOf: (threadId) => store.botByThread(threadId)?.id ?? null, browsers: browserOwners }); const perf = createPerfHost({ dataDir: DATA_DIR, bus, store, limits: () => limitClock.report(), engines: () => engineMemory.enginePids(), owners: botProcessOwners, pruneOwners: (rows) => engineOwners.prune(rows), cap: botMemoryCapReport, wholeMachine: Boolean(CLOUD_HOME) }); startBotMemoryCapHost({ owners: botProcessOwners, botName: (botId) => store.bot(botId)?.name, closeBrowser: closeCapBrowser }); 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 botProcessOwners = footprintOwners({ botOf: (threadId) => store.botByThread(threadId)?.id ?? null, browsers: browserOwners }); const perf = createPerfHost({ dataDir: DATA_DIR, bus, store, limits: () => limitClock.report(), engines: () => engineMemory.enginePids(), owners: botProcessOwners, pruneOwners: (rows) => engineOwners.prune(rows), cap: botMemoryCapReport, wholeMachine: Boolean(CLOUD_HOME) }); startBotMemoryCapHost({ owners: botProcessOwners, botName: (botId) => store.bot(botId)?.name, closeBrowsers: closeCapBrowsers }); 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) });