Skip to main content
gradually.ai logogradually.ai
  • Blog
  • About Us
AI Newsletter
AI Newsletter
  1. Home
  2. AI Blog

Codex Commands: The Complete Reference

Every Codex CLI command, flag, slash command, and shortcut at a glance. The most thorough reference for OpenAI's coding agent.

FHFinn Hillebrandt
May 14, 2026
Auf Deutsch lesen
AI Programming
Codex Commands: The Complete Reference
𝕏XShare on XFacebookShare on FacebookLinkedInShare on LinkedInPinterestShare on PinterestThreadsShare on ThreadsFlipboardShare on Flipboard
Links marked with * are affiliate links. If a purchase is made through such links, we receive a commission.

You installed Codex, typed codex into your terminal, and wondered: "Okay, now what?"

Same here. OpenAI's coding agent ships with dozens of CLI commands, more than 30 slash commands in the interactive TUI, and a separate desktop app with its own shortcuts. Without a reference, you lose track fast.

This article lays out every Codex command in one place. Each CLI command, every slash command, all flags, every keyboard shortcut. Sorted by CLI and App so you see at a glance what works where. It's the most thorough Codex reference you'll find in English.

TL;DRKey Takeaways
  • 30+ CLI commands cover the whole tool, from codex exec (non-interactive execution) to codex review (code review) and codex cloud (cloud tasks)
  • 34 slash commands in the interactive CLI TUI, 5 in the desktop app. The tables show exactly what's available where
  • Three sandbox modes (read-only, workspace-write, danger-full-access) and four approval policies control what Codex can do on your system
  • Codex Cloud offloads long-running tasks to remote sandboxed environments, with best-of-N attempts on demand

Installing and Starting Codex

Codex CLI installs via npm or Homebrew. On first launch, Codex asks you to sign in with your ChatGPT account or an API key.

# Install via npm
npm install -g @openai/codex

# Or via Homebrew (native Rust binary, faster)
brew install codex
# Sign in interactively (opens browser for OAuth)
codex login

# Sign in with an API key
echo $OPENAI_API_KEY | codex login --with-api-key

# Check login status
codex login status

# Sign out
codex logout
# Start an interactive TUI session
codex

# Start with an initial prompt
codex "Explain the architecture of this project"

# Run non-interactively (for scripts)
codex exec -s workspace-write -m gpt-5.5 "Refactor auth.ts"

# Launch the desktop app
codex app
Tip
Always start Codex inside the right project folder. You can also set the working directory explicitly with --cd /path/to/project.

CLI Commands (Overview)

Codex comes in two flavors. The CLI runs in your terminal. The App is a desktop application for macOS and Windows. The "Available in" column tells you where each command works.

Command
Description
Available in
codexStarts the interactive TUI session in the terminalCLI
codex appLaunches the Codex desktop app (macOS/Windows)App
codex execRuns a task non-interactively and streams output to stdoutCLI
codex exec resumeResumes a previous session non-interactivelyCLI
codex reviewCode review (uncommitted changes, branch diff, or commit)CLI
codex applyApplies a diff from a Codex session or cloud taskCLI
codex resumeResumes an interactive session via session pickerCLI
codex forkForks a session into a new threadCLI
codex cloud execSubmits a cloud task in a sandboxed environmentCLI
codex cloud listLists cloud tasks (with filter and pagination)CLI
codex cloud statusShows the status of a cloud taskCLI
codex cloud diffShows the diff produced by a cloud taskCLI
codex cloud applyApplies a cloud task diff locallyCLI
codex mcp addAdds an MCP server (stdio or HTTP)CLI
codex mcp listLists configured MCP serversCLI
codex mcp getShows the config for a specific MCP serverCLI
codex mcp removeRemoves an MCP serverCLI
codex mcp loginOAuth login for an MCP serverCLI
codex mcp logoutRemoves OAuth credentials for an MCP serverCLI
codex features listShows feature flags with status and maturity stageCLI
codex features enable/disablePermanently enables or disables a feature flagCLI
codex loginSign in via OAuth or API keyCLI
codex login statusShows current login statusCLI
codex logoutRemoves stored credentialsCLI
codex sandboxRuns a command inside the Codex sandbox (macOS/Linux/Windows)CLI
codex completionGenerates shell completions (bash, zsh, fish, elvish, PowerShell)CLI
codex updateChecks for updates and installs a new versionCLI
codex execpolicyValidates exec policy rule files before savingCLI
codex mcp-serverRuns Codex itself as an MCP server (stdio transport)CLI
codex plugin marketplaceManages plugin marketplace sources (add, remove, upgrade)CLI
Note
codex exec is the command you'll use most for automation. It runs tasks non-interactively and prints the result to stdout. Perfect for scripts and CI/CD pipelines.

