* feat: complete architecture rewrite with Bun, OpenTUI, bash-only tools, and X Search API Major rewrite of the Grok CLI agent: - Runtime: Bun-first (removed Node.js/tsx fallbacks) - UI: Replaced Ink with OpenTUI (@opentui/react) terminal framework - Tools: Simplified to bash-only (removed text-editor, search, morph, todo, confirmation tools) - Search: Integrated X Search API and Web Search via xAI Responses API - Models: Updated to all latest Grok models (grok-4, grok-4.20-beta, grok-4-1-fast, grok-4-fast, grok-3-mini) - Agent: Streamlined agent loop with async generator streaming - Client: Dual API support (Chat Completions for tool calling, Responses API for search) - Removed MCP integration, confirmation service, token counter, Morph editor - Updated tsconfig for OpenTUI React JSX - Clean 10-file architecture in src/ Co-authored-by: Ismail Pelaseyed <homanp@users.noreply.github.com> * Fix HelpPanel rendering bug: replace <br/> with Text component - Replaced <br/> tag with <text>{" "}</text> in HelpPanel component - Ink requires all HTML-like elements to be wrapped in Text components - Fixes React reconciler error: 'Component of type br must be created inside of a Text node' Co-authored-by: Ismail Pelaseyed <homanp@users.noreply.github.com> * fix: use ref for reliable streaming content accumulation in UI - Replace fragile setState callback with contentAccRef for tracking streamed content - Save intermediate assistant content when tool calls arrive - Remove unused useTerminalDimensions import - Fix HelpPanel <br/> tag (must be inside text node in OpenTUI) Co-authored-by: Ismail Pelaseyed <homanp@users.noreply.github.com> * fix: improve UI visibility with dark theme and text wrapping - Add dark background (#0f172a) to main app, model picker, input - Set explicit text/background colors on input for visibility - Use wrapMode='word' on all text content for proper wrapping - Use children instead of content prop for user messages - Add Grok label to streaming content display Co-authored-by: Ismail Pelaseyed <homanp@users.noreply.github.com> * fix: remove wrapMode that caused garbled text rendering wrapMode='word' was corrupting character display in OpenTUI text components. Removed it from all message views and streaming display. Co-authored-by: Ismail Pelaseyed <homanp@users.noreply.github.com> * feat: rewrite UI to match OpenCode's design language - Use OpenCode's exact dark theme tokens (#0a0a0a bg, #141414 panel, #eeeeee text, #fab283 primary) - Left-border accent (┃) on user messages with primary color, matching OpenCode's SplitBorder - Panel backgrounds for user messages and tool blocks (backgroundPanel) - Home screen with centered logo + prompt (like OpenCode's home.tsx) - Session view with header, scrollable messages, prompt, footer - Inline tool results (icon + label) for simple tools - Block tool results (panel with output) for bash with >3 lines - Footer with cwd on left, model on right (matching OpenCode's footer.tsx) - Separate theme.ts with typed dark theme object - Reasoning shown in subtle left-bordered panel (like OpenCode's ReasoningPart) Co-authored-by: Ismail Pelaseyed <homanp@users.noreply.github.com> * feat: add Agent/Plan/Ask mode system with tab cycling and OpenCode home screen - Add AgentMode type (agent/plan/ask) with per-mode system prompts - Agent mode: full tool access, executes changes directly - Plan mode: read-only tools, creates implementation plans without modifying files - Ask mode: read-only tools, answers questions with context - Tab key cycles between modes (visible in prompt box) - OpenCode-style block-letter GROK logo on home screen (left=muted, right=bold) - Prompt box shows mode label + model name + provider (like OpenCode's prompt) - Shadow/bottom-edge effect below prompt (╹ + ▀ pattern from OpenCode) - Keyboard hints bar: 'tab modes · ctrl+p commands' (matches OpenCode layout) - Mode color changes left-border accent on prompt and user messages - Refactored into HomeView and SessionView components Co-authored-by: Ismail Pelaseyed <homanp@users.noreply.github.com> * feat: black and white theme, Grok brand logo, modal model picker - Theme: pure black (#000000) and white (#ffffff) only, no color accents - Logo: Grok brand symbol (stylized compass/G) next to bold 'Grok' text - Model picker: floating modal dialog overlaying the app (like OpenCode's DialogSelect) - Centered panel with dark background - Title 'Select model' + esc hint - Search placeholder - Models grouped by category (Grok 4, Grok Code, Grok 3) - Current model marked with ● - Selected item highlighted with selectedBg - Pricing shown for budget models - Mode colors changed to white/gray (monochrome) - Models grouped via MODEL_GROUPS in models.ts - Added selectedBg and selected tokens to theme Co-authored-by: Ismail Pelaseyed <homanp@users.noreply.github.com> * feat: differentiated UI, colored modes, clean logo, remove xAI labels - Remove all 'xAI' labels from model picker and prompt box - Mode colors: blue (#5c9cf5) for Agent, yellow (#e5c07b) for Plan, orange (#f5a742) for Ask - Logo: clean '✦ G R O K' text with tagline (no broken Unicode art) - Differentiated UI from OpenCode: - Home: centered logo + tagline, input with thin single-line border colored by mode, mode selector row showing all three modes with dots, model name on right - Session: top bar with model + mode instead of bordered header panel, thin separator line, user messages with colored ▸ prefix instead of left-border panels, input with colored single-line border instead of thick ┃ accent - Tool output in subtle background panels - Model picker: bordered modal instead of borderless floating panel, category headers in muted text, no 'xAI' provider label - Simplified theme: removed unused color tokens, added textDim for ultra-subtle text Co-authored-by: Ismail Pelaseyed <homanp@users.noreply.github.com> * revert: restore ┃ left-border prompt box with mode/model line and shadow edge Bring back the previous input style that was preferred: - ┃ left-border accent colored by mode (blue/yellow/orange) - Mode label + model name inside the prompt box below input - ╹/▀ shadow edge below the prompt - Hints row (tab modes · ctrl+p commands) right-aligned under prompt - Used in both home screen and session view - Keep everything else from current version (differentiated session layout, ▸ prefix messages, top bar, clean model picker, logo, mode colors) Co-authored-by: Ismail Pelaseyed <homanp@users.noreply.github.com> * feat: replicate OpenCode conversation layout Session view now matches OpenCode's session/index.tsx patterns: - Session header: # Model Name in ┃ left-border panel with backgroundPanel - User messages: ┃ left-border colored by mode, backgroundPanel fill, text inside - Tool results (inline): paddingLeft=3, icon + muted text ($ cmd, ◈ Search) - Tool results (block): ┃ left-border panel for bash output >3 lines, search results - Assistant text: paddingLeft=3, marginTop=1, plain text - Metadata line: ▣ Mode · model · duration after each assistant turn (like OpenCode's AssistantMessage final block with ▣ icon) - Reasoning: ┃ left-border panel with backgroundElement border, italic dim text - Pending tools: ~ prefix with text color - Track tool call count and elapsed time for metadata line - InlineTool component for consistent tool result formatting Co-authored-by: Ismail Pelaseyed <homanp@users.noreply.github.com> * feat: redesign model picker and slash menu modals - Remove borders, add search filtering with keyboard input - Flat model list without category sections - Blue accent color for current model highlight - Fit-to-content modals with max height cap and scroll - scrollChildIntoView for arrow key navigation - Trim logo height by removing decorative lines - Add accent color to theme Made-with: Cursor * feat: migrate to Vercel AI SDK with xAI provider - Replace custom OpenAI client with AI SDK streamText + @ai-sdk/xai - Add standalone search_web and search_x tools via chat completions - Fix follow-up messages by using isProcessingRef to avoid stale closures - Fallback message history when result.response fails after stream errors - Remove post-response status line, adjust input padding Made-with: Cursor * feat: add file tools, diff view, and markdown rendering - Add read_file, write_file, edit_file tools with diff generation - Inline diff viewer with line numbers, colored add/remove, and unmodified-lines separators (OpenCode-style) - Lightweight markdown renderer for assistant messages: headings, bold, italic, inline code, code blocks, lists, blockquotes, links - Update agent system prompts with terminal environment guidance - Install diff package for unified diff computation Made-with: Cursor * feat: add plan mode (#156) * feat: add plan mode with interactive questions UI Add generate_plan tool, structured plan types, and an OpenCode-style inline questions panel with tabbed navigation, number-key shortcuts, custom text answers, and a review/confirm tab. * fix: plan-to-agent handover, mode-scoped tools, and UI polish - Carry plan context forward when switching plan→agent mode - Restrict generate_plan tool to plan mode only - Stamp modeColor on all message types for correct per-message colors - Sanitize model-echoed role labels and raw JSON from content - Truncate tool result labels to single lines - Single-word tab labels for plan questions - Always show edit/write file results with diff - Clear agent history on mode switch * feat: add Brin contributor trust check workflow and use OpenTUI native markdown (#157) * feat: add sub-agent task delegation and UI (#159) * feat: add background agents and background bash processes (#161) Add async background delegation system (delegate, delegation_read, delegation_list) for read-only research that persists to disk and notifies the session on completion. Extend bash tool with background mode for long-running processes (dev servers, watchers) with companion process_logs, process_stop, and process_list tools. Closes #146 * feat: add prompt queuing with follow-ups UI (#162) Allow users to submit messages while the agent is processing. Queued messages display in a follow-ups panel above the prompt and are processed sequentially after the current response completes. --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: Ismail Pelaseyed <homanp@users.noreply.github.com>
Grok CLI
A conversational AI CLI tool powered by Grok with intelligent text editor capabilities and tool usage.
Features
- 🤖 Conversational AI: Natural language interface powered by Grok-3
- 📝 Smart File Operations: AI automatically uses tools to view, create, and edit files
- ⚡ Bash Integration: Execute shell commands through natural conversation
- 🔧 Automatic Tool Selection: AI intelligently chooses the right tools for your requests
- 🚀 Morph Fast Apply: Optional high-speed code editing at 4,500+ tokens/sec with 98% accuracy
- 🔌 MCP Tools: Extend capabilities with Model Context Protocol servers (Linear, GitHub, etc.)
- 💬 Interactive UI: Beautiful terminal interface built with Ink
- 🌍 Global Installation: Install and use anywhere with
bun add -g @vibe-kit/grok-cli
Installation
Prerequisites
- Bun 1.0+ (or Node.js 18+ as fallback)
- Grok API key from X.AI
- (Optional, Recommended) Morph API key for Fast Apply editing
Global Installation (Recommended)
bun add -g @vibe-kit/grok-cli
Or with npm (fallback):
npm install -g @vibe-kit/grok-cli
Local Development
git clone <repository>
cd grok-cli
bun install
bun run build
bun link
Setup
-
Get your Grok API key from X.AI
-
Set up your API key (choose one method):
Method 1: Environment Variable
export GROK_API_KEY=your_api_key_here
Method 2: .env File
cp .env.example .env
# Edit .env and add your API key
Method 3: Command Line Flag
grok --api-key your_api_key_here
Method 4: User Settings File
Create ~/.grok/user-settings.json:
{
"apiKey": "your_api_key_here"
}
-
(Optional, Recommended) Get your Morph API key from Morph Dashboard
-
Set up your Morph API key for Fast Apply editing (choose one method):
Method 1: Environment Variable
export MORPH_API_KEY=your_morph_api_key_here
Method 2: .env File
# Add to your .env file
MORPH_API_KEY=your_morph_api_key_here
Custom Base URL (Optional)
By default, the CLI uses https://api.x.ai/v1 as the Grok API endpoint. You can configure a custom endpoint if needed (choose one method):
Method 1: Environment Variable
export GROK_BASE_URL=https://your-custom-endpoint.com/v1
Method 2: Command Line Flag
grok --api-key your_api_key_here --base-url https://your-custom-endpoint.com/v1
Method 3: User Settings File
Add to ~/.grok/user-settings.json:
{
"apiKey": "your_api_key_here",
"baseURL": "https://your-custom-endpoint.com/v1"
}
Configuration Files
Grok CLI uses two types of configuration files to manage settings:
User-Level Settings (~/.grok/user-settings.json)
This file stores global settings that apply across all projects. These settings rarely change and include:
- API Key: Your Grok API key
- Base URL: Custom API endpoint (if needed)
- Default Model: Your preferred model (e.g.,
grok-code-fast-1) - Available Models: List of models you can use
Example:
{
"apiKey": "your_api_key_here",
"baseURL": "https://api.x.ai/v1",
"defaultModel": "grok-code-fast-1",
"models": [
"grok-code-fast-1",
"grok-4-latest",
"grok-3-latest",
"grok-3-fast",
"grok-3-mini-fast"
]
}
Project-Level Settings (.grok/settings.json)
This file stores project-specific settings in your current working directory. It includes:
- Current Model: The model currently in use for this project
- MCP Servers: Model Context Protocol server configurations
Example:
{
"model": "grok-3-fast",
"mcpServers": {
"linear": {
"name": "linear",
"transport": "stdio",
"command": "npx",
"args": ["@linear/mcp-server"]
}
}
}
How It Works
- Global Defaults: User-level settings provide your default preferences
- Project Override: Project-level settings override defaults for specific projects
- Directory-Specific: When you change directories, project settings are loaded automatically
- Fallback Logic: Project model → User default model → System default (
grok-code-fast-1)
This means you can have different models for different projects while maintaining consistent global settings like your API key.
Using Other API Providers
Important: Grok CLI uses OpenAI-compatible APIs. You can use any provider that implements the OpenAI chat completions standard.
Popular Providers:
- X.AI (Grok):
https://api.x.ai/v1(default) - OpenAI:
https://api.openai.com/v1 - OpenRouter:
https://openrouter.ai/api/v1 - Groq:
https://api.groq.com/openai/v1
Example with OpenRouter:
{
"apiKey": "your_openrouter_key",
"baseURL": "https://openrouter.ai/api/v1",
"defaultModel": "anthropic/claude-3.5-sonnet",
"models": [
"anthropic/claude-3.5-sonnet",
"openai/gpt-4o",
"meta-llama/llama-3.1-70b-instruct"
]
}
Usage
Interactive Mode
Start the conversational AI assistant:
grok
Or specify a working directory:
grok -d /path/to/project
Headless Mode
Process a single prompt and exit (useful for scripting and automation):
grok --prompt "show me the package.json file"
grok -p "create a new file called example.js with a hello world function"
grok --prompt "run bun test and show me the results" --directory /path/to/project
grok --prompt "complex task" --max-tool-rounds 50 # Limit tool usage for faster execution
This mode is particularly useful for:
- CI/CD pipelines: Automate code analysis and file operations
- Scripting: Integrate AI assistance into shell scripts
- Terminal benchmarks: Perfect for tools like Terminal Bench that need non-interactive execution
- Batch processing: Process multiple prompts programmatically
Tool Execution Control
By default, Grok CLI allows up to 400 tool execution rounds to handle complex multi-step tasks. You can control this behavior:
# Limit tool rounds for faster execution on simple tasks
grok --max-tool-rounds 10 --prompt "show me the current directory"
# Increase limit for very complex tasks (use with caution)
grok --max-tool-rounds 1000 --prompt "comprehensive code refactoring"
# Works with all modes
grok --max-tool-rounds 20 # Interactive mode
grok git commit-and-push --max-tool-rounds 30 # Git commands
Use Cases:
- Fast responses: Lower limits (10-50) for simple queries
- Complex automation: Higher limits (500+) for comprehensive tasks
- Resource control: Prevent runaway executions in automated environments
Model Selection
You can specify which AI model to use with the --model parameter or GROK_MODEL environment variable:
Method 1: Command Line Flag
# Use Grok models
grok --model grok-code-fast-1
grok --model grok-4-latest
grok --model grok-3-latest
grok --model grok-3-fast
# Use other models (with appropriate API endpoint)
grok --model gemini-2.5-pro --base-url https://api-endpoint.com/v1
grok --model claude-sonnet-4-20250514 --base-url https://api-endpoint.com/v1
Method 2: Environment Variable
export GROK_MODEL=grok-code-fast-1
grok
Method 3: User Settings File
Add to ~/.grok/user-settings.json:
{
"apiKey": "your_api_key_here",
"defaultModel": "grok-code-fast-1"
}
Model Priority: --model flag > GROK_MODEL environment variable > user default model > system default (grok-code-fast-1)
Command Line Options
grok [options]
Options:
-V, --version output the version number
-d, --directory <dir> set working directory
-k, --api-key <key> Grok API key (or set GROK_API_KEY env var)
-u, --base-url <url> Grok API base URL (or set GROK_BASE_URL env var)
-m, --model <model> AI model to use (e.g., grok-code-fast-1, grok-4-latest) (or set GROK_MODEL env var)
-p, --prompt <prompt> process a single prompt and exit (headless mode)
--max-tool-rounds <rounds> maximum number of tool execution rounds (default: 400)
-h, --help display help for command
Custom Instructions
You can provide custom instructions to tailor Grok's behavior to your project or globally. Grok CLI supports both project-level and global custom instructions.
Project-Level Instructions
Create a .grok/GROK.md file in your project directory to provide instructions specific to that project:
mkdir .grok
Create .grok/GROK.md with your project-specific instructions:
# Custom Instructions for This Project
Always use TypeScript for any new code files.
When creating React components, use functional components with hooks.
Prefer const assertions and explicit typing over inference where it improves clarity.
Always add JSDoc comments for public functions and interfaces.
Follow the existing code style and patterns in this project.
Global Instructions
For instructions that apply across all projects, create ~/.grok/GROK.md in your home directory:
mkdir -p ~/.grok
Create ~/.grok/GROK.md with your global instructions:
# Global Custom Instructions for Grok CLI
Always prioritize code readability and maintainability.
Use descriptive variable names and add comments for complex logic.
Follow best practices for the programming language being used.
When suggesting code changes, consider performance implications.
Priority Order
Grok will load custom instructions in the following priority order:
- Project-level (
.grok/GROK.mdin current directory) - takes highest priority - Global (
~/.grok/GROK.mdin home directory) - fallback if no project instructions exist
If both files exist, project instructions will be used. If neither exists, Grok operates with its default behavior.
The custom instructions are added to Grok's system prompt and influence its responses across all interactions in the respective context.
Morph Fast Apply (Optional)
Grok CLI supports Morph's Fast Apply model for high-speed code editing at 4,500+ tokens/sec with 98% accuracy. This is an optional feature that provides lightning-fast file editing capabilities.
Setup: Configure your Morph API key following the setup instructions above.
How It Works
When MORPH_API_KEY is configured:
edit_filetool becomes available alongside the standardstr_replace_editor- Optimized for complex edits: Use for multi-line changes, refactoring, and large modifications
- Intelligent editing: Uses abbreviated edit format with
// ... existing code ...comments - Fallback support: Standard tools remain available if Morph is unavailable
When to use each tool:
edit_file(Morph): Complex edits, refactoring, multi-line changesstr_replace_editor: Simple text replacements, single-line edits
Example Usage
With Morph Fast Apply configured, you can request complex code changes:
grok --prompt "refactor this function to use async/await and add error handling"
grok -p "convert this class to TypeScript and add proper type annotations"
The AI will automatically choose between edit_file (Morph) for complex changes or str_replace_editor for simple replacements.
MCP Tools
Grok CLI supports MCP (Model Context Protocol) servers, allowing you to extend the AI assistant with additional tools and capabilities.
Adding MCP Tools
Add a custom MCP server:
# Add an stdio-based MCP server
grok mcp add my-server --transport stdio --command "bun" --args server.js
# Add an HTTP-based MCP server
grok mcp add my-server --transport http --url "http://localhost:3000"
# Add with environment variables
grok mcp add my-server --transport stdio --command "python" --args "-m" "my_mcp_server" --env "API_KEY=your_key"
Add from JSON configuration:
grok mcp add-json my-server '{"command": "bun", "args": ["server.js"], "env": {"API_KEY": "your_key"}}'
Linear Integration Example
To add Linear MCP tools for project management:
# Add Linear MCP server
grok mcp add linear --transport sse --url "https://mcp.linear.app/sse"
This enables Linear tools like:
- Create and manage Linear issues
- Search and filter issues
- Update issue status and assignees
- Access team and project information
Managing MCP Servers
# List all configured servers
grok mcp list
# Test server connection
grok mcp test server-name
# Remove a server
grok mcp remove server-name
Available Transport Types
- stdio: Run MCP server as a subprocess (most common)
- http: Connect to HTTP-based MCP server
- sse: Connect via Server-Sent Events
Development
# Install dependencies
bun install
# Development mode
bun run dev
# Build project
bun run build
# Run linter
bun run lint
# Type check
bun run typecheck
Architecture
- Agent: Core command processing and execution logic
- Tools: Text editor and bash tool implementations
- UI: Ink-based terminal interface components
- Types: TypeScript definitions for the entire system
License
MIT