### Quick Start Commands Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Commands to install Grok and run it in interactive, headless, and agent modes. Use these to get started quickly. ```bash # Install curl -fsSL https://x.ai/cli/install.sh | bash # Interactive TUI grok # Headless (for scripts/automation) grok -p "Explain this codebase" # Agent mode (for IDE/app integration) grok agent stdio ``` -------------------------------- ### TUI usage examples with grok Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Shows common ways to start the TUI: specifying a project directory, sending an initial prompt, adding project-specific rules, and enabling auto-approve mode. ```bash # Start in a specific project grok --cwd ~/projects/my-app # Start with an initial task grok --prompt "Review this codebase and suggest improvements" # Add project-specific rules grok --rules "Always use TypeScript. Prefer functional components." # Auto-approve mode for trusted tasks grok --always-approve --prompt "Format all files" ``` -------------------------------- ### Browse docs with /docs Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/04-slash-commands.md Use /docs to browse the built-in How-to Guides, open the online Build docs, or jump to a guide by title. Bare /docs opens the How-to Guides picker, /docs web opens https://docs.x.ai/build/overview, and /docs opens a specific guide by case-insensitive title match. ```text /docs /docs web /docs Getting Started ``` -------------------------------- ### Install released binary with curl or PowerShell Source: https://github.com/xai-org/grok-build/blob/main/README.md Use these commands to install the prebuilt binary on macOS, Linux, or Windows (Git Bash or PowerShell). The first command installs on macOS/Linux/Git Bash, the second on Windows PowerShell, and the third verifies the installation. ```sh curl -fsSL https://x.ai/cli/install.sh | bash # macOS / Linux / Git Bash irm https://x.ai/cli/install.ps1 | iex # Windows PowerShell grok --version ``` -------------------------------- ### Verify installation with grok --version Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/01-getting-started.md Verifies the Grok Build installation by printing the installed version. ```bash grok --version ``` -------------------------------- ### SessionStart hook configuration Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/custom-hooks.md Example hook configuration file that runs a command when a Grok session starts. Place it at ~/.grok/hooks/session-start.json. The hook runs automatically on SessionStart after starting or restarting a session. ```json { "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "echo \"🚀 Grok session started in $(pwd)\"" } ] } ] } } ``` -------------------------------- ### Install xai-crash-handler and check previous crash Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-crash-handler/README.md Initialize the crash handler: call check_previous_crash() before install() because install() truncates last-crash.bin. Install before spawning threads or async runtime since sigaltstack is per-thread. install() creates crash_dir if missing. ```rust use std::path::PathBuf; let crash_dir = PathBuf::from("/home/user/.myapp/crash"); // check_previous_crash MUST be called before install(), because // install() opens last-crash.bin with O_TRUNC. if let Some(r) = xai_crash_handler::check_previous_crash(&crash_dir) { eprintln!("Crashed last session: {}", r.signal_name); eprintln!("Report: {}", r.report_path.display()); } // install() before any threads or async runtime — sigaltstack is per-thread. // Creates crash_dir if it does not exist. xai_crash_handler::install(xai_crash_handler::CrashHandlerConfig { app_version: env!("CARGO_PKG_VERSION").to_string(), crash_dir, }); ``` -------------------------------- ### Add marketplace and install plugin Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/09-plugins.md Adds a marketplace and installs a plugin with trust. The marketplace can be specified as GitHub shorthand, a git URL, or a local path. ```bash grok plugin marketplace add my-org/my-org-plugins # GitHub shorthand, a git URL, or a local path grok plugin install gdrive --trust ``` -------------------------------- ### Start dev server in background Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/20-background-tasks.md Instructs the agent to start the dev server with `npm run dev` in the background and continue coding. The agent runs the server with `background: true` and shows a notification when the server starts. ```text Start the dev server with `npm run dev` in the background, then implement the login form. ``` -------------------------------- ### Filesystem MCP server example Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Runs the filesystem server via npx, allowing access to the specified directory. ```toml [mcp_servers.filesystem] command = "npx" args = ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/directory"] ``` -------------------------------- ### plain output example Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/14-headless-mode.md Example of the default plain text output format, suitable for direct display or piping. ```text Here's a summary of the codebase... ``` -------------------------------- ### Install Grok CLI (latest and specific version) Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Install the latest stable version with curl, or specify a version by appending the version number to the install script command. ```bash # Install latest stable curl -fsSL https://x.ai/cli/install.sh | bash # Install a specific version curl -fsSL https://x.ai/cli/install.sh | bash -s 0.1.42 ``` -------------------------------- ### xai-grok-agent Usage Examples Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-agent/README.md Code examples demonstrating how to parse agent definitions, build agents, and discover agent definitions using the xai-grok-agent crate. ```APIDOC ## [RUST] AgentDefinition::from_file ### Description Parses an agent definition from a Markdown file with YAML frontmatter. ### Method Rust function ### Endpoint `AgentDefinition::from_file(path: impl AsRef<Path>) -> Result<Self, Error>` ### Parameters - **path** (string) - Required - Path to the agent definition file (e.g., `.grok/agents/code-reviewer.md`). ### Request Example ```rust let def = AgentDefinition::from_file(".grok/agents/code-reviewer.md")?; ``` ### Response Returns a parsed `AgentDefinition` on success, or an error if the file cannot be read or parsed. ``` ```APIDOC ## [RUST] AgentBuilder::new ### Description Creates a new `AgentBuilder` with the given working directory, optional context, and a tool notification handle. ### Method Rust function ### Endpoint `AgentBuilder::new(cwd: impl Into<PathBuf>, context: Option<...>, notification_handle: ToolNotificationHandle) -> Self` ### Parameters - **cwd** (path) - Required - The current working directory. - **context** (optional) - Optional - Additional context (type not specified in source). - **notification_handle** (ToolNotificationHandle) - Required - A handle for tool notifications. ### Request Example ```rust let builder = AgentBuilder::new(cwd, None, ToolNotificationHandle::noop()); ``` ### Response Returns a new `AgentBuilder` instance. ``` ```APIDOC ## [RUST] AgentBuilder::from_definition ### Description Sets the agent definition to use when building the agent. ### Method Rust function ### Endpoint `AgentBuilder::from_definition(self, def: AgentDefinition) -> Self` ### Parameters - **def** (AgentDefinition) - Required - The parsed agent definition. ### Request Example ```rust let builder = AgentBuilder::new(cwd, None, ToolNotificationHandle::noop()) .from_definition(def); ``` ### Response Returns the builder with the definition set. ``` ```APIDOC ## [RUST] AgentBuilder::build ### Description Builds the `Agent` from the configured parameters. ### Method Rust async function ### Endpoint `AgentBuilder::build(self) -> Result<Agent, Error>` ### Parameters None. ### Request Example ```rust let agent = builder.build().await?; ``` ### Response Returns a built `Agent` on success, or an error if building fails. ``` ```APIDOC ## [RUST] AgentBuilder::with_name ### Description Sets the name of the agent. ### Method Rust function ### Endpoint `AgentBuilder::with_name(self, name: impl Into<String>) -> Self` ### Parameters - **name** (string) - Required - The agent name. ### Request Example ```rust let builder = AgentBuilder::new(cwd, None, ToolNotificationHandle::noop()) .with_name("my-agent"); ``` ### Response Returns the builder with the name set. ``` ```APIDOC ## [RUST] AgentBuilder::with_description ### Description Sets the description of the agent. ### Method Rust function ### Endpoint `AgentBuilder::with_description(self, description: impl Into<String>) -> Self` ### Parameters - **description** (string) - Required - The agent description. ### Request Example ```rust let builder = AgentBuilder::new(cwd, None, ToolNotificationHandle::noop()) .with_description("A custom agent"); ``` ### Response Returns the builder with the description set. ``` ```APIDOC ## [RUST] AgentBuilder::with_tools ### Description Sets the list of tools available to the agent. ### Method Rust function ### Endpoint `AgentBuilder::with_tools(self, tools: Vec<ToolName>) -> Self` ### Parameters - **tools** (array of strings) - Required - List of tool names (e.g., `"read_file"`, `"grep"`). ### Request Example ```rust let builder = AgentBuilder::new(cwd, None, ToolNotificationHandle::noop()) .with_tools(vec!["read_file".into(), "grep".into()]); ``` ### Response Returns the builder with the tools set. ``` ```APIDOC ## [RUST] Agent::name ### Description Returns the name of the agent. ### Method Rust function ### Endpoint `Agent::name(&self) -> &str` ### Parameters None. ### Request Example ```rust println!("Agent: {}", agent.name()); ``` ### Response Returns the agent's name as a string slice. ``` ```APIDOC ## [RUST] Agent::system_prompt ### Description Returns the assembled system prompt for the agent. ### Method Rust function ### Endpoint `Agent::system_prompt(&self) -> &str` ### Parameters None. ### Request Example ```rust println!("Prompt: {}", agent.system_prompt()); ``` ### Response Returns the system prompt as a string slice. ``` ```APIDOC ## [RUST] Agent::tool_definitions ### Description Returns the tool definitions available to the agent. ### Method Rust async function ### Endpoint `Agent::tool_definitions(&self) -> impl Future<Output = Vec<ToolDefinition>>` ### Parameters None. ### Request Example ```rust let tool_defs = agent.tool_definitions().await; ``` ### Response Returns a vector of tool definitions. ``` ```APIDOC ## [RUST] discovery::discover ### Description Finds all agent definition files in `.grok/agents/` directories. ### Method Rust function ### Endpoint `discovery::discover(cwd: &Path) -> Vec<AgentDefinition>` ### Parameters - **cwd** (path) - Required - The current working directory to search from. ### Request Example ```rust let definitions = discovery::discover(&cwd); ``` ### Response Returns a vector of discovered `AgentDefinition` objects. ``` ```APIDOC ## [RUST] discovery::by_name ### Description Finds a specific agent by name, checking built-ins first, then user directories. ### Method Rust function ### Endpoint `discovery::by_name(name: &str) -> Option<AgentDefinition>` ### Parameters - **name** (string) - Required - The agent name to search for. ### Request Example ```rust let reviewer = discovery::by_name("code-reviewer"); ``` ### Response Returns an `Option<AgentDefinition>` - `Some` if found, `None` otherwise. ``` ```APIDOC ## [RUST] discovery::by_name_in_cwd ### Description Finds a specific agent by name with project-level priority. ### Method Rust function ### Endpoint `discovery::by_name_in_cwd(name: &str, cwd: &Path) -> Option<AgentDefinition>` ### Parameters - **name** (string) - Required - The agent name to search for. - **cwd** (path) - Required - The current working directory to search first. ### Request Example ```rust let agent = discovery::by_name_in_cwd("my-agent", &cwd); ``` ### Response Returns an `Option<AgentDefinition>` - `Some` if found, `None` otherwise. ``` -------------------------------- ### Postgres MCP server example Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Runs the Postgres server via npx, connecting to the specified database URL. ```toml [mcp_servers.postgres] command = "npx" args = ["-y", "@modelcontextprotocol/server-postgres", "postgresql://user:pass@localhost/db"] ``` -------------------------------- ### Custom MCP server example Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Runs a custom server executable with arguments and custom timeouts. ```toml [mcp_servers.my-tools] command = "/usr/local/bin/my-mcp-server" args = ["--config", "/etc/my-mcp.json"] startup_timeout_sec = 30 tool_timeout_sec = 120 ``` -------------------------------- ### Slash Commands for Quick Actions Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/01-getting-started.md Slash commands are typed in the prompt to perform quick actions. The example shows commands to switch the model, compress conversation history, toggle always-approve mode, and start a new session. ```plaintext /model grok-4.6 # Switch model /compact # Compress conversation history /always-approve # Toggle always-approve mode /new # Start a new session ``` -------------------------------- ### Install @xai-official/grok Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/npm/grok-darwin-x64/README.md Install the main package globally. The platform-specific binary is pulled automatically via optionalDependencies. ```sh npm install -g @xai-official/grok ``` -------------------------------- ### Install Grok CLI with npm Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/npm/grok/README.md Installs the Grok CLI globally via npm. ```bash npm i -g @xai-official/grok ``` -------------------------------- ### SKILL.md format example Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/08-skills.md Example SKILL.md file with YAML frontmatter and markdown instructions. The frontmatter includes name and description fields; the body contains the skill's instructions. ```markdown --- name: commit description: Create well-formatted git commits following conventional commit standards. Use when the user wants to commit changes or asks for /commit. --- # Git Commit Skill Review staged changes and create a commit with a clear, conventional message. ## Steps 1. Run `git diff --staged` to see changes 2. Summarize what changed and why 3. Create commit message following conventional commits format 4. Run `git commit -m "..."` with the message ``` -------------------------------- ### GitHub MCP server example Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Runs the GitHub server via npx, requiring a GitHub personal access token in the environment. ```toml [mcp_servers.github] command = "npx" args = ["-y", "@modelcontextprotocol/server-github"] env = { GITHUB_PERSONAL_ACCESS_TOKEN = "ghp_xxxxxxxxxxxx" } ``` -------------------------------- ### Zsh completions: generate and install (Grok-managed location) Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Alternative installation that writes the completion script to ~/.grok/completions/zsh/_grok. Requires adding the fpath and compinit lines to ~/.zshrc. ```bash mkdir -p ~/.grok/completions/zsh grok completions zsh > ~/.grok/completions/zsh/_grok ``` ```zsh fpath=("$HOME/.grok/completions/zsh" $fpath) autoload -Uz compinit compinit ``` -------------------------------- ### Install plugin with trust Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/09-plugins.md Installs a plugin with trust, granting it permission to load skills, commands, hooks, MCP servers, and LSP servers. Use this when installing plugins from sources you trust. ```bash grok plugin install <source> --trust ``` -------------------------------- ### Scripting examples for automation Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Shows common scripting patterns: piping output to a file, parsing JSON with jq, CI/CD code review, chaining with git diff, batch processing files, and a pre-commit hook. These examples use --always-approve and --output-format json. ```bash grok -p "Generate a README" > README.md ``` ```bash grok -p "List files" --output-format json | jq -r '.text' ``` ```bash grok -p "Review changes for bugs and security issues." \ --output-format json --always-approve | jq -r '.text' > review.md ``` ```bash git diff --staged | grok -p "Write a concise commit message for these changes" ``` ```bash for file in src/*.js; do grok -p "Migrate $file from CommonJS to ES modules." --always-approve done ``` ```bash grok -p "Review staged changes for obvious bugs. Reply OK if fine, or list issues." \ --always-approve --output-format json | jq -r '.text' | grep -q "^OK" || exit 1 ``` -------------------------------- ### /model command examples Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/04-slash-commands.md Switch models with /model. Accepts a model ID or display name (case-insensitive), and for reasoning models you can add an effort level as a second argument. Alias: /m. ```text /model grok-4.6 /model Grok 4.6 /model Reasoning X high ``` -------------------------------- ### Write marketplace.json index Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/09-plugins.md Example `marketplace.json` index file that names the marketplace and lists each plugin. The `source` field can be a local path or a separate repository URL with a pinned `sha`. ```json { "name": "My Org Plugins", "description": "Internal skills and tools", "owner": { "name": "Platform Team", "email": "platform@example.com" }, "plugins": [ { "name": "gdrive", "description": "Search and edit Google Drive, Docs, Sheets, and Slides", "category": "productivity", "source": { "type": "local", "path": "./plugins/gdrive" } } ] } ``` -------------------------------- ### Start Grok with default authentication Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/01-getting-started.md Launch Grok. On first launch, it opens the browser to authenticate with grok.com; credentials are stored in ~/.grok/auth.json and refreshed automatically. ```bash grok ``` -------------------------------- ### OpenAI Example TOML Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Example of configuring a built-in OpenAI model with the OpenAI API endpoint and OPENAI_API_KEY environment variable. ```toml [model.gpt-4o] model = "gpt-4o" base_url = "https://api.openai.com/v1" name = "GPT-4o" env_key = "OPENAI_API_KEY" ``` -------------------------------- ### Start a new session with /new Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/17-sessions.md Starts a new session in the TUI, clearing the current context. Alias: /clear. ```plaintext /new ``` -------------------------------- ### Launch the TUI with grok [OPTIONS] Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Starts the interactive TUI. Use command-line flags to configure the working directory, initial prompt, rules, approval mode, sandbox, theme, and more. ```bash grok [OPTIONS] ``` -------------------------------- ### Bash completions: generate and install (Grok-managed location) Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Alternative installation that writes the completion script to ~/.grok/completions/bash/grok.bash. Requires adding a source line to ~/.bashrc to load it. ```bash mkdir -p ~/.grok/completions/bash grok completions bash > ~/.grok/completions/bash/grok.bash ``` ```bash [[ -r "$HOME/.grok/completions/bash/grok.bash" ]] && source "$HOME/.grok/completions/bash/grok.bash" ``` -------------------------------- ### Together AI Example TOML Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Example of configuring a Together AI model using the Together API endpoint and TOGETHER_API_KEY environment variable. ```toml [model.together-mixtral] model = "mistralai/Mixtral-8x7B-Instruct-v0.1" base_url = "https://api.together.xyz/v1" name = "Mixtral 8x7B" env_key = "TOGETHER_API_KEY" ``` -------------------------------- ### Start agent mode with always-approve (stdio and WebSocket) Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/15-agent-mode.md Start Grok in agent mode with always-approve for automation. The first command uses stdio transport for local processes and SDKs; the second starts a WebSocket server bound to 127.0.0.1:2419 with a secret token. Deny rules and hooks still apply. ```bash grok agent --always-approve stdio ``` ```bash grok agent --always-approve serve --bind 127.0.0.1:2419 --secret <token> ``` -------------------------------- ### Quick Start: Run grok with sandbox profiles Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/18-sandbox.md Use these commands to start grok with different sandbox profiles. The workspace profile allows reading everywhere and writing to the current directory, temp dirs, and ~/.grok. Read-only mode allows reading everywhere but only writing to ~/.grok and temp dirs. Strict mode is the most restrictive, limiting reads to CWD, system paths, and ~/.grok, and writes to CWD, ~/.grok/sessions, and temp dirs, with child network blocked on Linux. ```bash # Run with workspace sandbox (read everywhere, write to CWD + temp dirs + ~/.grok/) grok --sandbox workspace # Read-only mode (read everywhere, write only to ~/.grok/ + temp dirs) grok --sandbox read-only # Most restrictive profile (read CWD + system paths + ~/.grok, write CWD + ~/.grok/sessions + temp dirs, no child network) grok --sandbox strict ``` -------------------------------- ### Install a plugin with trust Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/09-plugins.md Installs the 'deploy-tools' plugin from a marketplace, using --trust to bypass the trust warning. Without --trust, Grok shows the source and warns about hooks, MCP servers, and skills before stopping. ```bash grok plugin install deploy-tools --trust ``` -------------------------------- ### AGENTS.md example Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/tutorial/08-make-it-yours.md Place this AGENTS.md file in the repository root to teach Grok about your project. Grok reads it automatically in every session, making it the highest-leverage customization. ```markdown # My Project - Run tests with `pnpm test` - Never edit files under generated/ ``` -------------------------------- ### /loop command examples Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/20-background-tasks.md Three example invocations of /loop with different intervals and prompts: every 5 minutes, every 2 hours, and every 60 seconds. ```plaintext /loop 5m Check if the test suite passes and report any failures ``` ```plaintext /loop 2h Summarize new commits since the last check ``` ```plaintext /loop 60s Check if the dev server at localhost:3000 is responding ``` -------------------------------- ### Install DotSlash and verify Source: https://github.com/xai-org/grok-build/blob/main/README.md Install DotSlash via cargo or prebuilt packages, then verify it is on PATH. This is required before building so hermetic tools like bin/protoc can run. ```sh cargo install dotslash # or: prebuilt packages — https://dotslash-cli.com/docs/installation/ /usr/bin/env dotslash --help # sanity check ``` -------------------------------- ### Example lsp.json Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Example LSP server configuration for TypeScript. The command must be available in PATH or be an absolute path. The extensionToLanguage field maps file extensions to LSP language IDs. ```json { "typescript": { "command": "typescript-language-server", "args": ["--stdio"], "extensionToLanguage": { ".ts": "typescript", ".tsx": "typescriptreact" }, "startupTimeout": 30000 } } ``` -------------------------------- ### Monitor examples: tail, inotifywait, and GitHub polling Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/20-background-tasks.md Three shell command examples for monitoring: tail a log for errors, watch file changes with inotifywait, and poll GitHub for new PR comments. Use grep --line-buffered to avoid buffering delays, and set poll intervals to 30 seconds or more for remote APIs. ```bash # Watch for errors in a log file tail -f /var/log/app.log | grep --line-buffered "ERROR" ``` ```bash # Monitor file changes in a directory inotifywait -m --format '%e %f' /watched/dir ``` ```bash # Poll GitHub for new PR comments last=$(date -u +%Y-%m-%dT%H:%M:%SZ) while true; do now=$(date -u +%Y-%m-%dT%H:%M:%SZ) gh api "repos/owner/repo/issues/123/comments?since=$last" \ --jq '.[] | "\(.user.login): \(.body)"' last=$now; sleep 30 done ``` -------------------------------- ### Install cargo-fuzz and nightly toolchain Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-markdown/fuzz/README.md Install cargo-fuzz and the nightly Rust toolchain, which are required for fuzzing the markdown renderer. ```bash cargo install cargo-fuzz # if not already installed rustup toolchain install nightly ``` -------------------------------- ### Ollama Example TOML Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Example of configuring an Ollama model via its OpenAI-compatible endpoint at localhost:11434/v1. ```toml [model.ollama-codellama] model = "codellama" base_url = "http://localhost:11434/v1" name = "CodeLlama (Ollama)" ``` -------------------------------- ### /workflow command examples Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/04-slash-commands.md Example invocations of the /workflow slash command. Launch a saved workflow with launch flags or a JSON argument object, list runs, and manage a running workflow by its display name using pause, resume, stop, and save verbs. Display names are numbered for duplicate launches (e.g., review-changes-2). ```text /workflow review-changes --agent-budget 256 --effort high {"target":"origin/main...HEAD"} /workflow review-changes {"target":"origin/main...HEAD","agent_budget":256,"effort":"high"} /workflow runs /workflow pause review-changes /workflow resume review-changes /workflow stop review-changes-2 /workflow save review-changes ``` -------------------------------- ### Zsh completions: generate and install (standard location) Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Writes the zsh completion script to ~/.zsh/completions/_grok. Then adds that directory to fpath and enables compinit in ~/.zshrc. ```bash mkdir -p ~/.zsh/completions grok completions zsh > ~/.zsh/completions/_grok ``` ```zsh fpath=(~/.zsh/completions $fpath) autoload -Uz compinit compinit ``` -------------------------------- ### Install Tool Activity Logger Hook Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-hooks/examples/README.md Install the Tool Activity Logger hook globally. Creates the hooks bin directory, copies the hook configuration and shell script, and makes the script executable. ```sh mkdir -p ~/.grok/hooks/bin cp examples/hooks/tool-logger.json ~/.grok/hooks/ cp examples/hooks/bin/tool-logger.sh ~/.grok/hooks/bin/ chmod +x ~/.grok/hooks/bin/tool-logger.sh ``` -------------------------------- ### Run a Skill by Name Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/08-skills.md Run a skill by typing its name as a slash command. The example shows the 'commit' and 'review-pr' skills. ```text /commit # Runs the "commit" skill /review-pr # Runs the "review-pr" skill ``` -------------------------------- ### Config File Configuration Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/02-authentication.md Configuration file example for setting the external auth provider command, label, and token TTL. ```toml # ~/.grok/config.toml [auth] auth_provider_command = "/usr/local/bin/my-auth-provider" auth_provider_label = "Acme Corp" # optional -- customizes the TUI login button auth_token_ttl = 3600 # optional -- token lifetime in seconds ``` -------------------------------- ### Install Stop Gate Hook Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-hooks/examples/README.md Install the Stop Gate hook globally. Creates the hooks bin directory, copies the hook configuration and shell script, and makes the script executable. ```sh mkdir -p ~/.grok/hooks/bin cp examples/hooks/stop-verify.json ~/.grok/hooks/ cp examples/hooks/bin/stop-verify.sh ~/.grok/hooks/bin/ chmod +x ~/.grok/hooks/bin/stop-verify.sh ``` -------------------------------- ### Start agent server mode with --bind and --secret Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/15-agent-mode.md Starts the agent in server mode, listening on 127.0.0.1:2419. Clients connect over WebSocket and authenticate with the secret token. If --secret is omitted, the agent prints a generated token at startup or uses the GROK_AGENT_SECRET environment variable. ```bash grok agent --always-approve serve --bind 127.0.0.1:2419 --secret <token> ``` -------------------------------- ### Add plugin-index.json catalog Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/09-plugins.md Optional `plugin-index.json` catalog that lets the marketplace browser show plugin components before installation. It is for display only and installs work without it. ```json { "version": 1, "plugins": { "gdrive": { "components": { "skills": [{ "name": "gdrive", "description": "Google Drive access" }] } } } } ``` -------------------------------- ### Open onboarding tutorial with /tutorial Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/04-slash-commands.md Use /tutorial to open the onboarding tutorial, a short list of topics each about a 30-second read. Nothing auto-shows; this command or the command palette is the way in. ```text /tutorial ``` -------------------------------- ### OpenAI-compatible Endpoint Example TOML Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Example of a custom model pointing to a local OpenAI-compatible endpoint. Sets model identifier, base URL, display name, and temperature. ```toml [model.local-llama] model = "llama-3.1-70b" base_url = "http://localhost:8080/v1" name = "Local Llama" temperature = 0.8 ``` -------------------------------- ### json output example Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/14-headless-mode.md Example of the JSON output format, showing the response object with text, stop reason, session ID, request ID, and spend fields. The 'usage' field sums tokens for the prompt, and 'modelUsage' provides per-model cost details. ```json { "text": "Here's a summary of the codebase...", "stopReason": "end_turn", "sessionId": "abc123", "requestId": "xyz789", "num_turns": 7, "usage": { "input_tokens": 7210, "cache_read_input_tokens": 41000, "cache_creation_input_tokens": 0, "output_tokens": 1893, "reasoning_tokens": 412, "total_tokens": 50103 }, "modelUsage": { "grok-4.6": { "inputTokens": 7210, "outputTokens": 1893, "cacheReadInputTokens": 41000, "modelCalls": 7, "costUSD": 0.01268905 } }, "total_cost_usd": 0.01268905, "total_cost_usd_ticks": 126890500 } ``` -------------------------------- ### JSON hook configuration with variable substitution Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/custom-hooks.md Example of a command hook configuration using ${HOME} in the command string. Demonstrates the substitution syntax supported at config-load time. ```json { "type": "command", "command": "${HOME}/.config/grok-hooks/check.sh" } ``` -------------------------------- ### Select model with CLI flag `-m` Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/11-custom-models.md Starts a session with the specified model using the `-m` flag. The model must be in the fleet allowlist if one is configured. ```bash grok -p "Hello" -m grok-4.6 ``` -------------------------------- ### General settings in config.toml Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Example of the general-purpose configuration sections in config.toml. Only specify values you want to override; defaults are used otherwise. Includes settings for CLI, models, UI, features, session, tools, and toolset timeouts. ```toml [cli] auto_update = true # check for updates on launch [models] default = "grok-4.6" # model used for new sessions web_search = "grok-4.6" # model used by the web_search tool [ui] max_thoughts_width = 120 # max column width for reasoning display [features] support_permission = false # prompt before tool execution telemetry = false # anonymous usage telemetry (env: GROK_TELEMETRY_ENABLED) feedback = false # feedback system (env: GROK_FEEDBACK_ENABLED) lsp_tools = false # expose the lsp tool (see LSP Servers below) codebase_indexing = true # code graph indexing (true, false, or glob patterns) [session] auto_compact_threshold_percent = 85 # auto-compact at this % of context window load_envrc = true # load .envrc environment variables into bash commands [tools] respect_gitignore = true # filter gitignored files from tools (env: GROK_RESPECT_GITIGNORE) [toolset.bash] timeout_secs = 120.0 # command timeout in seconds output_byte_limit = 65536 # max output size (64KB) [toolset.web_fetch] proxy_endpoint = "https://proxy.example.com" # egress proxy URL (all requests routed through it) allowed_domains = ["docs.rs", "x.ai"] # override the built-in ~84-domain allowlist ``` -------------------------------- ### MCP server not starting: test command and increase timeout Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Tests the MCP server command manually with npx, then shows a config.toml snippet to increase the startup timeout for the filesystem server. ```bash # Test the server command manually npx -y @modelcontextprotocol/server-filesystem /path ``` ```toml # Increase startup timeout in config [mcp_servers.filesystem] startup_timeout_sec = 30 ``` -------------------------------- ### Example PromQL queries for grok-code metrics Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/24-monitoring-usage.md Example PromQL queries to run against the Prometheus exporter from the collector config. They show token usage by model and type, session counts per team per day, and a tool-permission denial ratio. ```promql # Tokens by model and type across the org, 1h rate sum by (model, type) (rate(grok_code_token_usage_total[1h])) # Sessions per team per day sum by (team_id) (increase(grok_code_session_count_total[1d])) # Tool-permission denial ratio sum(rate(grok_code_tool_decision_total{decision="deny"}[1h])) / sum(rate(grok_code_tool_decision_total[1h])) ``` -------------------------------- ### Install Safe Shell Guard Hook Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-hooks/examples/README.md Install the Safe Shell Guard hook globally. Creates the hooks bin directory, copies the hook configuration and guard script, and makes the script executable. ```sh mkdir -p ~/.grok/hooks/bin cp examples/hooks/safe-shell.json ~/.grok/hooks/ cp examples/hooks/bin/safe-shell-guard.sh ~/.grok/hooks/bin/ chmod +x ~/.grok/hooks/bin/safe-shell-guard.sh ``` -------------------------------- ### Get the session ID from a previous JSON response Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/14-headless-mode.md Use this command to start a session and capture its ID from the JSON output. The --output-format json flag ensures the response includes the sessionId field, which can be extracted with jq. ```bash grok -p "Remember: the secret number is 42" --output-format json ``` -------------------------------- ### Install No Recursive Grep Hook Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-hooks/examples/README.md Install the No Recursive Grep hook globally. Requires python3 on PATH. Copies the hook configuration and Python guard script, then makes the script executable. ```sh mkdir -p ~/.grok/hooks/bin cp examples/hooks/no-recursive-grep.json ~/.grok/hooks/ cp examples/hooks/bin/no-recursive-grep-guard.py ~/.grok/hooks/bin/ chmod +x ~/.grok/hooks/bin/no-recursive-grep-guard.py ``` -------------------------------- ### Create hooks directory and SessionStart hook configuration Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/10-hooks.md Creates the hooks directory and a SessionStart hook configuration file. The hook runs automatically when a Grok session starts, printing the current working directory. ```sh mkdir -p ~/.grok/hooks ``` ```json { "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "echo 'Grok session started in '$(pwd)" } ] } ] } } ``` -------------------------------- ### Project structure example Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/12-project-rules.md Shows a project tree with AGENTS.md files at different levels. Grok loads all files from the repo root to the current working directory when running inside a git repository. ```text ~/projects/my-app/ AGENTS.md # "Use TypeScript. Follow ESLint rules." src/ AGENTS.md # "Prefer functional components." components/ AGENTS.md # "Use CSS modules for styling." ``` -------------------------------- ### Test MCP server command and set startup_timeout_sec Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/07-mcp-servers.md Manually test the MCP server command and increase the startup timeout in config.toml if the server fails to start. ```bash # Test the server command manually npx -y @modelcontextprotocol/server-filesystem /path # Increase startup timeout # In config.toml: [mcp_servers.filesystem] startup_timeout_sec = 30 ``` -------------------------------- ### /goal command examples Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/04-slash-commands.md Use the /goal command to set, manage, or check an autonomous goal. Arguments are <objective> [--budget <tokens>] or one of status, pause, resume, clear. The --budget is a token budget for the goal run, separate from agent-count budgets. /goal appears when goal mode is enabled for the session. ```text /goal Migrate the auth module to the new API /goal status /goal pause /goal resume /goal clear ``` -------------------------------- ### Bash completions: generate and install (standard location) Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Creates the standard bash-completion directory and writes the grok completion script to it. After running, reload your shell or source ~/.bashrc to activate tab completion. ```bash mkdir -p ~/.local/share/bash-completion/completions grok completions bash > ~/.local/share/bash-completion/completions/grok ``` -------------------------------- ### Install specific version with curl Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/01-getting-started.md Installs a specific version of Grok Build (0.1.42) using the bash installer. ```bash curl -fsSL https://x.ai/cli/install.sh | bash -s 0.1.42 ``` -------------------------------- ### Install specific version with PowerShell Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/01-getting-started.md Installs a specific version of Grok Build (0.1.42) on Windows using the PowerShell installer. ```powershell $env:GROK_VERSION="0.1.42"; irm https://x.ai/cli/install.ps1 | iex ``` -------------------------------- ### Install latest stable release with PowerShell Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/01-getting-started.md Installs the latest stable release of Grok Build on Windows using the native PowerShell installer. ```powershell irm https://x.ai/cli/install.ps1 | iex ``` -------------------------------- ### Build & Test Instructions Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/12-project-rules.md Provides build and test commands, including prerequisites like Docker for integration tests. ```markdown # Build & Test - Run `npm test` before committing - Use `npm run lint` to check code style - Build with `npm run build` -- ensure no TypeScript errors - Integration tests: `npm run test:e2e` (requires Docker) ``` -------------------------------- ### Enable Memory with GROK_MEMORY=1 Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/13-memory.md Set the environment variable GROK_MEMORY to 1 to enable memory for the process, then start the grok CLI. ```bash export GROK_MEMORY=1 grok ``` -------------------------------- ### Include git diff as context via command substitution Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/14-headless-mode.md Demonstrates how to pass external content into the prompt using command substitution. The example includes the staged git diff as context for a commit message. ```bash # Include git diff as context via command substitution grok -p "Write a concise commit message for these changes: $(git diff --staged)" # Or read the prompt from a file grok --prompt-file ./prompt.txt ``` -------------------------------- ### grok du example output Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/17-sessions.md Example output from `grok du` (alias: `grok disk-usage`) showing disk usage for ~/.grok. It lists top-level directories largest first, then each worktree with size, type, age, label, and path. Untracked worktrees appear as untracked. After the grok-home table, grok du may print Redirections, Orphaned redirections, and Unattributed redirect directories; those bytes live in Grove escape jails, not in the grok-home total. An empty scan prints nothing. ```text Disk usage for ~/.grok 412.3 GB worktrees 1.2 GB sessions 412.0 MB (top-level files) 413.9 GB total Worktree clones share storage with their source, so the total can exceed real disk use. Worktrees SIZE TYPE AGE LABEL PATH 380.0 GB session 12d ago my-fix ~/.grok/worktrees/xai/worktree-abc 32.3 GB untracked (session) 40d ago ~/.grok/worktrees/xai/worktree-old To reclaim space, run `grok worktree gc --max-age 7d --dry-run`, then the same command without `--dry-run`. Without `--max-age`, gc expires nothing, and it keeps a worktree whose work it cannot find elsewhere, naming each one. Untracked rows are not in the registry, so gc never visits them. Remove one with `grok worktree rm --dry-run <path>`, then without `--dry-run`. ``` -------------------------------- ### Configure toolset.bash, ask_user_question, web_fetch, and web_search Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/05-configuration.md Configure toolset behaviors in config.toml. For web_fetch, allow_local is off by default (SSRF fail-closed); enabling it only allows explicit loopback hosts. For web_search, allowed_domains and excluded_domains are mutually exclusive; if both are set, the allowlist wins and the blocklist is dropped with a warning. An empty or absent list is unbounded. The configured policy is authoritative and cannot be bypassed by the model. ask_user_question timeout settings are honored across requirements.toml, managed config, and user config.toml; timeout_secs must be a positive integer. ```toml [toolset.bash] timeout_secs = 120.0 # foreground command timeout in seconds (default: 120) output_byte_limit = 20000 # max captured output in bytes (default: 20000) [toolset.ask_user_question] timeout_enabled = true # false = wait forever for answers (default: true) timeout_secs = 1800 # seconds to wait when enabled (default: 1800 / 30 min) [toolset.web_fetch] proxy_endpoint = "https://proxy.example.com" # egress proxy URL allowed_domains = ["docs.rs", "x.ai"] # override the built-in allowlist allow_local = false # true = allow localhost / 127.0.0.0/8 / ::1 only [toolset.web_search] # Restrict web_search to these domains (max 5). Mutually exclusive with excluded_domains. allowed_domains = ["docs.x.ai", "arxiv.org"] # ...or block these domains instead (leave allowed_domains unset): # excluded_domains = ["reddit.com", "pinterest.com"] ``` -------------------------------- ### Basic CLI usage examples Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-shell/README.md Shows common invocations of the grok command: simple prompts, model selection with -m, JSON output with --output-format, multi-turn conversation with --resume, resuming the most recent session with -c, and running in a different directory with --cwd and --always-approve. ```bash grok -p "What does this project do?" ``` ```bash grok -p "Optimize this function" -m grok-build ``` ```bash grok -p "List all TODO comments in the codebase" --output-format json ``` ```bash grok -p "Explain the architecture" --output-format streaming-json ``` ```bash grok -p "Remember: the secret number is 42" --output-format json grok -p "What's the secret number?" --resume <sessionId> ``` ```bash grok -p "Continue where we left off" -c ``` ```bash grok -p "Run the tests" --cwd ~/projects/other-app --always-approve ``` -------------------------------- ### Hook file format (PreToolUse example) Source: https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-hooks/examples/README.md Defines a hook file in the Claude-compatible JSON format. The matcher is a regex on tool name; Claude names like Bash are auto-expanded to also match Grok names. Timeout is in seconds (default 5) and the command is a path relative to the hook file directory or an inline shell command. ```json { "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "bin/check.sh", "timeout": 5 } ] } ] } } ```