codex exec: Flags for Non-Interactive Execution

codex exec is your workhorse for automated workflows. Without any flags, Codex waits for human approval, and scripts hang. So always set a sandbox mode.

# Standard pattern for automated execution
codex exec -s workspace-write -m gpt-5.5 "your prompt"

# Maximum reasoning depth
codex exec -s workspace-write -m gpt-5.5 \
  -c model_reasoning_effort='"xhigh"' "complex task"

# Read-only for analysis (no file changes)
codex exec -s read-only -m gpt-5.5 "Analyze the architecture"
Flag
Description
Example
--model, -mOverrides the model from your config-m gpt-5.5
--sandbox, -sSandbox mode: read-only, workspace-write, or danger-full-access-s workspace-write
--ask-for-approval, -aApproval policy: untrusted, on-failure, on-request, never-a on-request
--cd, -CSets the working directory for the agent-C /path/to/project
--add-dirGrants additional writable directories--add-dir ../backend
--image, -iAttaches images to the prompt (repeatable)-i screenshot.png
--config, -cOverrides config.toml values (TOML syntax)-c model_reasoning_effort='"xhigh"'
--profile, -pLoads a named config profile from config.toml-p fast-profile
--enable / --disableEnables or disables a feature flag for this run--enable search_tool
--jsonOutputs events as JSONL (one JSON line per event)codex exec --json "..."
--output-last-message, -oSaves the agent's last message to a file-o /tmp/result.txt
--output-schemaJSON Schema file that constrains the final response--output-schema schema.json
--ephemeralSession is not persisted to diskcodex exec --ephemeral "..."
--skip-git-repo-checkAllows running outside a Git repocodex exec --skip-git-repo-check "..."
--colorControls ANSI colors: always, never, auto--color never
--ossUses the local open-source provider (Ollama)codex exec --oss "..."
--full-autoDeprecated. Alias for ,[object Object],. Use ,[object Object], directly insteadcodex exec --full-auto "..."
Warning
--full-auto is deprecated. Use -s workspace-write instead (or -s workspace-write -a on-request for the same behavior).

Common Patterns

# Attach images (screenshots, design specs)
codex exec -s workspace-write -m gpt-5.5 -i screenshot.png "Implement this UI"

# Multiple writable directories
codex exec -s workspace-write -C apps/frontend --add-dir ../backend "Sync API types"

# JSON output for scripts
codex exec -s workspace-write --json "List all TODO comments"

# Save the result to a file
codex exec -s workspace-write -o /tmp/result.txt "Summarize this codebase"

# Structured output with JSON Schema
codex exec -s workspace-write --output-schema schema.json "Extract all API endpoints"

# Pipe the prompt via stdin
cat prompt.txt | codex exec -s workspace-write -

# Use a config profile
codex exec -s workspace-write -p thorough "Thorough analysis"

# Local open-source model (Ollama)
codex exec --oss -s workspace-write "Explain this function"

Code Review

codex review analyzes code changes non-interactively and prints the results to stdout. It doesn't modify files.

Flag
Description
Example
--uncommittedReviews staged, unstaged, and untracked changescodex review --uncommitted
--baseReviews changes against a base branchcodex review --base main
--commitReviews a specific commitcodex review --commit abc123
--titleOptional title for the review summarycodex review --title "Add auth"
PROMPTCustom review instructions (can also be piped via stdin with -)codex review "Focus on security"
# Review uncommitted changes (staged + unstaged + untracked)
codex review --uncommitted

