Codex
Printed from:
Complete Codex Cheatsheet
Note: "Codex" today refers to OpenAI Codex CLI — the open-source terminal coding agent from OpenAI (
@openai/codex). The original 2021 Codex API model is deprecated; this cheat sheet covers the modern CLI. It is a peer of Claude Code, Aider, Cursor, and similar agentic coding tools.
Table of Contents
- What Codex Is
- Installation
- Authentication
- First Run
- Interactive Mode (REPL)
- Slash Commands
- Non-interactive (
exec) Mode - Approval & Sandboxing
- Configuration File
- Models & Providers
- MCP Servers
- Project Memory (
AGENTS.md) - Notifications & Hooks
- Common Workflows
- Cost / Token Management
- Troubleshooting
- Quick Reference
What Codex Is
Codex CLI is an interactive terminal agent that:
- Reads/writes files in the current working directory (sandboxed).
- Runs shell commands (with your approval policy).
- Uses the OpenAI Responses API and the latest reasoning models (e.g.
gpt-5,o4-mini,gpt-5-codex). - Supports MCP servers as tools.
- Is open source (Apache 2.0) — repo:
https://github.com/openai/codex.
1234codex # start the REPL in the current directory
codex "add tests for utils/date.ts"
codex exec "lint and fix" # one-shot, non-interactive
Installation
1234567891011121314# npm (recommended, cross-platform)
npm install -g @openai/codex
# Homebrew (macOS / Linux)
brew install codex
# Standalone binaries (from GitHub Releases)
curl -fsSL https://github.com/openai/codex/releases/latest/download/codex-x86_64-unknown-linux-gnu.tar.gz \
| tar -xz && sudo mv codex /usr/local/bin/
# Verify
codex --version
codex --help
Requirements
- Node 20+ (only for the npm install path).
- macOS, Linux, or Windows (Windows works best via WSL2).
- An OpenAI account / API key (or ChatGPT login).
Authentication
123456789101112131415# Interactive login (OAuth, recommended for ChatGPT Plus/Pro/Team/Enterprise users)
codex login
# API key
export OPENAI_API_KEY=sk-...
# or persist in ~/.codex/config.toml (see Configuration File)
# Logout / refresh
codex logout
codex login --status
# Azure OpenAI / OpenAI-compatible endpoints
export OPENAI_BASE_URL=https://my-endpoint.example.com/v1
export OPENAI_API_KEY=...
First Run
12345cd ~/projects/my-app
codex # opens the REPL
> Explain this codebase.
> Add a /healthz endpoint to server.ts and write a vitest for it.
Codex will read files, plan changes, ask before running commands or writing (depending on approval policy), and stream a transcript in the terminal.
Useful flags
1234567891011121314codex # interactive
codex "<initial prompt>" # interactive, seeded
codex -m gpt-5 # pick a model
codex --model gpt-5-codex
codex --approval suggest|auto-edit|full-auto
codex --sandbox read-only|workspace-write|danger-full-access
codex --image ./screenshot.png # attach an image
codex --cd ~/other/repo # work from a different dir
codex -q "<prompt>" # quiet: print only the final answer
codex --resume # resume the last session
codex --resume <session-id>
codex --json # emit machine-readable events
codex --no-color
Interactive Mode (REPL)
Keystrokes inside the REPL:
12345678910Enter submit Shift+Enter newline Ctrl+C cancel current step (twice = quit) Ctrl+D quit Esc interrupt model mid-stream Tab autocomplete file paths / slash commands ↑ / ↓ history @<path> attach a file/dir to your message !<cmd> run a shell command directly (no agent)
File and image attachments
123> Look at @src/server.ts and @tests/server.spec.ts and add the missing case. > /image ./mock.png describe this design
Slash Commands
(Available in the REPL — type / to discover.)
12345678910111213141516171819/help show help /init create AGENTS.md for this project /model <name> switch model in this session /approval <mode> suggest | auto-edit | full-auto /sandbox <mode> read-only | workspace-write | danger-full-access /clear clear chat history /compact summarise older turns to free context /cost show token + dollar usage so far /save <file> save transcript to a file /resume resume a previous session /sessions list past sessions /mcp list configured MCP servers /tools list tools the model can call /diff show pending file changes vs disk /apply apply staged changes /discard discard staged changes /copy copy last assistant message /quit exit
Non-interactive (exec) Mode
For scripting and CI:
123456789101112131415161718codex exec "Run the tests and fix the first failure."
codex exec --approval full-auto "format and lint"
codex exec --cd ./api "write a README section about /healthz"
# Read prompt from stdin
echo "summarise CHANGELOG.md" | codex exec -
# Constrain to a sandbox (recommended in CI)
codex exec \
--sandbox workspace-write \
--approval auto-edit \
"bump the version to $(date +%Y.%m.%d)"
# Machine-readable output
codex exec --json "describe repo" | jq .
# Exit codes: 0 success, 1 user abort, 2 model error, 3 tool/shell error
Use in CI (GitHub Actions)
123456- uses: actions/setup-node@v4
with: { node-version: 20 }
- run: npm i -g @openai/codex
- env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
codex exec --approval full-auto --sandbox workspace-write \
"Update CHANGELOG.md for tag ${{ github.ref_name }}"
Approval & Sandboxing
Codex separates what it can change (sandbox) from when it asks first (approval).
Sandbox modes
| Mode | Reads | Writes | Net | Notes |
|---|---|---|---|---|
read-only | ✅ cwd | ❌ | ❌ | Inspect-only. Safe default for unknown repos. |
workspace-write | ✅ cwd | ✅ cwd | ❌ (toggleable) | Default. Cannot touch files outside cwd. |
danger-full-access | ✅ everywhere | ✅ everywhere | ✅ | No sandbox. Avoid unless you know why. |
Approval modes
| Mode | Behaviour |
|---|---|
suggest | Show every action; user approves each one. |
auto-edit | File edits auto-approved; shell commands still ask. |
full-auto | Everything auto-approved within the sandbox. |
12345# Set per session
codex --approval auto-edit --sandbox workspace-write
# Set persistently in config (see below)
Configuration File
~/.codex/config.toml (or ~/.config/codex/config.toml):
12345678910111213141516171819202122232425262728293031323334353637383940# Default model
model = "gpt-5"
# Default approval + sandbox
approval_policy = "auto-edit" # suggest | auto-edit | full-auto
sandbox_mode = "workspace-write" # read-only | workspace-write | danger-full-access
# Network access from inside the sandbox
[sandbox_workspace_write]
network_access = false # set true to allow curl/git fetch etc.
exclude_tmpdir_env_var = false
exclude_slash_tmp = false
# Provider / endpoint
model_provider = "openai"
# Multiple providers
[model_providers.openai]
name = "OpenAI"
base_url = "https://api.openai.com/v1"
wire_api = "responses"
[model_providers.azure]
name = "Azure OpenAI"
base_url = "https://my-resource.openai.azure.com/openai/v1"
env_key = "AZURE_OPENAI_API_KEY"
# History / sessions
[history]
persistence = "save-all" # save-all | none
# Notifications
notify = ["terminal-bell"] # or e.g. ["program", "/usr/local/bin/notify-codex"]
# Profile shortcuts: `codex --profile work`
[profiles.work]
model = "gpt-5-codex"
approval_policy = "full-auto"
sandbox_mode = "workspace-write"
Useful environment variables
123456OPENAI_API_KEY=...
OPENAI_BASE_URL=...
CODEX_HOME=~/.codex # override config dir
CODEX_DISABLE_TELEMETRY=1
CODEX_LOG=debug # debug, info, warn, error
Models & Providers
123456789101112# List available models for the current provider
codex models
# One-off model override
codex -m gpt-5
codex -m gpt-5-codex
codex -m o4-mini
codex -m gpt-5-mini
# Cheaper for routine edits
codex --profile cheap
Common picks (subject to availability on your account):
gpt-5— flagship reasoning.gpt-5-codex— coding-tuned variant.gpt-5-mini/gpt-5-nano— faster, cheaper.o4-mini— fast reasoning.
Codex talks to any provider that speaks the OpenAI Responses or Chat Completions API — point
base_urlat LM Studio, Ollama (/v1), Azure OpenAI, OpenRouter, etc.
MCP Servers
Codex is an MCP client — it can use tools exposed by any Model Context Protocol server.
1234567891011121314151617# ~/.codex/config.toml
[[mcp_servers]]
name = "github"
command = "npx"
args = ["-y", "@modelcontextprotocol/server-github"]
env = { GITHUB_PERSONAL_ACCESS_TOKEN = "ghp_..." }
[[mcp_servers]]
name = "filesystem"
command = "npx"
args = ["-y", "@modelcontextprotocol/server-filesystem", "/home/me/projects"]
[[mcp_servers]]
name = "postgres"
command = "uvx"
args = ["mcp-server-postgres", "postgresql://localhost/mydb"]
1234# In the REPL /mcp # list servers + tool inventories /tools # see all tools the model can call
Codex can also act as an MCP server itself for other clients:
12codex mcp serve
Project Memory (AGENTS.md)
Codex reads AGENTS.md from the project root (and merges with ~/.codex/AGENTS.md for global rules). Use it for repo-specific conventions.
12codex /init # generate a starter AGENTS.md
Example:
1234567# AGENTS.md
- Use pnpm, not npm.
- All new code must include vitest tests in __tests__ next to source.
- Don't touch files under /vendor or /generated.
- Prefer functional React components; no class components.
- Commit message format: Conventional Commits.
Codex respects .gitignore and additionally .codexignore (same syntax) for files it should not read or modify.
Notifications & Hooks
123456# Terminal bell when a turn finishes
notify = ["terminal-bell"]
# Shell out to a script after each turn (macOS example)
notify = ["program", "/usr/local/bin/notify-codex"]
1234# /usr/local/bin/notify-codex
#!/usr/bin/env bash
osascript -e "display notification \"$1\" with title \"Codex\""
The script receives a JSON payload on stdin with the event type and a summary.
Common Workflows
Add a feature with tests
1234> Add a /healthz endpoint to src/server.ts that returns {status:"ok"}. > Then add a vitest in src/__tests__/server.spec.ts. > Run the tests; fix anything that fails.
Refactor across many files
123codex --approval auto-edit \
"Rename UserModel -> Account everywhere, update imports, run tsc."
Generate a PR description from staged changes
12git diff --cached | codex exec - "Write a PR description with risk + test plan."
Triage a failing test
12> Run pnpm test, then debug the first failing test until it passes.
Drive a migration
123codex exec --approval full-auto --sandbox workspace-write \
"Migrate the project from CommonJS to ESM. Update package.json, fix imports, keep tests green."
Explore a repo before coding
123> @. give me a 10-line overview of this repo's architecture. > Which files own database access?
Cost / Token Management
123/cost # totals for this session /compact # summarise older turns to free context
Best practices:
- Start a fresh
/clearor--resume newbetween unrelated tasks. - Prefer
gpt-5-mini/o4-minifor mechanical edits; reach forgpt-5/gpt-5-codexfor design. - Use
--sandbox read-onlyfor exploration; only widen when needed. - Use
.codexignoreto keep huge generated dirs out of the model's view.
Troubleshooting
12345678910111213141516171819202122232425262728# Auth errors
codex login --status
unset OPENAI_API_KEY && codex login
# Wrong sandbox / "permission denied"
codex --sandbox workspace-write
# Network calls failing inside the sandbox
# (set network_access = true in config under [sandbox_workspace_write])
# Hanging on a long step
# Press Esc to interrupt the current model call
# Verbose logs
CODEX_LOG=debug codex
tail -f ~/.codex/log/codex-latest.log
# Reset everything
rm -rf ~/.codex
codex login
# MCP server not appearing
codex mcp doctor
codex mcp logs github
# Resume an aborted run
codex --resume
Quick Reference
123456789101112131415161718192021# Daily
codex # REPL
codex "do X" # REPL, seeded
codex exec "do X" # one-shot
# Models / approval / sandbox
codex -m gpt-5
codex --approval auto-edit
codex --sandbox workspace-write
# Sessions
codex --resume
codex --resume <id>
# MCP
codex mcp serve
codex mcp doctor
# Config
$EDITOR ~/.codex/config.toml
Tip: put a short
AGENTS.mdin every project. Codex will follow it like a style guide — far more reliable than re-explaining your conventions every session.
Continue Learning
Discover more cheatsheets to boost your productivity