OpenAI Codex Commands Cheat Sheet (2026 Update)

Codex commands cheat sheet for developers: CLI commands, slash commands, flags, config keys, environment variables, sandbox settings, MCP, and real workflows.

Codex CLI is OpenAI’s local coding agent for the terminal. It can inspect a repository, edit files, run commands, review changes, and continue previous work through saved sessions.

This cheat sheet is for developers who use Codex from a shell, a terminal UI, or automation scripts. It separates shell commands, interactive slash commands, CLI flags, configuration keys, environment variables, and experimental features so each command is used in the right place.

Use the tables as a working reference. Start with the stable commands, then add flags, sandbox settings, MCP servers, and non-interactive workflows as your usage gets more advanced.

Last audited: July 30, 2026

New to Codex CLI?

Install Codex with one of the commands below, open a project directory, and run codex. The first launch opens the sign-in flow.

Platform or methodCommand
macOS or Linux installercurl -fsSL https://chatgpt.com/codex/install.sh | sh
Windows PowerShellpowershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex"
npmnpm install -g @openai/codex
Homebrew on macOSbrew install --cask codex
Check the installed versioncodex --version
Update Codexcodex update
cd /path/to/your-project
codex

Quick Classification

TypeWhere to use itExample
CLI commandType in a shell or terminal.codex exec "Fix the failing tests"
Slash commandType inside the interactive Codex TUI./status
TUI shortcutPress or type inside the TUI composer.@ or Tab
Global flagAdd to codex or supported subcommands.--sandbox workspace-write
Subcommand flagAdd only to the documented subcommand.codex exec --json
Config keySave in $CODEX_HOME/config.toml.approval_policy = "on-request"
Environment variableSet for one shell, installer, or automation run.CODEX_HOME

Codex CLI Commands

Use these commands from the shell.

CommandUse
codex [PROMPT]Open the terminal UI, optionally with an initial prompt.
codex app [PATH]Open the ChatGPT desktop app on macOS or Windows; macOS can open a workspace path.
codex apply <TASK_ID>Apply the latest diff from a Codex cloud chat to the local working tree. Alias: codex a.
codex archive <SESSION>Archive a saved interactive session by ID or name.
codex completion <shell>Generate completion scripts for Bash, Zsh, Fish, or PowerShell.
codex delete <SESSION>Permanently delete a saved interactive session by ID or name.
codex doctorGenerate a diagnostic report for installation, config, auth, runtime, Git, terminal, and session issues.
codex exec "TASK"Run Codex non-interactively. Alias: codex e.
codex exec resume --last "TASK"Resume the latest non-interactive session and add a follow-up task.
codex features listList feature flags and their effective states.
codex features enable <FEATURE>Persistently enable a feature in config.toml.
codex features disable <FEATURE>Persistently disable a feature in config.toml.
codex fork <SESSION>Fork a saved interactive session into a new chat.
codex loginAuthenticate through the default ChatGPT login flow.
codex login --device-authUse device-code authentication for remote or headless environments.
printenv OPENAI_API_KEY | codex login --with-api-keyRead an API key from stdin and persist the login.
printenv CODEX_ACCESS_TOKEN | codex login --with-access-tokenRead an access token from stdin for trusted automation.
codex login statusPrint the active authentication mode and return success when logged in.
codex logoutRemove stored authentication credentials.
codex mcp ...List, add, inspect, authenticate, and remove MCP servers.
codex mcp-serverRun Codex as an MCP server over stdio.
codex plugin ...Install, list, or remove plugins.
codex plugin marketplace ...Manage plugin marketplace sources.
codex resume [SESSION]Resume a saved interactive session. Add --last for the latest session.
codex reviewRun a non-interactive review of uncommitted changes, a branch diff, a commit, or custom instructions.
codex sandbox <platform> -- <COMMAND>Run a command under a Codex-provided macOS, Linux, or Windows sandbox helper.
codex unarchive <SESSION>Restore an archived interactive session by ID or name.
codex updateInstall the latest available Codex CLI update.

