Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Bot API: a Retry on a caller's line runs it again as the call
milind-soni594adf83d7fe
diff --git a/server/bot-api-host.test.ts b/server/bot-api-host.test.tsindex ca1458cffa..3141b638f4 100644--- a/server/bot-api-host.test.ts+++ b/server/bot-api-host.test.ts@@ -26,6 +26,7 @@ type Task = { threadId: string; title: string; busy: boolean; botApi?: true; botfunction fakeStore() {const bots = new Map<string, { id: string; name: string; tasks: Task[] }>([["b1", { id: "b1", name: "Scout", tasks: [] }]]);const messages = new Map<string, Message[]>();+ const leaves = new Map<string, string>();let ids = 0;const listeners: Array<(change: { type: string; botId: string }) => void> = [];const store = {@@ -50,9 +51,19 @@ function fakeStore() {return line;},messagesFor: (threadId: string) => messages.get(threadId) ?? [],+ branchMessage: (threadId: string, sourceId: string, text: string, sendId?: string, _sender?: unknown, _dataContext?: unknown, from?: Partial<Message>) => {+ const source = messages.get(threadId)?.find((line) => line.id === sourceId);+ if (!source) return null;+ const line = { ...from, id: `m${++ids}`, at: Date.now(), role: "user", kind: "text", text, parentId: source.parentId ?? null, ...(sendId ? { sendId } : {}) } as Message;+ messages.set(threadId, [...(messages.get(threadId) ?? []), line]);+ leaves.set(threadId, line.id);+ return line;+ },+ activeLeaf: (threadId: string) => leaves.get(threadId) ?? messages.get(threadId)?.at(-1)?.id ?? null,+ setActiveLeaf: (threadId: string, messageId: string) => { leaves.set(threadId, messageId); return messageId; },onChange: (listener: (change: { type: string; botId: string }) => void) => { listeners.push(listener); return () => {}; },};- return { store: store as unknown as BotApiHostDeps["store"], bots, messages, deleted: (botId: string) => { bots.delete(botId); for (const listener of listeners) listener({ type: "bot.deleted", botId }); } };+ return { store: store as unknown as BotApiHostDeps["store"], bots, messages, leaves, deleted: (botId: string) => { bots.delete(botId); for (const listener of listeners) listener({ type: "bot.deleted", botId }); } };}type Fake = ReturnType<typeof fakeStore>;@@ -545,3 +556,76 @@ describe("a key that acts as the owner", () => {expect(h.fake.bots.get("b1")!.tasks.at(-1)).toMatchObject({ approvalMode: "ask", outside: true });});});++describe("Retry in the app on a line a caller sent", () => {+ it("runs the same words again as the caller's: on the API's line, framed and fenced, and the status reads the retried turn", async () => {+ const answers = ["First answer", "Retried answer"];+ const h = await harness((fake, _botId, _prompt, opts) => {+ const text = answers.shift() ?? "Later";+ setTimeout(() => { fake.store.appendMessage(opts.threadId, { role: "bot", kind: "text", text }); opts.onSettled({ ok: true, text }); }, 30);+ });+ const key = (await h.app("POST", "/api/bots/b1/bot-api", { enabled: true })).body.key as string;+ const first = await h.call("b1", key, { message: "Sum up the report" });+ const threadId = first.body.thread as string;+ const sent = h.fake.messages.get(threadId)!.find((line) => line.role === "user")!;++ const retried = await h.host.retry("b1", threadId, sent, "send-retry");+ expect(retried).toMatchObject({ role: "user", text: "Sum up the report", via: "api", sendId: "send-retry" });+ expect(retried!.apiAsOwner).toBeUndefined();+ expect(h.fake.bots.get("b1")!.tasks[0]).toMatchObject({ rewound: true });+ const turn = h.turns.at(-1)!;+ expect(turn.opts).toMatchObject({ threadId, automationSource: "api", unattended: true, userMessage: retried });+ expect(turn.opts).not.toHaveProperty("editedMessageId");+ expect(turn.prompt).toContain("[UNTRUSTED BOT API MESSAGE]");+ expect(turn.prompt).toContain(`Received: ${new Date(sent.at).toISOString()}`);+ expect(turn.prompt).toContain("Sum up the report");++ await vi.waitFor(() => expect(h.fake.bots.get("b1")!.tasks[0]!.busy).toBe(false));+ expect(await h.call("b1", key, undefined, { method: "GET", query: `?thread=${threadId}` })).toEqual({ status: 200, body: { reply: "Retried answer", thread: threadId } });+ });++ it("leaves a person's line and a thread the person opened to the ordinary edit", async () => {+ const h = await harness(replies("Done"));+ const key = (await h.app("POST", "/api/bots/b1/bot-api", { enabled: true })).body.key as string;+ const threadId = (await h.call("b1", key, { message: "Hi" })).body.thread as string;+ const person = h.fake.store.appendMessage(threadId, { role: "user", kind: "text", text: "Mine" });+ expect(await h.host.retry("b1", threadId, person)).toBeNull();+ const own = h.fake.store.createTask("b1", "Mine")!;+ const pasted = h.fake.store.appendMessage(own.threadId, { role: "user", kind: "text", text: "Hi", via: "api" });+ expect(await h.host.retry("b1", own.threadId, pasted)).toBeNull();+ expect(h.turns).toHaveLength(1);+ });++ it("runs an owner's thread as theirs only while the key still acts as the owner", async () => {+ let allowed = true;+ const h = await harness(replies("Done"), { owner: { available: () => allowed } });+ const key = (await h.app("POST", "/api/bots/b1/bot-api", { enabled: true })).body.key as string;+ await h.app("POST", "/api/bots/b1/bot-api/acts-as-owner", { enabled: true });+ const threadId = (await h.call("b1", key, { message: "Tidy the build folder" })).body.thread as string;+ const sent = h.fake.messages.get(threadId)!.find((line) => line.role === "user")!;++ expect(await h.host.retry("b1", threadId, sent)).toMatchObject({ via: "api", apiAsOwner: true });+ expect(h.turns.at(-1)!.prompt).toContain("on their behalf at your level");+ await vi.waitFor(() => expect(h.fake.bots.get("b1")!.tasks[0]!.busy).toBe(false));++ allowed = false;+ const fenced = await h.host.retry("b1", threadId, sent);+ expect(fenced!.via).toBe("api");+ expect(fenced!.apiAsOwner).toBeUndefined();+ expect(h.turns.at(-1)!.prompt).toContain("[UNTRUSTED BOT API MESSAGE]");+ expect(h.turns.at(-1)!.prompt).not.toContain("on their behalf at your level");+ });++ it("puts the conversation back on the branch the person was reading when the turn is refused", async () => {+ const h = await harness(replies("Done"));+ const key = (await h.app("POST", "/api/bots/b1/bot-api", { enabled: true })).body.key as string;+ const threadId = (await h.call("b1", key, { message: "Hi" })).body.thread as string;+ const sent = h.fake.messages.get(threadId)!.find((line) => line.role === "user")!;+ const leaf = h.fake.store.activeLeaf(threadId);+ const refused = Object.assign(new Error("over the cap"), { status: 429 });+ const refusing = createBotApiHost({ store: h.fake.store, manager: h.manager, startTurn: async () => { throw refused; }, threadBusy: () => false, canStart: () => true, canConfine: () => true,+ hooksBaseUrl: () => "https://bots.example.test", manageRefusal: () => null });+ await expect(refusing.retry("b1", threadId, sent)).rejects.toBe(refused);+ expect(h.fake.store.activeLeaf(threadId)).toBe(leaf);+ });+});diff --git a/server/bot-api-host.ts b/server/bot-api-host.tsindex 6a8416f184..437865b2fd 100644--- a/server/bot-api-host.ts+++ b/server/bot-api-host.ts@@ -48,7 +48,7 @@ export interface BotApiTurnOptions {}export interface BotApiHostDeps {- store: Pick<Store, "bot" | "taskByThread" | "createTask" | "patchTask" | "appendMessage" | "messagesFor" | "onChange">;+ store: Pick<Store, "bot" | "taskByThread" | "createTask" | "patchTask" | "appendMessage" | "messagesFor" | "onChange" | "branchMessage" | "activeLeaf" | "setActiveLeaf">;startTurn(botId: string, text: string, opts: BotApiTurnOptions): Promise<unknown>;threadBusy(botId: string, threadId: string): boolean;/** Whether a new turn would start now, before anything is written. */@@ -213,6 +213,36 @@ export function createBotApiHost(deps: BotApiHostDeps) {return { status: 200, body: { reply: replyText(after()), thread: threadId } };}+ /** Retry, pressed in the app, on a line a caller sent: the same words go again as the caller's, framed, fenced and counted+ * as the call was, so the thread stays the API's and a status read reports the retried turn. Null for any other line,+ * which the app retries as an ordinary edit. */+ async function retry(botId: string, threadId: string, source: Message, sendId?: string): Promise<Message | null> {+ const store = deps.store;+ const task = store.taskByThread(botId, threadId);+ if (source.via !== "api" || source.role !== "user" || typeof source.text !== "string" || task?.botApi !== true) return null;+ // Never upgraded: a thread opened as the owner's work runs as theirs only while the key still acts as the owner.+ const owned = task.botApiAsOwner === true && asOwner(botId);+ const message = source.text.trim();+ const leafBefore = store.activeLeaf(threadId);+ const userMessage = store.branchMessage(threadId, source.id, message, sendId, undefined, undefined, { via: "api", ...(owned ? { apiAsOwner: true as const } : {}) });+ if (!userMessage) return null;+ store.patchTask(botId, threadId, { rewound: true });+ markRunning(botId, threadId, true);+ try {+ await deps.startTurn(botId, owned ? botApiOwnerPrompt(message) : botApiPrompt(message, source.at), {+ threadId, automationSource: "api", unattended: true, userMessage,+ onSettled: () => markRunning(botId, threadId, false),+ onDispatchError: () => markRunning(botId, threadId, false),+ });+ } catch (error) {+ // A turn that never started leaves the conversation on the branch the person was reading.+ markRunning(botId, threadId, false);+ if (leafBefore) store.setActiveLeaf(threadId, leafBefore);+ throw error;+ }+ return userMessage;+ }+const door: IngressDoor = async (req, res, url) => {const match = PUBLIC_PATH.exec(url.pathname);if (!match) return false;@@ -367,5 +397,5 @@ export function createBotApiHost(deps: BotApiHostDeps) {}};- return { manager, door, routes };+ return { manager, door, routes, retry };}diff --git a/server/bot-api.e2e.test.ts b/server/bot-api.e2e.test.tsindex 6b23e9dc4d..c2f8829c91 100644--- a/server/bot-api.e2e.test.ts+++ b/server/bot-api.e2e.test.ts@@ -3,7 +3,8 @@// and, on a bot that asks before acting, a call that stops at the approval nobody outside may give.import { execFile } from "node:child_process";import { randomUUID } from "node:crypto";-import { mkdirSync, readFileSync, realpathSync } from "node:fs";+import { mkdirSync, mkdtempSync, readFileSync, realpathSync } from "node:fs";+import { tmpdir } from "node:os";import { connect, type Socket } from "node:net";import { join } from "node:path";import { afterEach, expect, it } from "vitest";@@ -261,3 +262,40 @@ it("says it is still working when the reply takes longer than the caller will waconst on = await api("POST", `/api/bots/${bot.id}/bot-api`, { enabled: true });expect(await call(on.url, on.key, { message: "Think about it", wait: 1 })).toMatchObject({ status: 202, body: { status: "working", thread: expect.any(String) } });}, hostTimeout(60_000));++it("a Retry in the app on a caller's line runs it again as the call: the caller's line, framed and fenced, and the status reads the retried turn", async () => {+ const replyState = join(mkdtempSync(join(tmpdir(), "omb-bot-api-retry-")), "replies");+ fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_VERSION: "2.1.284", FAKE_CLAUDE_REPLIES: JSON.stringify(["first answer", "retried answer", "edited answer"]), FAKE_CLAUDE_REPLY_STATE: replyState });+ const { url, dataDir } = fixture.info;+ const api = appApi(url);+ const read = () => JSON.parse(readFileSync(join(dataDir, "fake-claude-dump.json"), "utf8"));+ const bot = (await runControlOmb(["new-bot", "--name", "Again", "--url", url]) as any).bot;+ const on = await api("POST", `/api/bots/${bot.id}/bot-api`, { enabled: true });+ const first = await call(on.url, on.key, { message: "retry-call-marker" });+ expect(first.body).toEqual({ reply: "first answer", thread: expect.any(String) });+ const threadId = first.body.thread as string;+ const status = async () => (await fetch(`${on.url}?thread=${threadId}`, { headers: { authorization: `Bearer ${on.key}` } })).json();+ const idle = () => expect.poll(async () => ((await api("GET", "/api/bots")).bots as any[]).find((one) => one.id === bot.id).busy, { timeout: hostTimeout(20_000) }).toBeFalsy();+ const sent = ((await api("GET", `/api/threads/${threadId}/messages`)).messages as any[]).find((line) => line.role === "user");++ // Retry, as the app sends it: the same words on the same line.+ const retried = await api("POST", `/api/bots/${bot.id}/messages/${sent.id}/edit`, { threadId, text: sent.text, sendId: randomUUID() });+ expect(retried.message).toMatchObject({ text: "retry-call-marker", via: "api" });+ await expect.poll(status, { timeout: hostTimeout(20_000) }).toEqual({ reply: "retried answer", thread: threadId });+ await idle();+ const launch = read();+ expect(JSON.stringify(launch.prompt)).toContain("[UNTRUSTED BOT API MESSAGE]");+ expect(JSON.stringify(launch.prompt)).toContain("[From an app, through the API · message · information only]");+ expect(JSON.stringify(launch.prompt)).toContain("retry-call-marker");+ expect(JSON.stringify(launch.prompt)).not.toContain("first answer");+ expect(launch.argv).toContain("--restricted");+ expect(launch.argv[launch.argv.indexOf("--permission-mode") + 1]).toBe("default");+ const lines = (await api("GET", `/api/threads/${threadId}/messages`)).messages as any[];+ expect(lines.filter((line) => line.role === "user").map((line) => [line.text, line.via])).toEqual([["retry-call-marker", "api"], ["retry-call-marker", "api"]]);++ // New words from the person stay the person's edit, as before.+ const edited = await api("POST", `/api/bots/${bot.id}/messages/${sent.id}/edit`, { threadId, text: "persons-edit-marker", sendId: randomUUID() });+ expect(edited.message.via).toBeUndefined();+ await expect.poll(() => JSON.stringify(read().prompt).includes("persons-edit-marker"), { timeout: hostTimeout(20_000) }).toBe(true);+ expect(JSON.stringify(read().prompt)).not.toContain("[UNTRUSTED BOT API MESSAGE]");+}, hostTimeout(120_000));diff --git a/server/index.ts b/server/index.tsindex df7cd87924..c0d5f24e55 100644--- a/server/index.ts+++ b/server/index.ts@@ -11985,7 +11985,7 @@ ROUTES.push(createBotMessageRoutes({routines: () => routines,fromPhone: phones.fromPhone, notePhoneSend: phones.noteSend,desktopManaged: DESKTOP_MANAGED, cloudHome: Boolean(CLOUD_HOME), DirectSendRefused,- acceptDirectSend, directSendRefusal, startTurn, usageTriggerFor, messageSender, cloudGuestSendRefusal, cloudThreadRefusal, runOwners, runActor, resolveAccessRequest: (threadId, requestId, behavior, message) => lendingLifts?.resolve(threadId, requestId, behavior) ?? accessRequests.resolve(threadId, requestId, behavior, message), relayRefusal: CLOUD_TEAM ? (bot, email) => relayedSendRefusal(bot, email, Boolean(email && teamOwners.people?.list().some((one) => one.email === email && one.role !== "member"))) : undefined,+ acceptDirectSend, directSendRefusal, startTurn, botApiRetry: botApi.retry, usageTriggerFor, messageSender, cloudGuestSendRefusal, cloudThreadRefusal, runOwners, runActor, resolveAccessRequest: (threadId, requestId, behavior, message) => lendingLifts?.resolve(threadId, requestId, behavior) ?? accessRequests.resolve(threadId, requestId, behavior, message), relayRefusal: CLOUD_TEAM ? (bot, email) => relayedSendRefusal(bot, email, Boolean(email && teamOwners.people?.list().some((one) => one.email === email && one.role !== "member"))) : undefined,noAiRefusal: noAiNotice.refusal, cardAnswerRefusal, commandRememberRefusal, requestBehavior, requestedTaskBot, botForThread, threadBusy,botAtThreadCapacity, parksBehindCoordination, activeGroupTurnForBot, runningTurnInstance, engineSteersImages, resolveReplyTarget,turnSelection, policyModelRefusal, clearUnattended, drainQueuedSends, answeringCardAs, resolveAndSendTrust, resolveAndSendTeamSetup, resolveAndSendMcp,diff --git a/server/routes/bot-messages.test.ts b/server/routes/bot-messages.test.tsindex e4b2a74435..bc449ff97d 100644--- a/server/routes/bot-messages.test.ts+++ b/server/routes/bot-messages.test.ts@@ -221,6 +221,44 @@ describe("editing a message with no AI", () => {});});+describe("Retry on a line a caller sent through the Bot API", () => {+ const apiRetry = (calls: Array<[string, string, Message, string | undefined]>, store: () => Store) => ({+ botApiRetry: async (botId: string, threadId: string, source: Message, sendId?: string) => {+ calls.push([botId, threadId, source, sendId]);+ if (source.via !== "api") return null;+ return store().branchMessage(threadId, source.id, source.text!.trim(), sendId, undefined, undefined, { via: "api" });+ },+ });++ it("hands the same words on a caller's line to the Bot API, which runs them as the call ran", async () => {+ const calls: Array<[string, string, Message, string | undefined]> = [];+ let held: Store | undefined;+ const { store, bot, threadId, state, edit } = await fixture(apiRetry(calls, () => held!));+ held = store;+ const sent = store.appendMessage(threadId, { role: "user", kind: "text", text: "Sum up the report\n", via: "api" });+ const answer = await edit(sent.id, { threadId, text: "Sum up the report", sendId: SEND });+ expect(answer).toMatchObject({ status: 202, body: { ok: true, message: { text: "Sum up the report", via: "api", sendId: SEND } } });+ expect(calls).toEqual([[bot.id, threadId, expect.objectContaining({ id: sent.id }), SEND]]);+ expect(state.started).toEqual([]);+ });++ it("keeps new words on a caller's line, and the same words on a person's line, an ordinary edit", async () => {+ const calls: Array<[string, string, Message, string | undefined]> = [];+ let held: Store | undefined;+ const { store, threadId, state, edit } = await fixture(apiRetry(calls, () => held!));+ held = store;+ const sent = store.appendMessage(threadId, { role: "user", kind: "text", text: "Sum up the report", via: "api" });+ expect((await edit(sent.id, { threadId, text: "Sum up the other report" })).status).toBe(202);+ const mine = store.appendMessage(threadId, { role: "user", kind: "text", text: "Mine" });+ expect((await edit(mine.id, { threadId, text: "Mine" })).status).toBe(202);+ expect(calls).toEqual([]);+ expect(state.started).toMatchObject([+ { text: "Sum up the other report", opts: { editedMessageId: sent.id } },+ { text: "Mine", opts: { editedMessageId: mine.id } },+ ]);+ });+});+describe("running a request again where several people write", () => {const PRIYA = "p_priyapriyapriyapriyapr", TOM = "p_tomtomtomtomtomtomtomt";const team = (by: { person?: string; admin: boolean }, shared = true) => ({diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.tsindex 339b4308d0..8d6311a1e6 100644--- a/server/routes/bot-messages.ts+++ b/server/routes/bot-messages.ts@@ -76,6 +76,8 @@ export interface BotMessageRouteDeps {threadId?: string; replyTo?: Message; sendId?: string; sender?: ResolvedSender; trigger?: UsageTrigger; relayed?: boolean;dataContext?: DataContext; compactOnly?: boolean; cardContinuation?: boolean; editedMessageId?: string;}): Promise<Message>;+ /** Retry on a line a caller sent through the Bot API, run as that call ran (bot-api-host.ts); null for any other line. */+ botApiRetry?(botId: string, threadId: string, source: Message, sendId?: string): Promise<Message | null>;usageTriggerFor(auth: RequestAuth): UsageTrigger;messageSender(auth: RequestAuth): ResolvedSender | undefined;cloudGuestSendRefusal(auth: RequestAuth, threadId: string): string | null;@@ -555,6 +557,9 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerconst rerunInstance = registry.get(rerunSelection.instanceId)!;const rerunRefusal = policyModelRefusal(rerunInstance);if (rerunRefusal) return json(res, 409, { error: rerunRefusal });+ // The same words again on a caller's line: the caller's message again, never the person's own.+ const apiRetry = source.via === "api" && text === source.text?.trim() ? await deps.botApiRetry?.(bot.id, bot.threadId, source, sendId) : null;+ if (apiRetry) return json(res, 202, { ok: true, message: apiRetry });const quoted = source.replyToId ? resolveReplyTarget(bot.threadId, source.replyToId) : undefined;const replyTo: ReplyTarget | undefined = quoted && source.reaction && text === source.text ? { ...quoted, reactedWith: source.reaction } : quoted;const dataContext = parseDataContext(body.dataContext) ?? (text === source.text ? source.dataContext : undefined);diff --git a/server/store.ts b/server/store.tsindex e3120d9215..61d6e5abbf 100644--- a/server/store.ts+++ b/server/store.ts@@ -1198,7 +1198,7 @@ export class Store {return pruned;}- branchMessage(threadId: string, sourceId: string, text: string, sendId?: string, sender?: Message["sender"], dataContext?: Message["dataContext"]): Message | null {+ branchMessage(threadId: string, sourceId: string, text: string, sendId?: string, sender?: Message["sender"], dataContext?: Message["dataContext"], from?: Pick<Message, "via" | "apiAsOwner">): Message | null {const t = this.thread(threadId);const source = t.messages.find((m) => m.id === sourceId);if (!source) return null;@@ -1213,7 +1213,7 @@ export class Store {...(source.reaction && source.text === text ? { reaction: source.reaction } : {}),...(sendId ? { sendId } : {}),...(sender ? { sender } : {}),- ...(dataContext ? { dataContext } : {}),+ ...(dataContext ? { dataContext } : {}), ...from,};t.messages.push(full); this.threads.grew(threadId, full);t.activeLeafId = full.id;