Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Tell the owner the moment a bot's memory locks, with an Allow card (#5132)
Milind Soni617d4a294690
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex 5ad06e4f62..a06942d645 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -1031,7 +1031,11 @@ On the Cloud home (`server/shared-computers.ts`, `server/index.ts`):reaction or a process on the Cloud), and counted only while it recordsthe owner as its answerer; the request goes on by itself once they allowit (in a group chat they ask again). **Not now** is- not asked again for that line. A webhook's or a routine's run, or a line a+ not asked again for that line. The moment a bot's memory locks, a card like+ it also goes to the bot's own main chat, so the owner hears about the lock+ instead of finding out when something fails: **Allow** there accepts+ exactly what it showed and starts no turn, and **Not now** holds until the+ memory changes again. A webhook's or a routine's run, or a line abot handed in, never raises one. The same card lets the owner's own linethrough the work a bot opened a conversation with, for that line alone:work a bot hands into it after they allowed it (made or run then) shuts itdiff --git a/server/host/lending-lifts.test.ts b/server/host/lending-lifts.test.tsindex 18dcb9c684..838e0f2e72 100644--- a/server/host/lending-lifts.test.ts+++ b/server/host/lending-lifts.test.ts@@ -27,7 +27,7 @@ function world({ room = false, busy = false, owners = true, stopped = false, atactivePath: () => lines,appendMessage: (_: string, message: any) => { const line = { id: `m${lines.length}`, ...message }; lines.push(line); return line; },patchMessage: (_: string, id: string, patch: any) => { const line = lines.find((candidate) => candidate.id === id)!; Object.assign(line, patch); return line; },- bot: () => ({ id: "b1", name: "Postmeister", color: "red" }),+ bot: () => ({ id: "b1", name: "Postmeister", color: "red", threadId: "t1" }),botByThread: () => ({ id: "b1" }),groupByThread: () => (room ? { id: "g1", name: "Room" } : undefined),projectBotForTask: () => ({ busy: false, activity: "working" }),@@ -66,6 +66,7 @@ function world({ room = false, busy = false, owners = true, stopped = false, atreturn { lines, state, continued, timers, deps, lifts, answer };}const input = { botId: "b1", threadId: "t1", requestMessageId: "u1", memoryChanged: true, outside: false };+const wholeBotCards = (lines: Line[]) => lines.filter((line) => line.card?.lendingLift?.requestMessageId === "whole-bot-memory");const cardOf = (lines: Line[]) => lines.filter((line) => line.card?.lendingLift).at(-1)!.card;describe("the card that lifts a lock on the lent computer (server/host/lending-lifts.ts)", () => {@@ -269,6 +270,51 @@ describe("the card that lifts a lock on the lent computer (server/host/lending-l});});+describe("the card a bot's lock raises in its own chat", () => {+ it("names the bot, shows what changed, and notifies once, however often it is told", () => {+ const { lines, deps, lifts } = world();+ lifts.memoryLocked("b1");+ lifts.memoryLocked("b1");+ expect(wholeBotCards(lines)).toHaveLength(1);+ expect(deps.notify).toHaveBeenCalledTimes(1);+ const card = wholeBotCards(lines)[0]!.card;+ expect(card.title).toBe("Postmeister's notes changed in work you didn't write. Let it keep using your Mac?");+ expect(card.subtitle).toContain("MEMORY.md");+ expect(card.lendingLift).toEqual({ requestMessageId: "whole-bot-memory", memoryToken: "t1" });+ });+ it("Allow accepts exactly what it showed, and starts no turn", () => {+ const { lines, state, continued, lifts, answer } = world();+ lifts.memoryLocked("b1");+ expect(answer(wholeBotCards(lines)[0]!.card.requestId, "allow")!.status).toBe(200);+ expect(state.accepted).toEqual(["t1"]);+ expect(continued).toEqual([]);+ });+ it("only the owner's own device answers it", () => {+ const { lines, state, lifts, answer } = world({ owners: false });+ lifts.memoryLocked("b1");+ expect(answer(wholeBotCards(lines)[0]!.card.requestId, "allow")!.status).toBe(403);+ expect(state.accepted).toEqual([]);+ });+ it("Not now holds until the memory changes again; then it asks once more, about what's there now", () => {+ const { lines, state, lifts, answer } = world();+ lifts.memoryLocked("b1");+ answer(wholeBotCards(lines)[0]!.card.requestId, "deny");+ lifts.memoryLocked("b1");+ expect(wholeBotCards(lines)).toHaveLength(1);+ state.token = "t2";+ state.changed = ["memory/people.md"];+ lifts.memoryLocked("b1");+ expect(wholeBotCards(lines)).toHaveLength(2);+ expect(wholeBotCards(lines)[1]!.card.lendingLift.memoryToken).toBe("t2");+ });+ it("a bot that no longer exists raises nothing", () => {+ const { lines, lifts, deps } = world();+ (deps.store as unknown as { bot: () => undefined }).bot = () => undefined;+ lifts.memoryLocked("gone");+ expect(wholeBotCards(lines)).toEqual([]);+ });+});+describe("Allow on the card, in a conversation whose waiting state follows its open cards", () => {beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));diff --git a/server/host/lending-lifts.ts b/server/host/lending-lifts.tsindex df14341e12..763b2cec67 100644--- a/server/host/lending-lifts.ts+++ b/server/host/lending-lifts.ts@@ -17,6 +17,8 @@ import { turnWaitedOnPerson } from "../waiting-on-person.ts";import { workspaceDir } from "../workspace.ts";const TOOL = "lending_lift";+/** The request of a card for a whole bot's memory, which no line of a conversation asked for. */+const WHOLE_BOT = "whole-bot-memory";/** A card shows what it allows; past this it says where the rest is. */const SHOWN_CHARS = 2_000;const CARRY_ON_EVERY_MS = 5_000;@@ -132,10 +134,11 @@ export function createLendingLifts(deps: LendingLiftDeps) {}return "open";}- if (last?.card?.answered === "deny") return "declined";+ // A line's Not now holds for that line; a bot's holds until its memory changes again.+ if (last?.card?.answered === "deny" && (requestMessageId !== WHOLE_BOT || last.card.lendingLift?.memoryToken === lift.memoryToken)) return "declined";const language = deps.language(threadId);const room = store.groupByThread(threadId);- const title = serverLine(language, "server.lendingLift.title", { bot: bot?.name ?? "", device: deps.device() });+ const title = serverLine(language, requestMessageId === WHOLE_BOT ? "server.lendingLift.wholeBotTitle" : "server.lendingLift.title", { bot: bot?.name ?? "", device: deps.device() });const requestId = `lending-lift-${randomUUID()}`;store.appendMessage(threadId, {role: "bot", kind: "options",@@ -148,6 +151,14 @@ export function createLendingLifts(deps: LendingLiftDeps) {return "open";},+ /** Security invariant: a bot's memory just became locked. The card goes to its own main chat, for the owner alone to+ * answer from one of their devices, and shows exactly what it would allow, like any other. */+ memoryLocked(botId: string): void {+ const bot = store.bot(botId);+ if (!bot?.threadId) return;+ this.raise({ botId, threadId: bot.threadId, requestMessageId: WHOLE_BOT, memoryChanged: true, outside: false });+ },+/** They said Not now to this line of theirs. */declined(threadId: string, requestMessageId: string): boolean {return cards(threadId, requestMessageId).at(-1)?.card?.answered === "deny";diff --git a/server/index.ts b/server/index.tsindex d2869d41f4..6ecff4b7c6 100644--- a/server/index.ts+++ b/server/index.ts@@ -715,7 +715,7 @@ const lendingMemory = CLOUD_PERSONAL ? createLendingMemory({{ workspace: ensureWorkspace, taskWorkspaces: TASK_WORKSPACES_DIR, skillLinks: harnessSkillLinks });},knownBots: () => store.bots.map((bot) => bot.id),- log: (line) => console.warn(line),+ log: (line) => console.warn(line), onLocked: (botId) => lendingLifts?.memoryLocked(botId),}) : null;if (CLOUD_HOME) readMemoryOnlyFromRegularFiles();if (CLOUD_HOME) {diff --git a/server/lending-memory.test.ts b/server/lending-memory.test.tsindex 5ea9a2dc0a..356b9195fe 100644--- a/server/lending-memory.test.ts+++ b/server/lending-memory.test.ts@@ -170,6 +170,18 @@ describe("a bot's memory and a lent Mac (server/lending-memory.ts)", () => {expect(reloaded.needsReview("bot1")).toBe(false);expect(reloaded.reconcile("bot1", false).changedBySomeoneElse).toBe(false);});+ it("tells the owner once, as the bot becomes locked", async () => {+ const ws = workspace();+ const locked: string[] = [];+ const memory = createLendingMemory({ file: join(dir, "lending-memory.json"), files: () => memoryFiles(ws), knownBots: () => ["bot1"], onLocked: (bot) => locked.push(bot) });+ memory.reconcile("bot1", false);+ memory.noteForeignTurn("bot1");+ appendFileSync(join(ws, "MEMORY.md"), "- planted\n");+ expect(memory.reconcile("bot1", true).changedBySomeoneElse).toBe(true);+ memory.reconcile("bot1", true);+ await Promise.resolve();+ expect(locked).toEqual(["bot1"]);+ });it("the owner's own changes, and a foreign turn that changed nothing, are not flagged", () => {const ws = workspace();const memory = tracker(ws);diff --git a/server/lending-memory.ts b/server/lending-memory.tsindex 6146e27732..49f885cbff 100644--- a/server/lending-memory.ts+++ b/server/lending-memory.ts@@ -223,9 +223,11 @@ export interface LendingMemoryDeps {files: (botId: string) => Record<string, string>;knownBots: () => readonly string[];log?: (line: string) => void;+ /** A bot just became locked: the owner hears about it, with a way to allow it, instead of finding out when something fails. */+ onLocked?: (botId: string) => void;}-export function createLendingMemory({ file, files: snapshot, knownBots, log = () => {} }: LendingMemoryDeps) {+export function createLendingMemory({ file, files: snapshot, knownBots, log = () => {}, onLocked }: LendingMemoryDeps) {let bots: { [botId: string]: Record_ } = {};// Fail closed: a damaged, linked or oversized record flags every bot that existed when it was found.let unknownFlagged = new Set<string>();@@ -294,6 +296,7 @@ export function createLendingMemory({ file, files: snapshot, knownBots, log = ()if (current.pending && !unchanged(current, snap)) {log(`lending: memory of bot ${botId} changed while a conversation the owner did not write was running; its turns cannot use the lent Mac until the owner reviews it`);set(botId, { ...current, flagged: true });+ if (onLocked) queueMicrotask(() => onLocked(botId));return { changedBySomeoneElse: true };}if (snap.hash !== current.trusted || (current.pending && !foreignRunning)) {diff --git a/src/locales/de.json b/src/locales/de.jsonindex c31504477f..7ba164c9f8 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -288,6 +288,7 @@"server.teammates.resumedResults": "Mit den Ergebnissen von {who} fortgesetzt, wird geprüft","server.teammates.resumedResultsRestart": "Nach einem Neustart mit den Ergebnissen von {who} fortgesetzt, wird geprüft","server.lendingLift.title": "{bot} dafür deinen {device} benutzen lassen?",+ "server.lendingLift.wholeBotTitle": "Die Notizen von {bot} wurden in Arbeit geändert, die du nicht geschrieben hast. Darf der Bot deinen {device} weiter nutzen?","server.lendingLift.memory": "Seine Notizen wurden in Arbeit geändert, die du nicht geschrieben hast:","server.lendingLift.botOpened": "Ein Bot hat dieses Gespräch mit Arbeit für diesen Bot eröffnet. „Erlauben“ lässt nur diese eine Nachricht von dir deinen {device} benutzen.","server.lendingLift.outside": "Ein Webhook oder eine Routine, die du nicht geschrieben hast, hat in diesem Gespräch gepostet. „Erlauben“ lässt nur diese eine Nachricht von dir deinen {device} benutzen.",diff --git a/src/locales/en.json b/src/locales/en.jsonindex d0eb2dfb9b..73d7a60e89 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -423,6 +423,7 @@"server.teammates.backWithResultsRestart": "Back with the work it handed on after a restart, reviewing","server.teammates.handedWork": "work it handed on","server.lendingLift.title": "Let {bot} use your {device} for this?",+ "server.lendingLift.wholeBotTitle": "{bot}'s notes changed in work you didn't write. Let it keep using your {device}?","server.lendingLift.memory": "Its notes changed in work you didn't write:","server.lendingLift.botOpened": "A bot opened this conversation with work for this bot. Allow lets only this message of yours use your {device}.","server.lendingLift.outside": "A webhook or a routine you didn't write posted in this conversation. Allow lets only this message of yours use your {device}.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex b3488299c2..0ebf321194 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -406,6 +406,7 @@"server.teammates.backWithResultsRestart": "Após uma reinicialização, voltou com o trabalho que repassou e está revisando","server.teammates.handedWork": "trabalho que repassou","server.lendingLift.title": "Permitir que {bot} use seu {device} para isto?",+ "server.lendingLift.wholeBotTitle": "As anotações de {bot} mudaram em um trabalho que você não escreveu. Permitir que continue usando seu {device}?","server.lendingLift.memory": "As notas dele mudaram durante tarefas que não partiram de você:","server.lendingLift.botOpened": "Outro bot abriu esta conversa para passar uma tarefa a este bot. “Permitir” autoriza o uso do seu {device} só para atender a esta mensagem sua.","server.lendingLift.outside": "Um webhook ou uma rotina que você não criou publicou uma mensagem nesta conversa. “Permitir” autoriza o uso do seu {device} só para atender a esta mensagem sua.",