Cloud and Plugin Command Syntax

CommandUse
codex cloudOpen the interactive cloud chat picker.
codex cloud exec --env <ENV_ID> "TASK"Submit a cloud task directly.
codex cloud list --jsonList recent cloud chats as machine-readable JSON.
codex plugin list --jsonList installed plugins and available metadata.
codex plugin add <PLUGIN[@MARKETPLACE]> --jsonInstall a plugin from a configured marketplace.
codex plugin remove <PLUGIN[@MARKETPLACE]> --jsonRemove an installed plugin.
codex plugin marketplace list --jsonList marketplace sources.
codex plugin marketplace add <SOURCE>Add a Git or local marketplace source.
codex plugin marketplace upgrade [NAME]Refresh one Git marketplace or all configured Git marketplaces.
codex plugin marketplace remove <NAME>Remove a configured marketplace.

Codex CLI Slash Commands

Slash commands work inside the interactive terminal UI after codex starts. Type / to open the current command list for the installed version.

Slash commandUse
/permissionsChange what Codex can do without asking first.
/ideAttach IDE files, selections, and editor context to the current chat.
/keymapInspect, remap, and persist TUI keyboard shortcuts.
/vimToggle Vim editing mode for the composer.
/setup-default-sandboxSet up the elevated agent sandbox on Windows.
/sandbox-add-read-dir <PATH>Grant sandbox read access to another absolute Windows directory.
/agent or /subagentsSwitch to an active delegated-agent thread.
/appsBrowse apps and insert a connector into the prompt.
/pluginsBrowse installed and discoverable plugins.
/hooksInspect, trust, or disable lifecycle hooks.
/clearClear the terminal and start a fresh chat.
/renameRename the current saved chat.
/archiveArchive the current session and exit Codex.
/deletePermanently delete the current session and exit Codex.
/compactSummarize the visible chat to free context tokens.
/copyCopy the latest completed Codex output.
/diffShow the current Git diff, including untracked files.
/exit or /quitExit the terminal UI.
/experimentalView and toggle experimental features.
/approveRetry one action denied by automatic review.
/memoriesConfigure memory use and generation.
/skillsBrowse and attach local skills.
/importImport supported Claude Code setup, project files, and recent chats.
/feedbackOpen the feedback flow and optionally include logs.
/initCreate an AGENTS.md scaffold.
/logoutSign out from inside the TUI.
/mcpView connected MCP servers and tools. Add verbose for details.
/mention <PATH>Attach a file or folder to the chat.
/modelChoose the active model and reasoning effort.
/fastToggle Fast mode.
/planToggle plan mode and optionally send a planning prompt.
/goalSet, edit, pause, resume, view, or clear a task goal.
/personalityChoose the response personality.
/psShow background terminals and recent output.
/stopStop background terminal work.
/forkFork the current chat into a new chat.
/appContinue the current session in the desktop app on macOS or Windows.
/side or /btwStart a temporary side chat without interrupting the main transcript.
/rawToggle copy-friendly raw scrollback mode.
/resumeResume a saved chat from the session list.
/newStart a new chat inside the same CLI session.
/reviewReview the working tree or compare against a base branch.
/statusShow model, permissions, writable roots, token use, and session details.
/usageView account usage and rate limits.
/debug-configPrint config layering and requirements diagnostics.
/statuslineChoose and order TUI footer fields.
/titleConfigure terminal title fields.
/themeChoose a syntax-highlighting theme.
/pets or /petChoose or hide a terminal pet.

Useful TUI Shortcuts

ShortcutUse
@Open the mentions menu for files, plugins, and skills.
Tab while Codex is workingQueue a prompt, slash command, or shell command for the next turn.
Enter while Codex is workingInject a new instruction into the active turn.
Esc twice with an empty composerEdit the previous user message and fork from that point.
Ctrl+CStop or exit according to the current TUI state.

