Skip to content

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

12.9 KB
Raw Blame
// POSIX-gated: the fake CLI is a shebang script.
import { spawn, type ChildProcess } from "node:child_process";
import { createHash } from "node:crypto";
import { chmodSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";

import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import { workerPort } from "./testing/worker-port.ts";

const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const FAKE_CLAUDE = join(SERVER_DIR, "testing", "fake-claude-cli.ts");
const posixOnly = describe.skipIf(process.platform === "win32");

interface Msg {
  id: string;
  role: string;
  kind: string;
  text?: string;
  tool?: { name: string; itemId?: string; fullResult?: boolean; output?: string };
  digest?: { hookCoverage: string; tools: Array<{ name: string; count: number }> };
  compaction?: unknown;
  engineCompaction?: true;
}

const BIG = `line ${"x".repeat(80)}\n`.repeat(200); // ~17 KB: past the 6 KB preview

function harness(label: string, serverEnv: Record<string, string>, instanceEnv: Record<string, string> = {}) {
  const PORT = workerPort(18800, 10_000);
  const BASE = `http://127.0.0.1:${PORT}`;
  let child: ChildProcess;
  let home: string;
  let stderr = "";
  const api = async (method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<{ status: number; body: any }> => {
    const res = await fetch(`${BASE}${path}`, {
      method,
      headers: { ...(body ? { "content-type": "application/json" } : {}), ...headers },
      body: body ? JSON.stringify(body) : undefined,
    });
    return { status: res.status, body: await res.json().catch(() => null) };
  };
  const getBot = async (id: string) => (await api("GET", "/api/bots")).body.bots.find((b: any) => b.id === id);
  const waitFor = async (predicate: () => Promise<boolean>, what: string, ms = 30_000) => {
    const deadline = Date.now() + ms;
    while (!(await predicate())) {
      if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}. stderr: ${stderr.slice(-3000)}`);
      await new Promise((r) => setTimeout(r, 200));
    }
  };
  beforeAll(async () => {
    chmodSync(FAKE_CLAUDE, 0o755);
    home = mkdtempSync(join(tmpdir(), `omb-hooks-${label}-`));
    mkdirSync(join(home, ".openmausbot"), { recursive: true });
    writeFileSync(join(home, ".openmausbot", "config.json"), JSON.stringify({
      instances: {
        claude: {
          driver: "claudeAgent",
          environment: {
            FAKE_CLAUDE_TURN_STATE: join(home, "turns"),
            FAKE_CLAUDE_PROMPTS: join(home, "prompts.ndjson"),
            FAKE_CLAUDE_HOOKS: "1",
            FAKE_CLAUDE_TOOL_CALLS: JSON.stringify([
              { name: "Bash", input: { command: "cat big.log" }, ok: true, output: BIG },
              { name: "Read", input: { file_path: "a.ts" }, ok: true, output: "const a = 1;" },
            ]),
            ...instanceEnv,
          },
          config: { cli: FAKE_CLAUDE },
        },
      },
    }));
    const env: NodeJS.ProcessEnv = { HOME: home, USERPROFILE: home, OMB_PORT: String(PORT), ...serverEnv };
    if (process.env.PATH) env.PATH = process.env.PATH;
    child = spawn(process.execPath, [join(SERVER_DIR, "index.ts")], { cwd: join(SERVER_DIR, ".."), env, stdio: ["ignore", "pipe", "pipe"] });
    child.stderr!.on("data", (c) => (stderr += c));
    const deadline = Date.now() + 20_000;
    for (;;) {
      try {
        if ((await fetch(`${BASE}/api/health`)).ok) break;
      } catch {}
      if (Date.now() > deadline) throw new Error(`server never came up. stderr:\n${stderr}`);
      if (child.exitCode !== null) throw new Error(`server exited ${child.exitCode}. stderr:\n${stderr}`);
      await new Promise((r) => setTimeout(r, 150));
    }
  }, 30_000);
  afterAll(async () => {
    await waitForExit(child, { signal: "SIGTERM" });
    await removeTempDir(home);
  });
  return {
    api,
    getBot,
    waitFor,
    home: () => home,
    runTurn: async () => {
      const created = (await api("POST", "/api/bots")).body.bot;
      expect((await api("PATCH", `/api/bots/${created.id}`, { modelSelection: { instanceId: "claude", model: "fake-model" } })).status).toBe(200);
      expect((await api("POST", `/api/bots/${created.id}/messages`, { text: "read the big log" })).status).toBe(202);
      await waitFor(async () => {
        const b = await getBot(created.id);
        return !!b && !b.busy && b.messages.some((m: Msg) => m.kind === "digest");
      }, "the turn to settle with a digest");
      return getBot(created.id);
    },
  };
}

posixOnly("engine hooks e2e (fake Claude honouring the settings hooks)", () => {
  const h = harness("on", {});

  it("delivers full tool results through PostToolUse: spilled to a private file, attached to the activity row, digest evidence full", async () => {
    const bot = await h.runTurn();
    const tools: Msg[] = bot.messages.filter((m: Msg) => m.kind === "activity" && m.tool);
    expect(tools.map((m) => m.tool!.name)).toEqual(["Bash", "Read"]);
    for (const row of tools) {
      expect(row.tool!.itemId).toBeTruthy();
      expect(row.tool!.fullResult).toBe(true);
      expect(row.tool).not.toHaveProperty("outputPath");
    }
    expect(JSON.stringify(tools)).not.toContain(h.home());
    const root = join(h.home(), ".openmausbot", "tool-results");
    const threads = readdirSync(root);
    expect(threads).toHaveLength(1);
    const dir = join(root, threads[0]!);
    const files = readdirSync(dir).map((name) => join(dir, name));
    expect(files).toHaveLength(2);
    for (const file of files) expect(statSync(file).mode & 0o777).toBe(0o600);
    const bash = tools[0]!.tool!;
    const spilled = files.map((file) => readFileSync(file, "utf8")).find((text) => text.startsWith("line "))!;
    expect(spilled.length).toBeGreaterThan(10_000);
    expect(spilled).toContain(BIG.slice(0, 200));
    expect((bash.output ?? "").length).toBeLessThan(7_000);
    const digest: Msg = bot.messages.find((m: Msg) => m.kind === "digest");
    expect(digest.digest?.hookCoverage).toBe("full");
    expect(digest.text).not.toContain("from tool previews");
  }, 60_000);

  it("refuses a hook call whose bearer is not a live hooks capability", async () => {
    const forged = await h.api("POST", "/api/internal/hook", { event: "PostToolUse", payload: { tool_use_id: "x" } }, { authorization: "Bearer not-a-real-token" });
    expect(forged.status).toBe(401);
  });
});

posixOnly("engine hooks e2e: full tool output that arrives after its turn ended", () => {
  const h = harness("late", {}, { FAKE_CLAUDE_HOOKS_AFTER_TURN_MS: "4000" });

  it("is still saved on that turn's rows, each once, and the ended turn's bearer is good for nothing else", async () => {
    const bot = await h.runTurn();
    expect(bot.messages.find((m: Msg) => m.kind === "digest").digest?.hookCoverage).toBe("preview");
    const rows = async (): Promise<Msg[]> => (await h.getBot(bot.id)).messages.filter((m: Msg) => m.kind === "activity" && m.tool?.itemId);
    const tokenDir = createHash("sha256").update(`${bot.id}\0${bot.threadId}`).digest("hex").slice(0, 24);
    const bearer = { authorization: `Bearer ${readFileSync(join(h.home(), ".openmausbot", "hook-tokens", tokenDir, "token"), "utf8").trim()}` };

    // While the late outputs are still owed, the ended turn's bearer writes only into its own bot and conversation.
    const owed = (await rows()).find((m) => m.tool!.fullResult !== true)!;
    for (const named of [{ botId: "another-bot" }, { fromBotId: "another-bot" }, { threadId: "another-thread" }, { fromThreadId: "another-thread" }]) {
      const forged = await h.api("POST", "/api/internal/hook", { event: "PostToolUse", payload: { tool_use_id: owed.tool!.itemId, tool_response: "forged" }, ...named }, bearer);
      expect(forged.status, JSON.stringify(named)).toBe(403);
    }
    await h.waitFor(async () => (await rows()).every((m) => m.tool!.fullResult === true), "the late hooks to save both outputs");
    const digest = (await h.getBot(bot.id)).messages.find((m: Msg) => m.kind === "digest");
    expect(digest.digest?.hookCoverage).toBe("full");
    expect(digest.text).not.toContain("from tool previews");
    const root = join(h.home(), ".openmausbot", "tool-results");
    const spilled = readdirSync(join(root, readdirSync(root)[0]!)).map((name) => readFileSync(join(root, readdirSync(root)[0]!, name), "utf8"));
    expect(spilled.some((text) => text.includes(BIG.slice(0, 200)))).toBe(true);
    expect(spilled.some((text) => text.includes("forged"))).toBe(false);

    const [first] = await rows();
    const again = await h.api("POST", "/api/internal/hook", { event: "PostToolUse", payload: { tool_use_id: first!.tool!.itemId, tool_response: "replaced" } }, bearer);
    expect(again.status).toBe(401);
    expect((await h.api("POST", "/api/internal/hook", { event: "PreCompact", payload: { trigger: "auto" } }, bearer)).status).toBe(401);
  }, 60_000);
});

posixOnly("engine hooks e2e: compaction", () => {
  const h = harness("compact", {}, { FAKE_CLAUDE_COMPACT: "1" });

  it("records the compaction in the transcript and hands the latest digests back to the engine as plain-text context", async () => {
    const bot = await h.runTurn();
    // The fake runs PreCompact then SessionStart(compact) at the start of its second turn, so run one more turn.
    expect((await h.api("POST", `/api/bots/${bot.id}/messages`, { text: "and again, after compaction" })).status).toBe(202);
    await h.waitFor(async () => {
      const b = await h.getBot(bot.id);
      return !b.busy && b.messages.filter((m: Msg) => m.kind === "digest").length >= 2;
    }, "the second turn to settle with its digest");
    const after = await h.getBot(bot.id);
    const chips: Msg[] = after.messages.filter((m: Msg) => m.kind === "activity" && m.tool?.name.startsWith("context compact"));
    expect(chips.map((m) => m.tool!.name)).toEqual([
      "context compaction started (auto)",
      "context compacted — re-sent the last 1 digest",
    ]);
    // Those rows hide with tool calls; the chat also gets one marker people always see, with nothing for the engine.
    const markers: Msg[] = after.messages.filter((m: Msg) => m.kind === "compaction");
    expect(markers).toHaveLength(1);
    expect(markers[0]).toMatchObject({ role: "bot", engineCompaction: true });
    expect(markers[0]!.compaction).toBeUndefined();
    // The fake echoes what SessionStart's stdout gave it: the first turn's digest line.
    const replies: Msg[] = after.messages.filter((m: Msg) => m.role === "bot" && m.kind === "text" && m.text);
    expect(replies.at(-1)!.text).toContain("[What ");
    expect(replies.at(-1)!.text).toContain("did in an earlier turn");
    expect(replies.at(-1)!.text).toContain("Bash ×1");
  }, 90_000);
});

posixOnly("engine hooks e2e: a shell call that hit its time limit", () => {
  const dumpDir = mkdtempSync(join(tmpdir(), "omb-hooks-timeout-dump-"));
  const dump = join(dumpDir, "turn.json");
  afterAll(() => removeTempDir(dumpDir));
  const h = harness("timeout", {}, {
    FAKE_CLAUDE_DUMP: dump,
    FAKE_CLAUDE_TOOL_CALLS: JSON.stringify([
      { name: "Bash", input: { command: "ffmpeg -i talk.mp3 -ar 16000 talk.wav" }, ok: false, output: "Exit code 143\nCommand timed out after 2m 0s" },
      { name: "Bash", input: { command: "find / -iname 'ggml-*.bin'" }, ok: false, output: "Exit code 143\nCommand timed out after 2m 0s" },
      { name: "Bash", input: { command: "false" }, ok: false, output: "Exit code 1" },
    ]),
  });

  it("tells the engine how to rerun it, and the prompt said so up front", async () => {
    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 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("86400000");
  }, 60_000);
});

posixOnly("engine hooks e2e with OMB_HOOKS=0", () => {
  const h = harness("off", { OMB_HOOKS: "0" });

  it("registers nothing: rows keep only previews and the digest says so", async () => {
    const bot = await h.runTurn();
    const tools: Msg[] = bot.messages.filter((m: Msg) => m.kind === "activity" && m.tool);
    expect(tools.length).toBe(2);
    for (const row of tools) {
      expect(row.tool!.fullResult).toBeUndefined();
      expect(row.tool).not.toHaveProperty("outputPath");
    }
    const digest: Msg = bot.messages.find((m: Msg) => m.kind === "digest");
    expect(digest.digest?.hookCoverage).toBe("preview");
  }, 60_000);
});