Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
OpenCode: one thread per folder in a shared process (fixes mid-turn "capability has expired") (#4699)
Milind Soni469583b47b13
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex dc3d43e480..9f4b8b6801 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -623,14 +623,14 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>? { jsonrpc: "2.0", id: msg.id, result: question.cancelled }: { jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: "method not found" } });};- const sharedHost = (hostKey: string | null): AcpHost | null => {+ const sharedHost = (hostKey: string | null, threadId: string, cwd: string): AcpHost | null => {if (hostKey === null) return null;- for (const host of hosts) if (host.key === hostKey && host.accepts(SHARED_SESSIONS_MAX, SHARED_SESSIONS_LIFETIME)) return host;+ for (const host of hosts) if (host.key === hostKey && host.accepts(SHARED_SESSIONS_MAX, SHARED_SESSIONS_LIFETIME, threadId, cwd)) return host;return null;};- const hostFor = (launch: { command: string }, argv: string[], env: Record<string, string | undefined>, cwd: string,+ const hostFor = (threadId: string, launch: { command: string }, argv: string[], env: Record<string, string | undefined>, cwd: string,hostKey: string | null): AcpHost => {- const running = sharedHost(hostKey);+ const running = sharedHost(hostKey, threadId, cwd);if (running) return running;const child = spawnCli(launch.command, argv, { cwd, env, stdio: ["pipe", "pipe", "pipe"], box: { allowEnv: instanceEnvNames(input.environment, env) } }, "bot");const host = new AcpHost(child, hostKey, { source: SOURCE, logMessage: nativeLogMessage, unrouted: refuse });@@ -650,8 +650,8 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>hostKey: string | null,): AcpSession => {const commandCwd = permissionLaunchCwd(cwd);- const host = hostFor(launch, argv, env, cwd, hostKey);- const acp = host.link(threadId);+ const host = hostFor(threadId, launch, argv, env, cwd, hostKey);+ const acp = host.link(threadId, cwd);const send = (obj: unknown) => acp.send(obj);const resolveClientPath = async (requestPath: unknown): Promise<string> => {@@ -1119,7 +1119,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>if (pooled.dead) sessions.delete(threadId);else closeSession(threadId, "contract");}- const joining = sharedHost(hostKey);+ const joining = sharedHost(hostKey, threadId, cwd);await turn.engineAdmission?.(joining ? "session" : "process", joining?.child.pid);requireRunning();if (active.has(threadId)) throw new Error("a turn is already running on this thread");diff --git a/server/drivers/acp/host.test.ts b/server/drivers/acp/host.test.tsindex 3c9d0c175e..6a8bc48062 100644--- a/server/drivers/acp/host.test.ts+++ b/server/drivers/acp/host.test.ts@@ -21,7 +21,7 @@ function hostWith(key: string | null) {const host = new AcpHost(child, key, { source: "test.acp", logMessage: (msg) => msg, unrouted: (msg) => refused.push(msg) });const heard = new Map<string, any[]>();const link = (threadId: string, sessionId: string | null) => {- const linked = host.link(threadId);+ const linked = host.link(threadId, `/work/${threadId}`);linked.sessionId = sessionId;const inbox: any[] = [];heard.set(threadId, inbox);@@ -36,7 +36,7 @@ describe("an ACP process's exit", () => {const { child } = fakeChild();const host = new AcpHost(child, null, { source: "test.acp", logMessage: (msg) => msg, unrouted: () => {} });const exits: Array<[number | null, NodeJS.Signals | null, string]> = [];- const linked = host.link("a");+ const linked = host.link("a", "/work/a");linked.inbound = { request: () => {}, notification: () => {}, error: () => {}, busy: () => false, exit: (code, signal) => exits.push([code, signal, host.stderrTail.text]) };const stderr = child.stderr as unknown as PassThrough;stderr.write("starting\nOpen https://accounts.google.com/o/oauth2/v2/auth?state=private-state\n");diff --git a/server/drivers/acp/host.ts b/server/drivers/acp/host.tsindex 818148e5c7..d468573e63 100644--- a/server/drivers/acp/host.ts+++ b/server/drivers/acp/host.ts@@ -119,6 +119,10 @@ export class AcpHost {opened = 0;retired = 0;recycle: ReturnType<typeof setTimeout> | null = null;+ /** Security: the thread each folder belongs to, for the process's life. An agent may keep MCP servers per folder and+ * name, not per session (OpenCode 1.18.27: session/new and session/load call mcp.add({ directory, name })), so a+ * second thread in a folder would call through the first one's servers and act on that thread's turn capability. */+ readonly #folders = new Map<string, string>();#nextId = 1;readonly #pending = new Map<number, Pending>();readonly #privateResponses = new Set<number>();@@ -164,12 +168,16 @@ export class AcpHost {});}- /** Room for one more thread: alive, not draining, under `limit` sessions open and `lifetime` ever opened. */- accepts(limit: number, lifetime: number): boolean {- return !this.dead && !this.draining && this.child.exitCode === null && this.links.size < limit && this.opened < lifetime;+ /** Room for `threadId` in `folder`: alive, not draining, under `limit` sessions open and `lifetime` ever opened, and+ * no other thread has had a session in that folder here. */+ accepts(limit: number, lifetime: number, threadId: string, folder: string): boolean {+ const owner = this.#folders.get(folder);+ return !this.dead && !this.draining && this.child.exitCode === null && this.links.size < limit && this.opened < lifetime &&+ (owner === undefined || owner === threadId);}- link(threadId: string): AcpLink {+ link(threadId: string, folder: string): AcpLink {+ this.#folders.set(folder, threadId);const link = new AcpLink(this, threadId);this.links.add(link);this.opened += 1;diff --git a/server/drivers/acp/opencode-go.test.ts b/server/drivers/acp/opencode-go.test.tsindex d5fbe34c71..2ef3ca5991 100644--- a/server/drivers/acp/opencode-go.test.ts+++ b/server/drivers/acp/opencode-go.test.ts@@ -1202,7 +1202,9 @@ describe("OpenCode session variants", () => {const f = await fixture({ [model]: variantConfig(["low", "high"]) });expect((await f.run({ variant: "high" })).done).toMatchObject({ ok: true });const before = f.calls().length;- const { done, events } = await f.run({ threadId: "resumed-thread", resumeCursor: "native-resumed", variant: "high" });+ const folder = join(dirname(f.dump), "resumed-thread");+ mkdirSync(folder);+ const { done, events } = await f.run({ threadId: "resumed-thread", cwd: folder, resumeCursor: "native-resumed", variant: "high" });expect(done).toMatchObject({ ok: true, threadId: "resumed-thread" });expect(f.calls().slice(before).map((entry) => entry.params)).toEqual([{ sessionId: "native-resumed", configId: "effort", value: "high" }]);expect(events.filter((event) => event.type === "session.model-variants").every((event) => event.threadId === "resumed-thread")).toBe(true);diff --git a/server/drivers/acp/shared-process.test.ts b/server/drivers/acp/shared-process.test.tsindex dbdaa53aeb..3929ece837 100644--- a/server/drivers/acp/shared-process.test.ts+++ b/server/drivers/acp/shared-process.test.ts@@ -115,6 +115,19 @@ describe("ACP threads sharing one agent process", () => {expect(g.spawned).toHaveLength(2);});+ it("gives each folder in a process to one thread for the process's life, since the agent keeps MCP servers per folder", async () => {+ const f = await fixture();+ const shared = join(f.scratch, "project");+ mkdirSync(shared, { recursive: true });+ await Promise.all([f.run("thread-a", { cwd: shared }), f.run("thread-b", { cwd: shared })]);+ expect(f.spawned).toHaveLength(2);+ await f.run("thread-c", { cwd: shared });+ expect(f.spawned).toHaveLength(3);+ await f.run("thread-a", { cwd: shared });+ await f.run("thread-d");+ expect(f.spawned).toHaveLength(3);+ });+it("on a Team Cloud never shares a process between two audiences, whose engines have homes of their own", async () => {const f = await fixture();const dataDir = mkdtempSync(join(tmpdir(), "omb-acp-homes-"));diff --git a/server/index.test.ts b/server/index.test.tsindex 69bd23a4a4..945d7129ca 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -2729,7 +2729,7 @@ describe("harness HTTP API", () => {await mintTestCapability(BASE, chief.id, chief.threadId);const expired = await held.finish();expect(expired.status).toBe(401);- expect(expired.body.error).toMatch(/expired/);+ expect(expired.body.error).toMatch(/turn has already ended/);held.close();held = undefined;token = await mintTestCapability(BASE, chief.id, chief.threadId, { kind: "connectors" });@@ -2780,7 +2780,7 @@ describe("harness HTTP API", () => {const rejected = await held.finish();expect(rejected.status).toBe(401);- expect(rejected.body.error).toMatch(/expired/i);+ expect(rejected.body.error).toMatch(/turn has already ended/i);const state = (await api("GET", "/api/bots?messages=0")).body;expect(state.bots.some((bot: { name: string }) => bot.name === lateName)).toBe(false);} finally {@@ -10070,7 +10070,7 @@ describe("harness HTTP API", () => {{ mode: "size", sizes: [25 * 1024 * 1024 + 1], message: "Uploads are limited to 25 MiB per file.", status: 200 },{ mode: "batch", sizes: Array(5).fill(21 * 1024 * 1024) as number[], message: "Uploads are limited to 100 MiB per batch.", status: 200 },{ mode: "changed", sizes: [1024], message: expect.stringContaining("changed while staging"), status: 200 },- { mode: "stop", sizes: [1024], message: "the internal turn capability has expired", status: 401 },+ { mode: "stop", sizes: [1024], message: expect.stringContaining("turn has already ended"), status: 401 },{ mode: "disk", sizes: [1024], message: expect.stringMatching(/ENOTDIR|EEXIST/), status: 500 },])("returns the correct browser upload result for $mode", async ({ mode, sizes, message, status }) => {const bot = (await api("POST", "/api/bots")).body.bot;diff --git a/server/index.ts b/server/index.tsindex bbc7a8700f..6da39a8590 100644--- a/server/index.ts+++ b/server/index.ts@@ -521,7 +521,7 @@ import {ProviderTurnGenerationRegistry,RetiredTurnRegistry,guardTurnDispatch,- isTurnEventQuarantined,+ isTurnEventQuarantined, TURN_ENDED_REFUSAL,} from "./turn-dispatch-guard.ts";import { createGracefulShutdown } from "./graceful-shutdown.ts";import { acquireDataDirLeaseForProcess } from "./data-dir-lease.ts";@@ -13002,7 +13002,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const body = await readBody(req);// Authorization at header time is not a lease: if the owning turn settled meanwhile, die before any side effect.if (!internalCapabilityIsActive(internalCapability)) {- throw Object.assign(new Error("the internal turn capability has expired"), { status: 401 });+ throw Object.assign(new Error(TURN_ENDED_REFUSAL), { status: 401 });}if (body && typeof body === "object" && !Array.isArray(body)) {for (const key of ["fromBotId", "botId"] as const) {@@ -13020,7 +13020,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {};const requireActiveInternalCapability = () => {if (!internalCapabilityIsActive(internalCapability)) {- throw Object.assign(new Error("the internal turn capability has expired"), { status: 401 });+ throw Object.assign(new Error(TURN_ENDED_REFUSAL), { status: 401 });}};const botFolders = async () => ({ roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), vmWorkspace: (await attachmentVmForTurn(internalCapability))?.workspaceDir ?? null }); if (await lentMcp.route({ method, path, req, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS || await internalToolRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, folders: botFolders }) !== PASS || await waitRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, ...waitTurnChecks(internalCapability, internalSender) }) !== PASS || await teamMessages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await devsReports.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || (computerAsks && await computerAsks.internal({ method, path, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS) || await imageTools.internal({ method, path, res, json, readBody: readInternalBody, threadId: internalCapability.threadId, requireActive: requireActiveInternalCapability, personTurn: turnOrigin(internalCapability).kind === "user" || (Boolean(roomRun(internalCapability.generation)?.requestMessageId) && guestDrivenTurns.get(internalCapability.threadId) !== internalCapability.generation) }) !== PASS) return; const pagesCall = new AbortController(); res.once("close", () => { if (!res.writableEnded) pagesCall.abort(); }); if (await publishedPages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, requireActive: requireActiveInternalCapability, signal: pagesCall.signal, folders: botFolders, post: (text, publishedPage, bundle) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return !source ? null : (bundle && publishedPages.show({ threadId: internalCapability.threadId, card: publishedPage, bundle, bot: internalSender })) || store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, publishedPage, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id; } }) !== PASS) return;diff --git a/server/turn-dispatch-guard.ts b/server/turn-dispatch-guard.tsindex 966b2c6a3b..7499fac51a 100644--- a/server/turn-dispatch-guard.ts+++ b/server/turn-dispatch-guard.ts@@ -1,3 +1,6 @@+export const TURN_ENDED_REFUSAL = "This bot turn has already ended (it finished or was stopped), so this call was refused. " ++ "Anything the call started before the turn ended may still have run.";+/** Admission failures that can resume once a slot frees; never matched on error wording. */export function isTurnAdmissionBlocked(error: unknown): boolean {return typeof error === "object" && error !== null && "code" in error &&