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 failed call reports to no Chief, and a person hears the API's reason
milind-soni10744220e395
diff --git a/docs/bot-api.md b/docs/bot-api.mdindex cb10d70686..a48d3b1d56 100644--- a/docs/bot-api.md+++ b/docs/bot-api.md@@ -72,7 +72,8 @@ saved memory and the thread itself, whoever writes there next:teammate, make a routine or webhook, change the bot, write its memory or searchother conversations.- It works in the thread's own empty folder, and its words stay out of the person's- other conversations.+ other conversations. A call that fails shows on the card and in its thread, and+ reports to no Chief.A key is like a password: whoever holds it can read what this bot can read, whichhere means its instructions and memory, through its replies. A bot whose AI can't rundiff --git a/server/bot-api-fence.ts b/server/bot-api-fence.tsindex c55f203411..debf957c52 100644--- a/server/bot-api-fence.ts+++ b/server/bot-api-fence.ts@@ -7,7 +7,8 @@// - of OpenMausBot's own routes it may reach only the engine's hooks and the paging of its own long results;// - its system prompt keeps the bot's standing instructions, its saved memory and the rules for reading who sent a line,// and nothing about the person or their work;-// - what it says never reaches the person's other conversations.+// - what it says never reaches the person's other conversations, and its problems are no report to a Chief, whose turn has+// tools and would read its words.export const BOT_API_TOOLS: ReadonlySet<string> = new Set(["hooks"]);export const BOT_API_PARTS: ReadonlySet<string> = new Set(["memory", "webhook", "coordination"]);const ROUTES: ReadonlySet<string> = new Set([@@ -18,6 +19,9 @@ const ROUTES: ReadonlySet<string> = new Set([export const BOT_API_REFUSAL = "This call came in through the Bot API, so it can only answer from what this bot already knows.";+/** What a person hears on typing into an API thread whose engine can't be confined: the thread is why, not their Cloud. */+export const BOT_API_ENGINE_REFUSAL = "This thread came in through the Bot API, and this bot's AI can't work in it. Start a new conversation.";+export function botApiRouteRefused(method: string, path: string): boolean {return !ROUTES.has(`${method.toUpperCase()} ${path}`);}diff --git a/server/bot-api.e2e.test.ts b/server/bot-api.e2e.test.tsindex b06c0d032a..6b23e9dc4d 100644--- a/server/bot-api.e2e.test.ts+++ b/server/bot-api.e2e.test.ts@@ -11,6 +11,8 @@ import { afterEach, expect, it } from "vitest";import { launchVerificationServer, runControlOmb, type VerificationServer } from "../scripts/control-omb.ts";import { botApiCurl } from "../shared/bot-api.ts";import { hostTimeout } from "./testing/host-timeout.ts";+import { BOT_API_REFUSAL } from "./bot-api-fence.ts";+import { INCIDENTS_THREAD_TITLE } from "./incidents.ts";let fixture: VerificationServer | undefined;let socket: Socket | undefined;@@ -211,6 +213,46 @@ it("tells the model nothing about the person or their work, works in no folder oexpect(JSON.stringify(next.prompt)).not.toContain("api-call-marker");}, hostTimeout(120_000));+it("a failed call reports to no Chief, whose turn has tools, while a person's own failed turn still does", async () => {+ fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_VERSION: "2.1.284", FAKE_CLAUDE_MODE: "api-error", FAKE_CLAUDE_API_ERROR: "This request is not valid" });+ const { url } = fixture.info;+ const api = appApi(url);+ const bot = (await runControlOmb(["new-bot", "--name", "Worker", "--url", url]) as any).bot;+ const on = await api("POST", `/api/bots/${bot.id}/bot-api`, { enabled: true });+ const bots = async () => (await api("GET", "/api/bots")).bots as any[];+ const chief = (await bots()).find((one) => one.chiefOfStaff);+ expect(chief, "the fixture has a Chief").toBeTruthy();+ const reports = async () => (await bots()).find((one) => one.id === chief.id).tasks.filter((task: any) => task.title === INCIDENTS_THREAD_TITLE);++ const failed = await call(on.url, on.key, { message: "caller-words-marker", wait: 20 });+ expect(failed.status).toBe(502);+ await new Promise((resolve) => setTimeout(resolve, 1_500));+ expect(await reports()).toEqual([]);++ // The control: the same failure from a person reaches the Chief, so the silence above means something.+ await api("POST", `/api/bots/${bot.id}/messages`, { text: "persons-own-words" });+ await expect.poll(async () => (await reports()).length, { timeout: hostTimeout(45_000) }).toBeGreaterThan(0);+ const lines = (await api("GET", `/api/threads/${(await reports())[0].threadId}/messages`)).messages;+ expect(JSON.stringify(lines)).not.toContain("caller-words-marker");+}, hostTimeout(120_000));++it("gives a caller fixed words and a person the Bot API's reason when the engine is too old to confine the call", async () => {+ fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_VERSION: "2.1.200" });+ const { url } = fixture.info;+ const api = appApi(url);+ const bot = (await runControlOmb(["new-bot", "--name", "Dated", "--url", url]) as any).bot;+ const on = await api("POST", `/api/bots/${bot.id}/bot-api`, { enabled: true });+ const failed = await call(on.url, on.key, { message: "Hello", wait: 20 });+ expect(failed.status).toBe(502);+ expect(JSON.stringify(failed.body)).not.toContain("too old");+ const { bots } = await api("GET", "/api/bots");+ const thread = bots.find((one: any) => one.id === bot.id).tasks.find((task: any) => task.botApi).threadId;+ const said = async () => JSON.stringify((await api("GET", `/api/threads/${thread}/messages`)).messages);+ await expect.poll(said, { timeout: hostTimeout(15_000) }).toContain("too old to run this turn");+ expect(await said()).toContain(BOT_API_REFUSAL);+ expect(await said()).not.toContain("My Cloud");+}, hostTimeout(60_000));+it("says it is still working when the reply takes longer than the caller will wait", async () => {fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_VERSION: "2.1.284", FAKE_CLAUDE_MODE: "hang" });const { url } = fixture.info;diff --git a/server/cloud-guest-shell.e2e.test.ts b/server/cloud-guest-shell.e2e.test.tsindex 60b89f8edb..da525205e1 100644--- a/server/cloud-guest-shell.e2e.test.ts+++ b/server/cloud-guest-shell.e2e.test.ts@@ -1,5 +1,6 @@// The real server booted the way the image's launcher boots it (secrets over a pipe, never the environment), synthetic// engines. No guest can connect, so what a guest left behind is written into the records while the server is stopped.+import { BOT_API_ENGINE_REFUSAL } from "./bot-api-fence.ts";import { randomBytes, randomUUID } from "node:crypto";import { connect } from "node:net";import { spawn, type ChildProcess } from "node:child_process";@@ -382,3 +383,20 @@ it("a room a guest opened with a bot whose engine needs its shell refuses the tuawait expect.poll(async () => ((await api("GET", `/api/threads/${room.body.group.threadId}/messages`, { token: owner })).body.messages as any[]).some((message) => String(message.tool?.name ?? "").includes("this bot's AI can't work in it")), { timeout: hostTimeout(15_000) }).toBe(true);}, hostTimeout(60_000));++it("a person typing into a Bot API thread whose engine needs its shell is told so in the API's words", async () => {+ const bot = await newBot("Called bot", "codex");+ const on = (await api("POST", `/api/bots/${bot.id}/bot-api`, { token: owner, body: { enabled: true } })).body;+ const endpoint = new URL(new URL(on.url).pathname, `http://127.0.0.1:${Number(new URL(base).port) + 1}`);+ const called = await fetch(endpoint, { method: "POST", headers: { authorization: `Bearer ${on.key}`, "content-type": "application/json" }, body: JSON.stringify({ message: "Hello.", wait: 0 }) });+ const { thread } = await called.json() as { thread: string };+ await expect.poll(async () => ((await api("GET", `/api/threads/${thread}/messages`, { token: owner })).body.messages as any[])+ .some((message) => message.role === "bot" && message.kind === "text"), { timeout: hostTimeout(15_000) }).toBe(true);+ // A send while the turn is still settling queues, and would answer 202; the bot's own model moves too, since a thread+ // whose engine is not ready gives way to the bot's, which could confine it.+ await expect.poll(async () => (await api("GET", "/api/bots", { token: owner })).body.bots.find((one: any) => one.id === bot.id).tasks.find((task: any) => task.threadId === thread).busy, { timeout: hostTimeout(15_000) }).toBeFalsy();+ expect((await api("PATCH", `/api/bots/${bot.id}/tasks/${thread}`, { token: owner, body: { modelSelection: { instanceId: "shelled", model: "claude-sonnet-5" }, updateBotDefault: true } })).status).toBeLessThan(300);+ const refused = await say(owner, bot, "Hello.", thread);+ expect(refused.status, JSON.stringify(refused.body)).toBe(409);+ expect(refused.body.error).toBe(BOT_API_ENGINE_REFUSAL);+}, hostTimeout(60_000));diff --git a/server/index.ts b/server/index.tsindex 205d97e977..6f28d7d142 100644--- a/server/index.ts+++ b/server/index.ts@@ -469,7 +469,7 @@ import { createOutboundHold, OUTBOUND_HOLD_MS, type OutboundHoldAnswer } from ".import { connectorCallsIn, outboundCallsIn } from "../shared/outbound.ts";import { connectorAccessDecision, describeConnectorScopes } from "../shared/connector-scopes.ts";import { bindThreadLogCapProvider } from "./thread-log-rotation.ts";-import { listenWebhookIngress, type WebhookIngress } from "./webhook-ingress.ts"; import { createBotApiHost } from "./bot-api-host.ts"; import { BOT_API_PARTS, BOT_API_REFUSAL, BOT_API_TOOLS, botApiRouteRefused } from "./bot-api-fence.ts";+import { listenWebhookIngress, type WebhookIngress } from "./webhook-ingress.ts"; import { createBotApiHost } from "./bot-api-host.ts"; import { BOT_API_ENGINE_REFUSAL, BOT_API_PARTS, BOT_API_REFUSAL, BOT_API_TOOLS, botApiRouteRefused } from "./bot-api-fence.ts";import { addressFor } from "./webhook-address.ts";import { assertModelVariantSupported, memberTurnSelection } from "./member-turn.ts";import { WebhookManager } from "./webhooks.ts";@@ -7071,7 +7071,7 @@ function runtimeWorkPending(threadId: string): boolean {}const { reportIncident, reportEscalation, incidentRefused, retryThread } = createChiefNotices({- store, notify, threadBusy, botAtThreadCapacity, startTurn, quietThread: (_botId, threadId) => proactive.fence.confines(threadId), privateThread: (threadId) => teamHost.ownTurn(threadId), threadLanguage,+ store, notify, threadBusy, botAtThreadCapacity, startTurn, quietThread: (_botId, threadId) => proactive.fence.confines(threadId) || botApiThread(threadId), privateThread: (threadId) => teamHost.ownTurn(threadId), threadLanguage,assignerOf: (threadId) => coordinator.assignerOf(threadId),threadSettling: (threadId) => settlingTurns.has(threadId), threadQueued: (botId, threadId) => queuedThreadPosition(botId, threadId) !== null,groupTurnActive: (botId) => Boolean(activeGroupTurnForBot(botId)),@@ -7756,7 +7756,7 @@ async function beginTurn(guestDrivenTurns.delete(threadId);const guestConfined = cloudGuestDriven(threadId) || cloudGuestDrivenHandoff(opts?.coordination?.id) || botApiDriven(threadId);if (guestConfined && instance.adapter.capabilities.guestTurns !== "confined") {- throw Object.assign(new Error(guestEngineRefusal(threadId)), { status: 409, code: "guest_engine" });+ throw Object.assign(new Error(botApiDriven(threadId) ? BOT_API_ENGINE_REFUSAL : guestEngineRefusal(threadId)), { status: 409, code: "guest_engine" });}const resolvedImages = extractTurnImages(text);const usesNativeImageInput = instance.adapter.capabilities.nativeImageInput === true;@@ -8578,7 +8578,7 @@ async function beginTurn(approvalMode: approvalModeForTurn(bot, commsDepth > 0, threadId),approvalModeNow: () => liveApprovalMode(bot, threadId, commsDepth > 0),toolScope,- ...(guestConfined ? { guestConfined: true, confinedWhy: confinedWhy(threadId) } : {}),+ ...(guestConfined ? { guestConfined: true, confinedWhy: botApiDriven(threadId) ? BOT_API_REFUSAL : confinedWhy(threadId) } : {}),model,effort,variant,