An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
feat(agents): run the side panel on Grok Build, in beta, behind a tool list, approvals that refuse what was not granted, and a sandbox
Shahriara19bf76395d6
diff --git a/src/daemon/agent/config.test.ts b/src/daemon/agent/config.test.tsindex 4d619a7..753a1d5 100644--- a/src/daemon/agent/config.test.ts+++ b/src/daemon/agent/config.test.ts@@ -26,7 +26,13 @@ beforeEach(() => {const DEFAULTS: AgentConfig = {agent: 'claude',- agents: { claude: { bin: 'claude', model: 'claude-sonnet-5' }, codex: { bin: 'codex' }, antigravity: { bin: 'agy' }, vibe: { bin: 'vibe' } },+ agents: {+ claude: { bin: 'claude', model: 'claude-sonnet-5' },+ codex: { bin: 'codex' },+ antigravity: { bin: 'agy' },+ vibe: { bin: 'vibe' },+ grok: { bin: 'grok' },+ },requireApproval: ['page.submitForm'],};diff --git a/src/daemon/agent/runners/fixtures/README.md b/src/daemon/agent/runners/fixtures/README.mdindex 74adad0..b20e171 100644--- a/src/daemon/agent/runners/fixtures/README.md+++ b/src/daemon/agent/runners/fixtures/README.md@@ -5,7 +5,9 @@ What each agent CLI printed on stdout, one event per line, for the reader tests- `<cli version>-<case>.jsonl` was recorded from that version of the real CLI. The only edits are toClaude Code's `init` line, where the working directory became `/Users/you/.browsentic` and therecording machine's slash commands, agents, skills, plugins and memory paths were emptied, and to- its `rate_limit_event`, which keeps only its status.+ its `rate_limit_event`, which keeps only its status. Grok Build prints the same `available_commands`+ line several times over; its recordings keep one of each, with the recording machine's slash+ commands emptied.- `<case>.hand-written.jsonl` was written from the reader code, for streams a contained run cannotproduce or a CLI that was not installed. Its first line says so.diff --git a/src/daemon/agent/runners/fixtures/grok/1.0.40-every-tool.jsonl b/src/daemon/agent/runners/fixtures/grok/1.0.40-every-tool.jsonlnew file mode 100644index 0000000..a241791--- /dev/null+++ b/src/daemon/agent/runners/fixtures/grok/1.0.40-every-tool.jsonl@@ -0,0 +1 @@+{"type":"available_commands","tools":["run_terminal_command","read_file","search_replace","list_dir","grep","kill_command_or_subagent","todo_write","get_command_or_subagent_output","spawn_subagent","scheduler_create","scheduler_delete","scheduler_list","monitor","search_tool","use_tool","workflow","enter_plan_mode","exit_plan_mode","ask_user_question","send_feedback","web_search","web_fetch","image_gen","image_edit","image_to_video","reference_to_video","write"],"commands":[]}diff --git a/src/daemon/agent/runners/fixtures/grok/1.0.40-not-signed-in.jsonl b/src/daemon/agent/runners/fixtures/grok/1.0.40-not-signed-in.jsonlnew file mode 100644index 0000000..5b9ae2c--- /dev/null+++ b/src/daemon/agent/runners/fixtures/grok/1.0.40-not-signed-in.jsonl@@ -0,0 +1 @@+{"type":"error","message":"Not signed in. To authenticate without a browser, run:\n grok login --device-code\n\nAlternatively, set the XAI_API_KEY environment variable or run `grok login` on a machine with a browser."}diff --git a/src/daemon/agent/runners/fixtures/grok/1.0.40-rate-limited.jsonl b/src/daemon/agent/runners/fixtures/grok/1.0.40-rate-limited.jsonlnew file mode 100644index 0000000..341ea30--- /dev/null+++ b/src/daemon/agent/runners/fixtures/grok/1.0.40-rate-limited.jsonl@@ -0,0 +1,2 @@+{"type":"available_commands","tools":["todo_write","search_tool","use_tool"],"commands":[]}+{"type":"error","message":"Internal error: {\n \"message\": \"API error (status 500 Internal Server Error): API error (status 500 Internal Server Error): error: Service temporarily unavailable. The model did not respond to this request.\",\n \"http_status\": 500\n}"}diff --git a/src/daemon/agent/runners/fixtures/grok/1.0.40-unknown-effort.jsonl b/src/daemon/agent/runners/fixtures/grok/1.0.40-unknown-effort.jsonlnew file mode 100644index 0000000..2df5aad--- /dev/null+++ b/src/daemon/agent/runners/fixtures/grok/1.0.40-unknown-effort.jsonl@@ -0,0 +1 @@+{"type":"error","message":"--effort/--reasoning-effort: unknown effort level 'ultra'; use one of: xhigh, high, medium, low"}diff --git a/src/daemon/agent/runners/fixtures/grok/1.0.40-unknown-model.jsonl b/src/daemon/agent/runners/fixtures/grok/1.0.40-unknown-model.jsonlnew file mode 100644index 0000000..e320f8c--- /dev/null+++ b/src/daemon/agent/runners/fixtures/grok/1.0.40-unknown-model.jsonl@@ -0,0 +1 @@+{"type":"error","message":"Couldn't set model 'grok-nope': Invalid params: \"unknown model id\". Run 'grok models' to see available models."}diff --git a/src/daemon/agent/runners/fixtures/grok/tool-loop.hand-written.jsonl b/src/daemon/agent/runners/fixtures/grok/tool-loop.hand-written.jsonlnew file mode 100644index 0000000..3713fda--- /dev/null+++ b/src/daemon/agent/runners/fixtures/grok/tool-loop.hand-written.jsonl@@ -0,0 +1,18 @@+# Hand-written from the streaming-json section of grok 1.0.40's own docs, not recorded: the free account it was written on is rate-limited before the model answers. A research turn over three model responses: it looks tools up, calls a Browsentic tool, searches the web, reaches another server's tool, and reports each call while it runs and again when it finishes.+{"type":"available_commands","tools":["web_search","web_fetch","search_tool","use_tool"],"commands":[]}+{"type":"text","data":"Let me read the page first."}+{"type":"tool_call","toolCallId":"call_1","title":"search_tool","kind":"search","status":"in_progress","toolName":"search_tool","rawInput":{"query":"page info"},"content":[],"locations":[]}+{"type":"tool_call_update","toolCallId":"call_1","status":"completed","content":[],"rawOutput":{"tools":["browsentic__page_getPageInfo"]},"locations":[]}+{"type":"tool_call","toolCallId":"call_2","title":"use_tool","kind":"other","status":"in_progress","toolName":"use_tool","rawInput":{"tool_name":"browsentic__page_getPageInfo","tool_input":{"maxPerKind":30}},"content":[],"locations":[]}+{"type":"tool_call_update","toolCallId":"call_2","status":"completed","content":[],"rawOutput":{"ok":true},"locations":[]}+{"type":"usage","messageId":"resp_1","stopReason":"tool_use","usage":{"input_tokens":900,"output_tokens":30,"cache_read_input_tokens":3000,"cache_creation_input_tokens":0,"reasoning_tokens":0},"signature":"sig_1"}+{"type":"tool_call","toolCallId":"call_3","title":"web_search","kind":"search","status":"in_progress","toolName":"web_search","rawInput":{"query":"acme pro plan price"},"content":[],"locations":[]}+{"type":"tool_call","toolCallId":"call_3","title":"web_search","kind":"search","status":"completed","toolName":"web_search","rawInput":{"query":"acme pro plan price"},"content":[],"locations":[]}+{"type":"tool_call","toolCallId":"call_4","title":"use_tool","kind":"other","status":"pending","toolName":"use_tool","content":[],"locations":[]}+{"type":"tool_call","toolCallId":"call_4","title":"use_tool","kind":"other","status":"in_progress","toolName":"use_tool","rawInput":{"tool_name":"github__create_issue","tool_input":{"title":"price"}},"content":[],"locations":[]}+{"type":"usage","messageId":"resp_2","stopReason":"tool_use","usage":{"input_tokens":400,"output_tokens":20,"cache_read_input_tokens":3900,"cache_creation_input_tokens":0,"reasoning_tokens":0},"signature":"sig_2"}+{"type":"plan","entries":[{"content":"Compare the prices","status":"completed"}]}+{"type":"text","data":"It costs $12 a month."}+{"type":"usage","messageId":"resp_3","stopReason":"end_turn","usage":{"input_tokens":150,"output_tokens":10,"cache_read_input_tokens":4300,"cache_creation_input_tokens":0,"reasoning_tokens":0},"signature":"sig_3"}+{"type":"auto_compact_started"}+{"type":"end","stopReason":"end_turn","sessionId":"0199a3c4-5b6d-7e8f-9a0b-1c2d3e4f5a6b","requestId":"req_2","num_turns":3}diff --git a/src/daemon/agent/runners/fixtures/grok/turn.hand-written.jsonl b/src/daemon/agent/runners/fixtures/grok/turn.hand-written.jsonlnew file mode 100644index 0000000..2bb41b1--- /dev/null+++ b/src/daemon/agent/runners/fixtures/grok/turn.hand-written.jsonl@@ -0,0 +1,7 @@+# Hand-written from the streaming-json section of grok 1.0.40's own docs (~/.grok/docs/user-guide/14-headless-mode.md), not recorded: the free account it was written on is rate-limited before the model answers. A turn that thinks, says its answer in two chunks and finishes.+{"type":"available_commands","tools":["todo_write","search_tool","use_tool"],"commands":[]}+{"type":"thought","data":"The price is in the page heading."}+{"type":"text","data":"It costs "}+{"type":"text","data":"$12 a month."}+{"type":"usage","messageId":"resp_1","stopReason":"end_turn","usage":{"input_tokens":812,"output_tokens":45,"cache_read_input_tokens":4000,"cache_creation_input_tokens":0,"reasoning_tokens":12},"signature":"sig_1"}+{"type":"end","stopReason":"end_turn","sessionId":"0199a3c4-5b6d-7e8f-9a0b-1c2d3e4f5a6b","requestId":"req_1","usage":{"input_tokens":812,"output_tokens":45,"cache_read_input_tokens":4000,"cache_creation_input_tokens":0,"reasoning_tokens":12,"total_tokens":4857},"num_turns":1}diff --git a/src/daemon/agent/runners/grok.test.ts b/src/daemon/agent/runners/grok.test.tsnew file mode 100644index 0000000..097feef--- /dev/null+++ b/src/daemon/agent/runners/grok.test.ts@@ -0,0 +1,331 @@+import { existsSync, mkdirSync, utimesSync } from 'node:fs';+import { homedir } from 'node:os';+import { basename, dirname, join } from 'node:path';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { stateDir } from '../../lockfile';+import { grokRunner } from './grok';+import { jsonContext, readThrough, shown, streamContext, transcript, valueOf } from './fixtures/support';++const settings = { bin: 'grok' };+const stream = (overrides: Parameters<typeof streamContext>[1] = {}) => grokRunner.stream(streamContext(settings, overrides));+const task = (overrides: Parameters<typeof jsonContext>[1] = {}) => grokRunner.json(jsonContext(settings, overrides));+const read = (name: string, only?: Parameters<typeof readThrough>[2]) => readThrough(grokRunner, transcript('grok', name), only);+const readLines = (...lines: object[]) => readThrough(grokRunner, lines.map((line) => JSON.stringify(line)));+const recorded = (name: string) => transcript('grok', name).join('\n');++const SESSION = '0199a3c4-5b6d-7e8f-9a0b-1c2d3e4f5a6b';++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('a streamed run', () => {+ test('a fresh run is contained by flags, and only the browser server is written to disk', () => {+ expect(shown(stream())).toMatchInlineSnapshot(`+ {+ "args": [+ "-p",+ "what does this page cost",+ "--output-format",+ "streaming-json",+ "--permission-mode",+ "dontAsk",+ "--allow",+ "MCPTool(browsentic__*)",+ "--tools",+ "todo_write",+ "--deny",+ "Bash",+ "--deny",+ "Edit",+ "--deny",+ "Write",+ "--deny",+ "Read",+ "--no-subagents",+ "--sandbox",+ "workspace",+ "--rules",+ "You are Browsentic.++ Browsentic's tools are on the MCP server named browsentic. Call them with use_tool, prefixing each name with "browsentic__": page_getPageInfo is browsentic__page_getPageInfo.",+ "--session-id",+ "<uuid>",+ ],+ "cwd": "<state>/agents/grok/run/<uuid>",+ "env": {+ "BROWSENTIC_AGENT_RUN": "run-1",+ "GROK_CLAUDE_MCPS_ENABLED": "false",+ "GROK_CURSOR_MCPS_ENABLED": "false",+ "GROK_FOLDER_TRUST": "0",+ "GROK_MEMORY": "0",+ },+ "files": [+ {+ "content": "[mcp_servers.browsentic]+ command = "/usr/local/bin/node"+ args = ["/usr/local/lib/node_modules/browsentic/dist/cli.js", "mcp"]+ env = { BROWSENTIC_AGENT_RUN = "run-1" }+ ",+ "path": ".grok/config.toml",+ },+ ],+ }+ `);+ });++ test('a fresh run names its own session, and runs in a directory named after it', () => {+ const plan = stream();+ expect(valueOf(plan.args, '--session-id')).toBe(basename(plan.cwd));+ });++ test('a follow-up resumes the session in the directory its conversation started in', () => {+ const plan = stream({ sessionId: SESSION });+ expect({ resume: valueOf(plan.args, '--resume'), fresh: plan.args.includes('--session-id'), cwd: plan.cwd }).toEqual({+ resume: SESSION,+ fresh: false,+ cwd: join(grokRunner.workspace('run'), SESSION),+ });+ });++ test('a session id that is not a plain id cannot steer where the run happens', () => {+ expect(stream({ sessionId: '../../../etc' }).cwd).toBe(join(grokRunner.workspace('run'), '_________etc'));+ });++ test('research swaps the inert tool for web search and fetch, and changes nothing else', () => {+ const [plain, research] = [stream().args, stream({ research: true }).args];+ const changed = plain.flatMap((arg, at) => (arg === research[at] || arg === valueOf(plain, '--session-id') ? [] : [[arg, research[at]]]));+ expect(changed).toEqual([['todo_write', 'web_search,web_fetch']]);+ });++ test('the system prompt goes in as rules, followed by how Grok names the browser tools', () => {+ expect(valueOf(stream().args, '--rules')).toBe(+ 'You are Browsentic.\n\n' ++ 'Browsentic\'s tools are on the MCP server named browsentic. Call them with use_tool, prefixing each name with "browsentic__": page_getPageInfo is browsentic__page_getPageInfo.',+ );+ });++ test('the chosen model and effort are passed through', () => {+ const args = grokRunner.stream(streamContext({ bin: 'grok', model: 'grok-4.7', effort: 'xhigh' })).args;+ expect(args.slice(-4)).toEqual(['--model', 'grok-4.7', '--reasoning-effort', 'xhigh']);+ });++ test('an effort Grok does not accept is dropped rather than failing the run', () => {+ expect(grokRunner.stream(streamContext({ bin: 'grok', effort: 'max' })).args).not.toContain('--reasoning-effort');+ });++ test("yesterday's conversation directories are swept when a new run starts, and today's are kept", () => {+ const base = grokRunner.workspace('run');+ const [old, recent] = [join(base, 'conv-old'), join(base, 'conv-recent')];+ for (const dir of [old, recent]) mkdirSync(dir, { recursive: true });+ const yesterday = (Date.now() - 25 * 60 * 60_000) / 1000;+ utimesSync(old, yesterday, yesterday);+ stream();+ expect([existsSync(old), existsSync(recent)]).toEqual([false, true]);+ });+});++describe('a one-shot task', () => {+ test('a task writes nothing, refuses every MCP call and stays in a read-only sandbox', () => {+ expect(shown(task())).toMatchInlineSnapshot(`+ {+ "args": [+ "-p",+ "summarize this",+ "--output-format",+ "json",+ "--permission-mode",+ "dontAsk",+ "--tools",+ "todo_write",+ "--deny",+ "MCPTool",+ "--deny",+ "Bash",+ "--deny",+ "Edit",+ "--deny",+ "Write",+ "--no-subagents",+ "--sandbox",+ "read-only",+ ],+ "cwd": "<state>/agents/grok/task",+ "env": {+ "GROK_CLAUDE_MCPS_ENABLED": "false",+ "GROK_CURSOR_MCPS_ENABLED": "false",+ "GROK_MEMORY": "0",+ },+ }+ `);+ });++ test('a task handed a file may read it, and nothing else changes', () => {+ const [plain, reading] = [task().args, task({ reads: true }).args];+ expect(plain.flatMap((arg, at) => (arg === reading[at] ? [] : [[arg, reading[at]]]))).toEqual([['todo_write', 'read_file']]);+ });++ test('runs and tasks never share a directory', () => {+ expect(dirname(stream().cwd)).not.toBe(task().cwd);+ });+});++describe('reading the stream', () => {+ test('a turn says its answer, reports what it cost, names its session and finishes', () => {+ expect(read('turn.hand-written.jsonl')).toEqual([+ ['text', 'It costs '],+ ['text', '$12 a month.'],+ ['usage', { contextTokens: 4857, outputTokens: 45 }],+ ['session', SESSION],+ ['done', 'end_turn'],+ ]);+ });++ test('a Browsentic call and a tool lookup are left to the daemon; web search and another server are reported once each', () => {+ expect(read('tool-loop.hand-written.jsonl', 'tool')).toEqual([+ ['tool', 'call_3', 'web_search'],+ ['tool', 'call_4', 'github__create_issue'],+ ]);+ });++ test('each model response after the first starts a new paragraph', () => {+ expect(+ read('tool-loop.hand-written.jsonl', 'text')+ .map(([, text]) => text)+ .join(''),+ ).toBe('Let me read the page first.\n\nIt costs $12 a month.');+ });++ test('usage is reported per response, with the output added up', () => {+ expect(read('tool-loop.hand-written.jsonl', 'usage')).toEqual([+ ['usage', { contextTokens: 3930, outputTokens: 30 }],+ ['usage', { contextTokens: 4320, outputTokens: 50 }],+ ['usage', { contextTokens: 4460, outputTokens: 60 }],+ ]);+ });++ test('a turn with no usage lines reports the total the end line carries', () => {+ expect(readLines({ type: 'end', stopReason: 'end_turn', sessionId: SESSION, usage: { input_tokens: 100, output_tokens: 7 } })).toEqual([+ ['session', SESSION],+ ['usage', { contextTokens: 107, outputTokens: 7 }],+ ['done', 'end_turn'],+ ]);+ });++ test('the toolset a contained run is offered passes without a word', () => {+ expect(readLines({ type: 'available_commands', tools: ['todo_write', 'search_tool', 'use_tool'], commands: [] })).toEqual([]);+ });++ test('a toolset with the shell or file tools in it stops the run before the model sees it', () => {+ expect(read('1.0.40-every-tool.jsonl')).toEqual([+ [+ 'fail',+ 'AGENT_UNSAFE',+ 'Grok Build offered this run run_terminal_command, read_file, search_replace, list_dir, grep, kill_command_or_subagent, get_command_or_subagent_output, spawn_subagent, scheduler_create, scheduler_delete, scheduler_list, monitor, workflow, enter_plan_mode, exit_plan_mode, ask_user_question, send_feedback, image_gen, image_edit, image_to_video, reference_to_video, write, which Browsentic never asks for, so the run was stopped before the model saw them. Update Grok Build and Browsentic; if it persists, please report it.',+ ],+ ]);+ });++ test('a rate-limited account fails after Grok gives up retrying, and says what is going on', () => {+ expect(read('1.0.40-rate-limited.jsonl')).toEqual([+ [+ 'fail',+ 'AGENT_FAILED',+ expect.stringMatching(/^xAI did not answer, after Grok Build had retried for several minutes\. A free Grok account is rate-limited this way; wait and try again\. \(Internal error: /),+ ],+ ]);+ });++ test('a signed-out Grok is told to sign in', () => {+ expect(read('1.0.40-not-signed-in.jsonl')).toEqual([+ ['fail', 'AGENT_FAILED', 'Grok Build is installed but not signed in. Run "grok login", or set XAI_API_KEY, then try again.'],+ ]);+ });++ test('a model the account does not have says so, and where to pick another', () => {+ expect(read('1.0.40-unknown-model.jsonl')).toEqual([+ [+ 'fail',+ 'AGENT_FAILED',+ 'Couldn\'t set model \'grok-nope\': Invalid params: "unknown model id". Run \'grok models\' to see available models. Pick another model for Grok Build in the Browsentic popup, then try again.',+ ],+ ]);+ });++ test('an effort the model does not offer says so, and where to pick another', () => {+ expect(read('1.0.40-unknown-effort.jsonl')).toEqual([+ [+ 'fail',+ 'AGENT_FAILED',+ "--effort/--reasoning-effort: unknown effort level 'ultra'; use one of: xhigh, high, medium, low. Pick another effort for Grok Build in the Browsentic popup, then try again.",+ ],+ ]);+ });++ test('a rate limit Grok reports at once is explained the same way', () => {+ expect(readLines({ type: 'error', message: 'Some resource has been exhausted: You are sending requests too quickly.' })).toEqual([+ [+ 'fail',+ 'AGENT_FAILED',+ 'xAI is rate-limiting this Grok account. Wait a few minutes and try again, or upgrade at https://grok.com/supergrok. (Some resource has been exhausted: You are sending requests too quickly.)',+ ],+ ]);+ });++ test('an error with nothing to say still fails, in words', () => {+ expect(readLines({ type: 'error' })).toEqual([['fail', 'AGENT_FAILED', 'Grok Build reported an error']]);+ });++ test('lines it does not understand are passed over', () => {+ expect(readThrough(grokRunner, ['not json', '{"type":"max_turns_reached"}', '{"type":"thought","data":"hm"}'])).toEqual([]);+ });+});++describe('the answer to a one-shot task', () => {+ test('is the text of the result', () => {+ expect(grokRunner.answer(JSON.stringify({ text: 'A pricing page.', stopReason: 'end_turn', sessionId: SESSION }))).toEqual({+ text: 'A pricing page.',+ });+ });++ test('a signed-out Grok is an error, not an answer', () => {+ expect(grokRunner.answer(recorded('1.0.40-not-signed-in.jsonl'))).toEqual({+ error: 'Grok Build is installed but not signed in. Run "grok login", or set XAI_API_KEY, then try again.',+ });+ });++ test('output with no result is no answer', () => {+ expect(grokRunner.answer('')).toEqual({ text: undefined });+ });+});++describe('what a failed start is explained as', () => {+ test('the error Grok printed, with what to do about it', () => {+ expect(grokRunner.hint?.("Error: Couldn't set model 'grok-nope': Invalid params: \"unknown model id\".\n")).toMatch(+ /Pick another model for Grok Build in the Browsentic popup/,+ );+ });++ test('a Grok too old for the flags is told to update', () => {+ expect(grokRunner.hint?.("error: unexpected argument '--sandbox' found\n")).toBe(+ 'Your Grok Build does not understand the flags Browsentic uses. Run "grok update", then try again. (error: unexpected argument \'--sandbox\' found)',+ );+ });++ test('anything else is left to the exit code', () => {+ expect(grokRunner.hint?.('segmentation fault')).toBeNull();+ });+});++test("the user's own skills are listed from Grok's home, the shared agents folder and Claude Code's", () => {+ vi.stubEnv('GROK_HOME', '');+ expect(grokRunner.skillDirs?.()).toEqual([+ join(homedir(), '.grok', 'skills'),+ join(homedir(), '.agents', 'skills'),+ join(homedir(), '.claude', 'skills'),+ ]);+});++test('every directory a run or task uses is inside the state directory', () => {+ expect([stream().cwd, task().cwd].every((cwd) => cwd.startsWith(`${stateDir}/`))).toBe(true);+});diff --git a/src/daemon/agent/runners/grok.ts b/src/daemon/agent/runners/grok.tsnew file mode 100644index 0000000..2a2aeee--- /dev/null+++ b/src/daemon/agent/runners/grok.ts@@ -0,0 +1,289 @@+import { randomUUID } from 'node:crypto';+import { existsSync } from 'node:fs';+import { homedir } from 'node:os';+import { join } from 'node:path';+import type { AgentProblem } from '@/lib/agents/catalog';+import { stateDir } from '../../lockfile';+import { MCP_SERVER_NAME } from './claude';+import { effortOf, parseJsonLine, sweepRunDirs } from './util';+import type { JsonContext, McpServer, Plan, Runner, RunMode, StreamContext, StreamReader, StreamSink } from './types';++/** Grok takes every setting a run needs as a flag except its MCP server, which only a project config can add. */+const CONFIG = '.grok/config.toml';++/** `--tools` with nothing in it switches every tool on, so a run that needs none names the one that touches nothing. */+const INERT = 'todo_write';+const WEB_TOOLS = ['web_search', 'web_fetch'];+const READ_TOOL = 'read_file';++/** Every MCP call goes through these two, and Grok offers them whatever `--tools` says. */+const SEARCH_TOOL = 'search_tool';+const USE_TOOL = 'use_tool';++/** All a run can be offered. Anything else means Grok did not honour the list it was given. */+const OFFERED = [SEARCH_TOOL, USE_TOOL, INERT, ...WEB_TOOLS];++const DENIED = ['Bash', 'Edit', 'Write'];++/** Its MCP servers and memory are switched in the environment; see CONTAINMENT.grok for why. */+const SEALED = { GROK_MEMORY: '0', GROK_CLAUDE_MCPS_ENABLED: 'false', GROK_CURSOR_MCPS_ENABLED: 'false' };++/** Headless Grok skips a project's MCP server in a folder nobody trusted, without a word; this trusts one process, not the folder. */+const TRUSTED = { GROK_FOLDER_TRUST: '0' };++/** The skill prompts name tools as the server lists them; Grok reaches them under its own prefix. */+const TOOL_NAMES =+ `Browsentic's tools are on the MCP server named ${MCP_SERVER_NAME}. ` ++ `Call them with ${USE_TOOL}, prefixing each name with "${MCP_SERVER_NAME}__": page_getPageInfo is ${MCP_SERVER_NAME}__page_getPageInfo.`;++const grokHome = () => process.env.GROK_HOME || join(homedir(), '.grok');++interface Usage {+ input_tokens?: number;+ cache_read_input_tokens?: number;+ cache_creation_input_tokens?: number;+ output_tokens?: number;+}++interface Event {+ type?: string;+ data?: string;+ tools?: string[];+ toolCallId?: string;+ toolName?: string;+ rawInput?: { tool_name?: string };+ usage?: Usage;+ stopReason?: string;+ sessionId?: string;+ message?: string;+}++interface Answer {+ type?: string;+ text?: string;+ message?: string;+}++export const grokRunner: Runner = {+ kind: 'grok',+ versionArgs: ['--version'],+ efforts: ['low', 'medium', 'high', 'xhigh'],++ workspace: (mode: RunMode) => join(stateDir, 'agents', 'grok', mode),++ skillDirs: () => [join(grokHome(), 'skills'), join(homedir(), '.agents', 'skills'), join(homedir(), '.claude', 'skills')],++ stream(context: StreamContext): Plan {+ const { settings, research } = context;+ const effort = effortOf(settings, this.efforts);+ const base = this.workspace('run');+ sweepRunDirs(base);+ // A conversation keeps one directory, so a resume finds its session wherever Grok files it.+ const conversation = context.sessionId ?? randomUUID();+ return {+ cwd: join(base, conversation.replace(/[^\w-]/g, '_')),+ env: { BROWSENTIC_AGENT_RUN: context.runId, ...SEALED, ...TRUSTED },+ files: [{ path: CONFIG, content: config(context.mcp) }],+ args: [+ '-p',+ context.instruction,+ '--output-format',+ 'streaming-json',+ '--permission-mode',+ 'dontAsk',+ '--allow',+ `MCPTool(${MCP_SERVER_NAME}__*)`,+ '--tools',+ (research ? WEB_TOOLS : [INERT]).join(','),+ ...denying([...DENIED, 'Read']),+ '--no-subagents',+ '--sandbox',+ 'workspace',+ '--rules',+ `${context.systemPrompt.trim()}\n\n${TOOL_NAMES}`,+ ...(context.sessionId ? ['--resume', context.sessionId] : ['--session-id', conversation]),+ ...(settings.model ? ['--model', settings.model] : []),+ ...(effort ? ['--reasoning-effort', effort] : []),+ ],+ };+ },++ reader(): StreamReader {+ const reported = new Set<string>();+ let said = false;+ let turned = false;+ let counted = false;+ let generated = 0;++ const report = (usage: Usage, sink: StreamSink) => {+ counted = true;+ generated += usage.output_tokens ?? 0;+ sink.usage({+ contextTokens:+ (usage.input_tokens ?? 0) ++ (usage.cache_read_input_tokens ?? 0) ++ (usage.cache_creation_input_tokens ?? 0) ++ (usage.output_tokens ?? 0),+ outputTokens: generated,+ });+ };++ return (line, sink) => {+ const event = parseJsonLine<Event>(line);+ if (!event) return;++ switch (event.type) {+ case 'available_commands': {+ const unexpected = (event.tools ?? []).filter((tool) => !OFFERED.includes(tool));+ if (!unexpected.length) return;+ return sink.fail(+ 'AGENT_UNSAFE',+ `Grok Build offered this run ${unexpected.join(', ')}, which Browsentic never asks for, so the run was stopped before the model saw them. ` ++ 'Update Grok Build and Browsentic; if it persists, please report it.',+ );+ }++ case 'text':+ if (!event.data) return;+ sink.text(said && turned ? `\n\n${event.data}` : event.data);+ said = true;+ turned = false;+ return;++ case 'tool_call': {+ turned = true;+ const id = event.toolCallId;+ const name = toolOf(event);+ if (!id || !name || reported.has(id)) return;+ reported.add(id);+ if (name !== SEARCH_TOOL && !ownTool(name)) sink.tool(id, name);+ return;+ }++ case 'usage':+ turned = true;+ if (event.usage) report(event.usage, sink);+ return;++ case 'end':+ if (event.sessionId) sink.session(event.sessionId);+ if (!counted && event.usage) report(event.usage, sink);+ return sink.done(event.stopReason || 'end_turn');++ case 'error':+ return sink.fail('AGENT_FAILED', explain(event.message) ?? 'Grok Build reported an error');++ default:+ return;+ }+ };+ },++ json(context: JsonContext): Plan {+ const { settings } = context;+ const effort = effortOf(settings, this.efforts);+ return {+ cwd: this.workspace('task'),+ env: { ...SEALED },+ args: [+ '-p',+ context.prompt,+ '--output-format',+ 'json',+ '--permission-mode',+ 'dontAsk',+ '--tools',+ context.reads ? READ_TOOL : INERT,+ ...denying(['MCPTool', ...DENIED]),+ '--no-subagents',+ '--sandbox',+ 'read-only',+ ...(settings.model ? ['--model', settings.model] : []),+ ...(effort ? ['--reasoning-effort', effort] : []),+ ],+ };+ },++ answer(stdout: string) {+ const answer = lastLine<Answer>(stdout);+ if (answer?.type === 'error') return { error: explain(answer.message) ?? 'Grok Build reported an error' };+ return { text: answer?.text };+ },++ hint(stderrTail: string) {+ const error = /^Error: ([\s\S]+)/m.exec(stderrTail)?.[1]?.trim();+ if (error) return explain(error) ?? null;+ if (/unexpected argument|unrecognized|invalid value/i.test(stderrTail)) {+ return `Your Grok Build does not understand the flags Browsentic uses. Run "grok update", then try again. (${stderrTail.trim()})`;+ }+ return null;+ },++ async check(): Promise<AgentProblem | null> {+ if (process.env.XAI_API_KEY || existsSync(join(grokHome(), 'auth.json'))) return null;+ return {+ code: 'AGENT_NEEDS_PERMISSION',+ message: 'Grok Build is installed but not signed in.',+ fix: 'grok login',+ };+ },+};++const denying = (rules: string[]) => rules.flatMap((rule) => ['--deny', rule]);++const ownTool = (name: string) => name.startsWith(`${MCP_SERVER_NAME}__`);++/** An MCP call is reported under the tool it reaches, which only its input names. */+function toolOf(event: Event): string | undefined {+ if (event.toolName !== USE_TOOL) return event.toolName;+ return event.rawInput ? (event.rawInput.tool_name ?? USE_TOOL) : undefined;+}++/** Grok's own sentence, with what to do about it where Browsentic knows. */+function explain(message: string | undefined): string | undefined {+ if (!message) return message;+ if (/not signed in/i.test(message)) {+ return 'Grok Build is installed but not signed in. Run "grok login", or set XAI_API_KEY, then try again.';+ }+ if (/unknown model id|couldn't set model/i.test(message)) {+ return `${sentence(message)} Pick another model for Grok Build in the Browsentic popup, then try again.`;+ }+ if (/unknown effort level/i.test(message)) {+ return `${sentence(message)} Pick another effort for Grok Build in the Browsentic popup, then try again.`;+ }+ if (/resource has been exhausted|requests too quickly/i.test(message)) {+ return `xAI is rate-limiting this Grok account. Wait a few minutes and try again, or upgrade at https://grok.com/supergrok. (${oneLine(message)})`;+ }+ // Grok retries a rate-limited request for minutes before it gives up with this.+ if (/did not respond to this request|service temporarily unavailable/i.test(message)) {+ return `xAI did not answer, after Grok Build had retried for several minutes. A free Grok account is rate-limited this way; wait and try again. (${oneLine(message)})`;+ }+ if (/re-run with --trust|folder untrusted/i.test(message)) {+ return `Grok Build refused to use Browsentic's workspace because it is not trusted. This is a bug in Browsentic — please report it. (${message})`;+ }+ return message;+}++const oneLine = (message: string) => message.replace(/\s+/g, ' ').slice(0, 240);++const sentence = (message: string) => (/[.!?]$/.test(message.trim()) ? message.trim() : `${message.trim()}.`);++function config(server: McpServer): string {+ const quote = (value: string) => JSON.stringify(value);+ const env = Object.entries(server.env).map(([name, value]) => `${name} = ${quote(value)}`);+ return [+ `[mcp_servers.${MCP_SERVER_NAME}]`,+ `command = ${quote(server.command)}`,+ `args = [${server.args.map(quote).join(', ')}]`,+ `env = { ${env.join(', ')} }`,+ '',+ ].join('\n');+}++function lastLine<T>(stdout: string): T | null {+ for (const line of stdout.trim().split('\n').reverse()) {+ const parsed = parseJsonLine<T>(line.trim());+ if (parsed) return parsed;+ }+ return null;+}diff --git a/src/daemon/agent/runners/index.test.ts b/src/daemon/agent/runners/index.test.tsindex 19f0578..9ec7373 100644--- a/src/daemon/agent/runners/index.test.ts+++ b/src/daemon/agent/runners/index.test.ts@@ -1,7 +1,7 @@import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { homedir } from 'node:os';-import { basename, join } from 'node:path';-import { beforeAll, beforeEach, describe, expect, test } from 'vitest';+import { basename, dirname, join } from 'node:path';+import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest';import { AGENT_KINDS, AGENTS, type AgentKind } from '@/lib/agents/catalog';import { stateDir } from '../../lockfile';import type { AgentConfig, AgentSettings } from '../config';@@ -28,7 +28,14 @@ const rounds = () => {const configWith = (agents: Partial<Record<AgentKind, AgentSettings>>, agent: AgentKind = 'claude'): AgentConfig => ({agent,- agents: { claude: { bin: join(bin, 'claude') }, codex: { bin: join(bin, 'codex') }, antigravity: { bin: join(bin, 'agy') }, vibe: { bin: join(bin, 'vibe') }, ...agents },+ agents: {+ claude: { bin: join(bin, 'claude') },+ codex: { bin: join(bin, 'codex') },+ antigravity: { bin: join(bin, 'agy') },+ vibe: { bin: join(bin, 'vibe') },+ grok: { bin: join(bin, 'grok') },+ ...agents,+ },requireApproval: [],});@@ -59,13 +66,20 @@ describe('the registry', () => {describe('readiness probes', () => {beforeAll(() => {mkdirSync(bin, { recursive: true });- for (const name of ['claude', 'claude-next', 'codex', 'agy', 'vibe']) stub(name);+ for (const name of ['claude', 'claude-next', 'codex', 'agy', 'vibe', 'grok']) stub(name);stub('codex-expired', { prints: 'licence expired', exit: 3 });});beforeEach(() => {rmSync(probes, { force: true });rmSync(join(homedir(), '.gemini'), { recursive: true, force: true });+ rmSync(join(homedir(), '.grok'), { recursive: true, force: true });+ vi.stubEnv('XAI_API_KEY', '');+ vi.stubEnv('GROK_HOME', '');+ });++ afterEach(() => {+ vi.unstubAllEnvs();});test('an installed agent is ready, with the version it printed', async () => {@@ -96,10 +110,28 @@ describe('readiness probes', () => {});});+ test('a Grok Build nobody signed in to is not ready, and says how to sign in', async () => {+ expect(await runner('grok', configWith({}))).toMatchObject({+ ready: false,+ version: 'grok 1.0.0',+ problem: { code: 'AGENT_NEEDS_PERMISSION', fix: 'grok login' },+ });+ });++ test('a Grok Build that is signed in, or has an API key, is ready', async () => {+ const signedIn = join(homedir(), '.grok', 'auth.json');+ mkdirSync(dirname(signedIn), { recursive: true });+ writeFileSync(signedIn, '{}');+ const withLogin = await runner('grok', configWith({}));+ rmSync(signedIn);+ vi.stubEnv('XAI_API_KEY', 'xai-key');+ expect([withLogin?.ready, (await runner('grok', configWith({})))?.ready]).toEqual([true, true]);+ });+test('probes are reused for half a minute, even when only the active agent changed', async () => {await agentState(configWith({}), { refresh: true });const again = await agentState(configWith({}, 'antigravity'));- expect([rounds(), again.active]).toEqual([[['agy', 'claude', 'codex', 'vibe']], 'antigravity']);+ expect([rounds(), again.active]).toEqual([[['agy', 'claude', 'codex', 'grok', 'vibe']], 'antigravity']);});test('asking for a refresh probes again', async () => {@@ -112,8 +144,8 @@ describe('readiness probes', () => {await agentState(configWith({}), { refresh: true });await agentState(configWith({ claude: { bin: join(bin, 'claude-next') } }));expect(rounds()).toEqual([- ['agy', 'claude', 'codex', 'vibe'],- ['agy', 'claude-next', 'codex', 'vibe'],+ ['agy', 'claude', 'codex', 'grok', 'vibe'],+ ['agy', 'claude-next', 'codex', 'grok', 'vibe'],]);});diff --git a/src/daemon/agent/runners/index.ts b/src/daemon/agent/runners/index.tsindex 3ad3759..9001a07 100644--- a/src/daemon/agent/runners/index.ts+++ b/src/daemon/agent/runners/index.ts@@ -14,6 +14,7 @@ import { log } from '../../log';import { antigravityRunner } from './antigravity';import { claudeRunner } from './claude';import { codexRunner } from './codex';+import { grokRunner } from './grok';import type { McpServer, Runner } from './types';import { vibeRunner } from './vibe';@@ -22,6 +23,7 @@ export const RUNNERS: Record<AgentKind, Runner> = {codex: codexRunner,antigravity: antigravityRunner,vibe: vibeRunner,+ grok: grokRunner,};const cliPath = join(dirname(fileURLToPath(import.meta.url)), 'cli.js');diff --git a/src/daemon/cli.ts b/src/daemon/cli.tsindex bd2ddfd..c8e8329 100644--- a/src/daemon/cli.ts+++ b/src/daemon/cli.ts@@ -36,7 +36,7 @@ const USAGE = `browsentic ${pkg.version} — hand your real browser to the agentbrowsentic revoke [id] unpair one browser by the id "sessions" prints, or all of thembrowsentic agent show which agent runs the side panel, and which are installed- browsentic agent <name> switch to claude, codex, antigravity or vibe+ browsentic agent <name> switch to claude, codex, antigravity, vibe or grokbrowsentic agent fix <name> let Browsentic fix what that agent still needsbrowsentic agent model <name> [model] pin that agent's model, or omit it for the CLI's defaultdiff --git a/src/daemon/guardrails/spawn.test.ts b/src/daemon/guardrails/spawn.test.tsindex 81a4265..0ddf042 100644--- a/src/daemon/guardrails/spawn.test.ts+++ b/src/daemon/guardrails/spawn.test.ts@@ -59,6 +59,14 @@ describe('spawn containment', () => {expect(vetPlan('vibe', 'task', planOf('vibe', 'task', { reads: true }), stateDir)).toEqual([]);});+ test('grok run with web tools is still contained', () => {+ expect(vetPlan('grok', 'run', planOf('grok', 'run', { research: true }), stateDir)).toEqual([]);+ });++ test('grok task that reads a file is still contained', () => {+ expect(vetPlan('grok', 'task', planOf('grok', 'task', { reads: true }), stateDir)).toEqual([]);+ });+describe('a one-shot task cannot reach the browser at all', () => {test('claude task carries no mcp server', () => {expect(planOf('claude', 'task').args).toContain('{"mcpServers":{}}');@@ -68,6 +76,11 @@ describe('spawn containment', () => {expect(planOf('codex', 'task').args).toContain('mcp_servers={}');});+ test('grok task refuses every MCP call, whichever server the user configured', () => {+ const args = planOf('grok', 'task').args;+ expect(args.flatMap((arg, at) => (arg === '--deny' ? [args[at + 1]] : []))).toContain('MCPTool');+ });+test('antigravity task writes an empty mcp config', () => {const config = planOf('antigravity', 'task').files?.find((file) => file.path === '.agents/mcp_config.json');expect(JSON.parse(config?.content ?? 'null')?.mcpServers).toEqual({});@@ -102,6 +115,14 @@ describe('spawn containment', () => {const claudeRun = planOf('claude', 'run');const codexRun = planOf('codex', 'run');const agyRun = planOf('antigravity', 'run');+ const grokRun = planOf('grok', 'run');+ const grokTask = planOf('grok', 'task');+ const withEnv = (plan: Plan, name: string, value?: string): Plan => {+ const env = { ...plan.env };+ if (value === undefined) delete env[name];+ else env[name] = value;+ return { ...plan, env };+ };test('dropping --strict-mcp-config is caught', () => {expect(vetPlan('claude', 'run', without(claudeRun, '--strict-mcp-config'), stateDir)).toHaveLength(1);@@ -183,6 +204,59 @@ describe('spawn containment', () => {expect(vetPlan('antigravity', 'run', { ...agyRun, files: [] }, stateDir)).toHaveLength(2);});+ test('dropping the grok sandbox is caught', () => {+ expect(vetPlan('grok', 'run', without(without(grokRun, '--sandbox'), 'workspace'), stateDir)).toHaveLength(1);+ });++ test('turning the grok sandbox off with a later flag is caught', () => {+ expect(vetPlan('grok', 'run', plus(grokRun, '--sandbox', 'off'), stateDir)).toHaveLength(1);+ });++ test('--sandbox=off is caught', () => {+ expect(vetPlan('grok', 'run', plus(grokRun, '--sandbox=off'), stateDir)).toHaveLength(1);+ });++ test('approving everything with a later permission mode is caught', () => {+ expect(vetPlan('grok', 'run', plus(grokRun, '--permission-mode', 'bypassPermissions'), stateDir)).toHaveLength(1);+ });++ test('--always-approve is caught', () => {+ expect(vetPlan('grok', 'run', plus(grokRun, '--always-approve'), stateDir)).toHaveLength(1);+ });++ test('dropping the grok tool list is caught', () => {+ expect(vetPlan('grok', 'run', without(without(grokRun, '--tools'), 'todo_write'), stateDir)).toHaveLength(1);+ });++ // An empty list is how Grok spells every tool, the shell and file editing among them.+ test('an empty grok tool list is caught', () => {+ expect(vetPlan('grok', 'run', swapped(grokRun, 'todo_write', ''), stateDir)).toHaveLength(1);+ });++ test('switching the shell on through the grok tool list is caught', () => {+ expect(vetPlan('grok', 'run', swapped(grokRun, 'todo_write', 'todo_write,run_terminal_command'), stateDir)).toHaveLength(1);+ });++ test('un-denying Read on a grok run is caught', () => {+ expect(vetPlan('grok', 'run', without(grokRun, 'Read'), stateDir)).toHaveLength(1);+ });++ test("letting Grok load Claude Code's MCP servers is caught", () => {+ expect(vetPlan('grok', 'run', withEnv(grokRun, 'GROK_CLAUDE_MCPS_ENABLED', 'true'), stateDir)).toHaveLength(1);+ });++ test("leaving Grok's memory on is caught", () => {+ expect(vetPlan('grok', 'run', withEnv(grokRun, 'GROK_MEMORY'), stateDir)).toHaveLength(1);+ });++ test('losing the grok mcp config is caught', () => {+ expect(vetPlan('grok', 'run', { ...grokRun, files: [] }, stateDir)).toHaveLength(1);+ });++ test('a grok task that could reach an MCP server is caught', () => {+ expect(vetPlan('grok', 'task', without(grokTask, 'MCPTool'), stateDir)).toHaveLength(1);+ });+test('running outside the state dir is caught', () => {expect(vetPlan('antigravity', 'run', { ...agyRun, cwd: '/tmp/anywhere' }, stateDir)).toHaveLength(1);});@@ -229,6 +303,7 @@ describe('environment sealing', () => {GEMINI_API_KEY: 'sk-gem',MISTRAL_API_KEY: 'sk-mis',GOOGLE_APPLICATION_CREDENTIALS: '/creds.json',+ XAI_API_KEY: 'xai-key',};const sealedFor = (kind: AgentKind) => sealEnv(kind, DIRTY);@@ -303,6 +378,18 @@ describe('environment sealing', () => {expect(sealedFor('claude')).not.toHaveProperty('MISTRAL_API_KEY');});+ test('grok keeps its own key', () => {+ expect(sealedFor('grok').XAI_API_KEY).toBe('xai-key');+ });++ test('claude loses the xai key', () => {+ expect(sealedFor('claude')).not.toHaveProperty('XAI_API_KEY');+ });++ test('grok loses the anthropic key', () => {+ expect(sealedFor('grok')).not.toHaveProperty('ANTHROPIC_API_KEY');+ });+test('claude loses those google credentials', () => {expect(sealedFor('claude')).not.toHaveProperty('GOOGLE_APPLICATION_CREDENTIALS');});diff --git a/src/daemon/guardrails/spawn.ts b/src/daemon/guardrails/spawn.tsindex d6c1a19..ab8fdd7 100644--- a/src/daemon/guardrails/spawn.ts+++ b/src/daemon/guardrails/spawn.ts@@ -11,8 +11,8 @@* Containment is delegated, because flags are the only lever those CLIs offer. That is* worth having, but it is a request rather than an enforcement: a dropped flag, a* renamed option, or a new runner written in a hurry leaves no trace at runtime and no- * failing check. So the plan is vetted here — at `launch()`, the one place all three- * runners pass through, before `spawn()` — and a plan that has lost its containment+ * failing check. So the plan is vetted here — at `launch()`, the one place every+ * runner passes through, before `spawn()` — and a plan that has lost its containment* does not start.** `sealEnv` is the half that does not depend on the CLI cooperating at all. The daemon@@ -35,6 +35,7 @@ export type SpawnMode = 'run' | 'task';export interface SpawnPlan {readonly args: readonly string[];readonly cwd: string;+ readonly env?: Readonly<Record<string, string>>;readonly files?: readonly { readonly path: string; readonly content: string }[];}@@ -54,19 +55,21 @@ interface ToolDenial {interface ToolAllowance {readonly flag: string;- /** Every value the plan passes after `flag` has to be one of these. */+ /** Every value the plan passes after `flag`, comma lists included, has to be one of these. */readonly only: readonly string[];}interface Requirements {/** Arguments the plan must carry verbatim. */readonly required: readonly string[];- /** `--flag value` pairs the plan must carry. */+ /** `--flag value` pairs the plan must carry, with no later occurrence of the flag saying otherwise. */readonly pairs: readonly (readonly [string, string])[];/** Tools the plan must name after a deny flag. */readonly denies?: ToolDenial;/** The whole of what the plan may switch on, for a CLI whose tool flag is an allowlist. */readonly allows?: ToolAllowance;+ /** Variables the plan must set for a CLI that takes a switch only from its environment. */+ readonly env?: Readonly<Record<string, string>>;/** Workspace files the plan must write before the CLI starts. */readonly files: readonly string[];}@@ -88,7 +91,7 @@ interface Containment {}/**- * Flags that hand a CLI the machine, in every spelling the three of them use. Checked+ * Flags that hand a CLI the machine, in every spelling the runners use. Checked* against every runner rather than only the one that owns each flag: the cost is* nothing and it covers the runner nobody has written yet.*/@@ -96,11 +99,12 @@ const FORBIDDEN: readonly RegExp[] = [/^--dangerously/i,/^--yolo$/i,/^--auto-approve$/i,+ /^--always-approve$/i,/^--full-auto$/i,/^--no-sandbox$/i,/^--allow-all/i,/danger-full-access/i,- /^--sandbox=?(workspace-write|danger-full-access)$/i,+ /^--sandbox=?(workspace-write|danger-full-access|off)$/i,/^sandbox_mode=(?!"read-only"$)/i,/^approval_policy=(?!"never"$)/i,/^--permission-mode=?(bypassPermissions|acceptEdits)$/i,@@ -109,6 +113,13 @@ const FORBIDDEN: readonly RegExp[] = [/** Local tools no run may ever have, whatever else it is allowed. */const NEVER = ['Bash', 'Edit', 'Write', 'NotebookEdit', 'Glob', 'Grep', 'Task'];+/**+ * Grok takes these only from its environment. It loads Claude Code's and Cursor's MCP servers+ * by default — the user's own `browsentic` entry among them, which reaches the browser without+ * a run's gate — and its memory would carry what a page said into the user's next session.+ */+const GROK_SEALED = { GROK_MEMORY: '0', GROK_CLAUDE_MCPS_ENABLED: 'false', GROK_CURSOR_MCPS_ENABLED: 'false' };+export const CONTAINMENT: Record<AgentKind, Containment> = {claude: {localTools: 'allowlist',@@ -186,6 +197,37 @@ export const CONTAINMENT: Record<AgentKind, Containment> = {files: ['.vibe/config.toml', 'AGENTS.md'],},},++ grok: {+ localTools: 'allowlist',+ keepsEnv: ['XAI_', 'GROK_'],+ note: 'per-run built-in tool list, approvals that refuse whatever was not granted up front, and a kernel sandbox that keeps writes in its own directory; reads are closed by the tool list and a Read deny rather than the sandbox, and MCP servers the user gave Grok itself still load',+ run: {+ required: ['--no-subagents'],+ // `--always-approve` would be the headless default; dontAsk runs only what was allowed.+ pairs: [+ ['--permission-mode', 'dontAsk'],+ ['--sandbox', 'workspace'],+ ],+ // Deny beats every allow Grok merges in, including the user's Claude Code rules.+ denies: { flag: '--deny', tools: ['Bash', 'Edit', 'Write', 'Read'] },+ allows: { flag: '--tools', only: ['todo_write', 'web_search', 'web_fetch'] },+ env: GROK_SEALED,+ files: ['.grok/config.toml'],+ },+ task: {+ required: ['--no-subagents'],+ pairs: [+ ['--permission-mode', 'dontAsk'],+ ['--sandbox', 'read-only'],+ ],+ // A bare MCPTool refuses every MCP call, from whichever server the user configured.+ denies: { flag: '--deny', tools: ['MCPTool', 'Bash', 'Edit', 'Write'] },+ allows: { flag: '--tools', only: ['todo_write', 'read_file'] },+ env: GROK_SEALED,+ files: [],+ },+ },};/**@@ -202,21 +244,28 @@ export function vetPlan(kind: AgentKind, mode: SpawnMode, plan: SpawnPlan, home:if (!plan.args.includes(arg)) problems.push(`${label} is spawned without ${arg}.`);}+ // A CLI takes the last of a repeated flag, so every occurrence has to say the same thing.for (const [flag, value] of rules.pairs) {- if (valueOf(plan.args, flag) !== value) problems.push(`${label} is spawned without ${flag} ${value}.`);+ const given = everyValueOf(plan.args, flag);+ if (!given.length || given.some((other) => other !== value)) problems.push(`${label} is spawned without ${flag} ${value}.`);}if (rules.denies) {- const named = variadic(plan.args, rules.denies.flag);+ const named = [...variadic(plan.args, rules.denies.flag), ...everyValueOf(plan.args, rules.denies.flag)];const missing = rules.denies.tools.filter((tool) => !named.includes(tool));if (missing.length) problems.push(`${label} does not deny ${missing.join(', ')} via ${rules.denies.flag}.`);}if (rules.allows) {- const named = everyValueOf(plan.args, rules.allows.flag);- const extra = named.filter((tool) => !rules.allows?.only.includes(tool));- if (!named.length) problems.push(`${label} is spawned without ${rules.allows.flag}, which leaves every tool on.`);- if (extra.length) problems.push(`${label} switches on ${extra.join(', ')} via ${rules.allows.flag}.`);+ const { flag, only } = rules.allows;+ const named = everyValueOf(plan.args, flag).flatMap((value) => value.split(',').map((tool) => tool.trim()));+ const extra = named.filter((tool) => tool && !only.includes(tool));+ if (!named.length || named.includes('')) problems.push(`${label} is spawned without a ${flag} list, which leaves every tool on.`);+ if (extra.length) problems.push(`${label} switches on ${extra.join(', ')} via ${flag}.`);+ }++ for (const [name, value] of Object.entries(rules.env ?? {})) {+ if (plan.env?.[name] !== value) problems.push(`${label} is spawned without ${name}=${value}.`);}for (const path of rules.files) {@@ -254,7 +303,7 @@ const SECRET_PREFIX: readonly string[] = ['NPM_', 'YARN_', 'PYPI_', 'CARGO_', 'DOCKER_', 'KUBE_', 'HELM_','STRIPE_', 'SLACK_', 'TWILIO_', 'SENDGRID_', 'SENTRY_', 'DATADOG_', 'PAGERDUTY_','DATABASE_', 'POSTGRES_', 'PGPASS', 'MYSQL_', 'REDIS_', 'MONGO_', 'SUPABASE_',- 'OPENAI_', 'ANTHROPIC_', 'GEMINI_', 'CLAUDE_', 'CODEX_', 'ANTIGRAVITY_', 'MISTRAL_', 'HF_', 'HUGGINGFACE_',+ 'OPENAI_', 'ANTHROPIC_', 'GEMINI_', 'CLAUDE_', 'CODEX_', 'ANTIGRAVITY_', 'MISTRAL_', 'XAI_', 'GROK_', 'HF_', 'HUGGINGFACE_','VERCEL_', 'NETLIFY_', 'CLOUDFLARE_', 'FLY_', 'HEROKU_', 'RAILWAY_',];@@ -307,11 +356,6 @@ export function sealedAway(kind: AgentKind, env: NodeJS.ProcessEnv): string[] {return Object.keys(env).filter((name) => !(name in sealed));}-function valueOf(args: readonly string[], flag: string): string | undefined {- const at = args.indexOf(flag);- return at === -1 ? undefined : args[at + 1];-}-/** The value after each occurrence of a flag that is repeated rather than variadic. */function everyValueOf(args: readonly string[], flag: string): string[] {return args.flatMap((arg, at) => (arg === flag && at + 1 < args.length ? [args[at + 1]] : []));diff --git a/src/lib/agents/catalog.ts b/src/lib/agents/catalog.tsindex 34e6efa..8215a16 100644--- a/src/lib/agents/catalog.ts+++ b/src/lib/agents/catalog.ts@@ -1,4 +1,4 @@-export const AGENT_KINDS = ['claude', 'codex', 'antigravity', 'vibe'] as const;+export const AGENT_KINDS = ['claude', 'codex', 'antigravity', 'vibe', 'grok'] as const;export type AgentKind = (typeof AGENT_KINDS)[number];@@ -52,6 +52,15 @@ export const AGENTS: Record<AgentKind, AgentDescriptor> = {docs: 'https://github.com/mistralai/mistral-vibe',models: ['mistral-medium-3.5'],},+ grok: {+ kind: 'grok',+ label: 'Grok Build',+ vendor: 'xAI',+ bin: 'grok',+ install: 'curl -fsSL https://x.ai/cli/install.sh | bash',+ docs: 'https://docs.x.ai/build/overview',+ models: ['grok-4.7'],+ },};export const AGENT_LIST: AgentDescriptor[] = AGENT_KINDS.map((kind) => AGENTS[kind]);