Global Codex CLI Flags

Global flags apply to the base codex command and supported runtime subcommands. Check codex <subcommand> --help before assuming that every global flag propagates.

FlagUse
--add-dir <PATH>Grant write access to another directory. Repeat for multiple paths.
--ask-for-approval, -a <POLICY>Set approval behavior: untrusted, on-request, or never.
--cd, -C <PATH>Set the working directory before Codex starts.
--config, -c key=valueOverride one config value for the current invocation.
--dangerously-bypass-approvals-and-sandbox or --yoloDisable approvals and sandboxing. Use only inside an externally isolated environment.
--dangerously-bypass-hook-trustRun enabled hooks without persisted hook trust for the current invocation.
--disable <FEATURE>Disable a feature flag for one run.
--enable <FEATURE>Enable a feature flag for one run.
--image, -i <PATH[,PATH...]>Attach one or more images to the initial prompt.
--local-provider <lmstudio|ollama>Choose the local provider used with --oss.
--model, -m <MODEL_ID>Override the configured model for one run.
--no-alt-screenDisable alternate-screen TUI mode.
--ossUse a configured local open-source model provider.
--profile, -p <NAME>Layer $CODEX_HOME/NAME.config.toml over the base user config.
--remote <ENDPOINT>Connect the CLI to a remote app-server endpoint.
--remote-auth-token-env <ENV_VAR>Read the bearer token used for a secure remote app-server connection.
--sandbox, -s <MODE>Select read-only, workspace-write, or danger-full-access.
--searchEnable live web search for the run.
--strict-configFail when the installed version does not recognize fields in config.toml.
PROMPTOptional initial instruction for the TUI.

codex exec Flags

Use codex exec for scripts, CI jobs, and tasks that should finish without an interactive TUI.

OptionUse
--cd, -C <PATH>Set the workspace root.
--color <always|never|auto>Control ANSI color in output.
--ephemeralRun without saving session rollout files.
--ignore-rulesSkip user and project execpolicy rule files.
--ignore-user-configIgnore $CODEX_HOME/config.toml while retaining authentication state.
--image, -i <PATH>Attach one or more images to the first message.
--jsonEmit newline-delimited JSON events.
--model, -m <MODEL_ID>Override the model for the run.
--output-last-message, -o <PATH>Write the final assistant message to a file.
--output-schema <PATH>Validate the final response against a JSON Schema.
--profile, -p <NAME>Load a named profile file.
--sandbox, -s <MODE>Set the sandbox for generated commands.
--skip-git-repo-checkAllow a run outside a Git repository.
codex exec resume [SESSION_ID] --last --allResume a previous exec session by ID or choose the latest eligible session.
PROMPT or -Pass the task as text or read it from stdin.
--full-autoDeprecated compatibility flag. Prefer explicit sandbox and approval settings.

Config Keys

Codex stores user settings in $CODEX_HOME/config.toml. The default path is ~/.codex/config.toml.

