Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(grok): a model the Grok sign-in doesn't offer fails with a plain line naming the ones it does (#6993)
Milind Soni1c27aec5da16
diff --git a/server/drivers/acp/grok-session.test.ts b/server/drivers/acp/grok-session.test.tsindex b85c277b0b..bfeb3eba70 100644--- a/server/drivers/acp/grok-session.test.ts+++ b/server/drivers/acp/grok-session.test.ts@@ -8,6 +8,7 @@ import { afterEach, describe, expect, it } from "vitest";import { ensureDirs, NATIVE_DIR } from "../../config.ts";import type { ProviderInstance, SendTurnInput } from "../../contracts.ts";+import { classifyRoutineFailure } from "../../routine-recovery.ts";import { removeTempDir } from "../../testing/cleanup.ts";import { recordEvents } from "../../testing/events.ts";import { GrokAgentDriver, grokPermissionRequest } from "./grok.ts";@@ -163,6 +164,48 @@ describe("Grok changes model and effort inside the running session", () => {}});+ // grok 1.0.41 signed in to an account without grok-4.7 answers set_model "Invalid params: unknown model id".+ it("says in plain words which models Grok offers when it refuses one it does not, without a second process", async () => {+ const { instance, recorder, calls, processes, ask } = await start("grok-model-not-offered", {+ FAKE_ACP_MODE: "set-model-invalid-params", FAKE_ACP_SESSION_MODELS: "grok-4.6|Grok 4.6,grok-4.5|Grok 4.5",+ });+ const threadId = "t-grok-model-not-offered";+ try {+ expect(await ask({ threadId, model: "grok-4.6" })).toMatchObject({ ok: true });+ expect(await ask({ threadId, model: "grok-4.7", resumeCursor: "fake-acp-session" })).toMatchObject({ ok: false });+ const errors = recorder.events.filter((event) => event.type === "runtime.error").map((event) => (event as { message: string }).message);+ expect(errors).toEqual(["Grok can't use the model grok-4.7 here: this Grok sign-in offers grok-4.6 and grok-4.5, so choose one of those for this bot."]);+ // A routine does not spend its one retry on it: the next start would be refused the same way.+ expect(classifyRoutineFailure(errors[0]!)).toEqual({ kind: "final" });+ expect(processes()).toBe(1);+ expect(calls().filter((call) => call.method === "session/prompt")).toHaveLength(1);+ // The refusing process is retired: the next turn starts a new one, which reads the offered models afresh.+ expect(await ask({ threadId, model: "grok-4.7", resumeCursor: "fake-acp-session" })).toMatchObject({ ok: false });+ expect(processes()).toBe(2);+ } finally {+ recorder.stop();+ await instance.dispose();+ }+ });++ it("keeps the restart and Grok's own words when the switch to an unlisted model failed some other way", async () => {+ const { instance, recorder, processes, ask } = await start("grok-model-switch-failed", {+ FAKE_ACP_MODE: "set-model-internal-error", FAKE_ACP_SESSION_MODELS: "grok-4.6|Grok 4.6,grok-4.5|Grok 4.5",+ });+ const threadId = "t-grok-model-switch-failed";+ try {+ expect(await ask({ threadId, model: "grok-4.6" })).toMatchObject({ ok: true });+ expect(await ask({ threadId, model: "grok-4.7", resumeCursor: "fake-acp-session" })).toMatchObject({ ok: false });+ const errors = recorder.events.filter((event) => event.type === "runtime.error").map((event) => (event as { message: string }).message);+ expect(errors).toHaveLength(1);+ expect(errors[0]).toMatch(/^Grok rejected model "grok-4.7" via session\/set_model: Internal error: model switch failed/);+ 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";diff --git a/server/drivers/acp/grok.ts b/server/drivers/acp/grok.tsindex b75d7f9a54..35adc6d5ac 100644--- a/server/drivers/acp/grok.ts+++ b/server/drivers/acp/grok.ts@@ -152,6 +152,21 @@ export function readGrokModelCatalog(env: Record<string, string | undefined> = p};}+/** What a person reads when Grok refused `model` and its session listed the models this sign-in offers without it; null+ * when the session listed none, or listed this one (then the refusal was something else). */+export function grokModelNotOffered(model: string, sessionModels: readonly { modelId?: string }[]): string | null {+ const offered = [...new Set(sessionModels.map((entry) => entry.modelId).filter((id): id is string => typeof id === "string" && id.length > 0))];+ if (offered.length === 0 || offered.includes(model)) return null;+ const list = offered.length === 1 ? offered[0] : `${offered.slice(0, -1).join(", ")} and ${offered.at(-1)}`;+ // "can't use the model" keeps a routine from retrying a run that would be refused the same way (retry.ts).+ return `Grok can't use the model ${model} here: this Grok sign-in offers ${list}, so choose ${offered.length === 1 ? "it" : "one of those"} for this bot.`;+}++/** Grok's answer to set_model for a model it does not know: JSON-RPC invalid params, or its "unknown model id" words. */+function unknownGrokModel(error: unknown): boolean {+ return (error as { code?: unknown } | null)?.code === -32602 || /\bunknown model\b/i.test(error instanceof Error ? error.message : String(error));+}+function suggestGrokSlug(host: string, model: string, taken: Set<string>): string {let base = `${host}-${model}`.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");if (!base || !/^[a-z]/.test(base)) base = `m-${base || "model"}`;@@ -551,7 +566,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, currentEffort, effortApplied, configOptions }) {+ async configureSession({ request, sessionId, turn, sessionModels, 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] : []),@@ -590,6 +605,10 @@ const support: AcpSupport = {try {await request("session/set_model", { sessionId, modelId: turn.model });} catch (e) {+ // Refused as unknown, and missing from the models this sign-in offers: this turn ends at once, since a new process+ // would be refused the same way, and the process is retired, so the next turn reads the list afresh.+ const notOffered = unknownGrokModel(e) ? grokModelNotOffered(turn.model, sessionModels) : null;+ if (notOffered) throw Object.assign(new Error(notOffered), { acpSessionFailure: true });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.`,diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.tsindex 85fc072203..8f82018803 100755--- a/server/testing/fake-acp-cli.ts+++ b/server/testing/fake-acp-cli.ts@@ -17,6 +17,7 @@// FAKE_ACP_ASK_PARAMS; the client's reply is written to FAKE_ACP_ASK_ANSWER. FAKE_ACP_ASK_TIMING=with-result// settles the turn with the card open; after-result asks between turns)// | interleave (message, tool, message, tool, message) | no-session-config (set_mode/set_model answer -32601)+// | set-model-internal-error (set_model answers -32603)// | ask-peer | delegate-peer | chief-delegate | create-peer (coordinate_bots through the injected agents// MCP; FAKE_ACP_REDELEGATE_FILE, FAKE_ACP_TASKID_FILE; a hand-off result wake gets a fixed line)// | echo-gated (echo the whole prompt; hold until FAKE_ACP_GATE_FILE exists) | safe-agent-reads@@ -1193,6 +1194,9 @@ function handle(msg: any) {// Cursor's answer when handed an argv slug like `auto`.return out({ jsonrpc: "2.0", id: msg.id, error: { code: -32602, message: "Invalid params" } });}+ if (msg.method === "session/set_model" && mode === "set-model-internal-error") {+ return out({ jsonrpc: "2.0", id: msg.id, error: { code: -32603, message: "Internal error: model switch failed" } });+ }const settingId = msg.method === "session/set_mode" ? "modeId" : "modelId";if (typeof msg.params?.sessionId !== "string" || typeof msg.params?.[settingId] !== "string") {out({