Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(grok): make model switching work against a grid

tonyffe89b5a7ca2
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 5e3c7f731..178c7df88 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -3287,9 +3287,9 @@ async function runForeground(session: AuthSession): Promise<void> {
// user's own dotfiles. The label is unique per creation, so two agents never share one.
const createConfigDir = gridConfigDirFor(engine, built.launch)
if (createConfigDir) {
- const { envVar, files, pointAt } = createConfigDir
+ const { envVar, files, pointAt, links } = createConfigDir
try {
- const dir = await writeGridConfigDir(label, files)
+ const dir = await writeGridConfigDir(label, files, links)
// Pi is handed the directory; OpenCode's OPENCODE_CONFIG wants the file inside it.
gridLaunch.env[envVar] = pointAt ? join(dir, pointAt) : dir
} catch (error) {
@@ -3534,9 +3534,9 @@ async function runForeground(session: AuthSession): Promise<void> {
if (retargetConfigDir) {
// Keyed on the agent, so moving the same agent between grids rewrites one directory rather
// than leaving a trail of them.
- const { envVar, files, pointAt } = retargetConfigDir
+ const { envVar, files, pointAt, links } = retargetConfigDir
try {
- const dir = await writeGridConfigDir(session.agentId, files)
+ const dir = await writeGridConfigDir(session.agentId, files, links)
// Same split as create: a directory for Pi, the file itself for OpenCode.
gridEnv[envVar] = pointAt ? join(dir, pointAt) : dir
} catch (error) {
diff --git a/cli/src/engines/grok/runtimeProfile.spec.ts b/cli/src/engines/grok/runtimeProfile.spec.ts
index d11218019..c61487dee 100644
--- a/cli/src/engines/grok/runtimeProfile.spec.ts
+++ b/cli/src/engines/grok/runtimeProfile.spec.ts
@@ -9,6 +9,50 @@ describe('Grok runtime profile', () => {
})
})
+ it('reads the model off the composer box edge current builds print it on', () => {
+ // Measured on a live pane (grok 4.6, 2026-09-09). Current builds moved the cell out of a
+ // standalone footer and into the bottom edge of the composer box, where the character after
+ // `(xhigh)` is the rule closing the box rather than the `·` the old rule required — so this
+ // returned null on every current pane. It is the ONLY source the runtime profile has for grok's
+ // model and effort, so with it silent the app could never say which model an agent was on.
+ expect(parseGrokFooterProfile(
+ ' ╰──────────────────────────────── Grok 4.6 (xhigh) ─╯',
+ )).toEqual({ model: 'grok-4.6', effort: 'xhigh' })
+ // The old layouts still have to parse: a machine on an older grok is not a machine we stop
+ // reading.
+ expect(parseGrokFooterProfile('Grok 4.5 (high) | always-approve'))
+ .toEqual({ model: 'grok-4.5', effort: 'high' })
+ // The cell can also simply end the line.
+ expect(parseGrokFooterProfile('Grok 4.6 (low)')).toEqual({ model: 'grok-4.6', effort: 'low' })
+ })
+
+ it('reads a grid model, whose name is not the vendor\'s and carries no effort', () => {
+ // Measured on a live pane after moving a grok agent onto the autonomous.ai grid and picking
+ // DeepSeek-V4-Flash-0731. Anchoring on the word "Grok" was safe only while every model was one of
+ // xAI's: a grid model matches no `Grok …` pattern, so the scan fell THROUGH the box edge and kept
+ // walking up the pane until it reached the transcript, where the model had written the words
+ // "Grok 4.6 (xhigh)" about itself. The pane reported `grok-4.6` while actually running DeepSeek —
+ // the app stating the wrong model with full confidence, which is worse than stating none.
+ expect(parseGrokFooterProfile(' ╰──── DeepSeek-V4-Flash-0731 · always-approve ─╯'))
+ .toEqual({ model: 'deepseek-v4-flash-0731', effort: 'auto' })
+ expect(parseGrokFooterProfile(' ╰──────── DeepSeek-V4-Flash-0731 ─╯'))
+ .toEqual({ model: 'deepseek-v4-flash-0731', effort: 'auto' })
+ // The edge wins over anything the transcript above it happens to say about a model.
+ expect(parseGrokFooterProfile([
+ ' ┃ this session defaults to Grok 4.6 (xhigh), context 500k',
+ ' ╭────────────────────────────────────╮',
+ ' │ ❯ │',
+ ' ╰──── DeepSeek-V4-Flash-0731 ─╯',
+ ].join('\n'))).toEqual({ model: 'deepseek-v4-flash-0731', effort: 'auto' })
+ })
+
+ it('does not mistake prose that mentions a Grok version for the footer', () => {
+ // With no box edge to anchor on, the vendor's name plus `(effort)` is the only thing separating
+ // chrome from prose — so the fallback keeps requiring both, and a sentence satisfies neither.
+ expect(parseGrokFooterProfile('I used Grok 4.6 to write this')).toBeNull()
+ expect(parseGrokFooterProfile('Grok 4.6 (xhigh) was fast')).toBeNull()
+ })
+
it('reads the measured model catalog and skips prose', () => {
expect(parseGrokModelsOutput([
'You are logged in with grok.com.',
diff --git a/cli/src/engines/grok/runtimeProfile.ts b/cli/src/engines/grok/runtimeProfile.ts
index bdc5d01b6..0082144b7 100644
--- a/cli/src/engines/grok/runtimeProfile.ts
+++ b/cli/src/engines/grok/runtimeProfile.ts
@@ -1,8 +1,47 @@
-/** Grok's idle footer: `Grok 4.5 (medium) · always-approve`. */
+/**
+ * Which model a Grok pane is running, read off the composer box it prints the answer on.
+ *
+ * Grok has moved this cell twice, and the shapes it has to survive were all measured on live panes
+ * (2026-09-09):
+ *
+ * ╰──────────────────── Grok 4.6 (xhigh) ─╯ xAI's own model, with an effort
+ * ╰──── DeepSeek-V4-Flash-0731 · always-approve ─╯ a GRID model, on autonomous.ai
+ * ╰──────────── DeepSeek-V4-Flash-0731 ─╯ the same, with nothing after it
+ * Grok 4.5 (medium) · always-approve older builds' standalone footer
+ *
+ * ⚠️ **The anchor is the BOX, not the word "Grok".** Keying on the vendor's name looked safe while
+ * every model was one of xAI's, and it silently stopped being safe the moment an agent was pointed at
+ * a grid: `DeepSeek-V4-Flash-0731` matches no `Grok …` pattern, so the scan fell through the box edge
+ * and kept walking UP the pane until it reached the words "Grok 4.6, reasoning xhigh" inside the
+ * TRANSCRIPT — a sentence the model had written about itself. Measured: a pane whose edge read
+ * `DeepSeek-V4-Flash-0731` reported `grok-4.6`. Reading prose as configuration is worse than reading
+ * nothing, because the app then states the wrong model with full confidence — the exact disagreement
+ * the desktop's model pill exists to settle.
+ *
+ * So the box edge is matched FIRST and by its frame, which is a fact about the layout, and the model
+ * is whatever that cell holds. `(effort)` is optional because a grid model has none. The old
+ * standalone footer stays as a fallback for a machine on an older grok, and keeps its `Grok`-anchored
+ * shape: with no box around it, the vendor's name is the only thing proving the line is chrome rather
+ * than prose.
+ */
export function parseGrokFooterProfile(capture: string): { model: string; effort: string } | null {
const lines = capture.replace(/\u001b\[[0-9;:]*[A-Za-z]/g, '').split('\n')
+ // The composer box's bottom edge, nearest the prompt: `╰──… <model> [(effort)] [· …] ─╯`.
for (let i = lines.length - 1; i >= 0; i--) {
- const match = /\b(Grok\s+[0-9][A-Za-z0-9 ._-]*)\s+\((low|medium|high|xhigh)\)\s*[·|]/i.exec(lines[i])
+ const edge = /^\s*╰[─╌]*\s*([A-Za-z0-9][A-Za-z0-9 ._-]*?)\s*(?:\((low|medium|high|xhigh)\))?\s*(?:·[^╯]*?)?\s*[─╌]*╯\s*$/i
+ .exec(lines[i])
+ if (!edge) continue
+ return {
+ model: edge[1].trim().toLowerCase().replace(/\s+/g, '-'),
+ // A grid model carries no effort of its own, and `auto` is what the rest of the profile calls
+ // "the engine decides" — the same value pi and kilo report when their footer names no level.
+ effort: (edge[2] ?? 'auto').toLowerCase(),
+ }
+ }
+ // Older builds, which printed the cell as a line of its own with no box around it.
+ for (let i = lines.length - 1; i >= 0; i--) {
+ const match = /\b(Grok\s+[0-9][A-Za-z0-9 ._-]*?)\s+\((low|medium|high|xhigh)\)\s*(?:[·|]|$)/i
+ .exec(lines[i])
if (!match) continue
return {
model: match[1].trim().toLowerCase().replace(/\s+/g, '-'),
diff --git a/cli/src/lib/gridAssignment.spec.ts b/cli/src/lib/gridAssignment.spec.ts
index 14beaa280..329431214 100644
--- a/cli/src/lib/gridAssignment.spec.ts
+++ b/cli/src/lib/gridAssignment.spec.ts
@@ -71,6 +71,19 @@ describe('classifyGridAssignment', () => {
expect(classifyGridAssignment('codex', { GRID_API_KEY: 'gridkey-secret' })).toBeNull()
})
+ it('reads Grok\'s argv model, and reports the router as no model at all', () => {
+ const env = { GROK_MODELS_BASE_URL: RELAY_V1, GRID_API_KEY: 'gridkey-secret' }
+ expect(classifyGridAssignment('grok', env, 'grok -m DeepSeek-V4-Flash-0731'))
+ .toEqual({ baseUrl: RELAY_V1, model: 'DeepSeek-V4-Flash-0731' })
+ // ⚠️ Grok ALWAYS carries `-m`, unlike codex: its grid credential rides on a declared model block,
+ // so "let the grid route" is spelled `-m Auto` rather than by omitting the flag. Reporting that id
+ // verbatim would print `Auto` where the app prints its own Auto row from null, and
+ // `assignmentMatches` would compare 'Auto' against null and call every routed agent misplaced,
+ // forever — the same trap opencode's reader documents.
+ expect(classifyGridAssignment('grok', env, 'grok -m Auto'))
+ .toEqual({ baseUrl: RELAY_V1, model: null })
+ })
+
it('does not confuse one engine\'s knob for another\'s', () => {
// A grok agent whose OPENAI_BASE_URL happens to be set by the user's shell is not on a grid.
expect(classifyGridAssignment('grok', { OPENAI_BASE_URL: RELAY_V1 })).toBeNull()
diff --git a/cli/src/lib/gridAssignment.ts b/cli/src/lib/gridAssignment.ts
index 9e93e56fc..c0fd92933 100644
--- a/cli/src/lib/gridAssignment.ts
+++ b/cli/src/lib/gridAssignment.ts
@@ -51,7 +51,13 @@ const MODEL_VAR: Partial<Record<AgentEngine, string>> = {
copilot: 'COPILOT_MODEL',
}
-/** Engines whose model was written into argv as `-m <model>` rather than an environment variable. */
+/**
+ * Engines whose model was written into argv as `-m <model>` rather than an environment variable.
+ *
+ * Codex omits the flag when no model was picked; grok always carries one, because its grid credential
+ * rides on a declared model block and "let the grid route" is therefore spelled `-m Auto` rather than
+ * by leaving the flag off. [classifyGridAssignment] maps that id back to null.
+ */
const MODEL_IN_ARGV = new Set<AgentEngine>(['codex', 'grok'])
/**
@@ -101,6 +107,20 @@ export function classifyGridAssignment(
: MODEL_IN_ARGV.has(engine)
? ARGV_MODEL.exec(args)?.[1]
: undefined
+ // GROK ONLY, and deliberately not a rule for every engine here.
+ //
+ // Grok's launch always passes `-m`, unlike every other argv engine: its grid credential rides on a
+ // declared `[model.<id>]` block, so "let the grid route" is spelled by declaring the ROUTER rather
+ // than by omitting the flag. Reporting that id verbatim would print `Auto` where the app prints its
+ // own Auto row from null, and `assignmentMatches` would compare 'Auto' against null and call every
+ // routed grok agent misplaced, forever — the trap `readOpencodeGridAssignment` documents below.
+ //
+ // Scoped to grok because for anyone else a model literally named `Auto` is a model, and blanking it
+ // would be this function inventing a meaning the launch never gave it. Opencode reaches the same
+ // conclusion in its own reader, for its own reason; codex simply omits the flag.
+ if (engine === 'grok' && model && model.toLowerCase() === GRID_ROUTER_MODEL.toLowerCase()) {
+ return { baseUrl, model: null }
+ }
return { baseUrl, model: model || null }
}
diff --git a/cli/src/lib/gridConfigDir.ts b/cli/src/lib/gridConfigDir.ts
index dc9646ef8..2d585c0b3 100644
--- a/cli/src/lib/gridConfigDir.ts
+++ b/cli/src/lib/gridConfigDir.ts
@@ -11,10 +11,10 @@
* variable; the key itself only ever lives in the process environment.
*/
-import { mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises'
+import { lstat, mkdir, readdir, readlink, rm, stat, symlink, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { env } from '../config/env.js'
-import type { GridConfigFile } from './gridLaunch.js'
+import type { GridConfigFile, GridConfigLink } from './gridLaunch.js'
/** Everything this module owns lives under one root, so pruning can be confident about what it is. */
export function gridConfigRoot(): string {
@@ -45,13 +45,45 @@ async function prune(root: string): Promise<void> {
}))
}
+/**
+ * Link `name` in this agent's directory at `target`, so a redirected home can borrow one directory
+ * back from the real one.
+ *
+ * Grok is the case: `GROK_HOME` moves its WHOLE state directory, and `sessions/` has to keep landing
+ * where the daemon reads transcripts — see `GROK_GRID_HOME_LINKS`. A link rather than a copy because
+ * the point is that the engine writes through it, live.
+ *
+ * Never fatal. A machine that cannot make the link (a target that does not exist yet, a filesystem
+ * that will not) still gets an agent — one whose sessions land in the private directory, which costs
+ * the harness that agent's transcript but does not cost the launch. Refusing here would trade a
+ * degraded agent for no agent at all.
+ */
+async function linkInto(dir: string, name: string, target: string): Promise<void> {
+ const path = join(dir, name)
+ // A rewrite is the normal case (an agent moved between grids), and `symlink` will not overwrite.
+ // Only ever a link is removed — a real directory here would be the engine's own state, and
+ // deleting that is not this function's business.
+ const existing = await lstat(path).catch(() => null)
+ if (existing?.isSymbolicLink()) {
+ if (await readlink(path).catch(() => null) === target) return
+ await rm(path, { force: true }).catch(() => {})
+ } else if (existing) {
+ return
+ }
+ await symlink(target, path, 'dir').catch(() => {})
+}
+
/**
* Write `files` into this agent's own directory and return its path.
*
* Rewriting is the normal case, not an error: moving an agent to a different grid writes the same
* directory again with the new provider, which is exactly what a respawn should read.
*/
-export async function writeGridConfigDir(key: string, files: readonly GridConfigFile[]): Promise<string> {
+export async function writeGridConfigDir(
+ key: string,
+ files: readonly GridConfigFile[],
+ links: readonly GridConfigLink[] = [],
+): Promise<string> {
const root = gridConfigRoot()
const dir = join(root, safeKey(key))
await mkdir(dir, { recursive: true, mode: 0o700 })
@@ -60,5 +92,8 @@ export async function writeGridConfigDir(key: string, files: readonly GridConfig
for (const file of files) {
await writeFile(join(dir, file.name), file.content, { mode: 0o600 })
}
+ for (const link of links) {
+ await linkInto(dir, link.name, link.target)
+ }
return dir
}
diff --git a/cli/src/lib/gridLaunch.spec.ts b/cli/src/lib/gridLaunch.spec.ts
index 49379748d..56a37730f 100644
--- a/cli/src/lib/gridLaunch.spec.ts
+++ b/cli/src/lib/gridLaunch.spec.ts
@@ -139,10 +139,34 @@ describe('the launch each engine gets', () => {
expect(launchOf('opencode').env).toEqual({ GRID_API_KEY: WIRE.apiKey })
})
- it('uses xAI\'s model-list base for Grok, with the model on the command line', () => {
+ it('declares the model for Grok, because the documented variable pair loses to its session token', () => {
+ // `GROK_MODELS_BASE_URL` + `XAI_API_KEY` is the pair Grok documents, and it is not enough:
+ // `XAI_API_KEY` is LAST in Grok's credential order, behind the OIDC session token that a private
+ // GROK_HOME still acquires. Measured on a live pane — `auth_mode=Oidc`, `remedy=ManualLogin`, and
+ // "Authentication required" in the pane — while the relay answered 200 to the same key by curl.
+ // Declaring the model with `env_key` moves the grid key above the session token.
const launch = launchOf('grok')
- expect(launch.env).toEqual({ GROK_MODELS_BASE_URL: RELAY_V1, XAI_API_KEY: WIRE.apiKey })
+ expect(launch.env).toEqual({
+ GROK_MODELS_BASE_URL: RELAY_V1,
+ XAI_API_KEY: WIRE.apiKey,
+ GRID_API_KEY: WIRE.apiKey,
+ })
expect(launch.args).toEqual(['-m', 'GLM-4.7-Flash'])
+ // The config is written whether or not there are web tools: it is the credential that needs it.
+ const config = launch.configDir?.files.find((f) => f.name === 'config.toml')?.content ?? ''
+ expect(config).toContain('[model."GLM-4.7-Flash"]')
+ expect(config).toContain('env_key = "GRID_API_KEY"')
+ expect(config).toContain(`base_url = "${RELAY_V1}"`)
+ })
+
+ it('gives Grok a config even with no web tools to declare', () => {
+ // It used to write one only for MCP servers, on the reasoning that a launch with nothing to
+ // configure should leave the user's ~/.grok alone. That left the credential on the losing side of
+ // Grok's resolution order, so a grid agent authenticated as the user's own xAI login.
+ const launch = launchOf('grok', { ...WITH_MODEL, mcpUrl: undefined })
+ const config = launch.configDir?.files.find((f) => f.name === 'config.toml')?.content ?? ''
+ expect(config).toContain('env_key = "GRID_API_KEY"')
+ expect(config).not.toContain('mcp_servers')
})
it('uses the documented BYOK trio for Copilot', () => {
@@ -213,7 +237,6 @@ describe('the launch each engine gets', () => {
expect(launchOf('claude', OVERRIDE).env).not.toHaveProperty('ANTHROPIC_MODEL')
expect(launchOf('hermes', OVERRIDE).env).not.toHaveProperty('HERMES_INFERENCE_MODEL')
expect(launchOf('hermes', OVERRIDE).args).toEqual([])
- expect(launchOf('grok', OVERRIDE).args).toEqual([])
expect(launchOf('codex', OVERRIDE).args).not.toContain('-m')
})
@@ -221,6 +244,19 @@ describe('the launch each engine gets', () => {
const built = buildGridEngineLaunch('copilot', OVERRIDE)
expect(built).toMatchObject({ ok: false, error: 'GRID_MODEL_REQUIRED' })
})
+
+ it('declares the router for Grok when the user picked no model, rather than refusing', () => {
+ // The credential rides on a declared model block, so SOMETHING has to be named — but that is the
+ // contract's problem, not a question to put back to the user. `Auto` is the New Agent dialog's
+ // default, and refusing it would turn the common path into a wall at the moment of clicking
+ // Create. The relay serves the router id like any other model, and Grok launched against
+ // `[model."Auto"]` answered through it with no probe and no 401.
+ const launch = launchOf('grok', OVERRIDE)
+ expect(launch.args).toEqual(['-m', 'Auto'])
+ const config = launch.configDir?.files.find((f) => f.name === 'config.toml')?.content ?? ''
+ expect(config).toContain('[model."Auto"]')
+ expect(config).toContain('env_key = "GRID_API_KEY"')
+ })
})
describe('the engines that cannot', () => {
diff --git a/cli/src/lib/gridLaunch.ts b/cli/src/lib/gridLaunch.ts
index 2cfe62ae2..fbc4349cd 100644
--- a/cli/src/lib/gridLaunch.ts
+++ b/cli/src/lib/gridLaunch.ts
@@ -45,6 +45,10 @@ import {
codexMcpArgs,
GRID_MCP_AUTH_VAR,
GRID_MCP_SERVER_NAME,
+ GROK_CONFIG_FILE,
+ GROK_GRID_HOME_LINKS,
+ GROK_HOME_VAR,
+ grokGridConfig,
HERMES_MANAGED_CONFIG_FILE,
HERMES_MANAGED_DIR_VAR,
hermesManagedConfig,
@@ -56,6 +60,19 @@ function userPiSkillsDir(): string {
return join(homedir(), '.pi', 'agent', 'skills')
}
+/**
+ * Grok's real state directory — the one a private [GROK_HOME_VAR] borrows `sessions/` from.
+ *
+ * `homedir()` rather than the daemon's own `env.GROK_HOME`, deliberately and for the reason stated
+ * beside [HERMES_SYSTEM_MANAGED_DIR]: a contract that reads process configuration answers
+ * differently depending on who launched it. The two agree in every deployment that matters — the
+ * daemon's `GROK_HOME` defaults to exactly this — and a machine that has moved it has moved the
+ * transcripts the daemon reads too, which is a question for the caller, not for a pure contract.
+ */
+function userGrokHome(): string {
+ return join(homedir(), '.grok')
+}
+
/** What the desktop sends, once validated. Mirrors `GridAgentOverride` in the desktop app. */
export interface GridLaunchOverride {
networkId: string
@@ -287,6 +304,20 @@ function opencodeGridConfig(
}, null, 2)}\n`
}
+/**
+ * One directory the per-agent config directory borrows from elsewhere, as a symlink.
+ *
+ * For an engine whose variable redirects its WHOLE home rather than just its provider config: the
+ * private directory has to hand back the parts the daemon still reads. Grok is the only such engine
+ * — see `GROK_GRID_HOME_LINKS` in `gridWebMcp.ts`.
+ */
+export interface GridConfigLink {
+ /** Name inside the per-agent directory. Never a path. */
+ name: string
+ /** Absolute path the link points at — the user's real directory. */
+ target: string
+}
+
/** One file to write into the per-agent config directory a launch is given. */
export interface GridConfigFile {
/** File name inside the directory. Never a path — this writes one flat directory. */
@@ -321,6 +352,14 @@ export interface GridEngineLaunch {
* engine is handed, so it is a field rather than a second writer.
*/
pointAt?: string
+ /**
+ * Directories the private one borrows back from the engine's real home.
+ *
+ * Only for a variable that redirects a whole home: `GROK_HOME` takes `sessions/` with it, and the
+ * daemon reads transcripts from the real one. Empty for every engine whose variable names only a
+ * provider config, which is the usual case.
+ */
+ links?: GridConfigLink[]
}
}
@@ -384,6 +423,7 @@ export const GRID_CONFLICTING_ENV_VARS: readonly string[] = [
GRID_KEY_VAR,
GRID_MCP_AUTH_VAR,
HERMES_MANAGED_DIR_VAR,
+ GROK_HOME_VAR,
]
/**
@@ -606,16 +646,75 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
// xAI's own Grok CLI (the one this repo discovers under `~/.grok`, whose transcripts carry the
// `_x.ai/session/update` method). Its docs: "Grok fetches the model list from {base_url}/models",
- // and "when you set models_base_url, Grok uses API key auth instead of session auth" — which is
- // exactly the swap being asked for here. The model has no documented variable, so it goes in argv.
+ // and "when you set models_base_url, Grok uses API key auth instead of session auth" — the second
+ // half of which does NOT hold in practice: measured, the variable moves where requests go but not
+ // which credential is picked, and the session token still wins. See `grokGridConfig`. The model has
+ // no documented variable, so it goes in argv AND into the config block that carries the credential.
+ //
+ // Its web tools cost it a private home. Grok reads `[mcp_servers]` from its config file and takes
+ // no flag for them, and the only layer that both starts unattended and is not the user's own file
+ // is `$GROK_HOME/config.toml` — the project layer is gated on a folder-trust prompt nobody is
+ // there to answer, and `CLAUDE_CONFIG_DIR` does not move MCP discovery at all. See `gridWebMcp.ts`,
+ // which measured each of them.
+ //
+ // ⚠️ `GROK_HOME` moves the WHOLE state directory, `sessions/` included — and for grok that is not
+ // cosmetic: `cli.ts` drops an observed grok agent entirely when it can find no transcript, so an
+ // un-borrowed home would launch an agent the harness never registers. The directory is linked back
+ // rather than moved; [GROK_GRID_HOME_LINKS] says which, and why the list stops where it does.
+ //
+ // ⚠️ The private home is NOT optional, and the reason is the credential order rather than the web
+ // tools. `XAI_API_KEY` is the LAST thing Grok reaches for — behind the OIDC session token — so an
+ // agent launched with the documented variable pair alone authenticates as the user's own xAI login
+ // and the relay answers 401. The config block declares the model with `env_key`, which outranks the
+ // session token; `grokGridConfig` carries the measurement. So every grid launch writes a config,
+ // web tools or not, and the user's own `~/.grok` is still never opened.
grok: {
- build: (override) => ({
- env: {
- GROK_MODELS_BASE_URL: relayBaseUrl(override.baseUrl),
- XAI_API_KEY: override.apiKey,
- },
- args: override.model ? ['-m', override.model] : [],
- }),
+ // Deliberately NOT `requiresModel`. The credential rides on a declared model block, so a launch
+ // does need SOME model named — but that is this contract's problem to solve, not a question to
+ // put back to the user. No model picked means the grid routes, and the relay serves its router id
+ // like any other model (verified: `{"model":"Auto"}` → 200, answered by DeepSeek-V4-Flash-0731),
+ // so `Auto` is what the block declares. Verified end to end: Grok launched against `[model."Auto"]`
+ // with `env_key` answered a prompt through the router with `auth_mode=null` and no probe.
+ //
+ // Making this `requiresModel` was the first fix here and it was the wrong one: it turned "Auto",
+ // the default the New Agent dialog shows, into a refusal at the moment of clicking Create —
+ // trading a 401 the user could not diagnose for a wall they could not get past. Same trade
+ // OpenCode faced, same answer (see `GRID_ROUTER_MODEL` in its contract above).
+ build: (override) => {
+ // One name, used in three places that must agree: argv, the config block's header, and the
+ // `model` field inside it. A mismatch would declare a credential for a model Grok never asks for.
+ const model = override.model ?? GRID_ROUTER_MODEL
+ return {
+ env: {
+ GROK_MODELS_BASE_URL: relayBaseUrl(override.baseUrl),
+ // Kept even though the config below is what actually wins. It is the documented pair for a
+ // custom endpoint, it is what `gridAssignment.ts` reads back, and on a build whose config
+ // layer we have misjudged it is still the credential Grok would reach for last.
+ XAI_API_KEY: override.apiKey,
+ // Referenced by `env_key` in the config, which is always written — so this always is too.
+ [GRID_KEY_VAR]: override.apiKey,
+ },
+ args: ['-m', model],
+ // ⚠️ ALWAYS a config directory now, web tools or not. It used to be written only when there
+ // were MCP servers to declare, on the reasoning that a launch with nothing to configure should
+ // leave the user's `~/.grok` alone — but the credential order (see `grokGridConfig`) means the
+ // config is what makes the grid key win over the OIDC session token. Without it a grid agent
+ // authenticates as the user's xAI login and the relay answers 401.
+ configDir: {
+ envVar: GROK_HOME_VAR,
+ files: [{
+ name: GROK_CONFIG_FILE,
+ content: grokGridConfig(
+ override.mcpUrl,
+ GRID_KEY_VAR,
+ model,
+ relayBaseUrl(override.baseUrl),
+ ),
+ }],
+ links: GROK_GRID_HOME_LINKS.map((name) => ({ name, target: join(userGrokHome(), name) })),
+ },
+ }
+ },
},
// Pi reads its providers out of a config DIRECTORY, and `PI_CODING_AGENT_DIR` moves that
diff --git a/cli/src/lib/gridWebMcp.ts b/cli/src/lib/gridWebMcp.ts
index 0ab29248a..0a060a23d 100644
--- a/cli/src/lib/gridWebMcp.ts
+++ b/cli/src/lib/gridWebMcp.ts
@@ -30,6 +30,7 @@
* * opencode expands `{env:VAR}` in `headers`, in the config file the launch already writes it.
* * Copilot CLI expands `${VAR}` too, in the same JSON-string form, behind
* `--additional-mcp-config`.
+ * * Grok expands `${VAR}` in `headers` too, in the config file its private home already needs.
*
* Measured 2026-09-08 against a header-logging listener on loopback — Claude Code 2.1.263, Codex
* 0.144.6, opencode 1.18.29, the first two being the versions ADR 0041 itself measured — and Copilot
@@ -171,3 +172,126 @@ export function hermesManagedConfig(mcpUrl: string, keyVar: string): string {
},
}, null, 2)}\n`
}
+
+/**
+ * Grok's config directory, which is also the only lever it offers for MCP servers.
+ *
+ * Grok reads `[mcp_servers]` from three layers — `$GROK_HOME/config.toml`, then `.grok/config.toml`
+ * walked from the repo root down to the cwd — and offers no per-invocation flag for them at all:
+ * `grok --help` has no `--mcp-config`, and the binary contains no such string. Every other route was
+ * measured against grok 1.0.24 and rejected on evidence rather than on reading:
+ *
+ * * **Project scope (`.grok/config.toml`) is what the docs steer you to, and it does not start.**
+ * A repo-local server is gated on folder trust — `grok mcp doctor` answers "folder untrusted
+ * (repo-local (project-scoped) server not started for an untrusted folder)" and the server never
+ * runs. An agent the desktop launches has nobody to click through that, which is the same reason
+ * this file exists at all. It would also write into the USER'S repo, and a project layer
+ * *replaces* a same-named global server outright rather than merging with it.
+ * * **`CLAUDE_CONFIG_DIR` does not redirect MCP discovery.** Grok does read `~/.claude.json` for
+ * servers, so the variable looks like the seam — but it is not consulted for that. Pointed at a
+ * directory holding a `.claude.json` with this very server, `grok mcp list` reported none, and in
+ * the binary the string sits among session-import fields (`isSidechain`, `rollout_path`), not
+ * config paths. `GROK_CONFIG`, `GROK_CONFIG_PATH` and `GROK_MANAGED_CONFIG` were each tried as a
+ * file and as a directory: none of them moved a server either.
+ *
+ * So it is `GROK_HOME`, which the launch already owns a private directory for — and which comes with
+ * one consequence that has to be paid rather than ignored. See [grokGridHomeLinks].
+ *
+ * Measured 2026-09-09 against the same header-logging listener on loopback as the harnesses above:
+ * with a user-scope server in a private `GROK_HOME`, Grok started it with no trust prompt and sent
+ * `Authorization: Bearer <the variable's value>` on every request.
+ */
+export const GROK_HOME_VAR = 'GROK_HOME'
+
+/** The one file [GROK_HOME_VAR] is written for here. */
+export const GROK_CONFIG_FILE = 'config.toml'
+
+/**
+ * The directories a private [GROK_HOME_VAR] must borrow back from the user's real one.
+ *
+ * `GROK_HOME` moves Grok's whole state directory, and `sessions/` is in it — which for this repo is
+ * not a cosmetic loss. The daemon resolves transcripts under its OWN `env.GROK_HOME` (`cli.ts`,
+ * `findGrokTranscript`), and for grok specifically a missing transcript means the agent is never
+ * registered at all — `cli.ts` returns early on `!transcriptPath` for cursor and grok. A grid-launched
+ * Grok agent under an un-borrowed home would therefore write its session somewhere the harness does
+ * not look, and go invisible: no transcript, no resume, no session repair.
+ *
+ * Symlinking the directory back is what keeps the two halves pointing at one place. Verified by
+ * running Grok headless under such a home: the session landed in the real `~/.grok/sessions/<encoded
+ * cwd>/`, which is exactly where `findGrokTranscript` reads.
+ *
+ * Deliberately a SHORT list rather than "everything but config.toml". Each entry is state this repo
+ * or the user would miss, and a link that turns out to be unnecessary costs nothing, while inventing
+ * links for Grok's caches would be this module guessing at another program's internals — the thing
+ * its refusals exist to avoid. `auth.json` is NOT here on purpose: a grid launch authenticates with
+ * `XAI_API_KEY`, so borrowing the user's xAI credential would hand a grid agent a login it was
+ * deliberately not given.
+ */
+export const GROK_GRID_HOME_LINKS: readonly string[] = ['sessions']
+
+/**
+ * Grok's user-scope config: the grid model, and — when there are any — the grid's web tools.
+ *
+ * TOML rather than JSON because this is the only format Grok reads here. Values are JSON-encoded,
+ * which is valid TOML for a string and gets the escaping right for free.
+ *
+ * ## Why the model block is not optional
+ *
+ * `GROK_MODELS_BASE_URL` + `XAI_API_KEY` looks like the whole contract — Grok's own docs present the
+ * pair that way — but it only redirects WHERE requests go, not WHICH credential is chosen. Grok's
+ * documented resolution order is:
+ *
+ * api_key → env_key → auth_provider → session token → XAI_API_KEY
+ *
+ * `XAI_API_KEY` is LAST, behind the OIDC session token. A private `GROK_HOME` still ends up with an
+ * `auth.json` (Grok writes one on first run, and the desktop's own login flows put one there), so the
+ * session token outranks the grid key and every request goes out signed as the user's xAI login —
+ * which the relay rejects.
+ *
+ * Measured on a live pane (2026-09-09, grok 1.0.24) that had been moved onto the autonomous.ai grid:
+ *
+ * auth: first-party API key probe verdict=Unusable elapsed_ms=351 timeout_ms=400
+ * auth 401 attribution … consumer=OaiCompatClient auth_mode=Oidc remedy=ManualLogin
+ *
+ * — and the pane printed "Authentication required: your session has expired". The probe is Grok
+ * asking `api.x.ai` whether the key is one of ITS keys; a grid JWT is not, so it answers 400 in
+ * ~380ms and Grok files the key as unusable. The failure is therefore also a RACE: on a slower link
+ * the same probe exceeds its own 400ms timeout, comes back `Unknown`, and Grok keeps the key and
+ * works. Two panes launched minutes apart on one machine disagreed for exactly this reason
+ * (402ms → `Unknown`, worked; 351ms → `Unusable`, 401), which is what made this look intermittent.
+ *
+ * Declaring the model with `env_key` moves the grid key from last place to SECOND, above the session
+ * token, so the choice no longer depends on a probe or on whether an `auth.json` happens to exist.
+ * The key is still only referenced — `env_key` names the variable; nothing secret is written here.
+ *
+ * [model] may be the relay's ROUTER id rather than a real model, and that is a supported case rather
+ * than a degraded one: the relay answers `Auto` like any other id, so a user who picked no model gets
+ * a block declaring the router and the grid keeps choosing per request. Verified end to end — Grok
+ * under `[model."Auto"]` answered through the router with `auth_mode=null` and no probe. What must
+ * NOT happen is no block at all: that is the path back to the session token and the 401.
+ *
+ * ⚠️ The MCP server name keeps its HYPHEN, as it does for Codex and for the same reason — Grok
+ * namespaces MCP tools as `<server>__<tool>`, so renaming it here would rename its tools too.
+ *
+ * The MCP key is referenced the same way: Grok interpolates `${VAR}` in `headers` against the process
+ * environment, measured on the wire.
+ */
+export function grokGridConfig(
+ mcpUrl: string | undefined,
+ keyVar: string,
+ model: string,
+ baseUrl: string,
+): string {
+ // The model block first: it is what makes the launch authenticate at all, so a config that carried
+ // only web tools would be a pane with tools it cannot reach.
+ let config = `[model.${JSON.stringify(model)}]\n`
+ + `model = ${JSON.stringify(model)}\n`
+ + `base_url = ${JSON.stringify(baseUrl)}\n`
+ + `env_key = ${JSON.stringify(keyVar)}\n`
+ if (mcpUrl) {
+ config += `\n[mcp_servers.${GRID_MCP_SERVER_NAME}]\n`
+ + `url = ${JSON.stringify(mcpUrl)}\n`
+ + `headers = { Authorization = ${JSON.stringify(`Bearer \${${keyVar}}`)} }\n`
+ }
+ return config
+}
diff --git a/cli/src/lib/runtimeProfileController.spec.ts b/cli/src/lib/runtimeProfileController.spec.ts
index 99eb504ec..6c675431c 100644
--- a/cli/src/lib/runtimeProfileController.spec.ts
+++ b/cli/src/lib/runtimeProfileController.spec.ts
@@ -110,6 +110,39 @@ describe('runtime pane parsing', () => {
].join('\n'))).toMatchObject({ idle: false })
})
+ it('reads grok past the right-hand edge of its own composer box', () => {
+ // Measured on a live pane (`harness-grok-*`, grok 4.6, 2026-09-09) with NOTHING typed into it.
+ // The shared reader takes everything after `❯` and finds the box's closing `│`: one character,
+ // non-empty, so `draft` was true on an empty composer. Not a transient — that edge is drawn on
+ // every frame, so `idle` was false for the agent's whole life and every model switch came back
+ // AGENT_BUSY. Same family as the hermes and opencode cases above; here the culprit is the box.
+ const W = 60
+ const box = (composer: readonly string[]) => [
+ ' ╭' + '─'.repeat(W) + '╮',
+ ...composer.map((line) => ' │ ' + line.padEnd(W - 2) + '│'),
+ ' ╰' + '─'.repeat(W - 20) + ' Grok 4.6 (xhigh) ─╯',
+ '',
+ // The footer separator is also `│`, and it sits below the box. A body line must carry BOTH
+ // edges, which this — one separator, no edges — never does.
+ ' Shift+Tab:mode │ Ctrl+x:shortcuts',
+ ].join('\n')
+
+ expect(inspectRuntimePane('grok', box(['❯']))).toMatchObject({ idle: true, draft: false })
+ expect(inspectRuntimePane('grok', box(['❯ fix the parser']))).toMatchObject({ idle: false, draft: true })
+ // Wrapped text counts wherever in the box it sits — the marker is only on the first row.
+ expect(inspectRuntimePane('grok', box(['❯ a very long message', ' that wrapped down'])))
+ .toMatchObject({ idle: false, draft: true })
+ // An earlier box still in scrollback is a message already SENT, not a draft.
+ expect(inspectRuntimePane('grok', [box(['❯ what is an LSP']), 'answer text', box(['❯'])].join('\n')))
+ .toMatchObject({ idle: true, draft: false })
+ // A picker over the pane is not something to respawn under, empty composer or not.
+ expect(inspectRuntimePane('grok', box(['❯']) + '\n Select Model and Effort'))
+ .toMatchObject({ idle: false, dialog: true })
+ // A layout with no recognisable box is "we cannot tell", which the caller reads as busy. Refusing
+ // a switch costs a retry; respawning a pane we misread would discard whatever was in it.
+ expect(inspectRuntimePane('grok', ' │ ❯ fix the parser')).toMatchObject({ idle: false })
+ })
+
it('does not read a truecolor foreground as a dim placeholder', () => {
// `38;2;<r>;<g>;<b>` carries a literal 2 that is a colour-space selector, not the dim attribute.
// Counting it would make a line the user had TYPED look like an empty composer — the one
diff --git a/cli/src/lib/runtimeProfileController.ts b/cli/src/lib/runtimeProfileController.ts
index 3e46487e6..1002c3e39 100644
--- a/cli/src/lib/runtimeProfileController.ts
+++ b/cli/src/lib/runtimeProfileController.ts
@@ -145,6 +145,7 @@ export function inspectRuntimePane(engine: RegisteredSession['engine'], capture:
if (engine === 'pi') return inspectPiPane(capture)
if (engine === 'opencode') return inspectGutterBoxPane(capture, true)
if (engine === 'copilot') return inspectGutterBoxPane(capture, false)
+ if (engine === 'grok') return inspectGrokPane(capture)
const rawLines = capture.split('\n')
const marks = promptMarker(engine)
const promptIndex = rawLines.findLastIndex((line) => {
@@ -242,6 +243,54 @@ function inspectGutterBoxPane(capture: string, hasStatusStrip: boolean): PaneIns
*/
const PI_FOOTER_BUDGET = /\d+(?:\.\d+)?%\s*\/\s*\S+/
+/**
+ * Grok draws its composer as a ROUNDED BOX, and the generic reader counts the box's own right edge
+ * as something the user typed.
+ *
+ * Its empty composer is one line — `│ ❯` … padding … `│` — inside `╭─…─╮` above and
+ * `╰─… Grok 4.6 (xhigh) ─╯` below. The shared reader takes everything after `❯`, strips ANSI, trims,
+ * and finds `│`: one character, non-empty, so `draft` was true. Measured on a real pane
+ * (`harness-grok-*`, 2026-09-09) with nothing typed into it: `visible after marker = "│"`, `draft =
+ * true`, `idle = false`. Not a transient — the edge is drawn on every frame, so idle was false for
+ * the agent's whole life and EVERY model switch came back AGENT_BUSY over an empty prompt. Same
+ * family as the hermes and gutter-box bugs above; here the culprit is the box, not the placeholder.
+ *
+ * So the composer is the box's INTERIOR: the run of `│` body lines, read between their first and
+ * last `│` rather than from the marker to end-of-line. Every body line is checked, not just the one
+ * carrying `❯` — a long message wraps down the box and reading one line of it would call a full
+ * composer empty.
+ *
+ * ⚠️ `│` is also Grok's footer separator (`Shift+Tab:mode │ Ctrl+x:shortcuts`), which sits BELOW the
+ * box. It is excluded by requiring a body line to both open and close with `│`, which the footer —
+ * one separator, no edges — never does.
+ */
+function inspectGrokPane(capture: string): PaneInspection {
+ const rawLines = capture.split('\n')
+ const visibleLines = rawLines.map((line) => stripAnsi(line).replace(/ /g, ' '))
+ // The LAST box in the capture. Earlier ones are composers already sent, still in scrollback.
+ const bottom = visibleLines.findLastIndex((line) => /^\s*╰[─╌]*.*╯\s*$/u.test(line))
+ const top = bottom < 0
+ ? -1
+ : visibleLines.slice(0, bottom).findLastIndex((line) => /^\s*╭[─╌]+╮\s*$/u.test(line))
+ // No recognisable box is "we cannot tell", which the caller reads as busy — the safe direction.
+ // Respawning a pane whose layout we do not understand could discard a draft.
+ if (top < 0 || bottom - top < 2) return { idle: false, plan: false, dialog: false, draft: false }
+ const currentUi = visibleLines.slice(top).join('\n')
+ const dialog = DIALOG_UI.test(currentUi)
+ const draft = rawLines.slice(top + 1, bottom).some((line, offset) => {
+ const visible = visibleLines[top + 1 + offset]
+ const first = visible.indexOf('│')
+ const last = visible.lastIndexOf('│')
+ // Both edges, and not the same character: anything else is not a body line of this box.
+ if (first < 0 || last <= first) return false
+ const rawMarker = line.search(/[›❯]/u)
+ if (rawMarker >= 0 && hasPlaceholderSgr(line.slice(rawMarker + 1))) return false
+ // The marker is chrome, not content — it is printed whether or not anything was typed.
+ return visible.slice(first + 1, last).replace(/[›❯]/u, '').trim().length > 0
+ })
+ return { idle: !dialog && !draft, plan: /\bplan mode on\b/i.test(currentUi), dialog, draft }
+}
+
/**
* Pi draws no composer marker, so idleness is read from its layout instead: the composer is the band
* between the last two `───` rules, and the footer (`minimax/minimax-m3 • high`) is only rendered by the