# Review changes against a branch (before opening a PR)
codex review --base main

# Review a specific commit
codex review --commit abc123

# Review with a title and a custom focus
codex review --base main --title "Add auth" "Focus on security"

# Review via exec with JSON output
codex exec review --uncommitted --json

Session Management

Codex stores sessions locally under ~/.codex/sessions/. You can resume them any time, fork them, or pick them up non-interactively.

# Interactive: open the session picker
codex resume

# Interactive: resume the most recent session directly
codex resume --last

# Non-interactive: resume the latest session with a new prompt
codex exec resume --last -s workspace-write -m gpt-5.5 \
  "Now add error handling"

# Resume a specific session by UUID
codex exec resume 7f9f9a2e-1b3c-4c7a... -s workspace-write -m gpt-5.5 \
  "Implement the plan"

# Fork a session (new thread from existing context)
codex fork --last
# Apply a diff from a local session
codex apply TASK_ID

# Apply a diff from a cloud task
codex cloud apply TASK_ID

# Apply a specific attempt (when using --attempts N)
codex cloud apply TASK_ID --attempt 2
Tip
Sessions started with --ephemeral aren't saved to disk. Use this for quick one-off questions where you don't need any history.

Codex Cloud

Codex Cloud runs tasks in sandboxed remote environments. All subcommands are non-interactive. The --env flag is required.

Flag
Description
Example
--envRequired: target environment ID for the cloud task--env ENV_ID
--attemptsNumber of attempts (best-of-N), default: 1, max: 4--attempts 3
--branchGit branch the task should run on--branch feature/auth
--jsonMachine-readable JSON output (for codex cloud list)codex cloud list --json
--limitMaximum number of tasks returned (1-20)codex cloud list --limit 5
--cursorPagination cursor from the previous callcodex cloud list --cursor CURSOR
--attemptAttempt number for diff/apply (when using --attempts N)codex cloud diff TASK_ID --attempt 2
# Submit a task
codex cloud exec --env ENV_ID "Refactor the payment module"

# Best-of-3: run three attempts
codex cloud exec --env ENV_ID --attempts 3 "Fix the flaky test"

# Run on a specific branch
codex cloud exec --env ENV_ID --branch feature/auth "Add OAuth"

# List tasks
codex cloud list
codex cloud list --json --limit 5

# Check the status
codex cloud status TASK_ID

# Show the diff (specific attempt)
codex cloud diff TASK_ID --attempt 2

Sandbox Modes

The sandbox limits what Codex can do on your system. You pick the mode with -s or --sandbox.

Mode
Read
Write
Network
When to use
read-onlyAnywhereNowhereNoQuestions, explanations, code analysis
workspace-writeAnywhereWorking dir onlyNoDefault for most tasks
danger-full-accessAnywhereAnywhereYesOnly when truly needed (e.g., installing packages)

Codex also ships with a codex sandbox command that lets you run any command inside the sandbox without involving the agent:

# Run a command in the sandbox (macOS)
codex sandbox macos -- npm test

# Log denied accesses for debugging
codex sandbox macos --log-denials -- ./build.sh

# Linux (Landlock + seccomp)
codex sandbox linux -- python3 script.py

Approval Policies

Approval policies control when Codex asks for permission before running a command. You set them with -a or --ask-for-approval.

Policy
Behavior
untrustedOnly trusted commands (ls, cat, sed) run without approval
on-failureAll commands run; approval only on failure
on-requestThe model decides when to ask for approval
neverNever asks for approval; failures go straight back to the model
Note
Inside the interactive TUI you switch approval mode with /permissions. Three presets are available: Auto (default), Read Only, and Full Access.

MCP Servers (Model Context Protocol)

Codex can connect to MCP servers for extra tools (databases, APIs, GitHub, and more). All management commands are non-interactive.

# List configured servers
codex mcp list
codex mcp list --json

