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.

feat(cli): add xAI Grok engine

0xken15b34f9823f96e
diff --git a/.github/assets/engines/README.md b/.github/assets/engines/README.md
index 07f478143..f74e8a316 100644
--- a/.github/assets/engines/README.md
+++ b/.github/assets/engines/README.md
@@ -29,6 +29,7 @@ a retina display.
| `muse.png` | The Meta mark from the official lockup SVG at `static.xx.fbcdn.net/rsrc.php/y3/r/y6QsbGgc866.svg` — wordmark paths dropped, glyph rasterised to 104×104, gradient kept | 104 | `d7c4568f992e60f6d42a7a819a5a782d479cbfd9ad2bc11e69c82b35b8a5d8fe` |
| `amp.png` | Amp's official app icon — the `apple-touch-icon` the site itself declares, <https://ampcode.com/app-icon.png?v=3>, fetched 2026-08-07 | 512 | `e5fc0d1178674b80c0dcbbf9811787b44df91f865fac9cd3ef44bb13ef728018` |
| `kilo.png` | Kilo's official app icon — the 512px `icon` the site itself declares, <https://kilo.ai/favicon/android-chrome-512x512.png?v=2>, fetched 2026-08-10 | 512 | `01d05e48efb03321468e1af0110d05de4550806f653b95adb93ad93a546fee7b` |
+| `grok.png` | SpaceXAI symbol used by the official `xai-org/grok-build` README, <https://media.x.ai/v1/website/spacexai-symbol-black-transparent-6435cf42.png>, fetched 2026-08-10 | 600 | `d2ce9e34b770aeb1e6155646e37573a9eabc380c3fe48e72f7fe19c4b0b59e07` |
Open items, recorded rather than left implicit:
@@ -39,7 +40,8 @@ Open items, recorded rather than left implicit:
for in-app engine identification on the project owner's decision; a public README is a more visible
use than an in-app badge, and that decision should be confirmed rather than inherited.
- **Light and dark themes.** Several marks are opaque tiles (Claude orange, Command Code and Pi
- black, OpenCode and Hermes white, Amp dark green) and a few are transparent glyphs. GitHub renders
+ black, OpenCode and Hermes white, Amp dark green) and a few are transparent glyphs, including Grok's
+ black SpaceXAI symbol. GitHub renders
this README on both grounds; the glyphs are the ones to re-check if a theme change makes one
disappear.
- **`amp.png` is the app icon, not the bare mark.** Amp publishes both: the `apple-touch-icon` used
diff --git a/.github/assets/engines/grok.png b/.github/assets/engines/grok.png
new file mode 100644
index 000000000..5e8586b88
Binary files /dev/null and b/.github/assets/engines/grok.png differ
diff --git a/README.md b/README.md
index d449c5f58..8f93db44b 100644
--- a/README.md
+++ b/README.md
@@ -39,6 +39,8 @@ It drives the agents you already use:
<img src=".github/assets/engines/amp.png" height="72" alt="Amp" title="Amp">
&nbsp;&nbsp;
<img src=".github/assets/engines/kilo.png" height="72" alt="Kilo" title="Kilo">
+ &nbsp;&nbsp;
+ <img src=".github/assets/engines/grok.png" height="72" alt="Grok" title="Grok">
</p>
## Add your agent to Harness
@@ -86,7 +88,7 @@ Your agents stay your processes, on your hardware, with your credentials.
`harness join` `harness join` your HTTP API
│ │ │
claude · codex hermes · muse agents running on
- cursor · amp · … opencode · kilo · … your own servers
+ cursor · amp · … opencode · kilo · grok your own servers
└───────── CLI ─────────┘ └─────── API ───────┘
```
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index 95018ba4a..c87510864 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -20,6 +20,7 @@ import {
mkdirSync,
openSync,
readFileSync,
+ readdirSync,
readSync,
realpathSync,
renameSync,
@@ -62,7 +63,7 @@ function argValue(name, fallback) {
function argEngine() {
const i = process.argv.indexOf('--engine')
const value = i !== -1 ? process.argv[i + 1] : ''
- return value === 'codex' || value === 'cursor' || value === 'hermes' || value === 'commandcode' || value === 'devin' || value === 'muse' ? value : 'claude'
+ return value === 'codex' || value === 'cursor' || value === 'hermes' || value === 'commandcode' || value === 'devin' || value === 'muse' || value === 'grok' ? value : 'claude'
}
function paths() {
@@ -70,6 +71,7 @@ function paths() {
const dataDir = argValue('--data-dir', process.env.ADAPTER_DATA_DIR || join(cliDir, 'data'))
const claudeProjectsDir = argValue('--claude-projects-dir', process.env.CLAUDE_PROJECTS_DIR || join(homedir(), '.claude', 'projects'))
const codexHome = argValue('--codex-home', process.env.CODEX_HOME || join(homedir(), '.codex'))
+ const grokHome = argValue('--grok-home', process.env.GROK_HOME || join(homedir(), '.grok'))
const cursorHome = argValue('--cursor-home', process.env.CURSOR_HOME || join(homedir(), '.cursor'))
const commandcodeHome = argValue('--commandcode-home', process.env.COMMANDCODE_HOME || join(homedir(), '.commandcode'))
const devinHome = argValue('--devin-home', process.env.DEVIN_HOME || join(homedir(), '.local', 'share', 'devin', 'cli'))
@@ -79,6 +81,7 @@ function paths() {
bootFile: join(dataDir, 'registry-boot'),
claudeProjectsDir,
codexSessionsDir: join(codexHome, 'sessions'),
+ grokSessionsDir: join(grokHome, 'sessions'),
cursorProjectsDir: join(cursorHome, 'projects'),
commandcodeProjectsDir: join(commandcodeHome, 'projects'),
devinHome,
@@ -92,6 +95,41 @@ function existsPath(file) {
try { return statSync(file).isFile() } catch { return false }
}
+/** Resolve Grok's authoritative update log. Normal paths use URL-encoded cwd; very long paths use a
+ * hashed directory with a `.cwd` sidecar, so scan only that one level as a bounded fallback. */
+function grokTranscriptPath(p, cwd, sessionId) {
+ if (typeof cwd !== 'string' || !cwd || typeof sessionId !== 'string'
+ || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sessionId)) return ''
+ const direct = join(p.grokSessionsDir, encodeURIComponent(cwd), sessionId, 'updates.jsonl')
+ if (existsPath(direct)) return direct
+ try {
+ for (const entry of readdirSync(p.grokSessionsDir, { withFileTypes: true })) {
+ if (!entry.isDirectory()) continue
+ const group = join(p.grokSessionsDir, entry.name)
+ let recorded = ''
+ try { recorded = readFileSync(join(group, '.cwd'), 'utf8').trim() } catch { continue }
+ if (recorded !== cwd) continue
+ const candidate = join(group, sessionId, 'updates.jsonl')
+ if (existsPath(candidate)) return candidate
+ }
+ } catch { /* state root may not exist yet */ }
+ return ''
+}
+
+function grokHookEvent(value) {
+ const key = String(value || '')
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
+ .replace(/-/g, '_')
+ .toLowerCase()
+ return ({
+ session_start: 'SessionStart',
+ session_end: 'SessionEnd',
+ user_prompt_submit: 'UserPromptSubmit',
+ stop: 'Stop',
+ stop_failure: 'StopFailure',
+ })[key] || ''
+}
+
/**
* True when a hook payload came from Devin rather than the engine the hook was armed for. Devin session
* ids are lowercase word slugs (`blue-agustinia`) and every live session holds
@@ -250,6 +288,7 @@ function validTranscriptPath(engine, filePath, p) {
const actual = realpathSync(filePath)
const root = realpathSync(
engine === 'codex' ? p.codexSessionsDir
+ : engine === 'grok' ? p.grokSessionsDir
: engine === 'cursor' ? p.cursorProjectsDir
: engine === 'commandcode' ? p.commandcodeProjectsDir
: p.claudeProjectsDir,
@@ -413,7 +452,9 @@ async function fallbackRegister(input, engine, tmuxPane, launcherId) {
launcherId,
boundAt: Date.now(),
transcriptPath: transcriptPath || existing?.transcriptPath || null,
- projectDir: transcriptPath
+ projectDir: engine === 'grok'
+ ? basename(typeof input.cwd === 'string' ? input.cwd : '') || sessionId
+ : transcriptPath
? basename(dirname(transcriptPath))
: basename(typeof input.cwd === 'string' ? input.cwd : '') || sessionId,
cwd: typeof input.cwd === 'string' ? input.cwd : (existing?.cwd ?? null),
@@ -459,7 +500,7 @@ async function main() {
return
}
- const event = input.hook_event_name
+ const event = input.hook_event_name || input.hookEventName
const tmuxPane = process.env.TMUX_PANE
if (!tmuxPane) return // tmux-only: ignore every lifecycle event from standalone CLI sessions
// machine-launched only: `harness <engine>` exports MACHINE_ID into the CLI's env, and that id is what
@@ -476,6 +517,51 @@ async function main() {
// session id and no Devin lock file.
if (engine === 'claude' && isDevinSession(input, paths())) return
+ // Grok's hook payload and event records are camelCase, while every Claude-compatible engine above is
+ // snake_case. Its Stop hook is deliberately NOT installed: Grok persists that hook_execution before
+ // the final assistant chunk, so treating Stop as authoritative would close the turn too early. The
+ // transcript's `turn_completed` record closes normal turns; only StopFailure is needed as an error
+ // fallback here.
+ if (engine === 'grok') {
+ const grokEventName = grokHookEvent(event)
+ const sessionId = input.sessionId || input.session_id
+ const cwd = input.cwd || input.workspaceRoot
+ const transcriptPath = grokTranscriptPath(paths(), cwd, sessionId)
+ if (grokEventName === 'SessionEnd') {
+ const ok = await post(port, '/api/hook/session-end', { sessionId, reason: input.reason })
+ if (!ok) await fallbackSessionEnd(sessionId, input.reason, engine, tmuxPane)
+ return
+ }
+ if (grokEventName === 'StopFailure') {
+ await post(port, '/api/hook/turn-stop', { sessionId, transcriptPath, status: 'error' })
+ return
+ }
+ if (grokEventName !== 'SessionStart' && grokEventName !== 'UserPromptSubmit') return
+ const body = {
+ engine,
+ launcherId,
+ hookEvent: grokEventName,
+ sessionId,
+ transcriptPath,
+ cwd,
+ tmuxPane,
+ model: modelName(input.model),
+ cliVersion: input.cliVersion || input.version,
+ }
+ const registered = await post(port, '/api/hook/session-start', body)
+ if (!registered) {
+ await fallbackRegister({
+ ...input,
+ hook_event_name: grokEventName,
+ session_id: sessionId,
+ transcript_path: transcriptPath,
+ cwd,
+ cli_version: input.cliVersion || input.version,
+ }, engine, tmuxPane, launcherId)
+ }
+ return
+ }
+
if (((engine === 'claude' || engine === 'devin') && event === 'SessionEnd') || (engine === 'cursor' && event === 'sessionEnd')) {
const ok = await post(port, '/api/hook/session-end', {
sessionId: input.session_id || input.conversation_id,
diff --git a/cli/package.json b/cli/package.json
index 9a9bbb9d3..9d8472f14 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -32,7 +32,7 @@
"typescript": "^5.5.3",
"vitest": "^4.1.10"
},
- "description": "Run your own coding-agent CLIs (Claude Code, Codex, Cursor, OpenCode, Pi, Hermes, Command Code, Devin) in tmux and drive them from the web or a paired device.",
+ "description": "Run your own coding-agent CLIs (Claude Code, Codex, Cursor, OpenCode, Pi, Hermes, Command Code, Devin, Muse, Amp, Kilo, and Grok) in tmux and drive them from the web or a paired device.",
"license": "Apache-2.0",
"repository": {
"type": "git",
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 37852b73e..63a984967 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -1,5 +1,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { BackendSocket, compactRuntimePickerModels, deviceAgentListItem } from './backendSocket.js'
+import { readFileSync } from 'fs'
+import { fileURLToPath } from 'url'
+import { BackendSocket, compactRuntimePickerModels, deviceAgentListItem, grokHistoryPage } from './backendSocket.js'
const wsMock = vi.hoisted(() => {
const instances: MockWebSocket[] = []
@@ -335,4 +337,28 @@ describe('device agent list contract', () => {
id: 's1', name: 'A', engine: 'claude', selectedModel: null,
})
})
+
+ it('preserves Grok on the device agent contract', () => {
+ expect(deviceAgentListItem({ id: 'g1', name: 'Grok agent', engine: 'grok' })).toEqual({
+ id: 'g1', name: 'Grok agent', engine: 'grok',
+ })
+ })
+})
+
+describe('Grok session_get history', () => {
+ const fixture = readFileSync(
+ fileURLToPath(new URL('./lib/__fixtures__/grok-session.jsonl', import.meta.url)),
+ 'utf8',
+ ).split('\n').filter(Boolean)
+
+ it('replays the real transcript for both legacy and web-paginated requests', () => {
+ const full = grokHistoryPage(fixture, false)
+ const paginated = grokHistoryPage(fixture, true)
+
+ expect(full.events).toEqual(paginated.events)
+ expect(full.events[0]).toMatchObject({ type: 'user_message' })
+ expect(full.events.at(-1)).toEqual({ type: 'done', payload: { result: 'success' } })
+ expect(full).not.toHaveProperty('hasMore')
+ expect(paginated).toMatchObject({ hasMore: false, oldestCursor: null })
+ })
})
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 2bf118e16..9bfcf712d 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -31,6 +31,7 @@ import { opencodeMessagesToEvents, windowOpencodeMessages } from './engines/open
import { kiloMessagesToEvents, windowKiloMessages } from './engines/kilo/normalizer.js'
import { museMessagesToEvents } from './engines/muse/normalizer.js'
import { ampMessagesToEvents } from './engines/amp/normalizer.js'
+import { grokMessagesToEvents } from './engines/grok/normalizer.js'
import { ampThreadToEvents, readAmpThread } from './engines/amp/threadExport.js'
import { piMessagesToEvents, windowPiLines } from './engines/pi/normalizer.js'
import { commandcodeMessagesToEvents, windowCommandCodeLines } from './engines/commandcode/normalizer.js'
@@ -123,13 +124,22 @@ async function ampHistory(sessionId: string, lines: string[]): Promise<SessionEv
return ampMessagesToEvents(lines)
}
+/** Grok has no transcript windower yet. Keep BOTH `session_get` shapes on the same real-record replay:
+ * web always sends a limit, while legacy callers omit it. Returning the whole small transcript for a
+ * page is honest (`hasMore:false`) and cannot fall through to Claude's incompatible line cursor. */
+export function grokHistoryPage(lines: string[], paginated: boolean):
+ { events: SessionEvent[]; hasMore?: false; oldestCursor?: null } {
+ const events = grokMessagesToEvents(lines)
+ return paginated ? { events, hasMore: false, oldestCursor: null } : { events }
+}
+
export function deviceAgentListItem(
raw: unknown,
-): { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp' | 'kilo'; selectedModel?: string | null } {
+): { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp' | 'kilo' | 'grok'; selectedModel?: string | null } {
const o = (raw ?? {}) as Record<string, unknown>
- const item: { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp' | 'kilo'; selectedModel?: string | null } = { id: o.id }
+ const item: { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp' | 'kilo' | 'grok'; selectedModel?: string | null } = { id: o.id }
if (typeof o.name === 'string') item.name = clipDeviceAgentName(o.name)
- if (o.engine === 'claude' || o.engine === 'codex' || o.engine === 'cursor' || o.engine === 'opencode' || o.engine === 'pi' || o.engine === 'hermes' || o.engine === 'commandcode' || o.engine === 'devin' || o.engine === 'muse' || o.engine === 'amp' || o.engine === 'kilo') item.engine = o.engine
+ if (o.engine === 'claude' || o.engine === 'codex' || o.engine === 'cursor' || o.engine === 'opencode' || o.engine === 'pi' || o.engine === 'hermes' || o.engine === 'commandcode' || o.engine === 'devin' || o.engine === 'muse' || o.engine === 'amp' || o.engine === 'kilo' || o.engine === 'grok') item.engine = o.engine
// Runtime model/effort profile (opaque runtime-v1:...) — lets the device render + change model/effort.
if (typeof o.selectedModel === 'string' || o.selectedModel === null) item.selectedModel = o.selectedModel
return item
@@ -803,12 +813,14 @@ export class BackendSocket {
? museMessagesToEvents(lines)
: s.engine === 'amp'
? await ampHistory(sessionId, lines)
+ : s.engine === 'grok'
+ ? grokHistoryPage(lines, false).events
: s.engine === 'pi'
? piMessagesToEvents(lines)
: s.engine === 'commandcode'
? commandcodeMessagesToEvents(lines)
: messagesToEvents(lines)
- if (s.engine !== 'cursor' && s.engine !== 'pi' && s.engine !== 'commandcode' && s.engine !== 'muse' && s.engine !== 'amp') await enrichSubagentStats(fullEvents, s.transcriptPath)
+ if (s.engine !== 'cursor' && s.engine !== 'pi' && s.engine !== 'commandcode' && s.engine !== 'muse' && s.engine !== 'amp' && s.engine !== 'grok') await enrichSubagentStats(fullEvents, s.transcriptPath)
reply(type, requestId, {
id: sessionId,
title: projectDisplayName(s),
@@ -826,15 +838,20 @@ export class BackendSocket {
// small: a real one measured 271 lines).
// Amp is in the same position as muse and for the same reason: no windower, so falling
// through would pair claude's line-uuid cursor with claude's normalizer and return nothing.
- if (s.engine === 'muse' || s.engine === 'amp') {
+ if (s.engine === 'muse' || s.engine === 'amp' || s.engine === 'grok') {
+ const grokPage = s.engine === 'grok' ? grokHistoryPage(lines, true) : null
reply(type, requestId, {
id: sessionId,
title: projectDisplayName(s),
- events: s.engine === 'amp' ? await ampHistory(sessionId, lines) : museMessagesToEvents(lines),
+ events: s.engine === 'amp'
+ ? await ampHistory(sessionId, lines)
+ : s.engine === 'grok'
+ ? grokPage!.events
+ : museMessagesToEvents(lines),
timestamp,
engine: s.engine,
- hasMore: false,
- oldestCursor: null,
+ hasMore: grokPage?.hasMore ?? false,
+ oldestCursor: grokPage?.oldestCursor ?? null,
})
return
}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 7005250f9..6beb926b6 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -24,7 +24,7 @@ import { homedir } from 'os'
import { env } from './config/env.js'
import { VERSION } from './version.js'
import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
-import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installHermesHooks, installKiloPlugin, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'
+import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installGrokHooks, installHermesHooks, installKiloPlugin, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'
import { PID_FILE, TOKEN_FILE, daemonPort, isAlive, readPid } from './lib/daemonState.js'
import { ENGINES, aliasesFor, engineBin, engineCommand, resolveEngine } from './lib/engineBin.js'
import { refuseDuplicateAgent } from './lib/duplicateAgent.js'
@@ -77,6 +77,8 @@ import { KiloReader, readKiloMessages } from './engines/kilo/reader.js'
import { lastKiloTurnText } from './engines/kilo/normalizer.js'
import { MuseNormalizer, lastMuseTurnText, museMessagesToEvents } from './engines/muse/normalizer.js'
import { AmpNormalizer, lastAmpTurnText, ampMessagesToEvents } from './engines/amp/normalizer.js'
+import { GrokNormalizer, lastGrokTurnText } from './engines/grok/normalizer.js'
+import { findGrokTranscript } from './engines/grok/session.js'
import { PiNormalizer, lastPiTurnText } from './engines/pi/normalizer.js'
import { HermesReader, readHermesMessages } from './engines/hermes/reader.js'
import { DevinReader, readDevinMessages } from './engines/devin/reader.js'
@@ -88,7 +90,7 @@ import {
commandCodeRunErrorSummary,
lastCommandCodeTurnText,
} from './engines/commandcode/normalizer.js'
-import { SessionInputController } from './lib/sessionInput.js'
+import { acceptsInputBeforeSession, SessionInputController } from './lib/sessionInput.js'
import { adaptSlashCommand } from './lib/goalCommand.js'
import { RuntimeProfileManager } from './lib/runtimeProfile.js'
import { RuntimeProfileController } from './lib/runtimeProfileController.js'
@@ -593,6 +595,7 @@ async function runForeground(token: string): Promise<void> {
const piNormalizers = new Map<string, PiNormalizer>()
const museNormalizers = new Map<string, MuseNormalizer>()
const ampNormalizers = new Map<string, AmpNormalizer>()
+ const grokNormalizers = new Map<string, GrokNormalizer>()
const hermesReaders = new Map<string, HermesReader>()
const devinReaders = new Map<string, DevinReader>()
const commandcodeNormalizers = new Map<string, CommandCodeNormalizer>()
@@ -683,6 +686,7 @@ async function runForeground(token: string): Promise<void> {
|| piNormalizers.has(session.sessionId)
|| museNormalizers.has(session.sessionId)
|| ampNormalizers.has(session.sessionId)
+ || grokNormalizers.has(session.sessionId)
|| hermesReaders.has(session.sessionId)
|| devinReaders.has(session.sessionId)
|| commandcodeNormalizers.has(session.sessionId)
@@ -759,6 +763,13 @@ async function runForeground(token: string): Promise<void> {
for (const line of lines) historyEvents.push(...normalizer.ingest(line))
historyTurnOpen = normalizer.turnOpen
ampNormalizers.set(session.sessionId, normalizer)
+ } else if (session.engine === 'grok') {
+ const normalizer = new GrokNormalizer()
+ for (const line of lines) historyEvents.push(...normalizer.ingest(line))
+ historyTurnOpen = normalizer.turnOpen
+ grokNormalizers.set(session.sessionId, normalizer)
+ const capture = await captureTmuxPane(session.tmuxPane, 60)
+ if (capture) runtimeProfiles.ingestPane(session, capture, true)
} else if (session.engine === 'pi') {
const normalizer = new PiNormalizer('live')
// Hydrate state silently; never replay history live — except a turn left open, below.
@@ -905,6 +916,7 @@ async function runForeground(token: string): Promise<void> {
if (s.engine === 'cursor') return lastCursorTurnText(lines)
if (s.engine === 'muse') return lastMuseTurnText(lines)
if (s.engine === 'amp') return lastAmpTurnText(lines)
+ if (s.engine === 'grok') return lastGrokTurnText(lines)
if (s.engine === 'pi') return lastPiTurnText(lines)
if (s.engine === 'commandcode') return lastCommandCodeTurnText(lines)
return lastTurnTextFromRawLines(lines)
@@ -987,6 +999,7 @@ async function runForeground(token: string): Promise<void> {
?? piNormalizers.get(sessionId)?.turnOpen
?? museNormalizers.get(sessionId)?.turnOpen
?? ampNormalizers.get(sessionId)?.turnOpen
+ ?? grokNormalizers.get(sessionId)?.turnOpen
?? hermesReaders.get(sessionId)?.turnOpen
?? devinReaders.get(sessionId)?.turnOpen
?? commandcodeNormalizers.get(sessionId)?.turnOpen
@@ -1096,6 +1109,7 @@ async function runForeground(token: string): Promise<void> {
piNormalizers.delete(sessionId)
museNormalizers.delete(sessionId)
ampNormalizers.delete(sessionId)
+ grokNormalizers.delete(sessionId)
hermesReaders.get(sessionId)?.stop()
hermesReaders.delete(sessionId)
devinReaders.get(sessionId)?.stop()
@@ -1147,8 +1161,10 @@ async function runForeground(token: string): Promise<void> {
// other engines here are read from their own stores by session id.
const transcriptPath = candidate.engine === 'cursor'
? await findCursorTranscript(env.CURSOR_HOME, candidate.sessionId) ?? undefined
- : undefined
- if (candidate.engine === 'cursor' && !transcriptPath) continue
+ : candidate.engine === 'grok'
+ ? await findGrokTranscript(env.GROK_HOME, candidate.cwd, candidate.sessionId) ?? undefined
+ : undefined
+ if ((candidate.engine === 'cursor' || candidate.engine === 'grok') && !transcriptPath) continue
const result = registry.register({
engine: candidate.engine,
sessionId: candidate.sessionId,
@@ -1449,6 +1465,19 @@ async function runForeground(token: string): Promise<void> {
})
return
}
+ if (session.engine === 'grok') {
+ void (async () => {
+ await watcher.pollSession(sessionId)
+ const normalizer = grokNormalizers.get(sessionId)
+ if (status === 'error') {
+ announceTurnAborted(sessionId, 'grok', 'Grok ended the turn with an error')
+ emitSessionEvents(sessionId, normalizer?.abortTurn() ?? [])
+ }
+ })().catch((err) => {
+ console.error('[hooks] grok StopFailure hook failed:', err instanceof Error ? err.message : err)
+ })
+ return
+ }
if (session.engine !== 'claude') return
void (async () => {
await watcher.pollSession(sessionId)
@@ -1506,7 +1535,7 @@ async function runForeground(token: string): Promise<void> {
deviceE2eeConnected: backend.deviceE2eeConnected(),
uptimeSec: Math.round((Date.now() - startedAt) / 1000),
fingerprint: backend.e2eeFingerprint(),
- config: { watching: 'tmux Claude + Codex + Cursor + OpenCode + Pi + Hermes + Command Code + Devin sessions', dataDir: tildify(env.ADAPTER_DATA_DIR), port: daemonPort() },
+ config: { watching: 'tmux sessions across all supported engines (including Grok)', dataDir: tildify(env.ADAPTER_DATA_DIR), port: daemonPort() },
sessions: registry.list().map((s) => ({ id: s.agentId, sessionId: s.sessionId, name: projectDisplayName(s), engine: s.engine, cwd: tildify(s.cwd ?? ''), tmuxPane: s.tmuxPane, updatedAt: s.updatedAt })),
pairs: backend.listPairs(),
pending: backend.pendingPair(),
@@ -1531,6 +1560,7 @@ async function runForeground(token: string): Promise<void> {
installHermesHooks(hookPort)
installDevinHooks(hookPort)
installCommandCodeHooks(hookPort)
+ installGrokHooks(hookPort)
}
backend.setDashboardPort(hookPort) // surfaced to the web (e2e_status) so it can link here to approve
console.log(`[cli] local dashboard → http://127.0.0.1:${hookPort}`)
@@ -1570,6 +1600,10 @@ async function runForeground(token: string): Promise<void> {
let normalizer = ampNormalizers.get(evt.sessionId)
if (!normalizer) { normalizer = new AmpNormalizer(); ampNormalizers.set(evt.sessionId, normalizer) }
events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'grok') {
+ let normalizer = grokNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new GrokNormalizer(); grokNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
} else if (session.engine === 'pi') {
let normalizer = piNormalizers.get(evt.sessionId)
if (!normalizer) { normalizer = new PiNormalizer('live'); piNormalizers.set(evt.sessionId, normalizer) }
@@ -1613,6 +1647,7 @@ async function runForeground(token: string): Promise<void> {
?? piNormalizers.get(session.sessionId)?.turnOpen
?? museNormalizers.get(session.sessionId)?.turnOpen
?? ampNormalizers.get(session.sessionId)?.turnOpen
+ ?? grokNormalizers.get(session.sessionId)?.turnOpen
?? hermesReaders.get(session.sessionId)?.turnOpen
?? devinReaders.get(session.sessionId)?.turnOpen
?? commandcodeNormalizers.get(session.sessionId)?.turnOpen
@@ -1682,7 +1717,7 @@ async function runForeground(token: string): Promise<void> {
//
// Read just the footer, and only while such a session exists. NOT silent: a real change has to push to
// the device, which is the whole point.
- const PANE_POLLED_ENGINES = new Set(['devin', 'cursor'])
+ const PANE_POLLED_ENGINES = new Set(['devin', 'cursor', 'grok'])
const PANE_POLL_MS = 15_000
setInterval(() => {
for (const session of registry.list()) {
@@ -1728,6 +1763,7 @@ async function runForeground(token: string): Promise<void> {
piNormalizers.get(sessionId)?.closeTurn()
museNormalizers.get(sessionId)?.closeTurn()
ampNormalizers.get(sessionId)?.closeTurn()
+ grokNormalizers.get(sessionId)?.closeTurn()
hermesReaders.get(sessionId)?.closeTurn()
devinReaders.get(sessionId)?.closeTurn()
commandcodeNormalizers.get(sessionId)?.closeTurn()
@@ -1786,7 +1822,7 @@ async function runForeground(token: string): Promise<void> {
console.log(`[msg] ${sid(sessionId)} slash-command adapted for engine=${engine} · "${preview(content, 40)}" → "${preview(adapted, 40)}"`)
}
console.log(`[msg] ${sid(sessionId)} recv · engine=${engine} · len=${adapted.length} · "${preview(adapted)}"`)
- if (record && !record.sessionId) {
+ if (record && !record.sessionId && !acceptsInputBeforeSession(record.engine)) {
const held = pendingBeforeBind.get(record.agentId) ?? []
held.push(adapted)
pendingBeforeBind.set(record.agentId, held)
@@ -1813,7 +1849,7 @@ async function runForeground(token: string): Promise<void> {
backend.connect()
- console.log(`[cli] dialing ${env.BACKEND_WS_URL}/api/adapter-ws · watching registered Claude + Codex + Cursor tmux sessions`)
+ console.log(`[cli] dialing ${env.BACKEND_WS_URL}/api/adapter-ws · watching registered sessions for ${ENGINES.length} engines`)
// ── self-update: poll GCS for a newer bundle → verify+swap → restart IMMEDIATELY (supervised rollback) ──
//
diff --git a/cli/src/config/env.ts b/cli/src/config/env.ts
index da4becdd2..803773f94 100644
--- a/cli/src/config/env.ts
+++ b/cli/src/config/env.ts
@@ -100,6 +100,8 @@ const envSchema = z.object({
CLAUDE_PROJECTS_DIR: z.string().default(join(homedir(), '.claude', 'projects')),
// Codex state root. Only hook-registered rollout files beneath <CODEX_HOME>/sessions are exposed.
CODEX_HOME: z.string().default(join(homedir(), '.codex')),
+ // Grok state root. Conversation records live below <GROK_HOME>/sessions/<encoded-cwd>/<uuid>/updates.jsonl.
+ GROK_HOME: z.string().default(join(homedir(), '.grok')),
// Cursor state root. Interactive transcripts live below <CURSOR_HOME>/projects and local
// subagent linkage metadata lives below <CURSOR_HOME>/chats.
CURSOR_HOME: z.string().default(join(homedir(), '.cursor')),
@@ -166,8 +168,7 @@ const envSchema = z.object({
DEVIN_CONFIG_PATH: z.string().default(join(homedir(), '.config', 'devin', 'config.json')),
// Where the tmux-session registry + connect token are persisted.
ADAPTER_DATA_DIR: z.string().default(adapterDataDir),
- // Set to 'true' to skip auto-installing the SessionStart/SessionEnd hooks into
- // ~/.claude/settings.json on startup.
+ // Set to 'true' to skip auto-installing lifecycle hooks for every supported engine.
DISABLE_HOOK_INSTALL: z.string().default('false').transform((v) => v === 'true'),
// How often (ms) the reaper checks tmux panes and drops dead sessions.
TMUX_REAP_INTERVAL_MS: z.string().default('5000').transform(Number),
@@ -191,6 +192,8 @@ const envSchema = z.object({
// Path to the `kilo` CLI for Kilo recap one-shots (else `kilo` is resolved from PATH). `@kilocode/cli`
// also installs it as `kilocode`; both are the same file.
KILO_PATH: z.string().optional(),
+ // Path to the xAI Grok CLI for interactive sessions and recap one-shots.
+ GROK_PATH: z.string().optional(),
// Model for the device turn-recap one-shot.
SUMMARY_MODEL: z.string().default('sonnet'),
// Balanced Codex counterpart used only for recap workers; never inherits the interactive CLI model.
@@ -201,6 +204,8 @@ const envSchema = z.object({
OPENCODE_SUMMARY_MODEL: z.string().default(''),
// Kilo recap model (`provider/model` as `kilo models` prints it). Empty → the user's kilo default.
KILO_SUMMARY_MODEL: z.string().default(''),
+ // Grok recap model. Empty → use the user's Grok CLI default model.
+ GROK_SUMMARY_MODEL: z.string().default(''),
// Pi recap model (`provider/model` or a model pattern). Empty → use the user's pi config default.
PI_SUMMARY_MODEL: z.string().default(''),
// Hermes recap model. Empty → use the user's ~/.hermes/config.yaml default (keeps their provider).
diff --git a/cli/src/engines/README.md b/cli/src/engines/README.md
index 8f1a46e7d..62887f06a 100644
--- a/cli/src/engines/README.md
+++ b/cli/src/engines/README.md
@@ -126,6 +126,33 @@ Three things that pattern gets wrong if nobody warns you, all found by running i
---
+## When hooks and transcript events disagree about ordering
+
+Grok Build supplies both global hooks and an ACP-style `updates.jsonl`, but they do different jobs.
+Use the hook to discover and register the session; use the transcript as the authoritative turn stream.
+The real Grok recording exposed five details that are easy to get wrong by copying Claude's hook path:
+
+- Grok hook payload fields use camelCase (`hookEventName`, `sessionId`, `workspaceRoot`), while the event
+ values themselves are lowercase snake case (`session_start`, `user_prompt_submit`, `stop_failure`). The
+ shared notifier originally expected Claude's fields and canonical event values; normalise both axes.
+- A normal `Stop` hook was persisted before the final `agent_message_chunk` and `turn_completed` records.
+ Closing on that hook drops the actual answer, so Grok closes a normal turn only on `turn_completed`;
+ `StopFailure` remains a hook backstop for failed turns.
+- `spawn_subagent` is reported as a `Task`, and that tool result means only that the background task was
+ accepted. Its row stays open until the separate `subagent_finished` update arrives.
+- The planning tool is `todo_write`, not another engine's similarly named tool. It maps to `TodoWrite`
+ so `input.todos[].content` reaches the device checklist.
+- Session directories usually encode the cwd as one URL component. Long paths live under a hash instead,
+ with the original cwd in `.cwd`; discovery and restart repair must handle both layouts.
+- Grok creates no session when the TUI merely opens. The first prompt creates it and fires the hooks, so
+ a remote first prompt must be injected into the launcher's pane before a session id exists. Holding it
+ until registration deadlocks on the very `UserPromptSubmit` event that registration needs.
+
+The recorded envelope is `{timestamp, method, params:{sessionId, update, _meta}}`. Keep its fixture as a
+real recording: a hand-written sequence would not reveal the Stop-before-final-message ordering above.
+
+---
+
## Before you open a PR
Open an issue first with:
diff --git a/cli/src/engines/grok/askQuestion.spec.ts b/cli/src/engines/grok/askQuestion.spec.ts
new file mode 100644
index 000000000..701f8fc77
--- /dev/null
+++ b/cli/src/engines/grok/askQuestion.spec.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'fs'
+import { fileURLToPath } from 'url'
+import { parseGrokQuestionPane } from './askQuestion.js'
+
+function fixture(): string {
+ return readFileSync(fileURLToPath(new URL('../../lib/__fixtures__/question-grok.txt', import.meta.url)), 'utf-8')
+}
+
+describe('Grok question dialog', () => {
+ it('reads the question and strips same-line descriptions', () => {
+ expect(parseGrokQuestionPane(fixture())).toMatchObject({
+ kind: 'question',
+ question: 'Which color should I report?',
+ rows: [
+ { number: '1', label: 'Red' },
+ { number: '2', label: 'Blue' },
+ ],
+ multi: false,
+ })
+ })
+
+ it('keeps the free-text editor out of device options', () => {
+ const view = parseGrokQuestionPane(fixture())
+ expect(view).toMatchObject({ typeRow: { number: 'z', label: 'Type your answer here' } })
+ if (view?.kind !== 'question') throw new Error('fixture did not parse as a question')
+ expect(view.rows.some((row) => /type your answer/i.test(row.label))).toBe(false)
+ })
+
+ it('does not read old numbered prose without the live footer', () => {
+ expect(parseGrokQuestionPane('1 (o) Red\n2 (o) Blue')).toBeNull()
+ })
+})
diff --git a/cli/src/engines/grok/askQuestion.ts b/cli/src/engines/grok/askQuestion.ts
new file mode 100644
index 000000000..f55750b5f
--- /dev/null
+++ b/cli/src/engines/grok/askQuestion.ts
@@ -0,0 +1,55 @@
+import type { PaneView, QuestionRow, QuestionView } from '../../lib/askQuestion.js'
+
+function stripAnsi(value: string): string {
+ return value.replace(/\u001b\[[0-9;:]*[A-Za-z]/g, '')
+}
+
+/**
+ * Parse Grok 1.0.0's live questionnaire.
+ *
+ * Measured shape:
+ * | Which color should I report?
+ * | 1 (o) Red Report the color Red
+ * | 2 (o) Blue Report the color Blue
+ * | z (o) Type your answer here
+ * | up/down navigate ... Enter:submit
+ *
+ * Descriptions share the row with labels, separated by 2+ spaces. The `z` row opens free text and must
+ * not be offered as an option. Digits select and submit directly (verified by pressing `2`).
+ */
+export function parseGrokQuestionPane(capture: string): PaneView {
+ const lines = stripAnsi(capture).replace(/\u00a0/g, ' ').split('\n')
+ const footer = lines.findLastIndex((line) => /enter\s*:\s*submit/i.test(line))
+ if (footer < 0) return null
+
+ const rows: QuestionRow[] = []
+ let start = -1
+ for (let i = footer - 1; i >= 0 && footer - i <= 20; i--) {
+ const match = /^\s*[┃|]?\s*([0-9a-z])\s+\([^)]*\)\s+(.+?)\s*$/i.exec(lines[i])
+ if (!match) continue
+ const label = match[2].split(/\s{2,}/)[0].trim()
+ rows.unshift({ number: match[1], label, checked: /\([●x*]\)/i.test(lines[i]) })
+ start = i
+ }
+ if (!rows.length || start < 0) return null
+
+ let question = ''
+ for (let i = start - 1; i >= 0 && start - i <= 8; i--) {
+ const line = lines[i].replace(/^\s*[┃|]\s?/, '').trim()
+ if (!line) continue
+ question = line
+ break
+ }
+ if (!question) return null
+
+ const typeRow = rows.find((row) => /^type your answer here$/i.test(row.label)) ?? null
+ const view: QuestionView = {
+ kind: 'question',
+ question,
+ rows: rows.filter((row) => row !== typeRow),
+ // The measured 1.0.0 dialog is single-select; do not infer checkbox semantics from its `(○)` marker.
+ multi: false,
+ typeRow,
+ }
+ return view
+}
diff --git a/cli/src/engines/grok/normalizer.spec.ts b/cli/src/engines/grok/normalizer.spec.ts
new file mode 100644
index 000000000..9774d6d90
--- /dev/null
+++ b/cli/src/engines/grok/normalizer.spec.ts
@@ -0,0 +1,121 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'fs'
+import { fileURLToPath } from 'url'
+import {
+ GrokNormalizer,
+ grokMessagesToEvents,
+ grokRecord,
+ grokToolInput,
+ grokToolName,
+ lastGrokTurnText,
+} from './normalizer.js'
+
+/** Real Grok 1.0.0 session; only the scratch cwd was scrubbed. */
+function lines(): string[] {
+ const path = fileURLToPath(new URL('../../lib/__fixtures__/grok-session.jsonl', import.meta.url))
+ return readFileSync(path, 'utf-8').split('\n').filter((line) => line.trim())
+}
+
+function liveEvents() {
+ const normalizer = new GrokNormalizer()
+ return lines().flatMap((line) => normalizer.ingest(line))
+}
+
+describe('grok normalizer', () => {
+ it('derives exactly one complete turn from the real session', () => {
+ const normalizer = new GrokNormalizer()
+ const events = lines().flatMap((line) => normalizer.ingest(line))
+ expect(events.filter((event) => event.type === 'turn_started')).toHaveLength(1)
+ expect(events.filter((event) => event.type === 'turn_ended')).toHaveLength(1)
+ expect(normalizer.turnOpen).toBe(false)
+ expect(events.find((event) => event.type === 'turn_started')).toMatchObject({
+ payload: { userMessage: expect.stringContaining('spawn exactly one explore subagent') },
+ })
+ })
+
+ it('maps the measured todo shape to the exact shared name and fields', () => {
+ const events = liveEvents()
+ const todo = events.find((event) => event.type === 'tool_start' && event.payload.tool === 'TodoWrite')
+ expect(todo).toMatchObject({
+ payload: {
+ input: {
+ todos: [
+ { content: 'inspect colors', status: 'in_progress' },
+ { content: 'report result', status: 'pending' },
+ ],
+ },
+ },
+ })
+ })
+
+ it('keeps the Task row open until the measured subagent_finished record', () => {
+ const normalizer = new GrokNormalizer()
+ const events = lines().flatMap((line) => normalizer.ingest(line))
+ const taskStart = events.find((event) => event.type === 'tool_start' && event.payload.tool === 'Task')
+ const finished = events.find((event) => event.type === 'subagent_finished')
+ expect(taskStart).toMatchObject({ payload: { input: { description: 'Count colors.txt lines' } } })
+ expect(finished).toMatchObject({
+ payload: { id: taskStart && 'id' in taskStart.payload ? taskStart.payload.id : '', status: 'completed' },
+ })
+ expect(events.indexOf(finished!)).toBeLessThan(events.findIndex((event) => event.type === 'turn_ended'))
+ })
+
+ it('pairs every measured tool card and maps the wait tool independently', () => {
+ const events = liveEvents()
+ const starts = events.filter((event) => event.type === 'tool_start')
+ const ends = events.filter((event) => event.type === 'tool_end')
+ expect(starts).toHaveLength(4)
+ expect(ends).toHaveLength(4)
+ expect(starts.some((event) => event.payload.tool === 'TaskWait')).toBe(true)
+ for (const start of starts) {
+ expect(ends.some((end) => end.payload.id === start.payload.id)).toBe(true)
+ }
+ })
+
+ it('emits reasoning and the final assistant answer', () => {
+ const events = liveEvents()
+ expect(events.some((event) => event.type === 'thinking_delta')).toBe(true)
+ const text = events.filter((event) => event.type === 'text_delta')
+ .map((event) => event.payload.content).join('\n')
+ expect(text).toContain('Line count:')
+ expect(text).toContain('get_command_or_subagent_output')
+ })
+
+ it('replays history without live lifecycle frames', () => {
+ const events = grokMessagesToEvents(lines())
+ expect(events[0]).toMatchObject({ type: 'user_message' })
+ expect(events.at(-1)).toEqual({ type: 'done', payload: { result: 'success' } })
+ expect(events.map((event) => event.type)).not.toContain('turn_started')
+ expect(events.map((event) => event.type)).not.toContain('turn_ended')
+ })
+
+ it('reads the real last turn for recap', () => {
+ const last = lastGrokTurnText(lines())
+ expect(last?.userMessage).toContain('todo tool')
+ expect(last?.assistantText).toContain('Line count:')
+ })
+
+ it('ignores malformed and non-update records', () => {
+ expect(grokRecord('bad json')).toBeNull()
+ expect(grokRecord('{"method":"session/update"}')).toBeNull()
+ expect(new GrokNormalizer().ingest('{}')).toEqual([])
+ })
+})
+
+describe('grok measured mappings', () => {
+ it('uses the shared names needed by product surfaces', () => {
+ expect(grokToolName('read_file')).toBe('Read')
+ expect(grokToolName('todo_write')).toBe('TodoWrite')
+ expect(grokToolName('spawn_subagent')).toBe('Task')
+ expect(grokToolName('get_command_or_subagent_output')).toBe('TaskWait')
+ expect(grokToolName('ask_user_question')).toBe('AskUserQuestion')
+ expect(grokToolName('unmeasured_tool')).toBe('Unmeasured Tool')
+ })
+
+ it('gives Read the file_path field shared cards consume', () => {
+ expect(grokToolInput('Read', { target_file: '/workspace/colors.txt' })).toEqual({
+ target_file: '/workspace/colors.txt',
+ file_path: '/workspace/colors.txt',
+ })
+ })
+})
diff --git a/cli/src/engines/grok/normalizer.ts b/cli/src/engines/grok/normalizer.ts
new file mode 100644
index 000000000..a391f691a
--- /dev/null
+++ b/cli/src/engines/grok/normalizer.ts
@@ -0,0 +1,331 @@
+/**
+ * Grok Build `updates.jsonl` -> Harness's shared event vocabulary.
+ *
+ * Measured on Grok 1.0.0. Each line is an ACP envelope whose discriminator lives at
+ * `params.update.sessionUpdate`. The persisted stream is the authority for both live tailing and
+ * history; `chat_history.jsonl` is the model-facing representation and omits UI-specific lifecycle
+ * records such as `subagent_spawned`, `subagent_finished`, `plan`, and `turn_completed`.
+ */
+
+import type { EngineNormalizer } from '../types.js'
+import type { LastTurnText, LiveEvent, SessionEvent } from '../../lib/normalize.js'
+
+type JsonObject = Record<string, unknown>
+
+const MAX_OUTPUT = 2_000
+const MAX_THINKING = 500
+
+/** Only names observed in real Grok sessions belong here. Unknown tools stay visibly generic. */
+const TOOL_NAMES: Record<string, string> = {
+ read_file: 'Read',
+ todo_write: 'TodoWrite',
+ spawn_subagent: 'Task',
+ get_command_or_subagent_output: 'TaskWait',
+ ask_user_question: 'AskUserQuestion',
+}
+
+export function grokToolName(name: string): string {
+ if (TOOL_NAMES[name]) return TOOL_NAMES[name]
+ const words = name.split(/[_\s-]+/).filter(Boolean)
+ return words.length ? words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(' ') : 'Tool'
+}
+
+function obj(value: unknown): JsonObject | null {
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as JsonObject : null
+}
+
+function str(value: unknown): string {
+ return typeof value === 'string' ? value : ''
+}
+
+function clip(value: string, max: number): string {
+ return value.length <= max ? value : `${value.slice(0, max)}\n...[truncated]`
+}
+
+export interface GrokRecord {
+ sessionId: string
+ kind: string
+ update: JsonObject
+ meta: JsonObject
+}
+
+export function grokRecord(line: string): GrokRecord | null {
+ let envelope: JsonObject | null
+ try { envelope = obj(JSON.parse(line)) } catch { return null }
+ const params = obj(envelope?.params)
+ const update = obj(params?.update)
+ const kind = str(update?.sessionUpdate)
+ if (!params || !update || !kind) return null
+ return {
+ sessionId: str(params.sessionId),
+ kind,
+ update,
+ meta: obj(params._meta) ?? {},
+ }
+}
+
+/** Normalize the few measured argument differences that otherwise render blank shared cards. */
+export function grokToolInput(tool: string, value: unknown): unknown {
+ const input = obj(value)
+ if (!input) return value ?? {}
+ if (tool === 'Read' && str(input.target_file) && !str(input.file_path)) {
+ return { ...input, file_path: str(input.target_file) }
+ }
+ // Grok already writes `{todos:[{content,status}]}`, exactly what the device consumes.
+ return input
+}
+
+function nestedText(value: unknown): string {
+ if (typeof value === 'string') return value
+ if (Array.isArray(value)) return value.map(nestedText).filter(Boolean).join('\n')
+ const valueObj = obj(value)
+ if (!valueObj) return ''
+ if (typeof valueObj.text === 'string') return valueObj.text
+ if ('content' in valueObj) return nestedText(valueObj.content)
+ return ''
+}
+
+/** Unwrap the result shapes observed across Read, Todo, Task, TaskOutput and AskUserQuestion. */
+export function grokToolOutput(update: JsonObject): string {
+ const content = nestedText(update.content)
+ if (content) return content
+ const raw = obj(update.rawOutput)
+ if (!raw) return typeof update.rawOutput === 'string' ? update.rawOutput : ''
+
+ const file = obj(raw.FileContent)
+ if (file) return str(file.raw_output) || str(file.content)
+ const todos = obj(raw.TodosUpdated)
+ if (todos) return str(todos.summary_for_prompt)
+ const task = obj(raw.Result)
+ if (task) return str(task.output) || str(task.command)
+ const answered = obj(raw.UserAnswered)
+ if (answered) return str(answered.message)
+ if (typeof raw.text === 'string') return raw.text
+
+ try { return JSON.stringify(raw) } catch { return '' }
+}
+
+function contentText(update: JsonObject): string {
+ return str(obj(update.content)?.text)
+}
+
+interface SpawnRow {
+ id: string
+ description: string
+}
+
+interface GrokTurnState {
+ open: boolean
+ toolNames: Map<string, string>
+ endedTools: Set<string>
+ pendingSpawns: SpawnRow[]
+ subagentRows: Map<string, string>
+ openRows: Set<string>
+}
+
+function newGrokTurnState(): GrokTurnState {
+ return {
+ open: false,
+ toolNames: new Map(),
+ endedTools: new Set(),
+ pendingSpawns: [],
+ subagentRows: new Map(),
+ openRows: new Set(),
+ }
+}
+
+function childIdFromSpawnOutput(output: string): string {
+ return /^subagent_id:\s*([^\s]+)$/m.exec(output)?.[1] ?? ''
+}
+
+function closeRows(state: GrokTurnState, events: LiveEvent[], status: string): void {
+ for (const id of state.openRows) events.push({ type: 'subagent_finished', payload: { id, status } })
+ state.openRows.clear()
+ state.pendingSpawns = []
+ state.subagentRows.clear()
+}
+
+function grokRecordToEvents(
+ record: GrokRecord,
+ state: GrokTurnState,
+ mode: 'live' | 'replay',
+): LiveEvent[] {
+ const events: LiveEvent[] = []
+ const { kind, update } = record
+
+ if (kind === 'user_message_chunk') {
+ const prompt = contentText(update).trim()
+ if (!prompt) return events
+ if (mode === 'replay') {
+ events.push({ type: 'user_message', payload: { content: prompt } })
+ return events
+ }
+ // One persisted user_message_chunk per measured prompt. If a prior boundary was lost, close it before
+ // opening the next one rather than merging two user turns into a permanently-open turn.
+ if (state.open) events.push({ type: 'turn_ended', payload: { aborted: true } })
+ state.open = true
+ state.toolNames.clear()
+ state.endedTools.clear()
+ state.pendingSpawns = []
+ state.subagentRows.clear()
+ state.openRows.clear()
+ events.push({ type: 'turn_started', payload: { userMessage: prompt } })
+ return events
+ }
+
+ if (kind === 'agent_thought_chunk') {
+ const text = contentText(update)
+ if (text) events.push({ type: 'thinking_delta', payload: { content: clip(text, MAX_THINKING) } })
+ return events
+ }
+
+ if (kind === 'agent_message_chunk') {
+ const text = contentText(update)
+ if (text) events.push({ type: 'text_delta', payload: { content: text } })
+ return events
+ }
+
+ if (kind === 'tool_call') {
+ const id = str(update.toolCallId)
+ if (!id || state.toolNames.has(id)) return events
+ const tool = grokToolName(str(update.title))
+ const input = grokToolInput(tool, update.rawInput)
+ state.toolNames.set(id, tool)
+ if (tool === 'Task') {
+ const description = str(obj(input)?.description) || 'sub-agent'
+ state.pendingSpawns.push({ id, description })
+ state.openRows.add(id)
+ }
+ events.push({ type: 'tool_start', payload: { id, tool, input } })
+ return events
+ }
+
+ if (kind === 'subagent_spawned') {
+ const child = str(update.subagent_id) || str(update.child_session_id)
+ if (!child) return events
+ const description = str(update.description)
+ const index = state.pendingSpawns.findIndex((row) => !description || row.description === description)
+ const row = index >= 0 ? state.pendingSpawns.splice(index, 1)[0] : state.pendingSpawns.shift()
+ if (row) state.subagentRows.set(child, row.id)
+ return events
+ }
+
+ if (kind === 'subagent_finished') {
+ if (mode === 'replay') return events
+ const child = str(update.subagent_id) || str(update.child_session_id)
+ const rowId = state.subagentRows.get(child)
+ if (!rowId || !state.openRows.delete(rowId)) return events
+ state.subagentRows.delete(child)
+ events.push({
+ type: 'subagent_finished',
+ payload: { id: rowId, status: str(update.status) || 'completed', summary: str(update.output) || undefined },
+ })
+ return events
+ }
+
+ if (kind === 'tool_call_update') {
+ const id = str(update.toolCallId)
+ const status = str(update.status).toLowerCase()
+ if (!id || !status || state.endedTools.has(id)) return events
+ if (!['completed', 'failed', 'error', 'cancelled'].includes(status)) return events
+ state.endedTools.add(id)
+ const tool = state.toolNames.get(id) ?? 'Tool'
+ const output = grokToolOutput(update)
+ const isError = status !== 'completed'
+
+ // `subagent_spawned` normally arrives before the spawn tool's completed update. The output carries the
+ // same child id as a fallback, so reordered streams still pair the async completion with its Task row.
+ if (tool === 'Task') {
+ const child = childIdFromSpawnOutput(output)
+ if (child && !state.subagentRows.has(child)) state.subagentRows.set(child, id)
+ if (isError && state.openRows.delete(id) && mode === 'live') {
+ events.push({ type: 'subagent_finished', payload: { id, status: 'failed' } })
+ }
+ }
+ events.push({
+ type: 'tool_end',
+ payload: {
+ id,
+ tool,
+ output: clip(output, MAX_OUTPUT),
+ isError,
+ summary: isError ? status : '',
+ },
+ })
+ return events
+ }
+
+ if (kind === 'turn_completed') {
+ if (mode === 'replay' || !state.open) return events
+ const failed = str(update.stop_reason) !== 'end_turn'
+ closeRows(state, events, failed ? 'failed' : 'completed')
+ state.open = false
+ state.toolNames.clear()
+ state.endedTools.clear()
+ events.push({ type: 'turn_ended', payload: failed ? { aborted: true } : {} })
+ return events
+ }
+
+ return events
+}
+
+export class GrokNormalizer implements EngineNormalizer {
+ private state = newGrokTurnState()
+
+ get turnOpen(): boolean { return this.state.open }
+
+ closeTurn(): void {
+ this.state.open = false
+ this.state.toolNames.clear()
+ this.state.endedTools.clear()
+ this.state.pendingSpawns = []
+ this.state.subagentRows.clear()
+ this.state.openRows.clear()
+ }
+
+ abortTurn(): LiveEvent[] {
+ if (!this.state.open) return []
+ const events: LiveEvent[] = []
+ closeRows(this.state, events, 'failed')
+ this.state.open = false
+ this.state.toolNames.clear()
+ this.state.endedTools.clear()
+ events.push({ type: 'turn_ended', payload: { aborted: true } })
+ return events
+ }
+
+ ingest(line: string): LiveEvent[] {
+ const record = grokRecord(line)
+ return record ? grokRecordToEvents(record, this.state, 'live') : []
+ }
+
+ finishReplay(): LiveEvent[] { return [] }
+}
+
+export function grokMessagesToEvents(lines: string[]): SessionEvent[] {
+ const state = newGrokTurnState()
+ const events: SessionEvent[] = []
+ for (const line of lines) {
+ const record = grokRecord(line)
+ if (record) events.push(...grokRecordToEvents(record, state, 'replay') as SessionEvent[])
+ }
+ events.push({ type: 'done', payload: { result: 'success' } })
+ return events
+}
+
+export function lastGrokTurnText(lines: string[]): LastTurnText | null {
+ let userMessage = ''
+ let assistantText = ''
+ for (const line of lines) {
+ const record = grokRecord(line)
+ if (!record) continue
+ if (record.kind === 'user_message_chunk') {
+ userMessage = contentText(record.update).trim()
+ assistantText = ''
+ } else if (record.kind === 'agent_message_chunk') {
+ const text = contentText(record.update).trim()
+ if (text) assistantText += `${assistantText ? '\n\n' : ''}${text}`
+ }
+ }
+ return assistantText ? { userMessage, assistantText } : null
+}
diff --git a/cli/src/engines/grok/runtimeProfile.spec.ts b/cli/src/engines/grok/runtimeProfile.spec.ts
new file mode 100644
index 000000000..d11218019
--- /dev/null
+++ b/cli/src/engines/grok/runtimeProfile.spec.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest'
+import { parseGrokFooterProfile, parseGrokModelsOutput } from './runtimeProfile.js'
+
+describe('Grok runtime profile', () => {
+ it('reads the measured idle footer', () => {
+ expect(parseGrokFooterProfile('--- Grok 4.5 (medium) · always-approve ---')).toEqual({
+ model: 'grok-4.5',
+ effort: 'medium',
+ })
+ })
+
+ it('reads the measured model catalog and skips prose', () => {
+ expect(parseGrokModelsOutput([
+ 'You are logged in with grok.com.',
+ '',
+ 'Default model: grok-4.5',
+ '',
+ 'Available models:',
+ ' * grok-4.5 (default)',
+ ].join('\n'))).toEqual(['grok-4.5'])
+ })
+})
diff --git a/cli/src/engines/grok/runtimeProfile.ts b/cli/src/engines/grok/runtimeProfile.ts
new file mode 100644
index 000000000..bdc5d01b6
--- /dev/null
+++ b/cli/src/engines/grok/runtimeProfile.ts
@@ -0,0 +1,26 @@
+/** Grok's idle footer: `Grok 4.5 (medium) · always-approve`. */
+export function parseGrokFooterProfile(capture: string): { model: string; effort: string } | null {
+ const lines = capture.replace(/\u001b\[[0-9;:]*[A-Za-z]/g, '').split('\n')
+ 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, '-'),
+ effort: match[2].toLowerCase(),
+ }
+ }
+ return null
+}
+
+/** `grok models` rows: ` * grok-4.5 (default)`. */
+export function parseGrokModelsOutput(output: string): string[] {
+ const models: string[] = []
+ const seen = new Set<string>()
+ for (const line of output.split('\n')) {
+ const model = /^\s*\*\s+([^\s]+)(?:\s+\(default\))?\s*$/.exec(line)?.[1]
+ if (!model || seen.has(model)) continue
+ seen.add(model)
+ models.push(model)
+ }
+ return models
+}
diff --git a/cli/src/engines/grok/session.spec.ts b/cli/src/engines/grok/session.spec.ts
new file mode 100644
index 000000000..f636ffe14
--- /dev/null
+++ b/cli/src/engines/grok/session.spec.ts
@@ -0,0 +1,59 @@
+import { mkdtemp, mkdir, rm, writeFile } from 'fs/promises'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { findGrokTranscript } from './session.js'
+
+const cleanup: string[] = []
+
+afterEach(async () => {
+ await Promise.all(cleanup.splice(0).map((path) => rm(path, { recursive: true, force: true })))
+})
+
+async function home(): Promise<string> {
+ const path = await mkdtemp(join(tmpdir(), 'grok-session-spec-'))
+ cleanup.push(path)
+ return path
+}
+
+describe('Grok transcript discovery', () => {
+ it('resolves the URL-encoded cwd layout', async () => {
+ const root = await home()
+ const cwd = '/workspace/project with spaces'
+ const sessionId = '8184b11d-175e-46cb-9cee-cf41cafe70d2'
+ const transcript = join(root, 'sessions', encodeURIComponent(cwd), sessionId, 'updates.jsonl')
+ await mkdir(join(transcript, '..'), { recursive: true })
+ await writeFile(transcript, '{}\n')
+
+ await expect(findGrokTranscript(root, cwd, sessionId)).resolves.toBe(transcript)
+ })
+
+ it('resolves the long-cwd hash layout through its .cwd sidecar', async () => {
+ const root = await home()
+ const cwd = `/workspace/${'long-segment/'.repeat(30)}`
+ const sessionId = '019fea5b-3a9c-7903-a30a-8d88a9342df6'
+ const group = join(root, 'sessions', 'a1b2c3d4')
+ const transcript = join(group, sessionId, 'updates.jsonl')
+ await mkdir(join(transcript, '..'), { recursive: true })
+ await writeFile(join(group, '.cwd'), `${cwd}\n`)
+ await writeFile(transcript, '{}\n')
+
+ await expect(findGrokTranscript(root, cwd, sessionId)).resolves.toBe(transcript)
+ })
+
+ it('does not bind a session from another cwd', async () => {
+ const root = await home()
+ const sessionId = '98ee3dac-40b1-4146-91dc-f65591f6289a'
+ const group = join(root, 'sessions', 'a1b2c3d4')
+ await mkdir(join(group, sessionId), { recursive: true })
+ await writeFile(join(group, '.cwd'), '/workspace/other\n')
+ await writeFile(join(group, sessionId, 'updates.jsonl'), '{}\n')
+
+ await expect(findGrokTranscript(root, '/workspace/wanted', sessionId)).resolves.toBeNull()
+ })
+
+ it('rejects a non-UUID session id before joining it into a path', async () => {
+ const root = await home()
+ await expect(findGrokTranscript(root, '/workspace/wanted', '../../outside')).resolves.toBeNull()
+ })
+})
diff --git a/cli/src/engines/grok/session.ts b/cli/src/engines/grok/session.ts
new file mode 100644
index 000000000..0d9c0fc04
--- /dev/null
+++ b/cli/src/engines/grok/session.ts
@@ -0,0 +1,24 @@
+import { readFile, readdir, stat } from 'fs/promises'
+import { join } from 'path'
+
+async function isFile(path: string): Promise<boolean> {
+ try { return (await stat(path)).isFile() } catch { return false }
+}
+
+/** Resolve Grok's `updates.jsonl`, including its hashed-directory fallback for very long cwd names. */
+export async function findGrokTranscript(grokHome: string, cwd: string, sessionId: string): Promise<string | null> {
+ if (!cwd || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sessionId)) return null
+ const root = join(grokHome, 'sessions')
+ const direct = join(root, encodeURIComponent(cwd), sessionId, 'updates.jsonl')
+ if (await isFile(direct)) return direct
+ const groups = await readdir(root, { withFileTypes: true }).catch(() => [])
+ for (const group of groups) {
+ if (!group.isDirectory()) continue
+ const dir = join(root, group.name)
+ const recorded = await readFile(join(dir, '.cwd'), 'utf8').catch(() => '')
+ if (recorded.trim() !== cwd) continue
+ const candidate = join(dir, sessionId, 'updates.jsonl')
+ if (await isFile(candidate)) return candidate
+ }
+ return null
+}
diff --git a/cli/src/engines/types.ts b/cli/src/engines/types.ts
index ab1af6fe4..d64551123 100644
--- a/cli/src/engines/types.ts
+++ b/cli/src/engines/types.ts
@@ -1,7 +1,7 @@
import type { LiveEvent } from '../lib/normalize.js'
import type { RegisteredSession } from '../lib/registry.js'
-export type AgentEngine = 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp' | 'kilo'
+export type AgentEngine = 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp' | 'kilo' | 'grok'
export interface EngineNormalizer {
ingest(line: string): LiveEvent[]
diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.ts
index 159145aee..90590a8b1 100644
--- a/cli/src/hookNotify.spec.ts
+++ b/cli/src/hookNotify.spec.ts
@@ -21,12 +21,13 @@ interface RunHookOpts {
/** The launcher id `harness <engine>` exports. Defaults to a live-looking one; pass null to simulate a
* CLI the user started by hand (no machine → the hook must ignore the event entirely). */
launcherId?: string | null
- engine?: 'claude' | 'codex' | 'cursor' | 'devin' | 'commandcode'
+ engine?: 'claude' | 'codex' | 'cursor' | 'devin' | 'commandcode' | 'grok'
env?: Record<string, string>
dataDir?: string
claudeProjectsDir?: string
codexHome?: string
cursorHome?: string
+ grokHome?: string
devinHome?: string
input?: Record<string, unknown>
}
@@ -45,6 +46,7 @@ function runHook(opts: RunHookOpts): Promise<string> {
if (opts.claudeProjectsDir) args.push('--claude-projects-dir', opts.claudeProjectsDir)
if (opts.codexHome) args.push('--codex-home', opts.codexHome)
if (opts.cursorHome) args.push('--cursor-home', opts.cursorHome)
+ if (opts.grokHome) args.push('--grok-home', opts.grokHome)
if (opts.devinHome) args.push('--devin-home', opts.devinHome)
const child = spawn(process.execPath, args, {
env,
@@ -472,6 +474,61 @@ describe('hook notify tmux scope', () => {
})
})
+describe('hook notify Grok lifecycle', () => {
+ it('resolves updates.jsonl, registers lifecycle events, and uses only StopFailure as a close fallback', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-grok-'))
+ tmpDirs.push(dir)
+ const grokHome = join(dir, 'grok')
+ const cwd = '/tmp/grok workspace'
+ const sessionId = '8184b11d-175e-46cb-9cee-cf41cafe70d2'
+ const transcript = join(grokHome, 'sessions', encodeURIComponent(cwd), sessionId, 'updates.jsonl')
+ mkdirSync(join(transcript, '..'), { recursive: true })
+ writeFileSync(transcript, '{}\n')
+ const { port, requests } = await collect()
+
+ await runHook({
+ port, tmuxPane: '%44', engine: 'grok', grokHome,
+ input: { hookEventName: 'session_start', sessionId, cwd, model: 'grok-4.5', cliVersion: '1.0.0' },
+ })
+ expect(requests).toEqual([{
+ url: '/api/hook/session-start',
+ body: expect.objectContaining({
+ engine: 'grok', hookEvent: 'SessionStart', sessionId, transcriptPath: transcript,
+ cwd, tmuxPane: '%44', model: 'grok-4.5', cliVersion: '1.0.0',
+ }),
+ }])
+
+ requests.splice(0)
+ await runHook({ port, tmuxPane: '%44', engine: 'grok', grokHome, input: { hookEventName: 'stop', sessionId, cwd } })
+ expect(requests).toEqual([])
+ await runHook({ port, tmuxPane: '%44', engine: 'grok', grokHome, input: { hookEventName: 'stop_failure', sessionId, cwd } })
+ expect(requests).toEqual([{
+ url: '/api/hook/turn-stop',
+ body: { sessionId, transcriptPath: transcript, status: 'error' },
+ }])
+ })
+
+ it('writes an offline fallback registry entry under the trusted Grok root', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-grok-offline-'))
+ tmpDirs.push(dir)
+ const grokHome = join(dir, 'grok')
+ const dataDir = join(dir, 'data')
+ const cwd = '/tmp/grok-offline'
+ const sessionId = '98ee3dac-175e-46cb-9cee-cf41cafe70d2'
+ const transcript = join(grokHome, 'sessions', encodeURIComponent(cwd), sessionId, 'updates.jsonl')
+ mkdirSync(join(transcript, '..'), { recursive: true })
+ writeFileSync(transcript, '{}\n')
+
+ await runHook({
+ port: 9, tmuxPane: '%45', engine: 'grok', grokHome, dataDir,
+ input: { hookEventName: 'session_start', sessionId, cwd },
+ })
+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))).toMatchObject([{
+ sessionId, engine: 'grok', transcriptPath: transcript, projectDir: 'grok-offline', cwd, tmuxPane: '%45',
+ }])
+ })
+})
+
/**
* Devin's documented user-level hook locations include `~/.claude/settings.json`, so the machine's CLAUDE
* hook can fire inside a Devin session and register it under the wrong engine. The claude arm bails out
diff --git a/cli/src/lib/__fixtures__/grok-session.jsonl b/cli/src/lib/__fixtures__/grok-session.jsonl
new file mode 100644
index 000000000..ab52e767f
--- /dev/null
+++ b/cli/src/lib/__fixtures__/grok-session.jsonl
@@ -0,0 +1,29 @@
+{"timestamp":1786343265,"method":"_x.ai/session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"hook_execution","event_name":"session_start","runs":[{"name":"global/settings:session_start[0].hooks[0]","status":{"status":"success","elapsed_ms":115}}]},"_meta":{"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-2","agentTimestampMs":1786343265892}}}
+{"timestamp":1786343269,"method":"_x.ai/session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"hook_execution","event_name":"user_prompt_submit","prompt_id":"1709bc01-c8e8-47fd-abd1-424b9494f452","runs":[{"name":"global/settings:user_prompt_submit[0].hooks[0]","status":{"status":"success","elapsed_ms":108}}]},"_meta":{"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-4","agentTimestampMs":1786343269257}}}
+{"timestamp":1786343272,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"Use the todo tool to create exactly two items: inspect colors and report result. Mark inspect colors in progress. Then spawn exactly one explore subagent to read /workspace/colors.txt and report its line count. Wait for that subagent to finish. Mark both todos complete, then answer with the line count and the exact tools you used."},"_meta":{"modelId":"grok-4.5","promptIndex":0}},"_meta":{"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-3","agentTimestampMs":1786343269145}}}
+{"timestamp":1786343272,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The user wants me to:\n1. Create exactly two todo items: \"inspect colors\" and \"report result\""}},"_meta":{"totalTokens":4903,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-27","agentTimestampMs":1786343272062,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343270497,"turnStartMs":1786343269258,"updateType":"AgentThoughtChunk","chunkId":23}}}
+{"timestamp":1786343275,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"I'll create the two todos, start the inspect item, then spawn an explore subagent to count lines in `colors.txt`."}},"_meta":{"totalTokens":4903,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-52","agentTimestampMs":1786343273055,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343270497,"turnStartMs":1786343269258,"updateType":"AgentMessageChunk","chunkId":48}}}
+{"timestamp":1786343275,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"tool_call","toolCallId":"call-522cf1f8-38e1-4fe1-a06d-67faabe41257-0","title":"todo_write","rawInput":{"todos":[{"id":"inspect-colors","content":"inspect colors","status":"in_progress"},{"id":"report-result","content":"report result","status":"pending"}],"merge":false},"_meta":{"x.ai/tool":{"version":1,"name":"todo_write","kind":"plan","namespace":"grok_build","label":"Plan","read_only":false}}},"_meta":{"totalTokens":14341,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-54","agentTimestampMs":1786343275157,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343270497,"turnStartMs":1786343269258,"updateType":"ToolCall","updateParams":{"toolCallId":"call-522cf1f8-38e1-4fe1-a06d-67faabe41257-0","title":"todo_write","kind":"Other","status":"Pending"}}}}
+{"timestamp":1786343275,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"tool_call_update","toolCallId":"call-522cf1f8-38e1-4fe1-a06d-67faabe41257-0","kind":"think","title":"Updating plan","locations":[],"rawInput":{"variant":"TodoWrite","merge":false,"todos":[{"id":"inspect-colors","content":"inspect colors","status":"in_progress"},{"id":"report-result","content":"report result","status":"pending"}]},"_meta":{"x.ai/tool":{"version":1,"name":"todo_write","kind":"plan","namespace":"grok_build","label":"Plan","read_only":false}}},"_meta":{"totalTokens":14341,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-55","agentTimestampMs":1786343275158,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343270497,"turnStartMs":1786343269258,"updateType":"ToolCallUpdate","updateParams":{"toolCallId":"call-522cf1f8-38e1-4fe1-a06d-67faabe41257-0","status":null}}}}
+{"timestamp":1786343275,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"tool_call","toolCallId":"call-522cf1f8-38e1-4fe1-a06d-67faabe41257-1","title":"spawn_subagent","rawInput":{"description":"Count colors.txt lines","prompt":"Read the file /workspace/colors.txt and report its exact line count. Return only the line count number and a brief confirmation of what you found.","subagent_type":"explore","capability_mode":"read-only","background":true},"_meta":{"x.ai/tool":{"version":1,"name":"spawn_subagent","kind":"task","namespace":"grok_build","label":"Subagent","read_only":false},"subagentBackground":true}},"_meta":{"totalTokens":14341,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-56","agentTimestampMs":1786343275160,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343270497,"turnStartMs":1786343269258,"updateType":"ToolCall","updateParams":{"toolCallId":"call-522cf1f8-38e1-4fe1-a06d-67faabe41257-1","title":"spawn_subagent","kind":"Other","status":"Pending"}}}}
+{"timestamp":1786343275,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"tool_call_update","toolCallId":"call-522cf1f8-38e1-4fe1-a06d-67faabe41257-1","kind":"other","title":"Count colors.txt lines","locations":[],"rawInput":{"variant":"Task","prompt":"Read the file /workspace/colors.txt and report its exact line count. Return only the line count number and a brief confirmation of what you found.","description":"Count colors.txt lines","subagent_type":"explore","run_in_background":true,"capability_mode":"read-only","task_id":null},"_meta":{"x.ai/tool":{"version":1,"name":"spawn_subagent","kind":"task","namespace":"grok_build","label":"Subagent","read_only":false}}},"_meta":{"totalTokens":14341,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-57","agentTimestampMs":1786343275160,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343270497,"turnStartMs":1786343269258,"updateType":"ToolCallUpdate","updateParams":{"toolCallId":"call-522cf1f8-38e1-4fe1-a06d-67faabe41257-1","status":null}}}}
+{"timestamp":1786343275,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"tool_call_update","toolCallId":"call-522cf1f8-38e1-4fe1-a06d-67faabe41257-0","status":"completed","rawOutput":{"type":"Todo","TodosUpdated":{"summary_for_prompt":"- [in_progress] inspect-colors: inspect colors\n- [pending] report-result: report result\n","todos":[{"content":"inspect colors","priority":"medium","status":"in_progress"},{"content":"report result","priority":"medium","status":"pending"}],"state":{"todos":{"inspect-colors":{"content":"inspect colors","priority":"medium","status":"in_progress"},"report-result":{"content":"report result","priority":"medium","status":"pending"}}}}}},"_meta":{"totalTokens":14341,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-58","agentTimestampMs":1786343275167,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343270497,"turnStartMs":1786343269258,"updateType":"ToolCallUpdate","updateParams":{"toolCallId":"call-522cf1f8-38e1-4fe1-a06d-67faabe41257-0","status":"Completed"}}}}
+{"timestamp":1786343275,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"plan","entries":[{"content":"inspect colors","priority":"medium","status":"in_progress"},{"content":"report result","priority":"medium","status":"pending"}]},"_meta":{"totalTokens":14341,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-59","agentTimestampMs":1786343275167,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343270497,"turnStartMs":1786343269258,"updateType":"Plan","updateParams":{"planSteps":2}}}}
+{"timestamp":1786343275,"method":"_x.ai/session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"subagent_spawned","subagent_id":"019fea5b-3a9c-7903-a30a-8d88a9342df6","parent_session_id":"8184b11d-175e-46cb-9cee-cf41cafe70d2","parent_prompt_id":"1709bc01-c8e8-47fd-abd1-424b9494f452","child_session_id":"019fea5b-3a9c-7903-a30a-8d88a9342df6","subagent_type":"explore","description":"Count colors.txt lines","effective_context_source":"new","capability_mode":"read-only","role":"explore","model":"grok-4.5"},"_meta":{"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-61","agentTimestampMs":1786343275171}}}
+{"timestamp":1786343276,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"tool_call_update","toolCallId":"call-522cf1f8-38e1-4fe1-a06d-67faabe41257-1","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Subagent started in background.\nsubagent_id: 019fea5b-3a9c-7903-a30a-8d88a9342df6\ntype: explore\ndescription: Count colors.txt lines\n\nUse get_command_or_subagent_output with task_ids=[\"019fea5b-3a9c-7903-a30a-8d88a9342df6\"] and timeout_ms to wait for results."}}],"rawOutput":{"type":"Text","text":"Subagent started in background.\nsubagent_id: 019fea5b-3a9c-7903-a30a-8d88a9342df6\ntype: explore\ndescription: Count colors.txt lines\n\nUse get_command_or_subagent_output with task_ids=[\"019fea5b-3a9c-7903-a30a-8d88a9342df6\"] and timeout_ms to wait for results."}},"_meta":{"totalTokens":14363,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-60","agentTimestampMs":1786343275167,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343270497,"turnStartMs":1786343269258,"updateType":"ToolCallUpdate","updateParams":{"toolCallId":"call-522cf1f8-38e1-4fe1-a06d-67faabe41257-1","status":"Completed"}}}}
+{"timestamp":1786343277,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Now I need to wait for the subagent to finish."}},"_meta":{"totalTokens":14427,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-76","agentTimestampMs":1786343276967,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343275997,"turnStartMs":1786343269258,"updateType":"AgentThoughtChunk","chunkId":12}}}
+{"timestamp":1786343277,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"tool_call","toolCallId":"call-1a38541b-d62e-4708-97f5-930a0dd8065c-2","title":"get_command_or_subagent_output","rawInput":{"task_ids":["019fea5b-3a9c-7903-a30a-8d88a9342df6"],"timeout_ms":120000},"_meta":{"x.ai/tool":{"version":1,"name":"get_command_or_subagent_output","kind":"background_task_action","namespace":"grok_build","label":"Background Task","read_only":true}}},"_meta":{"totalTokens":14407,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-78","agentTimestampMs":1786343277357,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343275997,"turnStartMs":1786343269258,"updateType":"ToolCall","updateParams":{"toolCallId":"call-1a38541b-d62e-4708-97f5-930a0dd8065c-2","title":"get_command_or_subagent_output","kind":"Other","status":"Pending"}}}}
+{"timestamp":1786343285,"method":"_x.ai/session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"subagent_finished","subagent_id":"019fea5b-3a9c-7903-a30a-8d88a9342df6","child_session_id":"019fea5b-3a9c-7903-a30a-8d88a9342df6","status":"completed","tool_calls":1,"turns":1,"duration_ms":7332,"tokens_used":5504,"output":"3\n\n`/workspace/colors.txt` has exactly **3** lines (red, green, blue).","will_wake":false},"_meta":{"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-162","agentTimestampMs":1786343285644}}}
+{"timestamp":1786343285,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"tool_call_update","toolCallId":"call-1a38541b-d62e-4708-97f5-930a0dd8065c-2","kind":"other","title":"Get task output: 019fea5b-3a9c-7903-a30a-8d88a9342df6","locations":[],"rawInput":{"variant":"TaskOutput","task_ids":["019fea5b-3a9c-7903-a30a-8d88a9342df6"],"timeout_ms":120000},"_meta":{"x.ai/tool":{"version":1,"name":"get_command_or_subagent_output","kind":"background_task_action","namespace":"grok_build","label":"Background Task","read_only":true}}},"_meta":{"totalTokens":14407,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-79","agentTimestampMs":1786343277357,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343275997,"turnStartMs":1786343269258,"updateType":"ToolCallUpdate","updateParams":{"toolCallId":"call-1a38541b-d62e-4708-97f5-930a0dd8065c-2","status":null}}}}
+{"timestamp":1786343287,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"tool_call_update","toolCallId":"call-1a38541b-d62e-4708-97f5-930a0dd8065c-2","status":"completed","title":"[subagent:explore] Count colors.txt lines (019fea5b)","rawOutput":{"type":"TaskOutput","Result":{"task_id":"019fea5b-3a9c-7903-a30a-8d88a9342df6","command":"[subagent:explore] Count colors.txt lines","status":"completed","exit_code":0,"started":"2026-08-10T06:27:55Z","ended":"2026-08-10T06:28:02Z","duration_secs":7.332,"output":"3\n\n`/workspace/colors.txt` has exactly **3** lines (red, green, blue).\n\n<subagent_meta>id=019fea5b-3a9c-7903-a30a-8d88a9342df6, type=explore, tool_calls=1, turns=1, duration_ms=7332</subagent_meta>\n\n<subagent_result>\nsubagent_id: 019fea5b-3a9c-7903-a30a-8d88a9342df6\nsubagent_type: explore\nTo continue this subagent's conversation, use resume_from=\"019fea5b-3a9c-7903-a30a-8d88a9342df6\".\n</subagent_result>","output_file":"","truncated":false,"truncation_hint":"","raw_output_bytes":419}}},"_meta":{"totalTokens":14407,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-163","agentTimestampMs":1786343285646,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343275997,"turnStartMs":1786343269258,"updateType":"ToolCallUpdate","updateParams":{"toolCallId":"call-1a38541b-d62e-4708-97f5-930a0dd8065c-2","status":"Completed"}}}}
+{"timestamp":1786343288,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The subagent reported 3 lines. Now I need to mark both todos complete and answer with the line count and exact tools used."}},"_meta":{"totalTokens":14552,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-191","agentTimestampMs":1786343287216,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343286220,"turnStartMs":1786343269258,"updateType":"AgentThoughtChunk","chunkId":27}}}
+{"timestamp":1786343288,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"tool_call","toolCallId":"call-1e8f27b8-37f6-4b6e-8c60-837e77999719-3","title":"todo_write","rawInput":{"todos":[{"id":"inspect-colors","content":"inspect colors","status":"completed"},{"id":"report-result","content":"report result","status":"completed"}],"merge":true},"_meta":{"x.ai/tool":{"version":1,"name":"todo_write","kind":"plan","namespace":"grok_build","label":"Plan","read_only":false}}},"_meta":{"totalTokens":14783,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-193","agentTimestampMs":1786343288117,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343286220,"turnStartMs":1786343269258,"updateType":"ToolCall","updateParams":{"toolCallId":"call-1e8f27b8-37f6-4b6e-8c60-837e77999719-3","title":"todo_write","kind":"Other","status":"Pending"}}}}
+{"timestamp":1786343288,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"tool_call_update","toolCallId":"call-1e8f27b8-37f6-4b6e-8c60-837e77999719-3","kind":"think","title":"Updating plan","locations":[],"rawInput":{"variant":"TodoWrite","merge":true,"todos":[{"id":"inspect-colors","content":"inspect colors","status":"completed"},{"id":"report-result","content":"report result","status":"completed"}]},"_meta":{"x.ai/tool":{"version":1,"name":"todo_write","kind":"plan","namespace":"grok_build","label":"Plan","read_only":false}}},"_meta":{"totalTokens":14783,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-194","agentTimestampMs":1786343288117,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343286220,"turnStartMs":1786343269258,"updateType":"ToolCallUpdate","updateParams":{"toolCallId":"call-1e8f27b8-37f6-4b6e-8c60-837e77999719-3","status":null}}}}
+{"timestamp":1786343288,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"tool_call_update","toolCallId":"call-1e8f27b8-37f6-4b6e-8c60-837e77999719-3","status":"completed","rawOutput":{"type":"Todo","TodosUpdated":{"summary_for_prompt":"- [completed] inspect-colors: inspect colors\n- [completed] report-result: report result\n","todos":[{"content":"inspect colors","priority":"medium","status":"completed"},{"content":"report result","priority":"medium","status":"completed"}],"state":{"todos":{"inspect-colors":{"content":"inspect colors","priority":"medium","status":"completed"},"report-result":{"content":"report result","priority":"medium","status":"completed"}}}}}},"_meta":{"totalTokens":14783,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-195","agentTimestampMs":1786343288117,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343286220,"turnStartMs":1786343269258,"updateType":"ToolCallUpdate","updateParams":{"toolCallId":"call-1e8f27b8-37f6-4b6e-8c60-837e77999719-3","status":"Completed"}}}}
+{"timestamp":1786343289,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"plan","entries":[{"content":"inspect colors","priority":"medium","status":"completed"},{"content":"report result","priority":"medium","status":"completed"}]},"_meta":{"totalTokens":14783,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-196","agentTimestampMs":1786343288117,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343286220,"turnStartMs":1786343269258,"updateType":"Plan","updateParams":{"planSteps":2}}}}
+{"timestamp":1786343289,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"I have all the information. Line count is 3. Tools used:"}},"_meta":{"totalTokens":14805,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-211","agentTimestampMs":1786343289668,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343288688,"turnStartMs":1786343269258,"updateType":"AgentThoughtChunk","chunkId":15}}}
+{"timestamp":1786343291,"method":"_x.ai/session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"hook_execution","event_name":"stop","prompt_id":"1709bc01-c8e8-47fd-abd1-424b9494f452","runs":[{"name":"global/settings:stop[0].hooks[0]","status":{"status":"success","elapsed_ms":134}}]},"_meta":{"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-302","agentTimestampMs":1786343291454}}}
+{"timestamp":1786343291,"method":"session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"**Line count:** 3\n\n**Tools used:**\n1. `todo_write` — created the two todos and marked “inspect colors” in progress \n2. `spawn_subagent` — launched one explore subagent to read `colors.txt` \n3. `get_command_or_subagent_output` — waited for the subagent to finish \n4. `todo_write` — marked both todos complete"}},"_meta":{"totalTokens":14805,"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-300","agentTimestampMs":1786343291230,"promptId":"1709bc01-c8e8-47fd-abd1-424b9494f452","streamStartMs":1786343288688,"turnStartMs":1786343269258,"updateType":"AgentMessageChunk","chunkId":104}}}
+{"timestamp":1786343291,"method":"_x.ai/session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"turn_completed","prompt_id":"1709bc01-c8e8-47fd-abd1-424b9494f452","stop_reason":"end_turn","usage":{"inputTokens":68413,"outputTokens":655,"totalTokens":69068,"cachedReadTokens":48256,"cacheCreationTokens":0,"reasoningTokens":237,"modelCalls":6,"apiDurationMs":20065,"costUsdTicks":587208000,"modelUsage":{"grok-4.5":{"inputTokens":68413,"outputTokens":655,"totalTokens":69068,"cachedReadTokens":48256,"cacheCreationTokens":0,"reasoningTokens":237,"modelCalls":6,"apiDurationMs":20065,"costUsdTicks":587208000}},"numTurns":4}},"_meta":{"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-303","agentTimestampMs":1786343291456}}}
+{"timestamp":1786343292,"method":"_x.ai/session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"hook_execution","event_name":"session_end","runs":[{"name":"global/settings:session_end[0].hooks[0]","status":{"status":"success","elapsed_ms":112}}]},"_meta":{"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-304","agentTimestampMs":1786343292578}}}
+{"timestamp":1786343292,"method":"_x.ai/session/update","params":{"sessionId":"8184b11d-175e-46cb-9cee-cf41cafe70d2","update":{"sessionUpdate":"hook_execution","event_name":"stop","runs":[{"name":"global/settings:stop[0].hooks[0]","status":{"status":"success","elapsed_ms":108}}]},"_meta":{"eventId":"8184b11d-175e-46cb-9cee-cf41cafe70d2-305","agentTimestampMs":1786343292686}}}
diff --git a/cli/src/lib/__fixtures__/question-grok.txt b/cli/src/lib/__fixtures__/question-grok.txt
new file mode 100644
index 000000000..c5bfdcbad
--- /dev/null
+++ b/cli/src/lib/__fixtures__/question-grok.txt
@@ -0,0 +1,17 @@
+ /workspace [Click here to Upgrade] 13K / 500K
+
+ > Before answering, ask which color I should report.
+
+ * Ask Which color should I report?
+
+ * Waiting on answers for Which color should I report? 4.2s
+
+ | Which color should I report?
+ |
+ | 1 (o) Red Report the color Red
+ | 2 (o) Blue Report the color Blue
+ | z (o) Type your answer here
+ |
+ | up/down navigate - y copy Enter:submit
+
+ Tab:next answer | Esc:scrollback | Shift+x:dismiss
diff --git a/cli/src/lib/askQuestion.ts b/cli/src/lib/askQuestion.ts
index b17d6c4ce..cc6d67a02 100644
--- a/cli/src/lib/askQuestion.ts
+++ b/cli/src/lib/askQuestion.ts
@@ -27,6 +27,7 @@ import { parseMuseQuestionPane } from '../engines/muse/askQuestion.js'
import { ampSelectionKeys, parseAmpQuestionPane } from '../engines/amp/askQuestion.js'
import { kiloSelectionKeys, parseKiloQuestionPane } from '../engines/kilo/askQuestion.js'
import { parseDevinQuestionPane } from '../engines/devin/askQuestion.js'
+import { parseGrokQuestionPane } from '../engines/grok/askQuestion.js'
/** Device-facing question shape — byte-for-byte the hosted runtime’s `commanderQuestions()` output. */
export interface ShapedQuestion {
@@ -125,6 +126,7 @@ export function parseEngineQuestionPane(engine: AgentEngine, capture: string): P
// Kilo's is the same kind of prompt but laid out HORIZONTALLY, sharing its line with the key hints —
// it is a fork of opencode that did not keep opencode's dialog.
if (engine === 'kilo') return parseKiloQuestionPane(capture)
+ if (engine === 'grok') return parseGrokQuestionPane(capture)
// Hermes and OpenCode paint Claude's dialog inside a box; peel the border and the shared parser fits.
if (engine === 'hermes') return parseQuestionPane(unframe(capture))
if (engine === 'opencode') {
@@ -513,7 +515,7 @@ export interface QuestionWatcherDeps {
const POLL_MS = 1500
// Amp is here for its PERMISSION prompt, not a question tool — it has none. That prompt is drawn only in
// the pane and recorded nowhere, so polling the pane is the only way it is ever seen.
-const QUESTION_ENGINES = new Set<AgentEngine>(['claude', 'commandcode', 'devin', 'hermes', 'opencode', 'muse', 'amp', 'kilo'])
+const QUESTION_ENGINES = new Set<AgentEngine>(['claude', 'commandcode', 'devin', 'hermes', 'opencode', 'muse', 'amp', 'kilo', 'grok'])
/** Does this engine ever paint a question dialog? Callers use it to decide whether to watch its pane. */
export function pollsQuestions(engine: AgentEngine): boolean {
diff --git a/cli/src/lib/engineBin.ts b/cli/src/lib/engineBin.ts
index bef0fa520..7c06cce43 100644
--- a/cli/src/lib/engineBin.ts
+++ b/cli/src/lib/engineBin.ts
@@ -12,7 +12,7 @@ import type { AgentEngine } from '../engines/types.js'
/** Every engine the adapter can drive — also the set of `harness <engine>` launch subcommands. */
export const ENGINES: readonly AgentEngine[] = [
- 'claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo',
+ 'claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok',
] as const
/**
@@ -86,5 +86,6 @@ export function engineBin(engine: AgentEngine): string {
case 'muse': return env.MUSE_PATH || 'muse'
case 'amp': return env.AMP_PATH || 'amp'
case 'kilo': return env.KILO_PATH || 'kilo'
+ case 'grok': return env.GROK_PATH || 'grok'
}
}
diff --git a/cli/src/lib/enginePermissions.spec.ts b/cli/src/lib/enginePermissions.spec.ts
index 673b34c32..1f1b893b2 100644
--- a/cli/src/lib/enginePermissions.spec.ts
+++ b/cli/src/lib/enginePermissions.spec.ts
@@ -37,6 +37,8 @@ describe('default permission flags', () => {
// the root command rejects both. Adding either would stop the agent starting at all. The recap
// one-shot DOES pass `--auto`, because it invokes the `run` subcommand — see lib/oneshot.ts.
kilo: [],
+ // Documented by Grok 1.0.0 and reflected in the live TUI footer as `always-approve`.
+ grok: ['--always-approve'],
})
})
@@ -47,6 +49,7 @@ describe('default permission flags', () => {
expect(permissionArgsFor('claude', ['--permission-mode', 'plan'])).toEqual([])
expect(permissionArgsFor('devin', ['--permission-mode', 'accept-edits'])).toEqual([])
expect(permissionArgsFor('hermes', ['--safe-mode'])).toEqual([])
+ expect(permissionArgsFor('grok', ['--permission-mode', 'auto'])).toEqual([])
// `--flag=value` is the same choice as `--flag value`.
expect(permissionArgsFor('claude', ['--permission-mode=plan'])).toEqual([])
})
diff --git a/cli/src/lib/enginePermissions.ts b/cli/src/lib/enginePermissions.ts
index 84c8dd670..297cabc57 100644
--- a/cli/src/lib/enginePermissions.ts
+++ b/cli/src/lib/enginePermissions.ts
@@ -145,6 +145,16 @@ const PERMISSIONS: Readonly<Record<AgentEngine, EnginePermissions>> = {
add: [{ axis: 'permission', args: ['--dangerously-allow-all'] }],
owned: { permission: ['--dangerously-allow-all'] },
},
+ // `--always-approve` is Grok's documented unattended mode. The other policy switches are owned so
+ // an explicit user choice is never overridden by the launcher default.
+ grok: {
+ add: [{ axis: 'permission', args: ['--always-approve'] }],
+ owned: {
+ permission: [
+ '--always-approve', '--permission-mode', '--allow', '--deny', '--tools', '--disallowed-tools',
+ ],
+ },
+ },
}
/** Whole-argv-entry match; `--flag=value` is the same choice as `--flag value`. */
diff --git a/cli/src/lib/goalCommand.spec.ts b/cli/src/lib/goalCommand.spec.ts
index cb6d1dc5e..9128c2b7f 100644
--- a/cli/src/lib/goalCommand.spec.ts
+++ b/cli/src/lib/goalCommand.spec.ts
@@ -1,8 +1,8 @@
import { describe, expect, it } from 'vitest'
import { adaptGoalCommand, adaptSlashCommand, engineSupportsGoal, engineSupportsLoop } from './goalCommand.js'
-const ALL_ENGINES = ['claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse'] as const
-const NON_LOOP = ['codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse'] as const
+const ALL_ENGINES = ['claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok'] as const
+const NON_LOOP = ['codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok'] as const
describe('adaptGoalCommand', () => {
it('keeps /goal verbatim for engines with a native /goal (claude, codex)', () => {
@@ -13,8 +13,8 @@ describe('adaptGoalCommand', () => {
}
})
- it('drops the leading slash for engines without /goal (cursor, opencode, pi)', () => {
- for (const engine of ['cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin'] as const) {
+ it('drops the leading slash for engines without a verified native /goal', () => {
+ for (const engine of ALL_ENGINES.filter((candidate) => candidate !== 'claude' && candidate !== 'codex')) {
expect(engineSupportsGoal(engine)).toBe(false)
expect(adaptGoalCommand('/goal fix the bug', engine)).toBe('goal fix the bug')
expect(adaptGoalCommand('/goal', engine)).toBe('goal')
@@ -23,7 +23,7 @@ describe('adaptGoalCommand', () => {
})
it('leaves non-/goal content untouched for every engine', () => {
- for (const engine of ['claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin'] as const) {
+ for (const engine of ALL_ENGINES) {
expect(adaptGoalCommand('just a normal message', engine)).toBe('just a normal message')
expect(adaptGoalCommand('/model gpt-5', engine)).toBe('/model gpt-5')
expect(adaptGoalCommand('/goalkeeper stats', engine)).toBe('/goalkeeper stats') // /goal must be a whole token
diff --git a/cli/src/lib/grokOneShot.spec.ts b/cli/src/lib/grokOneShot.spec.ts
new file mode 100644
index 000000000..512ede229
--- /dev/null
+++ b/cli/src/lib/grokOneShot.spec.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest'
+import { grokOneShotSpawn } from './oneshot.js'
+
+describe('Grok recap containment', () => {
+ const options = { prompt: 'summarize this', model: 'grok-4.5', effort: 'low' as const, cwd: '/tmp/summary' }
+
+ it('uses print JSON mode with bounded turns and no memory or plan', () => {
+ const { args } = grokOneShotSpawn(options, '/tmp/isolated-grok', {})
+ expect(args).toEqual([
+ '--cwd', '/tmp/summary',
+ '--always-approve', '--no-memory', '--no-plan', '--max-turns', '1',
+ '--output-format', 'json', '--model', 'grok-4.5', '--reasoning-effort', 'low',
+ '-p', 'summarize this',
+ ])
+ })
+
+ it('isolates state and strips agent-discovery variables', () => {
+ const { env } = grokOneShotSpawn(options, '/tmp/isolated-grok', {
+ TMUX: 'socket', TMUX_PANE: '%9', MACHINE_ID: 'agent', HOME: '/real-home',
+ })
+ expect(env.GROK_HOME).toBe('/tmp/isolated-grok')
+ expect(env.HOME).toBe('/real-home')
+ expect(env.TMUX).toBeUndefined()
+ expect(env.TMUX_PANE).toBeUndefined()
+ expect(env.MACHINE_ID).toBeUndefined()
+ })
+})
diff --git a/cli/src/lib/hooks.spec.ts b/cli/src/lib/hooks.spec.ts
index e752efcc0..fdc4933e7 100644
--- a/cli/src/lib/hooks.spec.ts
+++ b/cli/src/lib/hooks.spec.ts
@@ -1,10 +1,11 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
import { join } from 'path'
import { tmpdir } from 'os'
let codexHome = ''
let cursorHome = ''
+let grokHome = ''
let hermesHome = ''
let commandcodeHome = ''
let devinConfigPath = ''
@@ -13,6 +14,7 @@ async function loadHooks() {
vi.resetModules()
process.env.CODEX_HOME = codexHome
process.env.CURSOR_HOME = cursorHome
+ process.env.GROK_HOME = grokHome
process.env.HERMES_HOME = hermesHome
process.env.COMMANDCODE_HOME = commandcodeHome
process.env.DEVIN_CONFIG_PATH = devinConfigPath
@@ -94,6 +96,41 @@ describe('Codex hook installation', () => {
})
})
+describe('Grok hook installation', () => {
+ beforeEach(() => {
+ grokHome = mkdtempSync(join(tmpdir(), 'adapter-grok-hooks-'))
+ })
+
+ afterEach(() => {
+ rmSync(grokHome, { recursive: true, force: true })
+ delete process.env.GROK_HOME
+ })
+
+ it('installs camelCase lifecycle hooks without the early Stop signal', async () => {
+ const { installGrokHooks } = await loadHooks()
+ installGrokHooks(18473)
+ const file = join(grokHome, 'hooks', 'harness.json')
+ const first = readFileSync(file, 'utf8')
+ const out = JSON.parse(first) as { hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>> }
+ expect(Object.keys(out.hooks).sort()).toEqual(['SessionEnd', 'SessionStart', 'StopFailure', 'UserPromptSubmit'])
+ expect(out.hooks).not.toHaveProperty('Stop')
+ expect(out.hooks.SessionStart[0].hooks[0].command).toContain('--engine grok')
+ expect(out.hooks.SessionStart[0].hooks[0].command).toContain(`--grok-home '${grokHome}'`)
+
+ installGrokHooks(18473)
+ expect(readFileSync(file, 'utf8')).toBe(first)
+ })
+
+ it('leaves malformed Grok hook JSON untouched', async () => {
+ const file = join(grokHome, 'hooks', 'harness.json')
+ mkdirSync(join(grokHome, 'hooks'), { recursive: true })
+ writeFileSync(file, '{not-json')
+ const { installGrokHooks } = await loadHooks()
+ installGrokHooks(18473)
+ expect(readFileSync(file, 'utf8')).toBe('{not-json')
+ })
+})
+
describe('Command Code hook installation', () => {
let file = ''
diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.ts
index 357014cfd..b4124eed9 100644
--- a/cli/src/lib/hooks.ts
+++ b/cli/src/lib/hooks.ts
@@ -15,6 +15,7 @@ import type { AgentEngine } from '../engines/types.js'
const SETTINGS_PATH = join(homedir(), '.claude', 'settings.json')
const CODEX_HOOKS_PATH = join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'hooks.json')
+const GROK_HOOKS_PATH = join(env.GROK_HOME, 'hooks', 'harness.json')
const CURSOR_HOOKS_PATH = join(process.env.CURSOR_HOME || join(homedir(), '.cursor'), 'hooks.json')
// notify.mjs location depends on the layout (import.meta.url is the REAL executing file at runtime):
@@ -49,7 +50,7 @@ function shellQuote(value: string): string {
return `'${value.replace(/'/g, `'\\''`)}'`
}
-function command(port: number, engine: 'claude' | 'codex' | 'cursor' | 'hermes' | 'commandcode' | 'devin'): string {
+function command(port: number, engine: 'claude' | 'codex' | 'cursor' | 'hermes' | 'commandcode' | 'devin' | 'grok'): string {
return [
'node',
shellQuote(HOOK_SCRIPT),
@@ -57,6 +58,7 @@ function command(port: number, engine: 'claude' | 'codex' | 'cursor' | 'hermes'
'--data-dir', shellQuote(env.ADAPTER_DATA_DIR),
'--claude-projects-dir', shellQuote(env.CLAUDE_PROJECTS_DIR),
'--codex-home', shellQuote(env.CODEX_HOME),
+ '--grok-home', shellQuote(env.GROK_HOME),
'--cursor-home', shellQuote(env.CURSOR_HOME),
'--commandcode-home', shellQuote(env.COMMANDCODE_HOME),
'--devin-home', shellQuote(env.DEVIN_HOME),
@@ -173,6 +175,47 @@ export function installCodexHooks(port: number): void {
}
}
+/** Merge the adapter's Grok lifecycle hooks into a dedicated global hook file. Grok loads every JSON
+ * file in ~/.grok/hooks, so using our own file avoids touching the user's other hook packages. Normal
+ * Stop is intentionally omitted because its record precedes Grok's final assistant chunk on disk. */
+export function installGrokHooks(port: number): void {
+ let settings: Settings = {}
+ if (existsSync(GROK_HOOKS_PATH)) {
+ try {
+ settings = JSON.parse(readFileSync(GROK_HOOKS_PATH, 'utf-8')) as Settings
+ } catch {
+ console.error(`[hooks] Grok hooks file is invalid JSON; leaving it unchanged: ${GROK_HOOKS_PATH}`)
+ console.error('[hooks] fix the file, then restart harness join')
+ return
+ }
+ }
+ if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}
+
+ const cmd = command(port, 'grok')
+ const required = ['SessionStart', 'SessionEnd', 'UserPromptSubmit', 'StopFailure'] as const
+ let changed = false
+ for (const event of required) {
+ const blocks = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : []
+ const foreign = blocks.filter((b) => !isOurs(b))
+ const ours = blocks.filter(isOurs)
+ const canonical: HookBlock = { hooks: [{ type: 'command', command: cmd, timeout: 5 }] }
+ if (ours.length !== 1 || ours[0]?.hooks?.[0]?.command !== cmd) changed = true
+ settings.hooks[event] = [...foreign, canonical]
+ }
+
+ if (!changed) {
+ console.log('[hooks] Grok lifecycle/StopFailure hooks already installed')
+ return
+ }
+ try {
+ writeJsonAtomic(GROK_HOOKS_PATH, settings)
+ console.log(`[hooks] installed Grok lifecycle/StopFailure hooks → ${GROK_HOOKS_PATH}`)
+ console.log('[hooks] (takes effect on the next Grok session start)')
+ } catch (err) {
+ console.error('[hooks] failed to write Grok hook file:', err)
+ }
+}
+
interface CursorHook {
command: string
failClosed?: boolean
@@ -882,5 +925,6 @@ export function installHooksFor(engine: AgentEngine, port: number): void {
case 'commandcode': installCommandCodeHooks(port); break
case 'devin': installDevinHooks(port); break
case 'amp': installAmpPlugin(port); break
+ case 'grok': installGrokHooks(port); break
}
}
diff --git a/cli/src/lib/oneshot.ts b/cli/src/lib/oneshot.ts
index 56724428f..db00517bc 100644
--- a/cli/src/lib/oneshot.ts
+++ b/cli/src/lib/oneshot.ts
@@ -1,8 +1,8 @@
-/** Disposable, pre-spawned Claude/Codex/Cursor processes used by the device turn recap. */
+/** Disposable one-shot processes used by device recaps and voice routing. */
import { spawn, type ChildProcess } from 'child_process'
-import { mkdirSync, readFileSync, writeFileSync } from 'fs'
-import { readFile, readdir, rm, unlink } from 'fs/promises'
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
+import { chmod, copyFile, mkdtemp, readFile, readdir, rm, unlink } from 'fs/promises'
import { dirname, join } from 'path'
import { randomUUID } from 'crypto'
import { homedir, tmpdir, userInfo } from 'os'
@@ -997,6 +997,98 @@ export function runCursorOneShot(opts: OneShotOptions): Promise<OneShotResult> {
return pool.run('cursor', opts)
}
+/** The measured Grok 1.0.0 headless invocation. A fresh GROK_HOME contains every persisted session. */
+export function grokOneShotSpawn(
+ opts: Pick<OneShotOptions, 'prompt' | 'model' | 'effort' | 'cwd'>,
+ scratchHome: string,
+ parentEnv: NodeJS.ProcessEnv = process.env,
+): { args: string[]; env: NodeJS.ProcessEnv } {
+ const args = [
+ '--cwd', opts.cwd,
+ '--always-approve', '--no-memory', '--no-plan', '--max-turns', '1',
+ '--output-format', 'json',
+ ...(opts.model ? ['--model', opts.model] : []),
+ ...(opts.effort ? ['--reasoning-effort', opts.effort] : []),
+ '-p', opts.prompt,
+ ]
+ const childEnv: NodeJS.ProcessEnv = { ...parentEnv, GROK_HOME: scratchHome }
+ delete childEnv.TMUX
+ delete childEnv.TMUX_PANE
+ delete childEnv.MACHINE_ID
+ return { args, env: childEnv }
+}
+
+function grokOutputText(stdout: string): string {
+ const candidates = [stdout.trim(), ...stdout.trim().split('\n').reverse()]
+ for (const candidate of candidates) {
+ if (!candidate) continue
+ try {
+ const parsed = JSON.parse(candidate) as { text?: unknown; result?: unknown }
+ if (typeof parsed.text === 'string') return parsed.text.trim()
+ if (typeof parsed.result === 'string') return parsed.result.trim()
+ } catch { /* try the next complete JSON value */ }
+ }
+ return ''
+}
+
+/** Grok takes its print prompt on argv, so it cannot be pre-warmed. Its real CLI always persists a
+ * session; isolating GROK_HOME and deleting it afterwards is the no-pollution equivalent. */
+export async function runGrokOneShot(opts: OneShotOptions): Promise<OneShotResult> {
+ if (opts.signal?.aborted) throw Object.assign(new Error('grok one-shot aborted'), { name: 'AbortError' })
+ mkdirSync(opts.cwd, { recursive: true })
+ const scratchHome = await mkdtemp(join(opts.cwd, '.grok-recap-'))
+ try {
+ // Copy auth/config into the short-lived home. A symlink would keep session writes isolated but still
+ // let a token refresh or config migration mutate the user's real files through the link.
+ for (const name of ['auth.json', 'config.toml']) {
+ const source = join(env.GROK_HOME, name)
+ if (!existsSync(source)) continue
+ const target = join(scratchHome, name)
+ await copyFile(source, target)
+ await chmod(target, 0o600)
+ }
+ const { args, env: processEnv } = grokOneShotSpawn(opts, scratchHome)
+ const timeoutMs = opts.timeoutMs ?? 60_000
+ return await new Promise<OneShotResult>((resolve, reject) => {
+ const child = spawn(env.GROK_PATH || 'grok', args, {
+ cwd: opts.cwd, env: processEnv, detached: true, stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ let stdout = ''
+ let stderr = ''
+ let settled = false
+ const finish = (fn: () => void): void => {
+ if (settled) return
+ settled = true
+ clearTimeout(timer)
+ opts.signal?.removeEventListener('abort', onAbort)
+ fn()
+ }
+ const kill = (): void => killGroup(child)
+ const onAbort = (): void => {
+ finish(() => reject(Object.assign(new Error('grok one-shot aborted'), { name: 'AbortError' })))
+ kill()
+ }
+ const timer = setTimeout(() => {
+ finish(() => reject(new Error(`grok one-shot timed out after ${timeoutMs}ms`)))
+ kill()
+ }, timeoutMs)
+ opts.signal?.addEventListener('abort', onAbort)
+ child.stdout?.on('data', (chunk: Buffer) => { stdout += chunk.toString() })
+ child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
+ child.on('error', (err) => finish(() => reject(err)))
+ child.on('close', (code) => {
+ const text = grokOutputText(stdout)
+ finish(() => {
+ if (!text) reject(new Error(`grok one-shot exited ${code}: ${stderr.slice(0, 500)}`))
+ else resolve({ text, sessionId: null })
+ })
+ })
+ })
+ } finally {
+ await rm(scratchHome, { recursive: true, force: true }).catch(() => {})
+ }
+}
+
function hermesBin(): string {
return env.HERMES_PATH || 'hermes'
}
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index d0abbd993..2641a3f87 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -383,6 +383,46 @@ describe('a Command Code session without a transcript path', () => {
})
})
+/** Grok's SessionStart hook can run while its updates file is still empty or absent. Register the
+ * deterministic ordinary layout immediately so the first remote prompt is not held waiting for a
+ * UserPromptSubmit hook that only that same prompt can trigger. */
+describe('a Grok session before updates.jsonl exists', () => {
+ beforeEach(() => {
+ dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-grok-'))
+ process.env.GROK_HOME = dataDir
+ })
+
+ afterEach(() => {
+ rmSync(dataDir, { recursive: true, force: true })
+ delete process.env.ADAPTER_DATA_DIR
+ delete process.env.CLAUDE_PROJECTS_DIR
+ delete process.env.CODEX_HOME
+ delete process.env.CURSOR_HOME
+ delete process.env.GROK_HOME
+ })
+
+ it('derives the URL-encoded cwd path at SessionStart', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const registered = registry.register({
+ launcherId: 'h1',
+ engine: 'grok',
+ sessionId: '8184b11d-175e-46cb-9cee-cf41cafe70d2',
+ tmuxPane: '%9',
+ cwd: '/workspace/project with spaces',
+ hookEvent: 'SessionStart',
+ })
+
+ expect(registered?.entry.transcriptPath).toBe(join(
+ dataDir,
+ 'sessions',
+ encodeURIComponent('/workspace/project with spaces'),
+ '8184b11d-175e-46cb-9cee-cf41cafe70d2',
+ 'updates.jsonl',
+ ))
+ })
+})
+
describe('agent identity: the launcher owns the agent, the session is bound to it', () => {
beforeEach(() => {
vi.useFakeTimers()
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 04eab8926..ad405e27c 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -103,6 +103,7 @@ const BOOT_FILE = join(env.ADAPTER_DATA_DIR, 'registry-boot')
const NAME_OVERRIDES = new Map<string, string>()
const PANE_RE = /^%\d+$/
+const GROK_SESSION_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
function isWithin(root: string, file: string): boolean {
const rel = relative(root, file)
@@ -121,6 +122,8 @@ export function validTranscriptPath(engine: AgentEngine, filePath: string): bool
? join(env.MUSE_HOME, 'sessions')
: engine === 'codex'
? join(env.CODEX_HOME, 'sessions')
+ : engine === 'grok'
+ ? join(env.GROK_HOME, 'sessions')
: engine === 'cursor'
? join(env.CURSOR_HOME, 'projects')
: engine === 'pi'
@@ -199,7 +202,7 @@ class Registry {
}
let changed = false
for (const raw of Array.isArray(arr) ? arr : []) {
- const engine: AgentEngine = raw?.engine === 'codex' || raw?.engine === 'cursor' || raw?.engine === 'opencode' || raw?.engine === 'pi' || raw?.engine === 'hermes' || raw?.engine === 'commandcode' || raw?.engine === 'devin' || raw?.engine === 'muse' || raw?.engine === 'amp' || raw?.engine === 'kilo' ? raw.engine : 'claude'
+ const engine: AgentEngine = raw?.engine === 'codex' || raw?.engine === 'cursor' || raw?.engine === 'opencode' || raw?.engine === 'pi' || raw?.engine === 'hermes' || raw?.engine === 'commandcode' || raw?.engine === 'devin' || raw?.engine === 'muse' || raw?.engine === 'amp' || raw?.engine === 'kilo' || raw?.engine === 'grok' ? raw.engine : 'claude'
const pane = typeof raw?.tmuxPane === 'string' && PANE_RE.test(raw.tmuxPane) ? raw.tmuxPane : ''
let transcriptPath =
typeof raw?.transcriptPath === 'string' && raw.transcriptPath
@@ -366,7 +369,7 @@ class Registry {
const sessionId =
input.sessionId || (transcriptPath ? basename(transcriptPath).replace(/\.jsonl$/, '') : '')
const engine: AgentEngine =
- input.engine === 'codex' || input.engine === 'cursor' || input.engine === 'opencode' || input.engine === 'pi' || input.engine === 'hermes' || input.engine === 'commandcode' || input.engine === 'devin' || input.engine === 'muse' || input.engine === 'amp' || input.engine === 'kilo' ? input.engine : 'claude'
+ input.engine === 'codex' || input.engine === 'cursor' || input.engine === 'opencode' || input.engine === 'pi' || input.engine === 'hermes' || input.engine === 'commandcode' || input.engine === 'devin' || input.engine === 'muse' || input.engine === 'amp' || input.engine === 'kilo' || input.engine === 'grok' ? input.engine : 'claude'
const pane = input.tmuxPane
// The machine id may be omitted only when re-registering a session we already know (the catch hook
// fires on every prompt and older payloads carried no id) — a NEW session always needs one, because
@@ -377,7 +380,8 @@ class Registry {
|| !agentId
|| !pane
|| !PANE_RE.test(pane)
- || (engine !== 'cursor' && engine !== 'opencode' && engine !== 'kilo' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && !transcriptPath)
+ || (engine === 'grok' && !GROK_SESSION_RE.test(sessionId))
+ || (engine !== 'cursor' && engine !== 'opencode' && engine !== 'kilo' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && engine !== 'grok' && !transcriptPath)
|| (transcriptPath && !validTranscriptPath(engine, transcriptPath))
) return null
if (engine === 'codex' && transcriptPath && readCodexRolloutMeta(transcriptPath)?.isSubagent) return null
@@ -415,7 +419,9 @@ class Registry {
// offset 0 and chokidar fires when it appears.
const derived = !transcriptPath && engine === 'commandcode'
? commandcodeTranscriptPath(input.cwd ?? existing?.cwd, sessionId)
- : null
+ : !transcriptPath && engine === 'grok' && (input.cwd ?? existing?.cwd)
+ ? join(env.GROK_HOME, 'sessions', encodeURIComponent((input.cwd ?? existing?.cwd)!), sessionId, 'updates.jsonl')
+ : null
const effectiveTranscriptPath = transcriptPath ?? existing?.transcriptPath ?? derived ?? null
const entry: RegisteredSession = {
agentId,
@@ -424,7 +430,9 @@ class Registry {
engine,
launcherId: agentId,
transcriptPath: effectiveTranscriptPath,
- projectDir: effectiveTranscriptPath
+ projectDir: engine === 'grok'
+ ? basename(input.cwd ?? existing?.cwd ?? '') || sessionId
+ : effectiveTranscriptPath
? basename(dirname(effectiveTranscriptPath))
: basename(input.cwd ?? existing?.cwd ?? '') || sessionId,
cwd: input.cwd ?? existing?.cwd ?? null,
diff --git a/cli/src/lib/runtimeProfile.spec.ts b/cli/src/lib/runtimeProfile.spec.ts
index 822685cd2..6fb11bd79 100644
--- a/cli/src/lib/runtimeProfile.spec.ts
+++ b/cli/src/lib/runtimeProfile.spec.ts
@@ -18,7 +18,7 @@ afterEach(async () => {
await Promise.all(cleanup.splice(0).map((path) => rm(path, { recursive: true, force: true })))
})
-function session(engine: 'claude' | 'codex' | 'cursor'): RegisteredSession {
+function session(engine: RegisteredSession['engine']): RegisteredSession {
return {
sessionId: 'session:1', engine, launcherId: 'h1', agentId: 'h1', boundAt: 0, transcriptPath: '/tmp/session.jsonl', projectDir: 'tmp', cwd: '/tmp',
tmuxPane: '%1', source: null, title: null, model: null,
@@ -50,7 +50,7 @@ describe('RuntimeProfileManager', () => {
// Every engine that can produce options must also parse them back. Widening the picker to a new
// engine and forgetting this line is silent: the id round-trips through web and device fine, then
// setProfile rejects it as INVALID_RUNTIME_PROFILE the moment someone picks a row.
- for (const engine of ['claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse']) {
+ for (const engine of ['claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok']) {
expect(parseRuntimeProfile(`runtime-v1:s1:${engine}:some-model@high`)).toMatchObject({ engine })
}
expect(parseRuntimeProfile('runtime-v1:cursor-1:cursor:gpt-5.6-sol@none')).toMatchObject({
@@ -92,7 +92,7 @@ describe('RuntimeProfileManager', () => {
// View-only engines still SHOW what they run (the ingest paths do that); they just have nothing to
// pick and nothing to drive. Both gates are asserted: an empty catalogue, and a refusal to control.
const manager = new RuntimeProfileManager()
- for (const engine of ['cursor', 'commandcode', 'devin', 'pi', 'opencode', 'hermes'] as const) {
+ for (const engine of ['cursor', 'commandcode', 'devin', 'pi', 'opencode', 'hermes', 'grok'] as const) {
const value = { ...session('cursor'), engine }
expect(supportsNativeRuntimeControl(value)).toBe(false)
await expect(manager.modelsForSession(value)).resolves.toEqual([])
@@ -126,6 +126,23 @@ describe('RuntimeProfileManager', () => {
})
})
+ it('observes Grok model metadata and its live footer effort', () => {
+ const manager = new RuntimeProfileManager()
+ const value = session('grok')
+ manager.hydrate(value, [])
+
+ manager.ingest(value, JSON.stringify({
+ params: { update: { _meta: { modelId: 'grok-4.5' } } },
+ }))
+ manager.ingestPane(value, 'Grok 4.5 (medium) · always-approve')
+
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({
+ engine: 'grok',
+ model: 'grok-4.5',
+ effort: 'medium',
+ })
+ })
+
it('observes Cursor Auto model and effort from the idle footer with context usage', () => {
const manager = new RuntimeProfileManager()
const value = session('cursor')
diff --git a/cli/src/lib/runtimeProfile.ts b/cli/src/lib/runtimeProfile.ts
index b87999555..b44e1c4a7 100644
--- a/cli/src/lib/runtimeProfile.ts
+++ b/cli/src/lib/runtimeProfile.ts
@@ -43,6 +43,7 @@ import {
parsePiFooterProfile,
parsePiModelsOutput,
} from '../engines/pi/runtimeProfile.js'
+import { parseGrokFooterProfile } from '../engines/grok/runtimeProfile.js'
export interface RuntimeProfile {
id: string
@@ -107,7 +108,7 @@ interface CodexCache {
models?: CodexCacheModel[]
}
-const PROFILE_RE = /^runtime-v1:([^:]+):(claude|codex|cursor|commandcode|pi|devin|opencode|hermes|muse|amp|kilo):([^@]+)@([a-z0-9_-]+)$/i
+const PROFILE_RE = /^runtime-v1:([^:]+):(claude|codex|cursor|commandcode|pi|devin|opencode|hermes|muse|amp|kilo|grok):([^@]+)@([a-z0-9_-]+)$/i
const CODEX_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'])
const CLAUDE_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])
const CURSOR_EFFORTS = new Set(['auto', 'none', 'low', 'medium', 'high', 'xhigh', 'max'])
@@ -642,6 +643,7 @@ export class RuntimeProfileManager {
void this.ingestConfig(session, silent).catch(() => undefined)
}
}
+ else if (session.engine === 'grok') this.ingestGrok(session, raw)
else this.ingestClaude(session, raw)
const after = this.selectedModel(session)
this.wake(session.sessionId)
@@ -854,6 +856,13 @@ export class RuntimeProfileManager {
state.observedAt = Date.now()
this.confirmObserved(session.sessionId, footer.model, footer.effort)
}
+ } else if (session.engine === 'grok') {
+ const footer = parseGrokFooterProfile(paneText)
+ if (footer) {
+ state.model = footer.model
+ state.effort = footer.effort
+ state.observedAt = Date.now()
+ }
} else {
const header = /(Fable|Opus|Sonnet|Haiku)\s+(\d+(?:\.\d+)*)(\s+\(1M context\))?\s+with\s+(low|medium|high|xhigh|max|ultracode)\s+effort/gi
const matches = [...paneText.matchAll(header)]
@@ -1128,6 +1137,17 @@ export class RuntimeProfileManager {
}
}
+ private ingestGrok(session: RegisteredSession, raw: Record<string, unknown>): void {
+ const params = record(raw.params)
+ const update = record(params?.update)
+ const meta = record(update?._meta)
+ const model = text(meta?.modelId)
+ if (!model) return
+ const state = this.state(session.sessionId)
+ state.model = model
+ state.observedAt = Date.now()
+ }
+
private async claudeModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {
const output: RuntimeModelOption[] = []
const seen = new Set<string>()
diff --git a/cli/src/lib/sessionInput.spec.ts b/cli/src/lib/sessionInput.spec.ts
index c596827fa..3ce8d9ffc 100644
--- a/cli/src/lib/sessionInput.spec.ts
+++ b/cli/src/lib/sessionInput.spec.ts
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { SessionInputController } from './sessionInput.js'
+import { acceptsInputBeforeSession, SessionInputController } from './sessionInput.js'
import type { RegisteredSession } from './registry.js'
function session(engine: 'claude' | 'codex' | 'cursor' | 'commandcode' = 'codex'): RegisteredSession {
@@ -322,3 +322,11 @@ describe('SessionInputController', () => {
controller.forget('s1')
})
})
+
+describe('pre-session input', () => {
+ it('lets Grok receive the prompt that creates its session', () => {
+ expect(acceptsInputBeforeSession('grok')).toBe(true)
+ expect(acceptsInputBeforeSession('claude')).toBe(false)
+ expect(acceptsInputBeforeSession('muse')).toBe(false)
+ })
+})
diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.ts
index fb4b9fcc8..ea49e84d5 100644
--- a/cli/src/lib/sessionInput.ts
+++ b/cli/src/lib/sessionInput.ts
@@ -36,12 +36,23 @@ const MUSE_SUBMIT_VERIFY_MS = 6_000
// Amp's plugin writes `turn_start` from the agent.start event, which fires the instant the prompt is
// accepted — no model round trip in between, so the same store-verified window fits.
const AMP_SUBMIT_VERIFY_MS = 6_000
+// Grok's FIRST prompt creates the session, runs SessionStart + UserPromptSubmit hooks, then writes the
+// user_message_chunk. The isolated real run took ~4.4s from paste to watcher-visible turn start; 2.5s
+// pressed Enter a second time on every fresh agent even though the first submission was accepted.
+const GROK_SUBMIT_VERIFY_MS = 6_000
const CURSOR_TURN_SETTLE_MS = 750
const SUBMIT_MAX_RETRIES = 2
// Non-cursor engines re-observe the pane (instead of erroring) while an accepted-but-not-yet-started
// prompt is in flight. Bounded so a truly wedged session eventually reverts to the retry/error path.
const SUBMIT_MAX_OBSERVES = 5
+/** Grok does not allocate a session until its first prompt is submitted. Holding that prompt until a
+ * session id exists deadlocks: UserPromptSubmit is the event that supplies the id. Inject it into the
+ * launcher's already-validated pane, then let the hook bind the resulting session. */
+export function acceptsInputBeforeSession(engine: RegisteredSession['engine']): boolean {
+ return engine === 'grok'
+}
+
interface QueuedInput {
content: string
bytes: number
@@ -290,6 +301,8 @@ export class SessionInputController {
? AMP_SUBMIT_VERIFY_MS
: session.engine === 'kilo'
? KILO_SUBMIT_VERIFY_MS
+ : session.engine === 'grok'
+ ? GROK_SUBMIT_VERIFY_MS
: SUBMIT_VERIFY_MS)
}
@@ -311,7 +324,7 @@ export class SessionInputController {
return
}
} else if (session.engine === 'opencode' || session.engine === 'kilo' || session.engine === 'pi' || session.engine === 'hermes' || session.engine === 'muse'
- || session.engine === 'amp') {
+ || session.engine === 'amp' || session.engine === 'grok') {
// OpenCode has no composer glyph, and the submitted text stays visible in the message area, so a
// pane scrape can't tell "still in the composer" from "already sent". Rely purely on the reader-
// derived turn_started (a new user row in opencode.db) to clear awaitingFingerprint; if it hasn't
diff --git a/cli/src/lib/sessionRepair.spec.ts b/cli/src/lib/sessionRepair.spec.ts
index 2f3f510ac..a924fda80 100644
--- a/cli/src/lib/sessionRepair.spec.ts
+++ b/cli/src/lib/sessionRepair.spec.ts
@@ -12,6 +12,7 @@ import { join } from 'path'
const dirs: string[] = []
afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+ delete process.env.GROK_HOME
vi.resetModules()
})
@@ -250,3 +251,33 @@ describe('session repair — muse', () => {
await expect(findLiveSession('muse', CWD, STARTED_AT)).resolves.toBeNull()
})
})
+
+describe('session repair — Grok', () => {
+ it('derives cwd and session id from the encoded updates.jsonl layout', async () => {
+ const home = tempRoot()
+ const id = '8184b11d-175e-46cb-9cee-cf41cafe70d2'
+ const file = join(home, 'sessions', encodeURIComponent(CWD), id, 'updates.jsonl')
+ mkdirSync(join(file, '..'), { recursive: true })
+ writeFileSync(file, '{}\n')
+ vi.resetModules()
+ process.env.GROK_HOME = home
+ const { findLiveSession } = await import('./sessionRepair.js')
+
+ await expect(findLiveSession('grok', CWD, STARTED_AT)).resolves.toEqual({ sessionId: id, transcriptPath: file })
+ })
+
+ it('reads the .cwd sidecar used by Grok for a long-path hash directory', async () => {
+ const home = tempRoot()
+ const id = '98ee3dac-175e-46cb-9cee-cf41cafe70d2'
+ const group = join(home, 'sessions', 'cwd-hash-123')
+ const file = join(group, id, 'updates.jsonl')
+ mkdirSync(join(file, '..'), { recursive: true })
+ writeFileSync(join(group, '.cwd'), `${CWD}\n`)
+ writeFileSync(file, '{}\n')
+ vi.resetModules()
+ process.env.GROK_HOME = home
+ const { findLiveSession } = await import('./sessionRepair.js')
+
+ await expect(findLiveSession('grok', CWD, STARTED_AT)).resolves.toEqual({ sessionId: id, transcriptPath: file })
+ })
+})
diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.ts
index b4bd01ad3..2e2791912 100644
--- a/cli/src/lib/sessionRepair.ts
+++ b/cli/src/lib/sessionRepair.ts
@@ -265,6 +265,18 @@ export async function findLiveSession(
// directory — but `findLiveSession` is asked about a cwd, not a pane, and a repair that silently
// needed a different question would be the kind of split path this file exists to avoid.
return fileEngineSession(env.AMP_SESSIONS_DIR, cwd, startedAtMs, readTranscriptMeta, opts)
+ case 'grok':
+ // `updates.jsonl` lives under `<encoded-cwd>/<uuid>/`; long cwd values use a hashed group with a
+ // `.cwd` sidecar. The file itself is ACP updates and carries no cwd, so derive it from that group.
+ return fileEngineSession(join(env.GROK_HOME, 'sessions'), cwd, startedAtMs, async (path) => {
+ if (basename(path) !== 'updates.jsonl') return null
+ const sessionDir = dirname(path)
+ const group = dirname(sessionDir)
+ let root = ''
+ try { root = decodeURIComponent(basename(group)) } catch { /* hashed layout below */ }
+ if (!root.startsWith('/')) root = (await readFile(join(group, '.cwd'), 'utf8').catch(() => '')).trim()
+ return root ? { cwd: root, sessionId: basename(sessionDir) } : null
+ }, opts)
case 'opencode':
// time_created is epoch MILLISECONDS here.
return dbEngineSession(
diff --git a/cli/src/lib/summarize.spec.ts b/cli/src/lib/summarize.spec.ts
index 9055b9e8a..3a99833e5 100644
--- a/cli/src/lib/summarize.spec.ts
+++ b/cli/src/lib/summarize.spec.ts
@@ -5,6 +5,7 @@ const mocks = vi.hoisted(() => ({
runClaude: vi.fn(),
runCodex: vi.fn(),
runCursor: vi.fn(),
+ runGrok: vi.fn(),
cleanupCursor: vi.fn(),
setCounts: vi.fn(),
}))
@@ -16,6 +17,7 @@ vi.mock('../config/env.js', () => ({
SUMMARY_MODEL: 'sonnet',
CODEX_SUMMARY_MODEL: 'gpt-5.5',
CURSOR_SUMMARY_MODEL: 'auto',
+ GROK_SUMMARY_MODEL: 'grok-4.5',
SUMMARY_EFFORT: 'low',
},
}))
@@ -26,6 +28,7 @@ vi.mock('./oneshot.js', () => ({
runClaudeOneShot: mocks.runClaude,
runCodexOneShot: mocks.runCodex,
runCursorOneShot: mocks.runCursor,
+ runGrokOneShot: mocks.runGrok,
setOneShotPoolActiveCounts: mocks.setCounts,
setOneShotPoolDeviceConnected: vi.fn(),
shutdownOneShotPool: vi.fn(),
@@ -37,6 +40,7 @@ beforeEach(() => {
mocks.runClaude.mockReset()
mocks.runCodex.mockReset()
mocks.runCursor.mockReset()
+ mocks.runGrok.mockReset()
mocks.cleanupCursor.mockReset()
mocks.cleanupCursor.mockResolvedValue(undefined)
mocks.setCounts.mockReset()
@@ -88,6 +92,28 @@ describe('Cursor recap', () => {
})
})
+describe('Grok recap', () => {
+ it('uses an isolated direct Grok one-shot with the configured model', async () => {
+ mocks.runGrok.mockResolvedValue({
+ text: 'Grok recap works.\n\nThe Grok turn now produces a persisted device recap.',
+ sessionId: 'grok-recap-session',
+ })
+
+ await expect(summarizeTurnText(
+ 'Implemented Grok recap support.',
+ undefined,
+ 'Does Grok recap work?',
+ 'grok',
+ )).resolves.toBe('Grok recap works.\n\nThe Grok turn now produces a persisted device recap.')
+
+ expect(mocks.runGrok).toHaveBeenCalledOnce()
+ expect(mocks.runGrok.mock.calls[0][0]).toMatchObject({ model: 'grok-4.5', effort: 'low' })
+ expect(mocks.runClaude).not.toHaveBeenCalled()
+ expect(mocks.runCodex).not.toHaveBeenCalled()
+ expect(mocks.runCursor).not.toHaveBeenCalled()
+ })
+})
+
describe('language fidelity', () => {
const VI_SOURCE = 'Đội tuyển Việt Nam đã thắng trận chung kết với tỉ số hai một trước Thái Lan tối qua tại sân Mỹ Đình.'
const VI_ASK = 'Trận đấu tối qua kết quả thế nào?'
diff --git a/cli/src/lib/summarize.ts b/cli/src/lib/summarize.ts
index f93437286..89beae3d3 100644
--- a/cli/src/lib/summarize.ts
+++ b/cli/src/lib/summarize.ts
@@ -26,6 +26,7 @@ import {
runDevinOneShot,
runMuseOneShot,
runAmpOneShot,
+ runGrokOneShot,
setOneShotPoolActiveCounts,
setOneShotPoolDeviceConnected,
shutdownOneShotPool,
@@ -59,7 +60,7 @@ export function syncSummaryPoolSessions(sessions: Array<{ engine: AgentEngine }>
// Hermes, Devin, Muse and Amp take their recap prompt as argv (`muse exec <prompt>`, `amp -x <prompt>`),
// so they cannot be pre-warmed the way a stdin-fed CLI can — no pooled worker for them.
if (session.engine === 'hermes' || session.engine === 'devin' || session.engine === 'muse'
- || session.engine === 'amp') continue
+ || session.engine === 'amp' || session.engine === 'grok') continue
counts[session.engine]++
}
setOneShotPoolActiveCounts(counts)
@@ -309,6 +310,8 @@ export async function summarizeTurnText(
? env.AMP_SUMMARY_MODE
: engine === 'kilo'
? env.KILO_SUMMARY_MODEL
+ : engine === 'grok'
+ ? env.GROK_SUMMARY_MODEL
: env.OPENCODE_SUMMARY_MODEL
const effort = engine === 'cursor' ? 'model-defined' : env.SUMMARY_EFFORT
console.log(`[recap] one-shot ${engine} · model=${model} · effort=${effort} · inputChars=${last.length}${ask ? ' · withAsk' : ''}`)
@@ -332,6 +335,8 @@ export async function summarizeTurnText(
? runAmpOneShot
: engine === 'kilo'
? runKiloOneShot
+ : engine === 'grok'
+ ? runGrokOneShot
: runOpencodeOneShot
let r = await run({ prompt, model, effort: env.SUMMARY_EFFORT, cwd: scratch, signal })
console.log(`[recap] one-shot returned in ${Date.now() - t0}ms · rawLen=${(r.text || '').length}`)
diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.ts
index 291513645..d5beb35e9 100644
--- a/cli/src/lib/tmux.spec.ts
+++ b/cli/src/lib/tmux.spec.ts
@@ -292,6 +292,13 @@ describe('tmux reaper', () => {
expect(engineProcessMatchScore({ executable: 'claude', args: 'claude' }, 'muse')).toBe(0)
})
+ it('matches the Grok binary and its installed path', async () => {
+ const { engineProcessMatchScore } = await loadModules()
+ expect(engineProcessMatchScore({ executable: 'grok', args: 'grok --always-approve' }, 'grok')).toBe(3)
+ expect(engineProcessMatchScore({ executable: '/Users/demo/.grok/bin/grok', args: 'grok' }, 'grok')).toBe(3)
+ expect(engineProcessMatchScore({ executable: 'claude', args: 'claude' }, 'grok')).toBe(0)
+ })
+
it('extracts resume session ids per engine, and only when the value looks like an id', async () => {
const { resumeSessionId } = await loadModules()
@@ -312,6 +319,10 @@ describe('tmux reaper', () => {
expect(resumeSessionId('commandcode', 'cmd -r 1348716c-421f-417f-99ef-cd6096ed248a'))
.toBe('1348716c-421f-417f-99ef-cd6096ed248a')
expect(resumeSessionId('commandcode', 'cmd -r Greeting')).toBeNull()
+ expect(resumeSessionId('grok', 'grok --resume 98ee3dac-175e-46cb-9cee-cf41cafe70d2'))
+ .toBe('98ee3dac-175e-46cb-9cee-cf41cafe70d2')
+ expect(resumeSessionId('grok', 'grok -r 98ee3dac-175e-46cb-9cee-cf41cafe70d2'))
+ .toBe('98ee3dac-175e-46cb-9cee-cf41cafe70d2')
// `--continue` carries no id on any engine: nothing to adopt, and nothing to invent.
expect(resumeSessionId('opencode', 'opencode --continue')).toBeNull()
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index 7999451c5..da201bef9 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -218,6 +218,12 @@ export function engineProcessMatchScore(
if (/\.amp[\/\\]bin[\/\\]amp(?:\s|$)/.test(haystack)) return 3
return /(^|[\/\s])amp(?:[\s]|$)/.test(haystack) ? 1 : 0
}
+ if (engine === 'grok') {
+ // Grok ships as a single binary at ~/.grok/bin/grok and keeps the bare executable name in tmux.
+ if (executable === 'grok') return 3
+ if (/\.grok[\/\\]bin[\/\\]grok(?:\s|$)/.test(haystack)) return 3
+ return /(^|[\/\s])grok(?:[\s]|$)/.test(haystack) ? 1 : 0
+ }
if (executable === 'claude') return 3
return /(^|[\/\s])claude(?:[\s]|$)/.test(haystack) ? 1 : 0
}
@@ -280,6 +286,8 @@ const RESUME_ARGS: Partial<Record<RegisteredSession['engine'], { flags: string[]
// `amp threads continue <id>` names the thread; the bare `amp last` does not. Amp's ids are the only
// ones here with a fixed prefix (`T-019fda49-…`), so the pattern doubles as proof it IS an amp id.
amp: { flags: ['continue', '-c'], id: /^T-[0-9a-f-]{16,}$/i },
+ // Grok 1.0.0 accepts both spellings and persists UUID session ids below ~/.grok/sessions.
+ grok: { flags: ['--resume', '-r'], id: /^[0-9a-f-]{16,}$/i },
}
/** The session id an engine was told to resume, or null when argv does not name one. */
diff --git a/cli/src/lib/voiceRouter.spec.ts b/cli/src/lib/voiceRouter.spec.ts
index e55371ab2..d35298055 100644
--- a/cli/src/lib/voiceRouter.spec.ts
+++ b/cli/src/lib/voiceRouter.spec.ts
@@ -5,9 +5,11 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
// consumed by routeVoiceTask's await — this avoids tinyspy's async settled-result tracking leaving an
// unhandled rejection once a resolved test has run on the same spy. The vi.fn is kept only for call counts.
const runRouterOneShot = vi.fn()
+const runGrokOneShot = vi.fn()
let routerImpl: (o: unknown) => Promise<{ text: string; sessionId: null }> = async () => ({ text: '', sessionId: null })
vi.mock('./oneshot.js', () => ({
runRouterOneShot: (...args: unknown[]) => { runRouterOneShot(...args); return routerImpl(args[0]) },
+ runGrokOneShot: (...args: unknown[]) => { runGrokOneShot(...args); return routerImpl(args[0]) },
configureRouterOneShot: vi.fn(),
setRouterOneShotDeviceConnected: vi.fn(),
shutdownRouterOneShot: vi.fn(),
@@ -97,7 +99,7 @@ describe('buildRouterPrompt', () => {
})
describe('routeVoiceTask', () => {
- beforeEach(() => { runRouterOneShot.mockReset(); routerImpl = async () => ({ text: '', sessionId: null }) })
+ beforeEach(() => { runRouterOneShot.mockReset(); runGrokOneShot.mockReset(); routerImpl = async () => ({ text: '', sessionId: null }) })
it('returns needNewAgent for an empty machine WITHOUT calling the LLM', async () => {
const d = await routeVoiceTask('anything', [])
@@ -180,10 +182,14 @@ describe('chooseRouterEngine', () => {
expect(chooseRouterEngine([{ engine: 'hermes' }, { engine: 'devin' }])).toBeNull()
expect(chooseRouterEngine([])).toBeNull()
})
+
+ it('uses Grok when it is the only routable CLI', () => {
+ expect(chooseRouterEngine([{ engine: 'grok' }, { engine: 'hermes' }])).toBe('grok')
+ })
})
describe('routeVoiceTask engine selection', () => {
- beforeEach(() => { runRouterOneShot.mockReset(); routerImpl = async () => ({ text: '', sessionId: null }) })
+ beforeEach(() => { runRouterOneShot.mockReset(); runGrokOneShot.mockReset(); routerImpl = async () => ({ text: '', sessionId: null }) })
it('classifies with the engine the agents run on', async () => {
routerImpl = async () => ({ text: '{"agentId":"2","confidence":0.9,"reason":"auth"}', sessionId: null })
@@ -212,6 +218,17 @@ describe('routeVoiceTask engine selection', () => {
expect((runRouterOneShot.mock.calls[0][1] as { model?: string }).model).toBe('')
})
+ it('routes a Grok-only machine through the isolated direct one-shot', async () => {
+ routerImpl = async () => ({ text: '{"agentId":"2","confidence":0.9,"reason":"auth"}', sessionId: null })
+ const agents: RouterAgent[] = [
+ { id: '1', name: 'Frontend', engine: 'grok' },
+ { id: '2', name: 'Auth', engine: 'grok' },
+ ]
+ await expect(routeVoiceTask('login broken', agents)).resolves.toMatchObject({ agentId: '2' })
+ expect(runGrokOneShot).toHaveBeenCalledOnce()
+ expect(runRouterOneShot).not.toHaveBeenCalled()
+ })
+
it('keeps Claude on its own small model', () => {
// Haiku is on every Claude plan and routing has a 12s budget; Opus for a classification is waste.
expect(routerModelFor('claude')).toBe('haiku')
diff --git a/cli/src/lib/voiceRouter.ts b/cli/src/lib/voiceRouter.ts
index 7fb00bf23..c40e47bba 100644
--- a/cli/src/lib/voiceRouter.ts
+++ b/cli/src/lib/voiceRouter.ts
@@ -1,12 +1,12 @@
// Voice router (adapter side, for REMOTE machines) — self-contained port of the the hosted runtime's
// Given a transcribed voice task and this machine's agents (name + a
// short summary of each agent's recent turn), pick the single best-fit agent. Uses the same key-free CLI
-// one-shot path as the turn summarizer (runClaudeOneShot) with a small/fast model (Haiku by default). Name
+// one-shot path as the turn summarizer, using a small/fast model where the engine exposes one. Name
// is the strongest signal (users name agents by role/domain); recent activity disambiguates.
import { existsSync, mkdirSync } from 'fs'
import { join } from 'path'
import { env } from '../config/env.js'
-import { runRouterOneShot, configureRouterOneShot, setRouterOneShotDeviceConnected, shutdownRouterOneShot } from './oneshot.js'
+import { runGrokOneShot, runRouterOneShot, configureRouterOneShot, setRouterOneShotDeviceConnected, shutdownRouterOneShot } from './oneshot.js'
export interface RouterAgent {
id: string
@@ -28,9 +28,9 @@ export interface RouteDecision {
const ROUTE_SCRATCH = join(env.ADAPTER_DATA_DIR, 'voice-route-scratch')
-/** Engines that can serve the router, best first. Hermes and Devin are absent on purpose: they take the
- * prompt as argv so they cannot be pre-warmed — the same exclusion the recap pool makes. */
-const ROUTER_ENGINE_PRIORITY = ['claude', 'codex', 'commandcode', 'cursor', 'pi', 'opencode', 'kilo'] as const
+/** Engines that can serve the router, best first. Grok takes the prompt as argv and cannot be warmed, but
+ * its isolated direct one-shot is still bounded enough to route a Grok-only machine. */
+const ROUTER_ENGINE_PRIORITY = ['claude', 'codex', 'commandcode', 'cursor', 'pi', 'opencode', 'kilo', 'grok'] as const
export type RouterEngine = (typeof ROUTER_ENGINE_PRIORITY)[number]
/**
@@ -78,6 +78,7 @@ function ensureRouteScratch(): string {
// Point the warm router worker at the chosen engine's small model @ the route scratch. Lazy (not at import)
// so importing this module for the pure helpers has no filesystem/pool side effects.
function ensureRouterConfigured(engine: RouterEngine): void {
+ if (engine === 'grok') return
configureRouterOneShot({ engine, cwd: ensureRouteScratch(), model: routerModelFor(engine), effort: 'low' })
}
@@ -93,6 +94,7 @@ export function setVoiceRouterSessions(sessions: Array<{ engine: string }>): voi
console.log('[voice-route] no agent this router can run on — voice will route by name matching')
return
}
+ if (next === 'grok') setRouterOneShotDeviceConnected(false)
console.log(`[voice-route] router engine=${next} model=${routerModelFor(next) || '(engine default)'}`)
ensureRouterConfigured(next)
}
@@ -102,7 +104,7 @@ export function setVoiceRouterDeviceConnected(connected: boolean): void {
// Config must be set before the pool spawns a warm worker. With no usable engine there is nothing to
// warm — the heuristic needs no process.
if (connected && routerEngine) ensureRouterConfigured(routerEngine)
- setRouterOneShotDeviceConnected(connected)
+ setRouterOneShotDeviceConnected(connected && routerEngine !== 'grok')
}
export function shutdownVoiceRouter(): void {
shutdownRouterOneShot()
@@ -236,7 +238,10 @@ export async function routeVoiceTask(transcript: string, agents: RouterAgent[],
try {
// Served from the warm router worker (no cold spawn). Cap under the backend's 15s nodeRequest budget so
// a slow route surfaces before the RPC deadline.
- const { text } = await runRouterOneShot(engine, { prompt, model, effort: 'low', cwd: ensureRouteScratch(), signal, timeoutMs: 12_000 })
+ const options = { prompt, model, effort: 'low' as const, cwd: ensureRouteScratch(), signal, timeoutMs: 12_000 }
+ const { text } = engine === 'grok'
+ ? await runGrokOneShot(options)
+ : await runRouterOneShot(engine, options)
return logDecision(engine, agents, parseRouteOutput(text || '', agents))
} catch (err) {
if (err instanceof Error && err.name === 'AbortError') throw err // caller cancelled — don't paper over it