Skip to content

Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.

Add Grok CLI as a harness (#87)

Matheus Apolonio33977af77051
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ae202f5..8c6155a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,11 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht
> - **A página do servidor abre por HTTP num endereço privado,** como o Tailscale ou a rede de casa. Ela ficava em branco.
> - **Um agente só acorda outro quando precisa.** Quando um agente menciona outro na resposta, o router lê e chama só quem tem algo a fazer: um agradecimento ou um “combinado” não acordam ninguém. Na dúvida, chama.
> - **O app abre fora do instalador mesmo com uma versão estranha.** O atualizador, que nem é usado ali, conferia a versão ao abrir e derrubava o app.
+> - **Agentes no Grok.** Um agente pode rodar no Grok CLI, com a assinatura do grok.com, como roda no Cursor CLI. Cada resposta usa uma pasta própria: os seus plugins, skills e hooks não carregam, e só as ferramentas do Tucano ficam à mão.
+
+### Added
+
+- **Agents on Grok.** An agent can run on the [Grok CLI](https://x.ai/cli) with a grok.com subscription, the way it runs on Cursor CLI: sign in with `grok login` and pick a Grok model. Each reply runs in a folder and a home of its own, so your MCP servers, skills, hooks and plugins (Grok's and the ones installed for Claude Code or Cursor) don't load, Grok's own shell and files stay off, and Tucano's tools are the only ones it has. An `XAI_API_KEY` in the environment is set aside when grok.com is signed in, so the subscription isn't billed per token. The official installer is macOS and Linux. Thanks [@matheus-apolonio](https://github.com/matheus-apolonio)! ([#87](https://github.com/eduwxyz/tucano/pull/87))
### Changed
diff --git a/README.md b/README.md
index d1a0d07..c11c2c4 100644
--- a/README.md
+++ b/README.md
@@ -28,7 +28,7 @@ Coding agents got good. Working with *several* of them is still a mess of termin
- **A team, not a prompt box.** Agents with names, roles, tools and memory. They talk in channels, call each other with `@mentions` and hand work over: one finds the bug, another fixes it, a third reviews it, and you get the result.
- **Your rules.** Each agent sees only the tools you give it, with *no access*, *read*, or *read and write* per tool. Merges, purchases, posts, emails and deletes become an approval tied to the exact action, on your computer or your phone.
-- **Runs on what you already have.** Agents think with the Claude Code, Codex, Cursor CLI, OpenCode or Pi on your computer, the way you set them up: your subscription, your company's AI gateway, or your providers. No API key to paste, no per-token bill from us, and Tucano never sees your password.
+- **Runs on what you already have.** Agents think with the Claude Code, Codex, Cursor CLI, Grok, OpenCode or Pi on your computer, the way you set them up: your subscription, your company's AI gateway, or your providers. No API key to paste, no per-token bill from us, and Tucano never sees your password.
- **Everything stays on your computer.** Conversations, memory, logins, files. There is no Tucano server.
## What it does
@@ -90,6 +90,7 @@ Give an agent the apps on your computer, such as Notes, Calendar or Spotify, eac
| [Cursor CLI](https://cursor.com/cli) | Your Cursor account (`cursor-agent login`) | Runs with a home of its own, so your hooks, plugins, skills and `~/.cursor/mcp.json` servers don't load; Cursor's own file reads, writes and shell stay off; each reply adds about 10k tokens of Cursor's own prompt |
| [OpenCode](https://opencode.ai) | The providers you configured | Uses the models you have logins for |
| [Pi](https://pi.dev) | The providers you configured | Uses the models you have logins for |
+| [Grok](https://x.ai/cli) | grok.com (`grok login`) | Runs with a home of its own, so your MCP servers, skills, hooks and plugins (Grok's and the ones installed for Claude Code or Cursor) don't load; Grok's own shell and files stay off; only Tucano's gateway; an `XAI_API_KEY` in the environment is unset when grok.com is signed in, so the subscription isn't billed as API. The official installer is macOS and Linux |
Each agent picks its harness and model, so a team can mix them: Opus to fix, GPT to review, Haiku to route.
@@ -161,7 +162,7 @@ On Linux and Windows, use **Ctrl** instead of **⌘**. Closing the window keeps
flowchart LR
subgraph Mac["Your computer"]
UI["Window<br/>(React)"] <-->|MessagePort| Core["Core process<br/>SQLite · runs · memory · routines"]
- Core -->|"one turn, isolated"| CLI["Harness CLI<br/>claude · codex · cursor · opencode · pi"]
+ Core -->|"one turn, isolated"| CLI["Harness CLI<br/>claude · codex · cursor · grok · opencode · pi"]
CLI -->|"secret per-turn URL<br/>only this agent's tools"| GW["Tucano MCP gateway"]
GW --> Tools["Connectors (MCP)<br/>computer · browser · memory"]
GW -.->|"write action"| OK{{"Your approval"}}
diff --git a/README.pt-BR.md b/README.pt-BR.md
index 3115ebe..dca9175 100644
--- a/README.pt-BR.md
+++ b/README.pt-BR.md
@@ -28,7 +28,7 @@ Os agentes de código ficaram bons. Trabalhar com *vários* deles ainda é uma b
- **Um time, não uma caixa de prompt.** Agentes com nome, papel, ferramentas e memória. Eles conversam em canais, se chamam com `@menção` e passam o trabalho adiante: um acha o erro, outro corrige, um terceiro revisa, e o resultado chega pra você.
- **Suas regras.** Cada agente só enxerga as ferramentas que você deu, com *sem acesso*, *ler* ou *ler e escrever* em cada uma. Merge, compra, post, e-mail e exclusão viram um pedido de aprovação amarrado à ação exata, no computador ou no celular.
-- **Roda no que você já tem.** Os agentes pensam com o Claude Code, o Codex, o Cursor CLI, o OpenCode ou o Pi do seu computador, do jeito que você configurou: na sua assinatura, no gateway de IA da sua empresa ou nos seus provedores. Sem chave de API pra colar, sem cobrança por token da nossa parte, e o Tucano nunca vê a sua senha.
+- **Roda no que você já tem.** Os agentes pensam com o Claude Code, o Codex, o Cursor CLI, o Grok, o OpenCode ou o Pi do seu computador, do jeito que você configurou: na sua assinatura, no gateway de IA da sua empresa ou nos seus provedores. Sem chave de API pra colar, sem cobrança por token da nossa parte, e o Tucano nunca vê a sua senha.
- **Tudo fica no seu computador.** Conversas, memória, logins, arquivos. Não existe servidor do Tucano.
## O que ele faz
@@ -90,6 +90,7 @@ Dê a um agente os apps do seu computador, como Notas, Calendário ou Spotify, c
| [Cursor CLI](https://cursor.com/cli) | Sua conta do Cursor (`cursor-agent login`) | Roda com um home próprio, pra não carregar seus hooks, plugins, skills e os servidores do `~/.cursor/mcp.json`; a leitura, a escrita e o shell do próprio Cursor ficam desligados; cada resposta soma uns 10 mil tokens do prompt do próprio Cursor |
| [OpenCode](https://opencode.ai) | Os provedores que você configurou | Usa os modelos em que você tem login |
| [Pi](https://pi.dev) | Os provedores que você configurou | Usa os modelos em que você tem login |
+| [Grok](https://x.ai/cli) | grok.com (`grok login`) | Roda com uma pasta pessoal própria, pra não carregar os seus servidores MCP, skills, hooks e plugins (do Grok e os instalados pro Claude Code ou Cursor); o shell e os arquivos do próprio Grok ficam desligados; só o gateway do Tucano; uma `XAI_API_KEY` no ambiente é retirada quando o grok.com está logado, pra a assinatura não ser cobrada como API. O instalador oficial é macOS e Linux |
Cada agente escolhe o harness e o modelo, então um time pode misturar: Opus pra corrigir, GPT pra revisar, Haiku pra rotear.
@@ -161,7 +162,7 @@ No Linux e no Windows, use **Ctrl** no lugar do **⌘**. Fechar a janela deixa o
flowchart LR
subgraph Mac["Seu computador"]
UI["Janela<br/>(React)"] <-->|MessagePort| Core["Núcleo<br/>SQLite · respostas · memória · rotinas"]
- Core -->|"um turno, isolado"| CLI["CLI do harness<br/>claude · codex · cursor · opencode · pi"]
+ Core -->|"um turno, isolado"| CLI["CLI do harness<br/>claude · codex · cursor · grok · opencode · pi"]
CLI -->|"URL secreta por turno<br/>só as ferramentas do agente"| GW["Gateway MCP do Tucano"]
GW --> Tools["Conectores (MCP)<br/>computador · navegador · memória"]
GW -.->|"ação de escrita"| OK{{"Sua aprovação"}}
diff --git a/docs/windows.md b/docs/windows.md
index 3b2affa..20cb972 100644
--- a/docs/windows.md
+++ b/docs/windows.md
@@ -11,7 +11,7 @@ Status: **runs on Windows 10/11 (x64)**, in development (`npm run dev`) and as a
| Windows 10 or 11, x64 | Tested on Windows 10 Home 22H2 (19045) |
| [Node.js](https://nodejs.org) 24+ | For `npm install` and the tests |
| [Git for Windows](https://git-scm.com/download/win) | Its **Git Bash** is the shell agents' commands run in when an agent's computer is *This PC* (Claude Code on Windows needs it too). Without it, those commands fall back to `cmd.exe` |
-| At least one harness, signed in | Claude Code is the quickest: `irm https://claude.ai/install.ps1 \| iex`, then `claude auth login`. Codex, OpenCode and Pi install with npm (`npm install -g @openai/codex`, `npm install -g opencode-ai`, `npm install -g @earendil-works/pi-coding-agent`) |
+| At least one harness, signed in | Claude Code is the quickest: `irm https://claude.ai/install.ps1 \| iex`, then `claude auth login`. Codex, OpenCode and Pi install with npm (`npm install -g @openai/codex`, `npm install -g opencode-ai`, `npm install -g @earendil-works/pi-coding-agent`). Grok's installer is the POSIX script (`curl -fsSL https://x.ai/cli/install.sh \| bash`); it has no Windows one-liner |
| Optional: [Docker Desktop](https://www.docker.com/products/docker-desktop/) | For the isolated Linux computer. The first use pulls `node:22-bookworm` |
| Optional: Google Chrome | For an agent's browser; it is found in `Program Files`, `Program Files (x86)` or `%LOCALAPPDATA%` |
diff --git a/package.json b/package.json
index b3f7aa4..29e7adc 100644
--- a/package.json
+++ b/package.json
@@ -121,7 +121,7 @@
"artifactName": "tucano-linux-${arch}.${ext}",
"maintainer": "Eduardo da Silva <[email protected]>",
"synopsis": "A team of AI agents on your computer",
- "description": "Tucano is a team of AI agents that lives on your computer. You talk to them in channels; they research, write, code and use your tools, and you decide how far each one goes. It runs on the Claude Code, Codex, OpenCode or Pi you already have."
+ "description": "Tucano is a team of AI agents that lives on your computer. You talk to them in channels; they research, write, code and use your tools, and you decide how far each one goes. It runs on the Claude Code, Codex, Cursor CLI, Grok, OpenCode or Pi you already have."
},
"deb": {
"recommends": [
diff --git a/site/index.html b/site/index.html
index 9ffa8f8..82e213b 100644
--- a/site/index.html
+++ b/site/index.html
@@ -762,7 +762,7 @@ if (/(^|\.)tucano\.sh$/.test(location.hostname)) {
<div class="eyebrow"><span lang="pt-BR">Instalar</span><span lang="en">Install</span></div>
<h2 class="h2" style="margin-top:18px"><span lang="pt-BR">Do download ao primeiro agente <em>em minutos.</em></span><span lang="en">From download to your first agent <em>in minutes.</em></span></h2>
<ol>
- <li><div><b><span lang="pt-BR">Entre no seu harness</span><span lang="en">Sign in to your harness</span></b><span><span lang="pt-BR">Claude Code, Codex, Gemini, OpenCode ou Pi. Basta um.</span><span lang="en">Claude Code, Codex, Gemini, OpenCode or Pi. One is enough.</span></span></div></li>
+ <li><div><b><span lang="pt-BR">Entre no seu harness</span><span lang="en">Sign in to your harness</span></b><span><span lang="pt-BR">Claude Code, Codex, Cursor, Gemini, Grok, OpenCode ou Pi. Basta um.</span><span lang="en">Claude Code, Codex, Cursor, Gemini, Grok, OpenCode or Pi. One is enough.</span></span></div></li>
<li><div><b><span lang="pt-BR">Baixe e instale</span><span lang="en">Download and install it</span></b><span><span lang="pt-BR">No Mac, arraste pra Aplicativos: assinado e notarizado pela Apple, abre sem aviso. No Linux, o .deb (Ubuntu, Debian) ou o AppImage. Ou cole o comando ao lado. No Windows, o comando é no PowerShell: instala sem pedir administrador.</span><span lang="en">On a Mac, drag it to Applications: signed and notarized by Apple, it opens with no warning. On Linux, the .deb (Ubuntu, Debian) or the AppImage. Or paste the command alongside. On Windows, the command goes in PowerShell: no admin rights needed.</span></span></div></li>
<li><div><b><span lang="pt-BR">Monte o time com o Tuca</span><span lang="en">Build the team with Tuca</span></b><span><span lang="pt-BR">A introdução te leva até o primeiro agente.</span><span lang="en">The introduction walks you to your first agent.</span></span></div></li>
</ol>
@@ -780,7 +780,7 @@ if (/(^|\.)tucano\.sh$/.test(location.hostname)) {
<div class="rv"><div class="eyebrow"><span lang="pt-BR">Perguntas</span><span lang="en">FAQ</span></div><h2 class="h2" style="margin-top:18px"><span lang="pt-BR">O que todo mundo <em>pergunta primeiro.</em></span><span lang="en">What everyone <em>asks first.</em></span></h2></div>
<div class="qa rv">
<details open><summary><span lang="pt-BR">Quanto custa?</span><span lang="en">How much does it cost?</span></summary><p><span lang="pt-BR">Nada. O Tucano é grátis, sem recurso trancado. Você usa o plano do Claude ou do ChatGPT que já paga, os seus provedores, ou o gateway da empresa.</span><span lang="en">Nothing. Tucano is free, with no locked features. You use the Claude or ChatGPT plan you already pay for, your own providers, or your company’s gateway.</span></p></details>
- <details><summary><span lang="pt-BR">Preciso de chave de API?</span><span lang="en">Do I need an API key?</span></summary><p><span lang="pt-BR">Não. Ele roda o Claude Code, o Codex, o Gemini, o OpenCode ou o Pi já configurados no seu computador. O app nunca vê nem guarda a sua senha.</span><span lang="en">No. It runs Claude Code, Codex, Gemini, OpenCode or Pi as they’re already set up on your computer. The app never sees or stores your password.</span></p></details>
+ <details><summary><span lang="pt-BR">Preciso de chave de API?</span><span lang="en">Do I need an API key?</span></summary><p><span lang="pt-BR">Não. Ele roda o Claude Code, o Codex, o Cursor, o Gemini, o Grok, o OpenCode ou o Pi já configurados no seu computador. O app nunca vê nem guarda a sua senha.</span><span lang="en">No. It runs Claude Code, Codex, Cursor, Gemini, Grok, OpenCode or Pi as they’re already set up on your computer. The app never sees or stores your password.</span></p></details>
<details><summary><span lang="pt-BR">É seguro deixar agentes mexendo nas coisas?</span><span lang="en">Is it safe to let agents touch things?</span></summary><p><span lang="pt-BR">Cada agente só usa o que recebeu, ações sensíveis pedem o seu sim (amarrado àquela ação exata) e os comandos rodam num Linux isolado, a não ser que você escolha dar o seu computador.</span><span lang="en">Each agent only uses what it was given, sensitive actions need your yes (tied to that exact action), and commands run on an isolated Linux machine, unless you choose to hand over your own computer.</span></p></details>
<details><summary><span lang="pt-BR">Onde ficam os meus dados?</span><span lang="en">Where does my data live?</span></summary><p><span lang="pt-BR">No seu computador: conversas, memória, arquivos e logins. O modelo recebe só o que os agentes mandam pra ele, pelo caminho que o seu harness já usa.</span><span lang="en">On your computer: conversations, memory, files and logins. The model only receives what the agents send it, through the path your harness already uses.</span></p></details>
<details><summary><span lang="pt-BR">E se o plano chegar no limite?</span><span lang="en">What if my plan hits its limit?</span></summary><p><span lang="pt-BR">Você define limite por agente e teto por resposta. O app confere antes de cada resposta, avisa em 80% e mostra onde cada agente vai fechar o mês no ritmo atual.</span><span lang="en">You set a limit per agent and a cap per reply. The app checks before every reply, warns at 80% and shows where each agent will end the month at the current pace.</span></p></details>
diff --git a/src/core/engines/detect.ts b/src/core/engines/detect.ts
index e923f82..7655dc4 100644
--- a/src/core/engines/detect.ts
+++ b/src/core/engines/detect.ts
@@ -11,6 +11,7 @@ import { codexEnv, userCodexProvider } from './codex'
import { opencodeMajor } from './opencode-v2'
import { geminiModels } from './gemini'
import { cursorSignedIn, parseCursorModels } from './cursor'
+import { grokLogin, parseGrokModels } from './grok'
function run(bin: string, args: string[], timeout = 15_000, env: NodeJS.ProcessEnv = process.env): Promise<{ code: number; stdout: string; stderr: string }> {
return new Promise((resolve) => {
@@ -247,6 +248,35 @@ export async function detectGemini(): Promise<{ status: EngineStatus; models: st
}
}
+// Grok's CLI. `grok models` says whether the grok.com login is in place and
+// lists the models that login can run. An API key, with no subscription login,
+// still counts as signed in, and the screen warns that it bills per token.
+export async function detectGrok(): Promise<{ status: EngineStatus; models: string[] }> {
+ const path = await which('grok')
+ if (!path) return { status: { installed: false, loggedIn: false }, models: [] }
+ const [v, list] = await Promise.all([run(path, ['--version']), run(path, ['models'], 30_000, { ...process.env, NO_COLOR: '1' })])
+ const text = `${list.stdout}\n${list.stderr}`
+ const login = grokLogin(text)
+ const models = login.loggedIn ? parseGrokModels(list.stdout) : []
+ const viaKey = login.loggedIn && !login.plan
+ return {
+ status: {
+ installed: true,
+ path,
+ version: version(v.stdout),
+ loggedIn: login.loggedIn && models.length > 0,
+ ...(login.loggedIn && models.length ? { route: login.plan ? ('plan' as const) : ('apikey' as const) } : {}),
+ account: models.length
+ ? login.plan
+ ? `Grok · ${models.length} ${L('modelos', 'models')}`
+ : L('Chave de API', 'API key')
+ : L('Sem login: entre com grok login', 'Not signed in: sign in with grok login'),
+ ...(viaKey ? { warning: apiKeyWarning() } : {})
+ },
+ models
+ }
+}
+
// Cursor's agent CLI, by its unique name (it also installs a plain `agent`).
// `status` says whether it's signed in; `models` lists what the account can run.
export async function detectCursor(): Promise<{ status: EngineStatus; models: string[] }> {
@@ -272,12 +302,12 @@ export async function detectEngines(codexHome: string): Promise<{ engines: Recor
process.env['PATH'] = withInstallDirs(process.env['PATH'] ?? '')
// Codex's catalog is read alongside (it can take a couple of seconds), used once the login is known.
const catalog = which('codex').then((p) => (p ? codexModels(p, codexHome) : []))
- const [claude, codex, opencode, pi, gemini, cursor] = await Promise.all([detectClaude(), detectCodex(codexHome), detectOpenCode(), detectPi(), detectGemini(), detectCursor()])
+ const [claude, codex, opencode, pi, gemini, cursor, grok] = await Promise.all([detectClaude(), detectCodex(codexHome), detectOpenCode(), detectPi(), detectGemini(), detectCursor(), detectGrok()])
// A gateway serves its own list (asked when picking); a plan or an API key gets Codex's catalog.
const codexCatalog = codex.loggedIn && codex.route !== 'gateway' ? await catalog : []
return {
- engines: { claude, codex, opencode: opencode.status, pi: pi.status, gemini: gemini.status, cursor: cursor.status },
- listed: { opencode: opencode.models, pi: pi.models, gemini: gemini.models, cursor: cursor.models, ...(codexCatalog.length ? { codex: codexCatalog.map((m) => m.slug) } : {}) },
+ engines: { claude, codex, opencode: opencode.status, pi: pi.status, gemini: gemini.status, cursor: cursor.status, grok: grok.status },
+ listed: { opencode: opencode.models, pi: pi.models, gemini: gemini.models, cursor: cursor.models, grok: grok.models, ...(codexCatalog.length ? { codex: codexCatalog.map((m) => m.slug) } : {}) },
codexCatalog
}
}
diff --git a/src/core/engines/grok.ts b/src/core/engines/grok.ts
new file mode 100644
index 0000000..66da4b9
--- /dev/null
+++ b/src/core/engines/grok.ts
@@ -0,0 +1,329 @@
+import { randomBytes } from 'node:crypto'
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { homedir, tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { GATEWAY_NAME } from './claude'
+import { lastLines, num, parseJson, runCli, type Parser } from './cli'
+import type { Engine, EngineEvent, Turn, TurnImage, Usage } from './types'
+import { L } from '../../shared/lang'
+
+// Grok Build, the `grok` CLI, on the grok.com subscription (~/.grok/auth.json),
+// not an xAI API key. Headless (`--prompt-file --output-format streaming-json`)
+// prints one JSON event per line and exits. Each turn gets a home of its own in
+// the temp folder, as GROK_HOME and HOME: Grok walks upward from the working
+// directory to a git checkout and would otherwise load that project's rules,
+// and from HOME it loads the plugins, skills and hooks installed for Claude
+// Code (~/.claude), whatever the compat switches say. The login stays the
+// person's, named with GROK_AUTH_PATH, and is never copied. An API key in the
+// environment is dropped when that login exists: Grok would bill the key
+// instead of the subscription.
+
+// streaming-json (grok 1.0.70): text {data}; thought (skipped); tool_call and
+// tool_call_update {toolCallId, toolName, status, rawInput, rawOutput}; usage
+// {usage}, one per model call; end {stopReason, usage, total_cost_usd}, the
+// whole turn; error {message}. `input_tokens` on these events leaves the cache
+// out. A web search says its query only when it completes, in rawOutput.
+
+const charsToTokens = (chars: number): number => Math.ceil(chars / 4)
+
+// Built-in tools a turn takes away. search_tool and use_tool stay: they are how
+// Grok finds and calls the gateway. Web search and fetch stay only with the web.
+const GROK_REMOVED = [
+ 'read_file', 'hashline_read', 'search_replace', 'hashline_edit', 'write', 'StrReplace', 'Delete',
+ 'run_terminal_command', 'run_terminal_cmd', 'list_dir', 'grep', 'hashline_grep', 'Glob',
+ 'kill_command_or_subagent', 'kill_task', 'todo_write', 'TodoWrite',
+ 'get_command_or_subagent_output', 'get_task_output', 'wait_tasks',
+ 'spawn_subagent', 'task', 'Agent', 'workflow', 'monitor', 'lsp',
+ 'scheduler_create', 'scheduler_delete', 'scheduler_list',
+ 'enter_plan_mode', 'exit_plan_mode', 'ask_user_question', 'send_feedback',
+ 'image_gen', 'image_edit', 'image_to_video', 'reference_to_video', 'GenerateImage', 'GenerateVideo',
+ 'web_search', 'web_fetch', 'WebSearch', 'WebFetch', 'XSearch'
+]
+
+const WEB_TOOLS = ['web_search', 'web_fetch']
+
+export function grokParser(sent = 0): Parser {
+ let text = ''
+ let finished = false
+ const pending = new Map<string, { action: 'search' | 'fetch'; detail: string }>()
+ const reported = new Set<string>()
+ // The turn so far: each usage event is one model call.
+ let tokens = 0
+ let cacheRead = 0
+
+ const usageOf = (raw: unknown, costFrom?: unknown): Usage | undefined => {
+ if (!raw || typeof raw !== 'object') return undefined
+ const u = raw as Record<string, unknown>
+ const told = 'input_tokens' in u || 'output_tokens' in u || 'inputTokens' in u || 'outputTokens' in u
+ if (!told) return undefined
+ const cacheRead = num(u['cache_read_input_tokens'] ?? u['cacheReadInputTokens'])
+ const cacheWrite = num(u['cache_creation_input_tokens'] ?? u['cacheCreationInputTokens'])
+ const cost = typeof costFrom === 'number' ? costFrom : u['total_cost_usd']
+ return {
+ inputTokens: num(u['input_tokens'] ?? u['inputTokens']) + cacheRead + cacheWrite,
+ cacheReadTokens: cacheRead,
+ outputTokens: num(u['output_tokens'] ?? u['outputTokens']),
+ ...(typeof cost === 'number' ? { apiCostUsd: cost } : {})
+ }
+ }
+
+ return {
+ line(line) {
+ const ev = parseJson(line)
+ if (!ev || finished) return []
+ const out: EngineEvent[] = []
+ const type = ev['type']
+ if (type === 'text' && typeof ev['data'] === 'string' && ev['data']) {
+ text += ev['data']
+ out.push({ type: 'text', delta: ev['data'] })
+ } else if (type === 'tool_call' || type === 'tool_call_update') {
+ const id = typeof ev['toolCallId'] === 'string' ? ev['toolCallId'] : ''
+ const found = webCall(ev)
+ if (id && found) pending.set(id, found)
+ const item = (id && pending.get(id)) || found
+ if (item && !item.detail) item.detail = searchQuery(ev)
+ if (item && ev['status'] === 'completed' && !reported.has(id || item.detail)) {
+ reported.add(id || item.detail)
+ out.push({ type: 'web', action: item.action, detail: item.detail })
+ }
+ } else if (type === 'usage') {
+ const u = usageOf(ev['usage'])
+ if (u) {
+ tokens += u.inputTokens + u.outputTokens
+ cacheRead += u.cacheReadTokens
+ out.push({ type: 'progress', tokens, cacheRead })
+ }
+ } else if (type === 'error') {
+ finished = true
+ out.push({ type: 'error', message: typeof ev['message'] === 'string' && ev['message'] ? ev['message'] : L('O Grok terminou com erro.', 'Grok ended with an error.') })
+ } else if (type === 'end') {
+ finished = true
+ const stop = String(ev['stopReason'] ?? '')
+ if ((stop === 'refusal' || stop === 'cancelled') && !text) {
+ out.push({ type: 'error', message: L(`O Grok parou (${stop}).`, `Grok stopped (${stop}).`) })
+ return out
+ }
+ if (typeof ev['text'] === 'string' && ev['text'] && !text) text = ev['text']
+ const u = usageOf(ev['usage'], ev['total_cost_usd']) ?? { inputTokens: charsToTokens(sent), cacheReadTokens: 0, outputTokens: charsToTokens(text.length) }
+ out.push({ type: 'progress', tokens: u.inputTokens + u.outputTokens, cacheRead: u.cacheReadTokens })
+ out.push({ type: 'done', text, usage: u })
+ }
+ return out
+ },
+ end(code, stderr) {
+ if (finished) return []
+ const detail = lastLines(stderr)
+ return [{ type: 'error', message: L(`O Grok saiu sem resposta (código ${code ?? '?'}).`, `Grok exited without a reply (code ${code ?? '?'}).`) + (detail ? `\n${detail}` : '') }]
+ }
+ }
+}
+
+// A web search or page read the CLI did itself. Refused calls never reach status completed.
+function webCall(ev: Record<string, unknown>): { action: 'search' | 'fetch'; detail: string } | undefined {
+ const name = String(ev['toolName'] ?? ev['title'] ?? '')
+ const args = (ev['rawInput'] ?? {}) as Record<string, unknown>
+ if (/web.?search|^xsearch$/i.test(name)) return { action: 'search', detail: String(args['query'] ?? args['search_term'] ?? args['q'] ?? '') }
+ if (/web.?fetch/i.test(name)) return { action: 'fetch', detail: String(args['url'] ?? '') }
+ return undefined
+}
+
+function searchQuery(ev: Record<string, unknown>): string {
+ const out = ev['rawOutput'] as { action?: { query?: unknown } } | null | undefined
+ return typeof out?.action?.query === 'string' ? out.action.query : ''
+}
+
+// Grok reaches MCP tools through search_tool and use_tool, by their full name; a
+// bare name fails and costs the agent a try.
+const gatewayNote = (): string =>
+ L(
+ `As ferramentas do Tucano estão no servidor MCP \`${GATEWAY_NAME}\`. Chame com use_tool pelo nome completo, \`${GATEWAY_NAME}__<nome>\` (por exemplo \`${GATEWAY_NAME}__lembrar\`); search_tool lista as que existem.`,
+ `Tucano's tools are on the \`${GATEWAY_NAME}\` MCP server. Call them with use_tool by their full name, \`${GATEWAY_NAME}__<name>\` (for example \`${GATEWAY_NAME}__lembrar\`); search_tool lists the ones there are.`
+ )
+
+// Headless, one shot. The prompt is a file: Grok does not read the prompt from
+// stdin, and a .json file is ACP content blocks, which is how images go along.
+// No -p beside --prompt-file (the two are alternatives, and -p wins).
+// bypassPermissions so the gateway's tools don't wait on a prompt a headless
+// run can't answer; deny rules still block Grok's own shell and files, and
+// --disallowed-tools takes those tools off the list. The leader socket is the
+// turn's, so this run doesn't attach to the person's grok and stop it on exit.
+export function grokArgs(turn: Pick<Turn, 'model' | 'effort' | 'system' | 'web' | 'mcpUrl'>, promptFile: string, socket: string): string[] {
+ const model = turn.model.includes(':') ? turn.model.slice(turn.model.indexOf(':') + 1) : turn.model.includes('/') ? turn.model.slice(turn.model.indexOf('/') + 1) : turn.model
+ const web = !!turn.web
+ // With the web, Grok's own search and page reading stay; X search does not.
+ const webTool = (name: string): boolean => WEB_TOOLS.includes(name) || name === 'WebSearch' || name === 'WebFetch'
+ const removed = GROK_REMOVED.filter((name) => !web || !webTool(name))
+ return [
+ '--no-auto-update',
+ '--no-wait-for-background',
+ '--output-format', 'streaming-json',
+ '--model', model,
+ '--reasoning-effort', turn.effort,
+ '--system-prompt-override', turn.mcpUrl ? `${turn.system}\n\n${gatewayNote()}` : turn.system,
+ '--permission-mode', 'bypassPermissions',
+ '--no-subagents',
+ '--no-plan',
+ ...(web ? [] : ['--disable-web-search']),
+ '--tools', ['search_tool', 'use_tool', ...(web ? WEB_TOOLS : [])].join(','),
+ '--disallowed-tools', removed.join(','),
+ '--deny', 'Bash',
+ '--deny', 'Read',
+ '--deny', 'Write',
+ '--deny', 'Edit',
+ '--deny', 'Grep',
+ ...(web ? [] : ['--deny', 'WebFetch']),
+ '--leader-socket', socket,
+ '--prompt-file', promptFile
+ ]
+}
+
+// The prompt file's contents. Images are ACP blocks after the text; without
+// them the file is plain text (a .json file would be parsed as blocks).
+export function grokPrompt(turn: Pick<Turn, 'prompt' | 'images'>): { name: string; body: string } {
+ const images = (turn.images ?? []).filter((img) => existsSync(img.path))
+ if (!images.length) return { name: 'prompt.txt', body: turn.prompt }
+ const blocks: Record<string, unknown>[] = []
+ if (turn.prompt.trim()) blocks.push({ type: 'text', text: turn.prompt })
+ for (const img of images) blocks.push(imageBlock(img))
+ return { name: 'prompt.json', body: JSON.stringify(blocks) }
+}
+
+function imageBlock(img: TurnImage): Record<string, unknown> {
+ return { type: 'image', mimeType: img.mime, data: readFileSync(img.path).toString('base64') }
+}
+
+const tomlString = (s: string): string => `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
+
+// The turn's config: the gateway is the only MCP server, and the scans that
+// would pull in the person's Claude, Cursor and Codex setup stay off. Env vars
+// say the same thing and outrank this file (see grokTurnEnv).
+export function grokConfig(turn: Pick<Turn, 'mcpUrl'>): string {
+ const mcp = turn.mcpUrl
+ ? `[mcp_servers.${GATEWAY_NAME}]\nurl = ${tomlString(turn.mcpUrl)}\nenabled = true\n\n`
+ : ''
+ return (
+ mcp +
+ ['[memory]', 'enabled = false', '', '[memory_v2]', 'enabled = false', '', '[workflows]', 'enabled = false', '', '[compat.claude]', 'agents = false', 'hooks = false', 'mcps = false', 'rules = false', 'skills = false', '', '[compat.cursor]', 'agents = false', 'hooks = false', 'mcps = false', 'rules = false', 'skills = false', '', '[compat.codex]', 'hooks = false', 'skills = false', ''].join('\n')
+ )
+}
+
+// Where the person signed in. Their GROK_HOME, or ~/.grok. Read before a turn
+// replaces GROK_HOME with its own.
+export function userGrokHome(env: NodeJS.ProcessEnv = process.env, home = homedir()): string {
+ const set = env['GROK_HOME']?.trim()
+ return set || join(home, '.grok')
+}
+
+const OFF = {
+ GROK_MEMORY: '0',
+ GROK_WORKFLOWS: '0',
+ GROK_DISABLE_AUTOUPDATER: '1',
+ GROK_MANAGED_MCPS_ENABLED: 'false',
+ GROK_MANAGED_MCP_GATEWAY_TOOLS_ENABLED: 'false',
+ GROK_CLAUDE_AGENTS_ENABLED: 'false',
+ GROK_CLAUDE_HOOKS_ENABLED: 'false',
+ GROK_CLAUDE_MCPS_ENABLED: 'false',
+ GROK_CLAUDE_RULES_ENABLED: 'false',
+ GROK_CLAUDE_SKILLS_ENABLED: 'false',
+ GROK_CURSOR_AGENTS_ENABLED: 'false',
+ GROK_CURSOR_HOOKS_ENABLED: 'false',
+ GROK_CURSOR_MCPS_ENABLED: 'false',
+ GROK_CURSOR_RULES_ENABLED: 'false',
+ GROK_CURSOR_SKILLS_ENABLED: 'false'
+} as const
+
+// authFile set: the subscription login, and the API key is removed so it can't
+// replace that login. Unset: an API key in the environment is the only way in.
+// HOME is the turn's too, so nothing installed for Claude Code loads.
+export function grokTurnEnv(base: NodeJS.ProcessEnv, home: string, authFile?: string, os: NodeJS.Platform = process.platform): NodeJS.ProcessEnv {
+ const env: NodeJS.ProcessEnv = { ...base, ...OFF, GROK_HOME: home, HOME: home, ...(os === 'win32' ? { USERPROFILE: home } : {}) }
+ delete env['GROK_CONFIG']
+ delete env['GROK_CONFIG_PATH']
+ delete env['GROK_AGENT']
+ if (authFile) {
+ env['GROK_AUTH_PATH'] = authFile
+ delete env['XAI_API_KEY']
+ delete env['GROK_CODE_XAI_API_KEY']
+ }
+ return env
+}
+
+export interface GrokTurnDirs {
+ root: string
+ work: string
+ socket: string
+}
+
+// A folder for one turn, outside any checkout. The socket path has to stay
+// short enough for a Unix socket; a long temp path gets a socket beside it.
+export function grokTurnDirs(): GrokTurnDirs {
+ const root = join(tmpdir(), `tucano-grok-${randomBytes(8).toString('hex')}`)
+ const work = join(root, 'work')
+ mkdirSync(work, { recursive: true })
+ const inside = join(root, 'leader.sock')
+ const socket = inside.length <= 100 ? inside : join(tmpdir(), `tg-${randomBytes(4).toString('hex')}.sock`)
+ return { root, work, socket }
+}
+
+export function grokCleanup(dirs: GrokTurnDirs): void {
+ for (const p of [dirs.root, dirs.socket])
+ try {
+ if (existsSync(p)) rmSync(p, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })
+ } catch {
+ // a rare leftover is a small dead folder; harmless
+ }
+}
+
+// `grok models` prints "You are logged in with grok.com.", "You are using
+// XAI_API_KEY." or "You are not authenticated.", then a line per model,
+// "* grok-4.7 (default)" or "- grok-4.6", listed even when signed out.
+export function parseGrokModels(out: string): string[] {
+ const ids: string[] = []
+ for (const line of out.split('\n')) {
+ const id = /^\s*[*+-]\s+([A-Za-z0-9][\w.-]*)/.exec(line)?.[1]
+ if (id && !ids.includes(id)) ids.push(id)
+ }
+ return ids
+}
+
+export function grokLogin(out: string): { loggedIn: boolean; plan: boolean } {
+ if (/not signed in|not logged in|not authenticated/i.test(out)) return { loggedIn: false, plan: false }
+ const plan = /logged in with grok\.com/i.test(out)
+ const models = parseGrokModels(out)
+ return { loggedIn: plan || (models.length > 0 && /logged in|api[ _]key/i.test(out)), plan }
+}
+
+export function grokEngine(bin: () => string | undefined, shellEnv: () => Promise<NodeJS.ProcessEnv> = async () => ({})): Engine {
+ return {
+ id: 'grok',
+ async *run(turn) {
+ const path = bin()
+ if (!path) {
+ yield { type: 'error', message: L('O Grok não está instalado. Veja em Configurações.', "Grok isn't installed. See Settings.") }
+ return
+ }
+ const dirs = grokTurnDirs()
+ const prompt = grokPrompt(turn)
+ writeFileSync(join(dirs.root, prompt.name), prompt.body)
+ writeFileSync(join(dirs.root, 'config.toml'), grokConfig(turn))
+ // The shell may hold an API key the app, opened from Finder, doesn't.
+ const shell = await shellEnv()
+ const auth = join(userGrokHome({ ...process.env, ...shell }), 'auth.json')
+ const env = grokTurnEnv({ ...process.env, ...shell }, dirs.root, existsSync(auth) ? auth : undefined)
+ try {
+ const sent = turn.system.length + turn.prompt.length
+ yield* runCli({
+ bin: path,
+ args: grokArgs(turn, join(dirs.root, prompt.name), dirs.socket),
+ stdin: '',
+ cwd: dirs.work,
+ signal: turn.signal,
+ parser: grokParser(sent),
+ env
+ })
+ } finally {
+ grokCleanup(dirs)
+ }
+ }
+ }
+}
diff --git a/src/core/harness.ts b/src/core/harness.ts
index 127a4c5..37d4da0 100644
--- a/src/core/harness.ts
+++ b/src/core/harness.ts
@@ -1,4 +1,4 @@
-// The harnesses agents run on (Claude Code, Codex, OpenCode, Pi). Each one is
+// The harnesses agents run on. Each one is
// used as the person set it up: their plan, their company's gateway or their
// providers. The app only reads that setup, to show it and to list models.
import type { Provider } from './engines/claude'
@@ -7,7 +7,7 @@ import { L } from '../shared/lang'
import type { EngineId, EngineStatus } from '../shared/types'
// The harnesses the app can run agents on; one added later is listed as coming until then.
-export const RUNNABLE: EngineId[] = ['claude', 'codex', 'opencode', 'pi', 'gemini', 'cursor']
+export const RUNNABLE: EngineId[] = ['claude', 'codex', 'opencode', 'pi', 'gemini', 'cursor', 'grok']
// Off for a harness pointed at a gateway: its own telemetry and error reports
// would go to Anthropic or OpenAI, around the gateway.
diff --git a/src/core/index.ts b/src/core/index.ts
index eb08b06..a440010 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -24,6 +24,7 @@ import { opencodeEngine } from './engines/opencode'
import { piEngine } from './engines/pi'
import { geminiAppDir, geminiEngine } from './engines/gemini'
import { cursorAppDir, cursorEngine } from './engines/cursor'
+import { grokEngine } from './engines/grok'
import { accountDir, accountStatus, adoptLoginShellPath, detectEngines, type CodexModel } from './engines/detect'
import { fakeEngine } from './engines/fake'
import { DesktopApps, macApps, SELF } from './apps'
@@ -95,7 +96,7 @@ const DEFAULTS: Omit<Settings, 'engines'> = {
}
const unknownEngine: EngineStatus = { installed: false, loggedIn: false }
-let engines: Record<EngineId, EngineStatus> = { claude: unknownEngine, codex: unknownEngine, opencode: unknownEngine, pi: unknownEngine, gemini: unknownEngine, cursor: unknownEngine }
+let engines: Record<EngineId, EngineStatus> = { claude: unknownEngine, codex: unknownEngine, opencode: unknownEngine, pi: unknownEngine, gemini: unknownEngine, cursor: unknownEngine, grok: unknownEngine }
// The models OpenCode and Pi list (what the person has logins for), from the last check.
let listed: Partial<Record<EngineId, string[]>> = {}
// Codex's own catalog for this login (names and what each model is for), from the last check.
@@ -104,7 +105,7 @@ let codexCatalog: CodexModel[] = []
const fakeStatus = (v: string): EngineStatus => ({ installed: true, loggedIn: true, path: 'fake', version: v, account: L('Motor de teste', 'Test engine'), route: 'plan' })
async function detect(): Promise<void> {
if (fake) {
- engines = { claude: fakeStatus('0.0.0'), codex: fakeStatus('0.0.0'), opencode: { ...fakeStatus('0.0.0'), route: 'providers', account: 'OpenAI, OpenCode · 3 modelos' }, pi: { installed: false, loggedIn: false }, gemini: { installed: false, loggedIn: false }, cursor: { installed: false, loggedIn: false } }
+ engines = { claude: fakeStatus('0.0.0'), codex: fakeStatus('0.0.0'), opencode: { ...fakeStatus('0.0.0'), route: 'providers', account: 'OpenAI, OpenCode · 3 modelos' }, pi: { installed: false, loggedIn: false }, gemini: { installed: false, loggedIn: false }, cursor: { installed: false, loggedIn: false }, grok: { installed: false, loggedIn: false } }
listed = { opencode: ['openai/gpt-5.5', 'opencode/big-pickle', 'opencode-go/qwen3.8-max'] }
} else ({ engines, listed, codexCatalog } = await detectEngines(codexHome))
await checkAccounts()
@@ -181,14 +182,15 @@ function watchAccount(id: string): void {
const githubInfo = (): Settings['github'] => githubRef?.info()
const engineImpls: Record<EngineId, Engine> = fake
- ? { claude: fakeEngine('claude'), codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ ? { claude: fakeEngine('claude'), codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
: {
claude: claudeEngine(() => engines.claude.path, async () => quietClaude(userProvider())),
codex: codexEngine(() => engines.codex.path, codexHome, loginEnv, async () => quietCodex(userCodexProvider())),
opencode: opencodeEngine(() => engines.opencode.path, join(dataDir, 'opencode-home'), loginEnv, () => engines.opencode.version),
pi: piEngine(() => engines.pi.path, join(dataDir, 'pi'), loginEnv),
gemini: geminiEngine(() => engines.gemini.path, geminiAppDir(dataDir), loginEnv),
- cursor: cursorEngine(() => engines.cursor.path, cursorAppDir(dataDir), loginEnv)
+ cursor: cursorEngine(() => engines.cursor.path, cursorAppDir(dataDir), loginEnv),
+ grok: grokEngine(() => engines.grok.path, loginEnv)
}
// A command in the login shell, where SSO tools live; what it prints, trimmed.
diff --git a/src/core/platform.ts b/src/core/platform.ts
index fad45d4..c7f5f77 100644
--- a/src/core/platform.ts
+++ b/src/core/platform.ts
@@ -128,7 +128,8 @@ export const pathDirs = (): string[] => (process.env['PATH'] ?? process.env['Pat
// on). Each one that exists and isn't on the PATH yet is appended to it.
export function withInstallDirs(path: string, os: Os = osOf(), home = homedir(), env: NodeJS.ProcessEnv = process.env, exists: (p: string) => boolean = existsSync): string {
// Windows: npm's global folder, and Cursor's installer (%LOCALAPPDATA%\cursor-agent).
- const dirs = [join(home, '.local', 'bin'), ...(os === 'windows' ? [env['APPDATA'] && join(env['APPDATA'], 'npm'), env['LOCALAPPDATA'] && join(env['LOCALAPPDATA'], 'cursor-agent')] : [])].filter((d): d is string => !!d)
+ // Grok's installer puts `grok` in ~/.grok/bin and may not add it to PATH.
+ const dirs = [join(home, '.local', 'bin'), join(home, '.grok', 'bin'), ...(os === 'windows' ? [env['APPDATA'] && join(env['APPDATA'], 'npm'), env['LOCALAPPDATA'] && join(env['LOCALAPPDATA'], 'cursor-agent')] : [])].filter((d): d is string => !!d)
const have = path.split(delimiter).filter(Boolean)
const same = (a: string, b: string): boolean => (os === 'windows' ? a.replace(/[\\/]+$/, '').toLowerCase() === b.replace(/[\\/]+$/, '').toLowerCase() : a.replace(/\/+$/, '') === b.replace(/\/+$/, ''))
const missing = dirs.filter((d) => exists(d) && !have.some((h) => same(h, d)))
diff --git a/src/core/tuca.ts b/src/core/tuca.ts
index c28c460..2640db9 100644
--- a/src/core/tuca.ts
+++ b/src/core/tuca.ts
@@ -88,7 +88,7 @@ export function availableModels(s: Pick<Settings, 'engines'>, listed: Partial<Re
const plan = [...MODELS.filter((m) => m.engine !== 'codex' || !codex), ...(codex ?? []).map((m) => ({ ...m, id: codexValue(m.id) }))]
.filter((m) => s.engines[m.engine].loggedIn && s.engines[m.engine].route !== 'gateway')
.map((m) => ({ id: m.id, label: `${ENGINES[m.engine].label} · ${m.label}` }))
- const own = (['opencode', 'pi', 'gemini', 'cursor'] as const).flatMap((e) => (s.engines[e]?.loggedIn ? (listed[e] ?? []).slice(0, 12).map((name) => ({ id: `${e}:${name}`, label: `${ENGINES[e].label} · ${name}` })) : []))
+ const own = (['opencode', 'pi', 'gemini', 'cursor', 'grok'] as const).flatMap((e) => (s.engines[e]?.loggedIn ? (listed[e] ?? []).slice(0, 12).map((name) => ({ id: `${e}:${name}`, label: `${ENGINES[e].label} · ${name}` })) : []))
return [...plan, ...own]
}
diff --git a/src/renderer/src/store.ts b/src/renderer/src/store.ts
index b1b0ebf..ce0d74f 100644
--- a/src/renderer/src/store.ts
+++ b/src/renderer/src/store.ts
@@ -133,7 +133,7 @@ let state: State = {
settings: {
workspaceName: '',
context: '',
- engines: { claude: { installed: false, loggedIn: false }, codex: { installed: false, loggedIn: false }, opencode: { installed: false, loggedIn: false }, pi: { installed: false, loggedIn: false }, gemini: { installed: false, loggedIn: false }, cursor: { installed: false, loggedIn: false } },
+ engines: { claude: { installed: false, loggedIn: false }, codex: { installed: false, loggedIn: false }, opencode: { installed: false, loggedIn: false }, pi: { installed: false, loggedIn: false }, gemini: { installed: false, loggedIn: false }, cursor: { installed: false, loggedIn: false }, grok: { installed: false, loggedIn: false } },
routerModel: 'haiku',
memoryModel: 'haiku',
memoryLearning: 'approve',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 5ef4d0e..b317fe4 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -6,7 +6,7 @@ import { L, lang, type Lang } from './lang'
export type AgentColor = 'sky' | 'indigo' | 'violet' | 'rose' | 'amber' | 'green' | 'teal' | 'graphite'
export type GrantLevel = 'none' | 'read' | 'read_write'
export type ToolClass = 'read' | 'write' | 'sensitive'
-export type EngineId = 'claude' | 'codex' | 'opencode' | 'pi' | 'gemini' | 'cursor'
+export type EngineId = 'claude' | 'codex' | 'opencode' | 'pi' | 'gemini' | 'cursor' | 'grok'
export type Effort = 'low' | 'medium' | 'high' | 'xhigh'
export type MemoryMode = 'auto' | 'approve' | 'read' // how an agent's `lembrar` calls land
@@ -390,7 +390,8 @@ export const ENGINES: Record<EngineId, { label: string; cli: string; login: stri
opencode: { label: 'OpenCode', cli: 'opencode', login: 'opencode auth login', install: 'curl -fsSL https://opencode.ai/install | bash', windows: 'npm install -g opencode-ai', site: 'https://opencode.ai' },
pi: { label: 'Pi', cli: 'pi', login: 'pi', install: 'npm install -g @earendil-works/pi-coding-agent', site: 'https://pi.dev' },
gemini: { label: 'Gemini CLI', cli: 'gemini', login: 'gemini', install: 'npm install -g @google/gemini-cli', site: 'https://github.com/google-gemini/gemini-cli' },
- cursor: { label: 'Cursor CLI', cli: 'cursor-agent', login: 'cursor-agent login', install: 'curl https://cursor.com/install -fsS | bash', windows: "irm 'https://cursor.com/install?win32=true' | iex", site: 'https://cursor.com/cli' }
+ cursor: { label: 'Cursor CLI', cli: 'cursor-agent', login: 'cursor-agent login', install: 'curl https://cursor.com/install -fsS | bash', windows: "irm 'https://cursor.com/install?win32=true' | iex", site: 'https://cursor.com/cli' },
+ grok: { label: 'Grok', cli: 'grok', login: 'grok login', install: 'curl -fsSL https://x.ai/cli/install.sh | bash', site: 'https://x.ai/cli' }
}
export const ENGINE_IDS = Object.keys(ENGINES) as EngineId[]
diff --git a/test/accounts.test.ts b/test/accounts.test.ts
index 4f5512b..72886cb 100644
--- a/test/accounts.test.ts
+++ b/test/accounts.test.ts
@@ -25,7 +25,7 @@ const work: Account = { id: 'w1', engine: 'claude', name: 'Trabalho', loggedIn:
function runner(): Runner {
claude = counted(fakeEngine('claude', { delayMs: 1 }))
- const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
return new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-work-')), dataDir: data })
}
const reply = (): Message => db.messages().find((m) => m.author.kind === 'agent')!
@@ -33,7 +33,7 @@ const reply = (): Message => db.messages().find((m) => m.author.kind === 'agent'
beforeEach(() => {
data = mkdtempSync(join(tmpdir(), 'ad-data-'))
db = new Db(join(data, 'test.db'))
- settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt', accounts: [work] }
+ settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt', accounts: [work] }
db.saveAgent(agent({ accountId: 'w1' }))
db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })
})
diff --git a/test/browser.test.ts b/test/browser.test.ts
index e0e0c56..258e909 100644
--- a/test/browser.test.ts
+++ b/test/browser.test.ts
@@ -245,7 +245,7 @@ describe('the runner with a browser', () => {
const fake = fakeHost()
const browser = new Browser({ host: fake.host, db, dataDir, emit: () => {}, me: () => 'Edu' })
const ready = { installed: true, loggedIn: true }
- const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
const gateway = new Gateway()
await gateway.start()
const results: unknown[] = []
@@ -259,7 +259,7 @@ describe('the runner with a browser', () => {
yield { type: 'done', text: 'ok', usage: { inputTokens: 1000, cacheReadTokens: 0, outputTokens: 10 } }
}
}
- const r = new Runner({ db, engines: { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'w-')), gateway, browser })
+ const r = new Runner({ db, engines: { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'w-')), gateway, browser })
await r.send('c1', '@theo abre o studio')
await r.idle()
@@ -292,7 +292,7 @@ describe('the runner with a browser', () => {
db.createConversation({ id: 'c1', kind: 'channel', name: 'conteudo', members: ['lia-0001'] })
const browser = new Browser({ host: fakeHost().host, db, dataDir, emit: () => {}, me: () => 'Edu' })
const ready = { installed: true, loggedIn: true }
- const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
const gateway = new Gateway()
await gateway.start()
const claude: Engine = {
@@ -310,7 +310,7 @@ describe('the runner with a browser', () => {
yield { type: 'done', text: 'O CTR foi 1,6%.', usage: { inputTokens: 1000, cacheReadTokens: 0, outputTokens: 10 } }
}
}
- const r = new Runner({ db, engines: { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'w-')), gateway, browser })
+ const r = new Runner({ db, engines: { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'w-')), gateway, browser })
const reply = async (text: string) => {
await r.send('c1', text)
await r.idle()
diff --git a/test/codex-models.test.ts b/test/codex-models.test.ts
index a1f4112..8207248 100644
--- a/test/codex-models.test.ts
+++ b/test/codex-models.test.ts
@@ -69,4 +69,13 @@ describe("Tuca's list of models", () => {
{ id: 'cursor:claude-opus-5-5-high', label: 'Cursor CLI · claude-opus-5-5-high' }
])
})
+
+ it('includes the Grok models when the Grok CLI is signed in', () => {
+ const off = { installed: false, loggedIn: false }
+ const s = { engines: { claude: off, codex: off, opencode: off, pi: off, gemini: off, cursor: off, grok: { installed: true, loggedIn: true, route: 'plan' } } } as unknown as Pick<Settings, 'engines'>
+ expect(availableModels(s, { grok: ['grok-4.7', 'grok-4.5'] })).toEqual([
+ { id: 'grok:grok-4.7', label: 'Grok · grok-4.7' },
+ { id: 'grok:grok-4.5', label: 'Grok · grok-4.5' }
+ ])
+ })
})
diff --git a/test/computer-down.test.ts b/test/computer-down.test.ts
index 2524395..781a2af 100644
--- a/test/computer-down.test.ts
+++ b/test/computer-down.test.ts
@@ -25,7 +25,7 @@ function runner(): Runner {
calls = []
const fake = fakeEngine('claude', { delayMs: 1 })
const claude: Engine = { id: 'claude', run: (t) => (turns.push(t), fake.run(t)) }
- const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
// Docker is off: every call fails the same way, and says so.
const computers = {
call: async (_a: Agent, name: string) => (calls.push(name), { result: textResult(`O Docker não está disponível neste computador: ${NO_DOCKER}`, true), down: NO_DOCKER }),
@@ -38,7 +38,7 @@ const reply = () => db.messages().filter((m) => m.author.kind === 'agent').at(-1
beforeEach(async () => {
db = new Db(join(mkdtempSync(join(tmpdir(), 'cd-db-')), 'test.db'))
- settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
db.saveAgent({ id: 'lia', name: 'Lia', handle: 'lia', role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1_000_000, used: 0, grants: {}, memory: 'auto', computer: true, archived: false })
db.createConversation({ id: 'dm', kind: 'dm', name: 'lia', members: ['lia'] })
off = undefined
@@ -80,7 +80,7 @@ describe('a computer whose Docker is off', () => {
if (!turn.signal.aborted) yield { type: 'done', text: 'Nenhum TODO, FIXME, XXX ou HACK no projeto.', usage: { inputTokens: 1, cacheReadTokens: 0, outputTokens: 1 } }
}
}
- const engines: Record<EngineId, Engine> = { claude: tries, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ const engines: Record<EngineId, Engine> = { claude: tries, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
const ran: string[] = []
const computers = {
call: async (_a: Agent, _n: string, args: Record<string, unknown>) => {
diff --git a/test/computer.test.ts b/test/computer.test.ts
index 464c61e..2cb2223 100644
--- a/test/computer.test.ts
+++ b/test/computer.test.ts
@@ -100,7 +100,7 @@ const hasDocker = ((): boolean => {
describe.skipIf(!hasDocker)('computer (Docker)', () => {
const ready = { installed: true, loggedIn: true }
- const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
const agent = (id: string, handle: string, computer: boolean): Agent => ({
id, name: handle, handle, role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1_000_000, used: 0, grants: {}, memory: 'read', computer, archived: false
})
@@ -201,7 +201,7 @@ describe.skipIf(!hasDocker)('computer (Docker)', () => {
it('only agents with a computer get the tools', async () => {
const gateway = new Gateway()
await gateway.start()
- const engines: Record<EngineId, Engine> = { claude: fakeEngine('claude', { delayMs: 1 }), codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ const engines: Record<EngineId, Engine> = { claude: fakeEngine('claude', { delayMs: 1 }), codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
const runner = new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-w-')), gateway, computers })
await runner.send('d1', 'rode `echo oi do computador`')
await runner.send('d2', 'rode `echo oi do computador`')
diff --git a/test/engines.test.ts b/test/engines.test.ts
index c02ecbf..c504e23 100644
--- a/test/engines.test.ts
+++ b/test/engines.test.ts
@@ -7,6 +7,7 @@ import { claudeArgs, claudeInput, claudeParser, userProvider } from '../src/core
import { CODEX_DISABLED_FEATURES, codexArgs, codexEnv, codexParser, userCodexProvider } from '../src/core/engines/codex'
import { detectGeminiCliModels, geminiArgs, geminiEnv, geminiHome, geminiModels, geminiParser } from '../src/core/engines/gemini'
import { cursorArgs, cursorCleanup, cursorConfig, cursorEngine, cursorHomeEnv, cursorParser, cursorSignedIn, cursorSlug, cursorWorkerSocket, cursorTurnDirs, imageRefused, parseCursorModels } from '../src/core/engines/cursor'
+import { grokArgs, grokCleanup, grokConfig, grokEngine, grokLogin, grokParser, grokPrompt, grokTurnDirs, grokTurnEnv, parseGrokModels, userGrokHome } from '../src/core/engines/grok'
import { customModel, modelInfo, usable } from '../src/shared/types'
import type { EngineEvent } from '../src/core/engines/types'
@@ -575,3 +576,248 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"images='"$
expect(done && done.type === 'done' && done.text).toBe('images=0 note=no')
})
})
+
+// The fixture is the streaming-json shape from grok 1.0.70's headless docs, not a recorded turn.
+describe('Grok stream', () => {
+ it('streams the text and skips thoughts', () => {
+ const events = feed(grokParser(), fixture('grok-stream.jsonl'))
+ expect(text(events)).toBe('Vou consultar. São 21:58.')
+ expect(events.find((e) => e.type === 'done')).toMatchObject({ type: 'done', text: 'Vou consultar. São 21:58.' })
+ })
+
+ it('counts cache reads and writes as sent, and does not add reasoning on top of output', () => {
+ const done = feed(grokParser(), fixture('grok-stream.jsonl')).find((e) => e.type === 'done')
+ expect(done).toMatchObject({ usage: { inputTokens: 100 + 50 + 10, cacheReadTokens: 50, outputTokens: 20, apiCostUsd: 0.0123 } })
+ })
+
+ it('reports a web search once, when it completes, and not the gateway tools', () => {
+ const web = feed(grokParser(), fixture('grok-stream.jsonl')).filter((e) => e.type === 'web')
+ expect(web).toEqual([{ type: 'web', action: 'search', detail: 'Node.js LTS' }])
+ })
+
+ // Recorded from grok 1.0.70: a web search, a page read, and a gateway tool found with search_tool and called with use_tool.
+ it('reads a recorded turn: its text, each web step once, a running total and the whole turn at the end', () => {
+ const events = feed(grokParser(), fixture('grok-stream-recorded.jsonl'))
+ const done = events.find((e) => e.type === 'done')
+ expect(done && done.type === 'done' && done.text).toContain('Node.js')
+ expect(done).toMatchObject({ usage: { inputTokens: 11445 + 16384, cacheReadTokens: 16384, outputTokens: 560, apiCostUsd: 0.039442 } })
+ expect(events.filter((e) => e.type === 'web')).toEqual([
+ { type: 'web', action: 'search', detail: 'Node.js current LTS version' },
+ { type: 'web', action: 'fetch', detail: 'https://nodejs.org/en' }
+ ])
+ const totals = events.flatMap((e) => (e.type === 'progress' ? [e.tokens] : []))
+ expect(totals.slice(0, 3)).toEqual([2767 + 1152 + 189, 2767 + 1152 + 189 + 7608 + 3840 + 113, 2767 + 1152 + 189 + 7608 + 3840 + 113 + 1070 + 11392 + 258])
+ expect(totals.at(-1)).toBe(11445 + 16384 + 560)
+ })
+
+ it('reports a finished page read, and not one still running', () => {
+ const running = '{"type":"tool_call","toolCallId":"f1","toolName":"web_fetch","status":"in_progress","rawInput":{"url":"https://nodejs.org"}}'
+ const done = '{"type":"tool_call_update","toolCallId":"f1","status":"completed"}'
+ expect(feed(grokParser(), [running]).filter((e) => e.type === 'web')).toEqual([])
+ expect(feed(grokParser(), [running, done]).filter((e) => e.type === 'web')).toEqual([{ type: 'web', action: 'fetch', detail: 'https://nodejs.org' }])
+ })
+
+ it('estimates the usage when the CLI gives none', () => {
+ const end = '{"type":"end","stopReason":"end_turn","text":"12345678"}'
+ const done = feed(grokParser(400), [end]).find((e) => e.type === 'done')
+ expect(done).toMatchObject({ text: '12345678', usage: { inputTokens: 100, cacheReadTokens: 0, outputTokens: 2 } })
+ })
+
+ it('turns an error line, a refusal and an exit without an end into errors', () => {
+ expect(feed(grokParser(), ['{"type":"error","message":"Not signed in"}'])).toEqual([{ type: 'error', message: 'Not signed in' }])
+ expect(feed(grokParser(), ['{"type":"end","stopReason":"refusal"}'])[0]).toMatchObject({ type: 'error' })
+ const gone = feed(grokParser(), ['{"type":"text","data":"oi"}'], 1, 'boom\nnot signed in')
+ expect(gone.some((e) => e.type === 'done')).toBe(false)
+ expect((gone.find((e) => e.type === 'error') as { message: string }).message).toContain('not signed in')
+ })
+})
+
+describe('Grok config', () => {
+ const base = { model: 'grok-4.7', effort: 'high' as const, system: 'You are Iris.' }
+
+ it('runs headless from a prompt file, with no -p, and names the model past a prefix', () => {
+ const args = grokArgs({ ...base, model: 'grok:grok-4.7' }, '/tmp/prompt.txt', '/tmp/leader.sock')
+ expect(args).toContain('--output-format')
+ expect(args[args.indexOf('--output-format') + 1]).toBe('streaming-json')
+ expect(args[args.indexOf('--model') + 1]).toBe('grok-4.7')
+ expect(args[args.indexOf('--reasoning-effort') + 1]).toBe('high')
+ expect(args[args.indexOf('--system-prompt-override') + 1]).toBe('You are Iris.')
+ expect(args[args.indexOf('--prompt-file') + 1]).toBe('/tmp/prompt.txt')
+ expect(args[args.indexOf('--leader-socket') + 1]).toBe('/tmp/leader.sock')
+ expect(args).not.toContain('-p')
+ const withGateway = grokArgs({ ...base, mcpUrl: 'http://127.0.0.1:1/mcp/x' }, 'p.txt', 's.sock')
+ expect(withGateway[withGateway.indexOf('--system-prompt-override') + 1]).toMatch(/^You are Iris\.\n\n.*tucano__lembrar/s)
+ expect(args).toContain('--no-subagents')
+ expect(args).toContain('--no-plan')
+ expect(args).toContain('--no-wait-for-background')
+ expect(args[args.indexOf('--permission-mode') + 1]).toBe('bypassPermissions')
+ })
+
+ it('keeps only the gateway tools, and the web only when the agent has it', () => {
+ const off = grokArgs({ ...base, web: false }, 'p.txt', 's.sock')
+ const on = grokArgs({ ...base, web: true }, 'p.txt', 's.sock')
+ const list = (args: string[], flag: string): string[] => (args[args.indexOf(flag) + 1] ?? '').split(',').filter(Boolean)
+ const deny = (args: string[]): string[] => args.flatMap((a, i) => (a === '--deny' ? [args[i + 1]!] : []))
+ expect(list(off, '--tools')).toEqual(['search_tool', 'use_tool'])
+ expect(list(on, '--tools')).toEqual(['search_tool', 'use_tool', 'web_search', 'web_fetch'])
+ expect(list(off, '--disallowed-tools')).toEqual(expect.arrayContaining(['run_terminal_command', 'web_search', 'WebFetch', 'XSearch']))
+ expect(list(on, '--disallowed-tools')).toEqual(expect.arrayContaining(['run_terminal_command', 'XSearch']))
+ for (const name of ['web_search', 'web_fetch', 'WebSearch', 'WebFetch']) expect(list(on, '--disallowed-tools')).not.toContain(name)
+ expect(off).toContain('--disable-web-search')
+ expect(on).not.toContain('--disable-web-search')
+ expect(deny(off)).toEqual(['Bash', 'Read', 'Write', 'Edit', 'Grep', 'WebFetch'])
+ expect(deny(on)).toEqual(['Bash', 'Read', 'Write', 'Edit', 'Grep'])
+ })
+
+ it('strips an API key when the subscription login is named, and keeps it otherwise', () => {
+ const baseEnv = { PATH: '/bin', XAI_API_KEY: 'secret', GROK_CODE_XAI_API_KEY: 'other', GROK_CONFIG: '/c', GROK_CONFIG_PATH: '/c2', GROK_AGENT: 'x' }
+ const withAuth = grokTurnEnv(baseEnv, '/turn', '/real/auth.json')
+ expect(withAuth['GROK_HOME']).toBe('/turn')
+ expect(withAuth['HOME']).toBe('/turn')
+ expect(grokTurnEnv(baseEnv, '/turn', undefined, 'darwin')['USERPROFILE']).toBeUndefined()
+ expect(grokTurnEnv(baseEnv, '/turn', undefined, 'win32')['USERPROFILE']).toBe('/turn')
+ expect(withAuth['GROK_AUTH_PATH']).toBe('/real/auth.json')
+ expect(withAuth['XAI_API_KEY']).toBeUndefined()
+ expect(withAuth['GROK_CODE_XAI_API_KEY']).toBeUndefined()
+ expect(withAuth['GROK_CONFIG']).toBeUndefined()
+ expect(withAuth['GROK_CONFIG_PATH']).toBeUndefined()
+ expect(withAuth['GROK_AGENT']).toBeUndefined()
+ expect(withAuth['GROK_MEMORY']).toBe('0')
+ expect(withAuth['GROK_WORKFLOWS']).toBe('0')
+ expect(withAuth['GROK_CLAUDE_SKILLS_ENABLED']).toBe('false')
+ expect(withAuth['GROK_CURSOR_HOOKS_ENABLED']).toBe('false')
+ expect(withAuth['PATH']).toBe('/bin')
+ const keyOnly = grokTurnEnv(baseEnv, '/turn')
+ expect(keyOnly['XAI_API_KEY']).toBe('secret')
+ expect(keyOnly['GROK_AUTH_PATH']).toBeUndefined()
+ })
+
+ it('writes the prompt as text, or as ACP blocks when an image exists', () => {
+ expect(grokPrompt({ prompt: 'oi' })).toEqual({ name: 'prompt.txt', body: 'oi' })
+ const dir = mkdtempSync(join(tmpdir(), 'tucano-grok-img-'))
+ const png = join(dir, 'a.png')
+ writeFileSync(png, Buffer.from([1, 2, 3]))
+ const withImage = grokPrompt({ prompt: 'veja', images: [{ block: 0, path: png, mime: 'image/png' }, { block: 1, path: join(dir, 'gone.png'), mime: 'image/png' }] })
+ expect(withImage.name).toBe('prompt.json')
+ expect(JSON.parse(withImage.body)).toEqual([
+ { type: 'text', text: 'veja' },
+ { type: 'image', mimeType: 'image/png', data: Buffer.from([1, 2, 3]).toString('base64') }
+ ])
+ expect(grokPrompt({ prompt: ' ', images: [{ block: 0, path: png, mime: 'image/png' }] }).body).toBe(JSON.stringify([{ type: 'image', mimeType: 'image/png', data: Buffer.from([1, 2, 3]).toString('base64') }]))
+ })
+
+ it('points the turn config at the gateway and turns the other scans off', () => {
+ const c = grokConfig({ mcpUrl: 'http://127.0.0.1:1/mcp/x"y' })
+ expect(c).toContain('[mcp_servers.tucano]')
+ expect(c).toContain('url = "http://127.0.0.1:1/mcp/x\\"y"')
+ expect(c).toContain('enabled = true')
+ expect(c).toContain('[compat.claude]')
+ expect(c).toContain('skills = false')
+ expect(c).toContain('[compat.cursor]')
+ expect(c).toContain('[compat.codex]')
+ expect(grokConfig({})).not.toContain('mcp_servers')
+ })
+
+ it('reads the model list and which login it is', () => {
+ const listed = 'You are logged in with grok.com.\nDefault model: grok-4.7\nAvailable models:\n\n * grok-4.7 (default)\n - grok-4.7-build-fast\n - grok-4.6\n - grok-4.5\n'
+ expect(parseGrokModels(listed)).toEqual(['grok-4.7', 'grok-4.7-build-fast', 'grok-4.6', 'grok-4.5'])
+ expect(grokLogin(listed)).toEqual({ loggedIn: true, plan: true })
+ // What grok 1.0.70 prints signed out (the models are still listed) and with only an API key.
+ const models = '\nDefault model: grok-4.6\n\nAvailable models:\n * grok-4.6 (default)\n - grok-4.5\n'
+ expect(grokLogin(`You are not authenticated.\n${models}`)).toEqual({ loggedIn: false, plan: false })
+ expect(grokLogin(`You are using XAI_API_KEY.\n${models}`)).toEqual({ loggedIn: true, plan: false })
+ expect(grokLogin('Not signed in. To authenticate without a browser, run: grok login --device-code')).toEqual({ loggedIn: false, plan: false })
+ expect(userGrokHome({ GROK_HOME: ' /custom/grok ' }, '/h')).toBe('/custom/grok')
+ expect(userGrokHome({}, '/h')).toBe(join('/h', '.grok'))
+ })
+
+ it('puts the turn outside any checkout, and the cleanup leaves the login file', () => {
+ const dirs = grokTurnDirs()
+ expect(existsSync(dirs.work)).toBe(true)
+ expect(dirs.work.startsWith(dirs.root)).toBe(true)
+ expect(dirs.root).toContain('tucano-grok-')
+ expect(dirs.socket.length).toBeLessThanOrEqual(100)
+ const auth = join(mkdtempSync(join(tmpdir(), 'tucano-grok-auth-')), 'auth.json')
+ writeFileSync(auth, 'secret')
+ writeFileSync(join(dirs.root, 'config.toml'), 'x')
+ grokCleanup(dirs)
+ expect(existsSync(dirs.root)).toBe(false)
+ expect(readFileSync(auth, 'utf8')).toBe('secret')
+ })
+})
+
+describe.skipIf(process.platform === 'win32')('Grok engine', () => {
+ const fakeCli = (): string => {
+ const dir = mkdtempSync(join(tmpdir(), 'tucano-grok-cli-'))
+ const bin = join(dir, 'grok')
+ writeFileSync(
+ bin,
+ `#!/bin/sh
+key=\${XAI_API_KEY-unset}
+cfg=\${GROK_CONFIG-unset}
+mem=\${GROK_MEMORY-unset}
+auth=\${GROK_AUTH_PATH-unset}
+pflag=no
+prompt=
+prev=
+for a in "$@"; do
+ [ "$a" = -p ] && pflag=yes
+ [ "$prev" = --prompt-file ] && prompt=$a
+ prev=$a
+done
+mcp=no
+if [ -f "$GROK_HOME/config.toml" ] && grep -q 'mcp_servers.tucano' "$GROK_HOME/config.toml"; then mcp=yes; fi
+img=no
+if [ -n "$prompt" ] && grep -q '"type":"image"' "$prompt"; then img=yes; fi
+printf '%s\\n' "{\\"type\\":\\"text\\",\\"data\\":\\"key=$key cfg=$cfg mem=$mem pflag=$pflag mcp=$mcp img=$img home=$GROK_HOME userhome=$HOME cwd=$(pwd) auth=$auth\\"}"
+printf '%s\\n' '{"type":"end","stopReason":"end_turn","usage":{"input_tokens":4,"output_tokens":1}}'
+`,
+ { mode: 0o755 }
+ )
+ return bin
+ }
+
+ const run = async (bin: string | undefined, extra: { images?: { block: number; path: string; mime: string }[]; shell?: NodeJS.ProcessEnv } = {}): Promise<EngineEvent[]> => {
+ const cwd = mkdtempSync(join(tmpdir(), 'tucano-grok-cwd-'))
+ const turn = { model: 'grok-4.7', effort: 'medium' as const, system: 'You are Iris.', prompt: 'Oi', images: extra.images, cwd, mcpUrl: 'http://127.0.0.1:9/mcp/abc', signal: new AbortController().signal }
+ const out: EngineEvent[] = []
+ for await (const ev of grokEngine(() => bin, async () => extra.shell ?? {}).run(turn)) out.push(ev)
+ return out
+ }
+
+ it('is missing when the CLI is not installed', async () => {
+ const events = await run(undefined)
+ expect(events).toEqual([expect.objectContaining({ type: 'error' })])
+ })
+
+ it("runs in its own home, drops an API key when the login file is named, and removes the turn folder", async () => {
+ const authDir = mkdtempSync(join(tmpdir(), 'tucano-grok-real-'))
+ const auth = join(authDir, 'auth.json')
+ writeFileSync(auth, 'secret')
+ const done = (await run(fakeCli(), { shell: { GROK_HOME: authDir, XAI_API_KEY: 'secret', GROK_CONFIG: '/nope' } })).find((e) => e.type === 'done')
+ const body = done && done.type === 'done' ? done.text : ''
+ expect(body).toContain('key=unset')
+ expect(body).toContain('cfg=unset')
+ expect(body).toContain('mem=0')
+ expect(body).toContain('pflag=no')
+ expect(body).toContain('mcp=yes')
+ expect(body).toContain('img=no')
+ expect(body).toContain(`auth=${auth}`)
+ const home = /home=(\S+)/.exec(body)?.[1]
+ const cwd = /cwd=(\S+)/.exec(body)?.[1]
+ // macOS resolves /var to /private/var; the shell's pwd follows the link.
+ const plain = (p: string): string => p.replace(/^\/private/, '')
+ expect(home).toBeTruthy()
+ expect(/userhome=(\S+)/.exec(body)?.[1]).toBe(home)
+ expect(plain(cwd!)).toBe(plain(join(home!, 'work')))
+ expect(existsSync(home!)).toBe(false)
+ expect(readFileSync(auth, 'utf8')).toBe('secret')
+ })
+
+ it('sends an existing image as an ACP block', async () => {
+ const png = join(mkdtempSync(join(tmpdir(), 'tucano-grok-pic-')), 'p.png')
+ writeFileSync(png, 'x')
+ const done = (await run(fakeCli(), { images: [{ block: 0, path: png, mime: 'image/png' }] })).find((e) => e.type === 'done')
+ expect(done && done.type === 'done' && done.text).toContain('img=yes')
+ })
+})
diff --git a/test/fixtures/grok-stream-recorded.jsonl b/test/fixtures/grok-stream-recorded.jsonl
new file mode 100644
index 0000000..f67016e
--- /dev/null
+++ b/test/fixtures/grok-stream-recorded.jsonl
@@ -0,0 +1,143 @@
+{"type":"thought","data":"Vou pesquisar a versão"}
+{"type":"thought","data":" LTS atual do Node.js."}
+{"type":"text","data":"V"}
+{"type":"text","data":"ou"}
+{"type":"text","data":" buscar"}
+{"type":"text","data":" a"}
+{"type":"text","data":" L"}
+{"type":"text","data":"TS"}
+{"type":"text","data":" do"}
+{"type":"text","data":" Node"}
+{"type":"text","data":".js"}
+{"type":"text","data":","}
+{"type":"text","data":" abrir"}
+{"type":"text","data":" o"}
+{"type":"text","data":" site"}
+{"type":"text","data":" oficial"}
+{"type":"text","data":" e"}
+{"type":"text","data":" consultar"}
+{"type":"text","data":" a"}
+{"type":"text","data":" estrutura"}
+{"type":"text","data":" da"}
+{"type":"text","data":" wiki"}
+{"type":"text","data":" do"}
+{"type":"text","data":" React"}
+{"type":"text","data":"."}
+{"type":"tool_call","toolCallId":"ws_a6248257-a732-9626-8da2-39104be210ce_call-97807bff-a2b0-4d60-bbc1-bf411bc854ef-0","title":"Web search:","kind":"search","status":"in_progress","toolName":"Web search:","rawInput":{"variant":"WebSearch","backend":true},"content":[],"locations":[]}
+{"type":"tool_call_update","toolCallId":"ws_a6248257-a732-9626-8da2-39104be210ce_call-97807bff-a2b0-4d60-bbc1-bf411bc854ef-0","status":"completed","content":[],"rawOutput":{"action":{"type":"search","query":"Node.js current LTS version","sources":[{"type":"url","url":"https://nodejs.org/en/blog/release"},{"type":"url","url":"https://nodejs.org/en/about/previous-releases"},{"type":"url","url":"https://www.linuxcompatible.org/story/nodejs-26130-lithium-reaches-lts-support-through-april-2029/"}]},"id":"ws_a6248257-a732-9626-8da2-39104be210ce_call-97807bff-a2b0-4d60-bbc1-bf411bc854ef-0","status":"completed"},"locations":[]}
+{"type":"usage","usage":{"input_tokens":2767,"output_tokens":189,"cache_read_input_tokens":1152,"cache_creation_input_tokens":0,"reasoning_tokens":108}}
+{"type":"tool_call","toolCallId":"call-97807bff-a2b0-4d60-bbc1-bf411bc854ef-1","title":"web_fetch","kind":"web_fetch","status":"pending","toolName":"web_fetch","rawInput":{"url":"https://nodejs.org/en"},"content":[],"locations":[]}
+{"type":"tool_call_update","toolCallId":"call-97807bff-a2b0-4d60-bbc1-bf411bc854ef-1","status":null,"content":[],"rawOutput":null,"locations":[]}
+{"type":"tool_call","toolCallId":"call-97807bff-a2b0-4d60-bbc1-bf411bc854ef-2","title":"search_tool","kind":"search_tool","status":"pending","toolName":"search_tool","rawInput":{"query":"tucano read_wiki_structure","limit":3},"content":[],"locations":[]}
+{"type":"tool_call_update","toolCallId":"call-97807bff-a2b0-4d60-bbc1-bf411bc854ef-2","status":null,"content":[],"rawOutput":null,"locations":[]}
+{"type":"tool_call_update","toolCallId":"call-97807bff-a2b0-4d60-bbc1-bf411bc854ef-2","status":"completed","content":[{"type":"content","content":{"type":"text","text":"{\n \"results\": [\n {\n \"server\": \"tucano\",\n \"tools\": [\n {\n \"tool_name\": \"tucano__read_wiki_structure\",\n \"description\": \"Get …"}}],"rawOutput":{"type":"SearchTool","result_count":3,"content":"{\n \"results\": [\n {\n \"server\": \"tucano\",\n \"tools\": [\n {\n \"tool_name\": \"tucano__read_wiki_structure\",\n \"description\": \"Get …"},"locations":[]}
+{"type":"tool_call_update","toolCallId":"call-97807bff-a2b0-4d60-bbc1-bf411bc854ef-1","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Node.js — Run JavaScript Everywhere\n\n[Skip to content](#main)\n\n# Run JavaScript Everywhere\n\nNode.js® is a free, open-source, cross-platform JavaScript runtime e…"}}],"rawOutput":{"type":"WebFetch","Content":{"url":"https://nodejs.org/en","content":"Node.js — Run JavaScript Everywhere\n\n[Skip to content](#main)\n\n# Run JavaScript Everywhere\n\nNode.js® is a free, open-source, cross-platform JavaScript runtime e…","content_type":"markdown","status_code":200,"bytes":3213}},"locations":[]}
+{"type":"thought","data":"Vou consultar a estrutura"}
+{"type":"thought","data":" do wiki no servidor"}
+{"type":"thought","data":" tucano em facebook/react."}
+{"type":"usage","usage":{"input_tokens":7608,"output_tokens":113,"cache_read_input_tokens":3840,"cache_creation_input_tokens":0,"reasoning_tokens":78}}
+{"type":"tool_call","toolCallId":"call-c1e28e3e-e021-4f65-8619-da09548610a7-3","title":"use_tool","kind":"use_tool","status":"pending","toolName":"use_tool","rawInput":{"tool_name":"tucano__read_wiki_structure","tool_input":{"repoName":"facebook/react"}},"content":[],"locations":[]}
+{"type":"tool_call_update","toolCallId":"call-c1e28e3e-e021-4f65-8619-da09548610a7-3","status":null,"content":[],"rawOutput":null,"locations":[]}
+{"type":"tool_call_update","toolCallId":"call-c1e28e3e-e021-4f65-8619-da09548610a7-3","status":"completed","content":[],"rawOutput":{"type":"MCP","tool_name":"read_wiki_structure","server_name":"tucano","output":{"OkayOutput":"Available pages for facebook/react:\n\n- 1 React Repository Overview\n - 1.1 Repository Structure and Packages\n - 1.2 Feature Flags System\n- 2 Core Reconciler Ar…"}},"locations":[]}
+{"type":"thought","data":"Vou responder em duas"}
+{"type":"thought","data":" linhas."}
+{"type":"text","data":"A"}
+{"type":"text","data":" L"}
+{"type":"text","data":"TS"}
+{"type":"text","data":" atual"}
+{"type":"text","data":" do"}
+{"type":"text","data":" Node"}
+{"type":"text","data":".js"}
+{"type":"text","data":" é"}
+{"type":"text","data":" a"}
+{"type":"text","data":" "}
+{"type":"text","data":"26"}
+{"type":"text","data":" “"}
+{"type":"text","data":"Lith"}
+{"type":"text","data":"ium"}
+{"type":"text","data":"”"}
+{"type":"text","data":" ("}
+{"type":"text","data":"26"}
+{"type":"text","data":"."}
+{"type":"text","data":"13"}
+{"type":"text","data":"."}
+{"type":"text","data":"0"}
+{"type":"text","data":","}
+{"type":"text","data":" suporte"}
+{"type":"text","data":" até"}
+{"type":"text","data":" abril"}
+{"type":"text","data":" de"}
+{"type":"text","data":" "}
+{"type":"text","data":"202"}
+{"type":"text","data":"9"}
+{"type":"text","data":");"}
+{"type":"text","data":" a"}
+{"type":"text","data":" home"}
+{"type":"text","data":" de"}
+{"type":"text","data":" node"}
+{"type":"text","data":"js"}
+{"type":"text","data":".org"}
+{"type":"text","data":" descre"}
+{"type":"text","data":"ve"}
+{"type":"text","data":" o"}
+{"type":"text","data":" runtime"}
+{"type":"text","data":" e"}
+{"type":"text","data":" exemplos"}
+{"type":"text","data":" ("}
+{"type":"text","data":"serv"}
+{"type":"text","data":"idor"}
+{"type":"text","data":" HTTP"}
+{"type":"text","data":","}
+{"type":"text","data":" testes"}
+{"type":"text","data":","}
+{"type":"text","data":" streams"}
+{"type":"text","data":"),"}
+{"type":"text","data":" sem"}
+{"type":"text","data":" list"}
+{"type":"text","data":"ar"}
+{"type":"text","data":" o"}
+{"type":"text","data":" número"}
+{"type":"text","data":" da"}
+{"type":"text","data":" L"}
+{"type":"text","data":"TS"}
+{"type":"text","data":".\n"}
+{"type":"text","data":"A"}
+{"type":"text","data":" wiki"}
+{"type":"text","data":" de"}
+{"type":"text","data":" facebook"}
+{"type":"text","data":"/"}
+{"type":"text","data":"react"}
+{"type":"text","data":" tem"}
+{"type":"text","data":" "}
+{"type":"text","data":"8"}
+{"type":"text","data":" t"}
+{"type":"text","data":"ópicos"}
+{"type":"text","data":":"}
+{"type":"text","data":" visão"}
+{"type":"text","data":" geral"}
+{"type":"text","data":","}
+{"type":"text","data":" reconc"}
+{"type":"text","data":"iler"}
+{"type":"text","data":","}
+{"type":"text","data":" al"}
+{"type":"text","data":"vos"}
+{"type":"text","data":" de"}
+{"type":"text","data":" render"}
+{"type":"text","data":","}
+{"type":"text","data":" React"}
+{"type":"text","data":" Compiler"}
+{"type":"text","data":","}
+{"type":"text","data":" Dev"}
+{"type":"text","data":"Tools"}
+{"type":"text","data":","}
+{"type":"text","data":" build"}
+{"type":"text","data":","}
+{"type":"text","data":" pac"}
+{"type":"text","data":"otes"}
+{"type":"text","data":" extras"}
+{"type":"text","data":" e"}
+{"type":"text","data":" gloss"}
+{"type":"text","data":"ário"}
+{"type":"text","data":"."}
+{"type":"usage","usage":{"input_tokens":1070,"output_tokens":258,"cache_read_input_tokens":11392,"cache_creation_input_tokens":0,"reasoning_tokens":160}}
+{"type":"end","stopReason":"end_turn","cwd":"/tmp/tucano-grok-0/work","usage":{"input_tokens":11445,"cache_read_input_tokens":16384,"cache_creation_input_tokens":0,"output_tokens":560,"reasoning_tokens":346,"total_tokens":28389},"num_turns":3,"total_cost_usd":0.039442,"total_cost_usd_ticks":394420000,"modelUsage":{"grok-4.7-build":{"inputTokens":11445,"outputTokens":560,"cacheReadInputTokens":16384,"cacheCreationInputTokens":0,"modelCalls":3,"costUSD":0.039442}}}
diff --git a/test/fixtures/grok-stream.jsonl b/test/fixtures/grok-stream.jsonl
new file mode 100644
index 0000000..616cc8b
--- /dev/null
+++ b/test/fixtures/grok-stream.jsonl
@@ -0,0 +1,8 @@
+{"type":"text","data":"Vou consultar. "}
+{"type":"thought","data":"skip me"}
+{"type":"tool_call","toolCallId":"c1","toolName":"web_search","status":"in_progress","rawInput":{"query":"Node.js LTS"}}
+{"type":"tool_call_update","toolCallId":"c1","status":"completed"}
+{"type":"tool_call","toolCallId":"c2","toolName":"search_tool","status":"completed","rawInput":{"query":"hora"}}
+{"type":"usage","usage":{"input_tokens":10,"output_tokens":4}}
+{"type":"text","data":"São 21:58."}
+{"type":"end","stopReason":"end_turn","usage":{"input_tokens":100,"cache_read_input_tokens":50,"cache_creation_input_tokens":10,"output_tokens":20,"reasoning_tokens":5},"total_cost_usd":0.0123}
diff --git a/test/github.test.ts b/test/github.test.ts
index a383f04..acbabe4 100644
--- a/test/github.test.ts
+++ b/test/github.test.ts
@@ -121,7 +121,7 @@ describe('the proxy and the PR', () => {
it('abrir_pr becomes an approval; approved, the app opens the PR with the cost of the issue', async () => {
const ready = { installed: true, loggedIn: true }
- const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
const gateway = new Gateway()
await gateway.start()
const claude: Engine = {
@@ -131,7 +131,7 @@ describe('the proxy and the PR', () => {
yield { type: 'done', text: 'ok', usage: { inputTokens: 1000, cacheReadTokens: 0, outputTokens: 10 } }
}
}
- const r = new Runner({ db, engines: { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'w-')), gateway, github: gh, computers: { call: async () => ({ result: { content: [] } }) } })
+ const r = new Runner({ db, engines: { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'w-')), gateway, github: gh, computers: { call: async () => ({ result: { content: [] } }) } })
await r.send('c1', '@staff corrige a OAB-66')
await r.idle()
const [ap] = db.approvals()
diff --git a/test/governance.test.ts b/test/governance.test.ts
index e2cd1aa..7567669 100644
--- a/test/governance.test.ts
+++ b/test/governance.test.ts
@@ -66,7 +66,7 @@ const agent = (grant: GrantLevel): Agent => ({
function runner(plan: (turn: Turn, tools: string[]) => Plan, onDb: Db = db): Runner {
return new Runner({
db: onDb,
- engines: { claude: scripted(plan, seen), codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') },
+ engines: { claude: scripted(plan, seen), codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') },
settings: async () => settings,
emit: (e) => events.push(e),
workDir: join(dir, 'work'),
@@ -91,7 +91,7 @@ beforeEach(async () => {
db = new Db(join(dir, 'test.db'))
events = []
seen = { turns: [], tools: [], results: [] }
- settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
gateway = new Gateway()
await gateway.start()
connectors = new ConnectorManager({ db, secrets: new Secrets(db, plainCipher), emit: (e) => events.push(e), openUrl: () => {}, oauthCallbackUrl: () => gateway.url('/oauth/callback') })
@@ -278,7 +278,7 @@ describe('approvals', () => {
}
r = new Runner({
db,
- engines: { claude: engine, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') },
+ engines: { claude: engine, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') },
settings: async () => settings,
emit: (e) => events.push(e),
workDir: join(dir, 'work'),
@@ -362,7 +362,7 @@ describe('pausing and attributing work', () => {
db.createConversation({ id: 'c1', kind: 'channel', name: 'eng', members: ['a1', 'a2'] })
const r = new Runner({
db,
- engines: { claude: fakeEngine('claude', { delayMs: 1, reply: (t) => (t.prompt.includes('Theo · agente') ? 'feito' : '@theo dá uma olhada') }), codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') },
+ engines: { claude: fakeEngine('claude', { delayMs: 1, reply: (t) => (t.prompt.includes('Theo · agente') ? 'feito' : '@theo dá uma olhada') }), codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') },
settings: async () => settings,
emit: () => {},
workDir: join(dir, 'work')
diff --git a/test/harness.test.ts b/test/harness.test.ts
index 89285d1..bf97465 100644
--- a/test/harness.test.ts
+++ b/test/harness.test.ts
@@ -5,7 +5,7 @@ import { startsPicked } from '../src/shared/types'
import type { EngineId, EngineStatus } from '../src/shared/types'
const ready: EngineStatus = { installed: true, loggedIn: true, route: 'plan' }
-const engines: Record<EngineId, EngineStatus> = { claude: ready, codex: ready, opencode: { ...ready, route: 'providers' }, pi: { ...ready, route: 'providers' }, gemini: { ...ready, route: 'providers' }, cursor: { ...ready, route: 'providers' } }
+const engines: Record<EngineId, EngineStatus> = { claude: ready, codex: ready, opencode: { ...ready, route: 'providers' }, pi: { ...ready, route: 'providers' }, gemini: { ...ready, route: 'providers' }, cursor: { ...ready, route: 'providers' }, grok: { ...ready, route: 'providers' } }
describe('harnesses', () => {
it('defaults the pick to the harnesses that can actually run', () => {
diff --git a/test/jev.test.ts b/test/jev.test.ts
index 34eae32..4857440 100644
--- a/test/jev.test.ts
+++ b/test/jev.test.ts
@@ -68,7 +68,7 @@ describe('in a channel', () => {
let settings: Settings
const engines = (): Record<EngineId, Engine> => {
const base = fakeEngine('claude', { delayMs: 1 })
- return { claude: { id: 'claude', run: (t) => (t.model === 'haiku' && routerTurns++, base.run(t)) }, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ return { claude: { id: 'claude', run: (t) => (t.model === 'haiku' && routerTurns++, base.run(t)) }, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
}
const runner = (f: typeof fetch, key: string | undefined): Runner =>
new Runner({ db, engines: engines(), settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-w-')), jev: { key: async () => key, fetch: f } })
@@ -77,7 +77,7 @@ describe('in a channel', () => {
beforeEach(() => {
db = new Db(join(mkdtempSync(join(tmpdir(), 'ad-jev-')), 'test.db'))
routerTurns = 0
- settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'jev', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'jev', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
db.saveAgent(lia)
db.saveAgent(nina)
db.createConversation({ id: 'c1', kind: 'channel', name: 'eng', members: ['a1', 'a2'] })
diff --git a/test/limits.test.ts b/test/limits.test.ts
index d8c7185..e3d85d7 100644
--- a/test/limits.test.ts
+++ b/test/limits.test.ts
@@ -37,7 +37,7 @@ let notes: string[]
let bash: (command: string) => CallToolResult // what the agent's "computer" answers
const runner = (claude: Engine): Runner => {
- const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
const computers = { call: async (_a: Agent, _n: string, args: Record<string, unknown>) => ({ result: bash(String(args['command'])) }) }
return new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-w-')), gateway, computers, notify: (title) => notes.push(title) })
}
@@ -46,7 +46,7 @@ const labels = () => reply().run!.steps.map((s) => s.label)
beforeEach(async () => {
db = new Db(join(mkdtempSync(join(tmpdir(), 'ad-limits-')), 'test.db'))
- settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
notes = []
bash = () => textResult('ok')
db.saveAgent(agent())
@@ -234,7 +234,7 @@ describe('web', () => {
describe('keeping the Mac awake', () => {
it('says when replies start and when the last one ends', async () => {
const busy: boolean[] = []
- const r = new Runner({ db, engines: { claude: fakeEngine('claude', { delayMs: 5 }), codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-w-')), onBusy: (b) => busy.push(b) })
+ const r = new Runner({ db, engines: { claude: fakeEngine('claude', { delayMs: 5 }), codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-w-')), onBusy: (b) => busy.push(b) })
db.saveAgent(agent({ id: 'a2', handle: 'theo', name: 'Theo' }))
db.createConversation({ id: 'c1', kind: 'channel', name: 'eng', members: ['a1', 'a2'] })
await r.send('c1', '@lia @theo oi')
diff --git a/test/memory-search.test.ts b/test/memory-search.test.ts
index 1453a13..b3f2d48 100644
--- a/test/memory-search.test.ts
+++ b/test/memory-search.test.ts
@@ -43,7 +43,7 @@ describe('memories past the prompt budget', () => {
describe('buscar_memorias', () => {
const ready = { installed: true, loggedIn: true }
- const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
const lia: Agent = { id: 'a1', name: 'Lia', handle: 'lia', role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1_000_000, used: 0, grants: {}, memory: 'auto', computer: false, archived: false }
let db: Db
let gateway: Gateway
@@ -67,7 +67,7 @@ describe('buscar_memorias', () => {
yield { type: 'done', text: 'ok', usage: { inputTokens: 10, cacheReadTokens: 0, outputTokens: 1 } }
}
}
- const engines = { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ const engines = { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
const workDir = mkdtempSync(join(tmpdir(), 'ad-work-'))
const memory = new Memories({ db, engines, settings: async () => settings, emit: () => {}, workDir })
runner = new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir, gateway, memory })
diff --git a/test/memory.test.ts b/test/memory.test.ts
index ec4d4b4..805eadd 100644
--- a/test/memory.test.ts
+++ b/test/memory.test.ts
@@ -27,7 +27,7 @@ let runner: Runner
function setup(): void {
const base = fakeEngine('claude', { delayMs: 1 })
const claude: Engine = { id: 'claude', run: (t) => (turns.push(t), base.run(t)) }
- const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
const emit = (_: CoreEvent): void => {}
const workDir = mkdtempSync(join(tmpdir(), 'ad-work-'))
memory = new Memories({ db, engines, settings: async () => settings, emit, workDir })
@@ -52,7 +52,7 @@ const active = (scope = 'me'): string[] => db.memories({ scope, state: 'active'
beforeEach(async () => {
db = new Db(join(mkdtempSync(join(tmpdir(), 'ad-db-')), 'test.db'))
turns = []
- settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
db.saveAgent(agent('a1', 'lia'))
db.saveAgent(agent('a2', 'theo'))
db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })
diff --git a/test/platform.test.ts b/test/platform.test.ts
index a3c0032..7b96aa8 100644
--- a/test/platform.test.ts
+++ b/test/platform.test.ts
@@ -245,7 +245,7 @@ describe('folders the CLIs install into', () => {
it("doesn't repeat a folder already there, whatever its case or trailing slash on Windows", () => {
expect(withInstallDirs([local.toUpperCase() + '/'].join(delimiter), 'windows', home, env, (p) => p === local)).toBe(local.toUpperCase() + '/')
- expect(withInstallDirs(local, 'mac', home, env, () => true)).toBe(local)
+ expect(withInstallDirs(local, 'mac', home, env, () => true)).toBe([local, join(home, '.grok', 'bin')].join(delimiter))
})
})
diff --git a/test/reserve-account.test.ts b/test/reserve-account.test.ts
index e38184b..40daefa 100644
--- a/test/reserve-account.test.ts
+++ b/test/reserve-account.test.ts
@@ -39,7 +39,7 @@ const personal: Account = { id: 'p1', engine: 'claude', name: 'Pessoal', loggedI
function runner(claude: Engine): Runner {
codexTurns = []
const codex = fakeEngine('codex', { delayMs: 1 })
- const engines: Record<EngineId, Engine> = { claude, codex: { id: 'codex', run: (t) => (codexTurns.push(t), codex.run(t)) }, opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ const engines: Record<EngineId, Engine> = { claude, codex: { id: 'codex', run: (t) => (codexTurns.push(t), codex.run(t)) }, opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
return new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-work-')), dataDir: data })
}
const reply = (): Message => db.messages().filter((m) => m.author.kind === 'agent').at(-1)!
@@ -47,7 +47,7 @@ const reply = (): Message => db.messages().filter((m) => m.author.kind === 'agen
beforeEach(() => {
data = mkdtempSync(join(tmpdir(), 'ad-data-'))
db = new Db(join(data, 'test.db'))
- settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt', accounts: [work, personal] }
+ settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt', accounts: [work, personal] }
db.saveAgent(agent())
db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })
})
diff --git a/test/reserve.test.ts b/test/reserve.test.ts
index 6251d48..5e8068b 100644
--- a/test/reserve.test.ts
+++ b/test/reserve.test.ts
@@ -38,14 +38,14 @@ let codex: ReturnType<typeof counted>
function runner(claude: Engine): Runner {
codex = counted(fakeEngine('codex', { delayMs: 1 }))
- const engines: Record<EngineId, Engine> = { claude, codex, opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ const engines: Record<EngineId, Engine> = { claude, codex, opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
return new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-work-')) })
}
const reply = (): Message => db.messages().find((m) => m.author.kind === 'agent')!
beforeEach(() => {
db = new Db(join(mkdtempSync(join(tmpdir(), 'ad-db-')), 'test.db'))
- settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
db.saveAgent(agent({ fallbackModelId: 'gpt-5.6-luna' }))
db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })
})
diff --git a/test/routines.test.ts b/test/routines.test.ts
index 78521e8..528374a 100644
--- a/test/routines.test.ts
+++ b/test/routines.test.ts
@@ -36,7 +36,7 @@ describe('schedule', () => {
describe('routines', () => {
const ready = { installed: true, loggedIn: true }
- const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
const agent = (id: string, handle: string, extra: Partial<Agent> = {}): Agent => ({
id, name: handle[0]!.toUpperCase() + handle.slice(1), handle, role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1_000_000, used: 0, grants: {}, memory: 'read', computer: false, archived: false, ...extra
})
@@ -60,7 +60,7 @@ describe('routines', () => {
clock = at(2026, 10, 19, 8, 0) // a Monday
const base = fakeEngine('claude', { delayMs: 1 })
const claude: Engine = { id: 'claude', run: (t) => (turns.push(t), base.run(t)) }
- const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
const emit = (_: CoreEvent): void => {}
gateway = new Gateway()
await gateway.start()
@@ -282,7 +282,7 @@ describe('quiet hours', () => {
// A reply that fails is tried again in place, up to twice, and then stays failed.
describe('routine retries', () => {
const ready = { installed: true, loggedIn: true }
- const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
const lia: Agent = { id: 'a1', name: 'Lia', handle: 'lia', role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1_000_000, used: 0, grants: {}, memory: 'read', computer: false, archived: false }
let db: Db
@@ -317,7 +317,7 @@ describe('routine retries', () => {
else yield { type: 'done', text: doneText, usage: { inputTokens: 1, cacheReadTokens: 0, outputTokens: 1 } }
}
}
- const engines: Record<EngineId, Engine> = { claude: flaky, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ const engines: Record<EngineId, Engine> = { claude: flaky, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
gateway = new Gateway()
await gateway.start()
routines = new Routines({
diff --git a/test/runner.test.ts b/test/runner.test.ts
index c41e857..922338b 100644
--- a/test/runner.test.ts
+++ b/test/runner.test.ts
@@ -29,7 +29,7 @@ let settings: Settings
function runner(engine: Engine = fakeEngine('claude', { delayMs: 1 })): Runner {
claude = counted(engine)
- const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
return new Runner({ db, engines, settings: async () => settings, emit: (e) => events.push(e), workDir: mkdtempSync(join(tmpdir(), 'ad-work-')) })
}
@@ -38,7 +38,7 @@ const agentMessages = (): Message[] => db.messages().filter((m) => m.author.kind
beforeEach(() => {
db = new Db(join(mkdtempSync(join(tmpdir(), 'ad-db-')), 'test.db'))
events = []
- settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
db.saveAgent(agent('a1', 'lia'))
db.saveAgent(agent('a2', 'theo', { modelId: 'gpt-5.6-luna' }))
db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })
@@ -66,7 +66,7 @@ describe('Runner', () => {
it('keeps the images I attach and shows them to the agent with my message', async () => {
const data = mkdtempSync(join(tmpdir(), 'ad-data-'))
claude = counted(fakeEngine('claude', { delayMs: 1 }))
- const r = new Runner({ db, engines: { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }, settings: async () => settings, emit: (e) => events.push(e), workDir: mkdtempSync(join(tmpdir(), 'ad-work-')), dataDir: data })
+ const r = new Runner({ db, engines: { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }, settings: async () => settings, emit: (e) => events.push(e), workDir: mkdtempSync(join(tmpdir(), 'ad-work-')), dataDir: data })
const png = Buffer.from('fake-png').toString('base64')
await r.send('d1', '', [{ name: 'Tela do checkout.png', mime: 'image/png', data: png }, { name: 'virus.exe', mime: 'application/x-msdownload', data: png }])
await r.idle()
@@ -307,7 +307,7 @@ describe('ask_user through the gateway', () => {
claude = counted(fakeEngine('claude', { delayMs: 1 }))
const r = new Runner({
db,
- engines: { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') },
+ engines: { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') },
settings: async () => settings,
emit: (e) => events.push(e),
workDir: mkdtempSync(join(tmpdir(), 'ad-work-')),
@@ -345,7 +345,7 @@ describe('browser handback', () => {
claude = counted(fakeEngine('claude', { delayMs: 1 }))
return new Runner({
db,
- engines: { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') },
+ engines: { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') },
settings: async () => settings,
emit: (e) => events.push(e),
workDir: mkdtempSync(join(tmpdir(), 'ad-work-')),
@@ -400,7 +400,7 @@ describe('an agent on Gemini', () => {
db.saveAgent(agent('a9', 'gi', { modelId: customModel('gemini', 'gemini/gemini-2.5-flash') }))
db.createConversation({ id: 'd9', kind: 'dm', name: 'a9', members: ['a9'] })
const gemini = counted(fakeEngine('gemini'))
- const r = new Runner({ db, engines: { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini, cursor: fakeEngine('cursor') }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-gemini-')) })
+ const r = new Runner({ db, engines: { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini, cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-gemini-')) })
await r.send('d9', 'oi')
await r.idle()
expect(gemini.turns.map((t) => t.model)).toEqual(['gemini/gemini-2.5-flash'])
@@ -413,10 +413,23 @@ describe('an agent on Cursor', () => {
db.saveAgent(agent('a10', 'cu', { modelId: customModel('cursor', 'auto') }))
db.createConversation({ id: 'd10', kind: 'dm', name: 'a10', members: ['a10'] })
const cursor = counted(fakeEngine('cursor'))
- const r = new Runner({ db, engines: { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-cursor-')) })
+ const r = new Runner({ db, engines: { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor, grok: fakeEngine('grok') }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-cursor-')) })
await r.send('d10', 'oi')
await r.idle()
expect(cursor.turns.map((t) => t.model)).toEqual(['auto'])
expect(claude.turns).toHaveLength(0)
})
})
+
+describe('an agent on Grok', () => {
+ it('runs on Grok, not on Claude', async () => {
+ db.saveAgent(agent('a11', 'gk', { modelId: customModel('grok', 'grok-4.7') }))
+ db.createConversation({ id: 'd11', kind: 'dm', name: 'a11', members: ['a11'] })
+ const grok = counted(fakeEngine('grok'))
+ const r = new Runner({ db, engines: { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-grok-')) })
+ await r.send('d11', 'oi')
+ await r.idle()
+ expect(grok.turns.map((t) => t.model)).toEqual(['grok-4.7'])
+ expect(claude.turns).toHaveLength(0)
+ })
+})
diff --git a/test/skills.test.ts b/test/skills.test.ts
index c60affc..48c7ddd 100644
--- a/test/skills.test.ts
+++ b/test/skills.test.ts
@@ -81,7 +81,7 @@ describe('in a reply', () => {
it('the agent sees its skills in the prompt, reads one, and proposes one', async () => {
skills.save({ ...recipe, agents: ['a1'] })
const ready = { installed: true, loggedIn: true }
- const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
gateway = new Gateway()
await gateway.start()
const turns: Turn[] = []
@@ -97,7 +97,7 @@ describe('in a reply', () => {
yield { type: 'done', text: 'feito', usage: { inputTokens: 10, cacheReadTokens: 0, outputTokens: 1 } }
}
}
- const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
const r = new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-w-')), gateway, skills })
db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })
await r.send('d1', 'roda os testes')
diff --git a/test/threads.test.ts b/test/threads.test.ts
index c491eaa..040d36f 100644
--- a/test/threads.test.ts
+++ b/test/threads.test.ts
@@ -35,7 +35,7 @@ function runner(opts: { reply?: (t: Turn) => string; memory?: boolean; onTurn?:
yield* base.run(t)
}
}
- const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
const workDir = mkdtempSync(join(tmpdir(), 'ad-work-'))
memory = new Memories({ db, engines, settings: async () => settings, emit: () => {}, workDir })
return new Runner({
@@ -65,7 +65,7 @@ beforeEach(async () => {
db = new Db(join(mkdtempSync(join(tmpdir(), 'ad-db-')), 'test.db'))
turns = []
notes = []
- settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
db.saveAgent(agent('a1', 'lia', { role: 'Engenharia' }))
db.saveAgent(agent('a2', 'theo', { role: 'Dados' }))
// Both answer in threads; a conversation that answers in it is made where it's tested.
diff --git a/test/triggers.test.ts b/test/triggers.test.ts
index 64a2c09..1798813 100644
--- a/test/triggers.test.ts
+++ b/test/triggers.test.ts
@@ -11,7 +11,7 @@ import { eventItems, Routines } from '../src/core/routines'
import { Runner } from '../src/core/runs'
const ready = { installed: true, loggedIn: true }
-const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
const pm: Agent = { id: 'a1', name: 'PM', handle: 'pm', role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1_000_000, used: 0, grants: {}, memory: 'read', computer: false, archived: false }
const issue = (n: number, title: string) => ({ id: `uuid-${n}`, identifier: `SIM-${n}`, title, description: `detalhes ${n}` })
@@ -37,7 +37,7 @@ beforeEach(() => {
issues = [issue(1, 'Lembrete duplicado')]
failing = undefined
const base = fakeEngine('claude', { delayMs: 1 })
- const engines: Record<EngineId, Engine> = { claude: { id: 'claude', run: (t) => (turns.push(t), base.run(t)) }, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ const engines: Record<EngineId, Engine> = { claude: { id: 'claude', run: (t) => (turns.push(t), base.run(t)) }, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
const connectors = {
list: () => [{ id: 'lin', name: 'Linear' } as Connector],
call: async () => (failing ? textResult(failing, true) : textResult(JSON.stringify({ issues }))) // the shape Linear's MCP answers with
@@ -149,7 +149,7 @@ describe('trying a failed routine run again by hand', () => {
} else yield* base.run(t)
}
}
- runner = new Runner({ db, engines: { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-w-')) })
+ runner = new Runner({ db, engines: { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-w-')) })
}
const failedReply = () => db.messages().find((m) => m.author.kind === 'agent')!
diff --git a/test/tuca.test.ts b/test/tuca.test.ts
index 98eb892..77770f3 100644
--- a/test/tuca.test.ts
+++ b/test/tuca.test.ts
@@ -36,7 +36,7 @@ describe('the Tuca proposals', () => {
describe('the Tuca in a conversation', () => {
const ready = { installed: true, loggedIn: true }
- const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
let db: Db
let gateway: Gateway
let runner: Runner
@@ -49,7 +49,7 @@ describe('the Tuca in a conversation', () => {
systems.length = 0
const base = fakeEngine('claude', { delayMs: 1 })
const claude: Engine = { id: 'claude', run: (t) => (systems.push(t.system), base.run(t)) }
- const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
runner = new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-work-')), gateway, connectors: { list: () => [linear], call: async () => ({ content: [] }) } })
})