OpenAI Codex CLI is an AI coding assistant that lives in your terminal: it reads code, edits files, runs commands, and reviews changes — interactively, or scripted and wired into CI. This guide covers the command-line tool only (including
codex execautomation). It does not cover the desktop app, IDE extensions, or the cloud product.
1. Install and update#
Pick whichever of the three install paths suits you:
# Option 1: npm (most common)npm install -g @openai/codex
# Option 2: Homebrew (macOS)brew install codex
# Option 3: official standalone installer (macOS / Linux)curl -fsSL https://chatgpt.com/codex/install.sh | sh
# Upgrade (for an npm install, just rerun the install command)npm install -g @openai/codex@latest
# Check the versioncodex --versionOther package managers work too: yarn global add @openai/codex / bun install -g @openai/codex / pnpm add -g @openai/codex.
2. Login and authentication#
The first run prompts you to log in, but you can also manage credentials by hand:
# Interactive login (ChatGPT account OAuth, or an API key)codex login
# Device-code flow (handy on remote / browserless machines)codex login --device-auth
# Log in with an API key from an environment variable (handy in CI)printenv OPENAI_API_KEY | codex login --with-api-key
# Show the current login statuscodex login status
# Log out (clears local credentials — remember this on shared machines)codex logout3. Quick start (interactive mode)#
cd into a project and start it:
# Launch the interactive TUI (no arguments)codex
# Start with an initial promptcodex "help me understand this project's architecture"
# Attach an image (screenshot / mockup / error dialog)codex -i error.png "find the problem from this error screenshot"
# Set the working directorycodex -C ~/projects/api "review this service"
# Two good first prompts# Tell me about this project# Find and fix bugs in my codebase with minimal, high-confidence changes.Beginners should do two things first:
/init # have Codex generate an AGENTS.md instruction file (type it inside the TUI)Then keep an eye on its edits with git status / git diff, and use Git checkpoints so you can always roll back.
4. Slash commands in interactive mode#
Type / in the TUI composer to open the command menu. The usual suspects:
| Command | What it does |
|---|---|
/init | Scaffold an AGENTS.md project instruction file in the current directory |
/status | Inspect the session config (model, approval policy, token usage, remaining context) |
/permissions | Adjust the approval / permission mode (Read Only, Auto, …) |
/model | Switch model and reasoning effort |
/fast | Toggle the model’s fast service tier (on / off / status) |
/plan | Enter plan mode: produce a plan before touching anything |
/goal <objective> | Set / view / pause / clear the task objective |
/review | Run one code review over the workspace changes |
/diff | Show the Git diff (untracked files included) |
/mention <path> | Add a file to the conversation context |
/compact | Compress earlier turns to free up context |
/new | Start a fresh conversation in the same session (resets context) |
/resume | Resume a past conversation from the session list |
/fork | Copy the current conversation into a new thread (to explore alternatives) |
/side | Open a throwaway side conversation without derailing the main thread |
/agent | Switch between / inspect subagent threads |
/skills | Browse and use local skills |
/mcp | List the configured MCP tools (/mcp verbose for details) |
/apps / /plugins / /hooks | Browse apps (connectors) / plugins / lifecycle hooks |
/ide | Pull the file and selection open in your IDE into the next prompt |
/vim / /keymap / /theme / /statusline / /title | Composer Vim mode / keymap / theme / status line / terminal title |
/personality | Set the communication style (friendly / pragmatic / none) |
/memories | Configure memory generation and enablement |
/ps / /stop | Inspect / stop background terminal tasks |
/copy | Copy the most recent reply (same as Ctrl+O) |
/raw | Toggle raw scrollback mode, which makes long output easier to copy |
/debug-config | Print config-layer diagnostics (when a setting refuses to take effect) |
/feedback / /logout / /quit (/exit) | Feedback / log out / quit |
Tip: while a task is running you can still queue a slash command with Tab; it runs once the current turn finishes.
5. Non-interactive mode: codex exec (scripts / CI)#
codex exec (alias codex e) skips the TUI, runs once, and exits — built for automation and pipelines:
# Basic use: one task, output straight to the terminalcodex exec "fix the failing unit tests"
# Read the prompt from stdinecho "add an install section to the README" | codex exec -
# Pipe data in and pass a prompt at the same timecat error.log | codex exec "diagnose this stack trace and suggest a fix"
# JSON event stream (easy to process with jq and friends)codex exec --json "list the 5 riskiest files" | jq
# Save the final reply to a filecodex exec "write release notes for the last 10 commits" -o notes.md
# Force a structured JSON replycodex exec "extract project metadata" --output-schema schema.json -o meta.json
# Resume the previous exec session to follow upcodex exec resume --last "now fix the issues you just found"
# Quiet, approval-free run in CIcodex exec --approve-for-me --quiet "update the CHANGELOG and prep the next release"A GitHub Actions example:
name: Codex Reviewon: [pull_request]jobs: review: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: openai/codex-action@v1 with: openai-api-key: ${{ secrets.OPENAI_API_KEY }} prompt: "Review the changes in this PR and point out potential problems"Useful environment variables:
| Variable | What it does |
|---|---|
OPENAI_API_KEY | API key (or store one via codex login) |
CODEX_QUIET_MODE=1 | Quiet mode: less interactive noise |
CODEX_DISABLE_PROJECT_DOC=1 | Stop loading project docs such as AGENTS.md |
DEBUG=true | Print full API requests/responses (for troubleshooting) |
CODEX_TOKEN_LOG=~/tokens.csv | Log token usage for every request |
6. Session management: resume / fork#
Codex stores sessions locally, so you can always return to earlier work:
# Pick a past session interactivelycodex resume
# Jump straight back into the most recent sessioncodex resume --last
# Fork a new session off an existing one (keep the original, branch out)codex fork --lastInside the TUI, /resume and /fork do the same.
7. Code review: codex review#
# Review the uncommitted workspace changes (workspace untouched)codex review
# Review against a base branch (PR style)codex review --base main
# Review a specific commitcodex review --commit HEAD~1
# Review a specific PRcodex review --pr 1238. Common CLI flags#
| Flag | Short | Description |
|---|---|---|
--model <name> | -m | Pick a model, e.g. -m gpt-5-codex (availability depends on your plan) |
--sandbox <mode> | -s | Sandbox policy: read-only / workspace-write / danger-full-access |
--ask-for-approval <policy> | -a | Approval policy: on-request (ask as needed) / never (stop asking) |
--full-auto | Preset combo: workspace-write + on-request, a low-friction automatic mode | |
--yolo | Alias for --dangerously-bypass-approvals-and-sandbox: no sandbox, no approvals — dangerous, hardened environments only | |
--image <path> | -i | Attach images to the initial prompt; separate multiple paths with commas |
--cd <path> | -C | Set the agent’s working directory |
--add-dir <path> | Grant write access outside the main workspace; repeatable | |
--config <key=value> | -c | Override one config value for this run (TOML-parsable values win) |
--profile <name> | -p | Load a profile from ~/.codex/<name>.config.toml |
--search | Enable live web search | |
--oss | Use a local open-source model (LM Studio / Ollama) | |
--local-provider <name> | Select the local provider: lmstudio or ollama | |
--enable/--disable <feature> | Force a feature flag on or off (same as -c features.x=true/false) | |
--no-alt-screen | Disable the TUI alternate screen (steadier under tmux / scripts) | |
--strict-config | Error out on unknown config fields (good for catching typos) | |
--remote <ws://...> | Connect to a remote app-server (experimental) | |
--version / --help | -V / -h | Version / help |
PROMPT (positional) | Optional initial prompt; omit it to land straight in the TUI |
Every subcommand takes --help for the most accurate, up-to-date flags — codex exec --help, for instance.
9. Sandbox and approval modes (the security core)#
Codex isolates the commands the model generates with native OS sandboxing: Seatbelt on macOS, Bubblewrap on Linux, restricted tokens on Windows.
Sandbox modes (-s):
| Mode | Permissions | Typical use |
|---|---|---|
read-only | Read only: no writes, no network | Safe exploration, code audit |
workspace-write | Read/write inside the working directory | Day-to-day development (the default in a Git repo) |
danger-full-access | Full access | System administration tasks, used with care |
Approval policies (-a):
| Policy | Behavior |
|---|---|
on-request | The model pauses to ask when needed (default) |
never | Stops asking; commands just run |
Common combinations:
# Safe exploration: read-only plus asking on requestcodex -s read-only -a on-request "audit this project for injection flaws"
# Everyday coding (the default behavior)codex -s workspace-write -a on-request "refactor the auth module and run the tests"
# Automatic mode: no approvals inside the sandboxcodex --full-auto "run the tests and fix the failing cases"
# Dangerous mode (only inside a CI sandbox or a disposable container)codex --yolo "set up the whole dev environment from scratch"You can change course mid-session with /permissions at any time.
10. Models and reasoning effort#
# Pick a model on the command linecodex -m gpt-5-codex "refactor this module"
# Override reasoning effort for one runcodex -c model_reasoning_effort=high "design a database migration plan"The model list is not baked into the CLI; it loads dynamically for your ChatGPT plan or API account. Inside the TUI, /model opens a picker for both model and reasoning effort, and /fast toggles the fast service tier.
11. Configuration: config.toml / profiles / AGENTS.md#
Config locations and precedence (high → low):
CLI flags (-c key=value) > Profile (~/.codex/<name>.config.toml) > Project config (.codex/config.toml) > User config (~/.codex/config.toml) > System config > DefaultsA user config example (~/.codex/config.toml):
model = "gpt-5-codex"model_reasoning_effort = "high"approval_policy = "on-request"sandbox_mode = "workspace-write"web_search = "cached" # or "live" / "off"Project-level config (shared with the team, committed to the repo): create .codex/config.toml at the project root to give different projects different models and sandbox policies.
Profiles (flipping between environments):
codex --profile ci "run the checks" # uses ~/.codex/ci.config.tomlAGENTS.md project instructions (the equivalent of Claude Code’s CLAUDE.md) merge bottom-up in this order:
~/.codex/AGENTS.md # personal global instructionsrepo root AGENTS.md # shared project conventions (commit it to Git)subdirectory AGENTS.md # per-directory / per-feature notesUse /init to generate the scaffold, then fill it in with your team’s conventions, for example:
## Project conventions- Use TypeScript strict mode- Every function needs a JSDoc comment- Keep test coverage above 80%12. MCP and extensions#
# List the configured MCP serverscodex mcp list
# Add a local MCP servercodex mcp add context7 -- npx -y @upstash/context7-mcp
# Connect to a remote HTTP MCP server (Figma, for example)codex mcp login figma
# Expose Codex itself as an MCP servercodex mcp-serverInside the TUI, /mcp lists the tools this session can call.
13. Recipes for common tasks#
# Understand an unfamiliar projectcodex "tell me what this project does and what the main modules are"
# Fix a bugcodex "find and fix bugs in my codebase with minimal, high-confidence changes"
# Refactorcodex "refactor the Dashboard component to React Hooks and get the tests passing"
# Write testscodex "write unit tests for utils/date.ts"
# Generate a migration / scaffoldcodex "generate the SQL migration that adds a users table"
# Bulk renamecodex "rename every *.jpeg to *.jpg with git mv and update the references"
# Explain a regexcodex "explain what this regex means: ^(?=.*[A-Z]).{8,}$"
# Security auditcodex "scan for vulnerabilities and write a security review report"
# Update the CHANGELOG in CIcodex exec --full-auto --quiet "update the CHANGELOG and prep the next release"
# Build a UI from a screenshotcodex -i mockup.png "implement this page from the mockup"
# Look up the current best practice onlinecodex --search "find the currently recommended best-practice Vite config"
# Review your own changes before committingcodex review --base main14. Best practices and gotchas#
- Git checkpoints are your lifeline: Codex edits code directly, so commit before and after a task and
git resetif things go sideways. - Start in Read Only: point
codex -s read-onlyat a new project first to explore without writes, then loosen up once you know how it behaves. - Prefer
--full-autoover--yolo: the former stays inside the sandbox, the latter has no protection at all. - Use
codex execfor CI and automation: pair it with--json/-o/--output-schemafor machine-readable output. - Pin conventions in AGENTS.md: writing team rules down once costs fewer tokens and behaves more consistently than repeating them every prompt.
/compactwhen context grows: compress the conversation after long tasks so you don’t burn the context window early.codex logouton shared machines: clear the local credentials when you’re done.- When a flag is unclear, read the help: whatever
codex --helpandcodex exec --helpprint for your installed version is the truth (the CLI moves fast; model names and feature flags change with releases).
Appendix: cheat sheet#
install npm install -g @openai/codexlogin codex login / codex login status / codex logoutinteractive codex ["prompt"] / codex -i image "prompt"scripting codex exec "task" / --json / -o file / stdin pipesessions codex resume [--last] / codex fork --lastreview codex review [--base main | --commit | --pr 123]security -s read-only|workspace-write|danger-full-access -a on-request|never / --full-auto / --yolo (dangerous)models -m <model> / -c model_reasoning_effort=highdirectories -C <path> / --add-dir <path>config -c key=value / --profile <name> / ~/.codex/config.tomlinstructions /init generates AGENTS.mdin-session /status /permissions /model /diff /review /compact /new /quit