Codex CLI is OpenAI’s terminal-based coding agent. Built in Rust, it reads your codebase, edits files, runs commands, and manages git workflows from the command line. Codex runs with OS-native sandboxing (Seatbelt on macOS, Bubblewrap on Linux) to safely execute commands without risking your system. This cheat sheet covers every command, shortcut, configuration option, and workflow pattern for Codex CLI.

Installation

Install Codex CLI via npm, Homebrew, or direct binary download:

# npm (all platforms)
npm install -g @openai/codex

# Homebrew (macOS)
brew install --cask codex

# Verify
codex --version

Authenticate with your ChatGPT account or API key:

# Browser-based login (default)
codex

# API key login
printenv OPENAI_API_KEY | codex login --with-api-key

# Headless/SSH login
codex login --device-auth

Keyboard Shortcuts

ShortcutAction
Ctrl+CCancel current operation (press twice to quit)
Ctrl+DExit Codex (press twice to force quit)
Ctrl+LClear terminal screen
Ctrl+GOpen prompt in external editor (vim, etc.)
EnterDuring execution – inject new instructions
TabQueue a follow-up prompt while agent is working
Esc + EscEdit your previous message (when composer is empty)
EscClose navigation drawer
Up/DownNavigate draft history
@Fuzzy file search – attach files to conversation
!Execute local shell command directly

Slash Commands

Session Management

CommandWhat It Does
/clearReset UI and conversation
/compactSummarize conversation to free token space
/newStart fresh conversation in same session
/resumeResume a saved conversation
/forkClone current conversation to new thread
/copyCopy latest Codex output to clipboard
/diffDisplay git diff including untracked files
/statusShow session config and token usage
/exit / /quitExit Codex CLI

Configuration and Model

CommandWhat It Does
/modelChoose model and reasoning effort level
/fastToggle fast mode for GPT-5.4
/permissionsSet what Codex can do without asking
/themeChoose syntax highlighting theme
/personalitySet communication style: friendly, pragmatic, or none
/statuslineConfigure footer status bar items
/experimentalToggle experimental features
/debug-configPrint config layer diagnostics

Code and Project Tools

CommandWhat It Does
/initGenerate AGENTS.md scaffold with project context
/reviewCode review of working tree changes
/planSwitch to plan mode (read-only exploration)
/mentionAttach files to conversation
/mcpList configured MCP tools
/agentSwitch active agent thread
/psShow background terminals and output
/feedbackSubmit logs to maintainers

CLI Subcommands

CommandWhat It Does
codexStart interactive TUI session
codex exec / codex eNon-interactive mode (like claude -p)
codex reviewNon-interactive code review
codex resumeResume a previous session
codex forkFork a previous session into new thread
codex apply / codex aApply latest diff as git apply
codex loginManage authentication
codex mcpManage MCP servers
codex mcp-serverRun Codex as an MCP server (stdio)
codex sandboxRun commands within Codex sandbox
codex features listList all feature flags
codex cloudBrowse and apply Codex Cloud tasks
codex appLaunch desktop app (macOS)
codex completion bashGenerate shell completions

CLI Flags Reference

Core Flags

FlagPurpose
-m, --model <MODEL>Set model (gpt-5.4, gpt-5.4-mini, gpt-5.3-codex)
-i, --image <FILE>Attach image(s) to initial prompt
-C, --cd <DIR>Set working root directory
--add-dir <DIR>Add writable directories
-p, --profile <NAME>Use named config profile
--searchEnable live web search
--ossUse local open-source model (LM Studio/Ollama)
-c, --config <key=value>Override config.toml values
--versionShow version number

Security and Approval Flags

FlagPurpose
-s, --sandbox <MODE>Sandbox: read-only, workspace-write, danger-full-access
-a, --ask-for-approval <MODE>Approval: untrusted, on-request, never
--full-autoAuto-approve within sandbox (on-request + workspace-write)
--yoloNo sandbox, no approvals (dangerous)

Non-Interactive (codex exec) Flags

# Run a task non-interactively
codex exec "fix the failing tests"

# Output JSON for scripting
codex exec --json "list all API endpoints"

# Save final response to file
codex exec -o result.txt "summarize the architecture"

# Enforce JSON schema on output
codex exec --output-schema schema.json "extract metadata"

