Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(grok): per-launch model override through the base harness mapping

Xavi Guardia3753f10a566b
diff --git a/docs/grok-agent.md b/docs/grok-agent.md
index ee6bd5580..94e99e916 100644
--- a/docs/grok-agent.md
+++ b/docs/grok-agent.md
@@ -43,6 +43,7 @@ is the cost of adding the next agent to the same list.
| `CANVAS_CONTROL_CAPABLE` | **joined** | Nothing new to install: grok scans `~/.claude/skills` by default for Claude Code compatibility, which is exactly where `manage-nodeterm-canvas` is already written (locally, and on an SSH host by `RemoteHooks.installCanvasControl`). Membership is what sets `NODETERM_CANVAS_CONTROL=1` in the session env — `hook-server.buildPtyEnv` locally, `remoteHookEnvArgs` remotely, both through the single `canControlCanvas` predicate — i.e. what makes the sh+curl shim anything other than a no-op. **The discovery premise is MEASURED, not inferred** (grok 1.0.13, 2026-09-02): `grok inspect --json` lists `manage-nodeterm-canvas` and `get-linked-context` with `vendor: claude` and `compatibilityStatus: enabled`, and `externalCompat.cells` reports `{surface: 'skills', enabled: true, source: 'default'}`. `source: 'default'` is the part that matters: grok reads `~/.claude/skills` with **no** config edit by the user. Two per-user failure modes survive the measurement and cannot be exercised on a default-config machine — `[compat.claude] skills = false` in `~/.grok/config.toml`, and `GROK_CLAUDE_SKILLS_ENABLED=false`. In each, `NODETERM_CANVAS_CONTROL=1` is still set while the skill is undiscoverable: the shim is armed and mute. See §8.7 and checklist 21. |
| `USAGE_CAPABLE` (the per-node context meter) | **joined** | `signals.json` yields both numbers AND the answer: `contextTokensUsed`, `contextWindowTokens` and `contextWindowUsage` — the percentage grok has already computed. Measured on 22 real sessions (1.0.13, 2026-09-02): all three present in all 22, and the stated percentage agrees with used/window in all 22, which is a free oracle and is pinned as a test. The window is READ, never inferred from the model id, putting grok with codex rather than with gemini. The reader (`core/grok-signals.ts`) takes three of the file's 66 keys and returns null unless both numbers are there — no denominator, no meter. Its tail is created with `wholeFile`, because signals.json is rewritten in place rather than appended to; an offset read would hand the parser a JSON fragment and the meter would freeze after its first fill with nothing to say so. The rule this row used to state still holds for everyone: a percentage against a guessed denominator is a wrong number presented as a fact, so no total ⇒ no meter. (The list is now `claude, codex, gemini, grok`; **opencode** is the one builtin outside it. Codex states its own denominator in its rollout; gemini's comes from its model id through `geminiWindowFor`, mirroring the CLI's own `tokenLimit`. See `docs/gemini-agent.md` §4.) **The trap this row used to warn about was real and is now disarmed:** joining this list also switched on two features that read CLAUDE's transcript, because `readsClaudeTranscript` shared a list with them — a codex node once metered and searched a stranger's claude session that way. That gate now reads `CLAUDE_TRANSCRIPT_READABLE` (claude only), pinned in `config.capabilities.test.ts`, so grok joins the meter without joining those. Do not confuse this with grok *billing* usage — see the note below. |
| `CONTEXT_LINK_CAPABLE` | **joined** | Two pieces, both pinned by fixtures cut from real sessions rather than written from the docs: `linesFromGrok` (`core/context-link-render.ts`) renders grok's log, and `locateGrok` (`core/handoff/locate.ts`) finds it. The file is **`chat_history.jsonl`, not the `updates.jsonl`** this row used to name and grok's own hook payloads advertise — routing through the advertised path fails **silently**, handing the reader an empty transcript with nothing logged, which is why the locator pins it. The directory comes from the hook-fed `sessionId → dir` map, never from a scan. The path jail was widened to `$GROK_HOME/sessions` — that subdirectory, not `$GROK_HOME`, because `auth.json` lives in the same tree. Grok is no longer outside this list; the list is now `claude, codex, gemini, opencode, grok`, and the one builtin still outside it is **copilot**. |
+| `MODEL_SWITCH_CAPABLE` | **joined** | The whole capability is the leaf in `shared/agents/model-gateway.ts`; no frontend spells a grok model id or the string `grok`. **Discovery has no allowlist:** `grok models` lists the CLI's own catalogue (`grok-4.6`, `grok-4.5` on 1.0.13), parsed by `grokModelsFrom` from a captured fixture, so a model shipped tomorrow appears with no code change. Only the indented bullets are read — the `Default model:` line is prose that repeats an id, and treating prose as data is how a banner becomes a fake model. Unparseable output ⇒ EMPTY list ⇒ no model switching, the pre-feature behaviour. **grok is offered its OWN models, never the gateway's,** and that is correctness rather than taste: grok cannot be routed through the gateway at all, so the gateway catalogue would put ids on the menu that grok rejects at launch — a picker that looks like it worked and kills the node. **It needs no new environment,** which is the part worth stating rather than omitting: grok's custom models are declared in `~/.grok/config.toml` with their own `base_url`/`api_key`, and `11-custom-models.md` says explicitly that `model`/`base_url`/`api_key` CANNOT be defaulted from the environment. So `modelGatewayEnv` returns `{}` for grok on purpose. Writing into the user's `config.toml` to route grok through the gateway is a real feature and a separate decision. The flag is `-m/--model`, emitted **before** the `--` separator — after it, grok swallows it into the prompt and the node launches on the default model while the agent reads the flag as its first instruction. `--reasoning-effort` exists and is deliberately NOT part of this. |
| `SUBAGENT_CAPABLE` | **not joined** | Needs the `spawn_subagent` `PreToolUse`/`PostToolUse` payload fields, including whatever marks a **background** launch. Task 11 stops at its capture step. |
| `BRANCH_CAPABLE` | not joined | Branch sends claude's `/branch` and resumes by claude's session id; grok has no counterpart. |
| `CHAT_CAPABLE` | **joined**, and the list was SPLIT to do it safely | `chatMessagesFromGrok` (`core/grok-chat.ts`) builds the panel's bubbles from the same `grokParse` the context-link reader uses, so the two views of one file cannot drift. The channel is now routed by agent (`chat:read-transcript` takes an `agentId`), and that routing is the safety property, not a refinement: claude's `resolveTranscript` falls back to **the newest claude transcript for the node's cwd** whenever its sessionId leg misses, which a grok id always does — so an unrouted grok node is answered with a stranger's conversation rather than with nothing. **The list itself had to be split.** `CHAT_CAPABLE` carried two facts that coincided only while claude was its sole member: "we can render this agent's conversation" and "claude's resolver can locate and parse this agent's file". Grok is the first agent for which they differ, so the second now lives in `CLAUDE_TRANSCRIPT_READABLE` (claude only), which is what `renderer/lib/transcriptGates.ts` reads. Merging them back is a cross-session read of someone else's transcript, and it fails OPEN — it shows data. `config.capabilities.test.ts` pins the pair. |
@@ -376,6 +377,7 @@ ai-name / comments).
| Cross-agent transfer (grok as SOURCE) | **yes** — `renderGrokTranscript` | **N/A** — `buildHandoff` lives in `src/main`; the Server Edition has no transfer path at all, pre-existing and unchanged by grok | N/A |
| Context meter | **yes** — a third tail, on `signals.json` rather than on a transcript, tracked from the session directory the hooks let us derive (there is no hook field pointing at it) | **yes** — both shells create the same tail the same way, with the same `wholeFile` flag. Invariant 11: a tail added in one shell only is a meter the Server Edition silently lacks | the phone reads the mirror, which is agent-agnostic, so the numbers arrive with no phone-side work |
| Session-id minting | **yes** — probed at boot (`ensureGrokCliCaps`), minted at node creation, checked against the ids already on disk for that cwd | **yes** — `registerGrokCliIpc` runs in this shell too, so the browser gets the same answer over WS-RPC. A probe registered in one shell only is minting that silently works on the desktop and not in the browser | N/A — the phone launches nothing (see §8) |
+| Model switch | **yes** — discovered from `grok models` through the same memoized CLI probe the session-id flag rides | **yes** — `registerGrokCliIpc` runs in this shell too, so the browser gets the same catalogue over WS-RPC | N/A — the phone launches nothing |
| Managed accounts | **deliberately N/A** — accounts are a claude config-dir mechanism. `createAgentNode` never stamps an `accountId` onto a non-claude node, and `CLAUDE_CONFIG_DIR` is irrelevant to `~/.grok/hooks`. A grok node in a managed-account project must still report status (checklist 7) | idem | idem |
| Brand logo | the **official** xAI mark, INLINED in `agentIcons.tsx` as `GrokMark` rather than shipped as an asset — it is a single monochrome path, so `fill="currentColor"` inherits the label colour and is correct in both themes. The other four marks are multi-colour and stay `<img src>` assets, where `currentColor` cannot inherit | same component, for free | the phone draws its own icons — **follow-up owed** |
| Working indicator | the **brand mark, breathing** — no critter. Since 2026-08-09 this is a THREE-agent mechanism (grok, gemini, opencode) driven by one pure decision, `brandPulsePlan` in `lib/brandPulse.ts`, with a thin renderer per surface: `BrandPulse` for the React badge (`AgentMascot` no longer imports `GrokMark`) and `workingMascot` for the notch strip. Grok is the only `kind: 'inline'` case — its mark is a single monochrome path from `lib/grokMark.ts` (`createGrokMarkSvg` in the HUD) pulsing with a `currentColor` drop-shadow bloom; the other marks are multi-colour assets whose bloom takes the label colour instead of their own ink. One decision, so an agent is never two things on two surfaces. See docs/mascot-sprites.md | **N/A** — no notch there; the canvas badge indicator works | the phone has its own SwiftUI renderer |
diff --git a/src/core/grok-cli.test.ts b/src/core/grok-cli.test.ts
index add3b7e47..330a02d33 100644
--- a/src/core/grok-cli.test.ts
+++ b/src/core/grok-cli.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { grokCliCapsFrom, UNKNOWN_GROK_CLI_CAPS } from './grok-cli'
+import { grokCapsFromRunner, grokCliCapsFrom, UNKNOWN_GROK_CLI_CAPS } from './grok-cli'
// Verbatim from `grok --help` on 1.0.13 (2026-09-02). The two lines matter for opposite reasons:
// the first DEFINES the flag, the second only MENTIONS it inside another option's prose.
@@ -16,14 +16,14 @@ const REAL_HELP = `
describe('grokCliCapsFrom', () => {
it('detects the flag from the real help text', () => {
- expect(grokCliCapsFrom(REAL_HELP)).toEqual({ sessionIdFlag: true })
+ expect(grokCliCapsFrom(REAL_HELP)).toEqual({ sessionIdFlag: true, models: [] })
})
it('is not fooled by a longer flag that merely starts the same', () => {
// The word-boundary anchor. `--session-id-file` is a different flag; answering yes for it would
// put an unknown option on the command line, and an unknown option makes grok EXIT — the launch
// dies rather than degrading.
- expect(grokCliCapsFrom(' --session-id-file <PATH>\n')).toEqual({ sessionIdFlag: false })
+ expect(grokCliCapsFrom(' --session-id-file <PATH>\n')).toEqual({ sessionIdFlag: false, models: [] })
})
it('is not fooled by a prose mention inside another option', () => {
@@ -32,7 +32,7 @@ describe('grokCliCapsFrom', () => {
// pinned because grok WRITES it, not because it is hypothetical.
const proseOnly =
' --fork-session\n create a new session ID instead of reusing the original (optionally set via `--session-id`)\n'
- expect(grokCliCapsFrom(proseOnly)).toEqual({ sessionIdFlag: false })
+ expect(grokCliCapsFrom(proseOnly)).toEqual({ sessionIdFlag: false, models: [] })
})
it('answers no for absent, empty and unreadable help', () => {
@@ -48,3 +48,45 @@ describe('grokCliCapsFrom', () => {
expect(grokCliCapsFrom(' -s, --session-id').sessionIdFlag).toBe(true)
})
})
+
+describe('grokCliCapsFrom — the model catalogue rides the same probe', () => {
+ it("carries grok's own model ids when `grok models` answered", () => {
+ const models = 'Available models:\n * grok-4.6 (default)\n - grok-4.5\n'
+ expect(grokCliCapsFrom('-s, --session-id <ID>', models).models).toEqual(['grok-4.6', 'grok-4.5'])
+ })
+
+ it('is empty when that subcommand failed, without costing the help answer', () => {
+ // Two spawns, two independent degrades: a `grok models` that errors must not also throw away
+ // what `--help` already told us about `--session-id`.
+ const caps = grokCliCapsFrom('-s, --session-id <ID>', null)
+ expect(caps.sessionIdFlag).toBe(true)
+ expect(caps.models).toEqual([])
+ })
+})
+
+describe('grokCapsFromRunner — both subcommands are actually asked', () => {
+ it('asks --help AND models, and feeds both into the caps', async () => {
+ const asked: string[][] = []
+ const caps = await grokCapsFromRunner(async (args) => {
+ asked.push(args)
+ return args[0] === '--help'
+ ? '-s, --session-id <ID>'
+ : 'Available models:\n - grok-4.6\n'
+ })
+ expect(asked).toEqual([['--help'], ['models']])
+ expect(caps).toEqual({ sessionIdFlag: true, models: ['grok-4.6'] })
+ })
+
+ it('keeps the help answer when `models` fails', async () => {
+ const caps = await grokCapsFromRunner(async (args) =>
+ args[0] === '--help' ? '-s, --session-id <ID>' : null
+ )
+ expect(caps).toEqual({ sessionIdFlag: true, models: [] })
+ })
+
+ it('gives up entirely when --help itself fails', async () => {
+ // No help means we know nothing about this binary; guessing from a models list alone would be
+ // claiming a flag we never saw advertised.
+ expect(await grokCapsFromRunner(async () => null)).toEqual(UNKNOWN_GROK_CLI_CAPS)
+ })
+})
diff --git a/src/core/grok-cli.ts b/src/core/grok-cli.ts
index db94c171b..213eb0985 100644
--- a/src/core/grok-cli.ts
+++ b/src/core/grok-cli.ts
@@ -13,6 +13,7 @@ import { promisify } from 'util'
import { IPC } from '../shared/ipc'
import { findInLoginPath } from './pty-manager'
import { platform } from './platform'
+import { grokModelsFrom } from '../shared/agents/model-gateway'
import { listGrokSessionIds } from './grok-session-mint'
import { grokSessionsDir } from './agents/grok-paths'
import { UNKNOWN_GROK_CLI_CAPS, type GrokCliCaps } from '../shared/types'
@@ -29,24 +30,48 @@ export { UNKNOWN_GROK_CLI_CAPS, type GrokCliCaps }
* answer yes for `--session-id`; and grok's own help MENTIONS `--session-id` inside the description
* of `--fork-session`, wrapped in backticks — a looser match would report the flag from prose alone.
*/
-export function grokCliCapsFrom(helpOutput: string | null | undefined): GrokCliCaps {
- return { sessionIdFlag: /(^|\s)--session-id(\s|=|$)/m.test(helpOutput ?? '') }
+export function grokCliCapsFrom(
+ helpOutput: string | null | undefined,
+ modelsOutput?: string | null
+): GrokCliCaps {
+ return {
+ sessionIdFlag: /(^|\s)--session-id(\s|=|$)/m.test(helpOutput ?? ''),
+ models: grokModelsFrom(modelsOutput).map((m) => m.id)
+ }
}
let cached: Promise<GrokCliCaps> | null = null
+/**
+ * The two spawns, separated from HOW they are spawned so the composition is testable.
+ *
+ * `run` returns the subcommand's stdout, or null when it failed. Exported for tests: the wiring
+ * between "ask `--help`" and "ask `models`" is precisely the kind of code the typecheck validates
+ * and nothing exercises — drop the second call and every pure-parser test stays green while model
+ * switching silently disappears.
+ */
+export async function grokCapsFromRunner(
+ run: (args: string[]) => Promise<string | null>
+): Promise<GrokCliCaps> {
+ const help = await run(['--help'])
+ if (help === null) return UNKNOWN_GROK_CLI_CAPS
+ // A second spawn, paid once per process (the whole probe is memoized). Its failure must not cost
+ // us the help answer, so it degrades on its own: no model list just means no model switching.
+ const models = await run(['models'])
+ return grokCliCapsFrom(help, models)
+}
+
async function probe(): Promise<GrokCliCaps> {
- try {
- // GUI apps don't inherit the shell PATH — resolve through the login shell like every other CLI
- // lookup in the app.
- const bin = await findInLoginPath('grok')
- if (!bin) return UNKNOWN_GROK_CLI_CAPS
- const { stdout } = await execFileP(bin, ['--help'], { timeout: PROBE_TIMEOUT_MS })
- return grokCliCapsFrom(stdout)
- } catch {
- // Missing CLI, timeout, non-zero exit — all mean "unknown", which means "omit the flag".
- return UNKNOWN_GROK_CLI_CAPS
- }
+ // GUI apps don't inherit the shell PATH — resolve through the login shell like every other CLI
+ // lookup in the app.
+ const bin = await findInLoginPath('grok').catch(() => null)
+ if (!bin) return UNKNOWN_GROK_CLI_CAPS
+ return grokCapsFromRunner((args) =>
+ execFileP(bin, args, { timeout: PROBE_TIMEOUT_MS })
+ .then((r) => r.stdout)
+ // Missing CLI, timeout, non-zero exit — all mean "unknown", which means "omit the flag".
+ .catch(() => null)
+ )
}
/** The local grok CLI's capabilities. Memoized for the process lifetime. Never rejects. */
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index ca4761b7d..c45bf09c4 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -165,7 +165,7 @@ import { planSetProjectFolder } from '../lib/setProjectFolder'
import { observationIsRemote, type ObservationOrigin } from '../lib/accountChip'
import { transferConversationItems } from '../lib/transferItems'
import { reopenVariants } from '../lib/reopenVariants'
-import { modelsForAgent } from '@shared/agents/model-gateway'
+import { modelsForAgent, type GatewayModel } from '@shared/agents/model-gateway'
import { useModelGateway } from '../state/modelGateway'
import { viewportAtZoom } from '../lib/zoomReset'
import { containerOrigin, snapPointInRootSpace } from '../lib/gridSnap'
@@ -455,7 +455,7 @@ import { oneLine } from '@shared/one-line'
import { invalidNodeColorMessage, isNodeColor } from '@shared/node-colors'
import { parseLenses, verifyLensPrompt, verifySynthesisPrompt } from '../lib/verifyPanel'
import { useSettings } from '../state/settings'
-import { activePermissionMode, projectPermissionMode } from '../state/permissionMode'
+import { activePermissionMode, grokCliCapsNow, projectPermissionMode } from '../state/permissionMode'
import { useContextWindow } from '../state/contextWindow'
import { useSessionNaming } from '../state/sessionNaming'
import { useSshServers } from '../state/sshServers'
@@ -1294,6 +1294,10 @@ export function Canvas() {
const [mergePush, setMergePush] = useState(false)
const settings = useSettings((s) => s.settings)
const gatewayModels = useModelGateway((s) => s.models)
+ // The agent's OWN catalogue, for the agents whose models do not come from the gateway. Read
+ // through the same probe memo the launch path uses; `modelsForAgent` decides who gets it, so no
+ // model id and no agent id is spelled here.
+ const grokModelList = (): GatewayModel[] => grokCliCapsNow().models.map((id) => ({ id }))
const gatewayStatus = useModelGateway((s) => s.status)
const gatewayError = useModelGateway((s) => s.error)
const discoverModels = useModelGateway((s) => s.discover)
@@ -7687,7 +7691,7 @@ export function Canvas() {
: []
const switchCapable = !!sourceAgentId && canSwitchModel(sourceAgentId)
const compatibleModels = sourceAgentId && session.source !== 'relay'
- ? modelsForAgent(gatewayModels, sourceAgentId)
+ ? modelsForAgent(gatewayModels, sourceAgentId, grokModelList())
: []
const currentModel =
typeof n?.data.agentModel === 'string' ? n.data.agentModel : undefined
diff --git a/src/renderer/state/workspace.session-id.test.ts b/src/renderer/state/workspace.session-id.test.ts
index e57fc38db..9878e20a1 100644
--- a/src/renderer/state/workspace.session-id.test.ts
+++ b/src/renderer/state/workspace.session-id.test.ts
@@ -114,7 +114,7 @@ describe('grok mints on ITS OWN probe', () => {
})
it('stamps a grok node once grok\'s help advertised the flag', () => {
- resetGrokCliCapsForTests({ sessionIdFlag: true })
+ resetGrokCliCapsForTests({ sessionIdFlag: true, models: [] })
const n = createAgentNode('grok', 0)
expect(n.data.agentSessionId).toMatch(UUID_RE)
// BEFORE the separator: grok's `--` is end of options, so a flag after it is swallowed into the
@@ -126,7 +126,7 @@ describe('grok mints on ITS OWN probe', () => {
// The mutation this exists for: pointing grok's gate at claude's probe result. Both CLIs are
// installed and upgraded independently, so claude's answer says nothing about grok's.
resetClaudeCliCapsForTests({ ...UNKNOWN_CLAUDE_CLI_CAPS, version: '2.1.226', sessionIdFlag: true })
- resetGrokCliCapsForTests({ sessionIdFlag: false })
+ resetGrokCliCapsForTests({ sessionIdFlag: false, models: [] })
const n = createAgentNode('grok', 0)
expect(n.data.agentSessionId).toBeUndefined()
expect(n.data.initialCommand).not.toContain('--session-id')
diff --git a/src/shared/agents/__fixtures__/grok-models.txt b/src/shared/agents/__fixtures__/grok-models.txt
new file mode 100644
index 000000000..c1dccf601
--- /dev/null
+++ b/src/shared/agents/__fixtures__/grok-models.txt
@@ -0,0 +1,7 @@
+You are logged in with grok.com.
+
+Default model: grok-4.6
+
+Available models:
+ * grok-4.6 (default)
+ - grok-4.5
diff --git a/src/shared/agents/config.capabilities.test.ts b/src/shared/agents/config.capabilities.test.ts
index bc7d73235..b40b8c405 100644
--- a/src/shared/agents/config.capabilities.test.ts
+++ b/src/shared/agents/config.capabilities.test.ts
@@ -43,7 +43,10 @@ describe('MODEL_SWITCH_CAPABLE', () => {
expect(canSwitchModel('claude')).toBe(true)
expect(canSwitchModel('codex')).toBe(true)
expect(canSwitchModel('copilot')).toBe(true)
- for (const id of ['gemini', 'opencode', 'grok', 'custom:plain'] as const) {
+ // grok joined once its leaf existed: `-m/--model` in the launch grammar plus `grok models` for
+ // discovery. It is NOT in this list as an example of a non-capable agent any more.
+ expect(canSwitchModel('grok')).toBe(true)
+ for (const id of ['gemini', 'opencode', 'custom:plain'] as const) {
expect(canSwitchModel(id), id).toBe(false)
}
})
@@ -248,6 +251,13 @@ describe('grok capabilities', () => {
expect(supportsSessionIdFlag('claude', false, true)).toBe(false)
})
+ it('picks a model through the base-harness mapping, from grok\'s own catalogue', () => {
+ // The whole capability is the leaf: membership plus `grok models` for discovery and `--model`
+ // in the launch grammar. No frontend spells a grok model id, and none spells `grok` here either
+ // — `modelsForAgent` decides who is offered which catalogue.
+ expect(canSwitchModel('grok')).toBe(true)
+ })
+
it('does not yet claim the capabilities whose per-agent leaf is unwritten', () => {
expect(canBranch('grok')).toBe(false)
expect(canSubagent('grok')).toBe(false)
diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.ts
index a48f4eaed..40f921a76 100644
--- a/src/shared/agents/config.ts
+++ b/src/shared/agents/config.ts
@@ -288,7 +288,7 @@ export const PERMISSION_MODE_CAPABLE = ['claude', 'grok', 'gemini', 'codex'] as
// Agents whose harness accepts a per-launch model override and whose gateway protocol we know how
// to configure. Custom agents inherit this through `capabilityAgentId`, like every other harness
// capability — the renderer never maintains its own Claude/Codex/Copilot allowlist.
-export const MODEL_SWITCH_CAPABLE = ['claude', 'codex', 'copilot'] as const
+export const MODEL_SWITCH_CAPABLE = ['claude', 'codex', 'copilot', 'grok'] as const
// Agents whose own CLI already tells the user when it copies, so nodeterm must not say it again.
// Claude Code captures the mouse itself and prints its own line — "copied N chars to tmux buffer ·
// paste with prefix + ]" — which makes our copy pill a second message for one gesture. Membership
diff --git a/src/shared/agents/launch.test.ts b/src/shared/agents/launch.test.ts
index 56ffac454..e78b15aae 100644
--- a/src/shared/agents/launch.test.ts
+++ b/src/shared/agents/launch.test.ts
@@ -77,6 +77,18 @@ describe('assembleLaunchCommand — builtins (byte-identical to the historical p
).toBe('grok')
})
+ it('grok puts the MODEL flag before the -- separator, alongside the others', () => {
+ // Same failure shape as the session id: a flag after grok's `--` is not rejected, it is
+ // swallowed into the PROMPT. The node would launch on the DEFAULT model while the agent read
+ // "--model grok-4.5" as the first words of its instructions — and no exit code would say so.
+ const cmd = assembleLaunchCommand(
+ { agentId: 'grok', initialPrompt: 'do the thing', model: 'grok-4.5' },
+ ENV
+ ).command
+ expect(cmd).toBe("grok --model 'grok-4.5' -- 'do the thing'")
+ expect(cmd.indexOf('--model')).toBeLessThan(cmd.indexOf(' -- '))
+ })
+
it('grok puts the permission flag BEFORE the -- separator', () => {
expect(
assembleLaunchCommand({ agentId: 'grok', initialPrompt: 'version', permissionMode: 'plan' }, ENV).command
diff --git a/src/shared/agents/model-gateway.test.ts b/src/shared/agents/model-gateway.test.ts
index 7144f890c..c1b5adb18 100644
--- a/src/shared/agents/model-gateway.test.ts
+++ b/src/shared/agents/model-gateway.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'fs'
+import path from 'path'
import {
+ grokModelsFrom,
+ normalizedAgentModel,
MODEL_GATEWAY_ENV_KEYS,
MODEL_GATEWAY_SECRET_REF,
modelGatewayEnv,
@@ -242,3 +246,82 @@ describe('MODEL_GATEWAY_ENV_KEYS lockstep', () => {
for (const k of seen) expect(MODEL_GATEWAY_ENV_KEYS).toContain(k)
})
})
+
+
+describe('grokModelsFrom — discovery without an allowlist', () => {
+ // Captured verbatim from `grok models` on 1.0.13 (2026-09-02). The CLI lists its own models, so
+ // there is no allowlist to maintain and a model shipped tomorrow appears with no code change.
+ const REAL = readFileSync(path.join(__dirname, '__fixtures__/grok-models.txt'), 'utf8')
+
+ it('reads the ids out of the real output', () => {
+ expect(grokModelsFrom(REAL)).toEqual([{ id: 'grok-4.6' }, { id: 'grok-4.5' }])
+ })
+
+ it('does not mistake the "Default model:" line for an entry', () => {
+ // That line repeats an id the bullet list already carries. Treating prose as data is how a login
+ // banner or a future footer becomes a fake model id on the menu.
+ const out = grokModelsFrom(REAL)
+ expect(out.filter((m) => m.id === 'grok-4.6')).toHaveLength(1)
+ expect(out.map((m) => m.id)).not.toContain('model:')
+ })
+
+ it('stops at the first unindented line', () => {
+ const withFooter = REAL + 'Run `grok --help` for more.\n - not-a-model\n'
+ expect(grokModelsFrom(withFooter).map((m) => m.id)).toEqual(['grok-4.6', 'grok-4.5'])
+ })
+
+ it('rejects an id that could not safely reach a command line', () => {
+ const hostile = 'Available models:\n - ok-model\n - $(rm -rf /)\n - --flag-shaped\n'
+ expect(grokModelsFrom(hostile).map((m) => m.id)).toEqual(['ok-model'])
+ })
+
+ it('is EMPTY for anything it cannot parse — never a partial list', () => {
+ // A failed probe must read as "no model switching", i.e. the pre-feature behaviour.
+ expect(grokModelsFrom('')).toEqual([])
+ expect(grokModelsFrom(null)).toEqual([])
+ expect(grokModelsFrom('command not found: grok')).toEqual([])
+ expect(grokModelsFrom('You are logged in with grok.com.')).toEqual([])
+ })
+})
+
+describe('modelsForAgent — grok is offered its OWN models, never the gateway catalogue', () => {
+ const GATEWAY = [{ id: 'anthropic/claude-x' }, { id: 'openai/gpt-x' }]
+ const GROK = [{ id: 'grok-4.6' }]
+
+ it("returns grok's list for a grok node", () => {
+ // Correctness, not preference: grok cannot be routed through the gateway at all (its custom
+ // models live in config.toml, not in env). Offering the gateway catalogue would put ids on the
+ // menu that grok rejects at launch — a picker that looks like it worked and kills the node.
+ expect(modelsForAgent(GATEWAY, 'grok', GROK)).toEqual(GROK)
+ })
+
+ it('gives grok nothing when its own probe found nothing', () => {
+ expect(modelsForAgent(GATEWAY, 'grok')).toEqual([])
+ })
+
+ it('leaves every other agent on the gateway catalogue', () => {
+ expect(modelsForAgent(GATEWAY, 'claude', GROK)).toEqual(GATEWAY)
+ expect(modelsForAgent(GATEWAY, 'codex', GROK)).toEqual(GATEWAY)
+ })
+})
+
+describe('grok takes its model as a FLAG, and needs no gateway environment', () => {
+ it('appends --model before anything else touches the line', () => {
+ expect(withAgentModel('grok', 'grok', 'grok-4.5')).toBe("grok --model 'grok-4.5'")
+ })
+
+ it('emits no environment at all', () => {
+ // grok's custom models are declared in ~/.grok/config.toml with their own base_url/api_key, and
+ // that file explicitly cannot be defaulted from the environment. Emitting the OpenAI pair anyway
+ // would point grok's built-in models at a gateway they were never configured for.
+ const settings = { baseUrl: 'https://gw.example', apiKey: 'k' }
+ expect(modelGatewayEnv(settings as never, 'grok', 'grok-4.6', {}, 'secret')).toEqual({})
+ })
+
+ it('refuses a hand-edited id at the point it would reach the command line', () => {
+ expect(normalizedAgentModel('grok', 'grok-4.6 && rm -rf /')).toBe('grok-4.6 && rm -rf /')
+ expect(withAgentModel('grok', 'grok', 'grok-4.6 && rm -rf /')).toBe(
+ "grok --model 'grok-4.6 && rm -rf /'"
+ )
+ })
+})
diff --git a/src/shared/agents/model-gateway.ts b/src/shared/agents/model-gateway.ts
index 1c9aca3ce..ae38894e8 100644
--- a/src/shared/agents/model-gateway.ts
+++ b/src/shared/agents/model-gateway.ts
@@ -154,11 +154,60 @@ export function parseGatewayModels(payload: unknown): GatewayModel[] {
* provider here would hide supported modes. The capability is the only UI gate; custom agents
* inherit it from their declared base harness.
*/
-export function modelsForAgent(models: GatewayModel[], agentId: AgentId): GatewayModel[] {
+export function modelsForAgent(
+ models: GatewayModel[],
+ agentId: AgentId,
+ grokModels: readonly GatewayModel[] = []
+): GatewayModel[] {
if (!canSwitchModel(agentId)) return []
+ // grok is offered ITS OWN models, never the gateway's, and this is a correctness rule rather than
+ // a preference: grok cannot be routed through the gateway at all (see `modelGatewayEnv` below —
+ // its custom models live in `~/.grok/config.toml`, not in environment variables). Handing it the
+ // gateway catalogue would put ids on the menu that its CLI rejects at launch: a picker that looks
+ // like it worked and kills the node.
+ if (capabilityAgentId(agentId) === 'grok') return [...grokModels]
return models
}
+/**
+ * Parse `grok models` — the CLI's own list, so there is no allowlist to maintain and a model shipped
+ * tomorrow appears without a code change.
+ *
+ * MEASURED output (1.0.13, 2026-09-02):
+ *
+ * You are logged in with grok.com.
+ *
+ * Default model: grok-4.6
+ *
+ * Available models:
+ * * grok-4.6 (default)
+ * - grok-4.5
+ *
+ * Only the indented bullets under "Available models:" are read. The `Default model:` line is
+ * deliberately NOT a source: it repeats an entry that the bullet list already carries, and treating
+ * a prose line as data is how a login banner or a future footer becomes a fake model id.
+ *
+ * Anything unparseable yields an EMPTY list, which the UI reads as "no model switching" — the
+ * pre-feature behaviour. Never a partial list built from whatever happened to match.
+ */
+export function grokModelsFrom(stdout: string | null | undefined): GatewayModel[] {
+ const text = stdout ?? ''
+ const start = text.indexOf('Available models:')
+ if (start < 0) return []
+ const byId = new Map<string, GatewayModel>()
+ for (const raw of text.slice(start).split('\n').slice(1)) {
+ // An unindented line ends the block: the list is indented, anything flush left is prose again.
+ if (raw.trim() && !/^\s/.test(raw)) break
+ const m = /^\s+[*-]\s+(\S+)/.exec(raw)
+ if (!m) continue
+ const id = m[1]
+ // Same charset discipline as every other id that reaches a command line.
+ if (!/^[A-Za-z0-9][A-Za-z0-9._:\/-]*$/.test(id)) continue
+ if (!byId.has(id)) byId.set(id, { id })
+ }
+ return [...byId.values()]
+}
+
/**
* Environment applied to a terminal session before custom-agent env (custom values still win).
* Claude/Codex model selection stays a quoted CLI flag. Copilot's BYOK protocol instead carries
@@ -268,6 +317,18 @@ export function modelGatewayEnv(
: {})
}
}
+ case 'grok':
+ // Deliberately EMPTY, and stated rather than omitted. grok's model gateway is not an
+ // environment: custom models are declared in `~/.grok/config.toml` with their own `base_url`
+ // and `api_key` (`~/.grok/docs/user-guide/11-custom-models.md`), and that file also says the
+ // environment-wide knobs it does accept CANNOT carry `model`/`base_url`/`api_key`. So there is
+ // no env for this function to emit, and emitting the OpenAI pair anyway would point grok's
+ // built-in models at a gateway they were never configured for.
+ //
+ // Writing into the user's `config.toml` to route grok through the gateway is a real feature
+ // and a separate decision — it edits a file the user owns, for a value they did not ask us to
+ // change. Not this PR.
+ return {}
default:
return {}
}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index a84a89a55..a589eb35a 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2608,10 +2608,18 @@ export interface GrokCliCaps {
* and `--resume` accepts a TITLE as well as an id, failing as ambiguous on duplicates.
*/
sessionIdFlag: boolean
+ /**
+ * Model ids this CLI lists, from `grok models` — the CLI's own catalogue, so there is no allowlist
+ * to maintain and a model shipped tomorrow appears without a code change.
+ *
+ * Empty when the subcommand fails, is unparseable, or grok is not installed: the UI then offers no
+ * model switching, which is the pre-feature behaviour. Never a partial list.
+ */
+ models: string[]
}
-/** Unprobed grok ⇒ omit the flag ⇒ today's command line, byte-identical. */
-export const UNKNOWN_GROK_CLI_CAPS: GrokCliCaps = { sessionIdFlag: false }
+/** Unprobed grok ⇒ omit the flag, offer no models ⇒ today's command line, byte-identical. */
+export const UNKNOWN_GROK_CLI_CAPS: GrokCliCaps = { sessionIdFlag: false, models: [] }
export interface GrokApi {
/** Capabilities of the local grok CLI (memoized in the shell; safe to call repeatedly).