Config keyUse
model = "<MODEL_ID>"Set the default model.
model_reasoning_effort = "medium"Set the default reasoning effort.
model_reasoning_summary = "auto"Control reasoning-summary behavior.
model_verbosity = "medium"Set response verbosity.
model_provider = "openai"Select the configured model provider.
oss_provider = "ollama"Choose the provider used by --oss.
sandbox_mode = "workspace-write"Persist the default sandbox mode.
sandbox_workspace_write.writable_roots = ["/path"]Add writable roots in workspace-write mode.
sandbox_workspace_write.network_access = trueAllow outbound network access in workspace-write mode.
approval_policy = "on-request"Persist approval behavior with untrusted, on-request, or never.
approvals_reviewer = "user"Choose whether eligible approvals go to the user or automatic review.
web_search = "live"Use live web search instead of the default cached mode.
history.persistence = "none"Disable transcript persistence in history.jsonl.
history.max_bytes = 10485760Cap saved history size and discard the oldest entries when the cap is exceeded.
hide_agent_reasoning = trueSuppress reasoning events in TUI and exec output.
check_for_update_on_startup = falseDisable startup update checks when updates are centrally managed.
cli_auth_credentials_store = "auto"Choose file, OS keyring, or automatic credential storage.
tui.alternate_screen = "auto"Control alternate-screen mode.
tui.status_line = ["model", "context"]Choose and order footer fields.
tui.keymap.<context>.<action> = "ctrl-a"Bind a TUI action in a specific keymap context.
mcp_servers.<id>.command = "node"Define a stdio MCP launcher command.
mcp_servers.<id>.args = ["server.js"]Define arguments for a stdio MCP server.
mcp_servers.<id>.url = "https://example.com/mcp"Define a streamable HTTP MCP endpoint.
mcp_servers.<id>.bearer_token_env_var = "MCP_TOKEN"Read an HTTP bearer token from an environment variable.
mcp_servers.<id>.enabled = falseDisable an MCP server without deleting its config.
hooks and hooks.<Event>Configure lifecycle hooks.

Sandbox Modes and Approval Policies

Sandboxing limits what generated shell commands can access. Approval policy controls when Codex pauses and asks before an action. Set both controls explicitly in automation.

Sandbox modeFile accessNetworkRecommended use
read-onlyRead project files; block writes.Restricted by policyRepository explanation, audits, and reviews that should not edit files.
workspace-writeWrite inside the workspace and configured writable roots.Off unless enabled in configNormal coding, fixes, refactors, and test-driven edits.
danger-full-accessNo Codex filesystem sandbox.Host environment controls accessExternally isolated containers or runners only.
Approval policyBehaviorRecommended use
untrustedPrompts for commands that do not match trusted rules.High-control interactive work.
on-requestLets Codex request approval when work requires broader access.Normal interactive coding.
neverNever opens an approval prompt; blocked actions fail instead.Deterministic non-interactive automation with a suitable sandbox.
Granular approval tableControls categories such as sandbox escalation, rules, MCP elicitations, permission requests, and skill approvals.Managed or advanced environments.

Do not treat --yolo as a faster form of workspace-write. It disables both sandboxing and approvals. Use --add-dir, writable roots, or a narrower approval policy before removing isolation.

MCP Commands

MCP server definitions are stored in ~/.codex/config.toml unless CODEX_HOME changes the config location.

CommandUse
codex mcp listList configured MCP servers. Add --json for machine-readable output.
codex mcp get <NAME>Show one server definition. Add --json for raw config output.
codex mcp add <NAME> -- <COMMAND...>Register a stdio MCP server.
codex mcp add <NAME> --env KEY=VALUE -- <COMMAND...>Pass environment variables to a stdio server.
codex mcp add <NAME> --url https://example.com/mcpRegister a streamable HTTP MCP server.
codex mcp add <NAME> --url https://example.com/mcp --bearer-token-env-var MCP_TOKENRead an HTTP bearer token from an environment variable.
codex mcp add <NAME> --url ... --oauth-client-id <ID> --oauth-resource <RESOURCE>Register OAuth client metadata for an HTTP server.
codex mcp login <NAME> --scopes scope1,scope2Start OAuth login with optional scopes.
codex mcp logout <NAME>Remove stored OAuth credentials.
codex mcp remove <NAME>Delete a server definition.
codex mcp-serverRun Codex itself as an MCP server over stdio.
/mcp or /mcp verboseInspect connected MCP servers and tools inside the TUI.

Environment Variables

Use environment variables for shell-scoped state, installer behavior, authentication secrets, network certificates, and diagnostics. Use config.toml for durable preferences.