# Resume previous session with follow-up
codex exec resume --last "now add error handling"

# Full-auto mode in CI/CD
codex exec --full-auto "run tests and fix failures"

# Set spending budget
codex exec --full-auto --config model=gpt-5.4-mini "fix linting errors"

Sandbox Modes

Codex uses OS-native sandboxing – Seatbelt on macOS, Bubblewrap on Linux, restricted tokens on Windows:

ModeFile AccessNetworkUse Case
read-onlyRead anywhere, no writesDisabledSafe exploration, code review
workspace-writeRead/write in project dirDisabledNormal coding (default for git repos)
danger-full-accessFull filesystem accessEnabledSystem admin tasks (use with caution)

Approval Policies

PolicyBehavior
untrustedOnly known-safe read commands auto-approved, everything else prompts
on-requestModel decides when to ask (default with –full-auto)
neverNever asks – failures returned to model silently
granularFine-grained per-category control in config.toml

Common combinations:

# Safe exploration (read-only, always ask)
codex -s read-only -a untrusted

# Normal coding (default for git projects)
codex -s workspace-write -a untrusted

# Full auto (shortcut for workspace-write + on-request)
codex --full-auto

# No safety rails (dangerous)
codex --yolo

Models and Reasoning

ModelBest ForSpeed
gpt-5.4Complex reasoning, architecture, multi-file changesSlower
gpt-5.4-miniQuick edits, simple tasks, lower costFast
gpt-5.3-codexSpecialized coding tasksMedium

Reasoning effort levels control how deeply the model thinks:

LevelUse Case
minimalTrivial lookups
lowSimple questions, quick fixes
mediumDefault – balanced
highComplex debugging, architecture
xhighHardest problems

Switch with /model in interactive mode or -m gpt-5.4-mini on the command line.

AGENTS.md – Project Instructions

AGENTS.md is Codex’s equivalent of Claude Code’s CLAUDE.md. It provides project-specific instructions loaded at the start of every session.

vi AGENTS.md

Example project instructions:

# My Project

## Build Commands
- Test: `npm test`
- Build: `npm run build`
- Lint: `npm run lint -- --fix`

## Rules
- Use TypeScript strict mode for all new files
- Write unit tests for every new function
- Never commit directly to main branch
- All API endpoints must have OpenAPI docs

Generate one automatically with /init.

Configuration (config.toml)

Codex uses TOML config files. Precedence (highest to lowest): CLI flags, profile values, project config (.codex/config.toml), user config (~/.codex/config.toml), system config (/etc/codex/config.toml), defaults.

vi ~/.codex/config.toml

Common settings:

# Model and reasoning
model = "gpt-5.4"
model_reasoning_effort = "high"

# Security defaults
sandbox_mode = "workspace-write"
approval_policy = "on-request"

# Personality
personality = "pragmatic"

# Web search
web_search = "cached"

# Performance
service_tier = "fast"

# Developer instructions (like AGENTS.md but in config)
developer_instructions = "Always use TypeScript. Prefer functional patterns."

# MCP servers
[mcp_servers.github]
command = ["npx", "-y", "@modelcontextprotocol/server-github"]

# Named profiles
[profiles.fast]
model = "gpt-5.4-mini"
model_reasoning_effort = "low"
service_tier = "fast"

[profiles.thorough]
model = "gpt-5.4"
model_reasoning_effort = "xhigh"

Use profiles with codex -p fast or codex -p thorough.

MCP Servers

Codex supports MCP for connecting to external tools. Configure in ~/.codex/config.toml:

# STDIO transport (local process)
[mcp_servers.github]
command = ["npx", "-y", "@modelcontextprotocol/server-github"]
enabled = true
startup_timeout_sec = 30

# HTTP transport (remote server)
[mcp_servers.remote-db]
url = "https://my-mcp-server.example.com"

Codex can also run as an MCP server itself:

codex mcp-server

Skills System

Skills extend Codex with reusable task-specific capabilities. They are scanned from multiple locations:

  • .agents/skills/ – project-level (checked into git)
  • ~/.codex/skills/ or ~/.agents/skills/ – personal
  • /etc/codex/skills/ – system-wide

Invoke skills with $skill-name in the composer, or create new ones with $skill-creator.

