Grok Build: An Architecture Book
This is a source-guided explanation of how Grok Build works. It favors architectural ideas, ownership boundaries, and runtime flows over line-by-line API documentation.
The citations point to the exact source that supports each claim. Because this is a living codebase, treat the prose as a map and the cited code as the final .
Choose a reading path
Journey preview
Start with the Guided Journey if you are new to Grok Build or want to understand how the whole system cooperates. It follows one concrete developer task from process startup, through the pager and resident shell session, across the model and tool boundaries, into a workspace edit, and back to durable user-visible state.
This is the narrative path: read it in order, keep one runtime baton in view, and use the package chapters as deeper reference material when a handoff deserves more detail.
Reference preview
Start with the workspace map if you already know which subsystem or package you need. The package chapters are the exhaustive reference path: each one explains a package's contracts, ownership boundaries, invariants, runtime flows, and exact source anchors.
The two paths are additive. The journey explains how the pieces become a product; the package reference explains each piece deeply enough to change it safely.
Guided journey
- Guided Journey: Grok Build from launch to durable answer — a start-to-finish tour of one real coding task through the entire system.
Package reference
- Workspace map and coverage — the complete 79-package inventory and architectural reading order.
xai-acp-lib— the typed, asynchronous bridge between ACP protocol traits, in-process channels, and newline-delimited transports.xai-agent-lifecycle— the -agnostic contracts that let in-process extensions observe lifecycle events, contribute model input, and own slash commands without taking over the agent loop.xai-prompt-queue— the shared server-authoritative prompt-queue vocabulary used by the shell and pager.xai-token-estimation— the arithmetic contract that keeps context estimates, displays, and compaction gates consistent.xai-grok-version— the lockstepped build identity used across binaries, headers, updates, and version-gated configuration.xai-grok-models— the embedded fallback model catalog and role-specific default selection.xai-grok-env— the leaf endpoint/environment preset shared across the shell crate family.xai-grok-auth— the dependency-inversion seam for request authentication, credential snapshots, and bounded 401 recovery.xai-grok-http— non-sampling HTTP client topologies, request identity, transport classification, and pool-escape retry mechanics.xai-chat-state— the single-writer conversation , request shaping, token and billing state, rewind/capture, and compaction data transforms.xai-grok-sampling-types— the canonical conversation model, three provider projections, normalized streaming outcomes, recovery evidence, and sampling configuration.xai-grok-compaction— the transport-agnostic full-replace, intra-turn, and inter-turn compaction engines behind -injected data, sampling, commit, and observation seams.xai-grok-sampler— the three-layer inference executor: HTTP/SSE clients, provider stream state machines, and a concurrent with cancellation and recovery.xai-grok-agent— the compiler from portable agent definitions and discovered context to a session-bound prompt, tool bridge, policies, and plugin snapshot.xai-tool-types— the canonical tool-description schema and shared task/subagent lifecycle vocabulary used across runtimes and transports.xai-tool-runtime— the typed-to-dynamic execution boundary for call context, streaming, output , errors, notifications, and tool discovery.xai-tool-protocol— the pure wire grammar for Computer Hub identities, JSON-RPC flows, session/server topology, tool calls, hooks, notifications, and compatibility.xai-computer-hub-core— the transport-neutral router kernel for principals, two-plane registries, local-first resolution, remote stream normalization, and nested dispatch.xai-computer-hub-sdk— the shared asynchronous transport runtime for pooled connections, reconnect, local-first harness calls, provider execution, cancellation, and telemetry donation.xai-computer-hub-mcp-adapter— the transport-neutral bridge that discovers MCP tools and adapts their definitions, calls, content, errors, and lifecycle into Computer Hub provider handlers.xai-circuit-breaker— the shared sliding-window HTTP failure gate, half-open recovery state machine, keyed registry, retry classifier, and observation seam.xai-interjection-core— the executor-neutral shared event queue and canonical mid-turn user-message framing used at agent-loop safe points.xai-tracing— the dual-rail fastrace and tracing/OpenTelemetry helpers for OTLP export, HTTP/gRPC propagation, task inheritance, and duration logging.xai-test-utils— shared hermetic Git, Cargo/Bazel runfiles, tracing-capture, performance-sizing, and image fixtures for cross-crate tests.xai-grok-config-types— the shared configuration vocabulary for remote overlays, provenance-aware flags, memory/MCP/permission values, defaults, and boundary projections.xai-grok-config— the layered TOML, path, override, requirements, managed-cache, signed-policy, and platform-shell mechanics beneath effective configuration.prod-mc-cli-chat-proxy-types— the low-dependency wire contract for proxy sessions, storage, metadata, sandboxes, feedback, telemetry, signed deployment policy, and subagent bundles.xai-proto-build— the shared protobuf build pipeline for compiler discovery, precise Cargo invalidation, prost/tonic generation, and optional proto JSON.xai-grok-tools-api— the protobuf and JSON control-plane contract for tool finalization, discovery, execution, state, validation, and shared slash-command behavior.xai-grok-paths— UTF-8 absolute/relative path invariants, explicit root resolution, and lexical containment helpers.xai-grok-secrets— allocation-aware credential, URL, JSON-string, and user-path redaction primitives.xai-sqlite-journal— filesystem-aware WAL versus rollback policy and per- isolation for SQLite on network mounts.xai-system-power— cross-platform suspend/resume and macOS dark-wake signals used to protect irreversible authentication work.xai-tracing-macros— timestamped tracing and sync/async block timing macros.xai-mixpanel— the narrow, secret-scrubbing Track/Engage adapter used by product telemetry.xai-gix-status— RLIMIT-awaregixstatus worker budgeting that prevents process-aborting spawn failures.xai-grok-announcements— tolerant banner DTOs, expiry, overrides, and deterministic per-announcement dismissal state.xai-grok-workspace-client— the reconnect-aware typedworkspace.*client carried over a Computer Hub tool stream.xai-hooks-plugins-types— ACP management DTOs for hooks, plugins, MCP, and terminal-safe marketplace catalogs.xai-tty-utils— TTY-safe subprocess detachment, noninteractive environments, process-tree scopes, stderr shielding, and WSL detection.xai-grok-shell-session-support— process-level managed-MCP credential/catalog caching, refresh, gateway epochs, and shell integration boundaries.xai-grok-markdown-core— the renderer-faithful headless Markdown grammar, statistics, and structural-degradation analysis.ordered_hashmap— the vendored insertion-order foundation beneath Graphlib and Dagre, including its and audit tradeoffs.graphlib_rust— the vendored mutable graph model that connects Mermaid semantics to Dagre layout.ptyctl-cli— the command-line PTY server/client boundary, named-session registry, wait contract, and presentation layer.ptyctl— the reusable headless PTY, terminal emulator, generation-driven wait engine, and unauthenticated HTTP/WebSocket adapter.xai-grok-shell-base— low-level process, environment, support-state, and CPU-profile foundations shared below the shell .xai-grok-shared— shell-independent UI/session contracts, native stderr, cross-platform clipboard behavior, and bounded image-placeholder recovery.xai-file-utils— structured local event evidence and a bounded, durable artifact-export data plane across proxy, GCS, and S3 routes.xai-fsnotify— shared platform watchers and a VCS-aware semantic invalidation stream for one canonical workspace root.xai-grok-workspace-types— the Tokio-free wire grammar for workspace requests, chunks, events, typed RPCs, identifiers, metadata, and portable failures.xai-grok-workspace— the -local for sessions, filesystems, VCS, permissions, tools, rewind, discovery, hub serving, and graceful drain.xai-fast-worktree— linked, standalone, native-checkout, and Linux-snapshot worktree creation with CoW copying, dirty-state replay, metadata, and cleanup.xai-codebase-graph— Tree-sitter-based structural definition/reference indexing with -owned incremental mutation, portable caches, and navigation queries.xai-hunk-tracker— the per-session single-writer ledger for baseline/current diffs, agent/external attribution, accept/reject, rewind snapshots, and LOC accounting.xai-grok-hooks— additive compatibility hook discovery, ordered lifecycle dispatch, explicit pre-tool denial, and bounded command/HTTPS execution.xai-grok-mcp— quarantined MCP SDK integration across pool/client/auth state machines, stdio/HTTP/ACP transports, OAuth, recovery, and tool .xai-grok-memory— Markdown-first global/workspace/session persistence with derived FTS/vector retrieval, synchronization, consolidation, and replay archives.xai-grok-sandbox— profile-driven Landlock/Seatbelt capabilities, bubblewrap deny composition, child seccomp networking, and enforcement evidence.xai-grok-subagent-resolution— pure role/persona precedence, fork-context normalization, and resume identity validation below -owned spawning.xai-grok-tools— the session-bound composition layer for registry finalization, typed resources, erased dispatch, local computer backends, dynamic integrations, and tool policy.xai-crash-handler— split-phase fatal-fault capture using crash-safe raw evidence, terminal restoration, next-start symbolication, and bounded report history.xai-grok-update— multi-source version policy, disk/process convergence, minimum-version enforcement, verified downloads, and crash-safe atomic activation.xai-grok-voice— backend-neutral microphone capture, refreshed per-utterance authentication, streaming STT, push-to-talk session control, and prompt-oriented transcript events.xai-grok-plugin-marketplace— compatibility-oriented source discovery, indexed browsing, explicit install resolution, provenance identity, Git caching, and staged transactional updates.xai-grok-test-support— hermetic real-binary harnesses, multi-dialect mock inference, deterministic SSE scripts, typed/raw ACP drivers, and frame-aware leader IPC faults.xai-grok-telemetry— independent product-event, local-log, Sentry, internal-trace, and customer-OTLP rails around shared typed evidence and privacy boundaries.xai-grok-shell— the -level composition root for policy, ACP session ownership, -serialized turns, tools and extensions, durability, and leader/relay topology.xai-grok-markdown— the incremental terminal document engine for parsing, rich-block , source metadata, checkpoint freezing, and streaming-safe rendering.xai-grok-mermaid— the hardened, swappable Mermaid-to-PNG boundary with pure-Rust layout, audited rasterization, and process-isolation support.xai-grok-pager— the interactive client state machine for startup, ACP , multi-agent view models, actions and effects, scrollback, input, and headless execution.xai-grok-pager-bin— the executable composition root for process hardening, CLI topology, leader recovery, updates, and minimal-mode installation.xai-grok-pager-minimal— the native-scrollback renderer with a print-once committed frontier, content-anchored live viewport, overlays, and sliced full-transcript generation.xai-grok-pager-pty-harness— the black-box PTY, terminal-emulator, scripted-scenario, scroll-matrix, and frame-benchmark test system.xai-grok-pager-render— reusable frame-output, terminal-capability, theme, media, hyperlink, clipboard, and -integration primitives.xai-ratatui-inline— the forked Ratatui terminal layer for native scrollback, inline viewport geometry, resize reconstruction, large-screen and hyperlink-aware frame diffs, and ANSI physical-row segmentation.xai-ratatui-textarea— the grapheme-aware multiline editor for atomic embedded elements, transactional history, keyboard and mouse interaction, display-projected wrapping, selection, and scrolling.dagre_rust— the vendored layered-graph geometry engine built as a reversible pipeline of cycle removal, ranking, normalization, crossing reduction, compound constraints, and coordinate assignment.mermaid-to-svg— the offline Mermaid syntax, diagram dispatch, Dagre adaptation, deterministic SVG, theme, and text-measurement layer beneath hardened rasterization.
Reading conventions
- means the runtime that owns a session and its agent loop. The currently using this crate is
xai-grok-shell. - means a stateful feature installed into a .
- Contributor means one interface an implements to participate in a particular event rail. One may be several kinds of contributor.
- Current wiring describes call paths present in this repository snapshot. A public contract may exist before a connects it to production control flow.