Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-2336]): add xAI Grok as an AI provider (API + Grok Build CLI + TUI)

[._.]/ Adam Eivy9cfb94719979
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6b70f25db4..2eb8c95740 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased
+## AI Providers
+
+- **[issue-2336] xAI Grok is now a built-in AI provider — API, Grok Build CLI, and Grok Build TUI.** Three new providers ship ready to enable under AI Providers: **xAI Grok** (the OpenAI-compatible chat API at `https://api.x.ai/v1` — paste your xAI key and pick a model), **Grok Build CLI** (headless, for one-shot generations and file-writing CoS agents), and **Grok Build TUI** (the interactive `grok` coding agent driven over a PTY like Claude Code / Codex). All three arrive disabled by default (nothing calls Grok until you turn one on) and reach existing installs on upgrade. The CLI/TUI use the local `grok` binary; run `grok login` (or set your xAI credentials) to authenticate it.
+
## Layered Intelligence
- **[issue-2322] Layered Intelligence is now a per-app scheduled task, not a global sweep.** The self-improvement loop used to run as a single global "Layered Intelligence Loop" job that swept every enabled app on one daily fire, with a confusing split between a global on/off (CoS → System Tasks) and per-app config (Edit App → Intelligence) — a per-app card could read "Enabled · Due now" while nothing ran. It now runs like every other self-improvement automation: a per-app, deterministic, handler-backed task in CoS → Schedule with its own per-app enable, interval, provider/model, and "Run now". Enabling the `layered-intelligence` task in the Schedule (plus per app on the Intelligence tab) drives it; the reasoning model still only returns JSON and files one deduplicated tracker issue — no code, no agent. Per-app behavior (telemetry sources, allowed scopes, guidance rules, hand-off) still lives on the app's Intelligence tab. An install upgrade migrates each app's scheduling into its per-app task override and tombstones the old global job, preserving effective on/off state. Note: because it's now a self-improvement task, the loop runs only while CoS improvement is enabled.
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index 24d9f74aa5..329fc0a956 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -11,6 +11,7 @@ export const ANTIGRAVITY_CONFIGURED_DEFAULT = 'antigravity-configured-default';
export const DEFAULT_LARGE_CONTEXT_WINDOW = 128_000;
export const CODEX_CONTEXT_WINDOW = 1_000_000;
export const GEMINI_CONTEXT_WINDOW = 1_048_576;
+export const GROK_CONTEXT_WINDOW = 256_000;
// Keep in sync with server/lib/stageRunner.js.
const KNOWN_MODEL_CONTEXT_WINDOWS = Object.freeze([
@@ -39,6 +40,7 @@ export const knownProviderContextWindow = (provider) => {
const command = String(provider?.command || '').toLowerCase();
if (id === 'codex' || id === 'codex-tui' || command === 'codex') return CODEX_CONTEXT_WINDOW;
if (id === 'antigravity-cli' || id === 'antigravity-tui' || command === 'agy') return GEMINI_CONTEXT_WINDOW;
+ if (id === 'grok-cli' || id === 'grok-tui' || command === 'grok') return GROK_CONTEXT_WINDOW;
return null;
};
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index 4ba67e8479..27316fc67f 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -310,6 +310,8 @@ describe('effectiveModelContextWindow', () => {
it('uses canonical provider windows for configured-default process providers', () => {
expect(effectiveModelContextWindow({ id: 'codex-tui', type: 'tui', command: 'codex' }, CODEX_CONFIGURED_DEFAULT)).toBe(1_000_000);
expect(effectiveModelContextWindow({ id: 'antigravity-cli', type: 'cli', command: 'agy' }, ANTIGRAVITY_CONFIGURED_DEFAULT)).toBe(1_048_576);
+ expect(effectiveModelContextWindow({ id: 'grok-cli', type: 'cli', command: 'grok' }, 'grok-build')).toBe(256_000);
+ expect(effectiveModelContextWindow({ id: 'grok-tui', type: 'tui', command: 'grok' }, 'grok-build')).toBe(256_000);
});
it('matches the server planner for local and cloud api defaults', () => {
diff --git a/data.reference/providers.json b/data.reference/providers.json
index 637c7b1e27..6b8766255e 100644
--- a/data.reference/providers.json
+++ b/data.reference/providers.json
@@ -247,6 +247,59 @@
"timeout": 300000,
"enabled": false,
"envVars": {}
+ },
+ "grok": {
+ "id": "grok",
+ "name": "xAI Grok",
+ "type": "api",
+ "endpoint": "https://api.x.ai/v1",
+ "apiKey": "",
+ "models": ["grok-4", "grok-3", "grok-3-mini", "grok-code-fast-1"],
+ "defaultModel": "grok-4",
+ "lightModel": "grok-3-mini",
+ "mediumModel": "grok-3",
+ "heavyModel": "grok-4",
+ "fallbackProvider": null,
+ "timeout": 300000,
+ "enabled": false,
+ "envVars": {},
+ "secretEnvVars": []
+ },
+ "grok-cli": {
+ "id": "grok-cli",
+ "name": "Grok Build CLI",
+ "type": "cli",
+ "command": "grok",
+ "args": [],
+ "models": ["grok-build"],
+ "defaultModel": "grok-build",
+ "lightModel": "grok-build",
+ "mediumModel": "grok-build",
+ "heavyModel": "grok-build",
+ "contextWindow": 256000,
+ "timeout": 300000,
+ "enabled": false,
+ "envVars": {},
+ "secretEnvVars": []
+ },
+ "grok-tui": {
+ "id": "grok-tui",
+ "name": "Grok Build TUI",
+ "type": "tui",
+ "command": "grok",
+ "args": [],
+ "models": ["grok-build"],
+ "defaultModel": "grok-build",
+ "lightModel": "grok-build",
+ "mediumModel": "grok-build",
+ "heavyModel": "grok-build",
+ "contextWindow": 256000,
+ "timeout": 600000,
+ "enabled": false,
+ "envVars": {},
+ "secretEnvVars": [],
+ "tuiPromptDelayMs": 2500,
+ "tuiIdleTimeoutMs": 180000
}
}
}
diff --git a/scripts/migrations/185-grok-providers.js b/scripts/migrations/185-grok-providers.js
new file mode 100644
index 0000000000..af1478e152
--- /dev/null
+++ b/scripts/migrations/185-grok-providers.js
@@ -0,0 +1,127 @@
+/**
+ * Ship the xAI "Grok" provider trio (API + Grok Build CLI + TUI) to existing installs.
+ *
+ * Background: issue-2336. xAI's Grok Build exposes an OpenAI-compatible chat API
+ * (https://api.x.ai/v1) plus a terminal coding agent (`grok`). PortOS adds three
+ * provider entries: `grok` (api), `grok-cli` (headless one-shot), and `grok-tui`
+ * (interactive PTY). The CLI/TUI argv conventions live in server/lib/grok.js
+ * (grok reads its prompt from `--prompt-file`, not raw stdin).
+ *
+ * `setup-data.js` merges *missing* provider entries from data.reference, but only
+ * when an install re-runs setup. This migration delivers the providers on a plain
+ * server restart too, and is the canonical path for deployed installs to pick
+ * them up. Purely additive: brand-new ids, so there's no rename or pinned-id
+ * rewrite — existing keys are left untouched (idempotent).
+ *
+ * Kept in lockstep with data.reference/providers.json and
+ * server/lib/aiToolkit/defaults/providers.sample.json. Frozen here as the
+ * historical record this migration installs; later default changes ride their
+ * own migrations rather than mutating this one.
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+
+const PROVIDERS_REL_PATH = 'data/providers.json';
+
+const GROK_API = {
+ id: 'grok',
+ name: 'xAI Grok',
+ type: 'api',
+ endpoint: 'https://api.x.ai/v1',
+ apiKey: '',
+ models: ['grok-4', 'grok-3', 'grok-3-mini', 'grok-code-fast-1'],
+ defaultModel: 'grok-4',
+ lightModel: 'grok-3-mini',
+ mediumModel: 'grok-3',
+ heavyModel: 'grok-4',
+ fallbackProvider: null,
+ timeout: 300000,
+ enabled: false,
+ envVars: {},
+ secretEnvVars: [],
+};
+
+const GROK_CLI = {
+ id: 'grok-cli',
+ name: 'Grok Build CLI',
+ type: 'cli',
+ command: 'grok',
+ args: [],
+ models: ['grok-build'],
+ defaultModel: 'grok-build',
+ lightModel: 'grok-build',
+ mediumModel: 'grok-build',
+ heavyModel: 'grok-build',
+ contextWindow: 256000,
+ timeout: 300000,
+ enabled: false,
+ envVars: {},
+ secretEnvVars: [],
+};
+
+const GROK_TUI = {
+ id: 'grok-tui',
+ name: 'Grok Build TUI',
+ type: 'tui',
+ command: 'grok',
+ args: [],
+ models: ['grok-build'],
+ defaultModel: 'grok-build',
+ lightModel: 'grok-build',
+ mediumModel: 'grok-build',
+ heavyModel: 'grok-build',
+ contextWindow: 256000,
+ timeout: 600000,
+ enabled: false,
+ envVars: {},
+ secretEnvVars: [],
+ tuiPromptDelayMs: 2500,
+ tuiIdleTimeoutMs: 180000,
+};
+
+export default {
+ async up({ rootDir }) {
+ const providersPath = join(rootDir, PROVIDERS_REL_PATH);
+ const raw = await readFile(providersPath, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) {
+ console.log(`📄 ${PROVIDERS_REL_PATH} not present — skipping (fresh install seeds Grok from data.reference)`);
+ return;
+ }
+
+ let config;
+ try {
+ config = JSON.parse(raw);
+ } catch (err) {
+ console.log(`⚠️ ${PROVIDERS_REL_PATH}: invalid JSON, skipping (${err.message})`);
+ return;
+ }
+
+ if (!config || typeof config !== 'object' || !config.providers || typeof config.providers !== 'object') {
+ console.log(`⚠️ ${PROVIDERS_REL_PATH}: unexpected shape, skipping`);
+ return;
+ }
+
+ const providers = config.providers;
+ let changed = false;
+
+ for (const def of [GROK_API, GROK_CLI, GROK_TUI]) {
+ if (!providers[def.id]) {
+ // structuredClone fully detaches the frozen shipped def (nested arrays/
+ // objects included) so a later mutation of the install can't corrupt it.
+ providers[def.id] = structuredClone(def);
+ changed = true;
+ console.log(`📝 ${PROVIDERS_REL_PATH}: added ${def.id} provider`);
+ }
+ }
+
+ if (changed) {
+ await writeFile(providersPath, `${JSON.stringify(config, null, 2)}\n`);
+ } else {
+ console.log(`✅ ${PROVIDERS_REL_PATH}: Grok providers already present — no change`);
+ }
+ },
+};
diff --git a/scripts/migrations/185-grok-providers.test.js b/scripts/migrations/185-grok-providers.test.js
new file mode 100644
index 0000000000..a8f8efe250
--- /dev/null
+++ b/scripts/migrations/185-grok-providers.test.js
@@ -0,0 +1,120 @@
+/**
+ * Test for migration 185 — add the xAI Grok provider trio (API + Grok Build
+ * CLI + TUI) to existing installs. Picked up by server/vitest.config.js's
+ * `../scripts/**\/*.test.js` glob.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration from './185-grok-providers.js';
+
+const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+
+describe('migration 185 — Grok providers', () => {
+ let rootDir;
+ let providersPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-185-'));
+ mkdirSync(join(rootDir, 'data'), { recursive: true });
+ providersPath = join(rootDir, 'data/providers.json');
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('adds the api, cli, and tui Grok providers to an existing install', async () => {
+ writeJson(providersPath, {
+ activeProvider: 'claude-code',
+ providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },
+ });
+
+ await migration.up({ rootDir });
+
+ const out = readJson(providersPath);
+
+ const api = out.providers.grok;
+ expect(api.type).toBe('api');
+ expect(api.endpoint).toBe('https://api.x.ai/v1');
+ expect(api.defaultModel).toBe('grok-4');
+ expect(api.enabled).toBe(false);
+
+ const cli = out.providers['grok-cli'];
+ expect(cli.type).toBe('cli');
+ expect(cli.command).toBe('grok');
+ expect(cli.defaultModel).toBe('grok-build');
+
+ const tui = out.providers['grok-tui'];
+ expect(tui.type).toBe('tui');
+ expect(tui.command).toBe('grok');
+ expect(tui.tuiPromptDelayMs).toBe(2500);
+
+ // unrelated providers + active provider untouched
+ expect(out.providers['claude-code']).toBeDefined();
+ expect(out.activeProvider).toBe('claude-code');
+ });
+
+ it('does not overwrite a user-customized grok entry', async () => {
+ writeJson(providersPath, {
+ providers: {
+ grok: { id: 'grok', type: 'api', endpoint: 'https://api.x.ai/v1', enabled: true, apiKey: 'sk-secret', defaultModel: 'grok-3' },
+ },
+ });
+
+ await migration.up({ rootDir });
+
+ const out = readJson(providersPath);
+ // existing entry preserved untouched
+ expect(out.providers.grok.enabled).toBe(true);
+ expect(out.providers.grok.apiKey).toBe('sk-secret');
+ expect(out.providers.grok.defaultModel).toBe('grok-3');
+ // the still-missing CLI/TUI siblings are added alongside it
+ expect(out.providers['grok-cli']).toBeDefined();
+ expect(out.providers['grok-tui']).toBeDefined();
+ });
+
+ it('deep-copies shipped arrays/objects so mutating the install cannot corrupt the frozen defaults', async () => {
+ writeJson(providersPath, { providers: {} });
+ await migration.up({ rootDir });
+ const first = readJson(providersPath);
+ first.providers.grok.models.push('mutated');
+
+ // A second install run must still ship the pristine model list.
+ const rootDir2 = mkdtempSync(join(tmpdir(), 'migration-185-b-'));
+ mkdirSync(join(rootDir2, 'data'), { recursive: true });
+ const providersPath2 = join(rootDir2, 'data/providers.json');
+ writeJson(providersPath2, { providers: {} });
+ await migration.up({ rootDir: rootDir2 });
+ expect(readJson(providersPath2).providers.grok.models).not.toContain('mutated');
+ rmSync(rootDir2, { recursive: true, force: true });
+ });
+
+ it('is idempotent — a second run makes no changes', async () => {
+ writeJson(providersPath, {
+ providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },
+ });
+
+ await migration.up({ rootDir });
+ const afterFirst = readFileSync(providersPath, 'utf-8');
+ await migration.up({ rootDir });
+ expect(readFileSync(providersPath, 'utf-8')).toBe(afterFirst);
+ });
+
+ it('is a no-op when data/providers.json does not exist (fresh install)', async () => {
+ await migration.up({ rootDir });
+ expect(existsSync(providersPath)).toBe(false);
+ });
+
+ it('does not modify the file on invalid JSON', async () => {
+ writeFileSync(providersPath, '{ not valid json');
+ const before = readFileSync(providersPath, 'utf-8');
+
+ await migration.up({ rootDir });
+
+ expect(readFileSync(providersPath, 'utf-8')).toBe(before);
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index eaee830b57..cd99faf8a4 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -97,6 +97,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring the models map under `provider.ollama.models` (bare ids) for Ollama-backed OpenCode providers. Fixes --model rejection. |
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. |
+| `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint/default-model constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`/`GROK_DEFAULT_MODEL`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin), and `prepareGrokPromptFile` (Windows temp-file delivery fallback). |
| `runners.js` | Image-runner family constants. |
| `codexAssistantExtract.js` | Strip Codex CLI banner + echoed metadata from session transcript. |
| `codexCliOutput.js` | Network/system error patterns for `agentErrorAnalysis.js`. |
diff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.json
index 6e481af425..0ccc37804b 100644
--- a/server/lib/aiToolkit/defaults/providers.sample.json
+++ b/server/lib/aiToolkit/defaults/providers.sample.json
@@ -262,6 +262,59 @@
"enabled": false,
"envVars": {},
"secretEnvVars": []
+ },
+ "grok": {
+ "id": "grok",
+ "name": "xAI Grok",
+ "type": "api",
+ "endpoint": "https://api.x.ai/v1",
+ "apiKey": "",
+ "models": ["grok-4", "grok-3", "grok-3-mini", "grok-code-fast-1"],
+ "defaultModel": "grok-4",
+ "lightModel": "grok-3-mini",
+ "mediumModel": "grok-3",
+ "heavyModel": "grok-4",
+ "fallbackProvider": null,
+ "timeout": 300000,
+ "enabled": false,
+ "envVars": {},
+ "secretEnvVars": []
+ },
+ "grok-cli": {
+ "id": "grok-cli",
+ "name": "Grok Build CLI",
+ "type": "cli",
+ "command": "grok",
+ "args": [],
+ "models": ["grok-build"],
+ "defaultModel": "grok-build",
+ "lightModel": "grok-build",
+ "mediumModel": "grok-build",
+ "heavyModel": "grok-build",
+ "contextWindow": 256000,
+ "timeout": 300000,
+ "enabled": false,
+ "envVars": {},
+ "secretEnvVars": []
+ },
+ "grok-tui": {
+ "id": "grok-tui",
+ "name": "Grok Build TUI",
+ "type": "tui",
+ "command": "grok",
+ "args": [],
+ "models": ["grok-build"],
+ "defaultModel": "grok-build",
+ "lightModel": "grok-build",
+ "mediumModel": "grok-build",
+ "heavyModel": "grok-build",
+ "contextWindow": 256000,
+ "timeout": 600000,
+ "enabled": false,
+ "envVars": {},
+ "secretEnvVars": [],
+ "tuiPromptDelayMs": 2500,
+ "tuiIdleTimeoutMs": 180000
}
}
}
diff --git a/server/lib/cliProviderArgs.js b/server/lib/cliProviderArgs.js
index 83974c939f..a0bcd42ac6 100644
--- a/server/lib/cliProviderArgs.js
+++ b/server/lib/cliProviderArgs.js
@@ -13,11 +13,13 @@
* - Codex: `codex exec -` (+ `--model` when not the sentinel)
* - Antigravity: `agy --print` with prompt piped to stdin
* - Gemini CLI: legacy prompt piped to stdin (+ `-m <model>`)
+ * - Grok Build: `grok --prompt-file /dev/stdin` (+ `--model <id>`, see grok.js)
* - Claude Code: `-p -` (+ `--model <id>`)
*/
import { resolveCliModel, hasModelFlag, resolveBedrockCliModel, prefixOpencodeModel, isOpencodeCommand } from './providerModels.js';
import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from './antigravity.js';
+import { isGrokCommand, ensureGrokHeadlessArgs } from './grok.js';
/**
* Build CLI args based on provider type. Each CLI provider has different
@@ -62,6 +64,15 @@ export function buildCliArgs(provider) {
return ensureAntigravityPrintArgs(baseArgs);
}
+ // Grok Build CLI (`grok`): headless one-shot. The prompt is delivered through
+ // `--prompt-file /dev/stdin` (grok reads a single-turn prompt from a file, not
+ // raw stdin) so PortOS's existing stdin write feeds it unchanged — see grok.js.
+ // `--output-format plain` + `--permission-mode bypassPermissions` are injected
+ // there unless the user pinned their own. Model flag gated like the others.
+ if (isGrokCommand(provider?.command)) {
+ return ensureGrokHeadlessArgs(baseArgs, effectiveDefaultModel);
+ }
+
// OpenCode CLI (`opencode run`): the headless, non-interactive subcommand. It
// reads the prompt from stdin (the runner's shell-pipeline delivery, same as
// every other CLI here) and selects the model with `-m provider/model`. The
diff --git a/server/lib/cliProviderArgs.test.js b/server/lib/cliProviderArgs.test.js
index 27775ea5fe..deb130e780 100644
--- a/server/lib/cliProviderArgs.test.js
+++ b/server/lib/cliProviderArgs.test.js
@@ -105,6 +105,54 @@ describe('cliProviderArgs', () => {
});
});
+ describe('buildCliArgs — Grok Build CLI', () => {
+ it('builds a headless one-shot invocation with plain output, bypassed permissions, model, and stdin prompt file', () => {
+ const args = buildCliArgs({ id: 'grok-cli', command: 'grok', defaultModel: 'grok-build' });
+ expect(args).toEqual([
+ '--output-format', 'plain',
+ '--permission-mode', 'bypassPermissions',
+ '--model', 'grok-build',
+ '--prompt-file', '/dev/stdin',
+ ]);
+ });
+
+ it('omits the model flag when no defaultModel is set (grok uses its own default)', () => {
+ const args = buildCliArgs({ id: 'grok-cli', command: 'grok', defaultModel: null });
+ expect(args).toEqual([
+ '--output-format', 'plain',
+ '--permission-mode', 'bypassPermissions',
+ '--prompt-file', '/dev/stdin',
+ ]);
+ });
+
+ it('resolves grok by command even when the id is custom', () => {
+ const args = buildCliArgs({ id: 'my-grok', command: '/opt/homebrew/bin/grok', defaultModel: 'grok-build' });
+ expect(args).toContain('--prompt-file');
+ expect(args).toContain('/dev/stdin');
+ expect(args).toEqual(expect.arrayContaining(['--model', 'grok-build']));
+ });
+
+ it('respects a user-baked --output-format and does not inject plain', () => {
+ const args = buildCliArgs({ id: 'grok-cli', command: 'grok', args: ['--output-format', 'json'], defaultModel: 'grok-build' });
+ expect(args.filter((a) => a === '--output-format')).toHaveLength(1);
+ expect(args).toContain('json');
+ expect(args).not.toContain('plain');
+ });
+
+ it('respects a user-baked --model and does not duplicate it', () => {
+ const args = buildCliArgs({ id: 'grok-cli', command: 'grok', args: ['--model', 'grok-code-fast-1'], defaultModel: 'grok-build' });
+ expect(args.filter((a) => a === '--model')).toHaveLength(1);
+ expect(args).toContain('grok-code-fast-1');
+ expect(args).not.toContain('grok-build');
+ });
+
+ it('respects a user-baked prompt source and does not append --prompt-file', () => {
+ const args = buildCliArgs({ id: 'grok-cli', command: 'grok', args: ['-p', 'hello'], defaultModel: 'grok-build' });
+ expect(args).not.toContain('--prompt-file');
+ expect(args).not.toContain('/dev/stdin');
+ });
+ });
+
describe('stripBrokenModelFlags', () => {
it('drops dangling / empty model flags but keeps pinned ones', () => {
expect(stripBrokenModelFlags(['--model'])).toEqual([]);
diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.js
index 274303aeaf..322e289631 100644
--- a/server/lib/cliProviderRun.js
+++ b/server/lib/cliProviderRun.js
@@ -18,6 +18,7 @@
import { spawn } from 'child_process';
import { buildCliArgs } from './cliProviderArgs.js';
+import { prepareGrokPromptFile } from './grok.js';
import { buildOpencodeEnvVars } from './opencodeConfig.js';
import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from './bufferedSpawn.js';
@@ -89,7 +90,10 @@ export function runCliProviderPrompt(args = {}) {
// Clone with the per-call model as defaultModel so buildCliArgs injects the
// right --model/-m flag for this provider's CLI convention.
const effectiveProvider = { ...provider, defaultModel: model ?? provider.defaultModel };
- const spawnArgs = [...buildCliArgs(effectiveProvider), ...(Array.isArray(extraArgs) ? extraArgs : [])];
+ const builtArgs = [...buildCliArgs(effectiveProvider), ...(Array.isArray(extraArgs) ? extraArgs : [])];
+ // Grok's `--prompt-file /dev/stdin` sentinel is fed via stdin on POSIX; on
+ // Windows it's rewritten to a temp file (useStdin=false). No-op otherwise.
+ const { args: spawnArgs, useStdin, cleanup: cleanupPromptFile } = prepareGrokPromptFile(builtArgs, prompt);
return new Promise((resolve) => {
let stdout = '';
@@ -128,6 +132,7 @@ export function runCliProviderPrompt(args = {}) {
if (settled) return;
settled = true;
clearTimeout(timer);
+ cleanupPromptFile();
resolve(result);
};
@@ -149,7 +154,9 @@ export function runCliProviderPrompt(args = {}) {
// 'error' would crash the process.
child.stdin?.on('error', () => {});
try {
- child.stdin.write(prompt);
+ // When grok is delivered via a Windows temp file, the prompt is already on
+ // disk — just close stdin instead of writing it.
+ if (useStdin) child.stdin.write(prompt);
child.stdin.end();
} catch {
// Synchronous write failure (e.g. already-destroyed stdin) — let the
diff --git a/server/lib/grok.js b/server/lib/grok.js
new file mode 100644
index 0000000000..de76f25f3e
--- /dev/null
+++ b/server/lib/grok.js
@@ -0,0 +1,157 @@
+/**
+ * Per-CLI conventions for xAI's "Grok Build" coding agent (binary: `grok`).
+ *
+ * Grok Build ships three PortOS provider shapes:
+ * - `grok` (type `api`) — OpenAI-compatible chat completions at
+ * https://api.x.ai/v1, handled generically by the API runner.
+ * - `grok-cli` (type `cli`) — headless one-shot via `grok --prompt-file …`.
+ * - `grok-tui` (type `tui`) — the interactive Grok Build TUI driven over a PTY.
+ *
+ * Unlike every other PortOS CLI provider, grok's headless mode does NOT read the
+ * prompt from raw stdin — it takes a single-turn prompt from a file path
+ * (`--prompt-file <PATH>`) or an argument (`-p/--single`). To keep PortOS's
+ * existing stdin delivery (`childProcess.stdin.write(prompt)`) working unchanged
+ * at every spawn site, `buildCliArgs` points grok at `--prompt-file /dev/stdin`
+ * on POSIX — grok opens the path and reads the piped prompt. Windows has no
+ * `/dev/stdin`, so the two primary spawn helpers rewrite the sentinel to a real
+ * temp file via `prepareGrokPromptFile` (see runner.js / cliProviderRun.js).
+ *
+ * Dependency-light on purpose: imports only `providerModels.js` helpers and node
+ * builtins, mirroring `cliProviderArgs.js` so it stays importable from the
+ * standalone autofixer process.
+ */
+
+import os from 'os';
+import { writeFileSync, unlinkSync } from 'fs';
+import { join } from 'path';
+import { hasModelFlag, commandBasename } from './providerModels.js';
+
+const NOOP_CLEANUP = () => {};
+
+// True when argv contains any of `flags`, in either separated (`--flag`) or
+// joined (`--flag=value`) form. The generic scan behind the grok arg builders.
+const argvHasFlag = (args = [], flags) =>
+ args.some((a) => typeof a === 'string' && flags.some((f) => a === f || a.startsWith(`${f}=`)));
+
+export const GROK_API_ID = 'grok';
+export const GROK_CLI_ID = 'grok-cli';
+export const GROK_TUI_ID = 'grok-tui';
+export const GROK_API_ENDPOINT = 'https://api.x.ai/v1';
+// Grok Build's built-in default coding model (256K context). A valid `--model`
+// value, so we ship it as the CLI/TUI default rather than a "configured-default"
+// sentinel — grok accepts the id directly.
+export const GROK_DEFAULT_MODEL = 'grok-build';
+
+// grok reads a single-turn prompt from a file path. On POSIX we hand it
+// /dev/stdin so the existing stdin write feeds it unchanged at every spawn site.
+export const GROK_STDIN_PROMPT_PATH = '/dev/stdin';
+
+/**
+ * True when a provider command points at the Grok Build binary — the bare `grok`
+ * on PATH, an absolute/relative path to it, or an optional Windows `.exe` suffix
+ * (same matching rules as `isOpencodeCommand`/`isClaudeCommand`).
+ * @param {string|null|undefined} command
+ * @returns {boolean}
+ */
+export function isGrokCommand(command) {
+ return commandBasename(command) === 'grok';
+}
+
+/** True for the CLI (headless) Grok provider. */
+export function isGrokCliProvider(provider) {
+ return provider?.id === GROK_CLI_ID
+ || (provider?.type === 'cli' && isGrokCommand(provider?.command));
+}
+
+/** True for the TUI (interactive) Grok provider. */
+export function isGrokTuiProvider(provider) {
+ return provider?.id === GROK_TUI_ID
+ || (provider?.type === 'tui' && isGrokCommand(provider?.command));
+}
+
+// A prompt source already declared (single-turn prompt, prompt file, or JSON
+// blocks) — so we don't append a second `--prompt-file`.
+const PROMPT_SOURCE_FLAGS = ['-p', '--single', '--prompt-file', '--prompt-json'];
+// An approval/permission posture already pinned by the user.
+const PERMISSION_FLAGS = ['--permission-mode', '--always-approve'];
+// An output format already pinned.
+const OUTPUT_FORMAT_FLAGS = ['--output-format', '-o'];
+
+/**
+ * Build the headless (one-shot) argv for the Grok Build CLI. Appends, when not
+ * already pinned by the user's saved `args`:
+ * - `--output-format plain` — PortOS parses CLI stdout as plain text.
+ * - `--permission-mode bypassPermissions` — don't block file-writing agents on
+ * approval prompts (grok's analog of `claude --dangerously-skip-permissions`).
+ * - `--model <id>` — gated on no user-baked model flag.
+ * - `--prompt-file /dev/stdin` — deliver the prompt over stdin (POSIX); the
+ * spawn helper rewrites this to a temp file on Windows.
+ * @param {string[]} baseArgs - user/legacy args (already model-flag-sanitized)
+ * @param {string|null|undefined} model - defaultModel to pin, or null to omit
+ * @returns {string[]}
+ */
+export function ensureGrokHeadlessArgs(baseArgs = [], model) {
+ const out = [...baseArgs];
+ if (!argvHasFlag(out, OUTPUT_FORMAT_FLAGS)) {
+ out.push('--output-format', 'plain');
+ }
+ if (!argvHasFlag(out, PERMISSION_FLAGS)) {
+ out.push('--permission-mode', 'bypassPermissions');
+ }
+ if (model && !hasModelFlag(out)) {
+ out.push('--model', model);
+ }
+ if (!argvHasFlag(out, PROMPT_SOURCE_FLAGS)) {
+ out.push('--prompt-file', GROK_STDIN_PROMPT_PATH);
+ }
+ return out;
+}
+
+/**
+ * Ensure the interactive Grok TUI argv auto-approves tool executions so a
+ * file-writing agent isn't stranded on an approval prompt (mirrors the codex
+ * `--dangerously-bypass-approvals-and-sandbox` / antigravity
+ * `--dangerously-skip-permissions` TUI defaults). Idempotent when the user
+ * already pinned a permission posture.
+ * @param {string[]} args
+ * @returns {string[]}
+ */
+export function ensureGrokTuiArgs(args = []) {
+ const out = [...args];
+ if (!argvHasFlag(out, PERMISSION_FLAGS)) {
+ out.push('--permission-mode', 'bypassPermissions');
+ }
+ return out;
+}
+
+/**
+ * Resolve how the prompt reaches grok for a spawned headless run.
+ *
+ * POSIX: the `--prompt-file /dev/stdin` sentinel stays put and the caller feeds
+ * the prompt via stdin exactly as for every other CLI (`useStdin: true`).
+ *
+ * Windows: `/dev/stdin` doesn't exist, so write the prompt to a real temp file,
+ * rewrite the argv to point `--prompt-file` at it, and tell the caller to skip
+ * the stdin write (`useStdin: false`). `cleanup()` removes the temp file and
+ * must be invoked from the child's close/error handler.
+ *
+ * A no-op (returns the argv untouched, `useStdin: true`) for any argv that isn't
+ * the grok stdin sentinel, so it's safe to call unconditionally before a spawn.
+ * @param {string[]} args - the built argv (may contain the /dev/stdin sentinel)
+ * @param {string} prompt - the prompt text
+ * @returns {{ args: string[], useStdin: boolean, cleanup: () => void }}
+ */
+export function prepareGrokPromptFile(args, prompt) {
+ if (process.platform !== 'win32') return { args, useStdin: true, cleanup: NOOP_CLEANUP };
+ const idx = args.indexOf(GROK_STDIN_PROMPT_PATH);
+ if (idx <= 0 || args[idx - 1] !== '--prompt-file') return { args, useStdin: true, cleanup: NOOP_CLEANUP };
+ const file = join(os.tmpdir(), `grok-prompt-${process.pid}-${Date.now()}.txt`);
+ writeFileSync(file, typeof prompt === 'string' ? prompt : '', 'utf8');
+ const rewritten = [...args];
+ rewritten[idx] = file;
+ return {
+ args: rewritten,
+ useStdin: false,
+ cleanup: () => { try { unlinkSync(file); } catch { /* already gone */ } },
+ };
+}
diff --git a/server/lib/grok.test.js b/server/lib/grok.test.js
new file mode 100644
index 0000000000..2ffbd1471f
--- /dev/null
+++ b/server/lib/grok.test.js
@@ -0,0 +1,142 @@
+import { describe, it, expect, afterEach } from 'vitest';
+import { existsSync, readFileSync } from 'fs';
+
+import {
+ GROK_API_ID,
+ GROK_CLI_ID,
+ GROK_TUI_ID,
+ GROK_API_ENDPOINT,
+ GROK_DEFAULT_MODEL,
+ GROK_STDIN_PROMPT_PATH,
+ isGrokCommand,
+ isGrokCliProvider,
+ isGrokTuiProvider,
+ ensureGrokHeadlessArgs,
+ ensureGrokTuiArgs,
+ prepareGrokPromptFile,
+} from './grok.js';
+
+describe('grok — constants', () => {
+ it('exposes the expected ids, endpoint, and default model', () => {
+ expect(GROK_API_ID).toBe('grok');
+ expect(GROK_CLI_ID).toBe('grok-cli');
+ expect(GROK_TUI_ID).toBe('grok-tui');
+ expect(GROK_API_ENDPOINT).toBe('https://api.x.ai/v1');
+ expect(GROK_DEFAULT_MODEL).toBe('grok-build');
+ expect(GROK_STDIN_PROMPT_PATH).toBe('/dev/stdin');
+ });
+});
+
+describe('grok — isGrokCommand', () => {
+ it('matches the bare binary, absolute paths, and .exe', () => {
+ expect(isGrokCommand('grok')).toBe(true);
+ expect(isGrokCommand('/Users/me/.local/bin/grok')).toBe(true);
+ expect(isGrokCommand('C:\\tools\\grok.exe')).toBe(true);
+ expect(isGrokCommand('GROK')).toBe(true);
+ });
+ it('rejects non-grok commands and empty/invalid input', () => {
+ expect(isGrokCommand('claude')).toBe(false);
+ expect(isGrokCommand('grokker')).toBe(false);
+ expect(isGrokCommand('')).toBe(false);
+ expect(isGrokCommand(null)).toBe(false);
+ expect(isGrokCommand(undefined)).toBe(false);
+ });
+});
+
+describe('grok — provider predicates', () => {
+ it('identifies the cli provider by id or by cli-type command', () => {
+ expect(isGrokCliProvider({ id: 'grok-cli' })).toBe(true);
+ expect(isGrokCliProvider({ id: 'custom', type: 'cli', command: 'grok' })).toBe(true);
+ expect(isGrokCliProvider({ id: 'grok', type: 'api', command: 'grok' })).toBe(false);
+ });
+ it('identifies the tui provider by id or by tui-type command', () => {
+ expect(isGrokTuiProvider({ id: 'grok-tui' })).toBe(true);
+ expect(isGrokTuiProvider({ id: 'custom', type: 'tui', command: 'grok' })).toBe(true);
+ expect(isGrokTuiProvider({ id: 'grok-cli', type: 'cli', command: 'grok' })).toBe(false);
+ });
+});
+
+describe('grok — ensureGrokHeadlessArgs', () => {
+ it('injects plain output, permission bypass, model, and the stdin prompt file', () => {
+ expect(ensureGrokHeadlessArgs([], 'grok-build')).toEqual([
+ '--output-format', 'plain',
+ '--permission-mode', 'bypassPermissions',
+ '--model', 'grok-build',
+ '--prompt-file', '/dev/stdin',
+ ]);
+ });
+
+ it('omits --model when no model is given', () => {
+ expect(ensureGrokHeadlessArgs([], null)).toEqual([
+ '--output-format', 'plain',
+ '--permission-mode', 'bypassPermissions',
+ '--prompt-file', '/dev/stdin',
+ ]);
+ });
+
+ it('does not override a user-pinned output format, permission mode, model, or prompt source', () => {
+ const out = ensureGrokHeadlessArgs(
+ ['--output-format', 'json', '--permission-mode', 'default', '--model', 'grok-4', '--prompt-file', '/my/prompt.txt'],
+ 'grok-build',
+ );
+ expect(out.filter((a) => a === '--output-format')).toHaveLength(1);
+ expect(out.filter((a) => a === '--permission-mode')).toHaveLength(1);
+ expect(out.filter((a) => a === '--model')).toHaveLength(1);
+ expect(out.filter((a) => a === '--prompt-file')).toHaveLength(1);
+ expect(out).toContain('grok-4');
+ expect(out).not.toContain('grok-build');
+ expect(out).not.toContain('/dev/stdin');
+ });
+
+ it('treats --always-approve as an existing permission posture', () => {
+ const out = ensureGrokHeadlessArgs(['--always-approve'], 'grok-build');
+ expect(out).not.toContain('--permission-mode');
+ expect(out).toContain('--always-approve');
+ });
+});
+
+describe('grok — ensureGrokTuiArgs', () => {
+ it('adds bypassPermissions by default', () => {
+ expect(ensureGrokTuiArgs([])).toEqual(['--permission-mode', 'bypassPermissions']);
+ });
+ it('is idempotent when a permission posture is already pinned', () => {
+ expect(ensureGrokTuiArgs(['--permission-mode', 'auto'])).toEqual(['--permission-mode', 'auto']);
+ expect(ensureGrokTuiArgs(['--always-approve'])).toEqual(['--always-approve']);
+ });
+});
+
+describe('grok — prepareGrokPromptFile', () => {
+ const realPlatform = process.platform;
+ const setPlatform = (p) => Object.defineProperty(process, 'platform', { value: p, configurable: true });
+ afterEach(() => setPlatform(realPlatform));
+
+ it('is a stdin no-op on POSIX (prompt delivered via /dev/stdin)', () => {
+ setPlatform('darwin');
+ const args = ['--prompt-file', '/dev/stdin'];
+ const res = prepareGrokPromptFile(args, 'hello');
+ expect(res.useStdin).toBe(true);
+ expect(res.args).toBe(args);
+ });
+
+ it('is a no-op for a non-grok argv even on Windows', () => {
+ setPlatform('win32');
+ const args = ['-p', '-'];
+ const res = prepareGrokPromptFile(args, 'hello');
+ expect(res.useStdin).toBe(true);
+ expect(res.args).toEqual(['-p', '-']);
+ });
+
+ it('writes a temp file and rewrites the sentinel on Windows', () => {
+ setPlatform('win32');
+ const args = ['--output-format', 'plain', '--prompt-file', '/dev/stdin'];
+ const res = prepareGrokPromptFile(args, 'my prompt body');
+ expect(res.useStdin).toBe(false);
+ const idx = res.args.indexOf('--prompt-file') + 1;
+ const file = res.args[idx];
+ expect(file).not.toBe('/dev/stdin');
+ expect(existsSync(file)).toBe(true);
+ expect(readFileSync(file, 'utf8')).toBe('my prompt body');
+ res.cleanup();
+ expect(existsSync(file)).toBe(false);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index fa008563a8..e4d8304c4c 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -86,6 +86,7 @@ export * from './cliProviderRun.js';
export * from './codexAssistantExtract.js';
export * from './codexCliOutput.js';
export * from './contextBudget.js';
+export * from './grok.js';
export * from './hfToken.js';
export * from './hfErrors.js';
export * from './hfCache.js';
diff --git a/server/lib/providerModels.js b/server/lib/providerModels.js
index 2993bfd2dd..85ec908f2a 100644
--- a/server/lib/providerModels.js
+++ b/server/lib/providerModels.js
@@ -8,6 +8,21 @@ export const ANTIGRAVITY_CONFIGURED_DEFAULT = 'antigravity-configured-default';
export const isCodexConfiguredDefault = (model) => model === CODEX_CONFIGURED_DEFAULT;
+/**
+ * Normalize a provider `command` to its lowercase binary basename, stripping any
+ * directory prefix and a Windows `.exe` suffix — e.g. `/opt/homebrew/bin/Grok.exe`
+ * → `grok`. Returns `''` for empty/non-string input. The shared primitive behind
+ * `isClaudeCommand`/`isOpencodeCommand`/`isGrokCommand` so the split/pop/case/.exe
+ * rule lives in exactly one place. (Only `.exe` is stripped, matching the runner's
+ * `shell:false` spawn path — a `.cmd`/`.bat` shim isn't directly spawnable.)
+ * @param {string|null|undefined} command
+ * @returns {string}
+ */
+export function commandBasename(command) {
+ if (typeof command !== 'string' || command === '') return '';
+ return command.split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '');
+}
+
/**
* Returns the model string to pass to a CLI's --model flag, or null if the
* caller should omit --model entirely (Codex sentinel case — the CLI will use
@@ -29,9 +44,7 @@ export const resolveCliModel = (model) => isCodexConfiguredDefault(model) ? null
* @returns {boolean}
*/
export function isOpencodeCommand(command) {
- if (typeof command !== 'string' || command === '') return false;
- const base = command.split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '');
- return base === 'opencode';
+ return commandBasename(command) === 'opencode';
}
/**
@@ -213,10 +226,11 @@ export function hasModelFlag(args) {
* @returns {boolean}
*/
export function isClaudeCommand(command) {
+ // An empty/blank command also counts as Claude: `buildCliSpawnConfig`'s default
+ // branch and the TUI `inferTuiCommand` fallback both resolve a blank command to
+ // `claude` — a policy that differs from the other predicates, so it stays here.
if (command == null || command === '') return true;
- if (typeof command !== 'string') return false;
- const base = command.split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '');
- return base === 'claude';
+ return commandBasename(command) === 'claude';
}
/**
diff --git a/server/lib/providerModels.test.js b/server/lib/providerModels.test.js
index a646165f16..b27e23f72e 100644
--- a/server/lib/providerModels.test.js
+++ b/server/lib/providerModels.test.js
@@ -16,10 +16,27 @@ import {
isClaudeCommand,
isOllamaClaudeProvider,
applyLeanClaudeArgs,
- LEAN_CLAUDE_ARGS
+ LEAN_CLAUDE_ARGS,
+ commandBasename
} from './providerModels.js';
describe('providerModels', () => {
+ describe('commandBasename', () => {
+ it('strips directory prefixes, lowercases, and drops a .exe suffix', () => {
+ expect(commandBasename('grok')).toBe('grok');
+ expect(commandBasename('/opt/homebrew/bin/Grok')).toBe('grok');
+ expect(commandBasename('C:\\tools\\GROK.exe')).toBe('grok');
+ expect(commandBasename('./bin/opencode')).toBe('opencode');
+ });
+
+ it('returns empty string for empty/non-string input', () => {
+ expect(commandBasename('')).toBe('');
+ expect(commandBasename(null)).toBe('');
+ expect(commandBasename(undefined)).toBe('');
+ expect(commandBasename(42)).toBe('');
+ });
+ });
+
describe('isCodexConfiguredDefault', () => {
it('matches the sentinel exactly', () => {
expect(isCodexConfiguredDefault(CODEX_CONFIGURED_DEFAULT)).toBe(true);
diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.js
index 660298b783..d3619f7170 100644
--- a/server/lib/tuiHandshake.js
+++ b/server/lib/tuiHandshake.js
@@ -14,6 +14,7 @@
import { resolveCliModel, hasModelFlag, resolveBedrockCliModel, prefixOpencodeModel, isOpencodeCommand } from './providerModels.js';
import { ensureAntigravityTuiArgs, isAntigravityCommand } from './antigravity.js';
+import { ensureGrokTuiArgs, isGrokCommand } from './grok.js';
// ─── Paste handshake constants ────────────────────────────────────────────
@@ -707,6 +708,9 @@ export function applyCommandDefaults(command, args) {
if (isAntigravityCommand(command)) {
return ensureAntigravityTuiArgs(args);
}
+ if (isGrokCommand(command)) {
+ return ensureGrokTuiArgs(args);
+ }
return args;
}
diff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.js
index e278f5d750..7f84220bb2 100644
--- a/server/lib/tuiHandshake.test.js
+++ b/server/lib/tuiHandshake.test.js
@@ -439,6 +439,12 @@ describe('tuiHandshake.applyCommandDefaults', () => {
expect(result).not.toBe(args);
expect(args).toEqual(['exec', '-']);
});
+
+ it('adds Grok TUI permission bypass and is idempotent when already pinned', () => {
+ expect(applyCommandDefaults('grok', [])).toEqual(['--permission-mode', 'bypassPermissions']);
+ const pinned = ['--permission-mode', 'auto'];
+ expect(applyCommandDefaults('grok', pinned)).toEqual(['--permission-mode', 'auto']);
+ });
});
describe('tuiHandshake.buildTuiInvocation', () => {
@@ -502,6 +508,13 @@ describe('tuiHandshake.buildTuiInvocation', () => {
expect(buildTuiInvocation(provider, '').args).toEqual(['-p', '-']);
});
+ it('injects Grok TUI permission bypass and appends --model', () => {
+ const provider = { id: 'grok-tui', command: 'grok', args: [] };
+ const out = buildTuiInvocation(provider, 'grok-build');
+ expect(out.command).toBe('grok');
+ expect(out.args).toEqual(['--permission-mode', 'bypassPermissions', '--model', 'grok-build']);
+ });
+
it('namespaces the Ollama model under ollama/ for an OpenCode TUI', () => {
const provider = { id: 'opencode-ollama-tui', command: 'opencode', args: [], ollamaBacked: true };
const out = buildTuiInvocation(provider, 'qwen2.5:7b');
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 06ffbbeaa7..5ee13fb30d 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -26,6 +26,7 @@ import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/antigravity.js';
+import { isGrokCommand, ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../lib/grok.js';
import { resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, applyLeanClaudeArgs } from '../lib/providerModels.js';
import { agentGuardEnv } from '../lib/agentGuard/index.js';
import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';
@@ -303,6 +304,21 @@ export function buildCliSpawnConfig(provider, model, settingsEnv = {}, { systemP
};
}
+ // Grok Build CLI (`grok`): headless one-shot agent. Reads the combined
+ // contract+task prompt from `--prompt-file /dev/stdin` (rewritten to a temp
+ // file on Windows at the spawn site — prepareGrokPromptFile), bypasses approval
+ // prompts, and emits plain text (the live-output handler falls through to its
+ // default text path, like OpenCode). grok is a non-Claude command, so
+ // agentLifecycle keeps the operating contract in the stdin prompt (no
+ // system-prompt-file split) — matching codex/antigravity/opencode.
+ if (isGrokCommand(provider?.command)) {
+ return {
+ command: provider?.command || 'grok',
+ args: ensureGrokHeadlessArgs(provider?.args || [], effectiveModel),
+ stdinMode: 'prompt',
+ };
+ }
+
// Default: Claude Code CLI. applyLeanClaudeArgs adds `--bare
// --strict-mcp-config` for Ollama-backed claude sessions (no-op otherwise,
// idempotent against user-baked flags); the system-prompt contract file
@@ -434,7 +450,10 @@ export async function spawnDirectly({
// bare name → spawn ENOENT (errno -4058) → startup-failure. Mirrors the
// working "Run Prompt" path (server/services/runner.js); resolved against
// childEnv so a provider PATH override is honored. See issue #2243.
- const { command: spawnCommand, args: spawnArgs } = prepareCliSpawn(cliConfig.command, cliConfig.args, childEnv);
+ // Grok's `--prompt-file /dev/stdin` is fed via stdin on POSIX; on Windows it's
+ // rewritten to a temp file (useStdin=false). No-op for every other provider.
+ const { args: deliveredArgs, useStdin: writePromptToStdin, cleanup: cleanupPromptFile } = prepareGrokPromptFile(cliConfig.args, prompt);
+ const { command: spawnCommand, args: spawnArgs } = prepareCliSpawn(cliConfig.command, deliveredArgs, childEnv);
const claudeProcess = spawn(spawnCommand, spawnArgs, {
cwd,
@@ -453,7 +472,7 @@ export async function spawnDirectly({
prompt: (task.description || '').substring(0, 500)
});
- claudeProcess.stdin.write(prompt);
+ if (writePromptToStdin) claudeProcess.stdin.write(prompt);
claudeProcess.stdin.end();
activeAgents.set(agentId, {
@@ -581,6 +600,7 @@ export async function spawnDirectly({
// completeAgent/completeAgentRun would crash the process, so wrap the body.
try {
clearTimeout(initializationTimeout);
+ cleanupPromptFile();
console.error(`❌ Agent ${agentId} spawn error: ${err.message}`);
// Release execution lane
@@ -622,6 +642,7 @@ export async function spawnDirectly({
let laneReleased = false;
try {
clearTimeout(initializationTimeout);
+ cleanupPromptFile();
const success = code === 0;
const agentData = activeAgents.get(agentId);
const duration = Date.now() - (agentData?.startedAt || Date.now());
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index f54ff415bd..a97574404e 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -224,6 +224,22 @@ describe('buildCliSpawnConfig', () => {
expect(config.args).toEqual(['run', '-m', 'ollama/custom']);
});
+ it('runs `grok` headless with plain output, permission bypass, model, and stdin prompt file', () => {
+ const config = buildCliSpawnConfig({ id: 'grok-cli', command: 'grok', args: [] }, 'grok-build');
+ expect(config.command).toBe('grok');
+ expect(config.stdinMode).toBe('prompt');
+ expect(config.args).toEqual([
+ '--output-format', 'plain',
+ '--permission-mode', 'bypassPermissions',
+ '--model', 'grok-build',
+ '--prompt-file', '/dev/stdin',
+ ]);
+ // Grok is non-Claude, so no claude-only flags leak in.
+ expect(config.args).not.toContain('--dangerously-skip-permissions');
+ expect(config.args).not.toContain('--print');
+ expect(config.args).not.toContain('--append-system-prompt-file');
+ });
+
it('adds lean-mode flags and the system-prompt file for an Ollama-backed claude CLI', () => {
const config = buildCliSpawnConfig(
{ id: 'claude-ollama', command: 'claude', ollamaBacked: true },
diff --git a/server/services/askService.js b/server/services/askService.js
index 0133107b4a..a5ce37618b 100644
--- a/server/services/askService.js
+++ b/server/services/askService.js
@@ -33,6 +33,7 @@ import { tokenize as bm25Tokenize, STOP_WORDS } from '../lib/bm25.js';
import { VALID_MODES as STORAGE_VALID_MODES } from './askConversations.js';
import { resolveCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand } from '../lib/providerModels.js';
import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/antigravity.js';
+import { isGrokCommand, ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../lib/grok.js';
import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';
// Re-export so the route can keep importing modes via askService — but
@@ -555,7 +556,7 @@ async function* streamCompletion(provider, model, prompt, signal) {
// sources + history are concatenated, which exceeds OS argv limits
// (especially on Windows ~32k).
const { spawn } = await import('child_process');
- const args = isAntigravityCliProvider(provider)
+ let args = isAntigravityCliProvider(provider)
? ensureAntigravityPrintArgs(provider.args || [])
: [...(provider.args || [])];
// OpenCode runs headless via the `run` subcommand (reads the prompt from
@@ -574,12 +575,19 @@ async function* streamCompletion(provider, model, prompt, signal) {
// OpenCode addresses its Ollama model as `ollama/<id>`; respect a user-baked
// -m/--model pin (mirrors buildCliArgs) rather than duplicating the flag.
if (cliModel && !hasModelFlag(args)) args.push('--model', prefixOpencodeModel(provider, cliModel));
+ } else if (isGrokCommand(provider?.command)) {
+ // Grok reads its prompt from --prompt-file /dev/stdin and needs plain output
+ // + permission bypass; ensureGrokHeadlessArgs adds them (gated on user pins).
+ args = ensureGrokHeadlessArgs(args, cliModel);
} else if (cliModel) {
args.push('--model', cliModel);
}
+ // Grok's /dev/stdin sentinel is fed via stdin on POSIX; on Windows it's
+ // rewritten to a temp file (writePromptToStdin=false). No-op otherwise.
+ const { args: deliveredArgs, useStdin: writePromptToStdin, cleanup: cleanupPromptFile } = prepareGrokPromptFile(args, prompt);
const out = await new Promise((resolve, reject) => {
let buf = '';
- const child = spawn(provider.command, args, {
+ const child = spawn(provider.command, deliveredArgs, {
env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; return e; })(),
stdio: ['pipe', 'pipe', 'pipe'],
shell: false,
@@ -595,6 +603,7 @@ async function* streamCompletion(provider, model, prompt, signal) {
const cleanup = () => {
if (timer) { clearTimeout(timer); timer = null; }
signal?.removeEventListener('abort', onAbort);
+ cleanupPromptFile();
};
const settle = (fn, value) => {
if (settled) return;
@@ -629,7 +638,10 @@ async function* streamCompletion(provider, model, prompt, signal) {
// Pipe the prompt in via stdin so we never blow the OS argv limit on
// long retrieval-augmented prompts.
child.stdin.on('error', () => { /* child may close stdin first; the close handler resolves */ });
- child.stdin.end(prompt);
+ // When grok is delivered via a Windows temp file the prompt is already on
+ // disk — just close stdin instead of writing it.
+ if (writePromptToStdin) child.stdin.end(prompt);
+ else child.stdin.end();
});
yield out;
}
diff --git a/server/services/askService.test.js b/server/services/askService.test.js
index 6afadff038..89e3772500 100644
--- a/server/services/askService.test.js
+++ b/server/services/askService.test.js
@@ -352,6 +352,44 @@ describe('runAsk', () => {
expect(args[modelIdx + 1]).toBe('o4-mini');
});
+ it('runs `grok` headless with plain output, permission bypass, model, and stdin prompt file', async () => {
+ providers.getActiveProvider.mockResolvedValue({
+ id: 'grok-cli',
+ type: 'cli',
+ enabled: true,
+ command: 'grok',
+ args: [],
+ defaultModel: 'grok-build',
+ timeout: 5000,
+ });
+
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.stdin = { on: vi.fn(), end: vi.fn(), write: vi.fn() };
+ child.kill = vi.fn();
+ setImmediate(() => {
+ child.stdout.emit('data', Buffer.from('answer text'));
+ child.emit('close', 0);
+ });
+ spawn.mockReturnValue(child);
+
+ const events = [];
+ for await (const evt of askService.runAsk({ question: 'test question' })) {
+ events.push(evt);
+ }
+
+ const [, args] = spawn.mock.calls.at(-1);
+ expect(args).toEqual([
+ '--output-format', 'plain',
+ '--permission-mode', 'bypassPermissions',
+ '--model', 'grok-build',
+ '--prompt-file', '/dev/stdin',
+ ]);
+ // POSIX delivery: the prompt is piped in via stdin.
+ expect(child.stdin.end).toHaveBeenCalled();
+ });
+
it('runs `opencode run --model ollama/<id>` for an OpenCode Ollama provider', async () => {
providers.getActiveProvider.mockResolvedValue({
id: 'opencode-ollama',
diff --git a/server/services/runner.js b/server/services/runner.js
index 87c7d70852..b12bf8d539 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -9,6 +9,7 @@ import { atomicWrite, ensureDir, tryReadFile } from '../lib/fileUtils.js';
import { hasModelFlag, extractBakedModel } from '../lib/providerModels.js';
import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';
import { buildCliArgs } from '../lib/cliProviderArgs.js';
+import { prepareGrokPromptFile } from '../lib/grok.js';
import { agentGuardEnv } from '../lib/agentGuard/index.js';
import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from '../lib/bufferedSpawn.js';
@@ -200,8 +201,13 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
};
// Build provider-specific args for stdin-based prompt delivery
- const args = buildCliArgs(provider);
- console.log(`🚀 Executing CLI: ${provider.command} (${prompt.length} chars via stdin)`);
+ const builtArgs = buildCliArgs(provider);
+ // Grok reads its prompt from `--prompt-file`; on POSIX that's /dev/stdin (fed
+ // by the stdin write below), on Windows a real temp file (no /dev/stdin). This
+ // rewrites the argv + tells us whether to still write stdin. No-op for every
+ // other provider. cleanupPromptFile removes any temp file after the run.
+ const { args, useStdin, cleanup: cleanupPromptFile } = prepareGrokPromptFile(builtArgs, prompt);
+ console.log(`🚀 Executing CLI: ${provider.command} (${prompt.length} chars via ${useStdin ? 'stdin' : 'prompt-file'})`);
// Prepend the pm2 shim (agentGuardEnv) onto the final PATH so an unrestricted
// agent can't `pm2 kill` the shared daemon. See server/lib/agentGuard.
@@ -224,8 +230,10 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
windowsHide: true
});
- // Pass prompt via stdin to avoid OS argv limits
- childProcess.stdin.write(prompt);
+ // Pass prompt via stdin to avoid OS argv limits. When grok is delivered via a
+ // Windows temp file (useStdin === false) the prompt is already on disk, so
+ // just close stdin.
+ if (useStdin) childProcess.stdin.write(prompt);
childProcess.stdin.end();
// Track active run via the toolkit's declared external-run registry so its
@@ -261,6 +269,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
childProcess.on('error', async (err) => {
if (timeoutHandle) clearTimeout(timeoutHandle);
toolkit.services.runner.unregisterExternalRun(runId);
+ cleanupPromptFile();
console.error(`❌ Run ${runId} spawn error: ${err.message}`);
const metadata = {
@@ -289,6 +298,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
try {
if (timeoutHandle) clearTimeout(timeoutHandle);
toolkit.services.runner.unregisterExternalRun(runId);
+ cleanupPromptFile();
await writeFile(outputPath, output);
diff --git a/server/services/visionCli.js b/server/services/visionCli.js
index d90cf1892a..e75923abf3 100644
--- a/server/services/visionCli.js
+++ b/server/services/visionCli.js
@@ -28,6 +28,7 @@ import { writeFile, rm, mkdtemp } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
import { buildCliArgs } from '../lib/cliProviderArgs.js';
+import { prepareGrokPromptFile } from '../lib/grok.js';
import { resolveCliModel } from '../lib/providerModels.js';
import { extractCodexAssistant, extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';
import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from '../lib/bufferedSpawn.js';
@@ -111,9 +112,16 @@ export async function describeImageViaCli({
// Fresh per-call temp dir so concurrent caption runs never collide on the
// image file, and cleanup is a single recursive rm.
const dir = await mkdtemp(join(tmpdir(), 'portos-vision-'));
+ // Grok's Windows prompt-file temp (no-op elsewhere); cleaned in the finally.
+ let cleanupPromptFile = () => {};
try {
await writeFile(join(dir, IMAGE_BASENAME), bytes);
const { command, args, stdin, cwd } = buildCliVisionInvocation(provider, visionModel, dir, prompt);
+ // Grok reads its prompt from --prompt-file /dev/stdin (fed via stdin on
+ // POSIX); on Windows it's rewritten to a temp file (writePromptToStdin=false).
+ // No-op for every other provider.
+ const { args: deliveredArgs, useStdin: writePromptToStdin, cleanup } = prepareGrokPromptFile(args, stdin);
+ cleanupPromptFile = cleanup;
const childEnv = { ...process.env, ...provider?.envVars };
delete childEnv.CLAUDECODE;
@@ -131,7 +139,7 @@ export async function describeImageViaCli({
// See resolveWindowsExecutable/prepareWindowsSafeSpawn in
// server/lib/bufferedSpawn.js.
const resolvedCommand = resolveWindowsExecutable(command, undefined, childEnv) || command;
- const { command: spawnCommand, args: spawnArgs } = prepareWindowsSafeSpawn(resolvedCommand, args);
+ const { command: spawnCommand, args: spawnArgs } = prepareWindowsSafeSpawn(resolvedCommand, deliveredArgs);
const text = await new Promise((resolve, reject) => {
const child = spawnImpl(spawnCommand, spawnArgs, {
@@ -173,7 +181,9 @@ export async function describeImageViaCli({
reject(new Error(`${command} vision call exited ${code}${tail ? `: ${tail}` : ''}`));
});
- if (stdin != null) {
+ // When grok is delivered via a Windows temp file the prompt is already on
+ // disk (writePromptToStdin=false) — just close stdin.
+ if (writePromptToStdin && stdin != null) {
child.stdin?.write(stdin);
child.stdin?.end();
} else {
@@ -183,6 +193,7 @@ export async function describeImageViaCli({
return { text, finishReason: null, usage: null, reasoning: '' };
} finally {
+ cleanupPromptFile();
await rm(dir, { recursive: true, force: true }).catch(() => {});
}
}