Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
fix(grok): probe health with initialize and allow in-session model changes (#214)
Leo1a47e922a1fd
diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.tsindex bc7828dd8..55059feb4 100644--- a/apps/server/scripts/acp-mock-agent.ts+++ b/apps/server/scripts/acp-mock-agent.ts@@ -278,15 +278,17 @@ function modeState(): AcpSchema.SessionModeState {};}+// Mirrors the real Grok ACP: it advertises versioned model ids, never the CLI's own+// "grok-build" product name, and it rejects unknown ids in session/set_model.const grokAcpModels: ReadonlyArray<AcpSchema.ModelInfo> = [- { modelId: "grok-build", name: "Grok Build" },+ { modelId: "grok-4.6", name: "Grok 4.6" },{ modelId: "grok-mock-alt", name: "Grok Mock Alt" },];function modelState(): AcpSchema.SessionModelState {const modelId = grokAcpModels.some((model) => model.modelId === currentModelId)? currentModelId- : "grok-build";+ : "grok-4.6";return {currentModelId: modelId,availableModels: grokAcpModels,@@ -303,6 +305,9 @@ const program = Effect.gen(function* () {return {protocolVersion: 1,agentCapabilities: { loadSession: true },+ // Grok advertises model state before any session exists; the provider+ // health check reads it from here without authenticating.+ _meta: { modelState: modelState() },};}),);diff --git a/apps/server/src/provider/Layers/GrokProvider.test.ts b/apps/server/src/provider/Layers/GrokProvider.test.tsindex 1c9bf1f26..5b210e4da 100644--- a/apps/server/src/provider/Layers/GrokProvider.test.ts+++ b/apps/server/src/provider/Layers/GrokProvider.test.ts@@ -1,3 +1,7 @@+// @effect-diagnostics nodeBuiltinImport:off - resolves the mock ACP agent script path relative to this test file.+import * as NodePath from "node:path";+import * as NodeURL from "node:url";+import * as NodeServices from "@effect/platform-node/NodeServices";import { describe, expect, it } from "@effect/vitest";import * as Effect from "effect/Effect";@@ -6,9 +10,72 @@ import * as Path from "effect/Path";import * as Schema from "effect/Schema";import { GrokSettings } from "@t3tools/contracts";-import { buildInitialGrokProviderSnapshot, checkGrokProviderStatus } from "./GrokProvider.ts";+import {+ buildGrokModelsFromSessionModelState,+ buildInitialGrokProviderSnapshot,+ checkGrokProviderStatus,+ parseGrokModelsCliOutput,+} from "./GrokProvider.ts";const decodeGrokSettings = Schema.decodeSync(GrokSettings);+const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));++const LOGGED_IN_MODELS_OUTPUT = [+ "You are logged in with grok.com.",+ "",+ "Default model: grok-4.6",+ "",+ "Available models:",+ " * grok-4.6 (default)",+ " - grok-4.5",+ "",+].join("\n");++const LOGGED_OUT_MODELS_OUTPUT = LOGGED_IN_MODELS_OUTPUT.replace(+ "You are logged in with grok.com.",+ "You are not authenticated.",+);++describe("parseGrokModelsCliOutput", () => {+ it("reads login state and model slugs, marking the default", () => {+ const parsed = parseGrokModelsCliOutput(LOGGED_IN_MODELS_OUTPUT);+ expect(parsed.authenticated).toBe(true);+ expect(parsed.models.map((model) => [model.slug, model.isDefault ?? false])).toEqual([+ ["grok-4.6", true],+ ["grok-4.5", false],+ ]);+ });++ it("detects a logged-out CLI even though it exits 0", () => {+ expect(parseGrokModelsCliOutput(LOGGED_OUT_MODELS_OUTPUT).authenticated).toBe(false);+ });++ it("reads the plain one-model-per-line output from current CLIs", () => {+ const parsed = parseGrokModelsCliOutput("grok-4.6\ncodex-1/gpt-5.6-sol\n");+ expect(parsed.authenticated).toBeNull();+ expect(parsed.models.map((model) => model.slug)).toEqual(["grok-4.6", "codex-1/gpt-5.6-sol"]);+ });++ it("returns unknown auth for unrecognized output", () => {+ expect(parseGrokModelsCliOutput("grok 9.9.9\n").authenticated).toBeNull();+ });+});++describe("buildGrokModelsFromSessionModelState", () => {+ it("marks the agent's current model as default", () => {+ const models = buildGrokModelsFromSessionModelState({+ currentModelId: "grok-4.6",+ availableModels: [+ { modelId: "grok-4.6", name: "Grok 4.6" },+ { modelId: "grok-4.5", name: "Grok 4.5" },+ ],+ });+ expect(models.map((model) => [model.slug, model.isDefault ?? false])).toEqual([+ ["grok-4.6", true],+ ["grok-4.5", false],+ ]);+ });+});describe("buildInitialGrokProviderSnapshot", () => {it.effect("returns a disabled snapshot when settings.enabled is false", () =>@@ -41,7 +108,7 @@ describe("buildInitialGrokProviderSnapshot", () => {expect(snapshot.status).toBe("warning");expect(snapshot.version).toBeNull();expect(snapshot.message).toContain("Checking Grok");- expect(snapshot.requiresNewThreadForModelChange).toBe(true);+ expect(snapshot.requiresNewThreadForModelChange).toBeUndefined();}),);});@@ -91,30 +158,153 @@ it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => {}),);- it.effect("reports an error when ACP model discovery is unavailable", () =>+ // Single-quotes a path for /bin/sh. Temp dirs and execPath never contain quotes.+ const shellQuote = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`;++ // A shell stand-in for the Grok CLI: `--version` and `models` print canned text,+ // and `agent stdio` execs the mock ACP agent so `initialize` returns model metadata.+ const writeFakeGrokCli = (input: { readonly modelsOutput: string; readonly acp: boolean }) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-probe-" });+ const modelsPath = path.join(dir, "models.txt");+ yield* fs.writeFileString(modelsPath, input.modelsOutput);+ const grokPath = path.join(dir, "grok");+ const mockAgentPath = path.resolve(__dirname, "../../../scripts/acp-mock-agent.ts");+ yield* fs.writeFileString(+ grokPath,+ [+ "#!/bin/sh",+ 'case "$1" in',+ ' --version) printf "grok 1.0.13\\n"; exit 0;;',+ ` models) cat ${shellQuote(modelsPath)}; exit 0;;`,+ input.acp+ ? ` agent) exec ${shellQuote(process.execPath)} ${shellQuote(mockAgentPath)};;`+ : " agent) exit 3;;",+ "esac",+ "exit 1",+ "",+ ].join("\n"),+ );+ yield* fs.chmod(grokPath, 0o755);+ return grokPath;+ });++ it.effect("reports ready with ACP-discovered models when logged in", () =>Effect.gen(function* () {const snapshot = yield* Effect.scoped(Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-success-" });- const grokPath = path.join(dir, "grok");- yield* fs.writeFileString(- grokPath,- ["#!/bin/sh", 'printf "grok-cli 0.0.99\\n"', "exit 0", ""].join("\n"),+ const grokPath = yield* writeFakeGrokCli({+ modelsOutput: LOGGED_IN_MODELS_OUTPUT,+ acp: true,+ });+ return yield* checkGrokProviderStatus(+ decodeGrokSettings({ enabled: true, binaryPath: grokPath }),+ { ...process.env, XAI_API_KEY: "" },);- yield* fs.chmod(grokPath, 0o755);+ }),+ );++ expect(snapshot.status).toBe("ready");+ expect(snapshot.version).toBe("1.0.13");+ expect(snapshot.auth).toEqual({+ status: "authenticated",+ type: "cached_token",+ label: "Grok account",+ });+ expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-4.6", "grok-mock-alt"]);+ expect(snapshot.models[0]?.isDefault).toBe(true);+ }),+ );+ it.effect("reports unauthenticated from `grok models` without starting a session", () =>+ Effect.gen(function* () {+ const snapshot = yield* Effect.scoped(+ Effect.gen(function* () {+ const grokPath = yield* writeFakeGrokCli({+ modelsOutput: LOGGED_OUT_MODELS_OUTPUT,+ acp: true,+ });return yield* checkGrokProviderStatus(decodeGrokSettings({ enabled: true, binaryPath: grokPath }),+ { ...process.env, XAI_API_KEY: "" },);}),);expect(snapshot.status).toBe("error");+ expect(snapshot.auth.status).toBe("unauthenticated");+ expect(snapshot.message).toContain("grok login");+ expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-4.6", "grok-mock-alt"]);+ }),+ );++ it.effect("falls back to CLI-listed models with a warning when ACP initialize fails", () =>+ Effect.gen(function* () {+ const snapshot = yield* Effect.scoped(+ Effect.gen(function* () {+ const grokPath = yield* writeFakeGrokCli({+ modelsOutput: LOGGED_IN_MODELS_OUTPUT,+ acp: false,+ });+ return yield* checkGrokProviderStatus(+ decodeGrokSettings({ enabled: true, binaryPath: grokPath }),+ { ...process.env, XAI_API_KEY: "" },+ );+ }),+ );++ expect(snapshot.status).toBe("warning");expect(snapshot.installed).toBe(true);- expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-build"]);- expect(snapshot.message).toContain("ACP startup failed");+ expect(snapshot.auth.status).toBe("authenticated");+ expect(snapshot.models.map((model) => [model.slug, model.isDefault ?? false])).toEqual([+ ["grok-4.6", true],+ ["grok-4.5", false],+ ]);+ expect(snapshot.message).toContain("ACP initialize failed");+ }),+ );++ it.effect("treats XAI_API_KEY as authenticated regardless of CLI login state", () =>+ Effect.gen(function* () {+ const snapshot = yield* Effect.scoped(+ Effect.gen(function* () {+ const grokPath = yield* writeFakeGrokCli({+ modelsOutput: LOGGED_OUT_MODELS_OUTPUT,+ acp: false,+ });+ return yield* checkGrokProviderStatus(+ decodeGrokSettings({ enabled: true, binaryPath: grokPath }),+ { ...process.env, XAI_API_KEY: "xai-test-key" },+ );+ }),+ );++ expect(snapshot.auth).toEqual({+ status: "authenticated",+ type: "api_key",+ label: "xAI API key",+ });+ expect(snapshot.status).toBe("warning");}),);});++describe.runIf(process.env.T3_GROK_ACP_PROBE === "1")("checkGrokProviderStatus live CLI", () => {+ it.effect("reports ready from initialize without requiring a new thread for model changes", () =>+ Effect.gen(function* () {+ const snapshot = yield* checkGrokProviderStatus(+ decodeGrokSettings({+ enabled: true,+ binaryPath: process.env.T3_GROK_BINARY || "grok",+ }),+ );+ expect(snapshot.status).toBe("ready");+ expect(["authenticated", "unknown"]).toContain(snapshot.auth.status);+ expect(snapshot.requiresNewThreadForModelChange).toBeUndefined();+ expect(snapshot.models.length).toBeGreaterThan(0);+ expect(snapshot.models.some((model) => model.slug === "grok-build")).toBe(false);+ }).pipe(Effect.provide(NodeServices.layer)),+ );+});diff --git a/apps/server/src/provider/Layers/GrokProvider.ts b/apps/server/src/provider/Layers/GrokProvider.tsindex b5068282b..84405891e 100644--- a/apps/server/src/provider/Layers/GrokProvider.ts+++ b/apps/server/src/provider/Layers/GrokProvider.ts@@ -2,6 +2,7 @@ import {type GrokSettings,type ModelCapabilities,type ServerProvider,+ type ServerProviderAuth,type ServerProviderModel,} from "@t3tools/contracts";import type * as EffectAcpSchema from "effect-acp/schema";@@ -18,6 +19,7 @@ import { createModelCapabilities } from "@t3tools/shared/model";import { resolveSpawnCommand } from "@t3tools/shared/shell";import {+ AUTH_PROBE_TIMEOUT_MS,buildServerProvider,isCommandMissingCause,parseGenericCliVersion,@@ -29,24 +31,30 @@ import {enrichProviderSnapshotWithVersionAdvisory,type ProviderMaintenanceCapabilities,} from "../providerMaintenance.ts";-import { makeGrokAcpRuntime, resolveGrokAcpBaseModelId } from "../acp/GrokAcpSupport.ts";+import { sessionModelStateFromInitialize } from "../acp/AcpRuntimeModel.ts";+import {+ GROK_DEFAULT_MODEL_SLUG,+ makeGrokAcpRuntime,+ resolveGrokAcpBaseModelId,+} from "../acp/GrokAcpSupport.ts";const GROK_PRESENTATION = {displayName: "Grok",badgeLabel: "Early Access",showInteractionModeToggle: false,- requiresNewThreadForModelChange: true,} as const;const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({optionDescriptors: [],});const VERSION_PROBE_TIMEOUT_MS = 4_000;-const GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;+// `initialize` is a single local round trip, so this is generous even on slow machines.+const GROK_ACP_INITIALIZE_TIMEOUT_MS = 8_000;+const GROK_API_KEY_ENV = "XAI_API_KEY";const GROK_BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [{- slug: "grok-build",+ slug: GROK_DEFAULT_MODEL_SLUG,name: "Grok Build",isCustom: false,capabilities: EMPTY_CAPABILITIES,@@ -99,56 +107,96 @@ function grokModelsFromSettings(return providerModelsFromSettings(builtInModels, customModels ?? [], EMPTY_CAPABILITIES);}-function buildGrokDiscoveredModelsFromSessionModelState(+/** Models advertised by the ACP agent, with the session's current model marked as default. */+export function buildGrokModelsFromSessionModelState(modelState: EffectAcpSchema.SessionModelState | null | undefined,): ReadonlyArray<ServerProviderModel> {if (!modelState || modelState.availableModels.length === 0) {return [];}+ const currentModelId = modelState.currentModelId.trim();const seen = new Set<string>();- return modelState.availableModels- .map((model): ServerProviderModel | undefined => {- const slug = resolveGrokAcpBaseModelId(model.modelId);- if (!slug || seen.has(slug)) {- return undefined;- }- seen.add(slug);- return {+ return modelState.availableModels.flatMap((model): ServerProviderModel[] => {+ const slug = resolveGrokAcpBaseModelId(model.modelId);+ if (!slug || seen.has(slug)) {+ return [];+ }+ seen.add(slug);+ return [+ {slug,name: model.name.trim() || slug,isCustom: false,+ ...(model.modelId.trim() === currentModelId ? { isDefault: true } : {}),capabilities: EMPTY_CAPABILITIES,- };- })- .filter((model): model is ServerProviderModel => model !== undefined);+ },+ ];+ });}-const discoverGrokModelsViaAcp = (- grokSettings: GrokSettings,- environment: NodeJS.ProcessEnv = process.env,-) =>- Effect.gen(function* () {- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const acp = yield* makeGrokAcpRuntime({- grokSettings,- environment,- childProcessSpawner,- cwd: process.cwd(),- clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },+export interface GrokModelsCliOutput {+ /** True or false when the CLI printed a login line, null when it printed neither. */+ readonly authenticated: boolean | null;+ readonly models: ReadonlyArray<ServerProviderModel>;+}++/**+ * Parses `grok models`. The command exits 0 whether or not the user is logged in, so the+ * text is the only signal. Current output looks like:+ *+ * You are logged in with grok.com.+ * Default model: grok-4.6+ * Available models:+ * * grok-4.6 (default)+ * - grok-4.5+ */+export function parseGrokModelsCliOutput(output: string): GrokModelsCliOutput {+ const authenticated = /you are logged in/i.test(output)+ ? true+ : /not authenticated|not logged in/i.test(output)+ ? false+ : null;++ const seen = new Set<string>();+ const models: ServerProviderModel[] = [];+ for (const line of output.split(/\r?\n/)) {+ const bullet = line.match(/^\s*[*-]\s+(\S+)(.*)$/);+ const plain = line.trim();+ const rawSlug = bullet?.[1] ?? (/^[a-z0-9][a-z0-9._/-]*$/i.test(plain) ? plain : null);+ if (rawSlug === null) {+ continue;+ }+ const slug = resolveGrokAcpBaseModelId(rawSlug);+ if (seen.has(slug)) {+ continue;+ }+ seen.add(slug);+ models.push({+ slug,+ name: displayNameFromGrokModelSlug(slug),+ isCustom: false,+ ...(/\(default\)/i.test(bullet?.[2] ?? "") ? { isDefault: true } : {}),+ capabilities: EMPTY_CAPABILITIES,});- const started = yield* acp.start();- return buildGrokDiscoveredModelsFromSessionModelState(started.sessionSetupResult.models);- }).pipe(Effect.scoped);+ }+ return { authenticated, models };+}-const runGrokVersionCommand = (+function displayNameFromGrokModelSlug(slug: string): string {+ return slug+ .split(/[-_]/g)+ .map((part) => (part.toLowerCase() === "grok" ? "Grok" : part))+ .join(" ");+}++const runGrokCliCommand = (grokSettings: GrokSettings,- environment: NodeJS.ProcessEnv = process.env,+ args: ReadonlyArray<string>,+ environment: NodeJS.ProcessEnv,) =>Effect.gen(function* () {const command = grokSettings.binaryPath || "grok";- const spawnCommand = yield* resolveSpawnCommand(command, ["--version"], {- env: environment,- });+ const spawnCommand = yield* resolveSpawnCommand(command, args, { env: environment });return yield* spawnAndCollect(command,ChildProcess.make(spawnCommand.command, spawnCommand.args, {@@ -158,6 +206,27 @@ const runGrokVersionCommand = ();});+/**+ * Reads model metadata from `initialize._meta.modelState`. This never calls `authenticate`+ * or `session/new`, so it cannot open a browser login or boot the workspace's MCP servers.+ */+const discoverGrokModelsViaAcpInitialize = (+ grokSettings: GrokSettings,+ environment: NodeJS.ProcessEnv,+) =>+ Effect.gen(function* () {+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const acp = yield* makeGrokAcpRuntime({+ grokSettings,+ environment,+ childProcessSpawner,+ cwd: process.cwd(),+ clientInfo: { name: "akeru-bot-provider-probe", version: "0.0.0" },+ });+ const initialized = yield* acp.initialize();+ return buildGrokModelsFromSessionModelState(sessionModelStateFromInitialize(initialized));+ }).pipe(Effect.scoped);+export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(function* (grokSettings: GrokSettings,environment: NodeJS.ProcessEnv = process.env,@@ -185,7 +254,7 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func});}- const versionResult = yield* runGrokVersionCommand(grokSettings, environment).pipe(+ const versionResult = yield* runGrokCliCommand(grokSettings, ["--version"], environment).pipe(Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),Effect.result,);@@ -251,51 +320,73 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func});}- const discoveryExit = yield* discoverGrokModelsViaAcp(grokSettings, environment).pipe(- Effect.timeoutOption(GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS),- Effect.exit,+ // `grok models` reports login state and model slugs without starting the agent.+ const modelsResult = yield* runGrokCliCommand(grokSettings, ["models"], environment).pipe(+ Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS),+ Effect.result,);- if (Exit.isFailure(discoveryExit)) {- yield* Effect.logWarning("Grok ACP model discovery failed", {- errorTag: causeErrorTag(discoveryExit.cause),+ // Only a clean exit is parsed. Failed invocations print help or error text that+ // must not be read as model slugs or as a login verdict.+ const modelsOutput =+ Result.isSuccess(modelsResult) &&+ Option.isSome(modelsResult.success) &&+ modelsResult.success.value.code === 0+ ? modelsResult.success.value+ : undefined;+ const cliModels: GrokModelsCliOutput = modelsOutput+ ? parseGrokModelsCliOutput(`${modelsOutput.stdout}\n${modelsOutput.stderr}`)+ : { authenticated: null, models: [] };+ if (!modelsOutput) {+ yield* Effect.logWarning("Grok CLI model listing failed or timed out.", {+ errorTag: Result.isFailure(modelsResult)+ ? modelsResult.failure._tag+ : Option.isNone(modelsResult.success)+ ? "Timeout"+ : `ExitCode${modelsResult.success.value.code}`,});- return buildServerProvider({- presentation: GROK_PRESENTATION,- enabled: grokSettings.enabled,- checkedAt,- models: fallbackModels,- probe: {- installed: true,- version,- status: "error",- auth: { status: "unknown" },- message: "Grok CLI is installed but ACP startup failed. Check server logs for details.",- },+ }++ const auth: ServerProviderAuth = environment[GROK_API_KEY_ENV]?.trim()+ ? { status: "authenticated", type: "api_key", label: "xAI API key" }+ : cliModels.authenticated === true+ ? { status: "authenticated", type: "cached_token", label: "Grok account" }+ : cliModels.authenticated === false+ ? { status: "unauthenticated" }+ : { status: "unknown" };++ const acpExit = yield* discoverGrokModelsViaAcpInitialize(grokSettings, environment).pipe(+ Effect.timeoutOption(GROK_ACP_INITIALIZE_TIMEOUT_MS),+ Effect.exit,+ );+ const acpModels = Exit.isSuccess(acpExit) ? Option.getOrElse(acpExit.value, () => []) : [];+ const acpFailed = Exit.isFailure(acpExit) || Option.isNone(acpExit.value);+ if (acpFailed) {+ yield* Effect.logWarning("Grok ACP initialize probe failed or timed out.", {+ errorTag: Exit.isFailure(acpExit) ? causeErrorTag(acpExit.cause) : "Timeout",});}- if (Option.isNone(discoveryExit.value)) {- yield* Effect.logWarning(- `Grok ACP model discovery timed out after ${GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`,- );++ const discoveredModels = acpModels.length > 0 ? acpModels : cliModels.models;+ const models =+ discoveredModels.length > 0+ ? grokModelsFromSettings(grokSettings.customModels, discoveredModels)+ : fallbackModels;++ if (auth.status === "unauthenticated") {return buildServerProvider({presentation: GROK_PRESENTATION,enabled: grokSettings.enabled,checkedAt,- models: fallbackModels,+ models,probe: {installed: true,version,status: "error",- auth: { status: "unknown" },- message: `Grok CLI is installed but ACP startup timed out after ${GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`,+ auth,+ message: "Grok CLI is installed but not logged in. Run `grok login`.",},});}- const discoveredModels = discoveryExit.value.value;- const models =- discoveredModels.length > 0- ? grokModelsFromSettings(grokSettings.customModels, discoveredModels)- : fallbackModels;return buildServerProvider({presentation: GROK_PRESENTATION,@@ -305,8 +396,15 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(funcprobe: {installed: true,version,- status: "ready",- auth: { status: "unknown" },+ // A failed metadata probe degrades the model picker, it does not make chats fail.+ status: acpFailed ? "warning" : "ready",+ auth,+ ...(acpFailed+ ? {+ message:+ "Grok CLI is installed but ACP initialize failed. Model options may be incomplete.",+ }+ : {}),},});});diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.test.ts b/apps/server/src/provider/acp/AcpRuntimeModel.test.tsindex c2f7612ad..11931784b 100644--- a/apps/server/src/provider/acp/AcpRuntimeModel.test.ts+++ b/apps/server/src/provider/acp/AcpRuntimeModel.test.ts@@ -16,6 +16,7 @@ import {parsePermissionRequest,parseSessionModeState,parseSessionUpdateEvent,+ sessionModelStateFromInitialize,sessionUpdateIsReplay,syntheticLoadSessionResponseFromInitialize,waitForSessionLoadReplayIdle,@@ -115,6 +116,32 @@ describe("AcpRuntimeModel", () => {).toBe(false);});+ it("reads Grok model state from initialize._meta before a session exists", () => {+ const modelState = sessionModelStateFromInitialize({+ protocolVersion: 1,+ _meta: {+ modelState: {+ currentModelId: "grok-4.6",+ availableModels: [+ { modelId: "grok-4.6", name: "Grok 4.6" },+ { modelId: "grok-mock-alt", name: "Grok Mock Alt" },+ ],+ },+ },+ } satisfies EffectAcpSchema.InitializeResponse);++ expect(modelState?.currentModelId).toBe("grok-4.6");+ expect(modelState?.availableModels.map((model) => model.modelId)).toEqual([+ "grok-4.6",+ "grok-mock-alt",+ ]);+ expect(+ sessionModelStateFromInitialize({+ protocolVersion: 1,+ } satisfies EffectAcpSchema.InitializeResponse),+ ).toBeUndefined();+ });+it("builds a synthetic load response from initialize model state", () => {const response = syntheticLoadSessionResponseFromInitialize({protocolVersion: 1,diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.ts b/apps/server/src/provider/acp/AcpRuntimeModel.tsindex e03647a65..287fbf31a 100644--- a/apps/server/src/provider/acp/AcpRuntimeModel.ts+++ b/apps/server/src/provider/acp/AcpRuntimeModel.ts@@ -612,13 +612,24 @@ export const waitForSessionLoadReplayIdle = (input: {}});+/**+ * Model state some agents (Grok) advertise in `initialize._meta.modelState`, before any+ * session exists. Undefined when the agent does not advertise it or the shape is unknown.+ */+export function sessionModelStateFromInitialize(+ initializeResult: EffectAcpSchema.InitializeResponse,+): EffectAcpSchema.SessionModelState | undefined {+ const meta = initializeResult._meta;+ const modelState = isRecord(meta) ? meta.modelState : undefined;+ return isSessionModelState(modelState) ? modelState : undefined;+}+export function syntheticLoadSessionResponseFromInitialize(initializeResult: EffectAcpSchema.InitializeResponse,): EffectAcpSchema.LoadSessionResponse {const meta = initializeResult._meta;- const modelState = isRecord(meta) ? meta.modelState : undefined;const modeState = isRecord(meta) ? meta.modeState : undefined;- const models = isSessionModelState(modelState) ? modelState : undefined;+ const models = sessionModelStateFromInitialize(initializeResult);const modes = isSessionModeState(modeState) ? modeState : undefined;return {diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.tsindex 587da2605..7052182de 100644--- a/apps/server/src/provider/acp/AcpSessionRuntime.ts+++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts@@ -181,6 +181,15 @@ export class AcpSessionRuntime extends Context.Service<* @see https://agentclientprotocol.com/protocol/extensibility*/readonly handleExtNotification: EffectAcpClient.AcpClient["Service"]["handleExtNotification"];+ /**+ * Sends ACP `initialize` without authenticating or opening a session.+ * Provider health checks use this to read advertised models from `_meta.modelState`.+ * @see https://agentclientprotocol.com/protocol/schema#initialize+ */+ readonly initialize: () => Effect.Effect<+ EffectAcpSchema.InitializeResponse,+ EffectAcpErrors.AcpError+ >;/*** Initializes the ACP connection, authenticates, and loads, resumes, or creates the session.* Concurrent calls share the same in-flight startup and a failed startup may be retried.@@ -535,18 +544,19 @@ export const make = (),);+ const initializePayload = {+ protocolVersion: 1,+ clientCapabilities: initializeClientCapabilities,+ clientInfo: options.clientInfo,+ } satisfies EffectAcpSchema.InitializeRequest;+ const sendInitialize = runLoggedRequest(+ "initialize",+ initializePayload,+ acp.agent.initialize(initializePayload),+ );+const startOnce = Effect.gen(function* () {- const initializePayload = {- protocolVersion: 1,- clientCapabilities: initializeClientCapabilities,- clientInfo: options.clientInfo,- } satisfies EffectAcpSchema.InitializeRequest;-- const initializeResult = yield* runLoggedRequest(- "initialize",- initializePayload,- acp.agent.initialize(initializePayload),- );+ const initializeResult = yield* sendInitialize;const authenticatePayload = {methodId: options.authMethodId,@@ -711,6 +721,7 @@ export const make = (handleUnknownExtNotification: acp.handleUnknownExtNotification,handleExtRequest: acp.handleExtRequest,handleExtNotification: acp.handleExtNotification,+ initialize: () => sendInitialize,start: () => start,getEvents: () => Stream.fromQueue(eventQueue),drainEvents: Effect.gen(function* () {diff --git a/apps/server/src/provider/acp/GrokAcpCliProbe.test.ts b/apps/server/src/provider/acp/GrokAcpCliProbe.test.tsindex 222fc4a12..472db319e 100644--- a/apps/server/src/provider/acp/GrokAcpCliProbe.test.ts+++ b/apps/server/src/provider/acp/GrokAcpCliProbe.test.ts@@ -13,6 +13,7 @@ import * as Effect from "effect/Effect";import { ChildProcessSpawner } from "effect/unstable/process";import { describe, expect } from "vite-plus/test";+import { sessionModelStateFromInitialize } from "./AcpRuntimeModel.ts";import { makeGrokAcpRuntime } from "./GrokAcpSupport.ts";const makeProbeRuntime = Effect.gen(function* () {@@ -27,6 +28,18 @@ const makeProbeRuntime = Effect.gen(function* () {});describe.runIf(process.env.T3_GROK_ACP_PROBE === "1")("Grok ACP CLI probe", () => {+ it.effect("initialize advertises model state without opening a session", () =>+ Effect.gen(function* () {+ const runtime = yield* makeProbeRuntime;+ const initialized = yield* runtime.initialize();+ const models = sessionModelStateFromInitialize(initialized);+ expect(initialized.protocolVersion).toBeDefined();+ expect(typeof models?.currentModelId).toBe("string");+ expect(models?.availableModels.length ?? 0).toBeGreaterThan(0);+ expect(models?.availableModels.some((model) => model.modelId === "grok-build")).toBe(false);+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );+it.effect("initialize and authenticate against real grok agent stdio", () =>Effect.gen(function* () {const runtime = yield* makeProbeRuntime;diff --git a/apps/server/src/provider/acp/GrokAcpSupport.test.ts b/apps/server/src/provider/acp/GrokAcpSupport.test.tsindex 02d60976b..4cd4dc4a2 100644--- a/apps/server/src/provider/acp/GrokAcpSupport.test.ts+++ b/apps/server/src/provider/acp/GrokAcpSupport.test.ts@@ -63,6 +63,20 @@ describe("applyGrokAcpModelSelection", () => {}),);+ it.effect("keeps the session's current model when the product slug is requested", () =>+ Effect.gen(function* () {+ const { runtime, modelCalls } = makeRecordingRuntime();+ const result = yield* applyGrokAcpModelSelection({+ runtime,+ currentModelId: "grok-4.6",+ requestedModelId: "grok-build",+ mapError: (cause) => cause.message,+ });+ expect(modelCalls).toEqual([]);+ expect(result).toBe("grok-4.6");+ }),+ );+it.effect("skips set_model when requested matches current", () =>Effect.gen(function* () {const { runtime, modelCalls } = makeRecordingRuntime();diff --git a/apps/server/src/provider/acp/GrokAcpSupport.ts b/apps/server/src/provider/acp/GrokAcpSupport.tsindex c928b3ed8..284efb60e 100644--- a/apps/server/src/provider/acp/GrokAcpSupport.ts+++ b/apps/server/src/provider/acp/GrokAcpSupport.ts@@ -76,10 +76,16 @@ export const makeGrokAcpRuntime = (return yield* makeXAiPromptCompletionRuntime(runtime);});+/**+ * Akeru's built-in Grok slug. It is the CLI's product name, not a model id the ACP accepts,+ * so selecting it means "use whatever model the Grok session currently runs on".+ */+export const GROK_DEFAULT_MODEL_SLUG = "grok-build";+export function resolveGrokAcpBaseModelId(model: string | null | undefined): string {const trimmed = model?.trim();- const base = trimmed && trimmed.length > 0 ? trimmed : "grok-build";- return normalizeModelSlug(base, GROK_DRIVER_KIND) ?? "grok-build";+ const base = trimmed && trimmed.length > 0 ? trimmed : GROK_DEFAULT_MODEL_SLUG;+ return normalizeModelSlug(base, GROK_DRIVER_KIND) ?? GROK_DEFAULT_MODEL_SLUG;}export function currentGrokModelIdFromSessionSetup(@@ -97,12 +103,15 @@ export function applyGrokAcpModelSelection<E>(input: {readonly requestedModelId: string | undefined;readonly mapError: (cause: EffectAcpErrors.AcpError) => E;}): Effect.Effect<string | undefined, E> {+ // The product slug is never sent over the wire; it keeps the session's current model.+ const requestedModelId =+ input.requestedModelId === GROK_DEFAULT_MODEL_SLUG ? undefined : input.requestedModelId;const shouldSwitchModel =- input.requestedModelId !== undefined && input.requestedModelId !== input.currentModelId;+ requestedModelId !== undefined && requestedModelId !== input.currentModelId;if (!shouldSwitchModel) {return Effect.succeed(input.currentModelId);}return input.runtime- .setSessionModel(input.requestedModelId)- .pipe(Effect.mapError(input.mapError), Effect.as(input.requestedModelId));+ .setSessionModel(requestedModelId)+ .pipe(Effect.mapError(input.mapError), Effect.as(requestedModelId));}diff --git a/docs/internals/providers.md b/docs/internals/providers.mdindex f3640aca5..fef9eda26 100644--- a/docs/internals/providers.md+++ b/docs/internals/providers.md@@ -79,6 +79,22 @@ revert boundary. OpenCode keeps reverted messages in the transcript until the ne`readThread` stops at `session.revert.messageID` rather than slicing the local copy. OpenCode Gostays on Mastra and does not use this adapter path.+### Grok health check++`checkGrokProviderStatus` never opens an ACP session. It runs `grok --version`, then `grok models`+for login state and model slugs, then a single ACP `initialize` and reads models from+`_meta.modelState`. `authenticate` and `session/new` are skipped on purpose: `authenticate` can open+a browser login and `session/new` boots every configured MCP server, both of which made background+probes hang or surprise the user. A failed `initialize` degrades to `warning` with the CLI's model+list instead of persisting `error` over a working install. `XAI_API_KEY` counts as authenticated.+The built-in `grok-build` slug is the CLI's product name, not an ACP model id.+`applyGrokAcpModelSelection` treats it as "keep the session's current model" and never sends it in+`session/set_model`. Grok snapshots no longer advertise `requiresNewThreadForModelChange`, so an+in-session model change reaches ACP `session/set_model`.++Cursor and OpenCode still start sessions through `AcpSessionRuntime.start()`. The new+`initialize()` method is additive and unused by those adapters.+## Raw protocol observationThe [ACP protocol](../../packages/effect-acp/src/protocol.ts) anddiff --git a/packages/contracts/src/model.ts b/packages/contracts/src/model.tsindex 90b8cc0db..1dcd981a2 100644--- a/packages/contracts/src/model.ts+++ b/packages/contracts/src/model.ts@@ -153,6 +153,7 @@ export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, strin[CODEX_DRIVER_KIND]: DEFAULT_MODEL,[CLAUDE_DRIVER_KIND]: "claude-sonnet-5",[CURSOR_DRIVER_KIND]: "auto",+ // Product slug, not an ACP model id. The Grok adapter treats it as "the session's current model".[GROK_DRIVER_KIND]: "grok-build",[KIMI_DRIVER_KIND]: "k3",[OPENCODE_DRIVER_KIND]: "openai/gpt-5",