Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Turn watchdog: keep a shell command running while its processes use CPU
AdityaUmalefdf894efa866
diff --git a/server/hooks.e2e.test.ts b/server/hooks.e2e.test.tsindex 796a6392e5..5a794fe15f 100644--- a/server/hooks.e2e.test.ts+++ b/server/hooks.e2e.test.ts@@ -189,14 +189,14 @@ posixOnly("engine hooks e2e: a shell call that hit its time limit", () => {const bot = await h.runTurn();const reply: Msg = bot.messages.filter((m: Msg) => m.role === "bot" && m.kind === "text" && m.text).at(-1);expect(reply.text!.match(/hit the shell time limit/g)).toHaveLength(2);- expect(reply.text).toContain("up to 7200000");+ expect(reply.text).toContain("up to 86400000");expect(reply.text).toContain("mdfind -name");const preview = await h.api("GET", `/api/bots/${bot.id}/system-prompt`);const shell = preview.body.sections.find((s: { id: string }) => s.id === "shell");expect(shell?.text).toContain("Long-running shell commands");const seen = JSON.parse(readFileSync(dump, "utf8"));expect(seen.systemPrompt).toContain(shell.text.trim());- expect(seen.env.BASH_MAX_TIMEOUT_MS).toBe("7200000");+ expect(seen.env.BASH_MAX_TIMEOUT_MS).toBe("86400000");}, 60_000);});diff --git a/server/index.ts b/server/index.tsindex c070463294..ed8de125f4 100644--- a/server/index.ts+++ b/server/index.ts@@ -332,7 +332,7 @@ import { Handoffs, handedStateUsable, isContextMessage, recordHanded, renderUnseimport { extractReplayImages, extractTurnImages, videoFramesWithin } from "./turn-images.ts";import { callTitleExcerpt } from "./thread-title.ts";import { generateThreadTitle, llmThreadTitlesEnabled } from "./thread-title-generate.ts";-import { engineProcessGone, stallLimitMs, stallNotice, TurnWatchdog } from "./turn-watchdog.ts"; import { createIdleThreads } from "./host/idle-threads.ts";+import { engineCommandCpuMs, engineProcessGone, stallLimitMs, stallNotice, TurnWatchdog } from "./turn-watchdog.ts"; import { createIdleThreads } from "./host/idle-threads.ts";import { TurnResources, type TurnOwner } from "./turn-resources.ts";import {ensureWorkspace,@@ -4979,7 +4979,7 @@ function stoppedTurnText(threadId: string, turnId: string | undefined, cause?: s});}const watchdog = new TurnWatchdog({- stallMs: TURN_STALL_MS, toolStallMs: TOOL_STALL_MS, parkedStallMs: COMPUTER_WAIT_MAX_MS + TURN_STALL_MS,+ stallMs: TURN_STALL_MS, toolStallMs: TOOL_STALL_MS, parkedStallMs: COMPUTER_WAIT_MAX_MS + TURN_STALL_MS, commandCpuMs: (turn, since) => engineCommandCpuMs(runningTurnInstance(botForThread(turn.botId, turn.threadId), turn.threadId)?.adapter, turn.threadId, since),checkMs: 60_000, unheld: { threads: () => idleThreads.unheld(), free: (threadId, botId) => idleThreads.free(botId, threadId) }, engineGone: (turn) => engineProcessGone(runningTurnInstance(botForThread(turn.botId, turn.threadId), turn.threadId)?.adapter, turn.threadId),onStall: (turn, silentMs) => {const stalledResourceOwner = turnResourceOwners.get(turn.threadId);diff --git a/server/shell-timeout-hint.test.ts b/server/shell-timeout-hint.test.tsindex 231ecf25d5..dff2ca34fb 100644--- a/server/shell-timeout-hint.test.ts+++ b/server/shell-timeout-hint.test.ts@@ -10,7 +10,7 @@ describe("shellTimeoutHint", () => {const hint = shellTimeoutHint("Bash", { command: "ffmpeg -i in.mp3 -ar 16000 out.wav" }, TIMED_OUT)!;expect(hint).toContain("Do not rerun it the same way");expect(hint).toContain("`timeout`");- expect(hint).toContain("up to 7200000, which is 120 minutes, unless a lower limit is set here");+ expect(hint).toContain("up to 86400000, which is 1440 minutes, unless a lower limit is set here");expect(hint).toContain("foreground");expect(hint).not.toContain("nohup");expect(hint).not.toContain("detached");diff --git a/server/system-prompt.test.ts b/server/system-prompt.test.tsindex 8eefeeefae..83e3f092d3 100644--- a/server/system-prompt.test.ts+++ b/server/system-prompt.test.ts@@ -462,7 +462,7 @@ describe("longCommandsPrompt", () => {it("names Bash's limit everywhere and vm_exec's own limit only with a Local VM", () => {for (const kind of [null, "local", "vps", "box"] as const) {const text = longCommandsPrompt(kind);- expect(text).toContain("`timeout` in milliseconds, up to 7200000, which is 120 minutes, unless a lower limit is set here");+ expect(text).toContain("`timeout` in milliseconds, up to 86400000, which is 1440 minutes, unless a lower limit is set here");expect(text).toContain("Never wait inside a command for CI, a deploy or any other job to finish (no sleep loops or repeated polls): check it once");expect(text).toContain("tell the person what you made (with links). Only on a turn the person started in their own chat, set wait_until or a one-time trigger to check back and end your turn");expect(text).toContain("When the person writes while you work, answer them first.");diff --git a/server/system-prompt.ts b/server/system-prompt.tsindex 0662123677..256de65722 100644--- a/server/system-prompt.ts+++ b/server/system-prompt.ts@@ -258,9 +258,9 @@ export const JUST_DO_IT_PROMPT =export const CREDENTIAL_PROMPT =" If a supported API key is missing for the service actually needed, use request_credential to create a secure credential request; a 1Password service account token, for signing in with logins from a 1Password vault, is one too (credential_id onePasswordToken). Before requesting a computer-provider key, inspect the configured targets with select_computer; an existing self-hosted VPS does not need Boat credentials. Do not request a different provider's key merely because a task mentions cloud. For any other secret (a Stripe or npm token, a webhook signing secret), give request_credential a label, reason and delivery: ref for mcp_server, file for your own commands. mcp_server sets up MCP servers in the chat: suggest one when a task needs a service you can't reach yet, and add, turn on or change one once the person asks or agrees. A freshly QR-paired mobile app or the desktop app can show the secure entry card. Never claim it opened unless the request succeeded, and never ask the user to paste credentials into chat.";-/** Two hours: the turn watchdog's default limit for a turn whose tool runs silently (OMB_TOOL_STALL_MS), so a long command- * that keeps working is not cut at ten minutes, and one still running at the limit is stopped and named as looking stuck. */-export const BASH_MAX_TIMEOUT_MS = 2 * 60 * 60_000;+/** A day: a long command that keeps working is not cut short. The turn watchdog stops one whose processes show neither+ * output nor CPU use for its tool limit (OMB_TOOL_STALL_MS, two hours) and names it as looking stuck. */+export const BASH_MAX_TIMEOUT_MS = 24 * 60 * 60_000;/** The default cap; a person's own BASH_MAX_TIMEOUT_MS can be lower, so the guidance names this as the most it allows. */export const BASH_MAX_TIMEOUT_TEXT = `${BASH_MAX_TIMEOUT_MS}, which is ${BASH_MAX_TIMEOUT_MS / 60_000} minutes, unless a lower limit is set here`;const LONG_COMMANDS_TEXT =diff --git a/server/turn-watchdog.test.ts b/server/turn-watchdog.test.tsindex 53ae9129ad..759bf0ba75 100644--- a/server/turn-watchdog.test.ts+++ b/server/turn-watchdog.test.ts@@ -8,7 +8,7 @@ import type { ProviderAdapter, RuntimeEvent } from "./contracts.ts";import { EngineMemory } from "./engine-memory.ts";import type { Message } from "./store.ts";import { TurnStops, stoppedTurnOutcome } from "./turn-outcome.ts";-import { engineProcessGone, stallLimitMs, stallNotice, stuckCommand, TurnWatchdog, type WatchedTurn } from "./turn-watchdog.ts";+import { engineCommandCpuMs, engineProcessGone, stallLimitMs, stallNotice, stuckCommand, TurnWatchdog, type TurnWatchdogOptions, type WatchedTurn } from "./turn-watchdog.ts";const STALL = 10_000;const TOOL_STALL = 50_000;@@ -19,7 +19,7 @@ const toolStarted = (itemId: string): RuntimeEvent => ({ ...base, type: "item.stconst shellStarted = (itemId: string, summary: string): RuntimeEvent => ({ ...base, type: "item.started", itemType: "tool", itemId, title: "Bash", summary });const toolEnded = (itemId: string): RuntimeEvent => ({ ...base, type: "item.completed", itemType: "tool", itemId, ok: true });-function rig() {+function rig(extra: Partial<TurnWatchdogOptions> = {}) {let now = 0;const stalls: WatchedTurn[] = [];const limits: number[] = [];@@ -39,6 +39,7 @@ function rig() {free: (threadId) => { freed.push(threadId); working.splice(working.findIndex((thread) => thread.threadId === threadId), 1); },},now: () => now,+ ...extra,});return { dog, stalls, limits, adapters, alive, working, freed, tick: (ms: number) => (now += ms) };}@@ -367,6 +368,103 @@ describe("TurnWatchdog", () => {});});+describe("a shell command that keeps working", () => {+ const settle = () => new Promise((resolve) => setImmediate(resolve));+ /** Sweeps once a turn limit at a time for ms, letting each CPU read land before the next sweep. */+ async function run(r: ReturnType<typeof rig>, ms: number) {+ for (let left = ms; left > 0; left -= STALL) {+ r.tick(Math.min(STALL, left));+ r.dog.sweep();+ await settle();+ }+ }++ it("is never stopped while its processes keep using CPU, and is once they stop for the tool limit", async () => {+ let cpuMs = 0, busy = true;+ const reads: number[] = [];+ const r = rig({ commandCpuMs: async (_turn, since) => { reads.push(since); if (busy) cpuMs += 1_000; return cpuMs; } });+ r.dog.watch("t1", "bot1");+ r.tick(5);+ r.dog.observe(shellStarted("tool-1", "ffmpeg -i talk.mov talk.mp4"));+ await run(r, 5 * TOOL_STALL);+ expect(r.stalls).toHaveLength(0);+ expect(new Set(reads)).toEqual(new Set([5]));+ busy = false;+ await run(r, TOOL_STALL - STALL);+ expect(r.stalls).toHaveLength(0);+ await run(r, 2 * STALL);+ expect(r.stalls).toEqual([expect.objectContaining({ threadId: "t1" })]);+ expect(r.limits).toEqual([TOOL_STALL]);+ expect(stallNotice(r.stalls[0]!, TOOL_STALL, 6 * TOOL_STALL + 5).key).toBe("chat.notice.stalledCommand");+ });++ it("is stopped at the tool limit when its processes use no CPU, or their CPU time cannot be read", async () => {+ for (const cpuMs of [500, null]) {+ const r = rig({ commandCpuMs: async () => cpuMs });+ r.dog.watch("t1", "bot1");+ r.dog.observe(shellStarted("tool-1", "sleep 100000"));+ await run(r, TOOL_STALL - 1);+ expect(r.stalls).toHaveLength(0);+ await run(r, 2);+ expect(r.limits).toEqual([TOOL_STALL]);+ }+ });++ it("reads nothing until the turn has been silent for the turn limit, nor for a tool that runs no shell command", async () => {+ let reads = 0;+ const r = rig({ commandCpuMs: async () => (reads += 1) });+ r.dog.watch("t1", "bot1");+ r.dog.observe(toolStarted("tool-1"));+ await run(r, TOOL_STALL - 1);+ expect(reads).toBe(0);+ r.dog.observe(toolEnded("tool-1"));+ r.dog.observe(shellStarted("tool-2", "make build"));+ await run(r, STALL - 1);+ expect(reads).toBe(0);+ await run(r, 1);+ expect(reads).toBe(1);+ });++ it("counts processes coming and going as work, and is not misled by a read that failed", async () => {+ const seen = [300, null, 200, 400, null, 100];+ let reads = 0;+ const r = rig({ commandCpuMs: async () => seen[reads++ % seen.length] ?? null });+ r.dog.watch("t1", "bot1");+ r.dog.observe(shellStarted("tool-1", "make -j8"));+ await run(r, 3 * TOOL_STALL);+ expect(r.stalls).toHaveLength(0);+ });++ it("goes on with the next sweep when reading a command's CPU time throws", async () => {+ const r = rig({ commandCpuMs: () => { throw new Error("thread gone"); } });+ r.dog.watch("t1", "bot1");+ r.dog.observe(shellStarted("tool-1", "make build"));+ await run(r, TOOL_STALL);+ expect(r.limits).toEqual([TOOL_STALL]);+ });++ it("never compares one command's CPU time with another's", async () => {+ const r = rig({ commandCpuMs: async (_turn, since) => (since === 0 ? 100 : 5_000) });+ r.dog.watch("t1", "bot1");+ r.dog.observe(shellStarted("tool-1", "make build"));+ await run(r, TOOL_STALL - STALL);+ r.dog.observe(shellStarted("tool-2", "make test"));+ r.dog.observe(toolEnded("tool-1"));+ await run(r, TOOL_STALL);+ expect(r.limits).toEqual([TOOL_STALL]);+ });++ it("reads the CPU time of what the engine started since the command did, and nothing for a driver with no process", async () => {+ const sample = vi.fn(async () => ({ cpuMs: 1_234, connections: null }));+ expect(await engineCommandCpuMs(tracked(ENGINE_PID), "t1", 99, sample)).toBe(1_234);+ expect(sample).toHaveBeenCalledWith(ENGINE_PID, 99);+ expect(await engineCommandCpuMs(tracked(undefined), "t1", 99, sample)).toBeNull();+ expect(await engineCommandCpuMs({}, "t1", 99, sample)).toBeNull();+ expect(await engineCommandCpuMs(undefined, "t1", 99, sample)).toBeNull();+ expect(sample).toHaveBeenCalledTimes(1);+ });+});+describe("stuckCommand", () => {it("names the longest-running shell command still running when the turn is stopped", () => {const { dog, stalls, tick } = rig();diff --git a/server/turn-watchdog.ts b/server/turn-watchdog.tsindex 713c3fc31d..dd6d9873f9 100644--- a/server/turn-watchdog.ts+++ b/server/turn-watchdog.ts@@ -1,9 +1,11 @@import { processAlive } from "./browser-processes.ts";import type { ProviderAdapter, RuntimeEvent } from "./contracts.ts";+import { sampleProcessTree, type ProcessSample } from "./drivers/acp/quiet-status.ts";// A turn whose thread emits nothing for stallMs is wedged; waiting on a person or a computer is not a stall unless the// turn's engine is known to have no process left. Drivers report a tool only when it starts and when it ends, so a turn-// with a tool running may stay silent for toolStallMs.+// with a tool running may stay silent for toolStallMs, and one whose shell command's processes keep using CPU is working,+// not silent, however long the command runs.export interface WatchedTurn {threadId: string;botId: string;@@ -20,14 +22,20 @@ export interface RunningTool {command?: string;}-/** The longest-running shell command of a turn stopped at stopAt, with the whole minutes it ran: what the person is told- * looks stuck. null when no running tool runs a shell command. */-export function stuckCommand(turn: Partial<Pick<WatchedTurn, "runningTools">>, stopAt: number): { command: string; minutes: number } | null {+/** The longest-running shell command of a turn, or undefined when no running tool runs one. */+function oldestCommand(turn: Partial<Pick<WatchedTurn, "runningTools">>): (RunningTool & { command: string }) | undefined {let oldest: RunningTool | undefined;for (const tool of turn.runningTools?.values() ?? []) {if (tool.command && (!oldest || tool.startedAt < oldest.startedAt)) oldest = tool;}- return oldest?.command ? { command: oldest.command, minutes: Math.max(1, Math.round((stopAt - oldest.startedAt) / 60_000)) } : null;+ return oldest as (RunningTool & { command: string }) | undefined;+}++/** The longest-running shell command of a turn stopped at stopAt, with the whole minutes it ran: what the person is told+ * looks stuck. null when no running tool runs a shell command. */+export function stuckCommand(turn: Partial<Pick<WatchedTurn, "runningTools">>, stopAt: number): { command: string; minutes: number } | null {+ const oldest = oldestCommand(turn);+ return oldest ? { command: oldest.command, minutes: Math.max(1, Math.round((stopAt - oldest.startedAt) / 60_000)) } : null;}/** What the person is told when the watchdog stops a turn silent for silentMs: the shell command still running, with how@@ -51,6 +59,14 @@ export function engineProcessGone(adapter: Pick<ProviderAdapter, "enginePid"> |return pid === undefined || !alive(pid);}+/** The CPU time used by the processes the thread's engine started since `since` (what a tool call started then runs, not+ * the engine or its tool servers); null when the driver tracks no engine process or the time cannot be read. */+export async function engineCommandCpuMs(adapter: Pick<ProviderAdapter, "enginePid"> | null | undefined, threadId: string, since: number,+ sample: (pid: number, since: number) => Promise<ProcessSample> = sampleProcessTree): Promise<number | null> {+ const pid = adapter?.enginePid?.(threadId);+ return pid === undefined ? null : (await sample(pid, since)).cpuMs;+}+const SUSPENDED_SWEEPS = 3;const parked = (turn: WatchedTurn): boolean => turn.waitingOnHuman || turn.waitingOnComputer;@@ -63,6 +79,9 @@ export interface TurnWatchdogOptions {checkMs: number;/** The turn's engine is known to have no process left for it; absent or false, a parked turn waits on. */engineGone?: (turn: WatchedTurn) => boolean;+ /** The CPU time the processes of the turn's shell command started at `since` have used, null when unknown. Read once+ * per sweep after a turn running one has been silent for stallMs: time gained since the last read counts as an event. */+ commandCpuMs?: (turn: WatchedTurn, since: number) => Promise<number | null>;/** silentMs: the silence that stopped the turn, stallMs, toolStallMs or parkedStallMs. */onStall: (turn: WatchedTurn, silentMs: number) => void;/** The conversations shown working that nothing holds but a watched turn (no dispatch, engine or settling turn): one no@@ -74,6 +93,8 @@ export interface TurnWatchdogOptions {export class TurnWatchdog {private turns = new Map<string, WatchedTurn>();private unheldSince = new Map<string, number>();+ /** Each turn's last read of its shell command's CPU time: the command it was read for (by start) and whether a read is out. */+ private cpu = new WeakMap<WatchedTurn, { since: number; ms: number | null; reading: boolean }>();private timer: ReturnType<typeof setInterval> | null = null;private opts: TurnWatchdogOptions;@@ -156,7 +177,7 @@ export class TurnWatchdog {}/** A turn of this bot is answering now: running and not parked on a person or a computer. One that goes silent is- * stopped by the sweep, so this never holds anything for longer than toolStallMs without events. */+ * stopped by the sweep, so this never holds anything for longer than toolStallMs without events or a command's CPU use. */answering(botId: string): boolean {for (const turn of this.turns.values()) if (turn.botId === botId && !parked(turn)) return true;return false;@@ -172,7 +193,9 @@ export class TurnWatchdog {for (const turn of this.turns.values()) {if (sleptMs) turn.lastEventAt = Math.min(at, turn.lastEventAt + sleptMs);const silentMs = this.silenceLimit(turn);- if (silentMs === null || at - turn.lastEventAt < silentMs) continue;+ if (silentMs === null) continue;+ if (at - turn.lastEventAt >= this.opts.stallMs) this.readCommandCpu(turn);+ if (at - turn.lastEventAt < silentMs) continue;this.turns.delete(turn.threadId);this.opts.onStall(turn, silentMs);}@@ -185,6 +208,23 @@ export class TurnWatchdog {return turn.runningTools.size > 0 ? Math.max(this.opts.stallMs, this.opts.toolStallMs) : this.opts.stallMs;}+ /** Reads the CPU time of a silent turn's shell command; one whose time changed since the last read is working (it gained+ * some, or a process came or went, as a build's compiler runs do), and that counts as an event, so a command that keeps+ * working is never stopped and one that stops for toolStallMs is. */+ private readCommandCpu(turn: WatchedTurn): void {+ const read = this.opts.commandCpuMs, command = parked(turn) ? undefined : oldestCommand(turn);+ if (!read || !command) return;+ const last = this.cpu.get(turn);+ if (last?.reading) return;+ const since = command.startedAt, previous = last?.since === since ? last.ms : null;+ this.cpu.set(turn, { since, ms: previous, reading: true });+ void Promise.resolve().then(() => read(turn, since)).catch(() => null).then((ms) => {+ // A read that failed keeps the last one to compare with.+ this.cpu.set(turn, { since, ms: ms ?? previous, reading: false });+ if (ms !== null && previous !== null && ms !== previous && this.turns.get(turn.threadId) === turn) turn.lastEventAt = Math.max(turn.lastEventAt, this.now());+ });+ }+private freeUnheld(at: number): void {const unheld = this.opts.unheld;if (!unheld) return;