API Dashboard ↗

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. 1

    Install

    Install the Codex CLI with PowerShell.

    npm i -g @openai/codex
  2. 2

    Run

    Run Codex in a terminal. It can inspect your repository, edit files, and run commands.

    codex

    The 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. 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


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:

Tip. You can pass multiple prompts in sequence and Codex will process them as a single conversation thread, maintaining full context between each instruction.

Resuming conversations

The codex resume subcommand lets you reopen earlier threads so you never lose context on long-running tasks.

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:

Note. Reasoning-capable models may produce longer thinking traces. You can inspect these traces in the TUI to understand how Codex arrived at its plan.

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.

Token usage. Subagents consume more tokens than single-agent runs because each subagent maintains its own context window. Use them deliberately for tasks that genuinely benefit from parallelism.

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:

Review results are presented inline with suggested fixes that you can accept or reject one at a time.

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:

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.
Pro tip. Combine --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
Note. Global flags should follow subcommands (e.g., codex exec --full-auto).

Slash Commands

Keyboard-first controls available during Codex interactive sessions. Type / to access the command popup.

Session Management

Command Description
/clearReset the visible UI and conversation for a fresh start
/newStart a fresh conversation without exiting the CLI
/resumeContinue work from a previous CLI session
/forkBranch the active session to explore alternatives
/quit or /exitTerminate the CLI session

Model & Performance

Command Description
/modelSwitch between models (e.g., gpt-5.4, gpt-4.1-mini)
/fastTurn Fast mode on or off for GPT-5.4
/planAsk Codex to propose an execution plan before implementation

Communication & Permissions

Command Description
/personalityChoose communication styles: friendly, pragmatic, none
/permissionsRelax or tighten approval requirements mid-session
/agentSwitch between spawned subagent threads

File & Content Management

Command Description
/mentionPoint Codex at specific files or folders to inspect
/copyGrab the latest finished response or plan text
/diffReview Codex's edits before you commit or run tests
/sandbox-add-read-dirGrant Windows sandbox read access to a directory

Tools & Configuration

Command Description
/mcpCheck which external tools Codex can call during the session
/appsBrowse and insert connectors into prompts
/pluginsInspect installed and discoverable plugins
/experimentalToggle optional features like subagents

Diagnostics & Maintenance

Command Description
/statusDisplay session configuration and token usage
/debug-configDebug precedence and policy requirements
/statuslinePick and reorder footer items
/titleConfigure terminal window title fields
/psCheck long-running commands without leaving the transcript
/stopCancel background terminal work

Utilities

Command Description
/reviewRequest working tree assessment
/compactSummarize the conversation to free tokens
/initCapture persistent instructions for the repository
/feedbackSubmit diagnostics to maintainers
/logoutClear local credentials
/themeChange syntax highlighting theme