# CLI reference

> Top-level grok commands and flags: default TUI, agent, login/logout, mcp, plugin, memory, models, sessions, inspect, setup, update, wrap, export, trace; shared runtime flags.

- Repository: xai-org/grok-build
- GitHub: https://github.com/xai-org/grok-build
- Human docs: https://grok-wiki.com/public/docs/xai-org-grok-build-90205de50458
- Complete Markdown: https://grok-wiki.com/public/docs/xai-org-grok-build-90205de50458/llms-full.txt

## Source Files

- `crates/codegen/xai-grok-pager/src/app/cli.rs`
- `crates/codegen/xai-grok-pager/src/headless.rs`
- `crates/codegen/xai-grok-pager/src/mcp_cmd.rs`
- `crates/codegen/xai-grok-pager/src/plugin_cmd.rs`
- `crates/codegen/xai-grok-pager/src/sessions_cmd.rs`
- `crates/codegen/xai-grok-pager/src/memory_cmd.rs`
- `crates/codegen/xai-grok-pager/docs/user-guide/14-headless-mode.md`
- `crates/codegen/xai-grok-pager-bin/src/main.rs`

---

---
title: "CLI reference"
description: "Top-level grok commands and flags: default TUI, agent, login/logout, mcp, plugin, memory, models, sessions, inspect, setup, update, wrap, export, trace; shared runtime flags."
---

The shipped `grok` binary is the `xai-grok-pager-bin` entrypoint. Clap parses a single top-level `PagerArgs` tree: no subcommand opens the interactive TUI (optional positional prompt), `-p` / `--prompt-json` / `--prompt-file` enter headless single-turn mode, and named subcommands (`agent`, `login`, `mcp`, `plugin`, `memory`, `models`, `sessions`, `inspect`, `setup`, `update`, `wrap`, `export`, `trace`, and peers) dispatch before the TUI. Shared session, model, permission, sandbox, and debug flags live on `PagerArgs` and apply to interactive and headless paths where noted.

```bash
grok [OPTIONS] [PROMPT]
grok [OPTIONS] <COMMAND>
grok -p "prompt" [OPTIONS]
```

## Invocation modes

| Mode | How you enter it | Behavior |
| --- | --- | --- |
| Interactive TUI | `grok` or `grok "initial prompt"` | Fullscreen (or minimal) pager; tools, slash commands, scrollback |
| Headless | `-p` / `--single`, `--prompt-json`, or `--prompt-file` | One prompt path; stdout formats `plain` / `json` / `streaming-json`; process exits |
| Subcommand | `grok <command> ...` | Auth, config, MCP, plugins, sessions, updates, export, etc. |
| ACP agent | `grok agent stdio` (and related modes) | Agent Client Protocol over stdio / WS / leader |

Interactive is defined as: no subcommand and none of the three headless prompt inputs. The binary name accepted by the parser is `grok` (or `agent` for argv0 compatibility).

## Shared runtime flags

These flags hang off the top-level `PagerArgs` parser. Many are available for both TUI and headless; a few are headless-only and are ignored with a warning in the TUI.

### Core session and prompt

