Codex · EN · Part 1
Ch 01 What Is Codex CLI
01-ch-01-What-is-Codex-CLI.md
第1章 What is Codex CLI?
GitHub Copilot suggests code, but what if an AI agent could actually run commands, edit files, and maintain conversation state?
The Problem Codex CLI Solves
Type function calculate in your editor, and Copilot fills in calculateTotal(items). Press Tab, accept the suggestion, and move on. This autocomplete pattern revolutionized coding—but it's fundamentally limited. Completion-only assistants can only suggest; they cannot act.
Consider a typical refactoring task. You want to rename a function across fifty files and update all its call sites. An autocomplete tool might suggest the new name once you start typing it, but you still need to:
- Navigate to each file
- Find every occurrence
- Manually apply the changes
- Hope you didn't miss any edge cases
This is where agents differ from assistants. An agent doesn't just complete your thought—it executes multi-step workflows autonomously. Codex CLI represents OpenAI's answer to this evolution: moving from passive autocomplete to active agent behavior.
The trajectory of AI coding tools tells a clear story:
| Era | Capability | Interaction Model |
|---|---|---|
| Autocomplete (2021-2023) | Suggests code completions based on context | Passive: you type, it suggests |
| Chat Assistants (2023-2024) | Answers questions, generates code snippets | Request-response: you ask, it answers |
| Agents (2024-present) | Executes commands, edits files, maintains state | Collaborative: you describe, it acts |
🤿 深入底层:The codebase distinguishes between CodexThread (conversation management) and ThreadManager (orchestration). This separation allows agents to maintain context across multiple operations while enabling features like thread forking and archival—capabilities impossible in stateless chat interfaces.
Why did OpenAI build Codex CLI as a separate local tool rather than extending cloud services? Three reasons:
- Filesystem access: Agents need to read and write your actual files, not just generate text
- Command execution: Real-world tasks require running shell commands, tests, and build processes
- State persistence: Complex tasks unfold over time; agents need to remember what they've done
The completion-only model assumes you want suggestions. The agent model assumes you want results.
Local-First Architecture Philosophy
Your code contains secrets—API keys, database credentials, proprietary algorithms. Sending every file to a cloud service for processing creates an inherent tension: productivity versus privacy.
Codex CLI's architecture resolves this with a local-first design. The agent runs on your machine, executing commands and editing files directly. Only the reasoning travels to the cloud via OpenAI's Responses API.
Rendering diagram...
This hybrid architecture delivers three critical benefits:
Privacy by default: Your files never leave your machine. The agent reads src/auth.ts locally, then sends only a description of the task to the API: "Read the authentication module and suggest refactoring options." The actual code contents stay local.
Offline capability: Once authenticated, Codex CLI can continue working with certain operations even during network hiccups. Configuration, conversation history, and tool execution all happen locally. The API call is the only network dependency.
Sandboxed security: Just because code runs locally doesn't mean it should run wildly. Codex CLI implements platform-specific sandboxing:
// codex-rs/sandboxing/src/lib.rs:14-19
pub struct SandboxExecRequest {
pub command: String,
pub args: Vec<String>,
pub policy: SandboxPolicy, // [1] Restricts filesystem access
pub cwd: PathBuf,
}
On Linux, this uses bubblewrap (bwrap) to create isolated environments with restricted filesystem access. macOS uses Seatbelt sandboxing. Windows uses job objects and restricted tokens. Your agent can modify files in your project directory but cannot arbitrarily touch system files or sensitive data.
⚠️ 避坑指南:Sandboxing isn't perfect isolation. The policy system (WorkspaceWrite mode) allows writes only in specified directories, but developers occasionally accidentally grant too broad permissions. Always review the sandbox policy when prompted—especially for commands that access
~or/tmp.
The local-first approach represents a fundamental philosophical choice: intelligence is a service, execution is a local right. OpenAI provides the brain; your computer provides the hands.
Codex CLI in the AI Coding Landscape
The AI coding tool ecosystem has fragmented rapidly. Understanding where Codex CLI fits helps you choose the right tool for each job.
Consider the competitive landscape:
| Tool | Architecture | Execution | Primary Use Case |
|---|---|---|---|
| Codex CLI | Local agent + cloud API | Full shell/file access | Multi-step development tasks |
| GitHub Copilot CLI | Cloud service | Limited shell access | One-off commands and scripts |
| Aider | Local agent + cloud API | Git-focused edits | Git workflow automation |
| Continue.dev | IDE extension (multi-provider) | In-editor suggestions | Editor-integrated assistance |
| Cursor IDE | Built-in editor AI | Deep editor integration | Editor-native experience |
Each tool occupies a distinct niche:
Codex CLI shines for orchestration-heavy tasks. When you need to:
- Read multiple files to understand context
- Execute a sequence of commands
- Apply coordinated changes across your codebase
- Maintain conversation state across iterations
The app-server protocol enables deep IDE integration. VS Code, Cursor, and Windsurf extensions can connect to Codex CLI's local JSON-RPC server, providing agent capabilities within your editor while keeping execution local.
GitHub Copilot CLI focuses on quick commands. Need a one-liner to extract JSON from a file? Copilot CLI generates it instantly. But it lacks the persistent state and multi-step orchestration that agents require.
Aider specializes in git-centric workflows. It excels at making commits, handling merges, and managing branches. However, it lacks Codex CLI's rich interactive TUI and official IDE partnerships.
☕ 茶水间时间:Why doesn't Codex CLI just run everything in the cloud like ChatGPT's web interface? The answer lies in latency and control. A local agent can execute
git statusin 50ms. A cloud agent must first upload your repository state, process it remotely, then send back results—adding seconds of latency and requiring you to trust the cloud with your code.
Tool selection guidance:
- Use Codex CLI for: refactoring projects, running test suites, implementing multi-file features
- Use Copilot CLI for: generating one-off scripts, quick command lookups
- Use Aider for: git-heavy workflows, automated commit generation
- Use Continue.dev for: multi-model flexibility in your existing editor
Quick Start: Your First Conversation
Enough theory—let's get Codex CLI running. The installation process varies by platform, but the core experience remains consistent.
Installation and Authentication
The fastest path to your first conversation:
# [ch-01-code1] Installation and First-Run Setup
# Install using npm (cross-platform)
npm install -g @openai/codex
# Or use Homebrew (macOS/Linux)
brew install --cask codex
# Launch Codex - first run triggers auth flow
codex
When you first run codex, you'll encounter an authentication prompt. The CLI supports two methods:
- Sign in with ChatGPT (recommended): Opens your browser for OAuth authentication. Works with ChatGPT Plus, Pro, Team, Edu, or Enterprise plans.
- API key authentication: Manual entry of an OpenAI API key. Requires additional configuration.
// codex-rs/cli/src/main.rs:62-73 — CLI entry point
#[derive(Debug, Parser)]
#[clap(
author,
version,
subcommand_negates_reqs = true,
bin_name = "codex",
override_usage = "codex [OPTIONS] [PROMPT]\n codex [OPTIONS] <COMMAND> [ARGS]"
)]
struct MultitoolCli {
#[clap(flatten)]
pub config_overrides: CliConfigOverrides, # [1] Config can be layered
#[clap(flatten)]
interactive: TuiCli, # [2] Default mode launches TUI
#[clap(subcommand)]
subcommand: Option<Subcommand>, # [3] Or route to exec/mcp/etc
}
After authentication completes, the Terminal UI (TUI) launches—a full-screen interface resembling a chat application, but with superpowers.
TUI and Exec Modes
Codex CLI operates in two primary modes:
TUI Mode (default): Interactive terminal interface with streaming responses, inline command approvals, and persistent conversation history.
# Launch interactive mode
codex
# Or explicitly
codex tui "Help me debug this function"
Exec Mode: Non-interactive, scriptable execution. Perfect for CI/CD pipelines or automation.
# Run non-interactively with output to stdout
codex exec "Run tests and report failures"
# Use JSONL output for machine parsing
codex exec --json "Lint the codebase" | jq '.items[] | select(.type == "toolUse")'
The difference isn't just visual—it's philosophical. TUI mode assumes you're collaborating with the agent. Exec mode assumes you're delegating to it.
Your First Task
Let's put Codex CLI through its paces with a simple "hello world" task:
# In TUI mode, enter this prompt:
"Create a Python function that calculates fibonacci numbers, write it to fib.py, then run it with argument 10"
Watch what happens:
- Understanding phase: The agent reads your prompt, recognizes three distinct actions
- Planning phase: It breaks down the task into steps (code generation → file creation → execution)
- Execution phase: Each tool use prompts for approval (in TUI mode) or runs automatically (in exec mode with
--yes) - Result phase: The agent reports back with the fibonacci result
🤿 深入底层:This workflow is orchestrated by the CodexThread in
codex-rs/core/src/codex.rs. Each "turn" (your input plus the agent's response) generates a stream of TurnItem events—userMessage,agentMessage,commandExecution,fileEdit, etc. These items flow through async channels, enabling the UI to update incrementally as the agent works.
The magic isn't that Codex CLI can write a fibonacci function—any LLM can do that. The magic is that it can:
- Write the code to a real file on your disk
- Execute real Python in your environment
- Capture and return the actual output
- Maintain conversation state so you can iterate
Try a follow-up: "Now memoize it." The agent remembers the context, reads fib.py, applies the optimization, and runs it again—all without re-entering the original request.
Understanding Local vs. Remote Operations
As you use Codex CLI, pay attention to which operations happen locally versus remotely:
| Operation | Location | Why |
|---|---|---|
| Prompt interpretation | Remote (API) | Requires LLM reasoning |
| File reading | Local | Your data stays on your machine |
| File writing | Local | Direct filesystem access |
| Shell execution | Local (sandboxed) | Runs in your environment |
| Tool orchestration | Local | Agent logic runs locally |
| Response generation | Remote (API) | LLM generates final output |
This hybrid approach gives you the best of both worlds: cloud intelligence with local control. Your code never leaves your machine unread—only task descriptions and execution summaries travel to the API.
You've now experienced Codex CLI's core value: an AI agent that doesn't just suggest code, but actively participates in your development workflow. The local-first architecture ensures your code stays private while giving the agent the access it needs to be useful. And the two-mode design (TUI for collaboration, exec for automation) accommodates different working styles.
But we've only scratched the surface. How does Codex CLI actually coordinate all these components? What happens under the hood when you type a prompt? Chapter 2 zooms out to show how the architecture fits together—from the CLI entry point through the app-server protocol to the core agent orchestration that makes it all work.
Chapter Exercises
-
Install and authenticate: Install Codex CLI using your preferred method (npm, Homebrew, or direct binary download) and complete the authentication flow. Verify the installation works by running
codex --version. -
Compare modes: Run the same simple task ("Create a hello world in Python and execute it") in both TUI mode (
codex) and exec mode (codex exec). Observe the differences in output format and interaction style. -
Trace the architecture: Using a simple task like "list the files in the current directory," identify which operations happen locally (file reading, shell execution) versus remotely (prompt interpretation, response generation). Use the architecture diagram as your guide.