Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(opencode): OpenCode 2.3.2, ending its background work at Stop and on woken turns (#6512)
Milind Sonic29e9bf51122
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex 6af466b039..5e35ad53b7 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -20,7 +20,7 @@ import { AcpBrowserAuth, acpBrowserAuthInstanceSurface, type AcpBrowserSignInSpeimport { deletePromptSplitReceipt, promptHalves, readPromptSplitReceipt, splitSessionPrompt, writePromptSplitReceipt } from "../prompt-split.ts";import type { PromptSplitReceipt } from "../prompt-split.ts";import { boxAudienceKey, describeSpawnFailure, execCli, killCliTree, sharedBoxScope, spawnCli } from "../../procs.ts"; import { stopEngineTree, stopEngineTrees } from "../../engine-stop.ts";-import { runAcpOneShot } from "./background-text.ts";+import { runAcpOneShot } from "./background-text.ts"; import type { OpenCodeBackgroundWork } from "./opencode-background.ts";import { acpCapabilities } from "./capabilities.ts";import { acpNativeLogMessage } from "./tool-log.ts";import { stripLeakedSystemHarnessMessages } from "../../../shared/system-message-guard.ts";@@ -156,7 +156,7 @@ export interface AcpSupport extends AcpDriverHooks {* confirms it; an approval change never respawns the process. */sessionScopedApproval?: boolean;/** False when this engine cannot run memory upkeep's one-shot text call cleanly; oneShotFolder holds a one-shot's folder. */- backgroundText?: false; oneShotFolder?(): Promise<string>;+ backgroundText?: false; oneShotFolder?(): Promise<string>; /** Work the agent goes on with after its turn: ended at Stop and when it wakes a turn between ours. */ backgroundWork?: OpenCodeBackgroundWork;/** Mutate the child env in place. `instanceEnvironment` tells a key put there on purpose from one* riding along in the server's own env. */transformEnv?(@@ -406,6 +406,8 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>};const sessionIdle = sessionIdlePolicy("ACP");+ const backgroundEnds = new Map<string, Promise<void>>(), endBackground = (threadId: string, session: AcpSession) => support.backgroundWork && !backgroundEnds.has(threadId) && session.child.exitCode === null+ && backgroundEnds.set(threadId, support.backgroundWork.end(session, (m, p, t) => session.host.request(null, m, p, t)).finally(() => backgroundEnds.delete(threadId)));const closeSession = (threadId: string, why: string) => {const session = sessions.get(threadId);if (!session || session.closing) return;@@ -573,7 +575,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>session.acp.failAll(new Error("turn settled"));// Detach before the final events: a listener may start the next turn synchronously.session.current = null;- active.delete(threadId);+ active.delete(threadId); if (current.state.stopped) endBackground(threadId, session);const end = endTurn(current, ok, stopReason, support.displayName);if (end.error) emit({ ...base(threadId, current.turnId), type: "runtime.error", ...end.error });emit({ ...base(threadId, current.turnId), type: "turn.completed", ok: end.ok, stopReason: end.stopReason, cost: null });@@ -814,7 +816,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>if (current && ["agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update", "plan"].includes(p.update?.sessionUpdate)) {current.state.startupActivity = true; if (current.state.promptSent) current.acknowledge();}- if (!current || !current.state.promptSent) return;+ if (!current || !current.state.promptSent) return void (!current && support.backgroundWork?.wakes(p.update) && endBackground(threadId, session));const u = filterUpdate ? filterUpdate(p.update ?? {}) : p.update ?? {};if (!u || (u.sessionUpdate === "agent_message_chunk" && typeof u.content?.text === "string" && current.steering?.swallow(u.content.text))) return;const finished = u.status === "completed" || u.status === "failed";@@ -956,7 +958,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>const sendTurn = async (turn: SendTurnInput, retryOf?: string) => {requireRunning();if (startupModelRefresh) await startupModelRefresh;- requireRunning();+ await backgroundEnds.get(turn.threadId); requireRunning();const parsedScope = parseToolScope(turn.toolScope);if (!parsedScope.ok) throw new Error(parsedScope.error);turn = { ...turn, toolScope: parsedScope.scope };@@ -1212,7 +1214,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>let runtimeAcceptsImages = await handshake();let init = session.initResult;- const cursor = !turn.sessionReset && typeof turn.resumeCursor === "string" ? turn.resumeCursor : null;+ await backgroundEnds.get(threadId); const cursor = turn.sessionReset ? null : support.backgroundWork ? support.backgroundWork.resumeCursor(turn.resumeCursor, session.sessionId) : typeof turn.resumeCursor === "string" ? turn.resumeCursor : null;let promptTurn = turn;let rebuiltFromReplay = false;for (;;) {diff --git a/server/drivers/acp/opencode-background.test.ts b/server/drivers/acp/opencode-background.test.tsnew file mode 100644index 0000000000..5fa2462cf0--- /dev/null+++ b/server/drivers/acp/opencode-background.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from "vitest";+import { openCodeBackgroundWork } from "./opencode-background.ts";++const capable = { agentCapabilities: { sessionCapabilities: { close: {}, delete: {}, fork: {} } } };++describe("OpenCode background work", () => {+ it("counts only a turn's own updates as a woken turn, never a title, usage or command list", () => {+ const work = openCodeBackgroundWork();+ for (const kind of ["agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update", "plan"]) {+ expect(work.wakes({ sessionUpdate: kind })).toBe(true);+ }+ expect(work.wakes({ sessionUpdate: "session_info_update", _meta: { "opencode/retry": null } })).toBe(true);+ expect(work.wakes({ sessionUpdate: "session_info_update", title: "Build the app" })).toBe(false);+ expect(work.wakes({ sessionUpdate: "usage_update", used: 10, size: 100 })).toBe(false);+ expect(work.wakes({ sessionUpdate: "available_commands_update", availableCommands: [] })).toBe(false);+ expect(work.wakes({ sessionUpdate: "config_option_update" })).toBe(false);+ expect(work.wakes(undefined)).toBe(false);+ });++ it("forks, deletes the original and closes the fork; later turns resume the fork", async () => {+ const work = openCodeBackgroundWork();+ const calls: string[] = [];+ const request = async (method: string, params: any) => {+ calls.push(`${method} ${params.sessionId}`);+ return method === "session/fork" ? { sessionId: `${params.sessionId}-f` } : {};+ };+ await work.end({ sessionId: "s1", cwd: "/w", initResult: capable }, request);+ expect(calls).toEqual(["session/fork s1", "session/delete s1", "session/close s1-f"]);+ expect(work.resumeCursor("s1", null)).toBe("s1-f");+ expect(work.resumeCursor(undefined, "s1")).toBe("s1-f");+ expect(work.resumeCursor(undefined, "other")).toBeNull();+ expect(work.resumeCursor("other", "s1")).toBe("other");+ // An ended session is never forked again by a late update.+ await work.end({ sessionId: "s1", cwd: "/w", initResult: capable }, request);+ expect(calls).toHaveLength(3);+ await work.end({ sessionId: "s1-f", cwd: "/w", initResult: capable }, request);+ expect(work.resumeCursor("s1", null)).toBe("s1-f-f");+ });++ it("does nothing when the agent cannot fork and delete, and keeps the session when the delete fails", async () => {+ const work = openCodeBackgroundWork();+ const calls: string[] = [];+ await work.end({ sessionId: "s1", cwd: "/w", initResult: { agentCapabilities: { sessionCapabilities: { close: {} } } } },+ async (method: string, params: any) => { calls.push(`${method} ${params.sessionId}`); return {}; });+ expect(calls).toEqual([]);++ calls.length = 0;+ await work.end({ sessionId: "s2", cwd: "/w", initResult: capable }, async (method: string, params: any) => {+ calls.push(`${method} ${params.sessionId}`);+ if (method === "session/delete" && params.sessionId === "s2") throw new Error("busy");+ return method === "session/fork" ? { sessionId: "s2-f" } : {};+ });+ expect(calls).toEqual(["session/fork s2", "session/delete s2", "session/delete s2-f"]);+ expect(work.resumeCursor("s2", null)).toBe("s2");+ });+});diff --git a/server/drivers/acp/opencode-background.ts b/server/drivers/acp/opencode-background.tsnew file mode 100644index 0000000000..a6e3e6fa2e--- /dev/null+++ b/server/drivers/acp/opencode-background.ts@@ -0,0 +1,63 @@+// OpenCode 2.3+ keeps work going after its turn: a shell command still running at its timeout moves to the background+// (2.3.1), subagents always run in the background (2.3.0), and each one's finish wakes a turn no session/prompt asked+// for. session/cancel and session/close only interrupt the running step; OpenCode ends a session's background jobs only+// when the session is deleted (core Session.remove: interrupt, wait for idle, cancel its jobs). So when a person stops a+// turn, or a turn wakes between ours (it would run tools unseen, with Full access's grants), the session is forked to+// keep its history (core Session.fork copies its messages, not its jobs or queued notices), then the original is deleted.+// The thread's next turn loads the fork. An OpenCode without session/fork and session/delete is left as it is.++type Request = (method: string, params: unknown, timeoutMs?: number) => Promise<any>;++const WAIT_MS = 10_000;+/** A woken turn's retry notice and the step after it are session_info_updates with this key (packages/cli/src/acp);+ * compaction and titles use others. */+const STEP_META = "opencode/retry";+const TURN_UPDATES = new Set(["agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update", "plan"]);++export interface OpenCodeBackgroundWork {+ /** Whether a session/update that arrives while no turn of ours runs is OpenCode working on its own. */+ wakes(update: Record<string, any> | undefined): boolean;+ /** The session a turn resumes: its stored cursor, or with none the live session once it was forked, after any forks. */+ resumeCursor(cursor: unknown, live: string | null): string | null;+ /** Ends the session's background jobs and any turn they woke, keeping its history in a fork. Never throws. */+ end(session: { sessionId: string | null; cwd: string; initResult: any }, request: Request): Promise<void>;+}++export function openCodeBackgroundWork(): OpenCodeBackgroundWork {+ const forkedTo = new Map<string, string>();+ return {+ wakes: (update) => {+ const kind = update?.sessionUpdate;+ if (TURN_UPDATES.has(kind)) return true;+ const meta = update?._meta;+ return kind === "session_info_update" && meta !== null && typeof meta === "object" && STEP_META in meta;+ },+ resumeCursor: (cursor, live) => {+ let id = typeof cursor === "string" ? cursor : live !== null && forkedTo.has(live) ? live : null;+ if (id === null) return null;+ for (let hops = 0; forkedTo.has(id) && hops < 64; hops++) id = forkedTo.get(id)!;+ return id;+ },+ end: async (session, request) => {+ const sessionId = session.sessionId;+ if (!sessionId || forkedTo.has(sessionId)) return;+ const can = session.initResult?.agentCapabilities?.sessionCapabilities ?? {};+ if (!can.fork || !can.delete) return;+ const quietly = (method: string, params: unknown) => request(method, params, WAIT_MS).then(() => true, () => false);+ let fork: unknown;+ try {+ fork = (await request("session/fork", { sessionId, cwd: session.cwd, mcpServers: [] }, WAIT_MS))?.sessionId;+ } catch {+ return;+ }+ if (typeof fork !== "string" || !fork) return;+ if (!await quietly("session/delete", { sessionId })) {+ await quietly("session/delete", { sessionId: fork });+ return;+ }+ forkedTo.set(sessionId, fork);+ // The fork was opened without the bot's MCP servers: the next turn loads it with them.+ await quietly("session/close", { sessionId: fork });+ },+ };+}diff --git a/server/drivers/acp/opencode-go.test.ts b/server/drivers/acp/opencode-go.test.tsindex a946d5ba2c..76c8d258ab 100644--- a/server/drivers/acp/opencode-go.test.ts+++ b/server/drivers/acp/opencode-go.test.ts@@ -298,6 +298,130 @@ describe("OpenCode catalog", () => {}});+ describe("work OpenCode goes on with after its turn", () => {+ // OpenCode 2.3+ moves a shell command still running at its timeout to the background, and its finish wakes a turn+ // that no session/prompt asked for. Only deleting the session ends its background jobs.+ const scratches: string[] = [];+ afterEach(async () => { for (const dir of scratches.splice(0)) await removeTempDir(dir); });+ const start = async (id: string, extra: Record<string, string> = {}) => {+ const scratch = mkdtempSync(join(tmpdir(), "omb-opencode-background-"));+ scratches.push(scratch);+ mkdirSync(join(scratch, "opencode"), { recursive: true });+ writeFileSync(join(scratch, "opencode", "auth.json"), JSON.stringify({ opencode: { type: "api", key: "zen-secret" } }));+ const files = { woken: join(scratch, "woken"), rpc: join(scratch, "rpc.jsonl"), dump: join(scratch, "dump.json") };+ const instance = await createOpenCodeDriver(async () => catalog("opencode/big-pickle")).create({+ instanceId: id,+ displayName: "OpenCode",+ environment: { XDG_DATA_HOME: scratch, OPENCODE_API_KEY: "", FAKE_ACP_MODELS: "opencode/big-pickle", FAKE_ACP_MODE: "background-wake",+ FAKE_ACP_WOKEN_FILE: files.woken, FAKE_ACP_RPC_APPEND_FILE: files.rpc, FAKE_ACP_DUMP: files.dump, FAKE_ACP_STEP_MS: "100", ...extra },+ enabled: true,+ config: { cli: FAKE_CLI, fullAuto: true },+ });+ const calls = () => existsSync(files.rpc)+ ? readFileSync(files.rpc, "utf8").trim().split("\n").map((line) => JSON.parse(line) as { pid: number; method: string; sessionId?: string }) : [];+ const steps = () => existsSync(files.woken) ? readFileSync(files.woken, "utf8").trim().split("\n").length : 0;+ const ask = async (threadId: string, text: string) => {+ const { turnId } = await instance.adapter.sendTurn({ threadId, text, model: "opencode/big-pickle" });+ return recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);+ };+ const recorder = recordEvents(instance.adapter);+ return { instance, recorder, files, calls, steps, ask };+ };+ const until = async (check: () => boolean) => {+ for (let i = 0; i < 400 && !check(); i++) await new Promise((resolve) => setTimeout(resolve, 25));+ expect(check()).toBe(true);+ };+ const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));+ const promptedSession = (calls: () => Array<{ method: string; sessionId?: string }>) =>+ calls().filter((call) => call.method === "session/prompt").at(-1)?.sessionId;++ it("ends a turn its background command wakes between ours, keeps the history in a fork, and drops its output", async () => {+ const { instance, recorder, calls, steps, ask } = await start("opencode-background-wake");+ const threadId = "t-opencode-background-wake";+ try {+ expect(await ask(threadId, "build it")).toMatchObject({ ok: true });+ expect(JSON.stringify(recorder.events)).toContain("build started");+ const session = promptedSession(calls)!;+ await until(() => calls().some((call) => call.method === "session/close" && call.sessionId === `${session}-fork`));+ const methods = calls().map((call) => `${call.method} ${call.sessionId ?? ""}`.trim());+ expect(methods.slice(methods.indexOf(`session/fork ${session}`))).toEqual(expect.arrayContaining([+ `session/delete ${session}`, `session/close ${session}-fork`]));+ // The woken turn stops once its session is deleted, and nothing of it reached the chat.+ const woken = steps();+ expect(woken).toBeGreaterThan(0);+ await pause(400);+ expect(steps()).toBe(woken);+ expect(JSON.stringify(recorder.events)).not.toContain("WOKEN");+ expect(recorder.events.filter((event) => event.type === "turn.completed")).toHaveLength(1);++ const second = await ask(threadId, "and now?");+ expect(second).toMatchObject({ ok: true });+ expect(JSON.stringify(recorder.events.filter((event) => "turnId" in event && event.turnId === second.turnId))).toContain("second answer");+ // The thread goes on in the fork, loaded again with the bot's own MCP servers.+ expect(calls().filter((call) => call.method === "session/load").at(-1)?.sessionId).toBe(`${session}-fork`);+ expect(promptedSession(calls)).toBe(`${session}-fork`);+ expect(recorder.events).toEqual(expect.arrayContaining([expect.objectContaining({ type: "session.started", turnId: second.turnId, sessionId: `${session}-fork` })]));+ expect(JSON.stringify(recorder.events)).not.toContain("WOKEN");+ } finally {+ recorder.stop();+ await instance.dispose();+ }+ });++ it("ends the session's background work when the person stops the turn, before it can wake a turn", async () => {+ // The job wakes its turn 1.5 s after it starts, unless its session is deleted first.+ const { instance, recorder, calls, steps, ask } = await start("opencode-background-stop", { FAKE_ACP_WAKE_MS: "1500" });+ const threadId = "t-opencode-background-stop";+ try {+ const { turnId } = await instance.adapter.sendTurn({ threadId, text: "build it STOP_ME", model: "opencode/big-pickle" });+ await until(() => JSON.stringify(recorder.events).includes("build started"));+ const startedAt = Date.now();+ await instance.adapter.interruptTurn(threadId);+ expect(await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId)).toMatchObject({ stopReason: "cancelled" });+ const session = promptedSession(calls)!;+ await until(() => calls().some((call) => call.method === "session/delete" && call.sessionId === session));+ expect(calls().some((call) => call.method === "session/fork" && call.sessionId === session)).toBe(true);+ await pause(Math.max(0, 1_800 - (Date.now() - startedAt)));+ expect(steps()).toBe(0);+ // The next message goes on in the fork.+ expect(await ask(threadId, "go on")).toMatchObject({ ok: true });+ expect(promptedSession(calls)).toBe(`${session}-fork`);+ expect(JSON.stringify(recorder.events)).not.toContain("WOKEN");+ } finally {+ recorder.stop();+ await instance.dispose();+ }+ });++ it("leaves an OpenCode that cannot fork and delete sessions as it is", async () => {+ const { instance, recorder, calls, steps, ask } = await start("opencode-background-no-fork", { FAKE_ACP_NO_FORK: "1" });+ const threadId = "t-opencode-background-no-fork";+ try {+ expect(await ask(threadId, "build it")).toMatchObject({ ok: true });+ const session = promptedSession(calls)!;+ await until(() => steps() > 0);+ expect(await ask(threadId, "and now?")).toMatchObject({ ok: true });+ expect(promptedSession(calls)).toBe(session);+ expect(calls().filter((call) => ["session/fork", "session/delete", "session/close"].includes(call.method))).toEqual([]);+ } finally {+ recorder.stop();+ await instance.dispose();+ }+ });++ it("starts OpenCode without the person's own CLAUDE.md instructions", async () => {+ const { instance, recorder, files, ask } = await start("opencode-no-claude-md");+ try {+ expect(await ask("t-opencode-no-claude-md", "hello")).toMatchObject({ ok: true });+ const env = (JSON.parse(readFileSync(files.dump, "utf8")) as { env: Record<string, string> }).env;+ expect(env.OPENCODE_DISABLE_CLAUDE_CODE_PROMPT).toBe("1");+ } finally {+ recorder.stop();+ await instance.dispose();+ }+ });+ });+it("classifies ACP's standard authentication error", () => {expect(classifyOpenCodeError({ code: -32000 })).toBe("invalid_credentials");});diff --git a/server/drivers/acp/opencode-go.ts b/server/drivers/acp/opencode-go.tsindex 6c4a7f940d..d1bdd221b7 100644--- a/server/drivers/acp/opencode-go.ts+++ b/server/drivers/acp/opencode-go.ts@@ -10,6 +10,7 @@ import { hostedWorkspaceConfigured } from "../../enterprise.ts";import { decodeInjectId, hostApiKey, localHost, mergeLocalInject } from "../local-inject.ts";import { applyStandaloneSpawnEnv } from "../../engine-install.ts";import { OPENCODE_STANDALONE } from "./opencode-release.ts";+import { openCodeBackgroundWork } from "./opencode-background.ts";import { createAcpDriver, type AccountErrorCode, type AcpConfig, type AcpSupport } from "./core.ts";import { offeredModels } from "./config-options.ts";import type { AcpRequestSteer } from "./steer.ts";@@ -694,6 +695,7 @@ const support = (oneShotFolder: discoveryDirectory,shareProcess: true,steer: OPENCODE_STEER,+ backgroundWork: openCodeBackgroundWork(),credentialEnv: ["OPENCODE_API_KEY", ...OPENCODE_PROVIDER_ENV],selectModel: { configId: "model" },fallbackModel: (sessionConfig, catalogDefault) => {@@ -710,6 +712,10 @@ const support = (withholdProviderKeysWhenManaged(env, config, instanceId, instanceEnvironment);declareLiveOpenCodeModels(env, sources.liveLists);applyStandaloneSpawnEnv(OPENCODE_STANDALONE, env, config.cli);+ // OpenCode 2.3.1+ reads CLAUDE.md, and ~/.claude/CLAUDE.md, where no AGENTS.md is found: the person's own Claude+ // Code instructions are not a bot's. Only those: OPENCODE_DISABLE_CLAUDE_CODE would also drop the .claude/skills+ // folders the app places bots' skills in.+ env.OPENCODE_DISABLE_CLAUDE_CODE_PROMPT = "1";},spawnFingerprint: (env, config) => openCodeSpawnFingerprint(env, config.cli),applyTurnEnv: (env, { fullAuto, botId, cwd }) => {diff --git a/server/drivers/acp/opencode-release.ts b/server/drivers/acp/opencode-release.tsindex 473304a6dc..a222cf46f2 100644--- a/server/drivers/acp/opencode-release.ts+++ b/server/drivers/acp/opencode-release.ts@@ -1,16 +1,17 @@// OpenCode's own builds, for installing it without Node.js: the version `npm install -g @opencode/cli` gives (latest on-// npm, 2026-10-30), from https://github.com/anomalyco/opencode/releases/tag/v2.2.5.+// npm, 2026-11-18), from https://github.com/anomalyco/opencode/releases/tag/v2.3.2.// Anomaly publishes a SHA256SUMS file for this release; each archive SHA-256 below was taken from that file and-// re-measured on 2026-11-03 by downloading the asset and running `sha256sum` on it — both agree. Each size is the byte-// count the GitHub assets API and the finished download agree on. Each program SHA-256 is `sha256sum` of the executable-// unpacked from that same verified archive (`unzip -p` / `tar -xzO`); the app checks it after unpacking, before reusing-// an installed copy and at every start. The 1.x executables keep their place in `previousPrograms`, so copies installed-// by earlier pins stay usable until they update. x64 takes the "baseline" builds, which need no AVX2 (older Intel CPUs,-// Rosetta); a Linux without glibc takes the musl builds. The macOS arm64 executable is signed with Anomaly Innovations'-// Developer ID, Team 5NZ4Q7NXJ4 (checked with codesign on 2026-11-05).+// re-measured on 2026-11-18 by downloading the asset and running `shasum -a 256` on it, and equals the `digest` GitHub+// reports for that asset — all three agree. Each size is the byte count the GitHub assets API and the finished download+// agree on. Each program SHA-256 is `shasum -a 256` of the executable unpacked from that same verified archive (`unzip -p`+// / `tar -xzO`); the app checks it after unpacking, before reusing an installed copy and at every start. Every archive+// still holds a single file at its root, the executable. The 1.x and 2.2.5 executables keep their place in+// `previousPrograms`, so copies installed by earlier pins stay usable until they update. x64 takes the "baseline" builds,+// which need no AVX2 (older Intel CPUs, Rosetta); a Linux without glibc takes the musl builds. Both macOS executables are+// signed with Anomaly Innovations' Developer ID, Team 5NZ4Q7NXJ4 (checked with codesign on 2026-11-18).import type { StandaloneRelease } from "../../contracts.ts";-const VERSION = "2.2.5";+const VERSION = "2.3.2";const RELEASE = `https://github.com/anomalyco/opencode/releases/download/v${VERSION}`;export const OPENCODE_STANDALONE: StandaloneRelease = {@@ -23,25 +24,25 @@ export const OPENCODE_STANDALONE: StandaloneRelease = {// The app installs its own copy's updates; OpenCode's self-updater would replace that copy behind its back.runEnv: { OPENCODE_DISABLE_AUTOUPDATE: "1" },// Program hashes of earlier pins whose installed copies stay usable after this pin moves on: the 1.x line, whose npm- // name (`opencode-ai`) the previous install command used.+ // name (`opencode-ai`) an earlier install command used, then 2.2.5.previousPrograms: {- "darwin-arm64": ["417af53923f3d529759ab85ce3e8dd09116f742efcd332de591d2da6ebae696b"],- "darwin-x64": ["362c45dcd36a16215dce88c6b5232fe230f542c25960f01ba4e4a35588f42de9"],- "linux-x64": ["538fcb1b6408c8d4608822acee19f7ff5b3a3eb3383c0633c4f06170857312a7"],- "linux-arm64": ["eba0da50d9cc22f2dd062c32e0e7e58d7ece301aa50aabdad1e9dba4ffbf25b4"],- "linux-x64-musl": ["ad5ae0ab7b5f0c6fec273648eb91c798fd49ffe0e3f222dcec3ab2d680b132d8"],- "linux-arm64-musl": ["2a0cfa6fe7d96ebb89da8d880bd884598d5cdca10e6c3a5b2e63f92c569f1452"],- "win32-x64": ["eba9fc042ac622648a66ac5764c5ad41a73244eabcd7a00527d651b7c443efbd"],- "win32-arm64": ["92c6c5f6f656e60d6809c029a911ecb578204085945dd2f6e2639981ecab8749"],+ "darwin-arm64": ["417af53923f3d529759ab85ce3e8dd09116f742efcd332de591d2da6ebae696b", "abe4d88594bffb12b364375b8a6732d2d1f7a977195ed1a35c5c76f8e89c9e0e"],+ "darwin-x64": ["362c45dcd36a16215dce88c6b5232fe230f542c25960f01ba4e4a35588f42de9", "f2e7af7237a08e970821aec92c6af95caadeab2fe9f54bd4e76e075d8092d47f"],+ "linux-x64": ["538fcb1b6408c8d4608822acee19f7ff5b3a3eb3383c0633c4f06170857312a7", "8d060e1d2fbb9bb44cf09ae6ed1f3f6a7cff070b5227e2f90970132b23a92050"],+ "linux-arm64": ["eba0da50d9cc22f2dd062c32e0e7e58d7ece301aa50aabdad1e9dba4ffbf25b4", "dcc7e6f4ac1672e1884dcb8d26ab333e55ffc3f080e01a7a60177aa05f54935f"],+ "linux-x64-musl": ["ad5ae0ab7b5f0c6fec273648eb91c798fd49ffe0e3f222dcec3ab2d680b132d8", "8b071dcb704137eb9be83cd84ebd634e9409f9b9aaf9d8e562e1c69941743ce4"],+ "linux-arm64-musl": ["2a0cfa6fe7d96ebb89da8d880bd884598d5cdca10e6c3a5b2e63f92c569f1452", "2d719ef7b593a3e836dab611bc28da0e9ee71958d5e72ddb41e0f6abe2924e14"],+ "win32-x64": ["eba9fc042ac622648a66ac5764c5ad41a73244eabcd7a00527d651b7c443efbd", "17531635c255d2dd70057b8d50564b829349eae8c2946590ce355f003cb251e6"],+ "win32-arm64": ["92c6c5f6f656e60d6809c029a911ecb578204085945dd2f6e2639981ecab8749", "a614cd11e3c98fb57ce2d3a45988f163ec15689269ee4cea64ee7cf6b2d1b1ee"],},assets: {- "darwin-arm64": { url: `${RELEASE}/opencode-darwin-arm64.zip`, archive: "zip", executable: "opencode", approxBytes: 105_851_917, sha256: "25ba9908979fa7d764792c82589b4b5768ab1511154e0317d98aa77d216ce767", executableSha256: "abe4d88594bffb12b364375b8a6732d2d1f7a977195ed1a35c5c76f8e89c9e0e" },- "darwin-x64": { url: `${RELEASE}/opencode-darwin-x64-baseline.zip`, archive: "zip", executable: "opencode", approxBytes: 111_093_665, sha256: "b83ab73b3eb7b08f580f597eba8a7bcd886d2efa2ebf90405ad74ef54da02f71", executableSha256: "f2e7af7237a08e970821aec92c6af95caadeab2fe9f54bd4e76e075d8092d47f" },- "linux-x64": { url: `${RELEASE}/opencode-linux-x64-baseline.tar.gz`, archive: "tar.gz", executable: "opencode", approxBytes: 119_196_162, sha256: "09f44302c10fd036912f59c81fd1aef5df45dd06f649197f9dfc9bbe2a79614e", executableSha256: "8d060e1d2fbb9bb44cf09ae6ed1f3f6a7cff070b5227e2f90970132b23a92050" },- "linux-arm64": { url: `${RELEASE}/opencode-linux-arm64.tar.gz`, archive: "tar.gz", executable: "opencode", approxBytes: 117_861_733, sha256: "5a528f42caf576c6cdece6a191eb273d3db54effa5518e0402684d8f8026aeb6", executableSha256: "dcc7e6f4ac1672e1884dcb8d26ab333e55ffc3f080e01a7a60177aa05f54935f" },- "linux-x64-musl": { url: `${RELEASE}/opencode-linux-x64-baseline-musl.tar.gz`, archive: "tar.gz", executable: "opencode", approxBytes: 117_818_616, sha256: "889389e99ffa39fa41d512b2c9c15316522d97398fb912503ef667f80e22a827", executableSha256: "8b071dcb704137eb9be83cd84ebd634e9409f9b9aaf9d8e562e1c69941743ce4" },- "linux-arm64-musl": { url: `${RELEASE}/opencode-linux-arm64-musl.tar.gz`, archive: "tar.gz", executable: "opencode", approxBytes: 116_087_436, sha256: "bbf927e3f7a92040f25fd78436c251f41deb25cefac1c906e79c01aa572bf73b", executableSha256: "2d719ef7b593a3e836dab611bc28da0e9ee71958d5e72ddb41e0f6abe2924e14" },- "win32-x64": { url: `${RELEASE}/opencode-windows-x64-baseline.zip`, archive: "zip", executable: "opencode.exe", approxBytes: 121_962_395, sha256: "3acca208ad79add59aed13d07b7e08ddf24e0adbbb7f44a9131408d7b3ca67cd", executableSha256: "17531635c255d2dd70057b8d50564b829349eae8c2946590ce355f003cb251e6" },- "win32-arm64": { url: `${RELEASE}/opencode-windows-arm64.zip`, archive: "zip", executable: "opencode.exe", approxBytes: 115_405_131, sha256: "4e426a39d68516b036cd28b574c5ce5f3b50846ab460521f83f2458fe7f242d8", executableSha256: "a614cd11e3c98fb57ce2d3a45988f163ec15689269ee4cea64ee7cf6b2d1b1ee" },+ "darwin-arm64": { url: `${RELEASE}/opencode-darwin-arm64.zip`, archive: "zip", executable: "opencode", approxBytes: 109_126_744, sha256: "31ab5a06a29edc7e49b895f35c2b64ebfe7c7f0437b0f2581b006efcd79fee1a", executableSha256: "635c523002b6eaf897597facba703729794cb07bdb59044d5e173b07b77ff934" },+ "darwin-x64": { url: `${RELEASE}/opencode-darwin-x64-baseline.zip`, archive: "zip", executable: "opencode", approxBytes: 114_496_820, sha256: "6dc5deb4554df035d27dbb3a4663d96954969a33079aeb6b01dd9de2d9092545", executableSha256: "5d188d68f808570aa1f8826c9d6bd7d9ade18e9bac8961aa3c0079f41e2850e8" },+ "linux-x64": { url: `${RELEASE}/opencode-linux-x64-baseline.tar.gz`, archive: "tar.gz", executable: "opencode", approxBytes: 122_641_607, sha256: "563b5d663637226b6e3bb4bb6803281bc39b0d2cd88db06d674b6420aab009b0", executableSha256: "e6543f6e5c39c40971ba38afd1819ac852c29ac735b5a89065d3d148d47f27ad" },+ "linux-arm64": { url: `${RELEASE}/opencode-linux-arm64.tar.gz`, archive: "tar.gz", executable: "opencode", approxBytes: 121_172_970, sha256: "9d10185acdb72336e086e699ca363a6065f410fd3c1caed0dc8046e95ac06ccb", executableSha256: "fc1ad8f2dffed8494e31265837f78d1e6ce5200f5c1c50e953cd9b63e607efdb" },+ "linux-x64-musl": { url: `${RELEASE}/opencode-linux-x64-baseline-musl.tar.gz`, archive: "tar.gz", executable: "opencode", approxBytes: 122_453_192, sha256: "4e952a67874cfdb4f53eeae5840f9813acc9f109c10e61bc26020271f56d7d84", executableSha256: "338bad40b5b5f602af50ebb995036bb6965d25deffc9d88df3f69ddc04524a17" },+ "linux-arm64-musl": { url: `${RELEASE}/opencode-linux-arm64-musl.tar.gz`, archive: "tar.gz", executable: "opencode", approxBytes: 120_472_892, sha256: "2148ba748f5410177868ed67d59ef70626cb6bd4fb2abc5177c807adfdc24fc3", executableSha256: "0e214ccebc6f0dd8775be65104b8a9de0585427b8911ad838c9fd83d1c812e2d" },+ "win32-x64": { url: `${RELEASE}/opencode-windows-x64-baseline.zip`, archive: "zip", executable: "opencode.exe", approxBytes: 125_643_830, sha256: "8dcfe392a79412bf908de4c0cf5338c52589147eff54f1a46c25fb24a94708e7", executableSha256: "ba343b5c0fd8d7daabc0501bd1c1866c0fd91e8ff7b4404f5524fbc0cc233882" },+ "win32-arm64": { url: `${RELEASE}/opencode-windows-arm64.zip`, archive: "zip", executable: "opencode.exe", approxBytes: 118_889_090, sha256: "13dabbf6874c8abfc7ff44bee0e64c3758e918a0e27f56f74173c353d56a842d", executableSha256: "cde2ef5e052143ecca725af3ab330e00b7b7ab6bab1b971bb1a9467fc2c15063" },},};diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.tsindex 25a76422cd..b9975cd67e 100755--- a/server/testing/fake-acp-cli.ts+++ b/server/testing/fake-acp-cli.ts@@ -26,6 +26,11 @@// grok 1.0.25's initialize, or FAKE_ACP_MCP_HANDSHAKE; FAKE_ACP_MCP_SCHEMA_BYTES=1 adds each schema's length)// | lend-question (list_shared_computers around a question)// | list-peers (list_bots through the agents MCP; keeps the first agents server it is offered, like Hermes)+// | background-wake (OpenCode 2.3.1+: the first prompt's shell call moves to the background and the prompt ends, or with+// STOP_ME in it waits for session/cancel; FAKE_ACP_WAKE_MS (300) later that shell's finish wakes a turn no prompt+// asked for, one step every FAKE_ACP_STEP_MS (50), each appended to FAKE_ACP_WOKEN_FILE, until session/close or+// session/delete interrupts it; only session/delete ends the job. session/fork answers <id>-fork; a closed or+// deleted session refuses session/prompt until loaded. Advertises close, delete and, unless FAKE_ACP_NO_FORK=1, fork)// FAKE_ACP_GROK_NATIVE_MCP _x.ai/mcp/list reports these comma-separated native servers after the session's accepted ones// FAKE_ACP_MCP_TRANSPORTS remote MCP transports advertised in initialize, e.g. "http,sse"// FAKE_ACP_PERMISSION_OPTIONS JSON options override in permission mode@@ -293,6 +298,7 @@ const dumpEnv = Object.fromEntries("OPENCODE_API_KEY","OPENCODE_PERMISSION","OPENCODE_DISABLE_AUTOUPDATE",+ "OPENCODE_DISABLE_CLAUDE_CODE_PROMPT","OPENAI_API_KEY","OPENROUTER_API_KEY","ANTHROPIC_API_KEY",@@ -502,6 +508,14 @@ let onAskQuestionAnswered: (() => void) | null = null;let hangingPromptId: unknown = null;let streamingPromptId: unknown = null;+let backgroundWakePlayed = false;+const backgroundJobs = new Map<string, { job: ReturnType<typeof setTimeout> | null; step: ReturnType<typeof setInterval> | null }>();+const detachedSessions = new Set<string>();+const endWokenStep = (sessionId: unknown) => {+ const job = backgroundJobs.get(String(sessionId));+ if (job?.step) clearInterval(job.step);+ if (job) job.step = null;+};let hangKeepAlive: ReturnType<typeof setInterval> | null = null;type McpEntry = { command: string; args?: string[]; env?: Array<{ name: string; value: string }> };@@ -887,7 +901,7 @@ function handle(msg: any) {const acceptsImages = process.env.FAKE_ACP_IMAGE_CAPABILITY === "1";const mcpTransports = (process.env.FAKE_ACP_MCP_TRANSPORTS ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);const closesSessions = ["1", "error"].includes(process.env.FAKE_ACP_SESSION_CLOSE ?? "");- const deletesSessions = process.env.FAKE_ACP_SESSION_DELETE === "1";+ const deletesSessions = process.env.FAKE_ACP_SESSION_DELETE === "1" || mode === "background-wake";if (["1", "stuck"].includes(process.env.FAKE_ACP_CURSOR_FAST ?? "") && msg.params?.clientCapabilities?._meta?.parameterizedModelPicker === true) {currentFast = "true";}@@ -902,7 +916,8 @@ function handle(msg: any) {...(mode === "devin-steer" && process.env.FAKE_ACP_STEERING !== "off" ? { _meta: { "cognition.ai/midTurnPrompts": true } } : {}),...(agentName ? { loadSession: true, sessionCapabilities: { resume: true }, auth: { logout: true } } : {}),...(closesSessions || deletesSessions- ? { sessionCapabilities: { ...(closesSessions ? { close: {} } : {}), ...(deletesSessions ? { delete: {} } : {}) } }+ ? { sessionCapabilities: { ...(closesSessions ? { close: {} } : {}), ...(deletesSessions ? { delete: {} } : {}),+ ...(mode === "background-wake" ? { close: {}, ...(process.env.FAKE_ACP_NO_FORK === "1" ? {} : { fork: {} }) } : {}) } }: {}),...(acceptsImages ? { promptCapabilities: { image: true } } : {}),...(mcpTransports.length ? { mcpCapabilities: { http: mcpTransports.includes("http"), sse: mcpTransports.includes("sse") } } : {}),@@ -964,13 +979,24 @@ function handle(msg: any) {break;}case "session/close":+ endWokenStep(msg.params?.sessionId);+ if (mode === "background-wake") detachedSessions.add(String(msg.params?.sessionId));if (process.env.FAKE_ACP_SESSION_CLOSE === "error") out({ jsonrpc: "2.0", id: msg.id, error: { code: -32603, message: "close failed" } });else if (process.env.FAKE_ACP_SESSION_CLOSE_MS) setTimeout(() => result(msg.id, {}), Number(process.env.FAKE_ACP_SESSION_CLOSE_MS));else result(msg.id, {});break;- case "session/delete":+ case "session/delete": {+ endWokenStep(msg.params?.sessionId);+ const job = backgroundJobs.get(String(msg.params?.sessionId))?.job;+ if (job) clearTimeout(job);+ backgroundJobs.delete(String(msg.params?.sessionId));+ if (mode === "background-wake") detachedSessions.add(String(msg.params?.sessionId));result(msg.id, {});break;+ }+ case "session/fork":+ result(msg.id, { sessionId: `${msg.params?.sessionId}-fork` });+ break;case "session/load": {if (process.env.FAKE_ACP_LOAD_ERROR) {out({ jsonrpc: "2.0", id: msg.id, error: JSON.parse(process.env.FAKE_ACP_LOAD_ERROR) });@@ -1002,6 +1028,7 @@ function handle(msg: any) {const opts = configOptions();const mdls = sessionModels();liveSession = typeof msg.params?.sessionId === "string" ? msg.params.sessionId : liveSession;+ detachedSessions.delete(String(msg.params?.sessionId));resultAndConfigUpdates(msg.id, { ...(opts ? { configOptions: opts } : {}), ...(mdls ? { models: mdls } : {}) }, "session/load", msg.params.sessionId);if (mode === "hermes-steer") advertiseHermesCommands(msg.params.sessionId);break;@@ -1294,6 +1321,44 @@ function handle(msg: any) {complete();return;}+ if (mode === "background-wake") {+ // OpenCode 2.3.1+: a shell command still running at its timeout moves to the background, the prompt ends, and the+ // command's finish later wakes a turn OpenCode streams as session/updates no session/prompt asked for.+ const sessionId = String(msg.params?.sessionId);+ if (detachedSessions.has(sessionId)) {+ out({ jsonrpc: "2.0", id: msg.id, error: { code: -32602, message: "Invalid params", data: { sessionId } } });+ return;+ }+ const update = (u: Record<string, unknown>) => out({ jsonrpc: "2.0", method: "session/update", params: { sessionId, update: u } });+ if (backgroundWakePlayed) {+ update({ sessionUpdate: "agent_message_chunk", content: { text: "second answer" } });+ complete();+ return;+ }+ backgroundWakePlayed = true;+ update({ sessionUpdate: "tool_call", toolCallId: "tc-build", status: "in_progress", kind: "execute", title: "make", rawInput: { command: "make" } });+ update({ sessionUpdate: "tool_call_update", toolCallId: "tc-build", status: "completed", rawOutput: { output: "Command moved to the background (shell ID: sh_1)." } });+ update({ sessionUpdate: "agent_message_chunk", content: { text: "build started" } });+ const entry: { job: ReturnType<typeof setTimeout> | null; step: ReturnType<typeof setInterval> | null } = { job: null, step: null };+ backgroundJobs.set(sessionId, entry);+ entry.job = setTimeout(() => {+ entry.job = null;+ let step = 0;+ entry.step = setInterval(() => {+ step += 1;+ update({ sessionUpdate: "session_info_update", _meta: { "opencode/retry": null } });+ update({ sessionUpdate: "agent_message_chunk", content: { text: `WOKEN step ${step}` } });+ update({ sessionUpdate: "tool_call", toolCallId: `tc-woken-${step}`, status: "completed", kind: "execute", title: "make test", rawOutput: { output: "WOKEN ok" } });+ if (process.env.FAKE_ACP_WOKEN_FILE) appendFileSync(process.env.FAKE_ACP_WOKEN_FILE, `${sessionId} ${step}\n`);+ }, Number(process.env.FAKE_ACP_STEP_MS ?? 50));+ }, Number(process.env.FAKE_ACP_WAKE_MS ?? 300));+ if (JSON.stringify(msg.params?.prompt ?? []).includes("STOP_ME")) {+ hangingPromptId = msg.id;+ return;+ }+ complete();+ return;+ }if (mode === "finished-tools") {const update = (u: Record<string, unknown>) => out({ jsonrpc: "2.0", method: "session/update", params: { update: u } });// An unkeyed call left running, so an unkeyed finished one must not take its place in the queue.