| Flag | Description |
| --- | --- |
| `-v`, `-V`, `--version` | Print version (channel-aware) and exit |
| `--cwd <DIR>` | Change working directory before run |
| `-p`, `--single`, `--print <PROMPT>` | Headless prompt text |
| `--prompt-json <JSON>` | Headless ACP content blocks (array or `{"type":"acp","content":[...]}`) |
| `--prompt-file <PATH>` | Headless prompt from file (`.json` → blocks, else text) |
| `--verbatim` | Send the prompt exactly as given |
| `[PROMPT]` | Positional initial prompt for the interactive TUI only |
| `-m`, `--model <MODEL>` | Model ID |
| `--reasoning-effort`, `--effort <LEVEL>` | Reasoning effort for supported models |
| `--rules`, `--append-system-prompt <TEXT>` | Extra rules appended to the system prompt |
| `--system-prompt-override`, `--system-prompt <PROMPT>` | Replace the agent system prompt |
| `-r`, `--resume [SESSION_ID]` | Resume by ID, or most recent when ID omitted |
| `--load <SESSION_ID>` | Hidden alias for `--resume` with an ID |
| `-c`, `--continue` | Continue most recent session for the current directory |
| `-s`, `--session-id <UUID>` | Create a **new** session with this UUID (must not exist). With `-r`/`-c`, only valid with `--fork-session` |
| `--fork-session` | On resume/continue, fork into a new session ID |
| `-w`, `--worktree [NAME]` | Start in a new git worktree |
| `--worktree-ref`, `--ref <REF>` | Base ref for `--worktree` |
| `--restore-code` | With `--resume`, check out the original session commit |

### Permissions, tools, and safety

| Flag | Description |
| --- | --- |
| `--always-approve`, `--yolo`, `--dangerously-skip-permissions` | Auto-approve tool executions (same effective path as `bypassPermissions` when allowed by policy) |
| `--permission-mode <MODE>` | One of: `default`, `acceptEdits`, `auto`, `dontAsk`, `bypassPermissions`, `plan` |
| `--allow`, `--allowedTools <RULE>` | Permission allow rule (comma-delimited, repeatable) |
| `--deny`, `--disallowedTools <RULE>` | Permission deny rule (comma-delimited, repeatable) |
| `--tools <TOOLS>` | Built-in tool allowlist (comma-separated; **headless only**) |
| `--disallowed-tools <TOOLS>` | Built-in tool denylist; supports `Agent` / `Agent(type)` (**headless only**) |
| `--max-turns <N>` | Cap agent turns, `N ≥ 1` (**headless only**) |
| `--disable-web-search` | Disable web search and web fetch tools |
| `--sandbox <PROFILE>` | Sandbox profile; also `GROK_SANDBOX`. Built-ins: `workspace`, `devbox`, `read-only`, `strict`, `off` |
| `--trust` | Trust current folder and persist (hidden) |

Deny rules take precedence over allow rules. `--tools` / `--disallowed-tools` / `--max-turns` / `--agents` are headless-only; interactive use prints a warning and ignores them. Resuming a session with a different `--sandbox` than the profile stored at creation is refused.

### Output, UI, and process

| Flag | Description |
| --- | --- |
| `--output-format <FMT>` | Headless output: `plain` (default), `json`, `streaming-json` |
| `--json-schema <SCHEMA>` | Constrain model JSON; implies `--output-format json` when plain was selected |
| `--no-plan` | Disable plan mode |
| `--no-subagents` | Disable subagent spawning |
| `--agent <NAME>` | Agent name or definition path |
| `--agents <JSON>` | Inline subagent definitions |
| `--experimental-memory` / `--no-memory` | Enable or disable cross-session memory for this session |
| `--check`, `--self-verify` | Append self-verification loop (**headless**; conflicts with `--no-subagents`) |
| `--best-of-n <N>` | Run N parallel candidates and pick best (**headless**) |
| `--minimal` / `--fullscreen` | Screen mode; sticky writes `[ui] screen_mode` in `~/.grok/config.toml` (mutually exclusive) |
| `--no-alt-screen` | Inline rendering without alternate screen |
| `--oauth` | Prefer OAuth when the welcome screen authenticates |
| `--debug` / `--debug-file <FILE>` | Debug logging (global); may set `GROK_DEBUG_LOG` / `GROK_HOOKS_LOG` |
| `--leader-socket <PATH>` | Custom leader socket (global; default `~/.grok/leader.sock`) |

Headless background wait defaults to wait after the first turn (up to `--background-wait-timeout`, default 600s). Hidden `--no-wait-for-background` exits when the first turn ends.