Execution Policy Rules

Define fine-grained rules for what commands Codex can run. Rules use Starlark format in ~/.codex/rules/:

vi ~/.codex/rules/default.rules

Example rules:

prefix_rule(
    pattern = ["git", "push"],
    decision = "forbidden",
    justification = "No direct pushes - use PR workflow"
)

prefix_rule(
    pattern = ["rm", "-rf"],
    decision = "prompt",
    justification = "Destructive operation needs confirmation"
)

Test rules before applying:

codex execpolicy check --pretty -- git push origin main

Environment Variables

VariablePurpose
CODEX_HOMEOverride config directory (default: ~/.codex)
CODEX_API_KEYAPI key for non-interactive/CI use
OPENAI_API_KEYOpenAI API key (alternative)
CODEX_CA_CERTIFICATECustom CA cert for corporate proxies
CODEX_THREAD_IDCurrent thread ID (injected into subprocesses)
HTTPS_PROXYHTTP proxy for corporate networks

Non-Interactive Code Review

# Review uncommitted changes
codex review --uncommitted

# Review against a branch
codex review --base main

# Review a specific commit
codex review --commit abc123

File Structure Reference

# User-level (personal, all projects)
~/.codex/
  config.toml            # Global settings
  auth.json              # Stored credentials
  rules/                 # Execution policy rules
  skills/                # Personal skills
  themes/                # Custom .tmTheme files
  log/                   # Debug logs

# Project-level (shared with team)
.codex/
  config.toml            # Project settings (trusted projects only)
AGENTS.md                # Project instructions
.agents/
  skills/                # Project skills

Codex CLI vs Claude Code

FeatureCodex CLIClaude Code
LanguageRustTypeScript
ModelsGPT-5 family + local OSSClaude family (Opus, Sonnet, Haiku)
SandboxOS-native (Seatbelt, Bubblewrap)Config-based
Project configAGENTS.md + config.tomlCLAUDE.md + settings.json
Non-interactivecodex execclaude -p
Code reviewBuilt-in codex reviewVia prompt
Web searchBuilt-in (cached/live)Via MCP
PricingChatGPT Plus ($20/mo) or APIClaude Pro ($20/mo) or API
Multi-agentBuilt-in thread spawningSubagent tool
Execution policyStarlark rules filesNot available
Local modelsLM Studio, OllamaNot supported
MCPClient and serverClient only

Practical Workflow Tips

Start Every Project Right

codex
/init

This generates an AGENTS.md with your project’s build commands, test setup, and conventions.

Use Profiles for Different Workflows

# Quick fix - fast model, low reasoning
codex -p fast "fix the typo in README"

# Deep architecture work - powerful model, max reasoning
codex -p thorough "redesign the auth module"

CI/CD Integration

# Fix failing tests automatically
codex exec --full-auto "run tests and fix all failures"

# Code review in CI
codex review --base main --json > review-results.json

# Generate documentation
codex exec -o docs/api.md "generate API documentation from the source code"

Image Input

# Analyze a screenshot
codex -i screenshot.png "what's wrong with this UI?"

# Multiple images
codex -i before.png,after.png "compare these two designs"

Local Models (No API Key Needed)

# Use with LM Studio
codex --oss --local-provider lmstudio

# Use with Ollama
codex --oss --local-provider ollama

Quick Reference Card

ActionHow
Start sessioncodex
Start with promptcodex "fix the auth bug"
Non-interactivecodex exec "query"
Resume sessioncodex resume
Full auto modecodex --full-auto
Switch model/model
Plan mode/plan
Code reviewcodex review --base main
Clear context/clear
Compact context/compact
View diff/diff
Check status/status
File mention@path/to/file
Shell command!ls -la
CancelCtrl+C
ExitCtrl+D
Apply last diffcodex apply
Web searchcodex --search
Local modelcodex --oss
Use profilecodex -p fast

Conclusion

Codex CLI brings OpenAI’s coding capabilities directly to the terminal with strong sandboxing defaults and flexible configuration. The key patterns: use AGENTS.md for project context, config profiles for different workflows, codex exec for automation, and the built-in sandbox to keep your system safe. For the latest features, check the official Codex CLI repository and OpenAI’s documentation.

Related guides: