Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Team: a member's own MausBot's main chat is theirs alone, and its notes go to their layer
milind-soni891d312b277d
diff --git a/server/cloud-team-mausbot-own-chat.e2e.test.ts b/server/cloud-team-mausbot-own-chat.e2e.test.tsnew file mode 100644index 0000000000..fdf6e5be50--- /dev/null+++ b/server/cloud-team-mausbot-own-chat.e2e.test.ts@@ -0,0 +1,96 @@+// A Team Cloud member's own MausBot: its main chat is theirs alone, on a Team Cloud with the synthetic Claude CLI. No+// admin or other member reads it through any route, and its notes go to the person's own layer. A MausBot made before+// this gets the same at the next start, its earlier notes moved out of the bot's own folder.+import { randomBytes } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { afterAll, beforeAll, expect, it } from "vitest";++import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { personKey } from "./person-key.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const OLIVE = { email: "[email protected]", role: "owner" as const };+const MIRA = { email: "[email protected]", role: "member" as const };+const BEN = { email: "[email protected]", role: "member" as const };+const ENGINE = `process.env.FAKE_CLAUDE_ROOM_PLAN = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/plan.json";`;+const SAID = "MAIN-CHAT-LINE Kestrel19";+const NOTE = "Mira prefers the Kestrel19 supplier";+const OLD_NOTE = "Ben's old note Heron77";++type Task = { threadId: string; private?: true };+type Bot = { id: string; threadId: string; defaultBot?: { person?: string }; tasks?: Task[] };++let fx: CloudSendFixture, team: CloudTeamFixture;+let olive = "", mira = "", ben = "";++const planPath = () => join(team.home, "plan.json");+const dataDir = (...rest: string[]) => join(team.home, ".openmausbot", ...rest);+const turns = (): Array<{ planKey?: string }> => existsSync(`${planPath()}.evidence.jsonl`)+ ? readFileSync(`${planPath()}.evidence.jsonl`, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [];+const botsOf = async (token: string, messages = "") => (await team.as(token, "GET", `/api/bots${messages}`)).body.bots as Bot[];+const ownMausBot = async (token: string) => (await botsOf(token)).find((bot) => bot.defaultBot?.person)!;+const layer = (bot: Bot, email: string) => dataDir("workspaces", `${bot.id}--member-${personKey({ id: "", email })}`, "MEMORY.md");+const read = (path: string) => (existsSync(path) ? readFileSync(path, "utf8") : "");+/** Everything a person can fetch about a bot and its main chat, in one string. */+async function everything(token: string, bot: Bot): Promise<string> {+ const paths = ["/api/bots", "/api/bots?messages=1", `/api/bots/${bot.id}`, `/api/threads/${bot.threadId}/messages?limit=200`,+ `/api/bots/${bot.id}/memory`, `/api/bots/${bot.id}/memory/file`, `/api/bots/${bot.id}/memory/journal`, `/api/bots/${bot.id}/memory/mine`,+ "/api/search?q=Kestrel19", "/api/search?q=Heron77", `/api/bots/${bot.id}/tasks`, "/api/notifications", "/api/inbox"];+ const answers = await Promise.all(paths.map(async (path) => JSON.stringify((await team.as(token, "GET", path)).body)));+ return answers.join("\n");+}++beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-6", name: "Acme", engine: ENGINE } });+ team = fx.team!;+ olive = (await team.pair(OLIVE)).token!;+ mira = (await team.pair(MIRA)).token!;+ ben = (await team.pair(BEN)).token!;+}, hostTimeout(120_000));++afterAll(async () => {+ await fx?.close();+});++it("is the person's own: private on the wire, its notes in their layer, and nobody else reads it through any route", async () => {+ const maus = await ownMausBot(mira);+ expect(maus.tasks!.find((task) => task.threadId === maus.threadId)?.private, "her main chat is marked hers").toBe(true);+ writeFileSync(planPath(), JSON.stringify({ [maus.id]: { script: [+ { key: "M-NOTE", repeat: true, match: ["MAIN-CHAT-LINE"], reply: "Noted Kestrel19.", steps: [{ tool: "memory_update", arguments: { action: "append", text: NOTE } }] },+ ] } }));+ expect((await team.as(mira, "POST", `/api/bots/${maus.id}/messages`, { text: SAID, threadId: maus.threadId })).status).toBe(202);+ await expect.poll(() => turns().some((one) => one.planKey === "M-NOTE"), { timeout: 60_000 }).toBe(true);+ await expect.poll(() => read(layer(maus, MIRA.email)), { timeout: 30_000 }).toContain(NOTE);+ expect(read(dataDir("workspaces", maus.id, "MEMORY.md"))).not.toContain(NOTE);++ expect(await everything(mira, maus)).toContain("Kestrel19");+ expect((await team.as(olive, "GET", `/api/threads/${maus.threadId}/messages?limit=1`)).status, "the Owner").toBe(404);+ expect((await team.as(ben, "GET", `/api/threads/${maus.threadId}/messages?limit=1`)).status, "another member").toBe(404);+ for (const token of [olive, ben]) expect(await everything(token, maus)).not.toContain("Kestrel19");+}, hostTimeout(120_000));++it("a MausBot made before this: at the next start its main chat becomes its person's and its earlier notes move to their layer", async () => {+ const maus = await ownMausBot(ben);+ expect((await team.as(ben, "POST", `/api/bots/${maus.id}/messages`, { text: "NO-SCRIPT Heron77 hello", threadId: maus.threadId })).status).toBe(202);+ await expect.poll(async () => JSON.stringify((await team.as(ben, "GET", `/api/threads/${maus.threadId}/messages?limit=50`)).body), { timeout: 60_000 }).toContain("Heron77");+ // As an earlier version left it: no person for the main chat, and a note in the bot's own folder.+ const starters = JSON.parse(readFileSync(dataDir("thread-starters.json"), "utf8")) as Record<string, string>;+ delete starters[maus.threadId];+ writeFileSync(dataDir("thread-starters.json"), JSON.stringify(starters));+ mkdirSync(dataDir("workspaces", maus.id), { recursive: true });+ writeFileSync(dataDir("workspaces", maus.id, "MEMORY.md"), `# Memory\n\n- ${OLD_NOTE}\n`);+ mkdirSync(dataDir("memory-journal"), { recursive: true });+ writeFileSync(dataDir("memory-journal", `${maus.id}.ndjson`), `${JSON.stringify({ id: "old-1", botId: maus.id, at: Date.now(), path: "MEMORY.md", actor: "bot", after: OLD_NOTE })}\n`);++ await team.relaunch();+ olive = (await team.pair(OLIVE)).token!;+ ben = (await team.pair(BEN)).token!;+ await expect.poll(() => read(layer(maus, BEN.email)), { timeout: 30_000 }).toContain(OLD_NOTE);+ expect(read(dataDir("workspaces", maus.id, "MEMORY.md"))).not.toContain(OLD_NOTE);+ expect(read(dataDir("memory-journal", `${maus.id}.ndjson`))).not.toContain(OLD_NOTE);+ expect((await ownMausBot(ben)).tasks!.find((task) => task.threadId === maus.threadId)?.private).toBe(true);+ expect(await everything(ben, maus)).toContain("Heron77");+ expect((await team.as(olive, "GET", `/api/threads/${maus.threadId}/messages?limit=1`)).status).toBe(404);+ expect(await everything(olive, maus)).not.toContain("Heron77");+}, hostTimeout(180_000));diff --git a/server/host/mausbot-own-chat.test.ts b/server/host/mausbot-own-chat.test.tsnew file mode 100644index 0000000000..e0d41269cc--- /dev/null+++ b/server/host/mausbot-own-chat.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from "vitest";++import { createMausBotOwnChat } from "./mausbot-own-chat.ts";++const key = (email: string) => `key:${email}`;+function world(starters: Record<string, string> = {}) {+ const moved: string[] = [];+ const bots = [+ { id: "maus-mira", threadId: "t-mira", defaultBot: { person: "[email protected]" } },+ { id: "maus-place", threadId: "t-place", defaultBot: {} },+ { id: "sales", threadId: "t-sales" },+ ];+ const own = createMausBotOwnChat({+ bots: () => bots,+ starters: { get: (threadId) => starters[threadId], set: (threadId, person) => { starters[threadId] = person; } },+ personKey: key,+ moveNotes: async (from, to) => { moved.push(`${from} -> ${to}`); },+ });+ return { own, starters, moved, bots };+}++describe("a member's own MausBot's main chat", () => {+ it("becomes its person's, and its notes move to their layer", async () => {+ const w = world();+ expect(await w.own.claimAll()).toBe(1);+ expect(w.starters).toEqual({ "t-mira": "key:[email protected]" });+ expect(w.moved).toEqual(["maus-mira -> maus-mira--member-key:[email protected]"]);+ });++ it("is marked theirs before anything waits on the notes", () => {+ const w = world();+ void w.own.claim(w.bots[0]!);+ expect(w.starters["t-mira"]).toBe("key:[email protected]");+ });++ it("leaves a chat that already has its person, a place's own MausBot and every other bot alone", async () => {+ const w = world({ "t-mira": "key:someone" });+ expect(await w.own.claimAll()).toBe(0);+ expect(w.own.claim(w.bots[1]!)).toBeNull();+ expect(w.own.claim(w.bots[2]!)).toBeNull();+ expect(w.starters).toEqual({ "t-mira": "key:someone" });+ expect(w.moved).toEqual([]);+ });+});diff --git a/server/host/mausbot-own-chat.ts b/server/host/mausbot-own-chat.tsnew file mode 100644index 0000000000..bc3ecdf75d--- /dev/null+++ b/server/host/mausbot-own-chat.ts@@ -0,0 +1,31 @@+// A Team Cloud member's own MausBot: its main chat is that person's, the way a chat they open is. Security: so it is+// private to them, an admin included, and the notes it wrote into the bot's own folder before (which anyone who sees+// the bot may read) move to their own layer the first time.+import { layerId, memberAudience } from "../audience.ts";+import { defaultBotPerson, type DefaultBotFields } from "../../shared/default-bot.ts";++export interface MausBotOwnChatDeps {+ bots(): ReadonlyArray<{ id: string; threadId: string } & DefaultBotFields>;+ starters: { get(threadId: string): string | undefined; set(threadId: string, person: string): void };+ personKey(email: string): string;+ moveNotes(from: string, to: string): Promise<unknown>;+}++export function createMausBotOwnChat(deps: MausBotOwnChatDeps) {+ /** Marks the main chat as its person's at once; the notes follow, before anything else writes there. */+ const claim = (bot: { id: string; threadId: string } & DefaultBotFields): Promise<unknown> | null => {+ const email = defaultBotPerson(bot);+ if (!email || deps.starters.get(bot.threadId) !== undefined) return null;+ const person = deps.personKey(email);+ deps.starters.set(bot.threadId, person);+ return deps.moveNotes(bot.id, layerId(bot.id, memberAudience(person)));+ };+ return {+ claim,+ /** At start, for the MausBots made before their main chat was their person's. */+ claimAll(): Promise<number> {+ const moving = deps.bots().map(claim).filter((move): move is Promise<unknown> => move !== null);+ return Promise.all(moving).then(() => moving.length);+ },+ };+}diff --git a/server/index.ts b/server/index.tsindex 8104d276fa..138529fcba 100644--- a/server/index.ts+++ b/server/index.ts@@ -295,7 +295,7 @@ import { createLiveApprovalMode } from "./host/live-approval.ts";import { CONSENT_RULE, escapeNotes, labelledLine, OUTSIDE, peerLineText, peerProvenanceNote, reportNote, requestWorkOrigin, type WorkOrigin } from "./peer-provenance.ts"; import { lineNote, PROVENANCE_PROMPT } from "./provenance-label.ts"; import { openRoomThread } from "./host/room-new-thread.ts"; import { createLineLabels } from "./host/line-labels.ts";import { decideRoomPost, emptyRoomPostBudget, type RoomPostAttempt, type RoomPostBudget } from "./room-post-budget.ts";import { messagePages, pageSize, slimMessage } from "./host/message-pages.ts";-import { createTeammatePrompts } from "./host/teammate-prompts.ts";+import { createTeammatePrompts } from "./host/teammate-prompts.ts"; import { createMausBotOwnChat } from "./host/mausbot-own-chat.ts"; import { moveMemoryLayer } from "./memory-move.ts";import { createQueuedReason } from "./host/queued-reason.ts";import { ReplayBuffer } from "./host/sse-replay.ts";import {@@ -947,7 +947,7 @@ let cloudEarlierOwners: Pick<CloudOwnership, "adopted" | "proven"> = { adopted:/** Until it is settled, a Cloud home counts as shared. */let cloudHome: ReturnType<typeof settleCloudHome> | null = null; const teamHost = createCloudTeamHost({ team: CLOUD_TEAM, dataDir: DATA_DIR, store: { groupByThread: (threadId) => store.groupByThread(threadId), get bots() { return store.bots; } }, engineHomes, starters: threadStarters, markers: new Set([CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY]), language: appLanguage,serverProfile: { read: () => cfg.profile, clear: () => { adminActorScope.exit(() => saveConfig({ profile: { name: "", email: "", aboutMe: "", avatarUrl: "" } })); Object.assign(cfg, loadConfig()); } } });-const teamOwners = createTeamOwners({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store: () => store, audienceOf: (threadId) => teamHost.audienceOf(threadId), starters: threadStarters });+const teamOwners = createTeamOwners({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store: () => store, audienceOf: (threadId) => teamHost.audienceOf(threadId), starters: threadStarters }); const mausbotOwnChat = createMausBotOwnChat({ bots: () => store.bots, starters: threadStarters, personKey: (email) => personKey({ id: "", email }), moveNotes: (from, to) => moveMemoryLayer(from, to, appLanguage()) });const personRooms = createPersonRooms({ reads: CLOUD_TEAM ? createRoomReads(DATA_DIR) : null, store: () => store, newestMessageId: (threadId) => readCursor(threadId).lastReadMessageId, publicGroupState, broadcast });function actorKey(auth: RequestAuth & { kind: "session" }): string {@@ -2936,7 +2936,7 @@ for (const pending of startupCatalogs) {broadcast({ kind: "config", ...configStatus() });}, () => {});}-const firstHourFresh = Boolean(CLOUD_PERSONAL) && store.needsSeed(); testedAi.seed({ defaultBot: !CLOUD_TEAM, ...(firstHourFresh ? { intro: (bot) => greetingMessage(bot, { name: cfg.profile?.name }, cfg.language) } : {}) }); moveFreeze.hold(() => { if (!CLOUD_TEAM) ensureDefaultBot(store, { dataDir: DATA_DIR }); }, () => {}); if (CLOUD_TEAM) readTeamRolesWith((email) => sessions.list().filter((session) => session.email?.toLowerCase() === email && session.teamRole).sort((a, b) => b.createdAt - a.createdAt)[0]?.teamRole ?? null);+const firstHourFresh = Boolean(CLOUD_PERSONAL) && store.needsSeed(); testedAi.seed({ defaultBot: !CLOUD_TEAM, ...(firstHourFresh ? { intro: (bot) => greetingMessage(bot, { name: cfg.profile?.name }, cfg.language) } : {}) }); moveFreeze.hold(() => { if (!CLOUD_TEAM) ensureDefaultBot(store, { dataDir: DATA_DIR }); }, () => {}); if (CLOUD_TEAM) readTeamRolesWith((email) => sessions.list().filter((session) => session.email?.toLowerCase() === email && session.teamRole).sort((a, b) => b.createdAt - a.createdAt)[0]?.teamRole ?? null); if (CLOUD_TEAM) void mausbotOwnChat.claimAll();hostedModels?.reconcile(store);if (skillsLibraryEnabled(cfg)) {try {@@ -12279,7 +12279,7 @@ ROUTES.push(createThreadRoutes({companionMutationToken: () => companionMutationToken,cliOwnerToken: () => cliOwnerToken,pageSize, messagePage, messageWindow, publicBotQueuedMessages, publicGroupState, wireBot,- botComputerControlSnapshot, messageFileRootsForThread, viewerFor, visibleTo, coordinator, groupThreadIsWorking, memberDefaultBot: CLOUD_TEAM ? (email) => ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM.name }) : undefined,+ botComputerControlSnapshot, messageFileRootsForThread, viewerFor, visibleTo, coordinator, groupThreadIsWorking, memberDefaultBot: CLOUD_TEAM ? (email) => { const own = ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM.name }); if (own) void mausbotOwnChat.claim(own); return own; } : undefined,uploads: uploadsFor(createUploadOwners(DATA_DIR), Boolean(CLOUD_TEAM)),attachmentInUse: (name) => threadsReferencing(name).length > 0 || store.bots.some((bot) => bot.avatarUrl === `/api/attachments/${name}`),keptAttachments: CLOUD_TEAM ? undefined : () => { const routineFiles = routines?.attachmentPaths(); return routineFiles && calendarCalls ? keptAttachmentNames([...store.bots.map((bot) => bot.avatarUrl), cfg.profile?.avatarUrl], [workspaceBannerStore.current()?.name, ...routineFiles,diff --git a/server/memory-move.test.ts b/server/memory-move.test.tsnew file mode 100644index 0000000000..b913c7916e--- /dev/null+++ b/server/memory-move.test.ts@@ -0,0 +1,47 @@+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { beforeEach, describe, expect, it } from "vitest";++import { DATA_DIR } from "./config.ts";+import { journalFile, JOURNAL_DIR } from "./memory-journal.ts";+import { moveMemoryLayer } from "./memory-move.ts";+import { ensureWorkspace, isMemorySeed, workspaceDir } from "./workspace.ts";++const at = (layer: string, path: string) => join(workspaceDir(layer), path);+const put = (layer: string, path: string, text: string) => {+ mkdirSync(join(at(layer, path), ".."), { recursive: true });+ writeFileSync(at(layer, path), text);+};++describe("moving one memory layer's notes into another", () => {+ beforeEach(() => {+ rmSync(DATA_DIR, { recursive: true, force: true });+ });++ it("moves the notes, topics, logs and journal, merging with what is there, and leaves an empty memory behind", async () => {+ ensureWorkspace("maus");+ put("maus", "MEMORY.md", "# Memory\n\n- old note\n");+ put("maus", "memory/people.md", "- Ada likes tea\n");+ put("maus", "memory/log/2026-11-01.md", "- talked about tea\n");+ put("maus--member-p", "MEMORY.md", "# Memory\n\n- her own note\n");+ put("maus--member-p", "memory/people.md", "- Ada is in Lisbon\n");+ mkdirSync(JOURNAL_DIR, { recursive: true });+ writeFileSync(journalFile("maus"), `${JSON.stringify({ id: "j1", botId: "maus", at: 1, path: "MEMORY.md", before: "x", canRevert: true })}\n`);++ expect(await moveMemoryLayer("maus", "maus--member-p")).toBe(true);+ expect(readFileSync(at("maus--member-p", "MEMORY.md"), "utf8")).toMatch(/her own note[\s\S]*old note/);+ expect(readFileSync(at("maus--member-p", "memory/people.md"), "utf8")).toMatch(/Lisbon[\s\S]*tea/);+ expect(readFileSync(at("maus--member-p", "memory/log/2026-11-01.md"), "utf8")).toContain("talked about tea");+ expect(isMemorySeed(readFileSync(at("maus", "MEMORY.md"), "utf8"))).toBe(true);+ expect(existsSync(at("maus", "memory/people.md"))).toBe(false);+ expect(existsSync(journalFile("maus"))).toBe(false);+ const row = JSON.parse(readFileSync(journalFile("maus--member-p"), "utf8").trim());+ expect(row).toMatchObject({ id: "j1", botId: "maus--member-p", before: null, canRevert: false });+ });++ it("moves nothing from a memory that holds nothing", async () => {+ ensureWorkspace("empty");+ expect(await moveMemoryLayer("empty", "empty--member-p")).toBe(false);+ expect(await moveMemoryLayer("missing", "missing--member-p")).toBe(false);+ });+});diff --git a/server/memory-move.ts b/server/memory-move.tsnew file mode 100644index 0000000000..cc5c9a1cd1--- /dev/null+++ b/server/memory-move.ts@@ -0,0 +1,68 @@+// Moves one memory layer's notes into another (workspace.ts layers), merging where both hold the same file: MEMORY.md,+// the topics and logs under memory/, and the journal of changes. What moved can't be reverted in its new place, since+// it may have merged with what was there.+import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync } from "node:fs";+import { dirname, join, relative } from "node:path";++import { writeFileAtomic } from "./atomic.ts";+import { flushMemoryJournal, journalFile, JOURNAL_DIR } from "./memory-journal.ts";+import { ensureWorkspace, isMemorySeed, readMemoryText, syncMemoryIndex, workspaceDir } from "./workspace.ts";++const MOVED = "This note moved here from where the bot kept it before, so it can't be reverted here.";++function filesUnder(dir: string): string[] {+ if (!existsSync(dir)) return [];+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) return filesUnder(path);+ return entry.isFile() ? [path] : [];+ });+}++function joined(kept: string, added: string): string {+ return kept.trim() ? `${kept.trimEnd()}\n\n${added.trim()}\n` : added;+}++/** True when anything moved. */+export async function moveMemoryLayer(from: string, to: string, language?: string): Promise<boolean> {+ const source = workspaceDir(from);+ if (!existsSync(source)) return false;+ const target = ensureWorkspace(to, language);+ let moved = false;+ const index = join(source, "MEMORY.md");+ const notes = existsSync(index) ? readMemoryText(index) : "";+ if (notes.trim() && !isMemorySeed(notes)) {+ const into = join(target, "MEMORY.md"), kept = readMemoryText(into);+ writeFileAtomic(into, isMemorySeed(kept) ? notes : joined(kept, notes), { mode: 0o600 });+ rmSync(index, { force: true });+ ensureWorkspace(from, language);+ moved = true;+ }+ for (const file of filesUnder(join(source, "memory"))) {+ if (!statSync(file).size) continue;+ const into = join(target, relative(source, file));+ mkdirSync(dirname(into), { recursive: true, mode: 0o700 });+ if (existsSync(into)) {+ writeFileAtomic(into, joined(readFileSync(into, "utf8"), readFileSync(file, "utf8")), { mode: 0o600 });+ rmSync(file, { force: true });+ } else {+ renameSync(file, into);+ }+ moved = true;+ }+ await flushMemoryJournal(from);+ await flushMemoryJournal(to);+ const journal = journalFile(from);+ if (existsSync(journal)) {+ const rows = readFileSync(journal, "utf8").split("\n").filter(Boolean).flatMap((line) => {+ try { return [JSON.stringify({ ...JSON.parse(line), botId: to, before: null, canRevert: false, revertUnavailableReason: MOVED })]; } catch { return []; }+ });+ mkdirSync(JOURNAL_DIR, { recursive: true, mode: 0o700 });+ if (rows.length) appendFileSync(journalFile(to), `${rows.join("\n")}\n`, { mode: 0o600 });+ rmSync(journal, { force: true });+ moved ||= rows.length > 0;+ }+ syncMemoryIndex(from);+ syncMemoryIndex(to);+ return moved;+}