Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
// A wait's follow-up is the work of the person whose own turn set the wait, on a real personal Cloud and a real Team
// Cloud, with the fake engine: the level each turn really got, read from what the engine was started with. A routine the
// follow-up makes keeps its shell; one an outside event's run makes still does not.
import { randomBytes } from "node:crypto";
import { readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";
import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts";
import { WAIT_MESSAGES } from "./routes/waits.ts";
import { hostTimeout } from "./testing/host-timeout.ts";
const tag = randomBytes(6).toString("hex");
const dump = join(tmpdir(), `wait-lineage-${tag}.json`), release = join(tmpdir(), `wait-lineage-${tag}.release`),
holding = join(tmpdir(), `wait-lineage-${tag}.holding`), held = join(tmpdir(), `wait-lineage-${tag}.held`);
// A turn started while `holding` is there ends on `held`, every other on `release`: one bot stays busy while another's turn ends.
const engine = `const { existsSync: __has } = await import("node:fs"); process.env.FAKE_CLAUDE_MODE = "hang"; process.env.FAKE_CLAUDE_DUMP = ${JSON.stringify(dump)}; process.env.FAKE_CLAUDE_RELEASE = __has(${JSON.stringify(holding)}) ? ${JSON.stringify(held)} : ${JSON.stringify(release)};`;
const KEY = randomBytes(16).toString("hex");
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const read = () => { try { return JSON.parse(readFileSync(dump, "utf8")); } catch { return null; } };
async function until<V>(what: string, fn: () => Promise<V> | V, ms = hostTimeout(40_000)): Promise<V> {
const end = Date.now() + ms;
for (;;) {
const value = await fn();
if (value) return value;
if (Date.now() > end) throw new Error(`timed out: ${what}`);
await sleep(100);
}
}
type Turn = { argv: string[]; mcpConfig: { mcpServers: { agents: { env: { OMB_COMMS_TOKEN: string } } } } };
const turnWith = async (marker: string): Promise<Turn> => (await until(`a turn with ${marker}`, () => { const turn = read(); return turn && JSON.stringify(turn.prompt ?? "").includes(marker) ? turn as Turn : null; }))!;
const confined = (turn: Turn) => turn.argv.includes("--restricted");
const atFull = (turn: Turn) => turn.argv[turn.argv.indexOf("--permission-mode") + 1] === "bypassPermissions";
const tokenOf = (turn: Turn) => turn.mcpConfig.mcpServers.agents.env.OMB_COMMS_TOKEN;
type Api = (method: string, path: string, body?: unknown) => Promise<{ status: number; body: any }>;
/** One Cloud, as one signed-in person: its routes, and the routes a bot's own turn calls. */
function home(base: string, as: Api, capability: (botId: string, threadId: string) => Promise<string>) {
const internal = async (botId: string, threadId: string, path: string, body: object, token?: string) => {
const bearer = token ?? await capability(botId, threadId);
const response = await fetch(`${base}${path}?fromBotId=${botId}`, { method: "POST", headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json" }, body: JSON.stringify({ fromBotId: botId, fromThreadId: threadId, ...body }) });
return { status: response.status, body: await response.json().catch(() => null) as any };
};
const runs = async () => (await as("GET", "/api/routines")).body.runs as any[];
const idle = (...ids: string[]) => until(`${ids} idle`, async () => {
const bots = (await as("GET", "/api/bots")).body.bots as any[];
return ids.every((id) => !bots.find((bot) => bot.id === id)?.busy);
});
const finish = async (...ids: string[]) => {
writeFileSync(release, ""); writeFileSync(held, "");
await idle(...ids);
await sleep(300);
for (const file of [release, held, holding, dump]) rmSync(file, { force: true });
};
/** The routine a turn in `threadId` makes, run at once: the turn that run got. */
const routineMadeIn = async (botId: string, threadId: string, marker: string, token?: string) => {
const made = await internal(botId, threadId, "/api/internal/trigger-requests", { action: "create", kind: "schedule", routine: { name: `Made by ${marker}`, instructions: marker, schedule: { type: "interval", everyMinutes: 60 } } }, token);
expect(made.body?.state, JSON.stringify(made.body)).toBe("applied");
const id = made.body.result.resultId as string;
return { id, started: () => internal(botId, threadId, "/api/internal/trigger-requests", { action: "run_now", triggerId: id }, token) };
};
/**
* `waiter` is asked by this person, sets a wait for `busy` to finish with a follow-up, and both turns end: the
* follow-up's own turn, running. Needs both bots idle.
*/
const followUpOfAWait = async (waiter: { id: string; threadId: string }, busy: { id: string; name: string; threadId: string }, marker: string, send: Api = as) => {
writeFileSync(holding, "");
expect((await send("POST", `/api/bots/${busy.id}/messages`, { text: `${marker}-busy`, threadId: busy.threadId })).status).toBe(202);
await turnWith(`${marker}-busy`);
rmSync(holding, { force: true });
expect((await send("POST", `/api/bots/${waiter.id}/messages`, { text: `${marker}-asked`, threadId: waiter.threadId })).status).toBe(202);
const asked = await turnWith(`${marker}-asked`);
const set = await internal(waiter.id, waiter.threadId, "/api/internal/waits", { label: marker, kind: "bot_idle", bot: busy.name, follow_up: `${marker}-follow-up` }, tokenOf(asked));
expect(set.status, JSON.stringify(set.body)).toBe(201);
writeFileSync(release, "");
await idle(waiter.id);
rmSync(release, { force: true });
rmSync(dump, { force: true });
writeFileSync(held, "");
const turn = await turnWith(`${marker}-follow-up`);
rmSync(held, { force: true });
const run = await until("the follow-up's run", async () => (await runs()).find((one) => one.eventSource === "wait" && one.routineName === marker && one.threadId));
return { turn, run, thread: run.threadId as string, asked };
};
return { internal, runs, idle, finish, routineMadeIn, followUpOfAWait };
}
let fx: CloudSendFixture, team: CloudTeamFixture, ada: string, ben: string;
beforeAll(async () => {
fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-${randomBytes(8).toString("hex")}`, cloudEngine: engine, desktopEngine: engine, env: { OMB_TEST_INTERNAL_CAPABILITY_KEY: KEY },
team: { id: "team-acme-1", name: "Acme", engine } });
team = fx.team!;
ada = (await team.pair({ email: "[email protected]", role: "admin" })).token!;
ben = (await team.pair({ email: "[email protected]", role: "member" })).token!;
}, hostTimeout(180_000));
afterAll(async () => {
writeFileSync(release, ""); writeFileSync(held, "");
await sleep(500);
await fx?.close?.();
for (const file of [dump, release, holding, held]) rmSync(file, { force: true });
});
describe("a personal Cloud only its owner has used", () => {
it("keeps the shell for a routine the follow-up of the owner's own wait makes, and takes it from one a webhook's run makes", async () => {
const cloud = fx.onCloud, at = home(fx.cloudBase, cloud, async (botId, threadId) => ((await (await fetch(`${fx.cloudBase}/api/testing/internal-capability`, { method: "POST",
headers: { "content-type": "application/json", "x-openmausbot-test-capability": KEY }, body: JSON.stringify({ botId, threadId }) })).json()) as { token: string }).token);
const bot = async (name: string) => {
const made = (await cloud("POST", "/api/bots", { name })).body.bot as { id: string; name: string; threadId: string };
expect((await cloud("PATCH", `/api/bots/${made.id}`, { approvalMode: "full", applyToAllThreads: true })).status).toBe(200);
return made;
};
const scout = await bot("Wait scout"), mate = await bot("Wait mate");
const writers = () => JSON.parse(readFileSync(join(fx.root, "cloud", ".openmausbot", "lending-routines.json"), "utf8")).writers as Record<string, string>;
const first = await at.followUpOfAWait(scout, mate, "owners-wait");
expect(first.run).toMatchObject({ triggerSource: "webhook", eventSource: "wait", waitSetBy: "owner" });
expect(confined(first.turn)).toBe(false);
const made = await at.routineMadeIn(scout.id, first.thread, "routine-after-owners-wait");
expect(writers()[made.id]).not.toBe(CLOUD_OUTSIDE_KEY);
await at.finish(scout.id, mate.id);
expect((await made.started()).status).toBe(201);
const ran = await turnWith("routine-after-owners-wait");
expect(confined(ran)).toBe(false);
expect(atFull(ran)).toBe(true);
await at.finish(scout.id, mate.id);
// A bot changing it from another such follow-up leaves it as it was: still with its shell.
const second = await at.followUpOfAWait(scout, mate, "owners-second-wait");
const changed = await at.internal(scout.id, second.thread, "/api/internal/trigger-requests", { action: "update", triggerId: made.id, changes: { instructions: "routine-changed-after-wait" } });
expect(changed.body?.state, JSON.stringify(changed.body)).toBe("applied");
expect(writers()[made.id]).not.toBe(CLOUD_OUTSIDE_KEY);
// The follow-up's own run cannot set the next wait on a Cloud: no chain of waits starts here.
expect(await at.internal(scout.id, second.thread, "/api/internal/waits", { label: "again", kind: "bot_idle", bot: mate.name, follow_up: "again-follow-up" }, tokenOf(second.turn)))
.toMatchObject({ status: 403, body: { error: WAIT_MESSAGES.notPerson } });
await at.finish(scout.id, mate.id);
expect((await made.started()).status).toBe(201);
expect(confined(await turnWith("routine-changed-after-wait"))).toBe(false);
await at.finish(scout.id, mate.id);
// A webhook's run: it sets no wait at all, and the routine it makes is outside work's, as before.
const hook = (await cloud("POST", "/api/webhooks", { name: "Wait hook", prompt: "Handle the event.", botId: scout.id })).body;
const receiver = fx.cloudBase.replace(/:(\d+)$/, (_: string, port: string) => `:${Number(port) + 1}`);
expect((await fetch(`${receiver}/hooks/${hook.webhook.endpointId}/${encodeURIComponent(hook.credential.secret)}`, { method: "POST", headers: { "content-type": "application/json", "idempotency-key": randomBytes(6).toString("hex") }, body: JSON.stringify({ text: "marker-wait-hook" }) })).status).toBe(202);
const hooked = await turnWith("marker-wait-hook");
const hookThread = (await until("the webhook's run", async () => (await at.runs()).find((run) => run.webhookId === hook.webhook.id && run.threadId))).threadId as string;
expect(await at.internal(scout.id, hookThread, "/api/internal/waits", { label: "from outside", kind: "bot_idle", bot: mate.name, follow_up: "outside-follow-up" }, tokenOf(hooked)))
.toMatchObject({ status: 403, body: { error: WAIT_MESSAGES.notPerson } });
const outside = await at.routineMadeIn(scout.id, hookThread, "routine-after-webhook");
expect(writers()[outside.id]).toBe(CLOUD_OUTSIDE_KEY);
expect((await outside.started()).status).toBe(201);
expect(confined(await turnWith("routine-after-webhook"))).toBe(true);
await at.finish(scout.id, mate.id);
}, hostTimeout(240_000));
});
describe("a Team Cloud", () => {
it("runs a member's wait follow-up and the routine it makes with the shell, as the member's and never the owner's", async () => {
const at = home(team.base, (method, path, body) => team.as(ada, method, path, body), (botId, threadId) => team.capability(botId, threadId));
const asBen: Api = (method, path, body) => team.as(ben, method, path, body);
const bot = async (name: string) => {
const made = (await team.as(ada, "POST", "/api/bots", { name, visibility: "everyone" })).body.bot as { id: string; name: string; threadId: string };
expect((await team.as(ada, "PATCH", `/api/bots/${made.id}`, { approvalMode: "full", applyToAllThreads: true })).status).toBe(200);
return made;
};
const scout = await bot("Team wait scout"), mate = await bot("Team wait mate");
const own = async (of: { id: string; name: string }, title: string) => ({ ...of, threadId: (await asBen("POST", `/api/bots/${of.id}/tasks`, { title })).body.task.threadId as string });
const writers = () => JSON.parse(readFileSync(join(team.home, ".openmausbot", "lending-routines.json"), "utf8")).writers as Record<string, string>;
const follow = await at.followUpOfAWait(await own(scout, "Ben asks"), await own(mate, "Ben's busy work"), "members-wait", asBen);
expect(follow.run).toMatchObject({ eventSource: "wait", waitSetBy: "person" });
expect(confined(follow.turn)).toBe(false);
const made = await at.routineMadeIn(scout.id, follow.thread, "routine-after-members-wait");
expect(writers()[made.id]).toBe(CLOUD_NOBODY_KEY);
await at.finish(scout.id, mate.id);
expect((await made.started()).status).toBe(201);
expect(confined(await turnWith("routine-after-members-wait"))).toBe(false);
await at.finish(scout.id, mate.id);
}, hostTimeout(240_000));
});