Skip to content

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

fix(acp): pass configured model on Grok one-shot calls

jonathanwxh-cell838a48a7b0c5
diff --git a/server/drivers/acp/background-text.test.ts b/server/drivers/acp/background-text.test.ts
index 68d708ed08..cc14c463a1 100644
--- a/server/drivers/acp/background-text.test.ts
+++ b/server/drivers/acp/background-text.test.ts
@@ -16,7 +16,7 @@ import { GrokAgentDriver } from "./grok.ts";
import { QwenAgentDriver } from "./qwen.ts";
const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "testing", "fake-acp-cli.ts");
-const ENV_KEYS = ["FAKE_ACP_MODE", "FAKE_ACP_DUMP", "FAKE_ACP_TEXT_REPLY", "FAKE_ACP_MODELS", "FAKE_ACP_MODEL_STICKS"];
+const ENV_KEYS = ["FAKE_ACP_MODE", "FAKE_ACP_DUMP", "FAKE_ACP_TEXT_REPLY", "FAKE_ACP_MODELS", "FAKE_ACP_SESSION_MODELS", "FAKE_ACP_MODEL_STICKS"];
describe("ACP memory one-shot (generateMemoryText)", () => {
let instance: ProviderInstance | undefined;
@@ -133,8 +133,6 @@ describe("ACP memory one-shot (generateMemoryText)", () => {
pickAuthMethod: () => null, authFailure: "continue", isAuthenticated: () => true, selectModel: { configId: "model" },
};
const promptedModels = () => readFileSync(`${process.env.FAKE_ACP_DUMP}.prompts.jsonl`, "utf8").trim().split("\n").map((line) => JSON.parse(line).model);
- const botModel = (model: string) => ({ model, refused: new Set<string>(), onRefused: () => {} });
-
beforeEach(() => {
process.env.FAKE_ACP_TEXT_REPLY = "[]";
process.env.FAKE_ACP_MODELS = "m-default,m-bot";
@@ -143,30 +141,106 @@ describe("ACP memory one-shot (generateMemoryText)", () => {
it("runs on the bot's own model, not the session's default, and books it there", async () => {
const usage: TextGenerationUsage[] = [];
- await (await create(createAcpDriver(support))).generateMemoryText!("prompt", { fallback: botModel("m-bot"), onUsage: (row) => usage.push(row) });
+ await (await create(createAcpDriver(support))).generateMemoryText!("prompt", { fallback: { model: "m-bot", refused: new Set<string>(), onRefused: () => {} }, onUsage: (row) => usage.push(row) });
expect(promptedModels()).toEqual(["m-bot"]);
expect(usage).toEqual([expect.objectContaining({ model: "m-bot" })]);
});
it("keeps the session's default when the session does not offer the bot's model", async () => {
- await (await create(createAcpDriver(support))).generateMemoryText!("prompt", { fallback: botModel("m-gone") });
+ await (await create(createAcpDriver(support))).generateMemoryText!("prompt", { fallback: { model: "m-gone", refused: new Set<string>(), onRefused: () => {} } });
expect(promptedModels()).toEqual(["m-default"]);
});
it("stops before the prompt when the session stays on another model after the switch", async () => {
process.env.FAKE_ACP_MODEL_STICKS = "1";
const engine = await create(createAcpDriver(support));
- await expect(engine.generateMemoryText!("prompt", { fallback: botModel("m-bot") })).rejects.toThrow("did not switch to m-bot (still m-default)");
+ await expect(engine.generateMemoryText!("prompt", { fallback: { model: "m-bot", refused: new Set<string>(), onRefused: () => {} } })).rejects.toThrow("did not switch to m-bot (still m-default)");
expect(existsSync(`${process.env.FAKE_ACP_DUMP}.prompts.jsonl`)).toBe(false);
});
it("keeps the session's default when the engine can no longer route the bot's model", async () => {
const resolveTurnModel = () => { throw new Error("model is no longer configured"); };
- await (await create(createAcpDriver({ ...support, resolveTurnModel }))).generateMemoryText!("prompt", { fallback: botModel("m-bot") });
+ await (await create(createAcpDriver({ ...support, resolveTurnModel }))).generateMemoryText!("prompt", { fallback: { model: "m-bot", refused: new Set<string>(), onRefused: () => {} } });
expect(promptedModels()).toEqual(["m-default"]);
});
});
+ describe("on Grok (slug via -m and session/set_model)", () => {
+ const botModel = (model: string) => ({ model, refused: new Set<string>(), onRefused: () => {} });
+
+ beforeEach(() => {
+ process.env.FAKE_ACP_TEXT_REPLY = "[]";
+ process.env.FAKE_ACP_DUMP = join(scratch, "dump.json");
+ process.env.FAKE_ACP_SESSION_MODELS = "grok-4.7,omni-combo-fast,explicit-combo";
+ });
+
+ it("carries the bot's configured model via -m and session/set_model and books usage to it", async () => {
+ const usage: TextGenerationUsage[] = [];
+ await (await create(GrokAgentDriver)).generateMemoryText!("prompt", { fallback: botModel("omni-combo-fast"), onUsage: (row) => usage.push(row) });
+ const { argv } = JSON.parse(readFileSync(process.env.FAKE_ACP_DUMP!, "utf8"));
+ expect(argv).toContain("-m");
+ expect(argv[argv.indexOf("-m") + 1]).toBe("omni-combo-fast");
+ const configCalls = JSON.parse(readFileSync(`${process.env.FAKE_ACP_DUMP}.config.json`, "utf8"));
+ expect(configCalls).toContainEqual(expect.objectContaining({ method: "session/set_model", params: expect.objectContaining({ modelId: "omni-combo-fast" }) }));
+ expect(usage).toEqual([expect.objectContaining({ model: "omni-combo-fast" })]);
+ });
+
+ it("skips session/set_model when session/new already starts on the requested model", async () => {
+ process.env.FAKE_ACP_SESSION_MODELS = "omni-combo-fast,grok-4.7";
+ const usage: TextGenerationUsage[] = [];
+ await (await create(GrokAgentDriver)).generateMemoryText!("prompt", { fallback: botModel("omni-combo-fast"), onUsage: (row) => usage.push(row) });
+ expect(existsSync(`${process.env.FAKE_ACP_DUMP}.config.json`)).toBe(false);
+ expect(usage).toEqual([expect.objectContaining({ model: "omni-combo-fast" })]);
+ });
+
+ it("surfaces offered models when Grok rejects session/set_model with -32602 Invalid params", async () => {
+ process.env.FAKE_ACP_MODE = "set-model-invalid-params";
+ const engine = await create(GrokAgentDriver);
+ await expect(engine.generateMemoryText!("prompt", { fallback: botModel("unlisted-slug") }))
+ .rejects.toThrow("this Grok sign-in offers grok-4.7, omni-combo-fast and explicit-combo");
+ });
+
+ it("lets an explicit model override the bot fallback", async () => {
+ await (await create(GrokAgentDriver)).generateMemoryText!("prompt", { model: "explicit-combo", fallback: botModel("omni-combo-fast") });
+ const { argv } = JSON.parse(readFileSync(process.env.FAKE_ACP_DUMP!, "utf8"));
+ expect(argv).toContain("-m");
+ expect(argv[argv.indexOf("-m") + 1]).toBe("explicit-combo");
+ });
+
+ it("omits -m when neither model nor fallback is supplied", async () => {
+ await (await create(GrokAgentDriver)).generateMemoryText!("prompt");
+ const { argv } = JSON.parse(readFileSync(process.env.FAKE_ACP_DUMP!, "utf8"));
+ expect(argv).not.toContain("-m");
+ expect(existsSync(`${process.env.FAKE_ACP_DUMP}.config.json`)).toBe(false);
+ });
+
+ it.each(["--evil", "bad model", "../x", "default", ""])("never passes an unsafe slug (%j) to -m or session/set_model", async (bad) => {
+ await (await create(GrokAgentDriver)).generateMemoryText!("prompt", { model: bad, fallback: botModel(bad) });
+ const { argv } = JSON.parse(readFileSync(process.env.FAKE_ACP_DUMP!, "utf8"));
+ expect(argv).not.toContain("-m");
+ expect(existsSync(`${process.env.FAKE_ACP_DUMP}.config.json`)).toBe(false);
+ });
+
+ it("leaves other non-selectModel engines (Gemini) unchanged", async () => {
+ await (await create(GeminiAgentDriver)).generateMemoryText!("prompt", { model: "omni-combo-fast", fallback: botModel("omni-combo-fast") });
+ const { argv } = JSON.parse(readFileSync(process.env.FAKE_ACP_DUMP!, "utf8"));
+ expect(argv).not.toContain("-m");
+ });
+
+ it("ignores a throwing oneShotModel hook and falls back to the stock turn", async () => {
+ const support: AcpSupport = {
+ driverKind: "oneshot-throw-test", displayName: "OneShot throw", models: { default: "m-default", options: [{ id: "m-default", label: "m-default" }] },
+ defaultCli: FAKE_CLI, nativeSource: "oneshot-throw-test.acp", loginNote: "sign in",
+ spawnArgs: (_c, turn) => (turn.model ? ["-m", turn.model] : []),
+ pickAuthMethod: () => null, authFailure: "continue", isAuthenticated: () => true,
+ oneShotModel: () => { throw new Error("boom"); },
+ };
+ await (await create(createAcpDriver(support))).generateMemoryText!("prompt", { fallback: botModel("m-bot") });
+ const { argv } = JSON.parse(readFileSync(process.env.FAKE_ACP_DUMP!, "utf8"));
+ expect(argv).not.toContain("-m");
+ });
+ });
+
it("is absent on an engine that opts out", async () => {
const support: AcpSupport = {
driverKind: "opt-out-test", displayName: "Opt out", models: { default: "m", options: [{ id: "m", label: "m" }] },
diff --git a/server/drivers/acp/background-text.ts b/server/drivers/acp/background-text.ts
index 289164b071..04c99124a5 100644
--- a/server/drivers/acp/background-text.ts
+++ b/server/drivers/acp/background-text.ts
@@ -9,6 +9,22 @@ export const BACKGROUND_TEXT_TIMEOUT_MS = 120_000;
export const BACKGROUND_TEXT_MAX_CHARS = 200_000;
const MAX_STDOUT_BYTES = 4_000_000;
+/** Resolves a one-shot turn model for drivers that accept it outside `selectModel` (for example `-m` and `session/set_model`). */
+export function oneShotTurnModel(
+ support: Pick<AcpSupport, "oneShotModel" | "selectModel">,
+ env: Record<string, string | undefined>,
+ options: TextGenerationOptions,
+ models: ModelCatalog,
+): string | undefined {
+ const requested = options.model ?? options.fallback?.model;
+ if (!support.oneShotModel || support.selectModel || !requested) return undefined;
+ try {
+ return support.oneShotModel(requested, env, models) || undefined;
+ } catch {
+ return undefined;
+ }
+}
+
/** Sets a one-shot's env for the bot's own model, not the engine's default (a local model server may hold only the
* model its chats run on), and returns that model for the session to pick. */
export function applyOneShotEnv(
@@ -16,14 +32,16 @@ export function applyOneShotEnv(
env: Record<string, string | undefined>,
options: TextGenerationOptions,
models: ModelCatalog,
- ctx: { fullAuto: false; cwd: string; threadId: string; mcpServers: [] },
+ ctx: { fullAuto: false; cwd: string; threadId: string; mcpServers: []; model?: string },
): AcpOneShotInput["model"] {
const selection = support.selectModel;
- const requestedModel = selection ? options.model ?? options.fallback?.model : undefined;
- const model = requestedModel && requestedModel !== selection?.agentDefault
- ? resolveOneShotModel(support, requestedModel, env, models)
- : undefined;
- support.applyTurnEnv?.(env, { ...(model ? { model, requestedModel } : {}), ...ctx });
+ const requestedModel = selection || ctx.model ? options.model ?? options.fallback?.model : undefined;
+ const model = selection
+ ? (requestedModel && requestedModel !== selection.agentDefault
+ ? resolveOneShotModel(support, requestedModel, env, models)
+ : undefined)
+ : ctx.model;
+ support.applyTurnEnv?.(env, { ...ctx, ...(model ? { model, requestedModel } : {}) });
return model && selection ? { configId: selection.configId, id: model } : undefined;
}
@@ -58,6 +76,8 @@ export interface AcpOneShotInput {
defaultModel: string;
/** Picked through this session config option when the session offers it; otherwise the session's own model runs. */
model?: { configId: string; id: string } | undefined;
+ /** Model applied outside `selectModel` (e.g. via argv or `configure`), used for usage attribution once configured. */
+ configuredModel?: string;
pickAuthMethod: (methods: Array<{ id?: string }>) => string | null;
authRequired: boolean | "if-requested";
loginNote: string;
@@ -127,7 +147,7 @@ export function runAcpOneShot(input: AcpOneShotInput): Promise<string> {
const waiter = pending.get(msg.id);
pending.delete(msg.id);
if (!waiter) return;
- if (msg.error) waiter.reject(new Error(`${name} background ${typeof msg.error?.message === "string" ? msg.error.message.slice(0, 200) : "request failed"}`));
+ if (msg.error) waiter.reject(Object.assign(new Error(`${name} background ${typeof msg.error?.message === "string" ? msg.error.message.slice(0, 200) : "request failed"}`), { code: msg.error.code, data: msg.error.data }));
else waiter.resolve(msg.result);
return;
}
@@ -218,6 +238,7 @@ export function runAcpOneShot(input: AcpOneShotInput): Promise<string> {
model = wanted.id;
}
await input.configure?.({ request: (method, params) => request(method, params), sessionId: session.sessionId, session });
+ if (!input.model && input.configuredModel) model = input.configuredModel;
const result = await request("session/prompt", { sessionId, prompt: [{ type: "text", text: input.prompt }] });
const reported = result?.usage ?? result?._meta ?? {};
const count = (value: unknown) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index e81ab88c47..dae527ccf3 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -21,7 +21,7 @@ import { AcpBrowserAuth, acpBrowserAuthInstanceSurface, type AcpBrowserSignInSpe
import { 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 { applyOneShotEnv, runAcpOneShot } from "./background-text.ts"; import type { AcpBackgroundWork } from "./background-work.ts";
+import { applyOneShotEnv, oneShotTurnModel, runAcpOneShot } from "./background-text.ts"; import type { AcpBackgroundWork } from "./background-work.ts";
import { acpCapabilities } from "./capabilities.ts"; import { readAcpMediaLinks } from "./media-links.ts";
import { acpNativeLogMessage } from "./tool-log.ts";
import { stripLeakedSystemHarnessMessages } from "../../../shared/system-message-guard.ts";
@@ -155,7 +155,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?: AcpBackgroundWork;
+ backgroundText?: false; oneShotFolder?(): Promise<string>; oneShotModel?(model: string, env: Record<string, string | undefined>, models: ModelCatalog): string | undefined; /** 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?(
@@ -1463,8 +1463,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const authenticated = await support.isAuthenticated(env, config, instanceId, instanceEnvNames(input.environment, env)); return { state: "available", version: probe.version, authenticated, ...apiKeyAccount(env, support.credentialEnv, authenticated) };
};
- /** Memory upkeep's one-shot: a fresh process and session, no MCP servers, an empty folder, and
- * every tool, file or permission request refused. */
+ /** Memory upkeep's one-shot: a fresh process and session, no MCP servers, an empty folder, every tool/permission refused. */
const generateMemoryText = async (prompt: string, options: TextGenerationOptions = {}): Promise<string> => {
if (startupModelRefresh) await startupModelRefresh;
const turnConfig: AcpConfig = { ...config, fullAuto: false };
@@ -1474,8 +1473,9 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
}
const cwd = mkdtempSync(join(await support.oneShotFolder?.() ?? tmpdir(), "omb-acp-memory-"));
try {
- const turn = { threadId: `memory-text-${newId()}`, text: prompt, approvalMode: "ask", cwd } as SendTurnInput;
- const model = applyOneShotEnv(support, env, options, catalog.models, { fullAuto: false, cwd, threadId: turn.threadId, mcpServers: [] });
+ const turnModel = oneShotTurnModel(support, env, options, catalog.models);
+ const turn = { threadId: `memory-text-${newId()}`, text: prompt, approvalMode: "ask", cwd, ...(turnModel ? { model: turnModel } : {}) } as SendTurnInput;
+ const model = applyOneShotEnv(support, env, options, catalog.models, { fullAuto: false, cwd, threadId: turn.threadId, mcpServers: [], ...(turnModel ? { model: turnModel } : {}) });
const launch: { command: string; args?: string[]; env?: Record<string, string | undefined>; ro?: readonly string[] } = support.resolveCommand ? await support.resolveCommand(env, turnConfig, instanceId) : { command: turnConfig.cli };
const spawnEnv = launch.env ?? env;
return await runAcpOneShot({
@@ -1486,9 +1486,9 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
env: spawnEnv,
cwd,
prompt,
- defaultModel: catalog.models.default, model,
+ defaultModel: turnModel ?? catalog.models.default, model, ...(turnModel ? { configuredModel: turnModel } : {}),
pickAuthMethod: (methods) => support.pickAuthMethod(methods, spawnEnv),
- authRequired: support.authFailure === "fail-request" ? "if-requested" : support.authFailure === "fail",
+ authRequired: turnModel && skipSubscriptionAuthForLocalInject(options.model ?? options.fallback?.model) ? false : support.authFailure === "fail-request" ? "if-requested" : support.authFailure === "fail",
loginNote: support.loginNote,
clientCapabilitiesMeta: support.clientCapabilitiesMeta,
...(support.configureSession ? {
diff --git a/server/drivers/acp/grok.ts b/server/drivers/acp/grok.ts
index 35adc6d5ac..ddd34a7080 100644
--- a/server/drivers/acp/grok.ts
+++ b/server/drivers/acp/grok.ts
@@ -552,6 +552,10 @@ const support: AcpSupport = {
...(turn.effort ? ["--reasoning-effort", turn.effort] : []),
"stdio",
],
+ oneShotModel: (model, env) => {
+ const resolved = ensureGrokInjectSlug(model, env);
+ return resolved !== "default" && SLUG.test(resolved) ? resolved : undefined;
+ },
spawnContractArgs: (config, turn) => grokContractArgs(support.spawnArgs(config, turn), turn),
loadReplayQuietMs: (turn) => narrowsNativeTools(turn.toolScope) ? undefined : GROK_LOAD_REPLAY_QUIET_MS,
permissionRequest: grokPermissionRequest,