Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Grok: resume a session whose load goes quiet, switch model and effort in place, scope "this session" approvals, check the login

milind-soni54a0536ec567
diff --git a/server/drivers/acp/acp.test.ts b/server/drivers/acp/acp.test.ts
index 249cf098ae..e072946f44 100644
--- a/server/drivers/acp/acp.test.ts
+++ b/server/drivers/acp/acp.test.ts
@@ -1936,7 +1936,7 @@ describe("ACP turns (fake CLI)", () => {
process.env.FAKE_ACP_ALLOW_ALWAYS = "1";
const answer = join(scratch, "permission-answer.txt");
process.env.FAKE_ACP_PERMISSION_ANSWER = answer;
- await create(GrokAgentDriver, "permission");
+ await create(GeminiAgentDriver, "permission");
await instance.adapter.sendTurn({ threadId: "t-always-native", text: "go", approvalMode: "ask" });
const opened = await recorder.until((e) => e.type === "request.opened");
expect(opened).toHaveProperty("allowSession", true);
diff --git a/server/drivers/acp/client-file-request.ts b/server/drivers/acp/client-file-request.ts
new file mode 100644
index 0000000000..c4f4c18793
--- /dev/null
+++ b/server/drivers/acp/client-file-request.ts
@@ -0,0 +1,55 @@
+// ACP's client file methods (fs/read_text_file, fs/write_text_file), answered inside the turn's folder.
+import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
+import { dirname } from "node:path";
+
+import { resolveAcpClientPath } from "./client-path.ts";
+
+const CLIENT_FILE_MAX_BYTES = 8 * 1024 * 1024;
+
+export async function answerClientFileRequest(msg: any, context: {
+ send: (obj: unknown) => void;
+ cwd: string;
+ enabled: boolean;
+ /** Server-owned directories a read may also reach; writes stay inside `cwd`. */
+ readRoots: () => readonly string[] | undefined;
+}): Promise<void> {
+ const { send } = context;
+ try {
+ if (!context.enabled) throw new Error("Client file access is disabled.");
+ const params = msg.params ?? {};
+ const path = await resolveAcpClientPath(params.path, context.cwd, msg.method === "fs/read_text_file" ? context.readRoots() : undefined);
+ if (msg.method === "fs/read_text_file") {
+ const info = await stat(path);
+ if (!info.isFile() || info.size > CLIENT_FILE_MAX_BYTES) {
+ throw new Error(`ACP can only read text files under ${CLIENT_FILE_MAX_BYTES} bytes.`);
+ }
+ const content = await readFile(path, "utf8");
+ if (params.line == null && params.limit == null) {
+ send({ jsonrpc: "2.0", id: msg.id, result: { content } });
+ return;
+ }
+ const line = typeof params.line === "number" && Number.isInteger(params.line) && params.line > 0 ? params.line : 1;
+ const limit = typeof params.limit === "number" && Number.isInteger(params.limit) && params.limit >= 0 ? params.limit : undefined;
+ const lines = content.split("\n");
+ const start = line - 1;
+ send({
+ jsonrpc: "2.0",
+ id: msg.id,
+ result: { content: lines.slice(start, limit === undefined ? undefined : start + limit).join("\n") },
+ });
+ return;
+ }
+ if (typeof params.content !== "string" || Buffer.byteLength(params.content) > CLIENT_FILE_MAX_BYTES) {
+ throw new Error(`ACP can only write text files under ${CLIENT_FILE_MAX_BYTES} bytes.`);
+ }
+ await mkdir(dirname(path), { recursive: true });
+ await writeFile(path, params.content, "utf8");
+ send({ jsonrpc: "2.0", id: msg.id, result: {} });
+ } catch (error) {
+ send({
+ jsonrpc: "2.0",
+ id: msg.id,
+ error: { code: -32602, message: error instanceof Error ? error.message : String(error) },
+ });
+ }
+}
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index db1745539c..ea52311a70 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -6,9 +6,9 @@ import { type ServerText } from "../../../shared/server-text.ts";
// `allow`-kind option approves, and option order is never a security contract.
import { mkdtempSync, rmSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
-import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
-import { dirname, join } from "node:path";
-import { resolveAcpClientPath } from "./client-path.ts";
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+import { answerClientFileRequest } from "./client-file-request.ts"; import { loadUntilReplayQuiet } from "./load-replay.ts";
import { createHash } from "node:crypto";
import { PROVIDER_CREDENTIAL_ENV, stripControlPlaneEnv, WORKSPACE_CREDENTIAL_ENV } from "../../config.ts";
@@ -65,7 +65,7 @@ import { acpSessionOperationKey, acpShellRequest, answersAlone, permissionLaunch
import { openQuestionRequest, questionRequestFor, type AcpQuestionRequest } from "./question-requests.ts";
import { commandSummary, toolDetailPreview } from "../../tool-summary.ts";
import { acpToolEndEvents } from "./tool-items.ts";
-import { AcpHost } from "./host.ts"; import { SignInRequests, type AcpDriverHooks } from "./driver-hooks.ts";
+import { AcpHost } from "./host.ts"; import { LiveSwitchRefused, SignInRequests, type AcpDriverHooks } from "./driver-hooks.ts";
import { exitBeforeResult } from "./exit-report.ts"; import { readNodeVersion } from "./node-version.ts";
import { decodeAcpConfig } from "./config-decode.ts";
import { endTurn, trackAssistantImage, trackAssistantWords, trackThoughtAfterTool, trackRunningTool, trackToolEndShown, type AcpAskFinish, type AcpSession, type AcpTurn } from "./turn-state.ts";
@@ -260,6 +260,7 @@ export interface AcpSupport extends AcpDriverHooks {
sessionModels: Array<{ modelId?: string; name?: string }>;
/** Last model acknowledged by session/new/load/set_model, preserved for pooled turns. */
currentModelId?: string;
+ /** The session's effort, and where a live change to it is recorded. */ currentEffort?: EffortLevel; effortApplied?(effort: EffortLevel | undefined): void;
/** session/new's or session/load's `configOptions`, verbatim. */
configOptions: Array<{ id?: unknown; currentValue?: unknown }>;
/** Tell the person the session runs another model than the one picked. */
@@ -293,7 +294,6 @@ function nextUnkeyedToolId(current: AcpTurn): string {
current.unkeyedToolIds.push(id);
return id;
}
-const CLIENT_FILE_MAX_BYTES = 8 * 1024 * 1024;
async function readAcpImageBlocks(images: readonly TurnImageInput[]) {
return Promise.all(images.map(async (image) => ({
@@ -618,52 +618,10 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const acp = host.link(threadId, cwd);
const send = (obj: unknown) => acp.send(obj); const nodeVersion = support.minNodeVersion ? readNodeVersion(env) : undefined;
- const handleClientFileRequest = async (msg: any, current: AcpTurn): Promise<void> => {
- const fail = (error: unknown) => send({
- jsonrpc: "2.0",
- id: msg.id,
- error: { code: -32602, message: error instanceof Error ? error.message : String(error) },
- });
- try {
- if (!support.clientFileSystem) throw new Error("Client file access is disabled.");
- const params = msg.params ?? {};
- const path = await resolveAcpClientPath(params.path, cwd, msg.method === "fs/read_text_file" ? support.clientReadRoots?.(current.turn) : undefined);
- if (msg.method === "fs/read_text_file") {
- const info = await stat(path);
- if (!info.isFile() || info.size > CLIENT_FILE_MAX_BYTES) {
- throw new Error(`ACP can only read text files under ${CLIENT_FILE_MAX_BYTES} bytes.`);
- }
- const content = await readFile(path, "utf8");
- if (params.line == null && params.limit == null) {
- send({ jsonrpc: "2.0", id: msg.id, result: { content } });
- return;
- }
- const line = typeof params.line === "number" && Number.isInteger(params.line) && params.line > 0 ? params.line : 1;
- const limit = typeof params.limit === "number" && Number.isInteger(params.limit) && params.limit >= 0 ? params.limit : undefined;
- const lines = content.split("\n");
- const start = line - 1;
- send({
- jsonrpc: "2.0",
- id: msg.id,
- result: { content: lines.slice(start, limit === undefined ? undefined : start + limit).join("\n") },
- });
- return;
- }
- if (typeof params.content !== "string" || Buffer.byteLength(params.content) > CLIENT_FILE_MAX_BYTES) {
- throw new Error(`ACP can only write text files under ${CLIENT_FILE_MAX_BYTES} bytes.`);
- }
- await mkdir(dirname(path), { recursive: true });
- await writeFile(path, params.content, "utf8");
- send({ jsonrpc: "2.0", id: msg.id, result: {} });
- } catch (error) {
- fail(error);
- }
- };
-
const handleServerRequest = (msg: any, current: AcpTurn) => {
current.state.startupActivity = true; if (current.state.promptSent) current.acknowledge();
if (msg.method === "fs/read_text_file" || msg.method === "fs/write_text_file") {
- void handleClientFileRequest(msg, current);
+ void answerClientFileRequest(msg, { send, cwd, enabled: support.clientFileSystem === true, readRoots: () => support.clientReadRoots?.(current.turn) });
return;
}
const question = questionRequestFor(support.questionRequests, msg.method);
@@ -1021,7 +979,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const envFingerprint = createHash("sha256").update(JSON.stringify(spawnEnv)).digest("hex").slice(0, 16);
const inheritedScopeFingerprint = narrowsNativeTools(turn.toolScope) && support.toolScopeCacheKey
? createHash("sha256").update(support.toolScopeCacheKey({ config: turnConfig, env, cwd })).digest("hex") : null;
- const processContract = [launch.command, launch.args ?? [], spawnArgs,
+ const processContract = [launch.command, launch.args ?? [], support.spawnContractArgs?.(turnConfig, cliTurn) ?? spawnArgs,
support.sessionScopedApproval ? null : turnConfig.fullAuto === true, envFingerprint,
support.spawnFingerprint?.(spawnEnv, turnConfig) ?? null, launch.ro ?? [], boxAudienceKey(cwd)];
const contractKey = JSON.stringify([...processContract, cwd, turn.toolScope ?? null, inheritedScopeFingerprint]);
@@ -1035,7 +993,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const hostKey = support.shareProcess && inheritedScopeFingerprint === null ? JSON.stringify([...processContract, launchModel ?? null, engineHomes.scope(), sharedBoxScope(cwd)]) : null;
const launchSession = () => {
const opened = openSession(threadId, launch, [...(launch.args ?? []), ...spawnArgs], launchEnv, cwd, contractKey, hostKey);
- opened.launchModel = launchModel;
+ opened.launchModel = launchModel; opened.effort = cliTurn.effort;
launchedThisTurn = true;
return opened;
};
@@ -1220,11 +1178,13 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
let loaded = false;
if (cursor && (!support.closeBeforeLiveLoad || liveSessionId !== cursor || await request("session/close", { sessionId: cursor }, 30_000).then(() => { session.sessionId = session.sessionKey = null; return true; }, () => false))) {
try {
- await request(
- support.resumeMethod === "resume" ? "session/resume" : "session/load",
- { sessionId: cursor, cwd, mcpServers: support.mcpServersFromLaunch ? [] : mcpServers, ...selectionParams, ...support.sessionSetupParams?.(init) },
- LOAD_SESSION_TIMEOUT,
- (result) => {
+ await loadUntilReplayQuiet({
+ link: session.acp, sessionId: cursor, quietMs: support.loadReplayQuietMs?.(turn), replayed: () => session.sessionConfigResult ?? {},
+ send: (receive) => request(
+ support.resumeMethod === "resume" ? "session/resume" : "session/load",
+ { sessionId: cursor, cwd, mcpServers: support.mcpServersFromLaunch ? [] : mcpServers, ...selectionParams, ...support.sessionSetupParams?.(init) },
+ LOAD_SESSION_TIMEOUT, receive),
+ receive: (result) => {
if (result) {
loaded = true;
session.sessionId = cursor;
@@ -1232,7 +1192,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
receiveModelVariants(result, true);
}
},
- );
+ });
} catch (error) {
const classification = support.classifyError?.(error);
// OpenCode sends invalidParams with only the rejected sessionId. Cursor puts the id in the
@@ -1322,7 +1282,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
sessionModels: Array.isArray(session.sessionConfigResult?.models?.availableModels)
? session.sessionConfigResult.models.availableModels
: [],
- currentModelId: session.sessionConfigResult?.models?.currentModelId,
+ currentModelId: session.sessionConfigResult?.models?.currentModelId, currentEffort: session.effort, effortApplied: (effort) => { session.effort = effort; },
configOptions: Array.isArray(session.sessionConfigResult?.configOptions)
? session.sessionConfigResult.configOptions
: [],
@@ -1351,6 +1311,13 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
} catch (error) {
// session.started is the only place the resume cursor is recorded.
emitSessionStarted();
+ if (error instanceof LiveSwitchRefused && !launchedThisTurn && retryOf === undefined && !state.stopped && !session.closing) {
+ acknowledge(); state.settled = true; session.current = null; active.delete(threadId); closeSession(threadId, "contract");
+ return void sendTurn({ ...turn, startupRecovery: undefined, sessionReset: undefined, resumeCursor: sessionId }, turnId).catch((failure) => {
+ emit({ ...base(threadId, turnId), type: "runtime.error", message: failure instanceof Error ? failure.message : String(failure) });
+ emit({ ...base(threadId, turnId), type: "turn.completed", ok: false, stopReason: "rpc_error", cost: null });
+ });
+ }
throw error;
}
emitSessionStarted();
diff --git a/server/drivers/acp/driver-hooks.ts b/server/drivers/acp/driver-hooks.ts
index fa19a4183e..e65c172602 100644
--- a/server/drivers/acp/driver-hooks.ts
+++ b/server/drivers/acp/driver-hooks.ts
@@ -2,6 +2,8 @@
// changes behaviour.
import type { ChildProcess } from "node:child_process";
+import type { SendTurnInput } from "../../contracts.ts";
+import type { AcpConfig } from "./core.ts";
import type { AcpHost } from "./host.ts";
export interface AcpDriverHooks {
@@ -29,8 +31,17 @@ export interface AcpDriverHooks {
/** The failure a turn's thrown error stands for, in the person's words (a usage limit with its reset), or undefined to
* keep the error as it is. Must not throw. */
reportedFailure?(error: unknown): Error | undefined;
+ /** For an agent that can leave session/load unanswered after replaying the history: how long the replay must go quiet
+ * before the load counts as done. Undefined waits for the answer. */
+ loadReplayQuietMs?(turn: SendTurnInput): number | undefined;
+ /** The part of spawnArgs a running process must match for a turn to reuse it. What it leaves out, configureSession
+ * changes inside the live session, throwing LiveSwitchRefused when the agent refuses; a reused session then restarts. */
+ spawnContractArgs?(config: AcpConfig, turn: SendTurnInput): string[];
}
+/** configureSession could not change a running session's model or effort in place. */
+export class LiveSwitchRefused extends Error {}
+
const MAX_LINE_CHARS = 64 * 1024;
export class SignInRequests {
diff --git a/server/drivers/acp/grok-session.test.ts b/server/drivers/acp/grok-session.test.ts
new file mode 100644
index 0000000000..042720ceb6
--- /dev/null
+++ b/server/drivers/acp/grok-session.test.ts
@@ -0,0 +1,221 @@
+// A Grok conversation's session across turns, against the scripted ACP peer: resuming it when the load goes unanswered
+// after its replay, changing model or effort without a second process, and what "this session" approves.
+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, NATIVE_DIR } from "../../config.ts";
+import type { ProviderInstance, SendTurnInput } from "../../contracts.ts";
+import { removeTempDir } from "../../testing/cleanup.ts";
+import { recordEvents } from "../../testing/events.ts";
+import { GrokAgentDriver, grokPermissionRequest } 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-session-"));
+ scratches.push(scratch);
+ mkdirSync(join(scratch, "grok"), { recursive: true });
+ writeFileSync(join(scratch, "grok", "auth.json"), "{}");
+ const files = { rpc: join(scratch, "rpc.jsonl"), dump: join(scratch, "dump.json"), answer: join(scratch, "answer.txt") };
+ const instance = await GrokAgentDriver.create({
+ instanceId: id,
+ displayName: "Grok",
+ enabled: true,
+ environment: {
+ GROK_HOME: join(scratch, "grok"), FAKE_ACP_RPC_APPEND_FILE: files.rpc, FAKE_ACP_DUMP: files.dump, FAKE_ACP_PERMISSION_ANSWER: files.answer, ...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 { pid: number; method: string; sessionId?: string }) : [];
+ const processes = () => new Set(calls().map((call) => call.pid)).size;
+ const ask = async (turn: Omit<SendTurnInput, "text"> & { text?: string }) => {
+ const { turnId } = await instance.adapter.sendTurn({ text: "go", ...turn } as SendTurnInput);
+ return recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId, 30_000);
+ };
+ const sent = (threadId: string, method: string) => readFileSync(join(NATIVE_DIR, `${threadId}.ndjson`), "utf8").trim().split("\n")
+ .map((line) => JSON.parse(line)).filter((entry) => entry.dir === "out" && entry.msg?.method === method).map((entry) => entry.msg.params);
+ return { instance, recorder, calls, processes, ask, sent, files };
+};
+
+describe("Grok resumes a session whose load goes unanswered after its replay", () => {
+ it.each([["unmarked", "0"], ["marked as replay", "1"]])("goes on in the loaded session once a %s replay goes quiet", async (_, marked) => {
+ const { instance, recorder, calls, ask } = await start(`grok-replay-${marked}`, {
+ FAKE_ACP_LOAD_REPLAY: "3", FAKE_ACP_LOAD_REPLAY_MARKED: marked, FAKE_ACP_LOAD_UNANSWERED: "1",
+ });
+ try {
+ const threadId = `t-grok-replay-${marked}`;
+ const startedAt = Date.now();
+ expect(await ask({ threadId, resumeCursor: "saved-session" })).toMatchObject({ ok: true });
+ // The load's own deadline is 120 s; the replay going quiet ends the wait in seconds.
+ expect(Date.now() - startedAt).toBeLessThan(60_000);
+ expect(calls().filter((call) => call.method === "session/new")).toEqual([]);
+ expect(calls().filter((call) => call.method === "session/prompt").map((call) => call.sessionId)).toEqual(["saved-session"]);
+ expect(JSON.stringify(recorder.events)).not.toContain("REPLAYED");
+ expect(recorder.events.find((event) => event.type === "session.started")).toMatchObject({ sessionId: "saved-session" });
+ expect(recorder.events.some((event) => event.type === "session.started" && "rebuilt" in event)).toBe(false);
+ } finally {
+ recorder.stop();
+ await instance.dispose();
+ }
+ }, 60_000);
+
+ it("still takes an answered load's own reply", async () => {
+ const { instance, recorder, calls, ask } = await start("grok-replay-answered", { FAKE_ACP_LOAD_REPLAY: "2" });
+ try {
+ expect(await ask({ threadId: "t-grok-replay-answered", resumeCursor: "saved-session" })).toMatchObject({ ok: true });
+ expect(calls().filter((call) => call.method === "session/prompt").map((call) => call.sessionId)).toEqual(["saved-session"]);
+ } finally {
+ recorder.stop();
+ await instance.dispose();
+ }
+ });
+});
+
+describe("Grok changes model and effort inside the running session", () => {
+ it("switches the model with session/set_model and keeps its one process", async () => {
+ const { instance, recorder, calls, processes, ask, sent } = await start("grok-live-model");
+ const threadId = "t-grok-live-model";
+ try {
+ expect(await ask({ threadId, model: "grok-4.5", effort: "high" })).toMatchObject({ ok: true });
+ expect(await ask({ threadId, model: "grok-4.6", effort: "high", resumeCursor: "fake-acp-session" })).toMatchObject({ ok: true });
+ expect(processes()).toBe(1);
+ expect(sent(threadId, "session/set_model").map((params) => params.modelId)).toEqual(["grok-4.5", "grok-4.6"]);
+ expect(calls().filter((call) => call.method === "session/prompt").map((call) => call.sessionId)).toEqual(["fake-acp-session", "fake-acp-session"]);
+ } finally {
+ recorder.stop();
+ await instance.dispose();
+ }
+ });
+
+ it("changes the effort with session/set_config_option, without set_model", async () => {
+ const { instance, recorder, processes, ask, sent } = await start("grok-live-effort", { FAKE_ACP_GROK_EFFORT: "1" });
+ const threadId = "t-grok-live-effort";
+ try {
+ expect(await ask({ threadId, model: "grok-4.5", effort: "high" })).toMatchObject({ ok: true });
+ expect(await ask({ threadId, model: "grok-4.5", effort: "low", resumeCursor: "fake-acp-session" })).toMatchObject({ ok: true });
+ expect(await ask({ threadId, model: "grok-4.5", effort: "low", resumeCursor: "fake-acp-session" })).toMatchObject({ ok: true });
+ expect(processes()).toBe(1);
+ expect(sent(threadId, "session/set_config_option")).toEqual([{ sessionId: "fake-acp-session", configId: "reasoning_effort", value: "low" }]);
+ expect(sent(threadId, "session/set_model")).toHaveLength(1);
+ } finally {
+ recorder.stop();
+ await instance.dispose();
+ }
+ });
+
+ it("changes the effort of a session whose load went quiet, which reported no options", async () => {
+ const { instance, recorder, processes, ask, sent } = await start("grok-live-effort-quiet", {
+ FAKE_ACP_GROK_EFFORT: "1", FAKE_ACP_LOAD_REPLAY: "2", FAKE_ACP_LOAD_UNANSWERED: "1",
+ });
+ const threadId = "t-grok-live-effort-quiet";
+ try {
+ expect(await ask({ threadId, model: "grok-4.5", effort: "high", resumeCursor: "saved-session" })).toMatchObject({ ok: true });
+ expect(await ask({ threadId, model: "grok-4.5", effort: "low", resumeCursor: "saved-session" })).toMatchObject({ ok: true });
+ expect(processes()).toBe(1);
+ expect(sent(threadId, "session/set_config_option")).toEqual([{ sessionId: "saved-session", configId: "reasoning_effort", value: "low" }]);
+ } finally {
+ recorder.stop();
+ await instance.dispose();
+ }
+ }, 30_000);
+
+ it("restarts with the new effort on its argv when Grok refuses the change, and the turn still runs", async () => {
+ const { instance, recorder, calls, processes, ask, files } = await start("grok-live-refused", { FAKE_ACP_GROK_EFFORT: "refuse" });
+ const threadId = "t-grok-live-refused";
+ try {
+ expect(await ask({ threadId, model: "grok-4.5", effort: "high" })).toMatchObject({ ok: true });
+ const second = await ask({ threadId, model: "grok-4.5", effort: "medium", resumeCursor: "fake-acp-session" });
+ expect(second).toMatchObject({ ok: true });
+ expect(processes()).toBe(2);
+ const argv = JSON.parse(readFileSync(files.dump, "utf8")).argv as string[];
+ expect(argv[argv.indexOf("--reasoning-effort") + 1]).toBe("medium");
+ expect(calls().filter((call) => call.method === "session/load").map((call) => call.sessionId)).toEqual(["fake-acp-session"]);
+ expect(recorder.events.filter((event) => event.type === "turn.completed")).toHaveLength(2);
+ expect(recorder.events.filter((event) => event.type === "runtime.error")).toEqual([]);
+ } finally {
+ recorder.stop();
+ await instance.dispose();
+ }
+ });
+
+ it("starts a new process when a narrowed tool profile names the model", async () => {
+ const { instance, recorder, processes, ask } = await start("grok-live-narrowed", { FAKE_ACP_GROK_VERSION: "1.0.41" });
+ const threadId = "t-grok-live-narrowed";
+ try {
+ const toolScope = { allow: ["native:read_file"] };
+ await ask({ threadId, model: "grok-4.5", toolScope });
+ await ask({ threadId, model: "grok-4.6", toolScope, resumeCursor: "fake-acp-session" });
+ expect(processes()).toBe(2);
+ } finally {
+ recorder.stop();
+ await instance.dispose();
+ }
+ });
+
+ it("starts a new process when the effort is cleared, since a running session cannot drop one", async () => {
+ const { instance, recorder, processes, ask } = await start("grok-live-cleared", { FAKE_ACP_GROK_EFFORT: "1" });
+ const threadId = "t-grok-live-cleared";
+ try {
+ await ask({ threadId, model: "grok-4.5", effort: "low" });
+ await ask({ threadId, model: "grok-4.5", resumeCursor: "fake-acp-session" });
+ expect(processes()).toBe(2);
+ } finally {
+ recorder.stop();
+ await instance.dispose();
+ }
+ });
+});
+
+// grok 1.0.41's options, as recorded for a bash command and for an edit.
+const BASH_OPTIONS = [
+ { optionId: "always-allow", name: "Yes, and don't ask again for bash commands", kind: "allow_always" },
+ { optionId: "allow-once", name: "Yes, proceed", kind: "allow_once" },
+ { optionId: "reject-once", name: "No, and tell Grok what to do differently", kind: "reject_once" },
+ { optionId: "reject-always", name: "No, and don't ask again for this command", kind: "reject_always" },
+];
+const EDIT_OPTIONS = [
+ { optionId: "allow-edits-session", name: "Yes, allow all edits during this session", kind: "allow_always" },
+ { optionId: "allow-once", name: "Yes", kind: "allow_once" },
+ { optionId: "reject-once", name: "No, and tell Grok what to do differently", kind: "reject_once" },
+];
+
+describe("Grok's \"allow for this session\"", () => {
+ it("keeps only the allow_always option that ends with the session", () => {
+ const filtered = (options: object[]) => grokPermissionRequest({ toolCall: { toolCallId: "call-1" }, options }).options.map((option: { optionId: string }) => option.optionId);
+ expect(filtered(BASH_OPTIONS)).toEqual(["allow-once", "reject-once", "reject-always"]);
+ expect(filtered(EDIT_OPTIONS)).toEqual(["allow-edits-session", "allow-once", "reject-once"]);
+ expect(filtered([{ optionId: "enable-always-approve", kind: "allow_always" }, { optionId: "allow-once", kind: "allow_once" }])).toEqual(["allow-once"]);
+ const question = { toolCall: { toolCallId: "interaction_1" }, options: [{ optionId: "a", kind: "allow_always", name: "A" }] };
+ expect(grokPermissionRequest(question)).toBe(question);
+ });
+
+ it.each([
+ ["a bash command", BASH_OPTIONS, { kind: "execute", rawInput: { command: "echo hi" }, title: "echo hi" }, "allow-once"],
+ ["an edit", EDIT_OPTIONS, { kind: "edit", title: "Edit notes.md", rawInput: { path: "notes.md" } }, "allow-edits-session"],
+ ])("answers %s with the session-scoped choice, never a saved grant", async (_, options, toolCall, expected) => {
+ const { instance, recorder, files } = await start(`grok-allow-${expected}`, {
+ FAKE_ACP_MODE: "permission", FAKE_ACP_PERMISSION_OPTIONS: JSON.stringify(options), FAKE_ACP_PERMISSION_TOOL_CALL: JSON.stringify(toolCall),
+ });
+ const threadId = `t-grok-allow-${expected}`;
+ try {
+ const { turnId } = await instance.adapter.sendTurn({ threadId, text: "go", approvalMode: "ask" });
+ const opened = await recorder.until((event) => event.type === "request.opened");
+ expect(opened).toHaveProperty("allowSession", true);
+ await instance.adapter.respondToRequest(threadId, (opened as { requestId: string }).requestId, { behavior: "allow", always: true });
+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);
+ expect(readFileSync(files.answer, "utf8")).toBe(expected);
+ } finally {
+ recorder.stop();
+ await instance.dispose();
+ }
+ });
+});
diff --git a/server/drivers/acp/grok-sign-in.test.ts b/server/drivers/acp/grok-sign-in.test.ts
new file mode 100644
index 0000000000..c2eeb04b95
--- /dev/null
+++ b/server/drivers/acp/grok-sign-in.test.ts
@@ -0,0 +1,116 @@
+// The Grok engine's sign-in status against a fake `grok models`, never a real login.
+import { chmodSync, 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 { GrokAgentDriver } from "./grok.ts";
+import { grokLoginCheck, readGrokModelsLogin } from "./grok-sign-in.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 home = (login: string, withAuth = true) => {
+ chmodSync(FAKE_CLI, 0o755);
+ const scratch = mkdtempSync(join(tmpdir(), "omb-grok-sign-in-"));
+ scratches.push(scratch);
+ mkdirSync(join(scratch, "grok"), { recursive: true });
+ const authFile = join(scratch, "grok", "auth.json");
+ if (withAuth) writeFileSync(authFile, "{}");
+ const count = join(scratch, "models-calls");
+ const env = { ...process.env, GROK_HOME: join(scratch, "grok"), FAKE_ACP_GROK_LOGIN: login, FAKE_ACP_GROK_LOGIN_COUNT: count };
+ const calls = () => existsSync(count) ? Number(readFileSync(count, "utf8")) : 0;
+ return { env, authFile, calls };
+};
+
+describe("reading `grok models`", () => {
+ it.each([
+ ["You are logged in with grok.com.\nDefault model: grok-4.5", "signed-in"],
+ ["You are using XAI_API_KEY.\nAvailable models:", "signed-in"],
+ ["You are authenticated via deployment key.", "signed-in"],
+ ["You are not authenticated.\nDefault model: grok-4.5", "signed-out"],
+ ["Not logged in. Run `grok login`.", "signed-out"],
+ ["Your auth token is invalid or expired. Run `grok login` to re-authenticate.", "signed-out"],
+ ["Token expired. Run `grok login` to re-authenticate.", "signed-out"],
+ ["Available models:\n - grok-4.5 (default)", "unknown"],
+ ["", "unknown"],
+ ])("%j is %s", (output, login) => {
+ expect(readGrokModelsLogin(output)).toBe(login);
+ });
+});
+
+describe("the Grok sign-in check", () => {
+ it("is signed in when Grok says so, asking once", async () => {
+ const { env, authFile, calls } = home("signed-in");
+ expect(await grokLoginCheck()(FAKE_CLI, env, authFile)).toBe(true);
+ expect(calls()).toBe(1);
+ });
+
+ it("is signed out only when Grok says so twice", async () => {
+ const { env, authFile, calls } = home("signed-out");
+ expect(await grokLoginCheck()(FAKE_CLI, env, authFile)).toBe(false);
+ expect(calls()).toBe(2);
+ });
+
+ it("is signed in when the first call refreshed an expired token", async () => {
+ const { env, authFile, calls } = home("refreshes");
+ expect(await grokLoginCheck()(FAKE_CLI, env, authFile)).toBe(true);
+ expect(calls()).toBe(2);
+ });
+
+ it("keeps the file's answer when Grok does not answer in time", async () => {
+ const { env, authFile } = home("hang");
+ const startedAt = Date.now();
+ expect(await grokLoginCheck({ timeoutMs: 1_500 })(FAKE_CLI, env, authFile)).toBe(true);
+ expect(Date.now() - startedAt).toBeLessThan(15_000);
+ });
+
+ it("is signed out without auth.json, and never asks", async () => {
+ const { env, authFile, calls } = home("signed-in", false);
+ expect(await grokLoginCheck()(FAKE_CLI, env, authFile)).toBe(false);
+ expect(calls()).toBe(0);
+ });
+
+ it("asks again only once auth.json changes", async () => {
+ const { env, authFile, calls } = home("signed-in");
+ const check = grokLoginCheck();
+ expect(await check(FAKE_CLI, env, authFile)).toBe(true);
+ expect(await check(FAKE_CLI, env, authFile)).toBe(true);
+ expect(calls()).toBe(1);
+ writeFileSync(authFile, '{"signed":"again"}');
+ env.FAKE_ACP_GROK_LOGIN = "signed-out";
+ expect(await check(FAKE_CLI, env, authFile)).toBe(false);
+ expect(calls()).toBe(3);
+ });
+
+ it("answers an old check at once and asks again behind it", async () => {
+ const { env, authFile, calls } = home("signed-in");
+ const check = grokLoginCheck({ freshMs: 0 });
+ expect(await check(FAKE_CLI, env, authFile)).toBe(true);
+ env.FAKE_ACP_GROK_LOGIN = "signed-out";
+ expect(await check(FAKE_CLI, env, authFile)).toBe(true);
+ expect(await check(FAKE_CLI, env, authFile)).toBe(false);
+ expect(calls()).toBeGreaterThanOrEqual(3);
+ });
+
+ it("reports an expired login as signed out in the engine's status", async () => {
+ ensureDirs();
+ const { env } = home("signed-out");
+ const instance = await GrokAgentDriver.create({
+ instanceId: "grok-sign-in-status", displayName: "Grok", enabled: true,
+ environment: { GROK_HOME: env.GROK_HOME!, FAKE_ACP_GROK_LOGIN: "signed-out" },
+ config: { cli: FAKE_CLI, fullAuto: true },
+ } as never) as ProviderInstance;
+ try {
+ expect(await instance.snapshot()).toMatchObject({ state: "available", authenticated: false });
+ } finally {
+ await instance.dispose();
+ }
+ });
+});
diff --git a/server/drivers/acp/grok-sign-in.ts b/server/drivers/acp/grok-sign-in.ts
new file mode 100644
index 0000000000..4461a04754
--- /dev/null
+++ b/server/drivers/acp/grok-sign-in.ts
@@ -0,0 +1,63 @@
+// Whether Grok's own login still works, beyond auth.json being there: an expired or revoked login keeps the file. Only
+// `grok models` is asked, and auth.json is only stat'ed, never read.
+import { statSync } from "node:fs";
+
+import { execCli } from "../../procs.ts";
+
+export type GrokLogin = "signed-in" | "signed-out" | "unknown";
+interface Probe { stamp: string; at: number; login: Promise<GrokLogin>; settled?: GrokLogin }
+
+/** grok 1.0.25 `grok models` prints "You are logged in with …", "You are using XAI_API_KEY.", "You are authenticated via
+ * deployment key." or "You are not authenticated.", and exits 0 either way; its errors say "Not logged in. Run `grok login`.",
+ * "Token expired. …" or "Your auth token is invalid or expired. …". */
+export function readGrokModelsLogin(output: string): GrokLogin {
+ if (/^You are (?:logged in|using XAI_API_KEY|authenticated via)\b/im.test(output)) return "signed-in";
+ if (/^You are not authenticated\b|\bnot logged in\b|\btoken (?:is invalid or )?expired\b/im.test(output)) return "signed-out";
+ return "unknown";
+}
+
+function askGrokModels(cli: string, env: Record<string, string | undefined>, timeoutMs: number): Promise<GrokLogin> {
+ return new Promise((resolve) => execCli(cli, ["models"], { timeout: timeoutMs, env }, (error, stdout, stderr) => {
+ resolve((error as { killed?: boolean } | null)?.killed ? "unknown" : readGrokModelsLogin(`${stdout}\n${stderr ?? ""}`));
+ }));
+}
+
+/** An access token past its time makes `grok models` say it is not authenticated and then refresh the token in that same
+ * process, so only a second "not authenticated" counts as signed out. */
+async function probeGrokLogin(cli: string, env: Record<string, string | undefined>, timeoutMs: number): Promise<GrokLogin> {
+ const first = await askGrokModels(cli, env, timeoutMs);
+ return first === "signed-out" ? askGrokModels(cli, env, timeoutMs) : first;
+}
+
+/** False for a missing auth.json, or one `grok models` twice calls signed out; a probe that times out, fails or says
+ * something else keeps the file's answer. A probe is reused while auth.json is unchanged and younger than `freshMs`; an
+ * older one answers at once while a new probe runs, so only an engine's first status read, or one after sign-in or
+ * sign-out, waits for `grok models`. */
+export function grokLoginCheck(options: { timeoutMs?: number; freshMs?: number } = {}) {
+ const timeoutMs = options.timeoutMs ?? 8_000;
+ const freshMs = options.freshMs ?? 5 * 60_000;
+ const probes = new Map<string, Probe>();
+ return async (cli: string, env: Record<string, string | undefined>, authFile: string): Promise<boolean> => {
+ let stamp: string;
+ try {
+ const info = statSync(authFile);
+ stamp = `${info.mtimeMs}:${info.size}`;
+ } catch {
+ return false;
+ }
+ const key = JSON.stringify([cli, authFile]);
+ const known = probes.get(key);
+ const probe = () => {
+ const next: Probe = { stamp, at: Date.now(), login: probeGrokLogin(cli, env, timeoutMs) };
+ void next.login.then((login) => { next.settled = login; });
+ probes.set(key, next);
+ return next;
+ };
+ if (!known || known.stamp !== stamp) return (await probe().login) !== "signed-out";
+ if (Date.now() - known.at >= freshMs && known.settled !== undefined) {
+ probe();
+ return known.settled !== "signed-out";
+ }
+ return (await known.login) !== "signed-out";
+ };
+}
diff --git a/server/drivers/acp/grok.ts b/server/drivers/acp/grok.ts
index 38a6505807..8827853c05 100644
--- a/server/drivers/acp/grok.ts
+++ b/server/drivers/acp/grok.ts
@@ -5,11 +5,13 @@ import { dirname, join, resolve } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { parse as parseYaml } from "yaml";
-import type { ModelCatalog } from "../../contracts.ts";
+import type { ModelCatalog, SendTurnInput } from "../../contracts.ts";
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 { LiveSwitchRefused } from "./driver-hooks.ts";
+import { grokLoginCheck } from "./grok-sign-in.ts";
import { closeEndsBackgroundWork } from "./background-work.ts";
import { readGrokFollowUp } from "./grok-follow-up.ts";
import type { AcpPromptSteer } from "./steer.ts";
@@ -34,6 +36,12 @@ export function grokSignedIn(env: Record<string, string | undefined>): boolean {
return existsSync(join(grokHome(env), "auth.json"));
}
+const grokLogin = grokLoginCheck();
+/** The engine's status: an auth.json whose login `grok models` reports gone (expired, revoked) is signed out too. */
+export function grokAuthenticated(cli: string, env: Record<string, string | undefined>): Promise<boolean> {
+ return grokLogin(cli, env, join(grokHome(env), "auth.json"));
+}
+
/** The sign-out probe: an auth.json that cannot be read is `unknown`, so sign-out refuses instead of reporting a
* removal that never happened. `grokSignedIn` keeps its boolean contract for turn gating. */
export function grokSignInState(env: Record<string, string | undefined>): DeviceSignInState {
@@ -57,8 +65,8 @@ function grokLoginFailure(output: string): string {
return "Grok sign-in did not finish. Check the server's connection, then try again.";
}
-/** `grok login --device-auth` / `grok logout` on the grok.com subscription (grok 1.0.25 and 1.0.41). Grok has no
- * status command, so the stored auth.json is the sign-in check. */
+/** `grok login --device-auth` / `grok logout` on the grok.com subscription (grok 1.0.25 and 1.0.41). The stored auth.json
+ * confirms them: `grok models` also reports the login, but takes seconds, and only the engine's status waits for it. */
export const GROK_DEVICE_SIGN_IN: DeviceSignIn = {
provider: "grok",
product: "Grok",
@@ -425,6 +433,54 @@ export const GROK_ASK_USER_QUESTION: AcpQuestionRequest = {
},
};
+/** The process contract leaves out the model and effort that configureSession changes in a live session, keeping only
+ * whether each is set. A narrowed tool profile carries the model, so there a change still starts a new process. */
+function grokContractArgs(args: string[], turn: SendTurnInput): string[] {
+ if (narrowsNativeTools(turn.toolScope)) return args;
+ return args.map((arg, index) => index > 0 && (args[index - 1] === "-m" || args[index - 1] === "--reasoning-effort") ? "set" : arg);
+}
+
+/** grok 1.0.x can leave session/load unanswered once it has replayed the history, which it streams from its own session
+ * files with no pause between updates: two seconds without one means the replay is over. */
+const GROK_LOAD_REPLAY_QUIET_MS = 2_000;
+
+/** grok 1.0.41 reports effort as the `reasoning_effort` select (category `thought_level`) of session/new's and
+ * session/load's configOptions, and session/set_config_option answers with the whole updated list. A load that went
+ * quiet reported no options, so the documented id is tried. */
+async function setGrokEffort(
+ request: (method: string, params: unknown) => Promise<any>,
+ sessionId: string,
+ effort: string,
+ configOptions: ReadonlyArray<{ id?: unknown; category?: unknown }>,
+): Promise<void> {
+ const offered = configOptions.find((entry) => entry.id === "reasoning_effort" || entry.category === "thought_level")?.id;
+ const configId = typeof offered === "string" ? offered : "reasoning_effort";
+ let reply: { configOptions?: Array<{ id?: unknown; currentValue?: unknown }> } | undefined;
+ try {
+ reply = await request("session/set_config_option", { sessionId, configId, value: effort });
+ } catch (e) {
+ throw new LiveSwitchRefused(`Grok rejected effort "${effort}": ${(e as Error).message}`);
+ }
+ if (reply?.configOptions?.find((entry) => entry.id === configId)?.currentValue !== effort) {
+ throw new LiveSwitchRefused(`Grok did not switch to effort "${effort}".`);
+ }
+}
+
+/** Only `allow-edits-session` of grok's `allow_always` options ends with the session; the others save a grant beyond it:
+ * `always-allow` stops asking about bash commands in the project (1.0.41), and the 1.0.25 binary also names
+ * `allow-always-command`, `allow-always-mcp`, `allow-always-domain` and `enable-always-approve` (every request). Without
+ * the session option, "this session" allows once and the driver remembers the exact operation. A question's options are
+ * its answers and stay as offered. */
+const GROK_SESSION_ALLOW = "allow-edits-session";
+export function grokPermissionRequest(params: Record<string, any>): Record<string, any> {
+ if (String(params.toolCall?.toolCallId ?? "").startsWith("interaction_") || !Array.isArray(params.options)) return params;
+ return {
+ ...params,
+ options: params.options.filter((option: { optionId?: unknown; kind?: unknown }) =>
+ option?.kind !== "allow_always" || option.optionId === GROK_SESSION_ALLOW),
+ };
+}
+
const support: AcpSupport = {
driverKind: "grokAgent",
questionRequests: {
@@ -474,6 +530,9 @@ const support: AcpSupport = {
...(turn.effort ? ["--reasoning-effort", turn.effort] : []),
"stdio",
],
+ spawnContractArgs: (config, turn) => grokContractArgs(support.spawnArgs(config, turn), turn),
+ loadReplayQuietMs: (turn) => narrowsNativeTools(turn.toolScope) ? undefined : GROK_LOAD_REPLAY_QUIET_MS,
+ permissionRequest: grokPermissionRequest,
toolScopeSessionParams: (turn, init, hasMcp, { config, env, cwd }) => {
if (!narrowsNativeTools(turn.toolScope)) return {};
@@ -485,7 +544,7 @@ const support: AcpSupport = {
toolScopeCacheKey: ({ config, env, cwd }) => JSON.stringify(grokInheritedProfile(config.cli, env, cwd) ?? null),
// -m on argv is not enough: session/new still starts on [models].default.
- async configureSession({ request, sessionId, turn, currentModelId }) {
+ async configureSession({ request, sessionId, turn, currentModelId, currentEffort, effortApplied, configOptions }) {
if (turn.toolScope !== undefined) {
const available = new Set([
...(turn.integrations?.agents ? ["agents"] : []), ...(turn.integrations?.composio ? ["composio"] : []), ...(turn.integrations?.composioOwn ? [OWN_APPS_SERVER] : []),
@@ -517,17 +576,22 @@ const support: AcpSupport = {
}
}
// Repeating set_model can rebuild the harness, dropping its MCP catalog, or reject a valid resumed profile.
- if (!turn.model || currentModelId === turn.model) return;
- if (narrowsNativeTools(turn.toolScope)) {
- throw new Error("Grok could not confirm the selected model without replacing its tool profile. Start a new conversation or choose a model with a supported Grok profile. No prompt was sent.");
+ if (turn.model && currentModelId !== turn.model) {
+ if (narrowsNativeTools(turn.toolScope)) {
+ throw new Error("Grok could not confirm the selected model without replacing its tool profile. Start a new conversation or choose a model with a supported Grok profile. No prompt was sent.");
+ }
+ try {
+ await request("session/set_model", { sessionId, modelId: turn.model });
+ } catch (e) {
+ throw new LiveSwitchRefused(
+ `Grok rejected model "${turn.model}" via session/set_model: ${(e as Error).message}. ` +
+ `Check that grok is current (1.0.6+ supports it) and that this slug exists in ~/.grok/config.toml.`,
+ );
+ }
}
- try {
- await request("session/set_model", { sessionId, modelId: turn.model });
- } catch (e) {
- throw new Error(
- `Grok rejected model "${turn.model}" via session/set_model: ${(e as Error).message}. ` +
- `Check that grok is current (1.0.6+ supports it) and that this slug exists in ~/.grok/config.toml.`,
- );
+ if (effortApplied && turn.effort !== undefined && turn.effort !== currentEffort) {
+ await setGrokEffort(request, sessionId, turn.effort, configOptions);
+ effortApplied(turn.effort);
}
},
@@ -553,7 +617,7 @@ const support: AcpSupport = {
pickAuthMethod: (methods) => ["cached_token", "grok.com"].find((id) => methods.some((m) => m.id === id)) ?? null,
authFailure: "fail",
- isAuthenticated: (env) => grokSignedIn(env),
+ isAuthenticated: (env, config) => grokAuthenticated(config.cli, env),
// `--append-system-prompt`/`--rules` do not reach the agent-stdio system prompt (1.0.0).
buildPromptText: (turn) => (turn.system ? `${turn.system}\n\n${turn.text}` : turn.text),
diff --git a/server/drivers/acp/host.ts b/server/drivers/acp/host.ts
index 730a67bdb7..4f2cd0bfbe 100644
--- a/server/drivers/acp/host.ts
+++ b/server/drivers/acp/host.ts
@@ -64,6 +64,8 @@ export interface AcpHostOptions {
export class AcpLink implements AcpConnection {
sessionId: string | null = null;
inbound: AcpInbound | null = null;
+ /** Hears every `session/update` routed to this link, replayed history included, before the thread reads it. */
+ onUpdate: ((params: any) => void) | null = null;
closed = false;
#lastInboundAt = Date.now();
readonly host: AcpHost;
@@ -306,6 +308,7 @@ export class AcpHost {
if (link?.inbound && !link.closed) link.inbound.request(msg);
else this.options.unrouted(msg, (obj) => this.write(obj, link?.threadId ?? null));
} else if (msg.method && link && !link.closed) {
+ if (msg.method === "session/update") link.onUpdate?.(msg.params);
link.inbound?.notification(msg);
}
}
diff --git a/server/drivers/acp/load-replay.test.ts b/server/drivers/acp/load-replay.test.ts
new file mode 100644
index 0000000000..f754f3dcb7
--- /dev/null
+++ b/server/drivers/acp/load-replay.test.ts
@@ -0,0 +1,81 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { loadUntilReplayQuiet } from "./load-replay.ts";
+
+const QUIET_MS = 2_000;
+
+function scripted(quietMs: number | undefined) {
+ const link: { onUpdate: ((params: any) => void) | null } = { onUpdate: null };
+ const received: unknown[] = [];
+ let answer!: (result: unknown) => void;
+ let fail!: (error: Error) => void;
+ let deliver!: (result: unknown) => void;
+ const done = loadUntilReplayQuiet({
+ link, sessionId: "s1", quietMs,
+ send: (receive) => new Promise((resolve, reject) => {
+ deliver = receive;
+ answer = (result) => { receive(result); resolve(result); };
+ fail = reject;
+ }),
+ receive: (result) => received.push(result),
+ replayed: () => ({ kept: true }),
+ });
+ let state = "pending";
+ done.then(() => { state = "loaded"; }, (error: Error) => { state = `failed: ${error.message}`; });
+ const replay = (sessionId = "s1") => link.onUpdate?.({ sessionId, update: { sessionUpdate: "agent_message_chunk" } });
+ return { link, received, done, state: () => state, answer: (result: unknown) => answer(result), fail: (error: Error) => fail(error), late: (result: unknown) => deliver(result), replay };
+}
+
+describe("a session/load that can go unanswered after its replay", () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it("counts as loaded once the replay has been quiet for the window, and drops a late answer", async () => {
+ const load = scripted(QUIET_MS);
+ load.replay();
+ await vi.advanceTimersByTimeAsync(QUIET_MS - 1);
+ load.replay();
+ await vi.advanceTimersByTimeAsync(QUIET_MS - 1);
+ expect(load.state()).toBe("pending");
+ await vi.advanceTimersByTimeAsync(1);
+ expect(load.state()).toBe("loaded");
+ expect(load.received).toEqual([{ kept: true }]);
+ expect(load.link.onUpdate).toBeNull();
+ load.late({ models: { currentModelId: "stale" } });
+ load.fail(new Error("session/load timed out"));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(load.received).toEqual([{ kept: true }]);
+ expect(load.state()).toBe("loaded");
+ });
+
+ it("takes the answer when it comes first", async () => {
+ const load = scripted(QUIET_MS);
+ load.replay();
+ load.answer({ models: { currentModelId: "grok-4.5" } });
+ await vi.advanceTimersByTimeAsync(QUIET_MS * 2);
+ expect(load.state()).toBe("loaded");
+ expect(load.received).toEqual([{ models: { currentModelId: "grok-4.5" } }]);
+ });
+
+ it("waits for the answer, or its timeout, when nothing of the session is replayed", async () => {
+ const load = scripted(QUIET_MS);
+ load.replay("another-session");
+ await vi.advanceTimersByTimeAsync(QUIET_MS * 10);
+ expect(load.state()).toBe("pending");
+ load.fail(new Error("session/load timed out"));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(load.state()).toBe("failed: session/load timed out");
+ expect(load.received).toEqual([]);
+ });
+
+ it("only waits for the answer without a quiet window", async () => {
+ const load = scripted(undefined);
+ expect(load.link.onUpdate).toBeNull();
+ await vi.advanceTimersByTimeAsync(QUIET_MS * 10);
+ expect(load.state()).toBe("pending");
+ load.answer(null);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(load.state()).toBe("loaded");
+ expect(load.received).toEqual([null]);
+ });
+});
diff --git a/server/drivers/acp/load-replay.ts b/server/drivers/acp/load-replay.ts
new file mode 100644
index 0000000000..a4f4dfe869
--- /dev/null
+++ b/server/drivers/acp/load-replay.ts
@@ -0,0 +1,38 @@
+import type { AcpLink } from "./host.ts";
+
+/** Sends a session/load and settles with its answer or, given `quietMs`, once the agent has replayed updates of
+ * `sessionId` and then sent none for that long, for an agent that can leave the load unanswered after its replay. A load
+ * that replays nothing waits for its answer, up to the request's own timeout. `receive` hears the answer, or `replayed()`
+ * when the replay went quiet first; a later answer or failure is dropped. */
+export function loadUntilReplayQuiet(load: {
+ link: Pick<AcpLink, "onUpdate">;
+ sessionId: string;
+ quietMs: number | undefined;
+ send: (receive: (result: any) => void) => Promise<unknown>;
+ receive: (result: any) => void;
+ replayed: () => any;
+}): Promise<void> {
+ return new Promise<void>((resolve, reject) => {
+ let settled = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const finish = () => {
+ settled = true;
+ clearTimeout(timer);
+ if (load.link.onUpdate === heard) load.link.onUpdate = null;
+ };
+ const heard = (params: any) => {
+ if (settled || params?.sessionId !== load.sessionId) return;
+ clearTimeout(timer);
+ timer = setTimeout(() => {
+ finish();
+ load.receive(load.replayed());
+ resolve();
+ }, load.quietMs);
+ };
+ if (load.quietMs) load.link.onUpdate = heard;
+ load.send((result) => { if (!settled) load.receive(result); }).then(
+ () => { if (!settled) { finish(); resolve(); } },
+ (error) => { if (!settled) { finish(); reject(error); } },
+ );
+ });
+}
diff --git a/server/drivers/acp/turn-state.ts b/server/drivers/acp/turn-state.ts
index 320949af59..04ccb25a86 100644
--- a/server/drivers/acp/turn-state.ts
+++ b/server/drivers/acp/turn-state.ts
@@ -73,6 +73,8 @@ export interface AcpSession {
commands?: ReadonlySet<string>;
fallbackNotice?: string;
launchModel?: string;
+ /** The effort the session runs: its process's launch argv's, or the last one configureSession applied. */
+ effort?: SendTurnInput["effort"];
}
/** A `tool_call` without a status is pending (ACP's default); a `tool_call_update` without one leaves the call as it was. */
diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.ts
index ea6285a25c..0012033b95 100755
--- a/server/testing/fake-acp-cli.ts
+++ b/server/testing/fake-acp-cli.ts
@@ -50,6 +50,13 @@
// FAKE_ACP_RPC_FAILURE_AFTER_OUTPUT emit text and a tool result before failing
// FAKE_ACP_RPC_FAILURE_AFTER_USAGE emit the scripted usage updates and FAKE_ACP_UPDATES_FILE's before failing
// FAKE_ACP_LOAD_ERROR JSON-RPC error returned by session/load
+// FAKE_ACP_LOAD_REPLAY session/load first replays this many history updates of the session (REPLAYED-USER-<n>,
+// REPLAYED-AGENT-<n>), marked _meta.isReplay with FAKE_ACP_LOAD_REPLAY_MARKED=1; FAKE_ACP_LOAD_UNANSWERED=1 then leaves
+// the load unanswered, as grok 1.0.x can
+// FAKE_ACP_GROK_EFFORT=1 sessions report grok 1.0.41's `reasoning_effort` select (starting on --reasoning-effort, else
+// high) and session/set_config_option changes it; =refuse answers that set with -32602
+// FAKE_ACP_GROK_LOGIN what `models` says of the login, as grok 1.0.25 prints it: signed-in | signed-out | refreshes (signed
+// out once, then signed in, as a token refreshed by the first call) | hang; FAKE_ACP_GROK_LOGIN_COUNT counts the calls
// FAKE_ACP_MODELS model ids: opencode-shaped configOptions and set_config_option (-32602 for others);
// a new session starts on AGY_ACP_DEFAULT_MODEL when set, taken unchecked as agy_acp_server 1.1.1 does
// FAKE_ACP_MODELS_FILE the same list, read once at startup, as `opencode acp` never re-reads a login
@@ -196,6 +203,8 @@ const variantValues = (entries: any[]): string[] => entries.flatMap((entry) => (
const modes = (process.env.FAKE_ACP_MODES ?? "").split(",").filter(Boolean);
let currentMode: string | null = modes[0] ?? null;
let currentFast: string | null = null;
+const grokEffort = process.env.FAKE_ACP_GROK_EFFORT;
+let currentEffort = process.argv.includes("--reasoning-effort") ? process.argv[process.argv.indexOf("--reasoning-effort") + 1]! : "high";
const taskIdFile = process.env.FAKE_ACP_TASKID_FILE ?? "";
const peerIdOf = (list: string): string => /id: ([\w-]+)/.exec(list)?.[1] ?? "";
function handoffCall(message: string, options: { consult?: boolean; reason?: string; doneWhen?: string } = {}): { name: string; args: (list: string) => object } {
@@ -263,6 +272,14 @@ const configOptions = () => {
currentValue: currentMode,
options: modes.map((value) => ({ value, name: value })),
}] : []),
+ ...(grokEffort ? [{
+ id: "reasoning_effort",
+ name: "Reasoning Effort",
+ category: "thought_level",
+ type: "select",
+ currentValue: currentEffort,
+ options: ["high", "medium", "low"].map((value) => ({ value, name: value })),
+ }] : []),
...(currentFast ? [{
id: "fast",
name: "Fast",
@@ -393,6 +410,19 @@ if (argv[0] === "status" || argv[0] === "whoami") {
console.log(JSON.stringify({ isAuthenticated: authenticated }));
process.exit(0);
}
+const grokLogin = process.env.FAKE_ACP_GROK_LOGIN;
+if (argv[0] === "models" && grokLogin) {
+ const countFile = process.env.FAKE_ACP_GROK_LOGIN_COUNT;
+ const calls = countFile && existsSync(countFile) ? Number(readFileSync(countFile, "utf8")) || 0 : 0;
+ if (countFile) writeFileSync(countFile, String(calls + 1));
+ if (grokLogin === "hang") setInterval(() => {}, 1_000);
+ else {
+ const signedIn = grokLogin === "signed-in" || (grokLogin === "refreshes" && calls > 0);
+ console.log([signedIn ? "You are logged in with grok.com." : "You are not authenticated.",
+ "Default model: grok-4.5", "Available models:", " - grok-4.5 (default)"].join("\n"));
+ process.exit(0);
+ }
+}
const catalogLock = process.env.FAKE_ACP_MODELS_LOCK;
if (catalogLock && (argv[0] === "models" || argv[0] === "acp") && !argv.includes("--refresh") && process.env.OPENCODE_DISABLE_MODELS_FETCH !== "1") {
writeFileSync(catalogLock, String(process.pid));
@@ -1057,6 +1087,15 @@ function handle(msg: any) {
detachedSessions.delete(String(msg.params?.sessionId));
const copies = openCopies.get(String(msg.params?.sessionId)) ?? 0;
openCopies.set(String(msg.params?.sessionId), process.env.FAKE_ACP_COPY_LIVE_LOAD === "1" ? copies + 1 : 1);
+ for (let turn = 1; turn <= Number(process.env.FAKE_ACP_LOAD_REPLAY ?? 0); turn++) {
+ for (const [sessionUpdate, text] of [["user_message_chunk", `REPLAYED-USER-${turn}`], ["agent_message_chunk", `REPLAYED-AGENT-${turn}`]]) {
+ out({ jsonrpc: "2.0", method: "session/update", params: {
+ sessionId: msg.params.sessionId, ...(process.env.FAKE_ACP_LOAD_REPLAY_MARKED === "1" ? { _meta: { isReplay: true } } : {}),
+ update: { sessionUpdate, content: { type: "text", text } },
+ } });
+ }
+ }
+ if (process.env.FAKE_ACP_LOAD_UNANSWERED === "1") break;
resultAndConfigUpdates(msg.id, { ...(opts ? { configOptions: opts } : {}), ...(mdls ? { models: mdls } : {}) }, "session/load", msg.params.sessionId);
if (mode === "hermes-steer") advertiseHermesCommands(msg.params.sessionId);
break;
@@ -1118,6 +1157,19 @@ function handle(msg: any) {
resultAndConfigUpdates(msg.id, process.env.FAKE_ACP_EMPTY_VARIANT_ACK ? {} : { configOptions: configOptions() }, "effort", msg.params.sessionId);
break;
}
+ if (configId === "reasoning_effort" && grokEffort && ["high", "medium", "low"].includes(value)) {
+ if (grokEffort === "refuse") {
+ out({ jsonrpc: "2.0", id: msg.id, error: { code: -32602, message: "Invalid params: reasoning_effort" } });
+ break;
+ }
+ currentEffort = value;
+ configCalls.push({ method: msg.method, params: msg.params });
+ if (process.env.FAKE_ACP_DUMP) {
+ writeFileSync(`${process.env.FAKE_ACP_DUMP}.config.json`, JSON.stringify(configCalls, null, 2));
+ }
+ result(msg.id, { configOptions: configOptions() });
+ break;
+ }
if (configId === "fast" && currentFast && (value === "true" || value === "false")) {
if (process.env.FAKE_ACP_CURSOR_FAST !== "stuck") currentFast = value;
configCalls.push({ method: msg.method, params: msg.params });