```bash
# Interactive with model + initial prompt
grok -m grok-build "summarize this repo"

# Headless with JSON and auto-approve tools
grok -p "list open TODOs" --output-format json --yolo

# Resume last session for this directory, headless
grok -p "continue the refactor" -c

# Fork resume into a new session UUID
grok -p "try another approach" -r <session-id> --fork-session -s "$(uuidgen | tr '[:upper:]' '[:lower:]')"
```

## Default interactive TUI

With no subcommand and no headless prompt flags, the binary starts the pager TUI after config load, auth, sandbox resolution, and optional auto-update checks. A positional prompt seeds the first turn. Screen mode follows sticky config plus `--minimal` / `--fullscreen` / `--no-alt-screen`. Dashboard-at-startup is available via `grok dashboard` when the dashboard feature is enabled.

Related workflows: [Quickstart](/quickstart), [Sessions](/sessions), [Slash commands](/slash-commands), [Keyboard shortcuts](/keyboard-shortcuts).

## Headless mode (`-p`)

Headless runs the agent in-process (ACP lifecycle), streams results to stdout, and exits. Stdin is **not** the prompt; use `-p`, `--prompt-file`, or command substitution.

| Format | Shape |
| --- | --- |
| `plain` | Final assistant text |
| `json` | Single object: `text`, `stopReason`, `sessionId`, optional spend (`usage`, `modelUsage`, costs) |
| `streaming-json` | NDJSON events: `text`, `thought`, `end`, `error` (non-exhaustive) |

```bash
grok -p "Review staged changes" --yolo --output-format json
grok --prompt-file ./prompt.txt --output-format streaming-json
grok -p "only read tools" --tools "read_file,grep,list_dir"
```

Full CI patterns, spend field policy, and tool filtering details: [Headless mode](/headless-mode).

## `grok agent`

Runs Grok without the interactive UI. Nested modes:

| Mode | Command | Role |
| --- | --- | --- |
| stdio | `grok agent stdio` | ACP server on stdio (IDEs / custom clients) |
| headless | `grok agent headless` | Headless over Grok WebSocket relay |
| serve | `grok agent serve` | WebSocket agent server (`--bind`, default `127.0.0.1:2419`; secret via `--secret` or `GROK_AGENT_SECRET`) |
| leader | `grok agent leader` | Shared leader process for multiple clients |

Shared agent flags include `-m` / `--model`, `--reasoning-effort`, `--always-approve` / `--yolo`, `--agent-profile`, `--plugin-dir` (repeatable, process-local trusted plugins), `--leader` / `--no-leader`, `--reauth`, and endpoint overrides (`--cli-chat-proxy-base-url`, `--xai-api-base-url`, `--grok-ws-origin`, `--grok-ws-url`). Top-level `--leader` / `--no-leader` do **not** apply to `agent`; pass them on the agent subcommand.

See [Agent mode (ACP)](/agent-mode).

## Auth: `login` / `logout`

```bash
grok login
grok login --oauth          # browser OAuth via auth.x.ai
grok login --device-auth    # device-code flow (alias: --device-code)
grok logout                 # clear cached credentials
```

`--legacy` is accepted but ignored. Credentials live under `~/.grok` (for example `auth.json`). CI can use `XAI_API_KEY` instead of interactive login. Details: [Authentication](/authentication).

## `grok mcp`

Manage MCP server entries in user (`~/.grok/config.toml`) or project (`./.grok/config.toml`) scope.

| Subcommand | Purpose |
| --- | --- |
| `list [--json]` | List servers (project-aware merge) |
| `add` | Add/update stdio, HTTP, or SSE server |
| `remove <name> [-s user\|project]` | Remove; all scopes searched if scope omitted |
| `doctor [--json] [name]` | Diagnose config and connectivity |