# Show a server's config
codex mcp get my-server
codex mcp get my-server --json

# Add a stdio server
codex mcp add my-server -- npx -y @my/mcp-server
codex mcp add my-server --env API_KEY=sk-123 -- node server.js

# Add an HTTP server
codex mcp add my-server --url https://mcp.example.com/sse
codex mcp add my-server --url https://mcp.example.com \
  --bearer-token-env-var MY_TOKEN_VAR

# Remove a server
codex mcp remove my-server

# OAuth login for an MCP server
codex mcp login my-server --scopes "read,write"
codex mcp logout my-server
Tip
With codex mcp-server you can run Codex itself as an MCP server. That makes it possible to plug Codex into other tools that speak MCP.

Slash Commands (CLI and App)

Slash commands are available in the interactive TUI (started with codex) and in the desktop app. Type / in the composer to open the list. While a task is running, you can type a slash command and press Tab to queue it for the next turn.

The CLI TUI has far more slash commands than the app. The "Available in" column shows you where each one works.

Command
Description
Available in
/agentSwitches the active agent threadCLI
/appsBrowses and inserts connectors/appsCLI
/clearClears the terminal and starts a new chatCLI
/compactSummarizes the conversation to free up tokensCLI
/copyCopies the last response to the clipboard (also ,[object Object],)CLI
/debug-configPrints config layer diagnosticsCLI
/diffShows the Git diff including untracked filesCLI
/exitCloses the CLI session (alias: ,[object Object],)CLI
/experimentalToggles optional features (Apps, Smart Approvals, Goals)CLI
/fastToggles Fast mode (,[object Object],, ,[object Object],, ,[object Object],)CLI
/feedbackSends feedback and logs to the developersCLI + App
/forkBranches the current conversation into a new threadCLI
/goalSets a persistent task objective (,[object Object],, ,[object Object],, ,[object Object],)CLI
/initGenerates an AGENTS.md project context fileCLI
/keymapInspects and updates keyboard shortcut bindings for the TUICLI
/logoutSigns out of CodexCLI
/mcpLists MCP tools (,[object Object], for details)CLI + App
/mentionAttaches files to the conversationCLI
/modelSwitches the active AI modelCLI
/newStarts a fresh conversation in the same CLI instanceCLI
/permissionsConfigures approval mode (Auto, Read Only, Full Access)CLI
/personalityChanges communication style (,[object Object],, ,[object Object],, ,[object Object],)CLI
/planActivates plan mode with an optional inline promptCLI
/plan-modeToggles multi-step planning modeApp
/pluginsManages installed plugins (install, toggle, inspect)CLI
/psShows background terminalsCLI
/resumeLoads a previous session via the session pickerCLI
/reviewAnalyzes changes in the working tree (code review)CLI + App
/sandbox-add-read-dirGrants the sandbox read access to a directory (Windows only)CLI
/sideStarts an ephemeral side conversationCLI
/statusShows active model, approval policy, writable roots, and token usageCLI + App
/statuslineConfigures items in the TUI footerCLI
/stopHalts all background terminalsCLI
/titleConfigures items in the terminal titleCLI

Keyboard Shortcuts: CLI (TUI)

These shortcuts work in the interactive terminal interface (started with codex). You can remap them with /keymap.

Shortcut
Function
Context
Ctrl+CCancels the current executionWhile the agent is working
Ctrl+DCloses the CLIWhen the input buffer is empty
Ctrl+GOpens external editor (VISUAL or EDITOR)For long prompts
Ctrl+LClears the screen (without starting a new chat)When the terminal gets too cluttered
Ctrl+OCopies the last response to the clipboardAfter a response
Ctrl+RReverse search through prompt historyIn the composer
Alt+,Lowers the reasoning depthDuring the session
Alt+.Raises the reasoning depthDuring the session
Up / DownNavigates the draft history in the composerIn the input field
TabQueues follow-up text, slash commands, or shell commandsWhile the agent is working
Esc + EscEdits the previous user messageIn the composer
@Fuzzy file search for attaching filesIn the input field
!Runs a shell command directlyAt the start of the input

