Codex CLI
OpenAI's coding agent for your terminal
CLI Overview
Codex CLI is OpenAI's coding agent that you can run locally from your terminal. It can read, change, and run code on your machine in the selected directory. It's open source and built in Rust for speed and efficiency.
ChatGPT Plus, Pro, Business, Edu, and Enterprise plans include Codex. Learn more about what's included.
CLI setup
Choose your package manager-
1
Install
Install the Codex CLI with PowerShell.
npm i -g @openai/codex -
2
Run
Run Codex in a terminal. It can inspect your repository, edit files, and run commands.
codexThe first time you run Codex, you'll be prompted to sign in. Authenticate with your ChatGPT account or an API key.
See the pricing page if you're not sure which plans include Codex access.
-
3
Upgrade
New versions of the Codex CLI are released regularly. See the changelog for release notes. To upgrade, run the install command again:
npm i -g @openai/codex
If you're new to Codex, read the best practices guide.
Work with the Codex CLI
Run Codex interactively
Run codex to start an interactive terminal UI (TUI) session.
Control model and reasoning
Use /model to switch between GPT-5.4, GPT-5.3-Codex, and other available models, or adjust reasoning levels.
Image inputs
Attach screenshots or design specs so Codex reads them alongside your prompt.
Run local code review
Get your code reviewed by a separate Codex agent before you commit or push your changes.
Use subagents
Use subagents to parallelize complex tasks.
Web search
Use Codex to search the web and get up-to-date information for your task.
Codex Cloud tasks
Launch a Codex Cloud task, choose environments, and apply the resulting diffs without leaving your terminal.
Model Context Protocol
Give Codex access to additional third-party tools and context with Model Context Protocol (MCP).
Approval modes
Choose the approval mode that matches your comfort level before Codex edits or runs commands.
Features
Running in interactive mode
Launch Codex by running codex in your terminal to access a full-screen terminal UI (TUI). The interactive mode is the primary way most developers work with Codex day to day.
You can specify an initial prompt directly on the command line:
codex "refactor the auth module to use JWT"
Inside the TUI you can:
- Send code snippets and screenshots alongside natural-language instructions.
- Review Codex's plan before any file changes are applied, giving you a chance to approve, reject, or refine.
- Navigate through the draft history to compare earlier iterations of a change.
- Use built-in commands such as
/clearto reset the conversation,/copyto copy the last response to the clipboard, and/exitto quit the session.
Resuming conversations
The codex resume subcommand lets you reopen earlier threads so you never lose context on long-running tasks.
- Launch a picker — run
codex resumewith no arguments to open an interactive picker of recent sessions. - Show all sessions — pass
--allto list every recorded session. - Jump to the most recent — use
--lastto immediately resume the latest session. - Target a specific run — supply the run ID directly, e.g.
codex resume abc123.
codex resume --last
codex resume --all
codex resume abc123
Resumed runs maintain the original transcript and approval history, so Codex remembers exactly what it was doing and which file edits were accepted.
Connect the TUI to a remote app server
Remote TUI mode separates the app server from the terminal frontend. You run the server on one machine (for example a powerful cloud VM) and connect to it from another machine over WebSocket.
Start the server
codex app-server --listen ws://127.0.0.1:4500
Connect from a client
codex --remote ws://127.0.0.1:4500
Three authentication modes are available:
| Mode | Description | Use case |
|---|---|---|
| No WebSocket auth | No token required; relies on network-level isolation. | Local-only or trusted LAN environments. |
| Capability tokens | Server generates a one-time capability token the client must present. | Shared machines where you want lightweight protection. |
| Signed bearer tokens | Tokens are signed with a secret key and validated on connection. | Production or multi-user deployments. |
Models and reasoning
gpt-5.4 is the recommended model for most coding tasks. It offers the best balance of speed, accuracy, and cost for everyday development work.
ChatGPT Pro subscribers can access GPT-5.3-Codex-Spark, which is optimized for fast, lightweight completions and ideal for rapid iteration.
You can switch models in two ways:
- Mid-session — type
/modelinside the TUI to open a model picker. - At launch — pass the
--modelflag, e.g.codex --model gpt-5.4 "prompt".
Feature flags
Codex includes experimental features that can be toggled on or off through the feature-flag system. Flags are persisted in your configuration files so they survive across sessions.
codex features list # Show all available feature flags and their status
codex features enable <flag> # Turn on a feature
codex features disable <flag> # Turn off a feature
Feature flags allow the Codex team to ship new capabilities incrementally. Enabled flags take effect immediately in both interactive and non-interactive modes.
Subagents
Codex can spawn subagents to parallelize larger tasks. Rather than handling every subtask sequentially, Codex distributes work across multiple agents that run concurrently.
Subagents are only spawned when you explicitly request parallelization — for example, asking Codex to refactor several independent modules at the same time. See the Subagents page for details.
Image inputs
Attach screenshots or diagrams to your prompts so Codex can reason about visual content alongside code.
codex -i screenshot.png "fix the layout bug shown here"
You can attach multiple images by separating filenames with commas:
codex -i before.png,after.png "describe the visual differences"
Supported formats include PNG, JPEG, GIF, and WebP. Images are resized automatically if they exceed the model's input limits.
Syntax highlighting and themes
Type /theme inside the TUI to open an interactive theme picker and preview syntax-highlighting styles in real time.
You can also add custom themes by placing .tmTheme files in the themes directory:
$CODEX_HOME/themes/
Codex picks up new theme files automatically — no restart required. Themes follow the standard TextMate theme format, so any editor theme in .tmTheme format can be reused.
Running local code review
Type /review inside the TUI to access built-in code review presets. These presets streamline common review workflows:
- Diff against a base branch — compare your working tree to
main,develop, or any branch you specify. - Uncommitted changes — review everything in your staging area and working directory.
- Specific commits — target individual commits by SHA for focused review.
- Custom instructions — add free-form guidance such as "focus on security" or "check error handling".
Review results are presented inline with suggested fixes that you can accept or reject one at a time.
Web search
Codex ships with a first-party web search tool that is enabled by default in local mode. Search results are cached to reduce latency on repeated queries.
For live (uncached) results, pass the --search flag at launch:
codex --search "what changed in the latest React release?"
You can also configure search behavior in your config.toml:
[search]
enabled = true
cache_ttl = "24h"
provider = "default"
Shell completions
Generate shell completion scripts for your preferred shell to get tab-completion for all Codex commands and flags.
codex completion bash >> ~/.bashrc
codex completion zsh >> ~/.zshrc
codex completion fish > ~/.config/fish/completions/codex.fish
After sourcing the updated profile (or opening a new terminal), you will be able to press Tab to auto-complete subcommands, flags, and in some cases file paths.
Scripting Codex
For non-interactive automation, use the exec subcommand. It runs a single prompt and pipes the result to stdout, making it easy to integrate Codex into shell scripts and CI pipelines.
codex exec "fix the CI failure"
You can chain exec with other Unix tools:
codex exec "generate a migration for adding an email column" | tee migration.sql
codex exec "summarize this diff" < changes.patch
Working with Codex cloud
The codex cloud subcommand manages tasks that run on OpenAI's hosted infrastructure rather than your local machine.
Interactive task management:
codex cloud
Programmatic execution with retries:
codex cloud exec --env ENV_ID "prompt" --attempts 3
Cloud environments are pre-configured with common toolchains. You can specify an environment ID to target a particular runtime (e.g. a Node 22 environment or a Python 3.12 environment). The --attempts flag tells Codex to retry the task up to the specified number of times if it encounters a transient error.
Slash commands
Built-in slash commands provide specialized workflows without leaving the TUI:
/review— launch a code review session with presets for diffs, commits, and custom instructions./fork— branch the current conversation so you can explore an alternative approach without losing your place./model— switch the active model mid-session./theme— change the syntax-highlighting theme./clear— reset the conversation context./copy— copy the last response to the clipboard./exit— quit the session.
You can also create custom slash commands for team-specific tasks by adding command definitions to your project's .codex/ directory. See the Slash Commands section for full details.
Prompt editor
For longer or more complex prompts, press Ctrl+G in the composer to open your preferred external text editor. Codex uses the editor defined by the VISUAL environment variable, falling back to EDITOR if VISUAL is not set.
export VISUAL="code --wait" # Use VS Code
export EDITOR="vim" # Fallback to Vim
When you save and close the editor, the contents are sent as your prompt. This is especially useful for multi-line instructions or pasting large code blocks.
Tips and shortcuts
Speed up your workflow with these handy shortcuts and techniques:
| Shortcut / Technique | Description |
|---|---|
@ |
Type @ in the composer to trigger a fuzzy file search and quickly reference files in your project. |
| Enter while running | Press Enter while Codex is executing to inject additional instructions without waiting for it to finish. |
! prefix |
Prefix a line with ! to run it as a local shell command without leaving the TUI. |
| Esc Esc | Press Escape twice to edit your previous message, letting you refine instructions after seeing results. |
--cd <path> |
Set the working root directory at launch: codex --cd ~/projects/my-app. |
--add-dir |
Expose additional writable directories beyond the working root, e.g. codex --add-dir ../shared-lib. |
--cd and --add-dir to give Codex access to a monorepo's packages while keeping the working root scoped to a single package.
Command Line Options
Global Flags
These flags apply to all subcommands:
| Flag | Description |
|---|---|
--add-dir <path> |
Grant write access to additional directories |
--ask-for-approval <mode> |
Control approval timing. Values: untrusted, on-request, never |
--cd <path> |
Set working directory |
--config/-c <key=value> |
Inline configuration overrides |
--sandbox/-s <mode> |
Sandbox mode: read-only, workspace-write, danger-full-access |
--model/-m <model> |
Model selection (e.g., gpt-5.4, gpt-5.3-codex) |
--full-auto |
Low-friction automation shortcut (implies full access) |
--remote <url> |
Connect to app-server WebSocket endpoint |
--search |
Enable live web search |
--json |
JSON Lines output (exec mode) |
-i <file> |
Attach image file(s) |
-o <path> |
Write final message to file |
--ephemeral |
Don't persist session files |
--skip-git-repo-check |
Override Git repo requirement |
Subcommands
codex (default) — Interactive TUI Stable
Launch the interactive terminal UI session.
codex [prompt]
codex --model gpt-5.4 "explain this codebase"
codex exec — Non-interactive execution Stable
Run tasks without the interactive interface.
codex exec "summarize the repository structure"
codex exec --json "list all API endpoints"
codex exec --full-auto "fix the failing test"
codex resume — Resume sessions Stable
Reopen earlier conversation threads.
codex resume # picker of recent sessions
codex resume --all # show all sessions
codex resume --last # most recent session
codex resume <ID> # specific session
codex fork — Fork session Stable
Branch the active session to explore alternatives.
codex login / codex logout Stable
Manage authentication credentials.
codex completion Stable
Generate shell completion scripts.
codex completion bash
codex completion zsh
codex completion fish
codex features Stable
Manage experimental feature flags.
codex features list
codex features enable <feature>
codex features disable <feature>
codex apply Stable
Apply patches or changes from a file.
codex cloud Experimental
Manage cloud tasks with environment and attempt specifications.
codex cloud
codex cloud exec --env ENV_ID "prompt" --attempts 3
codex mcp Experimental
Manage Model Context Protocol servers.
codex mcp add <name> -- <command>
codex mcp add <name> --env VAR=VALUE -- <command>
codex mcp list
codex mcp remove <name>
codex mcp login <server-name>
codex sandbox Experimental
Manage sandbox configuration.
codex app-server Experimental
Launch WebSocket app server for remote TUI connections.
codex app-server --listen ws://127.0.0.1:4500
codex exec --full-auto).
Slash Commands
Keyboard-first controls available during Codex interactive sessions. Type / to access the command popup.
Session Management
| Command | Description |
|---|---|
| /clear | Reset the visible UI and conversation for a fresh start |
| /new | Start a fresh conversation without exiting the CLI |
| /resume | Continue work from a previous CLI session |
| /fork | Branch the active session to explore alternatives |
| /quit or /exit | Terminate the CLI session |
Model & Performance
| Command | Description |
|---|---|
| /model | Switch between models (e.g., gpt-5.4, gpt-4.1-mini) |
| /fast | Turn Fast mode on or off for GPT-5.4 |
| /plan | Ask Codex to propose an execution plan before implementation |
Communication & Permissions
| Command | Description |
|---|---|
| /personality | Choose communication styles: friendly, pragmatic, none |
| /permissions | Relax or tighten approval requirements mid-session |
| /agent | Switch between spawned subagent threads |
File & Content Management
| Command | Description |
|---|---|
| /mention | Point Codex at specific files or folders to inspect |
| /copy | Grab the latest finished response or plan text |
| /diff | Review Codex's edits before you commit or run tests |
| /sandbox-add-read-dir | Grant Windows sandbox read access to a directory |
Tools & Configuration
| Command | Description |
|---|---|
| /mcp | Check which external tools Codex can call during the session |
| /apps | Browse and insert connectors into prompts |
| /plugins | Inspect installed and discoverable plugins |
| /experimental | Toggle optional features like subagents |
Diagnostics & Maintenance
| Command | Description |
|---|---|
| /status | Display session configuration and token usage |
| /debug-config | Debug precedence and policy requirements |
| /statusline | Pick and reorder footer items |
| /title | Configure terminal window title fields |
| /ps | Check long-running commands without leaving the transcript |
| /stop | Cancel background terminal work |
Utilities
| Command | Description |
|---|---|
| /review | Request working tree assessment |
| /compact | Summarize the conversation to free tokens |
| /init | Capture persistent instructions for the repository |
| /feedback | Submit diagnostics to maintainers |
| /logout | Clear local credentials |
| /theme | Change syntax highlighting theme |