Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep the main thread an install already had, and let go of one that is archived
luishron123864340d30c96
diff --git a/docs/verification/routines.md b/docs/verification/routines.mdindex 53dbe711ed..4e23ea442a 100644--- a/docs/verification/routines.md+++ b/docs/verification/routines.md@@ -143,9 +143,12 @@ The final startup JSON includes the server `url`, `previewUrl`, `pepperId`,Every routine reports into its bot's main thread unless the user chooses anotherdestination, whether it was made in a chat, the editor or the API, and whether ateammate (such as a Chief) asked for it. The main thread is the one the person set-as main while it is open, else the oldest open conversation a person started,-else the oldest open one; a bot with hidden threads opens there too. Writing in-another conversation never moves it. Each run looks it up+as main while it is open. A bot with none saved keeps the one it had: the open+conversation a person last wrote in, else the oldest open one a person started,+saved from then on as if chosen. Archiving or deleting the main thread passes it+to the oldest open conversation a person started, and unarchiving does not take+it back; a bot with hidden threads opens there too. Writing in another+conversation never moves it. Each run looks it upagain, so the routine saves nothing and its results follow the main thread. A routinestill pointing at an automatic "<name> · Results" thread from an older versionmoves to the main thread on its next run; that thread and its reports stay. Thediff --git a/server/index.ts b/server/index.tsindex 3c4809a626..93128773ea 100644--- a/server/index.ts+++ b/server/index.ts@@ -270,7 +270,7 @@ import {import { EventBus } from "./harness/bus.ts"; import { publicReplyEvent } from "./harness/public-reply.ts";import { ENGINE_LIST_REUSE_MS, engineMemory, enginesByUse, ProviderRegistry } from "./harness/registry.ts"; import { afterFirstEngineRead, holdUntilFirstEngineRead } from "./first-engine-read.ts"; import { HANDOFF_BROWSER_NOTE, HANDOFF_BROWSER_ONLY, handoffSurface, StoppedHandoffs, stoppedHandoffResult } from "./host/handoff-browser.ts";import { ManagedDesktopProviders } from "./managed-desktop.ts";-import { mainThread, wasOldestThread } from "./main-thread.ts"; import { createThreadSaveLines, createThreadScope, reachThreads, scopedMemoryUpdate, threadNotesPrompt } from "./thread-notes.ts";+import { mainThread, mainThreadToKeep, wasOldestThread } from "./main-thread.ts"; import { createThreadSaveLines, createThreadScope, reachThreads, scopedMemoryUpdate, threadNotesPrompt } from "./thread-notes.ts";import { computerKindForResource, ManagedDesktopPolicy, type ComputerKind } from "./managed-policy.ts"; import { nudgeCloudTeamPolicy, remoteAccessPaths, startCloudTeamPolicy, stopCloudTeamPolicy } from "./cloud-team-policy.ts"; import { startCloudTeamRoster, stopCloudTeamRoster } from "./cloud-team-roster.ts"; import { createTeamWelcomeStore } from "./team-welcome.ts"; import { teamOnboarding, teamSignInFor } from "./host/team-join-host.ts";import { hostedModelPolicy, HOSTED_MODEL_POLICY_HEADER } from "./hosted-models.ts";import { CLOUD_HOME_SECRET_KEYS, CLOUD_IGNORED_KEYS, cloudHomeConfiguration, cloudHomeOffersPlace, cloudHomePlaceRefusal, firstCloudTurnPatch } from "./cloud-home.ts";@@ -8544,7 +8544,7 @@ function routineSourceOwner(run: Pick<RoutineRun, "botId" | "sourceThreadId" | "function mainThreadTasks(botId: string) { const tasks = store.tasks(botId), own = store.bot(botId)?.defaultBot?.person ? [...tasks].sort((a, b) => a.createdAt - b.createdAt)[0]?.threadId : undefined; return CLOUD_TEAM ? tasks.filter((task) => (teamHost.audienceOf(task.threadId) === "team" && !conversationShares.fromSlack(task.threadId)) || task.threadId === own) : CLOUD_HOME ? tasks.filter((task) => !cloudGuestOpened(task.threadId) && !personalSlackMessages?.channelThread(task.threadId)) : tasks; }function botMainThread(botId: string): string | undefined {- return mainThread(mainThreadTasks(botId), store.bot(botId)?.mainThreadChoice);+ const tasks = mainThreadTasks(botId); return mainThread(tasks, store.keepMainThread(botId, (chosen) => mainThreadToKeep(tasks, chosen)));} const threadScoped = createThreadScope({ tasks: mainThreadTasks, chosen: (botId) => store.bot(botId)?.mainThreadChoice, room: (threadId) => Boolean(store.groupByThread(threadId)), routineRun: (threadId) => Boolean(routines?.runForThread(threadId)), team: Boolean(CLOUD_TEAM) }), threadSaveLines = createThreadSaveLines({ bus, append: (threadId, tool) => void store.appendMessage(threadId, { role: "bot", kind: "activity", tool }) });function routineSourceThread(run: RoutineRun): string | null {diff --git a/server/main-thread.e2e.test.ts b/server/main-thread.e2e.test.tsindex 66bc0133d0..49d1307060 100644--- a/server/main-thread.e2e.test.ts+++ b/server/main-thread.e2e.test.ts@@ -1,9 +1,10 @@import { randomUUID } from "node:crypto";-import { writeFileSync } from "node:fs";+import { readFileSync, writeFileSync } from "node:fs";import { join } from "node:path";import { expect, it } from "vitest";import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";import { readRegistry } from "./testing/registry.ts";+import { launchRestartableServer } from "./testing/restartable-server.ts";async function launch() {const fixture = await launchVerificationServer(process.env, undefined, undefined, undefined, undefined, { scripted: true });@@ -186,3 +187,63 @@ it("marks a job's review answer and a webhook post unread where they land", asynawait fixture.close();}}, 120_000);++it("keeps the main thread an install already had across an update, then moves it only when the person does or archives it", async () => {+ const server = await launchRestartableServer();+ const api = async (method: string, path: string, body?: unknown, status = 200) => {+ const response = await fetch(`${server.url}${path}`, {+ method, headers: { "content-type": "application/json", origin: server.url },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ });+ const value = await response.json() as any;+ expect(response.status, `${method} ${path}: ${JSON.stringify(value)}`).toBe(status);+ return value;+ };+ const cli = (...args: string[]) => runControlOmb([...args, "--url", server.url]) as Promise<any>;+ try {+ const { bot } = await cli("new-bot", "--name", "Keeper");+ const first = bot.activeTaskId as string;+ const main = async () => (await api("GET", "/api/bots")).bots.find((candidate: any) => candidate.id === bot.id).mainThreadId;+ const open = async (title: string) => (await api("POST", `/api/bots/${bot.id}/tasks`, { title, approvalMode: "ask" }, 201)).task.threadId as string;+ const write = async (threadId: string) => {+ await cli("send", "--bot", bot.id, "--task", threadId, "--text", "Note this.");+ await expect.poll(async () => ((await api("GET", `/api/threads/${threadId}/messages?limit=50`)).messages as any[]).some((message) => message.role !== "user"), { timeout: 20_000 }).toBe(true);+ await expect.poll(async () => (await api("GET", "/api/bots")).bots.find((candidate: any) => candidate.id === bot.id).busy, { timeout: 20_000 }).toBe(false);+ };+ const saved = () => readRegistry(server.dataDir).bots.find((candidate: any) => candidate.id === bot.id);+ const second = await open("Second");+ const third = await open("Third");+ await write(second);++ // What an install saved before a main thread was kept: threads stamped where the person wrote, and no choice.+ await server.stop();+ const file = join(server.dataDir, "bots.json");+ writeFileSync(file, JSON.stringify((JSON.parse(readFileSync(file, "utf8")) as any[]).map(({ mainThreadChoice: _choice, ...rest }) => rest)));+ expect(saved().tasks.find((task: any) => task.threadId === second).askedAt).toEqual(expect.any(Number));+ await server.start();+ expect(await main(), "the thread the person last wrote in, as before the update").toBe(second);+ await write(third);+ expect(await main()).toBe(second);+ await server.stop();+ expect(saved().mainThreadChoice).toBe(second);+ await server.start();+ expect(await main()).toBe(second);++ await api("PATCH", `/api/bots/${bot.id}/tasks/${second}`, { archivedAt: Date.now() });+ expect(await main(), "the oldest open conversation the person started takes over").toBe(first);+ await api("PATCH", `/api/bots/${bot.id}/tasks/${second}`, { archivedAt: null });+ await write(second);+ expect(await main(), "reopening the old main thread moves nothing").toBe(first);++ await api("PATCH", `/api/bots/${bot.id}`, { mainThreadChoice: third });+ expect(await main()).toBe(third);+ await api("PATCH", `/api/bots/${bot.id}/tasks/${third}`, { archivedAt: Date.now() });+ expect(await main()).toBe(first);+ await api("PATCH", `/api/bots/${bot.id}/tasks/${third}`, { archivedAt: null });+ expect(await main()).toBe(first);+ await api("DELETE", `/api/bots/${bot.id}/tasks/${first}`);+ expect(await main(), "deleting it moves it once more").toBe(second);+ } finally {+ await server.close();+ }+}, 180_000);diff --git a/server/main-thread.test.ts b/server/main-thread.test.tsindex 70fb29dcca..62405d01b0 100644--- a/server/main-thread.test.ts+++ b/server/main-thread.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { mainThread, oldestThread, wasOldestThread } from "./main-thread.ts";+import { mainThread, mainThreadToKeep, oldestThread, wasOldestThread } from "./main-thread.ts";const first = { threadId: "first", createdAt: 1 };const later = { threadId: "later", createdAt: 2 };@@ -46,6 +46,31 @@ describe("a bot's main thread", () => {});});+describe("the main thread a bot keeps", () => {+ const tasks = [{ ...latest, askedAt: 10 }, { ...later, askedAt: 30 }, { ...first, askedAt: 20 }];++ it("is, for a bot with none saved, the open thread a person last wrote in", () => {+ expect(mainThreadToKeep(tasks)).toBe("later");+ expect(mainThreadToKeep([latest, { ...later, askedAt: 30, archivedAt: 31 }, { ...first, askedAt: 20 }])).toBe("first");+ expect(mainThreadToKeep([latest, { ...later, askedAt: 30, routineRunId: "run" }, first])).toBe("first");+ });++ it("is the oldest open conversation a person started when nobody wrote anywhere, and nothing when there is none", () => {+ expect(mainThreadToKeep([latest, later, { ...first, openedBy: { botId: "teammate" } }])).toBe("later");+ expect(mainThreadToKeep([{ ...first, openedBy: { botId: "teammate" } }])).toBeUndefined();+ expect(mainThreadToKeep([{ ...first, archivedAt: 2 }])).toBeUndefined();+ });++ it("changes nothing while the saved thread is open", () => {+ expect(mainThreadToKeep(tasks, "latest")).toBeUndefined();+ });++ it("is the oldest open conversation a person started once the saved thread is archived or deleted, wherever they last wrote", () => {+ expect(mainThreadToKeep([latest, { ...later, askedAt: 30 }, { ...first, archivedAt: 40 }], "first")).toBe("later");+ expect(mainThreadToKeep([{ ...latest, askedAt: 50 }, later], "first")).toBe("later");+ });+});+describe("the oldest thread", () => {it("is the oldest open conversation, else the oldest archived one, never a routine run", () => {expect(oldestThread([latest, later, { ...first, routineRunId: "run" }])).toBe("later");diff --git a/server/main-thread.ts b/server/main-thread.tsindex 733c9032da..bdb5be411a 100644--- a/server/main-thread.ts+++ b/server/main-thread.ts@@ -3,6 +3,7 @@ interface MainThreadCandidate {createdAt: number;archivedAt?: number;routineRunId?: string;+ askedAt?: number;/** Set when a bot opened the thread: a hand-off, a burst lane, its own side job. */openedBy?: object;}@@ -20,13 +21,24 @@ export function wasOldestThread(tasks: readonly MainThreadCandidate[], threadId:return saved !== undefined && !tasks.some((task) => !task.routineRunId && task.archivedAt === undefined && task.createdAt < saved.createdAt);}-/** A bot's main thread, where it opens to with threads hidden and where its routines and briefs report: the one the- * person chose (while it is open), else the oldest open conversation a person started, else the oldest open one. Writing- * in another thread never moves it. */+const open = (task: MainThreadCandidate) => !task.routineRunId && task.archivedAt === undefined;++/** A bot's main thread, where it opens to with threads hidden and where its routines and briefs report: the one saved as+ * its choice (while it is open), else the oldest open conversation a person started, else the oldest open one. */export function mainThread(tasks: readonly MainThreadCandidate[], chosenId?: string): string | undefined {- const chosen = chosenId ? tasks.find((task) => task.threadId === chosenId) : undefined;- if (chosen && !chosen.routineRunId && chosen.archivedAt === undefined) return chosen.threadId;- return oldestThread(tasks.filter((task) => !task.openedBy && task.archivedAt === undefined)) ?? oldestThread(tasks);+ if (chosenId && tasks.some((task) => task.threadId === chosenId && open(task))) return chosenId;+ return oldestThread(tasks.filter((task) => !task.openedBy && open(task))) ?? oldestThread(tasks);+}++/** The thread to save as a bot's choice so its main thread stays put: nothing while the saved one is open. A bot that+ * never had one keeps the open thread a person last wrote in, where it reported until now; one whose saved thread was+ * archived or deleted moves to the oldest open conversation a person started, and reopening the old one moves nothing. */+export function mainThreadToKeep(tasks: readonly MainThreadCandidate[], chosenId?: string): string | undefined {+ if (chosenId && tasks.some((task) => task.threadId === chosenId && open(task))) return undefined;+ const asked = chosenId ? undefined : tasks.filter(open).reduce<MainThreadCandidate | undefined>(+ (latest, task) => ((task.askedAt ?? -1) > (latest?.askedAt ?? -1) ? task : latest), undefined,+ );+ return asked?.threadId ?? oldestThread(tasks.filter((task) => !task.openedBy && open(task)));}/** The conversation whose saves stay in the bot's own memory: the one the person set as main while it is open, else thediff --git a/server/store.ts b/server/store.tsindex 8d6cf32eb4..74c6c6f390 100644--- a/server/store.ts+++ b/server/store.ts@@ -1459,7 +1459,7 @@ export class Store {for (const g of rooms) this.emit({ type: "group", groupId: g.id });return true;}-+ /** A bot's saved main thread, after saving the one `keep` names for it: no save of its own, it goes with the bot's next one. */ keepMainThread(id: string, keep: (chosen?: string) => string | undefined): string | undefined { const bot = this.own(id), next = bot && keep(bot.mainThreadChoice); if (!bot || !next) return this.bot(id)?.mainThreadChoice; this.registry.changedInPlace({ kind: "bot", id }); return bot.mainThreadChoice = next; }patchBot(id: string, patch: Partial<BotRecord>): BotRecord | null {const bot = this.own(id);if (!bot) return null; patch = reshowWhenMoved(bot, patch);