Keyboard Shortcuts: Codex App

The desktop app (started with codex app) has its own shortcuts that follow common IDE conventions. On Windows, replace Cmd with Ctrl.

Shortcut
Function
Cmd+Shift+P / Cmd+KOpens the command palette
Cmd+,Opens settings
Cmd+OOpens a folder
Cmd+N / Cmd+Shift+ONew thread
Cmd+FFind in thread
Cmd+BToggle sidebar
Cmd+Option+BToggle diff panel
Cmd+JToggle terminal
Cmd+Shift+[ / ]Switch to previous / next thread
Cmd+[ / ]Navigate back / forward
Cmd++ / Cmd+-Increase / decrease font size
Ctrl+LClear terminal
Ctrl+MStart dictation
Note
The app also supports deeplinks via the codex:// scheme, for example codex://settings for settings or codex://new?prompt=your+prompt for a new thread with a prompt.

Configuration (config.toml)

Codex config lives at ~/.codex/config.toml. You can set defaults and define named profiles.

Setting
Description
Possible values
modelDefault model for all sessions[object Object], (recommended), ,[object Object],, ,[object Object],, ,[object Object]
model_reasoning_effortReasoning depth for complex tasks[object Object],, ,[object Object],, ,[object Object],, ,[object Object]
personalityCommunication style of the agent[object Object],, ,[object Object],, ,[object Object]
web_searchWeb search mode[object Object], (default), ,[object Object],, ,[object Object]
# ~/.codex/config.toml

# Default settings
model = "gpt-5.5"
model_reasoning_effort = "high"

# Profile for quick tasks
[profiles.quick]
model = "gpt-4.1-mini"
model_reasoning_effort = "low"

# Profile for thorough work
[profiles.thorough]
model = "gpt-5.5"
model_reasoning_effort = "xhigh"

# Project trust level
[projects."/path/to/project"]
trust_level = "trusted"
# Override a single value
codex exec -s workspace-write -c model='"gpt-5.5"' "Task"

# Set sandbox permissions
codex exec -s workspace-write \
  -c 'sandbox_permissions=["disk-full-read-access"]' "Task"

# Load a profile with -p
codex exec -s workspace-write -p quick "Quick question"

Feature Flags

Feature flags control both experimental and stable features. Changes via enable and disable are written permanently to config.toml. Per-run toggles with --enable and --disable only apply to the current run.

# List all feature flags with status and maturity
codex features list

# Permanently enable / disable a feature
codex features enable search_tool
codex features disable shell_snapshot

# Enable for this run only (not persistent)
codex exec -s workspace-write --enable search_tool \
  --disable shell_snapshot "Task"

Global Flags

These flags are available on almost every Codex command:

Flag
Description
--config, -cOverrides config.toml values. Dotted paths for nesting. Values are parsed as TOML.
--enableEnables a feature flag for this run (repeatable)
--disableDisables a feature flag for this run (repeatable)
--help, -hShows help
--version, -VShows the version number

Troubleshooting

Problem
Likely cause
Solution
Authentication failsStale token or wrong API keyRun codex logout, then codex login again
Codex hangs on codex execNo sandbox mode set (waiting for approval)Always pass -s workspace-write or -a on-request
Command blocked in sandboxNetwork access or write access outside the working directoryUse -s danger-full-access (only when needed)
MCP server doesn't connectMissing dependencies or wrong pathCheck codex mcp get server-name, then remove and add again
Session won't resumeSession was started with --ephemeralRestart without --ephemeral so sessions are saved
Cloud task shows no diffTask is still running or has failedCheck codex cloud status TASK_ID, then try again
# Diagnose the config layers
# (in the interactive TUI)
/debug-config

# Show available models as JSON
codex debug models

# Show only the bundled model catalog (no API refresh)
codex debug models --bundled

# Validate exec policy rules (before saving)
codex execpolicy --rules rules.toml -- npm test

# Log sandbox denials (debugging)
codex sandbox macos --log-denials -- ./build.sh