```bash
grok mcp add xcode -- xcrun mcpbridge
grok mcp add --transport http sentry https://mcp.sentry.dev/mcp
grok mcp add --scope project github -- npx -y @modelcontextprotocol/server-github
grok mcp add postgres -e DATABASE_URL=postgres://localhost/db -- npx -y @modelcontextprotocol/server-postgres
```

Transports: `stdio` (default), `http`, `sse`. Flags: `-t/--transport`, `-s/--scope`, `-e/--env KEY=value`, `-H/--header "Name: value"`. See [MCP servers](/mcp-servers).

## `grok plugin`

Install and manage plugins and marketplaces.

| Subcommand | Purpose |
| --- | --- |
| `list [--json] [--available]` | Installed plugins; `--available` needs `--json` |
| `install <source> [--trust]` | Git URL, `user/repo`, local path; optional `@ref`, `#subdir` |
| `uninstall` / `rm` / `remove <name>` | Uninstall (`--confirm`, `--keep-data`) |
| `update [name]` | Update one or all |
| `enable` / `disable <name>` | Toggle without uninstall |
| `details <name>` | Component inventory |
| `validate [path]` | Validate `plugin.json` (default `.`) |
| `tag [path] [--push] [-f] [--dry-run]` | Git tag from manifest version |
| `marketplace list\|add\|remove\|update` | Marketplace sources |

See [Plugins](/plugins).

## `grok memory`

Cross-session memory maintenance from the CLI.

```bash
grok memory clear              # workspace MEMORY.md, sessions/, index (default)
grok memory clear --global     # global MEMORY.md
grok memory clear --all -y     # both scopes, skip confirm
```

See [Project rules and memory](/project-rules-and-memory).

## `grok models`

Lists auth status (API key, OAuth host, deployment key, model-scoped key, or unauthenticated), the default model, and available model IDs by spawning a short-lived agent shell.

```bash
grok models
```

Model selection at runtime: `-m` / `--model` or interactive `/model`. See [Custom models](/custom-models).

## `grok sessions`

| Subcommand | Purpose |
| --- | --- |
| `list [-n N]` | Recent sessions (default limit 20) |
| `search <query> [-n N]` | Keyword search (local + remote when available) |
| `delete <id>` | Permanently delete session history |

Resume in a run with `-r` / `-c` rather than a dedicated resume subcommand. See [Sessions](/sessions).

## `grok inspect`

Dumps configuration discovered for the current directory: project instructions, permissions, login policy, hooks, skills, agents, plugins, marketplaces, MCP/LSP, config sources, and external-compat notes. Folder trust gates repo-local hooks/plugins/MCP listings.

```bash
grok inspect
grok inspect --json
```

See [Configure Grok](/configure-grok).

## `grok setup`

Fetches and installs managed team configuration. Requires a deployment key (`GROK_DEPLOYMENT_KEY` or `[endpoints] deployment_key`) or team sign-in. `--json` prints the served report without writing `~/.grok`.

```bash
grok setup
grok setup --json
```

## `grok update`

| Flag | Purpose |
| --- | --- |
| `--check` | Check without installing |
| `--json` | Machine-readable output (with `--check`) |
| `--force-reinstall` | Re-download even if current |
| `--version <VER>` | Install specific version |
| `--alpha` / `--stable` | Channel switch (mutually exclusive; enterprise channel exists but is hidden) |

```bash
grok update --check
grok update --version 0.1.150
grok update --alpha
```

Install layout and PATH: [Installation](/installation).

## `grok wrap`

Runs an arbitrary command in a local PTY, intercepts OSC 52 clipboard sequences, and writes them to the local system clipboard (useful inside containers/SSH when the outer terminal does not handle OSC 52). Terminal size tracks the outer window.

```bash
grok wrap docker exec -it my-container bash
grok wrap kubectl exec -it my-pod -- bash
```

On Unix, a single quoted string or shell alias can run via `$SHELL -i -c`. Hidden on platforms without Unix/Windows PTY support.

