Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
A routine outside work wrote stays outside, with what its runs write, its Undo and a backup
milind-soni5a82dbd5abb0
diff --git a/server/cloud-lending.test.ts b/server/cloud-lending.test.tsindex 797f024827..c7b2f389a0 100644--- a/server/cloud-lending.test.ts+++ b/server/cloud-lending.test.ts@@ -3,6 +3,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";import { cloudHomeLendingRefusal, cloudLendingRefusalText, createCloudRoutineAuthors, ownerOnlyConversation, routineFingerprint, teamLendingRefusal, type CloudLendingTurn } from "./cloud-lending.ts";+import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts";const OWNER = "p_owner", GUEST = "p_guest";const ownerPerson = (person: string | undefined) => person === OWNER;@@ -113,6 +114,17 @@ describe("the owner's routines", () => {afterEach(() => { if (dir) rmSync(dir, { recursive: true, force: true }); dir = ""; });const routine = { prompt: "Tidy ~/Downloads on my Mac", target: "bot", botId: "b1", attachments: [{ id: "a1", path: "/x" }],schedule: { type: "interval", everyMinutes: 1440, anchorAt: 1_790_000_000_000 }, runOn: "maus" };+ it("keeps a routine outside work wrote outside when a bot's change would make it nobody's; a person's save still makes it theirs", () => {+ dir = mkdtempSync(join(tmpdir(), "omb-cloud-lending-"));+ const authors = createCloudRoutineAuthors(join(dir, "lending-routines.json"));+ authors.wrote("r1", CLOUD_OUTSIDE_KEY);+ authors.wrote("r1", CLOUD_NOBODY_KEY);+ expect(authors.writer("r1")).toBe(CLOUD_OUTSIDE_KEY);+ expect(createCloudRoutineAuthors(join(dir, "lending-routines.json")).writer("r1")).toBe(CLOUD_OUTSIDE_KEY);+ authors.wrote("r1", "p_aPersonWhoSavedItxxxx");+ expect(authors.writer("r1")).toBe("p_aPersonWhoSavedItxxxx");+ });+it("records what the owner wrote; any change to the instructions, target or attachments no longer matches", () => {dir = mkdtempSync(join(tmpdir(), "omb-cloud-lending-"));const authors = createCloudRoutineAuthors(join(dir, "lending-routines.json"));diff --git a/server/cloud-lending.ts b/server/cloud-lending.tsindex 2300a68e4c..dcbca47d56 100644--- a/server/cloud-lending.ts+++ b/server/cloud-lending.ts@@ -6,6 +6,7 @@ import { createHash } from "node:crypto";import { existsSync, lstatSync, readFileSync } from "node:fs";import { z } from "zod";import { writeFileAtomic } from "./atomic.ts";+import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts";import type { RoutineRunTrigger } from "./routines.ts";type Card = { requestId?: string; answered?: string; answeredText?: string; dismissed?: boolean; autoApplied?: boolean; answeredBy?: { kind: string; person?: string } };@@ -126,7 +127,8 @@ export function createCloudRoutineAuthors(file: string) {return {record(id: string, routine: RoutineShape) { routines = { ...routines, [id]: routineFingerprint(routine) }; save(); },forget(id: string) { if (Object.hasOwn(routines, id)) { const next = { ...routines }; delete next[id]; routines = next; save(); } },- wrote(id: string, person: string) { if (writers[id] !== person) { writers = { ...writers, [id]: person }; save(); } },+ /** Security invariant: what outside work wrote stays outside until a person saves it; a bot's change never makes it nobody's. */+ wrote(id: string, person: string) { if (writers[id] !== person && !(writers[id] === CLOUD_OUTSIDE_KEY && person === CLOUD_NOBODY_KEY)) { writers = { ...writers, [id]: person }; save(); } },writer(id: string): string | undefined { return Object.hasOwn(writers, id) ? writers[id] : undefined; },remove(id: string) {if (!Object.hasOwn(routines, id) && !Object.hasOwn(writers, id)) return;diff --git a/server/index.ts b/server/index.tsindex fdb339f67e..a42d48b0c4 100644--- a/server/index.ts+++ b/server/index.ts@@ -9544,7 +9544,7 @@ async function undoAppliedChange(res: ServerResponse, threadId: string, requestIelse cloudRoutineAuthors.forget(undone.routineId);} else if (undone.action === "delete" && undone.restoredId) {if (undone.ownersBefore) cloudOwnersRoutine(undone.restoredId);- else cloudRoutineAuthors.wrote(undone.restoredId, CLOUD_NOBODY_KEY);+ else cloudRoutineAuthors.wrote(undone.restoredId, cloudRoutineAuthors.writer(undone.routineId) === CLOUD_OUTSIDE_KEY ? CLOUD_OUTSIDE_KEY : CLOUD_NOBODY_KEY);}}result = undone;@@ -13187,7 +13187,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {store,bot: internalSender, apps: chatApps, folders: async () => ({ roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), vmWorkspace: (await attachmentVmForTurn(internalCapability))?.workspaceDir ?? null }),threadId: internalCapability.threadId,- input: body?.frameless && cloudGuestDriven(internalCapability.threadId) ? { ...body, frameless: false } : body, authored: (id) => handoffs.authored(internalCapability.threadId, internalCapability.generation, id),+ input: (body?.tool === "show_html" || body?.tool === "update_html") && cloudGuestDriven(internalCapability.threadId) ? { ...body, frameless: false } : body, authored: (id) => handoffs.authored(internalCapability.threadId, internalCapability.generation, id),});return result.ok? json(res, 201, { messageId: result.messageId, ...("masked" in result && result.masked ? { masked: true } : {}) })@@ -13510,7 +13510,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (proposedInput.action !== "create" && (proposedInput.action === "update" ? outsideWorkStaysHere(fromThreadId) : cloudGuestDriven(fromThreadId)) && !outsideLineage.routineRunsConfined(String(proposedInput.routineId))) return json(res, 403, { error: OUTSIDE_STAYS_HERE });const wasOwners = proposedInput.action !== "create" && typeof proposedInput.routineId === "string" ? cloudRoutineIsOwners(proposedInput.routineId) : false;const run = activeRoutineRunForThread(fromThreadId);- const outside = Boolean(CLOUD_HOME) && outsideDrivenThread(fromThreadId);+ const outside = Boolean(CLOUD_HOME) && (outsideDrivenThread(fromThreadId) || outsideWorkStaysHere(fromThreadId));const ownersTurn = !outside && (cloudOwnerOnlyThread(fromThreadId) || cloudRoutineRunIsOwners(run, from.id, fromThreadId));const ownersLevel = !outside && CLOUD_HOME && !cloudGuestDriven(fromThreadId) && (proposedInput.action === "create" ||cloudRoutineAuthors?.writer(String(proposedInput.routineId)) === CLOUD_OWNER_KEY) && (run?.threadId === fromThreadId || ownerSpokeOnly(store.messagesFor(fromThreadId), cloudThreadStarters(fromThreadId), cloudProvenOwnerPerson, cloudCardAnswerer));diff --git a/server/outside-lineage.e2e.test.ts b/server/outside-lineage.e2e.test.tsindex 6026f2ef7d..0e80b5e538 100644--- a/server/outside-lineage.e2e.test.ts+++ b/server/outside-lineage.e2e.test.ts@@ -122,6 +122,39 @@ describe("a Team Cloud", () => {await finish(scout.id);}, hostTimeout(120_000));+ it("keeps a routine outside work wrote outside, with what its runs write, a bot's change and a person's Undo, until a person saves it", async () => {+ const scout = await newBot("Lineage scout");+ const mate = await newBot("Lineage mate");+ const soon = (ms: number) => new Date(Date.now() + ms).toISOString();+ const runs = async () => (await team.as(ada, "GET", "/api/routines")).body.runs as any[];+ const { thread } = await webhookTurn(scout.id, "Lineage hook", "marker-lineage");+ const made = await internal(scout.id, thread, "/api/internal/trigger-requests", { action: "create", kind: "schedule", routine: { name: "Outside first", instructions: "lineage-first-run", schedule: { type: "interval", everyMinutes: 60 } } });+ const first = made.body.result.resultId as string;+ expect((await internal(scout.id, thread, "/api/internal/trigger-requests", { action: "run_now", triggerId: first })).status).toBe(201);+ expect(confined(await turnWith("lineage-first-run"))).toBe(true);+ const runThread = (await runs()).find((run) => run.routineId === first).threadId as string;+ const made2 = await internal(scout.id, runThread, "/api/internal/trigger-requests", { action: "create", kind: "schedule", forBotId: mate.id,+ routine: { name: "Outside second", instructions: "lineage-new-routine", schedule: { type: "once", at: soon(9_000) } } });+ expect(made2.body?.state).toBe("applied");+ await finish(scout.id, mate.id);+ expect(confined(await turnWith("lineage-new-routine"))).toBe(true);+ await finish(mate.id);+ // A bot changing it from a person's own conversation is not the person saving it.+ const changed = await internal(scout.id, scout.threadId, "/api/internal/trigger-requests", { action: "update", triggerId: first,+ changes: { instructions: "lineage-after-change", schedule: { type: "once", at: soon(8_000) } } });+ expect(changed.body?.state).toBe("applied");+ await finish(scout.id);+ expect(confined(await turnWith("lineage-after-change"))).toBe(true);+ await finish(scout.id);+ const deleted = await internal(scout.id, thread, "/api/internal/trigger-requests", { action: "delete", triggerId: first });+ expect(deleted.body?.state).toBe("applied");+ expect((await team.as(ada, "POST", `/api/threads/${thread}/undo`, { requestId: deleted.body.requestId })).status).toBe(200);+ const restored = ((await team.as(ada, "GET", "/api/routines")).body.routines as any[]).find((one) => one.name === "Outside first" && one.id !== first);+ expect((await team.as(ada, "POST", `/api/routines/${restored.id}/run`)).status).toBe(201);+ expect(confined(await turnWith("lineage-after-change"))).toBe(true);+ await finish(scout.id);+ }, hostTimeout(150_000));+it("keeps a confined turn from starting or changing a person's routine", async () => {const scout = await newBot("Routine starter");const mine = (await team.as(ada, "POST", "/api/routines", { name: "Ada's", prompt: "routine-of-a-person", botId: scout.id, enabled: false, schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_600_000 } })).body.routine;@@ -497,6 +530,14 @@ describe("a personal Cloud only its owner has used", () => {writeFileSync(release, "");await sleep(1_500);rmSync(release, { force: true });+ rmSync(dump, { force: true });+ const second = await call(runThread, "/api/internal/trigger-requests", { action: "create", kind: "schedule", forBotId: mate.id,+ routine: { name: "Solo second", instructions: "solo-new-routine", schedule: { type: "once", at: new Date(Date.now() + 6_000).toISOString() } } });+ expect(second.body?.state).toBe("applied");+ expect(confined(await turnWith("solo-new-routine"))).toBe(true);+ writeFileSync(release, "");+ await sleep(1_500);+ rmSync(release, { force: true });}, hostTimeout(120_000));});@@ -510,16 +551,29 @@ describe("a personal Cloud someone else has used", () => {expect((await cloud("PATCH", `/api/bots/${mate.id}`, { approvalMode: "full", applyToAllThreads: true })).status).toBe(200);const room = (await cloud("POST", "/api/groups", { name: "Owner's room", memberIds: [chief.id, mate.id], setup: { bulletin: "as it was", defaultResponder: { kind: "member", botId: mate.id } } })).body.group;const theirs = (await cloud("POST", `/api/bots/${chief.id}/tasks`, { title: "Left behind" })).body.task.threadId as string;- markLeftBehind(join(fx.root, "cloud", ".openmausbot"), { threadIds: [theirs] });- await fx.relaunch({ kill: false, cloud: {} });const capabilityFor = async (botId: string, threadId: string) => ((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 any).token as string;const call = async (capability: string, from: string, path: string, body: object) => {const response = await fetch(`${fx.cloudBase}${path}?fromBotId=${chief.id}`, { method: "POST", headers: { authorization: `Bearer ${capability}`, "content-type": "application/json" }, body: JSON.stringify({ fromBotId: chief.id, fromThreadId: from, ...body }) });return { status: response.status, body: await response.json().catch(() => null) as any };};+ // A page shown without its frame before outside work reached this conversation.+ const page = await call(await capabilityFor(chief.id, theirs), theirs, "/api/internal/options-card", { tool: "show_html", html: "<p>Before</p>", title: "Before", frameless: true });+ expect(page.status).toBe(201);+ const borderOf = async () => ((await cloud("GET", `/api/threads/${theirs}/messages?limit=200`)).body.messages as any[]).find((line) => line.id === page.body.messageId).app.border;+ expect(await borderOf()).toBe(false);+ // A turn of the owner's ends the work that page came from, so nothing of it runs again after the restart.+ expect((await cloud("POST", `/api/bots/${chief.id}/messages`, { text: "before-mark", threadId: theirs })).status).toBe(202);+ await turnWith("before-mark");+ writeFileSync(release, "");+ await sleep(1_500);+ for (const file of [release, dump]) rmSync(file, { force: true });+ markLeftBehind(join(fx.root, "cloud", ".openmausbot"), { threadIds: [theirs] });+ await fx.relaunch({ kill: false, cloud: {} });expect((await cloud("POST", `/api/bots/${chief.id}/messages`, { text: "their-line", threadId: theirs })).status).toBe(202);expect(confined(await turnWith("their-line"))).toBe(true);const capability = await capabilityFor(chief.id, theirs);+ expect((await call(capability, theirs, "/api/internal/options-card", { tool: "update_html", app_id: page.body.messageId, html: "<p>After</p>" })).status).toBeLessThan(300);+ expect(await borderOf()).toBe(true);expect(await call(capability, theirs, "/api/internal/retry-thread", { toBotId: mate.id, toThreadId: mate.threadId, note: "note-for-owner" })).toMatchObject({ status: 403, body: { error: OUTSIDE_STAYS_HERE } });await sleep(800);diff --git a/server/team-backup.test.ts b/server/team-backup.test.tsindex 72185853ce..7fc8a11065 100644--- a/server/team-backup.test.ts+++ b/server/team-backup.test.ts@@ -238,6 +238,17 @@ describe("additive portable team backups", () => {expect(() => parseTeamBackup(tampered)).toThrow();});+ it("keeps a conversation that work from outside reached marked through backup and restore", () => {+ const { store, routines, chief } = fixture();+ const reached = store.createTask(chief.id, "Event chat", false)!.threadId;+ store.patchTask(chief.id, reached, { outside: true });+ const backup = createTeamBackup(store, routines.listRoutines(), "Marked");+ const result = importTeamBackup(store, routines, JSON.parse(JSON.stringify(backup)), selection());+ const restored = result.bots.find((bot) => bot.name === "Mira 2")!.tasks!;+ expect(restored.find((task) => task.title === "Event chat")!.outside).toBe(true);+ expect(restored.find((task) => task.title === "First conversation")).not.toHaveProperty("outside");+ });+it("keeps first-message title markers armed-once through backup and restore", () => {const { store, routines, chief, group } = fixture();const titled = store.createTask(chief.id, undefined, false)!.threadId;diff --git a/server/team-backup.ts b/server/team-backup.tsindex 1d06bd1fed..0c070b8ef0 100644--- a/server/team-backup.ts+++ b/server/team-backup.ts@@ -55,6 +55,7 @@ export function createTeamBackup(store: Store, routines: Routine[], name: stringreturn tasks.filter((task) => shown(task.threadId)).map((task) => ({key: task.threadId, title: task.title, createdAt: task.createdAt,titleFromFirstMessage: "titleFromFirstMessage" in task && task.titleFromFirstMessage || undefined,+ outside: "outside" in task && task.outside || undefined,openedBy: "openedBy" in task && task.openedBy? { botId: task.openedBy.botId, name: task.openedBy.name, at: task.openedBy.at,...(task.openedBy.kind ? { kind: task.openedBy.kind } : {}) }@@ -192,7 +193,7 @@ export function importTeamBackup(store: Store, routines: RoutineManager, input:const record: TaskRecord = {threadId: i === 0 ? bot.threadId : newId(), title: task.title, createdAt: task.createdAt, resumeCursors: {},activity: "idle" as const, busy: false, unread: false,- ...(task.titleFromFirstMessage ? { titleFromFirstMessage: true } : {}),+ ...(task.titleFromFirstMessage ? { titleFromFirstMessage: true } : {}), ...(task.outside ? { outside: true } : {}),};const opener = task.openedBy && botIds.get(task.openedBy.botId);if (task.openedBy && opener) record.openedBy = { botId: opener, name: task.openedBy.name, at: task.openedBy.at, ...(task.openedBy.kind ? { kind: task.openedBy.kind } : {}) };diff --git a/shared/team-backup.ts b/shared/team-backup.tsindex 1d6c8cc891..2a4b3248b4 100644--- a/shared/team-backup.ts+++ b/shared/team-backup.ts@@ -31,6 +31,8 @@ const task = z.object({// Travels only when the first message already named this task, so a// restore cannot re-arm one generated title on a row that used it.titleFromFirstMessage: z.literal(true).optional(),+ /** Work from outside reached this conversation: it stays confined after a restore. */+ outside: z.literal(true).optional(),openedBy: z.object({ botId: key, name, at: timestamp, kind: z.enum(["pair", "work"]).optional() }).optional(),closedBy: z.object({ botId: key, name, at: timestamp }).optional(),/** Only true travels; absence is unpinned. */