Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Store: a registry seam with today's JSON behind it (#6198)
Milind Soni92cedf056588
diff --git a/server/registry-store.test.ts b/server/registry-store.test.tsnew file mode 100644index 0000000000..f3ba27f7d5--- /dev/null+++ b/server/registry-store.test.ts@@ -0,0 +1,73 @@+import { mkdirSync, rmSync, statSync } from "node:fs";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { DATA_DIR } from "./config.ts";+import { BOTS_FILE, JsonRegistry, persistedBots, type RegistryStore } from "./registry-store.ts";+import { flushLaterSaves } from "./save-batch.ts";+import type { BotRecord } from "./store.ts";++const bot = (id: string) => ({ id, name: id, busy: true, activity: "working", tasks: [+ { threadId: `${id}-t`, busy: true, activity: "working", turnStartedAt: 1, pinned: false },+] }) as unknown as BotRecord;+const owner = { kind: "bot", id: "a" } as const;++describe("the JSON registry: today's bots.json and groups.json behind the registry calls", () => {+ beforeEach(() => {+ rmSync(DATA_DIR, { recursive: true, force: true });+ mkdirSync(DATA_DIR, { recursive: true });+ });+ afterEach(() => flushLaterSaves());++ it("never saves live state, and a missing file throws instead of reading as no bots", () => {+ expect(persistedBots([bot("a")])).toEqual([{ id: "a", name: "a", tasks: [{ threadId: "a-t" }] }]);+ const registry = new JsonRegistry();+ expect(() => registry.loadBots()).toThrow();+ expect(() => registry.loadGroups()).toThrow();+ });++ it("writes the whole file owner-only, skips an unchanged one, and reads back what it wrote", () => {+ const registry = new JsonRegistry();+ registry.writeBots([bot("a")], true);+ const first = statSync(BOTS_FILE);+ if (process.platform !== "win32") expect(first.mode & 0o777).toBe(0o600);+ registry.writeBots([bot("a")], true);+ expect(statSync(BOTS_FILE).ino, "the same text is not written again").toBe(first.ino);+ expect(new JsonRegistry().loadBots()).toEqual(persistedBots([bot("a")]));+ });++ it("writes a thread change at once, at the end of the running batch, or a bounded moment later", () => {+ const registry = new JsonRegistry();+ const write = vi.fn();+ registry.upsertThread(owner, "a-t", "now", write);+ expect(write).toHaveBeenCalledTimes(1);+ registry.batch(() => {+ registry.upsertThread(owner, "a-t", "pass", write);+ registry.upsertThread(owner, undefined, "pass", write);+ expect(write).toHaveBeenCalledTimes(1);+ });+ expect(write, "one write for the pass").toHaveBeenCalledTimes(2);+ registry.upsertThread(owner, "a-t", "later", write);+ expect(write).toHaveBeenCalledTimes(2);+ flushLaterSaves();+ expect(write).toHaveBeenCalledTimes(3);+ registry.deleteOwner(owner, write);+ expect(write).toHaveBeenCalledTimes(4);+ });++ it("a whole save of the live list supersedes a write still waiting", () => {+ const registry = new JsonRegistry();+ const waiting = vi.fn();+ registry.upsertThread(owner, "a-t", "later", waiting);+ registry.writeBots([bot("a")], false);+ registry.writeBots([bot("b")], true);+ flushLaterSaves();+ expect(waiting).not.toHaveBeenCalled();+ });++ it("has no deferrable save for a room: nothing of a room may wait, and no room save would supersede it", () => {+ const roomLater = (registry: RegistryStore) =>+ // @ts-expect-error "later" is for bots only+ registry.upsertThread({ kind: "group", id: "g" }, undefined, "later", () => {});+ expect(roomLater).toBeTypeOf("function"); // never called: the check is the typecheck's+ });+});diff --git a/server/registry-store.ts b/server/registry-store.tsnew file mode 100644index 0000000000..a845d25bff--- /dev/null+++ b/server/registry-store.ts@@ -0,0 +1,123 @@+// Where the Store keeps its bots, rooms and their threads. The Store says what changed (one thread, one owner's record,+// an owner gone, the whole list) and how soon it must be on disk; the registry decides how to write that. Today's one+// layout keeps everything in bots.json and groups.json, each rewritten whole for any change: temp file, fsync, rename,+// owner-only, skipped when the text is unchanged. A layout that keeps threads as rows can write one row where this one+// writes a whole file, behind the same calls.+import { chmodSync, readFileSync, statSync } from "node:fs";+import { join } from "node:path";++import { OwnedFile } from "./atomic.ts";+import { DATA_DIR } from "./config.ts";+import { batchSaves, saveLater, saveSoon, supersedeLaterSave } from "./save-batch.ts";+import type { BotRecord, GroupRecord } from "./store.ts";++export const BOTS_FILE = join(DATA_DIR, "bots.json");+export const GROUPS_FILE = join(DATA_DIR, "groups.json");++export type RegistryOwner = { kind: "bot" | "group"; id: string };++/**+ * How soon a change must be on disk:+ * - "now": before the call returns, synced. Creates, deletions, permissions, anything a person asked for; a failure+ * throws, so the caller can put memory back (server/registry-save.ts commitRegistryChange).+ * - "pass": when the running batch ends (`batch`, server/save-batch.ts batchSaves), at once outside one. A turn's+ * bookkeeping that must survive a crash: an engine session, which engine has the thread, what was handed to it.+ * - "later": within SAVE_LATER_MAX_MS (server/save-batch.ts saveLater). Only what server/registry-save.ts+ * DEFERRABLE_FIELDS allows, and a thread's usage: harmless to lose in a crash. Bots only: nothing of a room waits,+ * and no room save supersedes a waiting write, so the types refuse "later" for a room.+ */+export type RegistryDurability = "now" | "pass" | "later";++export interface RegistryStore {+ /** The saved bots as parsed; throws when nothing readable is saved, which must never read as "every bot was deleted". */+ loadBots(): BotRecord[];+ /** The saved rooms as parsed; throws when nothing readable is saved. */+ loadGroups(): GroupRecord[];+ /** Every bot and its threads as `bots` holds them, synced before it returns. `bots` may be a list that is not live+ * yet (saved first, so a failure leaves memory alone); `current` says it is the live list, holding every change. */+ writeBots(bots: readonly BotRecord[], current: boolean): void;+ /** Every room and its threads as `groups` holds them, synced before it returns. */+ writeGroups(groups: readonly GroupRecord[]): void;+ /**+ * One owner's thread changed (`threadId`), or its record or any of its threads (undefined). `write` is the Store's+ * own save of the whole list (what rollback and tests hook); it runs when `durability` says, and it throws for "now".+ * A row layout narrows that save to the one thread; this one writes the whole file.+ */+ upsertThread(owner: RegistryOwner & { kind: "bot" }, threadId: string | undefined, durability: RegistryDurability, write: () => void): void;+ upsertThread(owner: RegistryOwner & { kind: "group" }, threadId: string | undefined, durability: Exclude<RegistryDurability, "later">, write: () => void): void;+ /** An owner and all its threads leave the registry; `write` saves the list without it, synced, before it returns. */+ deleteOwner(owner: RegistryOwner, write: () => void): void;+ /** Saves asked for with "pass" while `run` runs are written once when it returns: one transaction in a row layout. */+ batch<T>(run: () => T): T;+}++/** Owner-only (0600): the registries hold souls, project paths and per-bot settings. Best effort; Windows has no POSIX mode bits. */+function tightenRegistryFile(file: string): void {+ if (process.platform === "win32") return;+ try {+ if ((statSync(file).mode & 0o077) !== 0) chmodSync(file, 0o600);+ } catch {+ }+}++export function persistedPin<T extends { pinned?: boolean }>(task: T): T {+ if (task.pinned === true) return task;+ if (!("pinned" in task)) return task;+ const { pinned: _pinned, ...rest } = task;+ return rest as T;+}++/** What bots.json holds: live state (busy, activity, a turn's start) is never saved. */+export const persistedBots = (bots: readonly BotRecord[]) => bots.map(({ busy: _busy, activity: _activity, ...bot }) => ({ ...bot,+ tasks: bot.tasks?.map(({ busy: _taskBusy, activity: _taskActivity, turnStartedAt: _taskTurnStarted, ...task }) => persistedPin(task)),+}));++/** What groups.json holds: a room's running turn is never saved. */+export const persistedGroups = (groups: readonly GroupRecord[]) => groups.map(({ busyBotId: _busyBotId, turnStartedAt: _turnStartedAt, ...g }) => ({+ ...g,+ ...(g.tasks ? { tasks: g.tasks.map((task) => persistedPin(task)) } : {}),+}));++/** Today's layout: bots.json and groups.json, each the whole list with its threads. */+export class JsonRegistry implements RegistryStore {+ private readonly botsFile = new OwnedFile(BOTS_FILE, { mode: 0o600 });+ private readonly groupsFile = new OwnedFile(GROUPS_FILE, { mode: 0o600 });++ loadBots(): BotRecord[] {+ tightenRegistryFile(BOTS_FILE);+ supersedeLaterSave(BOTS_FILE); // the file is read afresh, so a write still waiting has nothing left to add+ const text = readFileSync(BOTS_FILE, "utf8"), bots = JSON.parse(text) as BotRecord[];+ this.botsFile.loaded(text);+ return bots;+ }++ loadGroups(): GroupRecord[] {+ tightenRegistryFile(GROUPS_FILE);+ const text = readFileSync(GROUPS_FILE, "utf8"), groups = JSON.parse(text) as GroupRecord[];+ this.groupsFile.loaded(text);+ return groups;+ }++ writeBots(bots: readonly BotRecord[], current: boolean): void {+ this.botsFile.write(JSON.stringify(persistedBots(bots)));+ if (current) supersedeLaterSave(BOTS_FILE);+ }++ writeGroups(groups: readonly GroupRecord[]): void {+ this.groupsFile.write(JSON.stringify(persistedGroups(groups)));+ }++ upsertThread(owner: RegistryOwner, _threadId: string | undefined, durability: RegistryDurability, write: () => void): void {+ if (durability === "pass") saveSoon(owner.kind === "bot" ? this.botsFile : this.groupsFile, write);+ else if (durability === "later") saveLater(BOTS_FILE, write); // bots only (see RegistryDurability)+ else write();+ }++ deleteOwner(_owner: RegistryOwner, write: () => void): void {+ write();+ }++ batch<T>(run: () => T): T {+ return batchSaves(run);+ }+}diff --git a/server/store-reorder-groups.test.ts b/server/store-reorder-groups.test.tsindex 7ffd0a8415..6a4fea8fbb 100644--- a/server/store-reorder-groups.test.ts+++ b/server/store-reorder-groups.test.ts@@ -15,8 +15,7 @@ describe("reordering rooms", () => {const bot = store.createBot({ name: "Ada" });for (const name of ["One", "Two", "Three"]) store.createGroup(name, [bot.id]);const before = store.groups.map((group) => group.id), wanted = [...before].reverse();- const file = (store as unknown as { groupsFile: { write: (text: string) => void } }).groupsFile;- const write = vi.spyOn(file, "write").mockImplementation(() => { throw new Error("disk full"); });+ const write = vi.spyOn(store as unknown as { saveGroups: (...args: unknown[]) => void }, "saveGroups").mockImplementation(() => { throw new Error("disk full"); });try {expect(() => store.reorderGroups(wanted)).toThrow("disk full");expect(store.groups.map((group) => group.id)).toEqual(before);diff --git a/server/store.ts b/server/store.tsindex efb126986d..ad336def16 100644--- a/server/store.ts+++ b/server/store.ts@@ -1,7 +1,7 @@-import { chmodSync, existsSync, readFileSync, mkdirSync, rmSync, statSync, unlinkSync } from "node:fs";+import { existsSync, mkdirSync, rmSync, unlinkSync } from "node:fs";import { join } from "node:path"; import { isDeepStrictEqual } from "node:util";-import { OwnedFile, writeFileAtomic } from "./atomic.ts"; import { saveLater, saveSoon, supersedeLaterSave } from "./save-batch.ts"; import { discardNativeLog } from "./drivers/native.ts";+import { writeFileAtomic } from "./atomic.ts"; import { BOTS_FILE, JsonRegistry, persistedPin, type RegistryDurability, type RegistryStore } from "./registry-store.ts"; import { discardNativeLog } from "./drivers/native.ts";import { commitRegistryChange, deferrablePatch, keptRevocation, saveRegistryFor, touchesPermissions } from "./registry-save.ts";import { parseToolScope, toolScopeWidens } from "../shared/tool-scope.ts"; import { grantScopedApps } from "../shared/connector-scopes.ts"; import { dropRetiredApps } from "./retired-apps.ts";import { reorderInPlace } from "../shared/bot-order.ts"; import { trimOutboundPolicy } from "../shared/outbound.ts";@@ -116,13 +116,6 @@ export type TaskPatch = Partial<Pick<TaskRecord, typeof TASK_PATCH_FIELDS[numberexport type GroupTaskPatch = Partial<Pick<GroupTaskRecord, "title" | "pinned">> & { turnTimeoutMinutes?: number | null; archivedAt?: number | null; activity?: "waiting-on-you" | null };-function persistedPin<T extends { pinned?: boolean }>(task: T): T {- if (task.pinned === true) return task;- if (!("pinned" in task)) return task;- const { pinned: _pinned, ...rest } = task;- return rest as T;-}-export const ACTIVITY_BUSY: ReadonlySet<BotActivity> = new Set(["working", "waiting-on-you", "no-signal"]);export type StoreChange =@@ -178,19 +171,9 @@ export type BotWireProjection = Pick<BotRecord, Exclude<keyof BotRecord, BotWireexport type BotWireProjectionIsExact = AssertExact<Omit<WireBot, "avatarUrl" | "tasks">, BotWireProjection> & AssertSameKeys<Omit<WireBot, "avatarUrl" | "tasks">, BotWireProjection>;export const botWireProjectionIsExact: BotWireProjectionIsExact = true;-const BOTS_FILE = join(DATA_DIR, "bots.json");-const GROUPS_FILE = join(DATA_DIR, "groups.json");const THREAD_MODEL_COPIES_CLEARED = join(DATA_DIR, "thread-model-copies-cleared");const ASKED_AT_FILLED = join(DATA_DIR, "asked-at-filled");-/** Owner-only (0600): the registries hold souls, project paths and per-bot settings. Best effort; Windows has no POSIX mode bits. */-function tightenRegistryFile(file: string): void {- if (process.platform === "win32") return;- try {- if ((statSync(file).mode & 0o077) !== 0) chmodSync(file, 0o600);- } catch {- }-}const messagesFile = (threadId: string) => join(DATA_DIR, `messages-${threadId}.json`);export const sectionKey = (section?: string | null): string => section?.trim() || "";@@ -285,7 +268,8 @@ export class Store {newBotSharing: NewBotSharingRule = sharedUnlessRestricted;private listeners = new Set<(change: StoreChange) => void>();private registeringInitialSections = true;- private readonly botsFile = new OwnedFile(BOTS_FILE, { mode: 0o600 }); private readonly groupsFile = new OwnedFile(GROUPS_FILE, { mode: 0o600 });+ /** Where bots, rooms and their threads are saved (server/registry-store.ts). */+ private readonly registry: RegistryStore = new JsonRegistry();/** Clearing this slot must not clear a concurrently running task's activity. */private legacyActivities = new Map<string, BotActivity>();@@ -305,16 +289,15 @@ export class Store {this.initialLanguage = initialLanguage;this.personName = personName;mkdirSync(DATA_DIR, { recursive: true });- for (const file of [BOTS_FILE, GROUPS_FILE]) tightenRegistryFile(file);// An unreadable bots.json must never read as "every member was deleted".let botsLoaded = false;try {- supersedeLaterSave(BOTS_FILE); const text = readFileSync(BOTS_FILE, "utf8"); this.bots = JSON.parse(text); this.botsFile.loaded(text); botsLoaded = Array.isArray(this.bots);+ this.bots = this.registry.loadBots(); botsLoaded = Array.isArray(this.bots);} catch {this.bots = [];}try {- const text = readFileSync(GROUPS_FILE, "utf8"); this.groups = JSON.parse(text); this.groupsFile.loaded(text);+ this.groups = this.registry.loadGroups();} catch {this.groups = [];}@@ -654,27 +637,22 @@ export class Store {}private commitBotChange(bot: BotRecord, action: string, change: () => void, onRollback?: () => void, bookkeeping: boolean | "later" = false) {- commitRegistryChange(bot, "bots.json", action, bookkeeping === "later" ? () => this.saveBotsLater() : bookkeeping ? () => this.saveBotsSoon() : () => this.saveBots(), change, onRollback);+ commitRegistryChange(bot, "bots.json", action, () => this.saveBotThread(bot.id, undefined, bookkeeping === "later" ? "later" : bookkeeping ? "pass" : "now"), change, onRollback);}private commitGroupChange(group: GroupRecord, action: string, change: () => void) {- commitRegistryChange(group, "groups.json", action, () => this.saveGroups(), change);+ commitRegistryChange(group, "groups.json", action, () => this.registry.upsertThread({ kind: "group", id: group.id }, undefined, "now", () => this.saveGroups()), change);}- private saveBotsSoon() { saveSoon(this.botsFile, () => this.saveBots()); } private saveBotsLater() { saveLater(BOTS_FILE, () => this.saveBots()); }+ private saveBotThread(botId: string, threadId: string | undefined, durability: RegistryDurability) { this.registry.upsertThread({ kind: "bot", id: botId }, threadId, durability, () => this.saveBots()); }private saveBots(bots: BotRecord[] = this.bots, registerSections = true) {if (registerSections) this.rememberSections([...this.bots, ...bots].map((bot) => bot.section));- this.botsFile.write(JSON.stringify(bots.map(({ busy: _busy, activity: _activity, ...bot }) => ({ ...bot,- tasks: bot.tasks?.map(({ busy: _taskBusy, activity: _taskActivity, turnStartedAt: _taskTurnStarted, ...task }) => persistedPin(task)),- })))); if (bots === this.bots) supersedeLaterSave(BOTS_FILE);+ this.registry.writeBots(bots, bots === this.bots);}private saveGroups(groups: GroupRecord[] = this.groups, registerSections = true) {if (registerSections) this.rememberSections(groups.map((group) => group.section));- this.groupsFile.write(JSON.stringify(groups.map(({ busyBotId: _busyBotId, turnStartedAt: _turnStartedAt, ...g }) => ({- ...g,- ...(g.tasks ? { tasks: g.tasks.map((task) => persistedPin(task)) } : {}),- }))));+ this.registry.writeGroups(groups);}get sections(): string[] { return readSections(); }@@ -904,7 +882,7 @@ export class Store {const group = this.group(id);if (!group) return false;const remaining = this.groups.filter((g) => g.id !== id); this.threadsGoing([group.threadId, ...(group.tasks ?? []).map((task) => task.threadId)]);- saveRegistryFor("groups.json", group.dm ? "the chat deletion" : "the room deletion", () => this.saveGroups(remaining));+ saveRegistryFor("groups.json", group.dm ? "the chat deletion" : "the room deletion", () => this.registry.deleteOwner({ kind: "group", id }, () => this.saveGroups(remaining)));this.groups = remaining;for (const threadId of new Set([group.threadId, ...(group.tasks ?? []).map((task) => task.threadId)])) {this.deleteThreadRecord(threadId);@@ -1459,7 +1437,7 @@ export class Store {nextBots = nextBots.map((candidate) => candidate.id === chief.id ? { ...candidate, lastTeamSetupReceipt } : candidate);}// Persist removal before deleting data: a failed save must leave the bot recoverable.- this.saveBots(nextBots);+ this.registry.deleteOwner({ kind: "bot", id }, () => this.saveBots(nextBots));this.bots = nextBots;this.legacyActivities.delete(id);const rooms = this.groups.filter((g) => !g.dm && g.memberIds.includes(id));@@ -1812,7 +1790,7 @@ export class Store {const task = threadId ? this.taskByThread(botId, threadId) : this.activeTask(botId), mirrored = !threadId || bot.threadId === threadId;if (isDeepStrictEqual(task?.resumeCursors[instanceId], cursor) && (!mirrored || isDeepStrictEqual(bot.resumeCursors[instanceId], cursor))) return;if (task) task.resumeCursors[instanceId] = cursor; if (mirrored) bot.resumeCursors[instanceId] = cursor;- saveRegistryFor("bots.json", "the conversation's engine session", () => this.saveBotsSoon());+ saveRegistryFor("bots.json", "the conversation's engine session", () => this.saveBotThread(botId, task?.threadId, "pass"));this.emit({ type: "bot", botId, ...(task ? { threadId: task.threadId } : {}) });}@@ -1820,7 +1798,7 @@ export class Store {const task = this.taskByThread(botId, threadId);if (!task || task.lastInstanceId === instanceId) return;task.lastInstanceId = instanceId;- saveRegistryFor("bots.json", "which engine has this conversation", () => this.saveBotsSoon());+ saveRegistryFor("bots.json", "which engine has this conversation", () => this.saveBotThread(botId, threadId, "pass"));}setHandedMessages(botId: string, threadId: string, instanceId: string, state: HandedState) {@@ -1829,7 +1807,7 @@ export class Store {const live = Object.entries(task.handedMessages ?? {}).filter(([id, record]) => id !== instanceId && record.session !== undefined && record.session === task.resumeCursors[id]);task.handedMessages = { ...Object.fromEntries(live), [instanceId]: state };- saveRegistryFor("bots.json", "what this conversation handed its engine", () => this.saveBotsSoon());+ saveRegistryFor("bots.json", "what this conversation handed its engine", () => this.saveBotThread(botId, threadId, "pass"));}addTaskUsage(@@ -1866,7 +1844,7 @@ export class Store {? { context: { tokens: contextTokens, ...(contextWindow > 0 ? { window: contextWindow } : {}) } }: prev.context ? { context: prev.context } : {}),};- saveRegistryFor("bots.json", "the thread's usage", () => this.saveBotsLater());+ saveRegistryFor("bots.json", "the thread's usage", () => this.saveBotThread(botId, threadId, "later"));this.emit({ type: "bot", botId, threadId });return task.usage;}@@ -2200,7 +2178,7 @@ export class Store {const task = this.taskByThread(botId, threadId);if (!task || !Number.isFinite(at) || (task.askedAt ?? -1) >= at) return task ?? null;task.askedAt = at;- saveRegistryFor("bots.json", "when you last wrote in this thread", () => this.saveBotsSoon());+ saveRegistryFor("bots.json", "when you last wrote in this thread", () => this.saveBotThread(botId, threadId, "pass"));this.emit({ type: "bot", botId, threadId });return task;}