Codex CLI: The Complete Guide
Master Codex CLI: interactive vs exec mode, key flags (--full-auto, --sandbox, --model), config.toml setup, slash commands, and remote WebSocket sessions.
Codex CLI: The Complete Guide
Codex CLI is OpenAI’s open-source command-line coding agent. It runs locally, reads your codebase, and executes changes based on natural-language prompts. This guide covers both the interactive REPL and the non-interactive exec mode, every key flag, configuration via config.toml, slash commands, and remote sessions.
Interactive Mode vs Exec Mode#
Codex CLI has two fundamentally different operating modes, and choosing the right one is the first decision you make.
Interactive Mode (Default)#
Run codex with no subcommand and you enter an interactive REPL. A prompt appears, you type a natural-language instruction, and Codex responds by reading files, proposing edits, and running shell commands. You approve or reject each action in real time. This is ideal for exploratory development, debugging sessions, and any workflow where you want to steer the agent step by step.
The interactive loop works like this: Codex proposes a shell command or file edit, you review it, and then you approve or deny. This approval gate is your safety net. It prevents Codex from silently executing destructive operations. In interactive mode you can also use slash commands (covered later) to switch models, compact context, inspect permissions, and more.
When you exit the REPL, Codex saves the session so you can resume it later with codex --resume.
Exec Mode (codex exec)#
Exec mode is non-interactive. You pass a prompt directly on the command line and Codex runs to completion without waiting for human approval. This is designed for CI pipelines, batch scripts, and any scenario where no human is watching.
codex exec "Refactor the authentication module to use JWT tokens"
Exec mode respects the same flags and configuration as interactive mode, but it bypasses the approval loop. By default, exec mode runs with sandbox protections so Codex cannot write outside the workspace. You must explicitly opt in to broader permissions with --sandbox danger-full-access or --full-auto.
Because there is no human in the loop, exec mode pairs naturally with --full-auto and carefully scoped sandbox settings. Always set --sandbox to the minimum privilege level your task requires. An exec command with --full-auto --sandbox danger-full-access can modify any file and run any command on your machine without confirmation.#
Key Flags#
Codex CLI exposes a rich set of flags. Here are the most important ones organized by category.
Automation and Safety#
--full-auto: Approves every action automatically. Codex reads, writes, and executes without asking. Essential for CI and exec mode. Dangerous in interactive mode unless you fully trust the codebase.--sandbox <level>: Controls filesystem and execution isolation.read-only— Codex can read files but cannot write anything or run commands.workspace-write— Codex can write only within the current project directory and run read-only commands. This is the default.danger-full-access— No restrictions. Codex can write anywhere and execute any command. Use only when you understand the risk.
--ask-for-approval <mode>: Governs when Codex requests human approval.untrusted— Ask before executing any command not on a pre-approved list. Good default.on-request— Ask only when Codex explicitly decides approval is needed.never— Never ask for approval. Equivalent to full autonomy.
Model and Identity#
--model <name>: Override the default model. Pass any model identifier that your API key supports (e.g.,o4-mini,gpt-4.1). Useful for switching between fast and capable models without editing config.toml.--profile <name>: Select a named configuration profile from config.toml. Profiles let you maintain separate setups (work vs personal, different API keys, different default models) and switch with a single flag.
Workspace and Files#
--cd <path>: Change the working directory before starting. Equivalent tocd /path && codexbut cleaner in scripts.--add-dir <path>: Grant Codex access to an additional directory outside the current workspace. Use this when your project references shared libraries, config files, or documentation in a sibling directory. You can specify--add-dirmultiple times.--search: Enable web search capability during the session. Codex can look up documentation, API references, and error solutions online. Without this flag, Codex operates only on local files.
Open Source and Remote#
--oss: Run in open-source mode. This disables proprietary model routing and restricts Codex to models available through open-weight or permissive API endpoints. Relevant for users who want to avoid sending code to proprietary endpoints.--remote ws://host:port: Connect to a remote Codex session over WebSocket. See the Remote Sessions section below.
Configuration: config.toml#
Codex reads configuration from TOML files. There are two locations, loaded in order:
- Global:
~/.codex/config.tomlapplies to all projects on your machine. - Project-local:
.codex/config.toml(in your project root) overrides global settings for that project.
Project-local settings always win when there is a conflict. This means you can set sensible global defaults and then override them per project.
Example config.toml#
model = "o4-mini" sandbox = "workspace-write" ask_for_approval = "untrusted" [profiles.work] model = "gpt-4.1" api_key_env = "OPENAI_WORK_API_KEY" add_dir = ["/shared-libs", "/company-docs"] [profiles.fast] model = "o4-mini" sandbox = "read-only" [permissions] allow = ["git diff", "git log", "git status", "npm test"] deny = ["destructive-commands", "privilege-escalation", "disk-operations"]
Key Configuration Fields#
| Field | Type | Default | Description |
|---|---|---|---|
model | string | o4-mini | Default model identifier |
sandbox | string | workspace-write | Sandbox level |
ask_for_approval | string | untrusted | Approval policy |
api_key_env | string | OPENAI_API_KEY | Environment variable holding the API key |
add_dir | list | [] | Additional directories to grant access to |
search | boolean | false | Enable web search |
oss | boolean | false | Open-source mode |
Profiles are defined under [profiles.<name>] sections. Activate one with --profile <name> on the command line or set default_profile in config.toml.
The [permissions] section controls the allow/deny list for shell commands. Commands matching any deny pattern are blocked regardless of the approval mode. Commands matching an allow pattern skip the approval prompt even in untrusted mode.#
Slash Commands#
Slash commands are available only in interactive mode. They let you control the session without leaving the REPL.
Session and Context#
/init: Initialize a new Codex session in the current directory. Creates.codex/with a default config.toml if one does not exist./compact: Manually trigger context compaction. Codex summarizes older messages to free up the context window. Use this when you notice responses getting slower or less accurate./clear: Wipe the entire conversation context. Start fresh without restarting the process. Combine with re-reading key files for a clean handoff./model <name>: Switch the active model mid-session. No restart required. Example:/model gpt-4.1to escalate a hard problem.
Planning and Review#
/plan: Enter plan mode. Codex analyzes the codebase and proposes a strategy without making changes. Review the plan, adjust it, then switch back to execute. This is the safest way to approach complex refactors./review: Ask Codex to review the current state of the codebase, including recent changes, uncommitted files, failing tests. Useful for a status check before committing or before asking Codex to proceed with the next step./diff: Show the diff of all changes Codex has made in the current session. Review before you commit or exit.
System and Configuration#
/permissions: Display the current permission settings including sandbox level, approval mode, allow/deny lists. Helps debug why Codex is asking for approval on a command you expected to be auto-approved./status: Show session metadata including current model, context usage, working directory, elapsed time./mcp: List and manage MCP (Model Context Protocol) server connections. MCP servers give Codex access to external tools and data sources./plugins: List installed plugins and their status. Plugins extend Codex with custom tools, linters, and workflows./agent: Spawn a sub-agent for a specific subtask. The sub-agent runs with its own context window and reports results back. Useful for parallelizing work within a single session.
Session Forking and Resumption#
/fork: Fork the current session. Creates a branch point so you can explore a different approach without losing the current conversation history. Like git branches for your chat./resume: Resume a previously saved session. Codex reloads the conversation context and continues where you left off./experimental: Toggle experimental features on or off. Experimental features may be unstable but often provide early access to upcoming functionality.
Remote Sessions#
Codex supports remote sessions via WebSocket connections. This is useful when you want to run Codex on a powerful remote machine (more GPU, more memory, access to internal networks) but control it from your local terminal.
Starting a Remote Session#
On the remote host, start the Codex server:
codex --serve 0.0.0.0:8080
This binds a WebSocket endpoint at ws://0.0.0.0:8080. Codex listens for incoming connections and spawns sessions on demand.
Connecting from a Local Client#
From your local machine, connect with:
codex --remote ws://remote-host:8080
The local client sends your prompts to the remote Codex instance. File reads and writes happen on the remote machine. The interactive experience is identical to a local session. You see the same REPL, the same slash commands, and the same approval prompts.
Security Considerations#
Remote sessions transmit prompts and responses over the network. Use TLS or an SSH tunnel for production deployments:
ssh -L 8080:localhost:8080 user@remote-host codex --remote ws://localhost:8080
This tunnels the WebSocket through SSH, encrypting all traffic. Never expose a Codex server directly to the internet without encryption, especially with --full-auto or --sandbox danger-full-access enabled.
Remote Exec Mode#
You can combine remote sessions with exec mode for headless automation:
codex --remote ws://remote-host:8080 exec "Run the full test suite and fix any failures"
The command executes on the remote machine and streams results back. This is ideal for CI runners, shared build servers, or any scenario where the execution environment is different from your development machine.
Quick Reference#
| What | Command |
|---|---|
| Start interactive REPL | codex |
| Non-interactive exec | codex exec "prompt" |
| Full automation | codex --full-auto |
| Read-only sandbox | codex --sandbox read-only |
| Connect to remote | codex --remote ws://host:port |
| Switch model mid-session | /model gpt-4.1 |
| Plan without executing | /plan |
| Review session changes | /diff |
| Check permissions | /permissions |
| Fork session | /fork |
Codex CLI gives you a spectrum from fully interactive and human-supervised to fully autonomous and headless. The key is matching your mode, flags, and sandbox level to the task at hand. Use interactive mode when you want to steer, exec mode when you want to automate. Use --sandbox workspace-write as your default, escalate to danger-full-access only when needed. Keep your config.toml organized with profiles, and use slash commands to stay in control without leaving the REPL.