FAQ

Frequently Asked Questions

𝕏XShare on XFacebookShare on FacebookLinkedInShare on LinkedInPinterestShare on PinterestThreadsShare on ThreadsFlipboardShare on Flipboard
FH

Finn Hillebrandt

AI Expert & Blogger

Finn Hillebrandt is the founder of Gradually AI, an SEO and AI expert. He helps online entrepreneurs simplify and automate their processes and marketing with AI. Finn shares his knowledge here on the blog in 50+ articles as well as through his ChatGPT Course and the AI Business Club.

Learn more about Finn and the team, follow Finn on LinkedIn, join his Facebook group for ChatGPT, OpenAI & AI Tools or do like 17,500+ others and subscribe to his AI Newsletter with tips, news and offers about AI tools and online business. Also visit his other blog, Blogmojo, which is about WordPress, blogging and SEO.

Similar Articles

How to Create the Perfect AGENTS.md (incl. Template)
AI Programming

How to Create the Perfect AGENTS.md (incl. Template)

May 15, 2026
FHFinn Hillebrandt
Claude Code: The Complete Beginner's Guide
AI Programming

Claude Code: The Complete Beginner's Guide

May 15, 2026
FHFinn Hillebrandt
How to Create the Perfect CLAUDE.md (incl. Template)
AI Programming

How to Create the Perfect CLAUDE.md (incl. Template)

May 15, 2026
FHFinn Hillebrandt
OpenAI Codex Statistics 2026: Key Numbers, Data & Facts
AI Programming

OpenAI Codex Statistics 2026: Key Numbers, Data & Facts

May 15, 2026
FHFinn Hillebrandt
Gemini CLI Commands: The Ultimate Menu
AI Programming

Gemini CLI Commands: The Ultimate Menu

May 15, 2026
FHFinn Hillebrandt
Claude Code vs. Gemini CLI vs. OpenAI Codex: The Ultimate Comparison
AI Programming

Claude Code vs. Gemini CLI vs. OpenAI Codex: The Ultimate Comparison

May 8, 2026
FHFinn Hillebrandt

Stay Updated with the AI Newsletter

Get the latest AI tools, tutorials, and exclusive tips delivered to your inbox weekly

Unsubscribe anytime. About 4 to 8 emails per month. Consent includes notes on revocation, service provider, and statistics according to our Privacy Policy.

gradually.ai logogradually.ai

Germany's leading platform for AI tools and knowledge for online entrepreneurs.

AI Tools

  • AI Chat
  • ChatGPT in German
  • Text Generator
  • Prompt Enhancer
  • Prompt Link Generator
  • FLUX AI Image Generator
  • AI Art Generator
  • Midjourney Prompt Generator
  • Veo 3 Prompt Generator
  • AI Humanizer
  • AI Text Detector
  • Gemini Watermark Remover
  • All Tools →

Creative Tools

  • Blog Name Generator
  • AI Book Title Generator
  • Song Lyrics Generator
  • Artist Name Generator
  • Team Name Generator
  • AI Mindmap Generator
  • Headline Generator
  • Company Name Generator
  • AI Slogan Generator
  • Brand Name Generator
  • Newsletter Name Generator
  • YouTube Channel Name Generator

Business Tools

  • API Cost Calculator
  • Token Counter
  • AI Ad Generator
  • AI Copy Generator
  • Essay Generator
  • Story Generator
  • AI Rewrite Generator
  • Blog Post Generator
  • Meta Description Generator
  • AI Email Generator
  • Email Subject Line Generator
  • Instagram Bio Generator
  • AI Hashtag Generator

Resources

  • Claude Code MCP Servers
  • Claude Code Skills
  • n8n Hosting Comparison
  • OpenClaw Hosting Comparison
  • Claude Code Plugins
  • Claude Code Use Cases
  • Claude Cowork Use Cases
  • OpenClaw Use Cases
  • Changelogs

© 2025 Gradually AI. All rights reserved.

  • Blog
  • About Us
  • Legal Notice
  • Privacy Policy