Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Moves: keep a used MausBot here; the arriving one becomes "MausBot (from <computer>)"
AdityaUmaleb754b3eaefcc
diff --git a/electron/cloud-send-kinds.mjs b/electron/cloud-send-kinds.mjsindex 4715be7bff..f7e0ad9939 100644--- a/electron/cloud-send-kinds.mjs+++ b/electron/cloud-send-kinds.mjs@@ -120,7 +120,8 @@ export function createMoveKinds({ localJson, localBytes, localSend, entry, persiif (!names.length) return {};const held = await localJson(`/api/cloud-send/kind?key=${encodeURIComponent(`bot:${botId}`)}`);const fields = Object.fromEntries(names.map((name) => [name, record(held?.record) && held.record[name] !== undefined ? held.record[name] : null]));- const answer = await ctx.session.call("PUT", "/api/cloud-send/kind", { v: 1, key: `bot:${botId}`, dataDir: held?.dataDir ?? "-", record: fields });+ const answer = await ctx.session.call("PUT", "/api/cloud-send/kind", { v: 1, key: `bot:${botId}`, dataDir: held?.dataDir ?? "-", record: fields,+ ...(typeof held?.computer === "string" && held.computer ? { computer: held.computer } : {}) });return answer.ok ? {} : Object.fromEntries(parts.filter((part) => MOVE_BOT_PARTS[part]).map((part) => [part, refusal(answer, "My Cloud refused this setting.")]));}diff --git a/server/cloud-send-kinds.test.ts b/server/cloud-send-kinds.test.tsindex 7b27fe1711..dc9deaa103 100644--- a/server/cloud-send-kinds.test.ts+++ b/server/cloud-send-kinds.test.ts@@ -179,6 +179,18 @@ describe("My Cloud sets a bot's move-only fields", () => {expect((await take(d, "bot:b1", { soul: "not a move field" })).status).toBe(400);expect((await take(d, "bot:nobody", { pinned: true })).status).toBe(409);});++ it("this computer answers a bot's record with its own name, which a MausBot that moves is named for when the place it goes keeps its own (email 1a1c22b6)", async () => {+ const before = process.env.OMB_ENVIRONMENT_LABEL;+ process.env.OMB_ENVIRONMENT_LABEL = "Amits-MacBook-Pro.local";+ try {+ const answer = await ask(deps("/data"), "GET", `?key=${encodeURIComponent("bot:b1")}`);+ expect(answer).toMatchObject({ status: 200, body: { computer: "Amits-MacBook-Pro" } });+ expect((await ask(deps("/data"), "PUT", "", { v: 1, key: "bot:b1", dataDir: HERE, record: { pinned: true }, computer: "x".repeat(121) })).status).toBe(400);+ } finally {+ if (before === undefined) delete process.env.OMB_ENVIRONMENT_LABEL; else process.env.OMB_ENVIRONMENT_LABEL = before;+ }+ });});describe("skill extras", () => {diff --git a/server/cloud-send-kinds.ts b/server/cloud-send-kinds.tsindex b64f5de052..4a4071f572 100644--- a/server/cloud-send-kinds.ts+++ b/server/cloud-send-kinds.ts@@ -5,6 +5,7 @@// computer go of an app event My Cloud now collects. Admin scope; My Cloud takes an item only over its owner's session.import { createHash } from "node:crypto";import { lstatSync, readdirSync, readFileSync } from "node:fs";+import { hostname } from "node:os";import { join } from "node:path";import { z } from "zod";@@ -19,7 +20,7 @@ import type { AppTriggerManager } from "./app-triggers.ts";import type { CalendarCall, CalendarCallManager } from "./calendar-calls.ts";import type { CloudOwner } from "./cloud-owner-lines.ts";import type { CloudSendItem } from "./cloud-send.ts";-import { retireUnusedStarter, takeArrivingDefaultBot } from "./default-bot.ts";+import { keptDefaultBot, retireUnusedStarter, takeArrivingDefaultBot } from "./default-bot.ts";import { watchAsMade } from "./host/default-watch.ts";import { IMPORTED_SKILLS_DIR, readImportedSkills, storeImportedSkills, type ImportedSkillInput } from "./imported-skills.ts";import type { RequestAuth } from "./request-auth.ts";@@ -265,7 +266,7 @@ const librarySkillSchema = z.object({ text: z.string().max(512 * 1024), entry: z/** My Cloud sets a bot's move-only fields as they are on this computer: absent ones it clears, its own projects it keeps* beside the ones that arrive, and an engine, team or library skill it lacks it leaves out. */-function applyBotFields(deps: MoveKindsDeps, id: string, raw: unknown): void {+function applyBotFields(deps: MoveKindsDeps, id: string, raw: unknown, computer?: string): void {const bot = deps.store.bot(id) ?? refuse(409, "This bot is not on My Cloud yet.");const parsed = botFieldsSchema.safeParse(raw);if (!parsed.success) refuse(400, "send the bot's fields as this computer holds them");@@ -292,11 +293,12 @@ function applyBotFields(deps: MoveKindsDeps, id: string, raw: unknown): void {if (Object.hasOwn(fields, "chiefOfStaff") && fields.chiefOfStaff !== true) patch.chiefOfStaff = fields.chiefOfStaff ?? undefined;if (fields.chiefOfStaff === true) delete patch.hidden;deps.store.patchBot(id, patch);- if (fields.chiefOfStaff === true) {+ // A MausBot arriving where the person's own MausBot stays (takeArrivingDefaultBot) doesn't take that one's crown.+ if (fields.chiefOfStaff === true && !(fields.defaultBot && keptDefaultBot(deps.store, id)?.chiefOfStaff)) {deps.store.setChiefOfStaff(id);if (patch.managedSections) deps.store.patchBot(id, { managedSections: patch.managedSections });}- if (fields.defaultBot) takeArrivingDefaultBot(deps.store, id);+ if (fields.defaultBot) takeArrivingDefaultBot(deps.store, id, computer);retireUnusedStarter(deps.store, deps.dataDir);}@@ -326,10 +328,10 @@ function adoptRoutine(deps: MoveKindsDeps, raw: unknown, runs: unknown, from: stdeps.arrived?.();}-async function adopt(deps: MoveKindsDeps, kind: Kind, id: string, raw: unknown, runs: unknown, from: string, owner: CloudOwner): Promise<void> {+async function adopt(deps: MoveKindsDeps, kind: Kind, id: string, raw: unknown, runs: unknown, from: string, owner: CloudOwner, computer?: string): Promise<void> {if (!record(raw) && kind !== "bot") refuse(400, "send the item's record");const same = (value: unknown) => record(value) && (value.id === undefined || value.id === id);- if (kind === "bot") return applyBotFields(deps, id, raw);+ if (kind === "bot") return applyBotFields(deps, id, raw, computer);if (kind === "routine") return adoptRoutine(deps, raw, runs, from, owner);if (!same(raw) && kind !== "imported-skill" && kind !== "library-skill") refuse(400, "the record names another item");if (kind === "call") {@@ -376,7 +378,13 @@ async function adopt(deps: MoveKindsDeps, kind: Kind, id: string, raw: unknown,}}-const putSchema = z.object({ v: z.literal(1), key: z.string().max(200), dataDir: z.string().min(1).max(4096), record: z.unknown(), runs: z.array(z.unknown()).max(2_000).optional() });+const putSchema = z.object({ v: z.literal(1), key: z.string().max(200), dataDir: z.string().min(1).max(4096), record: z.unknown(), runs: z.array(z.unknown()).max(2_000).optional(),+ computer: z.string().max(120).optional() });++/** This computer's name as a person knows it, which a MausBot that moves away is named for when the place it goes keeps its own. */+function thisComputerName(): string {+ return (process.env.OMB_ENVIRONMENT_LABEL?.trim() || hostname()).replace(/\.local$/iu, "").slice(0, 120);+}/** False when the path is not this route. */export async function moveKindsRoute(deps: MoveKindsDeps, { req, res, path, method, url, auth, json, readBody }: RouteContext): Promise<boolean> {@@ -387,7 +395,7 @@ export async function moveKindsRoute(deps: MoveKindsDeps, { req, res, path, methconst key = parseKey(url.searchParams.get("key"));const found = key && kindRecord(deps, key.kind, key.id);if (!found) json(res, 404, { error: "not here" });- else json(res, 200, { v: 1, dataDir: deps.dataDir, ...found });+ else json(res, 200, { v: 1, dataDir: deps.dataDir, ...(key.kind === "bot" ? { computer: thisComputerName() } : {}), ...found });return true;}if (method === "PUT") {@@ -396,7 +404,7 @@ export async function moveKindsRoute(deps: MoveKindsDeps, { req, res, path, methconst body = putSchema.safeParse(await readBody(req, KIND_BODY_MAX));const key = body.success ? parseKey(body.data.key) : null;if (!body.success || !key) { json(res, 400, { error: "send { v: 1, key, dataDir, record }" }); return true; }- await adopt(deps, key.kind, key.id, body.data.record, body.data.runs, body.data.dataDir, owner);+ await adopt(deps, key.kind, key.id, body.data.record, body.data.runs, body.data.dataDir, owner, body.data.computer);json(res, 200, { v: 1, ok: true });return true;}diff --git a/server/default-bot.test.ts b/server/default-bot.test.tsindex d04969059c..2aeb25837e 100644--- a/server/default-bot.test.ts+++ b/server/default-bot.test.ts@@ -254,11 +254,11 @@ describe("MausBot, every person's helper", () => {const OWNER = { person: "p_owner0000000000000000", name: "Amit" };const deps = (store: Store): MoveKindsDeps => ({ dataDir: DATA_DIR, store, routines: () => null, calls: () => null, webhooks: () => null, appEvents: () => null,claudeCodeSkills: () => [], instanceExists: () => true, owner: () => OWNER, ownRoutine: () => {} } as unknown as MoveKindsDeps);- async function arrive(store: Store, id: string, record: Record<string, unknown>) {+ async function arrive(store: Store, id: string, record: Record<string, unknown>, computer?: string) {let status = 0;await moveKindsRoute(deps(store), { path: "/api/cloud-send/kind", method: "PUT", url: new URL("http://127.0.0.1/api/cloud-send/kind"), auth: {} as never, req: {} as never,res: { setHeader() {} } as never, json: ((_res: unknown, code: number) => { status = code; }) as never,- readBody: (async () => ({ v: 1, key: `bot:${id}`, dataDir: "/Users/amit/.openmausbot", record })) as never });+ readBody: (async () => ({ v: 1, key: `bot:${id}`, dataDir: "/Users/amit/.openmausbot", record, ...(computer ? { computer } : {}) })) as never });return status;}const fields = (bot: Record<string, unknown>) => Object.fromEntries(MOVE_BOT_FIELDS.map((name) => [name, bot[name] ?? null]));@@ -295,14 +295,41 @@ describe("MausBot, every person's helper", () => {expect(cloud.bot(starter.id)?.defaultBot).toBeUndefined();});- it("keeps a My Cloud MausBot someone already used as an ordinary bot", async () => {+ it("keeps a My Cloud MausBot someone already used as the MausBot, and the arriving one becomes an ordinary bot named for its computer (email 1a1c22b6)", async () => {const cloud = new Store(selection);+ cloud.seedIfEmpty();const theirs = boot(cloud)!;cloud.appendMessage(theirs.threadId, { role: "user", kind: "text", text: "Hi" });const arriving = cloud.createBot({ name: "MausBot" }, { id: "desk-maus-000002", seedMessages: false });- expect(await arrive(cloud, arriving.id, fields({ defaultBot: {} }))).toBe(200);- expect(placeMausBots(cloud).map((bot) => bot.id)).toEqual([arriving.id]);+ expect(await arrive(cloud, arriving.id, fields({ defaultBot: {}, sidebarHidden: true }), "Amit's MacBook")).toBe(200);+ expect(placeMausBots(cloud).map((bot) => bot.id)).toEqual([theirs.id]);+ expect(cloud.bot(theirs.id)).toMatchObject({ name: "MausBot", chiefOfStaff: true });expect(cloud.bot(theirs.id)?.hidden).toBeFalsy();+ const moved = cloud.bot(arriving.id)!;+ expect(moved).toMatchObject({ name: "MausBot (from Amit's MacBook)" });+ expect([moved.defaultBot, moved.sidebarHidden, moved.hidden]).toEqual([undefined, undefined, undefined]);+ expect(defaultBotPatchRefusal(moved, { hidden: true })).toBeNull();+ expect(defaultBotPatchRefusal(cloud.bot(theirs.id), { hidden: true })).toContain("can't be deleted or archived");+ expect(boot(cloud)?.id).toBe(theirs.id);+ // A Mac MausBot that was the Chief there doesn't take the crown from the one kept here.+ const chief = cloud.createBot({ name: "MausBot" }, { id: "desk-maus-000006", seedMessages: false });+ expect(await arrive(cloud, chief.id, fields({ defaultBot: {}, chiefOfStaff: true }), "Amit's MacBook")).toBe(200);+ expect(cloud.bots.filter((bot) => bot.chiefOfStaff).map((bot) => bot.id)).toEqual([theirs.id]);+ expect(placeMausBots(cloud).map((bot) => bot.id)).toEqual([theirs.id]);+ });++ it("keeps a used MausBot here and leaves a renamed arriving one its own name, or names an unknown computer plainly", async () => {+ const cloud = new Store(selection);+ const theirs = boot(cloud)!;+ cloud.patchBot(theirs.id, { soul: "Answer in French." });+ const jarvis = cloud.createBot({ name: "Jarvis" }, { id: "desk-maus-000004", seedMessages: false });+ expect(await arrive(cloud, jarvis.id, fields({ defaultBot: {} }), "Amit's MacBook")).toBe(200);+ expect(cloud.bot(jarvis.id)).toMatchObject({ name: "Jarvis" });+ expect(cloud.bot(jarvis.id)?.defaultBot).toBeUndefined();+ const unnamed = cloud.createBot({ name: "MausBot" }, { id: "desk-maus-000005", seedMessages: false });+ expect(await arrive(cloud, unnamed.id, fields({ defaultBot: {} }))).toBe(200);+ expect(cloud.bot(unnamed.id)).toMatchObject({ name: "MausBot (from another computer)" });+ expect(placeMausBots(cloud).map((bot) => bot.id)).toEqual([theirs.id]);});it("comes home to exactly the one MausBot My Cloud had, and makes none", () => {diff --git a/server/default-bot.ts b/server/default-bot.tsindex f264728c49..a67d3a9e2c 100644--- a/server/default-bot.ts+++ b/server/default-bot.ts@@ -135,11 +135,31 @@ export function ensureDefaultBot(store: DefaultBotStore, options: { dataDir: strreturn bot;}-/** A move brought this place's MausBot from another computer: it becomes the one MausBot here, and the one this place- * had becomes an ordinary bot (retireUnusedStarter archives it when nobody used it). */-export function takeArrivingDefaultBot(store: Pick<Store, "bots" | "patchBot">, id: string): void {+/** True once the person has made this bot their own: written to it, opened a second chat, or changed who it is. */+function usedBot(store: Pick<Store, "messagesFor">, bot: BotRecord): boolean {+ if (bot.soul?.trim() || bot.title || bot.description || bot.avatarUrl || (bot.tasks?.length ?? 1) > 1) return true;+ return store.messagesFor(bot.threadId).some((message) => message.role === "user");+}++/** This place's own MausBot that stays the MausBot when another arrives by a move: the visible one the person already used. */+export function keptDefaultBot(store: Pick<Store, "bots" | "messagesFor">, arrivingId: string): BotRecord | undefined {+ return store.bots.find((bot) => bot.id !== arrivingId && bot.defaultBot && !defaultBotPerson(bot) && !bot.hidden && usedBot(store, bot));+}++/** A move brought this place's MausBot from another computer. When nobody used the MausBot this place had, the arriving+ * one becomes the one MausBot here, and the one this place had becomes an ordinary bot (retireUnusedStarter archives it).+ * When this place's own MausBot was used, it stays the MausBot, and the arriving one becomes an ordinary bot that can be+ * deleted, named for the computer it came from so the two are told apart. */+export function takeArrivingDefaultBot(store: Pick<Store, "bots" | "patchBot" | "messagesFor">, id: string, computer?: string): void {const arriving = store.bots.find((bot) => bot.id === id);if (!arriving) return;+ const kept = keptDefaultBot(store, id);+ if (kept) {+ const from = computer?.trim() || "another computer";+ const plain = [DEFAULT_BOT_NAME, kept.name].map((name) => name.trim().toLowerCase()).includes(arriving.name.trim().toLowerCase());+ store.patchBot(id, { defaultBot: undefined, sidebarHidden: undefined, ...(plain ? { name: `${DEFAULT_BOT_NAME} (from ${from})` } : {}) });+ return;+ }for (const bot of store.bots) {if (bot.id !== id && bot.defaultBot && !defaultBotPerson(bot)) store.patchBot(bot.id, { defaultBot: undefined, sidebarHidden: undefined });}@@ -152,8 +172,6 @@ export function takeArrivingDefaultBot(store: Pick<Store, "bots" | "patchBot">,export function retireUnusedStarter(store: Pick<Store, "bot" | "patchBot" | "messagesFor">, dataDir: string): void {const own = ledger(dataDir)[""];const seed = own ? store.bot(own) : null;- if (!seed || seed.defaultBot || seed.chiefOfStaff || seed.hidden) return;- if (seed.soul?.trim() || seed.title || seed.description || seed.avatarUrl || (seed.tasks?.length ?? 1) > 1) return;- if (store.messagesFor(seed.threadId).some((message) => message.role === "user")) return;+ if (!seed || seed.defaultBot || seed.chiefOfStaff || seed.hidden || usedBot(store, seed)) return;store.patchBot(seed.id, { hidden: true, pinned: undefined });}