## `grok export` / `grok trace`

```bash
# Markdown transcript of a session (stdout, file, or clipboard)
grok export <session-id>
grok export <session-id> ./out.md
grok export <session-id> --clipboard

# Trace archive (local and/or upload when [telemetry] trace_upload is enabled)
grok trace <session-id>
grok trace <session-id> --local -o /tmp/trace.tar.gz
grok trace <session-id> --json
```

Default local trace path: `$GROK_HOME/trace-exports/<session-id>.tar.gz`.

## Version, completions, worktree, dashboard

| Command | Purpose |
| --- | --- |
| `grok version` / `grok v` | Version string; `--json` → `currentVersion` + `channel` |
| `grok completions <shell>` | Emit completion script (`bash`, `zsh`, `fish`, `powershell`, …) |
| `grok worktree` | List (`ls`), show, rm, gc/prune, db rebuild/stats/path for tracked worktrees |
| `grok dashboard` | Open Agent Dashboard at TUI startup (disabled by `[dashboard].enabled = false` or `GROK_AGENT_DASHBOARD=0`) |

Hidden/gated: `grok share`, `grok workspace` (hub exposure; requires server flag or `GROK_WORKSPACE_COMMAND=1`).

## Environment counterparts (selected)

| Variable | Role |
| --- | --- |
| `XAI_API_KEY` | Non-interactive API auth |
| `GROK_DEPLOYMENT_KEY` | Managed config / enterprise auth |
| `GROK_SANDBOX` | Default sandbox profile |
| `GROK_AGENT_SECRET` | Secret for `agent serve` |
| `GROK_DEBUG_LOG` / `GROK_HOOKS_LOG` | Debug / hooks logging |
| `GROK_LOG_SAMPLING` | Sampling log file |
| `GROK_DISABLE_AUTOUPDATER` | Suppress auto-update |
| `GROK_WORKSPACE_COMMAND` | Enable/disable `workspace` CLI gate |
| `GROK_AGENT_DASHBOARD` | Disable dashboard with `0` |

Config precedence and full key schema: [Configuration reference](/configuration-reference), [Configure Grok](/configure-grok).

## Dispatch map

```text
grok argv
├── completions | wrap          → early exit (no full agent config path)
├── version | login | logout | update | setup | inspect
├── mcp | plugin | memory | models | sessions | worktree | export | trace
├── agent {stdio|headless|serve|leader}
├── -p | --prompt-json | --prompt-file  → headless single-turn
└── else → interactive TUI (+ optional positional prompt / dashboard)
```

Implementation anchors: clap command tree in `crates/codegen/xai-grok-pager/src/app/cli.rs`; binary dispatch in `crates/codegen/xai-grok-pager-bin/src/main.rs`; headless runner in `crates/codegen/xai-grok-pager/src/headless.rs`; management commands in `mcp_cmd.rs`, `plugin_cmd.rs`, `sessions_cmd.rs`, `memory_cmd.rs`, `export_cmd.rs`, `trace_cmd.rs`.

## Related pages

<CardGroup cols={2}>
  <Card title="Headless mode" href="/headless-mode">
    `-p`, output formats, tool allow/deny, max-turns, CI patterns
  </Card>
  <Card title="Agent mode (ACP)" href="/agent-mode">
    `grok agent stdio` and JSON-RPC session lifecycle
  </Card>
  <Card title="Authentication" href="/authentication">
    OAuth, device-code, API key, login/logout storage
  </Card>
  <Card title="Configuration reference" href="/configuration-reference">
    `config.toml` / `pager.toml` keys and env counterparts
  </Card>
  <Card title="Permissions and safety" href="/permissions-and-safety">
    Allow/deny rules, permission modes, safe-bash defaults
  </Card>
  <Card title="Sessions" href="/sessions">
    Resume, continue, fork, persistence, `grok sessions`
  </Card>
</CardGroup>
