Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Count the engines that can start a bot for a local check, and let doctor use it on a shared server
milind-soni1e6b83472b47
diff --git a/docs/headless-cli.md b/docs/headless-cli.mdindex 6eac07c11f..3150d63f90 100644--- a/docs/headless-cli.md+++ b/docs/headless-cli.md@@ -90,7 +90,7 @@ one of its conversations.| Command | What it does ||---|---|-| `doctor [--wait 2m]` | Checks the server answers, is new enough, who you are to it (and when your session expires), that an engine is ready, and whether bots have a browser. |+| `doctor [--wait 2m]` | Checks the server answers, is new enough, who you are to it (and when your session expires), that an engine is ready, and whether bots have a browser. On a shared server without a session (`docker compose exec omb openmausbot doctor`), it learns only how many engines are ready, not which (`GET /api/health/engines`). || `doctor --host` | Checks this Linux machine can run the server and the bots' sandbox (below). || `bots`, `channels`, `models` | Your bots and what each is doing, your rooms, the engines and the models each offers. || `messages TARGET [--limit 30]` | The latest messages of a conversation. |diff --git a/scripts/mcp-server.ts b/scripts/mcp-server.tsindex 394fcf6154..b305b15477 100644--- a/scripts/mcp-server.ts+++ b/scripts/mcp-server.ts@@ -74,10 +74,9 @@ async function fetchJson(url: string, options: RequestInit = {}): Promise<any> {if (!response.ok) {const text = await response.text().catch(() => "");if (response.status === 403 && !new Headers(headers).has("Authorization")) {- throw new OpenMausBotApiError(403,- "OpenMausBot refused this write because the installed desktop app requires a paired session token. " +- "Set OPENMAUSBOT_TOKEN as described in docs/mcp-server.md.",- );+ throw new OpenMausBotApiError(403, /on this shared server/.test(text) // the server says which kind refused it+ ? "This is a shared server, so a program on it without a paired session token may only check its health. Set OPENMAUSBOT_TOKEN to a paired session (openmausbot connect), as described in docs/mcp-server.md."+ : "OpenMausBot refused this request because the installed desktop app requires a paired session token. Set OPENMAUSBOT_TOKEN as described in docs/mcp-server.md.");}throw new OpenMausBotApiError(response.status, `OpenMausBot API error (${response.status}): ${text || response.statusText}`);}diff --git a/server/headless/commands.ts b/server/headless/commands.tsindex 280237a07f..f02038595a 100644--- a/server/headless/commands.ts+++ b/server/headless/commands.ts@@ -18,10 +18,16 @@ const DAY = 24 * 3_600_000;async function doctorOnce(ctx: VerbContext): Promise<VerbOutcome> {const client = await ctx.client();- const [rawHealth, models] = await Promise.all([client.tool("get_system_health", {}), client.tool("list_available_models", {})]);+ // A shared server lets a local caller without a session count its engines, not list them: in the server's container+ // (`docker compose exec omb openmausbot doctor`, as deploy/update.sh runs it) that count is the answer.+ const counted = (refusal: unknown) => (refusal as { status?: unknown })?.status === 403+ ? client.json<Rec>("/api/health/engines").then((answer) => ({ counted: Number(answer?.engines) || 0 }), () => Promise.reject(refusal))+ : Promise.reject(refusal);+ const [rawHealth, models] = await Promise.all([client.tool("get_system_health", {}), client.tool("list_available_models", {}).catch(counted)]);const health = { ...rawHealth, endpoint: client.baseUrl };const instances: Rec[] = Array.isArray(models?.instances) ? models.instances : [];const availableEngines = instances.filter((instance) => instance.snapshot?.state === "available").map((instance) => instance.instanceId);+ const availableCount = typeof models?.counted === "number" ? models.counted : availableEngines.length;const quietly = <T>(read: Promise<T>) => read.catch(() => null);const [server, session, config] = await Promise.all([quietly(client.json<Rec>("/.well-known/openmausbot/environment")),@@ -34,19 +40,19 @@ async function doctorOnce(ctx: VerbContext): Promise<VerbOutcome> {if (!isOmb) problems.push(`${client.baseUrl} answered, but it is not OpenMausBot`);const tooOld = Boolean(server) && server!.capabilities?.jobs !== true;if (tooOld) problems.push(`OpenMausBot ${server!.version ?? "(unknown version)"} is too old for the headless commands: it cannot report a conversation's job`);- if (isOmb && !availableEngines.length) problems.push("no engine is available: set one up with `openmausbot engine set KIND --key-env VAR`");+ if (isOmb && !availableCount) problems.push("no engine is available: set one up with `openmausbot engine set KIND --key-env VAR`");if (session?.kind === "session" && typeof session.expiresAt === "number" && session.expiresAt - Date.now() < 14 * DAY) {warnings.push(`this session expires in ${Math.max(0, Math.floor((session.expiresAt - Date.now()) / DAY))} days: get a new one with openmausbot connect`);}const browser = config?.browserEngine ?? null;if (browser && browser.kind !== "engine") warnings.push(`bots have no built-in browser here: ${browser.reason ?? "not installed"}${browser.installable ? " (install it with `openmausbot browser install`)" : ""}`);- const ok = isOmb && !tooOld && availableEngines.length > 0;+ const ok = isOmb && !tooOld && availableCount > 0;const who = !session ? "unknown" : session.kind === "loopback"? `this computer${session.trust === "service" ? " (as a local service, not the owner)" : " (the owner)"}`: `session "${session.label || "unnamed"}" with ${Array.isArray(session.scopes) && session.scopes.includes("admin") ? "full access" : "chat access"}${typeof session.expiresAt === "number" ? `, until ${new Date(session.expiresAt).toISOString().slice(0, 10)}` : ""}`;return {result: {- ok, health, availableEngines, instances,+ ok, health, availableEngines, availableEngineCount: availableCount, instances,server: server ? { version: server.version, label: server.label, environmentId: server.environmentId, capabilities: server.capabilities } : null,session: session ? { kind: session.kind, ...(session.label !== undefined ? { label: session.label } : {}), scopes: session.scopes,...(session.expiresAt !== undefined ? { expiresAt: session.expiresAt } : {}), ...(session.trust ? { trust: session.trust } : {}) } : null,@@ -56,7 +62,7 @@ async function doctorOnce(ctx: VerbContext): Promise<VerbOutcome> {human: [`${server ? `OpenMausBot ${server.version} ("${server.label}")` : "OpenMausBot"} at ${client.baseUrl}: ${ok ? "ready" : "not ready"}`,`You are: ${who}`,- `Engines available: ${availableEngines.length ? availableEngines.join(", ") : "none"}`,+ `Engines available: ${availableEngines.length ? availableEngines.join(", ") : availableCount ? `${availableCount} (which ones needs a session)` : "none"}`,...(browser ? [`Bots' browser: ${browser.kind === "engine" ? `installed${browser.version ? ` (${browser.version})` : ""}` : "not available"}`] : []),...problems.map((line) => `problem: ${line}`),...warnings.map((line) => `warning: ${line}`),diff --git a/server/headless/doctor.test.ts b/server/headless/doctor.test.tsnew file mode 100644index 0000000000..642562b74a--- /dev/null+++ b/server/headless/doctor.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it, vi } from "vitest";++import type { HeadlessIo } from "./output.ts";+import { runHeadless } from "./main.ts";++const refused = (status: number) => Object.assign(new Error(`OpenMausBot API error (${status}): {"error":"forbidden"}`), { status });++/** `openmausbot doctor` on a server whose local callers without a session get the service routes only: a shared server,+ * or one in the hardened profile, as in the server's container, where deploy/update.sh runs it. */+function sharedServer(engines: number | "old server") {+ const callTool = vi.fn(async (name: string) => {+ if (name === "get_system_health") return { status: "connected", app: "openmausbot", packaged: true };+ if (name === "list_available_models") throw refused(403);+ throw new Error(`unexpected tool ${name}`);+ });+ const request = vi.fn(async (path: string) => {+ if (path === "/api/health/engines") {+ if (engines === "old server") throw refused(403);+ return { app: "openmausbot", engines };+ }+ if (path === "/.well-known/openmausbot/environment") return { version: "0.1.160", label: "maus.example.com", capabilities: { jobs: true } };+ if (path === "/api/auth/session") return { kind: "loopback", scopes: ["client"], trust: "service" };+ throw refused(403);+ });+ const out: string[] = [];+ const io: HeadlessIo = { out: (text) => out.push(text), err: () => {}, readStdin: async () => "" };+ return async (argv: string[]) => {+ const code = await runHeadless(argv, { env: { OPENMAUSBOT_URL: "http://127.0.0.1:19999" }, io, callTool: callTool as any, request: request as any });+ return { code, out };+ };+}++describe("doctor on a shared server, without a session", () => {+ it("is ready when the server counts an engine that can start a bot, without naming it", async () => {+ const { code, out } = await sharedServer(1)(["doctor", "--json"]);+ expect(code).toBe(0);+ expect(JSON.parse(out.at(-1)!)).toMatchObject({ ok: true, availableEngines: [], availableEngineCount: 1, problems: [] });+ const human = await sharedServer(2)(["doctor"]);+ expect(human.code).toBe(0);+ expect(human.out.join("\n")).toContain("Engines available: 2 (which ones needs a session)");+ expect(human.out.join("\n")).toContain("as a local service, not the owner");+ });++ it("is not ready when none can, and says so", async () => {+ const { code, out } = await sharedServer(0)(["doctor", "--json"]);+ expect(code).not.toBe(0);+ expect(JSON.parse(out.at(-1)!)).toMatchObject({ ok: false, availableEngineCount: 0, problems: [expect.stringContaining("no engine is available")] });+ });++ it("keeps the server's refusal when the server is too old to count", async () => {+ const { code } = await sharedServer("old server")(["doctor", "--json"]);+ expect(code).not.toBe(0);+ });+});diff --git a/server/mcp-server.test.ts b/server/mcp-server.test.tsindex 2cfbb0be89..40b6b40505 100644--- a/server/mcp-server.test.ts+++ b/server/mcp-server.test.ts@@ -744,6 +744,16 @@ describe("connection security and discovery", () => {}, "http://127.0.0.1:8799")).rejects.toThrow("paired session token");});+ it("says a shared server refused, not a desktop app, when the server says so", async () => {+ globalThis.fetch = vi.fn(async () => jsonResponse(+ { error: "forbidden: on this shared server a local request without a session may only use the service routes; sign in to change settings, people or access" },+ { ok: false, status: 403, statusText: "Forbidden" },+ )) as any;+ const refused = request("/api/instances", {}, "http://127.0.0.1:8799");+ await expect(refused).rejects.toThrow("This is a shared server, so a program on it without a paired session token may only check its health");+ await expect(refused).rejects.not.toThrow("desktop app");+ });+it("requires an explicit destination before sending a bearer token", async () => {process.env.OPENMAUSBOT_TOKEN = "proxy-token";await expect(resolveBaseUrl()).rejects.toThrow("OPENMAUSBOT_URL or OMB_PORT");diff --git a/server/request-auth.test.ts b/server/request-auth.test.tsindex 1305c96e69..e0df5603b1 100644--- a/server/request-auth.test.ts+++ b/server/request-auth.test.ts@@ -719,6 +719,12 @@ describe("loopback trust: owner on one person's machine, service on a shared wor}});+ it("lets a local check count the engines that can start a bot, as update.sh does, but no caller through a proxy", () => {+ expect(check("GET", "/api/health/engines", { trust: "service" }).auth).toEqual({ kind: "loopback", scopes: ["client"], trust: "service" });+ expect(check("POST", "/api/health/engines", { trust: "service" }).auth).toBeNull();+ expect(check("GET", "/api/health/engines", { trust: "service", headers: { "x-forwarded-for": "203.0.113.9" } }).auth).toBeNull();+ });+it("still admits a real session with its own scopes on a service-trust server", () => {const admin = sessions.issue({ label: "Laptop", scopes: ["admin", "client"] });const member = sessions.issue({ label: "Phone", scopes: ["client"] });diff --git a/server/request-auth.ts b/server/request-auth.tsindex 2046dfc5b3..a20a119199 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -39,6 +39,7 @@ const SERVICE_SCOPES: readonly Scope[] = ["client"];* the Slack worker holds, so these routes stop answering session-less loopback. */export const SERVICE_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: RegExp }> = [{ methods: ["GET"], path: /^\/api\/health$/ },+ { methods: ["GET"], path: /^\/api\/health\/engines$/ }, // a count: deploy/update.sh checks the server can still start a bot{ methods: ["GET"], path: /^\/api\/auth\/session$/ },{ methods: ["GET"], path: /^\/api\/edition$/ },{ methods: ["GET"], path: /^\/api\/brand$/ },diff --git a/server/routes/instances.test.ts b/server/routes/instances.test.tsindex 1b97ce1a5b..80a50e5dbd 100644--- a/server/routes/instances.test.ts+++ b/server/routes/instances.test.ts@@ -114,6 +114,22 @@ describe("the engine list", () => {});});+describe("whether the server can start a bot", () => {+ it("counts the engines that are available and names none of them", async () => {+ const { call } = await serve({+ describeInstances: async () => [+ { instanceId: "claude", snapshot: { state: "available" } },+ { instanceId: "codex", snapshot: { state: "needs-login" } },+ { instanceId: "custom-1", snapshot: { state: "available" } },+ { instanceId: "broken" },+ ],+ });+ expect(await call("GET", "/api/health/engines")).toEqual({ app: "openmausbot", engines: 2 });+ const none = await serve({ describeInstances: async () => [{ instanceId: "codex", snapshot: { state: "unavailable" } }] });+ expect(await none.call("GET", "/api/health/engines")).toEqual({ app: "openmausbot", engines: 0 });+ });+});+describe("an engine's check", () => {it("goes through the server's tested-AI record, so the welcome's test also settles the new-bot default", async () => {const asked: string[] = [];diff --git a/server/routes/instances.ts b/server/routes/instances.tsindex f9fca7514e..b9873f7262 100644--- a/server/routes/instances.ts+++ b/server/routes/instances.ts@@ -109,6 +109,13 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {if (url.searchParams.get("fresh") === "1") registry.forgetSnapshots();return json(res, 200, { instances: await describeInstances() });}+ // How many engines could start a bot now, never which: the check an update makes that the new version still can+ // (deploy/update.sh), which a shared server lets a local caller without a session make (SERVICE_ALLOW).+ if (method === "GET" && path === "/api/health/engines") {+ const described = await describeInstances();+ const available = Array.isArray(described) ? described.filter((instance) => Object(Object(instance).snapshot).state === "available").length : 0;+ return json(res, 200, { app: "openmausbot", engines: available });+ }const companyMutation = /^\/api\/instances\/(company\.[\w.-]+)(?:\/|$)/.exec(path);if (hostedModels && path.startsWith("/api/instances/") && method !== "GET") return json(res, 403, { error: HOSTED_PROVIDER_SETTINGS_ERROR });if (companyMutation && method !== "GET") return json(res, 403, { error: "Company accounts are read-only here. Manage this connection in desktop Settings." });