Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(grok): steer a running turn, and end background work that wakes a turn
Krishna Dobhal3ae034e0a915
diff --git a/apps/docs/content/docs/providers/index.mdx b/apps/docs/content/docs/providers/index.mdxindex 10b4490d08..016c6c6d53 100644--- a/apps/docs/content/docs/providers/index.mdx+++ b/apps/docs/content/docs/providers/index.mdx@@ -14,7 +14,7 @@ MausBot does not proxy every message through its own model account. It starts su|---|---|---|| Claude | Claude CLI login | Strong support for tools, approvals, sessions, and local computer use || Codex | Codex CLI login | Model discovery, approvals, steering, and computer tools |-| Grok | Grok CLI login | ACP-based local model catalog and session support |+| Grok | Grok CLI login | ACP-based local model catalog and session support; steering a running turn, turned on in Grok's own config the first time you chat || Cursor | Cursor Agent CLI login or API key | ACP driver with live model discovery || GitHub Copilot | `copilot login`, or `COPILOT_GITHUB_TOKEN` | ACP driver with the plan's live models, each labelled with its premium request multiplier || Command Code | `cmd login`, or `COMMAND_CODE_API_KEY` | ACP driver with the account's live models and their effort levels |diff --git a/docs/verification/README.md b/docs/verification/README.mdindex 0effa0a5bf..669f60edd1 100644--- a/docs/verification/README.md+++ b/docs/verification/README.md@@ -86,6 +86,7 @@ Use only mapped, tested commands:- [Chief authority over additional departments](team-access.md)- [Engines and Doctor](engines.md)- [Cline engine and native loopback qualification](cline.md)+- [Grok steering a running turn](grok-steering.md)- [Claude coordination and turn-scoped tools](claude-tool-lifecycle.md)- [Codex bot instructions](codex-instructions.md)- [Codex browser routing and native search](codex-browser-routing.md)diff --git a/docs/verification/grok-steering.md b/docs/verification/grok-steering.mdnew file mode 100644index 0000000000..a5c9b8a785--- /dev/null+++ b/docs/verification/grok-steering.md@@ -0,0 +1,65 @@+# Grok steering a running turn++A message sent while a Grok turn runs is taken into that turn instead of+waiting for it to end, once Grok's own config has `follow_up_behavior = "steer"`.+OpenMausBot adds the line itself, for a signed-in Grok, when a turn starts. A+`follow_up_behavior` the person already set, `"queue"` included, is left alone.++## What Grok does (grok 1.0.89, 2026-11-19)++- With `"steer"`, a second `session/prompt` is injected at the next tool call or+ model step. Its own reply is `stopReason: "cancelled"` with+ `_meta.completionKind: "removedFromQueue"` and no tokens; the running prompt+ then ends normally. The driver does not count that reply as the turn's result.+- With `"queue"`, the second prompt waits for the turn to end.+- `initialize` does not report the setting, and `GROK_CONFIG` cannot set `ui`,+ so the driver reads `config.toml` in `$GROK_HOME`.+- `_x.ai/queue/interject` cancels the running turn and runs the queued prompt.+ It is send-now, not steering, and is not used.+- One long streamed answer has no step to land on: the message arrives after it.++## Fixture check++Use an isolated home with a copy of the sign-in, never `~/.grok`:++```sh+GROK_HOME=<temp dir holding a copy of auth.json> node --experimental-strip-types scripts/control-omb.ts launch+```++The launcher's fixture has only the fake engine, so for the real CLI start the+server by hand with an instance `{ driver: "grokAgent", config: { cli: <grok> },+environment: { GROK_HOME } }` in the fixture's `config.json`, and give Grok's+shell tool a working shell. File tools need none.++1. Ask the bot for 8 files, `step1.txt` to `step8.txt`, one write per file.+2. After a few exist, send "do not create any more files, reply MANGO".+3. The UI tags it "sent mid-turn", the reply is MANGO, and fewer than 8 files+ exist (6 on the recorded run). The files that were already in flight still land.++Automated: `server/drivers/acp/grok-steer.test.ts` against the scripted peer+(`FAKE_ACP_MODE=grok-steer`), including `ensureGrokSteer` on a config with no+`[ui]`, one with `[ui]`, none at all, a `"queue"` choice and a signed-out home.++## Background subagents and commands++Grok's `auto_wake` (on by default) wakes a turn nobody prompted when a background+subagent or shell command finishes after the turn. Without a fix the driver drops+that turn's output while it runs, and under Full access it can run tools unseen+(the same hole OpenCode 2.3 had, fixed in #6512).++On grok 1.0.89, `session/close` ends the session's background work at once, and+`session/load` of the same id brings the history back. The driver therefore closes+the session when the person stops a turn, or when a turn update arrives with none+of ours running, and the thread's next turn loads the same session id. There is no+fork and no new session id.++Costs: a background subagent's result is discarded, as with OpenCode; the next+turn pays a `session/load`.++Recorded on the real CLI (2026-11-19): a subagent launched in the background+finished after the turn and Grok then ran a turn that confirmed its file; with+`session/close` right after the turn the subagent was ended, no file was written+and no turn woke. A session closed and loaded again remembered an earlier word.+Automated: `server/drivers/acp/grok-background.test.ts` (a woken turn between+ours, and Stop) against the scripted peer with `FAKE_ACP_CLOSE_ENDS_JOBS=1`.+diff --git a/server/drivers/acp/background-work.test.ts b/server/drivers/acp/background-work.test.tsnew file mode 100644index 0000000000..7e669a718b--- /dev/null+++ b/server/drivers/acp/background-work.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from "vitest";+import { closeEndsBackgroundWork } from "./background-work.ts";++const capable = { agentCapabilities: { sessionCapabilities: { close: {} } } };++describe("close-ends background work", () => {+ it("counts only a turn's own updates as a woken turn", () => {+ const work = closeEndsBackgroundWork();+ for (const kind of ["agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update", "plan"]) {+ expect(work.wakes({ sessionUpdate: kind })).toBe(true);+ }+ for (const kind of ["session_info_update", "usage_update", "available_commands_update", "config_option_update"]) {+ expect(work.wakes({ sessionUpdate: kind })).toBe(false);+ }+ expect(work.wakes(undefined)).toBe(false);+ });++ it("closes the session, forgets its live id, and resumes the same id", async () => {+ const work = closeEndsBackgroundWork();+ const calls: string[] = [];+ const session = { sessionId: "s1" as string | null, cwd: "/w", initResult: capable };+ await work.end(session, async (method: string, params: any) => { calls.push(`${method} ${params.sessionId}`); return {}; });+ expect(calls).toEqual(["session/close s1"]);+ expect(session.sessionId).toBeNull();+ expect(work.resumeCursor(undefined, null, session)).toBe("s1");+ expect(work.resumeCursor("other", null, session)).toBe("other");+ expect(work.resumeCursor(undefined, "live", session)).toBeNull();+ expect(work.resumeCursor(undefined, null, {})).toBeNull();+ });++ it("does nothing when the agent cannot close sessions, and keeps the session when the close fails", async () => {+ const work = closeEndsBackgroundWork();+ const calls: string[] = [];+ const noClose = { sessionId: "s1" as string | null, cwd: "/w", initResult: { agentCapabilities: { sessionCapabilities: {} } } };+ await work.end(noClose, async (method: string) => { calls.push(method); return {}; });+ expect(calls).toEqual([]);+ expect(noClose.sessionId).toBe("s1");++ const failing = { sessionId: "s2" as string | null, cwd: "/w", initResult: capable };+ await work.end(failing, async () => { throw new Error("busy"); });+ expect(failing.sessionId).toBe("s2");+ expect(work.resumeCursor(undefined, null, failing)).toBeNull();+ });+});diff --git a/server/drivers/acp/background-work.ts b/server/drivers/acp/background-work.tsnew file mode 100644index 0000000000..db3544c6fe--- /dev/null+++ b/server/drivers/acp/background-work.ts@@ -0,0 +1,39 @@+type Request = (method: string, params: unknown, timeoutMs?: number) => Promise<any>;++/** Work an agent goes on with after its turn (a background subagent or shell command) and whose finish wakes a turn no+ * `session/prompt` asked for. The driver ends it when the person stops a turn, and when such a turn wakes between ours. */+export interface AcpBackgroundWork {+ /** Whether a session/update that arrives while no turn of ours runs is the agent working on its own. */+ wakes(update: Record<string, any> | undefined): boolean;+ /** The session a turn resumes: its stored cursor, or with none whatever ending the work left behind for this live session. */+ resumeCursor(cursor: unknown, live: string | null, session?: object): string | null;+ /** Ends the session's background work and any turn it woke, keeping its history. Never throws. */+ end(session: { sessionId: string | null; cwd: string; initResult: any }, request: Request): Promise<void>;+}++/** The session/update kinds a turn streams; titles, usage, compaction and command lists are not one. */+export const TURN_UPDATES: ReadonlySet<string> = new Set(["agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update", "plan"]);++const CLOSE_WAIT_MS = 10_000;++/** For an agent whose `session/close` ends the session's background work and whose `session/load` of the same id brings its+ * history back (grok 1.0.89): the session is closed and the thread's next turn loads it again, under the same id. */+export function closeEndsBackgroundWork(): AcpBackgroundWork {+ const closed = new WeakMap<object, string>();+ return {+ wakes: (update) => TURN_UPDATES.has(update?.sessionUpdate),+ resumeCursor: (cursor, live, session) =>+ typeof cursor === "string" ? cursor : live === null && session ? closed.get(session) ?? null : null,+ end: async (session, request) => {+ const sessionId = session.sessionId;+ if (!sessionId || !session.initResult?.agentCapabilities?.sessionCapabilities?.close) return;+ try {+ await request("session/close", { sessionId }, CLOSE_WAIT_MS);+ closed.set(session, sessionId);+ session.sessionId = null;+ } catch {+ // The session keeps its background work, as before.+ }+ },+ };+}diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex 5e35ad53b7..a2b874e679 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 type { OpenCodeBackgroundWork } from "./opencode-background.ts";+import { runAcpOneShot } from "./background-text.ts"; import type { AcpBackgroundWork } from "./background-work.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>; /** Work the agent goes on with after its turn: ended at Stop and when it wakes a turn between ours. */ backgroundWork?: OpenCodeBackgroundWork;+ 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?: AcpBackgroundWork;/** 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?(@@ -1131,6 +1131,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>open: () => state.promptSent && !state.settled && !state.stopped && !session.closing,commands: () => session.commands,initializeResult: () => session.initResult,+ env,prompt: (text) => request("session/prompt", { sessionId: session.sessionId, prompt: [{ type: "text", text }] }, undefined, undefined, promptIdleTimeoutMs()),extension: (method, text) => request(method, { sessionId: session.sessionId, prompt: [{ type: "text", text }] }, STEER_REQUEST_TIMEOUT_MS),}),@@ -1214,7 +1215,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>let runtimeAcceptsImages = await handshake();let init = session.initResult;- 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;+ await backgroundEnds.get(threadId); const cursor = turn.sessionReset ? null : support.backgroundWork ? support.backgroundWork.resumeCursor(turn.resumeCursor, session.sessionId, session) : typeof turn.resumeCursor === "string" ? turn.resumeCursor : null;let promptTurn = turn;let rebuiltFromReplay = false;for (;;) {@@ -1435,9 +1436,10 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>);}}- const answers = [result, ...(current.steering?.replies ?? [])];+ const folded = support.steer && "folded" in support.steer ? support.steer.folded : undefined;+ const answers = [result, ...(current.steering?.replies ?? []).filter((reply) => !folded?.(reply))];if (current.steering?.failure !== undefined && !state.stopped) throw current.steering.failure;- const runOf = (answer: unknown) => support.steer && "run" in support.steer ? support.steer.run(answer) : undefined;+ const runOf = (answer: unknown) => support.steer && "run" in support.steer ? support.steer.run?.(answer) : undefined;for (const [index, answer] of answers.entries()) {const run = runOf(answer);if (run !== undefined && answers.slice(index + 1).some((later) => runOf(later) === run)) continue;diff --git a/server/drivers/acp/grok-background.test.ts b/server/drivers/acp/grok-background.test.tsnew file mode 100644index 0000000000..40b7cd67fa--- /dev/null+++ b/server/drivers/acp/grok-background.test.ts@@ -0,0 +1,103 @@+// Ending a Grok session's background work: a finished subagent or shell command wakes a turn nobody prompted, against the+// scripted ACP peer where session/close ends the job.+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, describe, expect, it } from "vitest";++import { ensureDirs } from "../../config.ts";+import type { ProviderInstance } from "../../contracts.ts";+import { removeTempDir } from "../../testing/cleanup.ts";+import { recordEvents } from "../../testing/events.ts";+import { GrokAgentDriver } from "./grok.ts";++const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "../../testing/fake-acp-cli.ts");++const scratches: string[] = [];+afterEach(async () => { for (const dir of scratches.splice(0)) await removeTempDir(dir); });++const start = async (id: string, extra: Record<string, string> = {}) => {+ ensureDirs();+ const scratch = mkdtempSync(join(tmpdir(), "omb-grok-background-"));+ scratches.push(scratch);+ mkdirSync(join(scratch, "grok"), { recursive: true });+ writeFileSync(join(scratch, "grok", "auth.json"), "{}");+ const files = { woken: join(scratch, "woken"), rpc: join(scratch, "rpc.jsonl") };+ const instance = await GrokAgentDriver.create({+ instanceId: id,+ displayName: "Grok",+ enabled: true,+ environment: {+ GROK_HOME: join(scratch, "grok"), FAKE_ACP_MODE: "background-wake", FAKE_ACP_NO_FORK: "1", FAKE_ACP_CLOSE_ENDS_JOBS: "1",+ FAKE_ACP_WOKEN_FILE: files.woken, FAKE_ACP_RPC_APPEND_FILE: files.rpc, FAKE_ACP_STEP_MS: "100", ...extra,+ },+ config: { cli: FAKE_CLI, fullAuto: true },+ } as never) as ProviderInstance;+ const recorder = recordEvents(instance.adapter);+ const calls = () => existsSync(files.rpc)+ ? readFileSync(files.rpc, "utf8").trim().split("\n").map((line) => JSON.parse(line) as { 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 });+ return recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);+ };+ return { instance, recorder, 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;++describe("Grok background work", () => {+ it("ends a turn its background job wakes between ours, drops its output, and goes on in the same session", async () => {+ const { instance, recorder, calls, steps, ask } = await start("grok-background-wake");+ const threadId = "t-grok-background-wake";+ try {+ expect(await ask(threadId, "build it")).toMatchObject({ ok: true });+ const session = promptedSession(calls)!;+ await until(() => calls().some((call) => call.method === "session/close" && call.sessionId === session));+ const woken = steps();+ 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");+ expect(calls().filter((call) => call.method === "session/load").at(-1)?.sessionId).toBe(session);+ expect(promptedSession(calls)).toBe(session);+ 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 () => {+ const { instance, recorder, calls, steps, ask } = await start("grok-background-stop", { FAKE_ACP_WAKE_MS: "1500" });+ const threadId = "t-grok-background-stop";+ try {+ const { turnId } = await instance.adapter.sendTurn({ threadId, text: "build it STOP_ME" });+ 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/close" && call.sessionId === session));+ await pause(Math.max(0, 1_800 - (Date.now() - startedAt)));+ expect(steps()).toBe(0);+ expect(await ask(threadId, "go on")).toMatchObject({ ok: true });+ expect(promptedSession(calls)).toBe(session);+ expect(JSON.stringify(recorder.events)).not.toContain("WOKEN");+ } finally {+ recorder.stop();+ await instance.dispose();+ }+ });+});diff --git a/server/drivers/acp/grok-steer.test.ts b/server/drivers/acp/grok-steer.test.tsnew file mode 100644index 0000000000..d9a4132a17--- /dev/null+++ b/server/drivers/acp/grok-steer.test.ts@@ -0,0 +1,160 @@+// Steering a running Grok turn with a second session/prompt, against the scripted ACP peer.+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { ensureDirs } from "../../config.ts";+import type { AnyProviderDriver, ProviderInstance } from "../../contracts.ts";+import { removeTempDir } from "../../testing/cleanup.ts";+import { recordEvents, type EventRecorder } from "../../testing/events.ts";+import { ensureGrokSteer, GrokAgentDriver } from "./grok.ts";++const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "../../testing/fake-acp-cli.ts");++let scratch: string;+let instance: ProviderInstance | undefined;+let recorder: EventRecorder | undefined;++beforeEach(() => {+ ensureDirs();+ scratch = mkdtempSync(join(tmpdir(), "omb-grok-steer-"));+});++afterEach(async () => {+ recorder?.stop();+ await instance?.dispose();+ instance = undefined;+ recorder = undefined;+ await removeTempDir(scratch);+});++const configure = (steer: boolean) => {+ mkdirSync(join(scratch, "grok"), { recursive: true });+ writeFileSync(join(scratch, "grok", "auth.json"), "{}");+ writeFileSync(join(scratch, "grok", "config.toml"), `[ui]+follow_up_behavior = "${steer ? "steer" : "queue"}"+`);+};++const gate = () => join(scratch, "finish.gate");++const start = async (driver: AnyProviderDriver, mode: string, extra: Record<string, string> = {}) => {+ instance = await driver.create({+ instanceId: `steer-${driver.driverKind}`,+ displayName: "Steer fixture",+ enabled: true,+ environment: {+ HOME: scratch,+ USERPROFILE: scratch,+ XDG_DATA_HOME: join(scratch, "data"),+ GROK_HOME: join(scratch, "grok"),+ OPENMAUSBOT_PROBE_LOCAL_INJECT: "0",+ FAKE_ACP_MODELS: "swe-1-6-fast,claude-sonnet-5-5",+ FAKE_ACP_MODES: "accept-edits,smart,ask,plan,bypass",+ FAKE_ACP_MODE: mode,+ FAKE_ACP_GATE_FILE: gate(),+ FAKE_ACP_RPC_APPEND_FILE: join(scratch, "rpc.jsonl"),+ ...extra,+ },+ config: { cli: FAKE_CLI, fullAuto: true },+ } as never) as ProviderInstance;+ recorder = recordEvents(instance.adapter);+ return instance;+};++const threadId = "steer-thread";++const runningTurn = async () => {+ const { turnId } = await instance!.adapter.sendTurn({ threadId, text: "Build the report.", cwd: scratch });+ await recorder!.until((event) => event.turnId === turnId && event.type === "content.delta" && event.delta.includes("working"));+ return turnId;+};++const finished = async (turnId: string) => {+ writeFileSync(gate(), "finish");+ return recorder!.until((event) => event.turnId === turnId && event.type === "turn.completed");+};++const replyOf = (turnId: string) => recorder!.events+ .flatMap((event) => event.turnId === turnId && event.type === "item.completed" && event.itemType === "assistant_text" ? [event.text] : []);++const usageOf = (turnId: string) => recorder!.events+ .flatMap((event) => event.turnId === turnId && event.type === "thread.token-usage.updated" ? [[event.input, event.output]] : []);++const until = async (done: () => boolean) => {+ for (let tries = 0; !done(); tries += 1) {+ if (tries > 200) throw new Error("the agent never received the steer");+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+};++const methods = () => existsSync(join(scratch, "rpc.jsonl"))+ ? readFileSync(join(scratch, "rpc.jsonl"), "utf8").trim().split("\n").map((line) => JSON.parse(line).method as string)+ : [];++describe("Grok steering", () => {+ it("steers a message into the running turn as a second prompt and ends with the turn's own reply", async () => {+ configure(true);+ await start(GrokAgentDriver, "grok-steer");+ const turnId = await runningTurn();++ expect(await instance!.adapter.steer!(threadId, " Use pytest. ")).toBe("steered");+ await until(() => methods().includes("session/prompt.steer"));++ expect(await finished(turnId)).toMatchObject({ ok: true });+ expect(replyOf(turnId)).toEqual(["working. done; steered: Use pytest."]);+ expect(usageOf(turnId)).toEqual([[10, 5]]);+ });++ it("refuses without sending while Grok's follow-up behaviour is queue", async () => {+ configure(false);+ await start(GrokAgentDriver, "grok-steer");+ const turnId = await runningTurn();++ expect(await instance!.adapter.steer!(threadId, "use pytest")).toBe("refused");+ expect(methods()).not.toContain("session/prompt.steer");+ await finished(turnId);+ expect(replyOf(turnId)).toEqual(["working. done"]);+ });+});++describe("ensureGrokSteer", () => {+ const home = () => join(scratch, "grok");+ const config = () => join(home(), "config.toml");+ const env = () => ({ GROK_HOME: home() });+ const signedIn = () => { mkdirSync(home(), { recursive: true }); writeFileSync(join(home(), "auth.json"), "{}"); };++ it("adds a [ui] section to a config without one", () => {+ signedIn();+ writeFileSync(config(), '[cli]\ninstaller = "internal"\n');+ ensureGrokSteer(env());+ expect(readFileSync(config(), "utf8")).toBe('[cli]\ninstaller = "internal"\n\n[ui]\nfollow_up_behavior = "steer"\n');+ });++ it("adds the key under an existing [ui]", () => {+ signedIn();+ writeFileSync(config(), '[ui]\nscreen_mode = "minimal"\n');+ ensureGrokSteer(env());+ expect(readFileSync(config(), "utf8")).toBe('[ui]\nfollow_up_behavior = "steer"\nscreen_mode = "minimal"\n');+ });++ it("creates the config for a signed-in account that has none", () => {+ signedIn();+ ensureGrokSteer(env());+ expect(readFileSync(config(), "utf8")).toBe('[ui]\nfollow_up_behavior = "steer"\n');+ });++ it("keeps a choice the person already made", () => {+ signedIn();+ writeFileSync(config(), '[ui]\nfollow_up_behavior = "queue"\n');+ ensureGrokSteer(env());+ expect(readFileSync(config(), "utf8")).toBe('[ui]\nfollow_up_behavior = "queue"\n');+ });++ it("leaves a signed-out home alone", () => {+ ensureGrokSteer(env());+ expect(existsSync(home())).toBe(false);+ });+});diff --git a/server/drivers/acp/grok.ts b/server/drivers/acp/grok.tsindex 1efda9b6e4..179cea1575 100644--- a/server/drivers/acp/grok.ts+++ b/server/drivers/acp/grok.ts@@ -10,6 +10,8 @@ import { harnessHome, splitCliString } from "../../env-path.ts";import type { DeviceSignIn, DeviceSignInState } from "../device-auth.ts";import { decodeInjectId, hostApiKey, localHost, mergeLocalInject } from "../local-inject.ts";import { createAcpDriver, type AcpSupport } from "./core.ts";+import { closeEndsBackgroundWork } from "./background-work.ts";+import type { AcpPromptSteer } from "./steer.ts";import { bundledEngineCatalog } from "../../model-manifest/bundled.ts";import { currentEngineCatalog } from "../../model-manifest/manifest.ts";import { ENGINE_MODEL_ID } from "../../model-manifest/schema.ts";@@ -338,6 +340,49 @@ export function grokToolScopeProfile(scope: unknown, init: unknown, inherited?:};}+/** grok 1.0.89: with `[ui] follow_up_behavior = "steer"` in config.toml, a second `session/prompt` is injected into the running+ * turn at its next safe point and answers `cancelled` with `_meta.completionKind: "removedFromQueue"` and no tokens; with the+ * default "queue" it waits for the turn to end. `initialize` does not report the setting, and `GROK_CONFIG` cannot set `ui`. */+export const GROK_STEER: AcpPromptSteer = {+ kind: "prompt",+ enabled: (env) => {+ try {+ return /^\s*follow_up_behavior\s*=\s*"steer"/m.test(readFileSync(join(grokHome(env), "config.toml"), "utf8"));+ } catch {+ return false;+ }+ },+ folded: (response) => (response as { _meta?: { completionKind?: unknown } } | null)?._meta?.completionKind === "removedFromQueue",+};++/** grok 1.0.89 (auto_wake, on by default): a background subagent or shell command that finishes after the turn wakes a turn+ * no `session/prompt` asked for; `session/close` ends it and `session/load` of the same id brings the history back. */+const GROK_BACKGROUND = closeEndsBackgroundWork();++/** Turns on Grok's mid-turn steering for a signed-in account, unless its config.toml already sets `follow_up_behavior`. */+export function ensureGrokSteer(env: Record<string, string | undefined> = process.env): void {+ if (!grokSignedIn(env)) return;+ const path = join(grokHome(env), "config.toml");+ let text = "";+ try {+ text = readFileSync(path, "utf8");+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") return;+ }+ if (/^\s*follow_up_behavior\s*=/m.test(text)) return;+ const eol = text.includes("\r\n") ? "\r\n" : "\n";+ const line = `follow_up_behavior = "steer"${eol}`;+ const header = /^\[ui\][ \t]*\r?\n/m.exec(text);+ const next = header+ ? text.slice(0, header.index + header[0].length) + line + text.slice(header.index + header[0].length)+ : `${text}${text && !text.endsWith("\n") ? eol : ""}${text ? eol : ""}[ui]${eol}${line}`;+ try {+ writeFileSync(path, next);+ } catch {+ // Grok then keeps queueing mid-turn messages, its default.+ }+}+/** Grok's `ask_user_question` blocks its turn on this extension request (xai-org/grok-build ask_user_question/types.rs);* ACP's Rust SDK adds the `_` prefix on the wire. Answers are keyed by Grok's question text, one label per pick; own* words ride as "Other" with the text in annotations[].notes. */@@ -403,6 +448,8 @@ const support: AcpSupport = {signInCommand: "grok login",},deviceSignIn: GROK_DEVICE_SIGN_IN,+ steer: GROK_STEER,+ backgroundWork: GROK_BACKGROUND,// With the instance HOME/GROK_HOME: ensureGrokInjectSlug defaults to process.env.resolveTurnModel: (model, env) => (model ? ensureGrokInjectSlug(model, env) : model),@@ -484,6 +531,7 @@ const support: AcpSupport = {delete env.XAI_API_KEY;},applyTurnEnv: (env, { toolScope }) => {+ ensureGrokSteer(env);if (toolScope !== undefined) {// These env switches outrank account defaults in the verified runtime.env.GROK_MANAGED_MCPS_ENABLED = "false";diff --git a/server/drivers/acp/hermes-steer.test.ts b/server/drivers/acp/hermes-steer.test.tsindex a7cf8115a0..e9b593abc6 100644--- a/server/drivers/acp/hermes-steer.test.ts+++ b/server/drivers/acp/hermes-steer.test.ts@@ -19,7 +19,6 @@ import { CustomAcpDriver } from "./custom.ts";import { DeepSeekAgentDriver } from "./deepseek.ts";import { DroidAgentDriver } from "./droid.ts";import { GeminiAgentDriver } from "./gemini.ts";-import { GrokAgentDriver } from "./grok.ts";import { HermesAgentDriver, hermesSteerAnswer } from "./hermes.ts";import { KimiAgentDriver } from "./kimi.ts";import { KiroAgentDriver } from "./kiro.ts";@@ -197,7 +196,7 @@ describe("other ACP engines", () => {// Each runs against an agent that offers /steer: an engine whose own support is unproven still never steers.it.each([GeminiAgentDriver, KimiAgentDriver, DroidAgentDriver, CursorAgentDriver, QwenAgentDriver, ClineAgentDriver,- CopilotAgentDriver, CommandCodeAgentDriver, KiroAgentDriver, CustomAcpDriver, DeepSeekAgentDriver, GrokAgentDriver, AntigravityDriver,+ CopilotAgentDriver, CommandCodeAgentDriver, KiroAgentDriver, CustomAcpDriver, DeepSeekAgentDriver, AntigravityDriver,] as AnyProviderDriver[])("$driverKind does not steer", async (driver) => {await start(driver);expect(instance!.adapter.capabilities.queueing).toBeUndefined();diff --git a/server/drivers/acp/opencode-background.ts b/server/drivers/acp/opencode-background.tsindex a6e3e6fa2e..bb0821f215 100644--- a/server/drivers/acp/opencode-background.ts+++ b/server/drivers/acp/opencode-background.ts@@ -6,24 +6,14 @@// 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>;+import { TURN_UPDATES, type AcpBackgroundWork } from "./background-work.ts";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 {+export function openCodeBackgroundWork(): AcpBackgroundWork {const forkedTo = new Map<string, string>();return {wakes: (update) => {diff --git a/server/drivers/acp/steer.ts b/server/drivers/acp/steer.tsindex 5cad3af903..a348f2cefa 100644--- a/server/drivers/acp/steer.ts+++ b/server/drivers/acp/steer.ts@@ -20,13 +20,17 @@ export interface AcpRequestSteer {supported(initializeResult: unknown): boolean;}-/** Devin: a second `session/prompt` joins the running turn, for a CLI whose `initialize` sets `agentCapabilities._meta[capability]`.- * Both prompts end together; their replies carry the same usage and the same `run`. */+/** A second `session/prompt` joins the running turn: Devin, for a CLI whose `initialize` sets `agentCapabilities._meta[capability]`+ * (both prompts end together; their replies carry the same usage and the same `run`), and Grok, whose config opts in (`enabled`). */export interface AcpPromptSteer {kind: "prompt";- capability: string;+ capability?: string;+ /** For an agent that does not announce the capability: whether this process's environment opts in. */+ enabled?(env: Record<string, string | undefined>): boolean;/** The run a prompt reply ends; replies of one run report their usage once. */- run(response: unknown): string | undefined;+ run?(response: unknown): string | undefined;+ /** A steer reply that only reports its message was taken into the running turn; the turn's own reply is the outcome. */+ folded?(response: unknown): boolean;}export type AcpSteerSupport = AcpCommandSteer | AcpRequestSteer | AcpPromptSteer;@@ -163,6 +167,7 @@ export interface AcpSteerIo {open(): boolean;commands(): ReadonlySet<string> | undefined;initializeResult(): any;+ env: Record<string, string | undefined>;prompt(text: string): Promise<unknown>;extension(method: string, text: string): Promise<unknown>;}@@ -173,7 +178,7 @@ export function turnSteering(support: AcpSteerSupport, io: AcpSteerIo): AcpTurnS(text) => io.extension(support.method, text));}if ("kind" in support && support.kind === "prompt") {- return acpPromptSteering(() => io.open() && io.initializeResult()?.agentCapabilities?._meta?.[support.capability] === true, io.prompt);+ return acpPromptSteering(() => io.open() && (support.enabled ? support.enabled(io.env) : io.initializeResult()?.agentCapabilities?._meta?.[support.capability ?? ""] === true), io.prompt);}return acpTurnSteering(support, () => io.open() && io.commands()?.has(support.command) === true, io.prompt);}diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.tsindex b9975cd67e..c45fe1955a 100755--- a/server/testing/fake-acp-cli.ts+++ b/server/testing/fake-acp-cli.ts@@ -30,7 +30,8 @@// 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)+// deleted session refuses session/prompt until loaded. Advertises close, delete and, unless FAKE_ACP_NO_FORK=1, fork; FAKE_ACP_CLOSE_ENDS_JOBS=1: session/close+// ends the job too, as grok 1.0.89's does)// 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@@ -93,6 +94,9 @@// {outcome:"steered"}, or {outcome:"promptRequired"} with no prompt running (FAKE_ACP_STEER_FAIL=rpc: a JSON-RPC error).// FAKE_ACP_MODE=devin-steer Devin's second `session/prompt`: initialize reports agentCapabilities._meta["cognition.ai/midTurnPrompts"];// a prompt during a running one joins it, and both end together with the same usage and _meta["cognition.ai/userMessageId"].+// FAKE_ACP_MODE=grok-steer Grok's second `session/prompt` with `[ui] follow_up_behavior = "steer"` in GROK_HOME/config.toml: a prompt+// during a running one is injected into it and answers {stopReason:"cancelled", _meta:{completionKind:"removedFromQueue"}}+// at once; the running prompt then ends with end_turn and every steer it took.// FAKE_ACP_STEERING=off the two steer modes above report no steering capability.import { AsyncLocalStorage } from "node:async_hooks";import { spawn } from "node:child_process";@@ -767,6 +771,12 @@ let gatedRuns = 0;* answered with the first one, with the same usage and run id, as Devin does. opencode-steer: only `_session/steering` joins it. */function gatedPrompt(msg: any) {const text = (Array.isArray(msg.params?.prompt) ? msg.params.prompt : []).map((block: any) => block?.text ?? "").join("");+ if (gatedTurn && mode === "grok-steer") {+ recordMethod("session/prompt.steer");+ gatedTurn.steers.push(text);+ result(msg.id, { stopReason: "cancelled", _meta: { completionKind: "removedFromQueue" } });+ return;+ }if (gatedTurn && mode === "devin-steer") {recordMethod("session/prompt.steer");gatedTurn.steers.push(text);@@ -980,6 +990,11 @@ function handle(msg: any) {}case "session/close":endWokenStep(msg.params?.sessionId);+ if (process.env.FAKE_ACP_CLOSE_ENDS_JOBS === "1") {+ 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));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));@@ -1167,7 +1182,7 @@ function handle(msg: any) {hermesPrompt(msg);return;}- if (mode === "opencode-steer" || mode === "devin-steer") {+ if (mode === "opencode-steer" || mode === "devin-steer" || mode === "grok-steer") {gatedPrompt(msg);return;}