VariableUse
CODEX_HOMESet the root directory for config, auth, logs, sessions, skills, and package metadata.
CODEX_SQLITE_HOMESet the location for SQLite-backed state. The sqlite_home config key takes precedence.
CODEX_NON_INTERACTIVESkip prompts in the standalone installer when set to 1, true, or yes.
CODEX_INSTALL_DIRChange where the standalone installer places the visible codex command.
CODEX_API_KEYProvide an API key for a single codex exec run.
CODEX_ACCESS_TOKENProvide an access token for trusted automation or pipe it to codex login --with-access-token.
CODEX_CA_CERTIFICATEPoint HTTPS, login, and WebSocket clients at a custom PEM CA bundle.
SSL_CERT_FILEFallback custom CA bundle when CODEX_CA_CERTIFICATE is unset.
RUST_LOGControl Rust log filtering and verbosity for CLI and app-server diagnostics.
Provider-specific env_keyName the environment variable that stores a custom provider API key.

Pipe OPENAI_API_KEY into codex login --with-api-key to store API-key authentication. The standard codex login command opens the ChatGPT sign-in flow.

Experimental, Deprecated, and Changed Commands

Command or syntaxNotes
codex app-serverExperimental command for local integration and protocol development.
codex cloudExperimental cloud interface with picker, cloud exec, and cloud list commands.
codex debug ...Experimental commands for model catalog, prompt input, and app-server debugging.
codex execpolicyExperimental command for testing execpolicy rules.
codex remote-controlExperimental command for app-server remote control.
--full-autoDeprecated compatibility flag. Use explicit --sandbox and approval settings.
--experimental-jsonLegacy alias. Use --json.
codex --upgradeOutdated syntax. Use codex update.
codex cloud status, cloud diff, cloud applyOutdated cloud syntax. Use codex cloud, codex cloud exec, codex cloud list, and codex apply <TASK_ID>.
/approvals and /cleanOlder aliases. Use /permissions and /stop.

Developer Workflows

These workflows address repository onboarding, implementation planning, feature development, debugging, testing, refactoring, dependency maintenance, code review, session recovery, and terminal automation.

Start Codex in an Existing Repository

Open the repository root before starting Codex. The session can then read project files, Git state, and local instructions.

cd /path/to/project
codex

Create Repository Instructions

Generate an AGENTS.md scaffold, then add the project’s build commands, test commands, code conventions, directory rules, and review requirements.

codex
/init

Understand an Unfamiliar Codebase

Use read-only mode to map the application before making changes. Ask for entry points, major modules, data flow, build commands, tests, and areas tied to the task.

codex --sandbox read-only "Map this codebase. Explain the entry points, major modules, data flow, build commands, test setup, and files related to authentication."

Plan a Change Before Editing Files

Switch to plan mode for migrations, cross-file features, architectural changes, and tasks that need an agreed implementation sequence before code changes begin.

codex
/plan Add rate limiting to the public API without changing existing client behavior. Identify affected files, tests, migration risks, and the implementation order.

Implement a Feature and Run Its Tests

Give Codex a bounded feature request, name the expected behavior, require existing project patterns, and ask it to run the relevant tests before reporting completion.

codex --sandbox workspace-write --ask-for-approval on-request "Implement user profile editing. Follow existing patterns, validate input, update affected tests, run the relevant checks, and summarize the changed files."

Diagnose and Fix a Failing Test

Ask Codex to reproduce the failure first, identify the root cause, make the smallest safe correction, and rerun the affected test set.

codex --sandbox workspace-write --ask-for-approval on-request "Run the failing test, identify the root cause, make the smallest safe fix, rerun the affected tests, and explain why the failure occurred."

Fix a Bug From an Error Message or Stack Trace

Include the observed error, reproduction path, and expected behavior. Ask Codex to trace the relevant code path, reproduce the defect, patch it, and add a regression test.

codex --sandbox workspace-write "Reproduce the null-reference error shown below, trace its source, fix it without changing the public API, add a regression test, and run the affected test suite.
PASTE_ERROR_OR_STACK_TRACE_HERE"

Refactor Code Without Changing Behavior

State the boundary of the refactor and require tests before and after the change. This keeps Codex focused on structure rather than new behavior.

codex --sandbox workspace-write --ask-for-approval on-request "Refactor src/auth to remove duplication and clarify responsibilities. Preserve the public API and runtime behavior. Run the existing auth tests before and after the change."

Add Tests for Existing Code

Point Codex at a module or changed behavior. Request tests for successful paths, failures, boundary cases, and regressions instead of a target percentage.

codex --sandbox workspace-write "Review src/parser and its current tests. Add focused tests for boundary inputs, malformed data, and the recent regression. Run only the parser test suite."

Upgrade a Dependency and Resolve Breakages

Use a narrow upgrade request that names the package, target version, affected APIs, lockfile expectations, and verification commands.

codex --sandbox workspace-write --ask-for-approval on-request "Upgrade PACKAGE_NAME to TARGET_VERSION. Update changed APIs, preserve existing behavior, refresh the lockfile, run lint and tests, and list any unresolved migration issues."

Review Uncommitted Changes Inside the TUI

Inspect the exact working-tree diff, then run Codex review mode to find behavior changes, regressions, missing tests, and implementation risks before committing.

/diff
/review

Review a Branch Against Main

Run a non-interactive branch review from the shell when you want Codex to inspect the full diff against the base branch without opening the TUI.

codex review --base main

Draft a Commit Summary From the Current Diff

Use read-only mode to summarize the actual diff and produce a concise commit title and body without changing the working tree.

codex --sandbox read-only "Inspect the current git diff. Draft a concise conventional commit title and a short body that explains the behavior change and tests."

Resume Work From the Previous Session

Resume the most recent session in the current repository when the earlier chat already contains the plan, decisions, and implementation context.

codex resume --last

Run a One-Off Task Without Opening the TUI

Use codex exec for a bounded task that should finish in the shell, such as updating generated files, applying a repetitive edit, or checking a package.

codex exec --sandbox workspace-write "Update the generated API client, run its tests, and summarize the changed files and any remaining errors."

Capture Machine-Readable Output for Automation

Use JSONL output for scripts or CI jobs, and save the final response separately for later steps or build artifacts.

codex exec --sandbox workspace-write --json --output-last-message codex-report.md "Run lint and tests without editing files. Report each failure, its likely cause, and the command that failed."

Debug a Frontend Issue From a Screenshot

Attach a screenshot when a visual defect is easier to identify from the rendered result than from a written description.

codex --image screenshot.png --sandbox workspace-write "Find the layout issue shown in this screenshot, inspect the relevant components and styles, fix the defect, and run the frontend checks."

FAQs

What is the difference between a Codex CLI command and a slash command?

A CLI command runs from the shell before or instead of the TUI. A slash command runs inside an active Codex TUI session. For example, codex review is a shell command, while /review starts review mode inside the TUI.

How do I check which commands my installed Codex version supports?

Run codex --version, codex --help, and codex <subcommand> --help. Inside the TUI, type / to open the slash-command list. Use codex features list to inspect feature maturity and state.

How do I run Codex non-interactively?

Use codex exec "TASK" or codex e "TASK". Add --json for JSONL events, --output-last-message to save the final response, and an explicit sandbox for commands that read or edit files.

Where is the Codex CLI config file?

Codex uses $CODEX_HOME/config.toml. The default location is ~/.codex/config.toml. Named profiles live beside it as $CODEX_HOME/profile-name.config.toml.

Which Codex sandbox mode should I use?

Use read-only for explanation and audit tasks. Use workspace-write for normal coding. Reserve danger-full-access for an externally isolated environment that already provides its own containment.

How do I add an MCP server to Codex CLI?

Use codex mcp add NAME -- COMMAND... for a stdio server or codex mcp add NAME --url URL for a streamable HTTP server. Run codex mcp list to confirm the saved definition and /mcp verbose inside the TUI to inspect active tools.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest & top AI tools sent directly to your email.

Subscribe now to explore the latest & top AI tools and resources, all in one convenient newsletter. No spam, we promise!