> esc

Codex CLI / terminal reference

Built from OpenAI's official docs as of 11 July 2026 (Codex CLI ~v0.144.1). Click any command to copy it. Things move fast — the source of truth is developers.openai.com/codex, and inside a session /status shows the active model, approval policy, and writable roots of your build.

Cheat sheet Cookbook Changes

Launch

experimental = marked experimental in the docs — may change without notice. windows = only when running natively on Windows. deprecated = kept for compatibility; prefer the replacement.

Sessions

codexLaunch the interactive terminal UI. On launch Codex recommends Auto in version-controlled folders, read-only elsewhere.
codex "prompt"Start the TUI with an opening instruction pre-filled.
codex resume [--last | --all]Continue an interactive session by ID, or the most recent. --last scopes to the current directory unless --all.
codex fork [--last]Fork a previous session into a new task; no flag opens the session picker. Original transcript preserved.
codex archive | unarchive <session>Hide a session from the picker without deleting the transcript / restore it. IDs take precedence over names.
codex delete <session> [--force]Permanently delete a saved session. --force only works with a UUID; named sessions always confirm.
codex login | logoutChatGPT OAuth by default; also API key or piped access token. codex login status exits 0 when credentials are present.
codex updateCheck for and apply a self-update when the installed release supports it.
codex doctorDiagnostic report: installation, config, auth, runtime, Git, terminal, app-server, thread inventory.

Scripting (codex exec)

codex exec "task"Non-interactive run (alias codex e). Progress streams to stderr; only the final message prints to stdout. Read-only sandbox by default.
npm test 2>&1 | codex exec "task"Prompt-plus-stdin: the argument is the instruction, piped content is context.
codex exec -Read the entire prompt from stdin — for prompts assembled by scripts.
codex exec resume --last [--all]Continue a non-interactive session; --all searches beyond the current directory. Also takes a session ID.
codex review --uncommitted | --base <branch> | --commit <SHA>Non-interactive code review. Targets conflict with each other and with a custom prompt; --title only with --commit.
codex apply <task-id>Apply the latest diff from a Codex cloud task to the local repo (alias codex a). Non-zero exit if git apply fails.
codex cloud [exec | list]experimental Browse cloud tasks (picker), submit one directly, or list recent tasks — --json for automation.

Setup & plumbing

codex mcpManage MCP server entries in ~/.codex/config.toml. codex mcp login <name> runs an OAuth flow for HTTP servers.
codex plugin [marketplace]Install, list, and remove plugins; manage marketplace sources (GitHub shorthand, Git URLs, local roots). --json throughout.
codex features [enable | disable <flag>]List feature flags or persist a toggle in config.toml.
codex completion bash|zsh|fish|powershellGenerate a shell completion script, e.g. eval "$(codex completion zsh)".
codex sandbox macos|linux|windows [cmd]Run any command under the same sandbox policies Codex uses internally. Also available as codex debug.
codex execpolicy check --rules <file>experimental Test how .rules files judge a command before saving them. --pretty formats the JSON.
codex mcp-serverRun Codex itself as an MCP server over stdio, so another agent can drive it.
codex appOpen the session in the ChatGPT desktop app (macOS opens the workspace path; Windows prints it).
codex app-server [--listen ws://IP:PORT]experimental Local app server for protocol clients — stdio, WebSocket, or Unix socket transports.
codex remote-control [start | stop | pair]experimental Remote-control daemon for managed clients and SSH workflows; pair prints a short-lived pairing code.

no matches in this section

CLI flags

Global flags apply to codex and propagate to most subcommands. -c key=value overrides any config value for one invocation.

Global

--model, -m <model>Override the configured model (for example gpt-5.4).
--sandbox, -s read-only|workspace-write|danger-full-accessSandbox policy for model-generated shell commands.
--ask-for-approval, -a untrusted|on-request|neverWhen Codex pauses for human approval before running a command.
--cd, -C <path>Set the agent's working directory before it starts.
--add-dir <path>Grant extra directories write access alongside the workspace. Repeatable.
--config, -c key=valueOne-off config override; values parse as TOML when possible.
--profile, -p <name>Layer ~/.codex/<name>.config.toml on top of the base user config.
--image, -i <path[,path…]>Attach image files to the initial prompt.
--searchLive web search (web_search = "live") instead of the default cached index.
--oss | --local-provider lmstudio|ollamaUse a local open-source model provider; --local-provider picks which one for this run.
--enable / --disable <feature>Force a feature flag on or off (translates to -c features.<name>). Repeatable.
--remote ws://host:port | unix://[PATH]Connect the TUI to an app server. Works with codex, resume, fork, archive, delete, unarchive.
--remote-auth-token-env <ENV_VAR>Bearer token for --remote; only sent over wss:// or local-only ws:// URLs.
--strict-configError when config.toml contains fields this Codex version doesn't recognize.
--no-alt-screenDisable the TUI alternate screen for this run (overrides tui.alternate_screen).
--dangerously-bypass-approvals-and-sandbox, --yoloNo approvals, no sandbox. Only inside an externally hardened environment.
--dangerously-bypass-hook-trustRun enabled hooks without persisted trust — only for automation that already vets hook sources.

codex exec (scripting)

--jsonstdout becomes a JSONL event stream: thread.started, turn.completed, item.*, error, …
--output-last-message, -o <path>Also write the final message to a file — pair with --json in CI.
--output-schema <schema.json>Force the final response to conform to a JSON Schema. For pipelines that need stable fields.
--ephemeralDon't persist session rollout files to disk.
--skip-git-repo-checkRun outside a Git repository. Codex requires one by default to prevent destructive changes.
--ignore-user-config | --ignore-rulesSkip $CODEX_HOME/config.toml / skip user and project .rules files for controlled automation.
--full-autodeprecated Compatibility alias that warns; use --sandbox workspace-write in new scripts.
CODEX_API_KEY=<key> codex exec …API key for a single non-interactive run. Set inline, never job-wide where untrusted code runs.

no matches in this section

Slash commands

Type / in the composer to open the popup. While a task runs, type a slash command and press Tab to queue it for the next turn.

Session & tasks

/clearClear the terminal and start a fresh task together. (Ctrl+L clears only the view.)
/newNew conversation in the same CLI session, without clearing the terminal first.
/resumeReload a saved conversation from the session picker; original history intact.
/forkClone the current task into a new task ID to explore an alternative. (codex fork forks a saved session.)
/side | /btwEphemeral side conversation with its own transcript; the parent task's status stays visible. Unavailable inside another side chat.
/rename [name]Name the saved task without changing its transcript.
/compactSummarize the conversation to free context, keeping key points.
/copyCopy the latest completed output — also Ctrl+O.
/diffShow the Git diff, including files Git isn't tracking yet.
/archiveArchive the current session and exit; restore later with codex unarchive.
/deletePermanently delete the current session and its descendant sessions, then exit.
/appContinue this session in the ChatGPT desktop app (macOS/Windows).
/quit | /exitExit immediately. Save or commit important work first.

Model & steering

/modelChoose the active model and, when available, reasoning effort.
/fastToggle the model's Fast service tier and persist the choice. Hidden if the catalog has none.
/personalityCommunication style: friendly, pragmatic, or none.
/plan [prompt]Switch to plan mode, optionally seeding the first planning request. Unavailable mid-task.
/goal [objective | edit | pause | resume | clear]Persistent target Codex tracks across the task. Max 4,000 chars — point at a file for more.
/permissionsSwitch approval preset (for example AutoRead Only), including named custom profiles.
/approveRetry a recent action that the automatic reviewer denied — once.
/reviewReview the working tree: behavior changes and missing tests. Uses review_model if set.
/statusActive model, approval policy, writable roots, token usage — plus remote address when connected remotely.
/usage [daily | weekly | cumulative]Account token activity, or redeem an earned rate-limit reset.

Context & extensions

/mention <path>Attach a file so follow-up turns reference it directly.
/idePull open files and the current selection from your IDE into the next prompt.
/skillsBrowse and apply skills; you can also mention one inline with $skill-name.
/mcp [verbose]List configured MCP servers and tools; verbose adds server diagnostics.
/appsBrowse apps (connectors) and insert one into the prompt as $app-slug.
/pluginsPlugin browser: installed and discoverable plugins. Space toggles an installed plugin.
/hooksInspect, trust, or disable lifecycle hooks. New or changed hooks are skipped until trusted.
/agent | /subagentsSwitch the active agent thread to inspect or continue a subagent's work.
/memoriesToggle memory injection and generation without leaving the TUI.
/initGenerate an AGENTS.md scaffold in the current directory.
/importMigrate Claude Code setup, project files, and recent chats into Codex. Local TUI sessions only.

TUI & misc

/statuslinePick and reorder footer items (model, context, limits, git, tokens, session); persists to tui.status_line.
/titleConfigure terminal window/tab title items; persists to tui.terminal_title.
/themeSyntax-highlighting theme picker; persists to tui.theme. Custom .tmTheme files go in $CODEX_HOME/themes.
/keymapRemap TUI shortcuts; writes to tui.keymap. Names like ctrl-a, shift-enter, page-down.
/vimToggle composer Vim mode. Default it with tui.vim_mode_default = true.
/raw [on|off]Raw scrollback for cleaner terminal selection — also Alt+R; persist with tui.raw_output_mode.
/psBackground terminals with up to three recent output lines each.
/stopStop all background terminals for this session. /clean is an alias.
/experimentalToggle experimental features (Network proxy, Prevent sleep, …); some need a restart.
/debug-configConfig layer order, on/off state, and policy sources — for debugging precedence.
/setup-default-sandboxwindows Replace the degraded restricted-token sandbox with the elevated one.
/sandbox-add-read-dir <path>windows Grant sandbox read access to an absolute directory outside the readable roots.
/feedbackSend logs and diagnostics to the Codex maintainers.
/logoutClear local credentials.

no matches in this section

Keyboard & composer

@Search for a workspace file and add its path to the prompt.
!Prefix a line to run a shell command under the current approval and sandbox settings.
$Mention a skill ($skill-name) or an app ($app-slug) inline.
TabWhile Codex works: queue a follow-up prompt, slash command, or shell command for the next turn.
EnterWhile Codex works: inject new instructions into the current turn.
Up / DownRestore draft history.
Ctrl+RSearch prompt history; Enter uses a match, Esc cancels.
Esc EscOn an empty composer: edit the previous user message and fork the conversation from that point.
Ctrl+OCopy the latest completed output (same as /copy).
Ctrl+GOpen the composer in the editor from VISUAL (or EDITOR); save and close to return the text.
Ctrl+LClear the terminal view, keeping the current task. Disabled while a task runs.
Alt+RToggle raw scrollback mode (default binding for /raw).
Ctrl+CClose the session (same as /exit).

no matches in this section

Sandbox & approvals

Two layers that work together: the sandbox is what commands can do; the approval policy is when Codex must stop and ask first.

Sandbox modes (--sandbox / sandbox_mode)

read-onlyInspect files only; edits and commands need approval.
workspace-writeRead, edit, and run routine commands inside the workspace. The default low-friction mode for local work.
danger-full-accessNo filesystem or network boundaries. Only when the outer environment provides the isolation.

Approval policies (--ask-for-approval / approval_policy)

untrustedOnly known-safe read operations run automatically; anything that can mutate state asks first.
on-requestWork inside the sandbox freely; ask when going beyond the boundary.
neverNo approval prompts; Codex does its best within the sandbox you set.
approvals_reviewer = "user" | "auto_review"Who reviews eligible approval requests: you (default), or a reviewer agent that fails closed on parse errors and timeouts.
approval_policy = { granular = { … } }Keep some prompt categories interactive and auto-reject the rest: sandbox, rules, MCP, request_permissions, skill scripts.

Common combinations

--sandbox workspace-write --ask-for-approval on-requestThe Auto preset (also the default in version-controlled folders): edit and run in the workspace, ask to go outside or use the network.
--sandbox read-only --ask-for-approval on-requestSafe browsing: read and answer; ask before any edit, command, or network access.
--sandbox read-only --ask-for-approval neverRead-only non-interactive — the CI default posture.
--sandbox workspace-write --ask-for-approval untrustedEdit automatically but ask before running untrusted commands.
--yoloNo sandbox, no approvals — not recommended outside a hardened container.

Boundaries

.git · .agents · .codexProtected read-only inside writable roots, recursively — even in workspace-write.
workspace = cwd + /tmpThe workspace includes the current directory and temp directories; /status lists the writable roots.
[sandbox_workspace_write] network_access = trueNetwork is off by default in workspace-write; this turns it on.
[features.network_proxy] domains = { "api.openai.com" = "allow" }Constrain enabled network access to a destination policy. deny beats allow; *.host excludes the apex, **.host includes it.
web_search = "cached" | "indexed" | "live" | "disabled"Web search without giving commands the network. Cached (default) serves an OpenAI-maintained index; --search = live.
sudo apt install bubblewrapLinux/WSL2 prerequisite — the sandbox uses bwrap + seccomp. macOS uses Seatbelt; native Windows has its own sandbox.

no matches in this section

Config & environment

Precedence, highest first: CLI flags and -c overrides → project .codex/config.toml (trusted projects, closest wins) → --profile file → ~/.codex/config.toml/etc/codex/config.toml.

config.toml keys people actually change

model = "gpt-5.6"Default model for the CLI and IDE extension.
approval_policy = "on-request"When Codex pauses to ask before running generated commands.
sandbox_mode = "workspace-write"Filesystem and network access while executing commands.
model_reasoning_effort = "high"Reasoning effort where the model supports it.
personality = "friendly"Default communication style (pragmatic, none); override per session with /personality.
[features]Optional capabilities: memories, multi_agent, hooks, fast_mode, unified_exec, … Enable from the CLI with codex --enable <flag>.
[tui.keymap.global]Custom shortcut bindings; composer/chat contexts override global. Empty list unbinds.
[shell_environment_policy] include_only = ["PATH", "HOME"]Which environment variables Codex forwards to spawned commands.
log_dir = "/path"Where local logs go; setting it also enables the opt-in plaintext codex-tui.log.
[windows] sandbox = "elevated"windows Native Windows sandbox mode; unelevated only without admin permissions.

Environment variables

CODEX_HOMERoot for Codex state — config, auth, logs, sessions, skills. Default ~/.codex; must exist if set.
CODEX_API_KEYAPI key for a single codex exec run — only supported there.
CODEX_ACCESS_TOKENChatGPT/Codex access token for trusted automation; persist with codex login --with-access-token.
CODEX_CA_CERTIFICATEPEM CA bundle for corporate TLS interception; beats SSL_CERT_FILE.
RUST_LOG=debugRust log filtering (errortrace, or targeted filters like codex_core=debug).
CODEX_NON_INTERACTIVE=1Skip installer prompts in the standalone install scripts — for scripted installs.
CODEX_INSTALL_DIRWhere the visible codex command lands (default ~/.local/bin on macOS/Linux).

no matches in this section

MCP

The ChatGPT desktop app, Codex CLI, and IDE extension share MCP configuration — set a server up once in config.toml.

[mcp_servers.<name>]One table per server in ~/.codex/config.toml, or project-scoped .codex/config.toml (trusted projects).
command / args / env / cwdSTDIO server: launched as a local process. env_vars allowlists which variables are forwarded.
url / bearer_token_env_var / http_headersStreamable HTTP server. auth = "oauth" (default) uses stored MCP OAuth credentials; "chatgpt" rides the ChatGPT session.
codex mcp login <name>Run the OAuth flow for an HTTP server from the shell.
enabled_tools / disabled_toolsTool allow list, then deny list applied after it.
default_tools_approval_mode = auto|prompt|writes|approveApproval behavior for the server's tools; writes prompts for tools not marked read-only. Per-tool: tools.<tool>.approval_mode.
required = trueStartup fails if this enabled server can't initialize — codex exec exits with an error instead of continuing without it.
startup_timeout_sec = 10 · tool_timeout_sec = 60Server start and per-tool timeouts (defaults shown).
mcp_oauth_callback_port / mcp_oauth_callback_urlFixed OAuth callback port or base URL when the provider needs one; Codex appends a server-specific callback ID.
enabled = falseDisable a server without deleting its config.

no matches in this section

AGENTS.md, skills & rules

AGENTS.md (read before any work)

~/.codex/AGENTS.mdGlobal guidance for every repository. AGENTS.override.md beside it wins when present.
<root>/AGENTS.md … <cwd>/AGENTS.mdProject scope: walks root → cwd, at most one file per directory, concatenated root-down so closer files override.
project_doc_max_bytes = 32768Combined size cap (default 32 KiB) — raise it or split guidance across nested directories.
project_doc_fallback_filenames = ["TEAM_GUIDE.md"]Treat existing files as instruction files without renaming them.

Skills

.agents/skills/<name>/SKILL.mdRepo skills — scanned from cwd up to the repo root. name + description required; description drives implicit matching.
~/.agents/skills · /etc/codex/skillsUser-wide and machine-wide (admin) skill locations. System skills ship with Codex.
$skill-name | /skillsExplicit invocation — mention with $ or pick from the browser. Codex also matches skills implicitly by description.
$skill-creator · $skill-installer <name>Draft a new skill interactively / install curated skills (e.g. $skill-installer linear).
[[skills.config]] enabled = falseDisable a skill by path without deleting it. Restart Codex after editing.
agents/openai.yamlOptional skill metadata: display name, icons, tool dependencies, allow_implicit_invocation: false to require explicit $ calls.

Rules (commands outside the sandbox)

~/.codex/rules/*.rulesexperimental Starlark files scanned at startup from every active config layer. Project rules load only in trusted projects.
prefix_rule(pattern=["gh","pr","view"], decision="prompt")Match a command prefix; decide allow, prompt, or forbidden. Most restrictive matching rule wins.
match / not_matchInline unit tests validated when rules load — catch mistakes before a rule takes effect.
bash -lc "a && b"Simple chains are split and each command is judged separately, so rm -rf / can't ride along with git add. Complex scripts are judged whole.
codex execpolicy check --pretty --rules <file> -- <cmd>Dry-run the decision for a command, with matching rules and justifications.

no matches in this section

Subagents

Ask directly — "spawn one agent per point, wait for all, summarize" — or let project and skill instructions request delegation.

default · worker · explorerBuilt-in agents: general-purpose fallback, execution-focused implementer, read-heavy explorer. A custom agent with the same name wins.
~/.codex/agents/<name>.toml · .codex/agents/Custom agents — one TOML file each, loaded as config layers for spawned sessions.
name / description / developer_instructionsRequired fields. Optional model, model_reasoning_effort, sandbox_mode, mcp_servers, skills.config inherit from the parent session.
agents.max_threads = 6Concurrent open agent thread cap (default shown).
agents.max_depth = 1Nesting: children can't spawn deeper descendants by default. Raising it multiplies token usage and latency.
/agentSwitch the active thread to inspect or steer a running subagent; or just ask Codex to steer, stop, or close it.
Sandbox inheritanceSubagents inherit the parent turn's sandbox policy and permission mode; a custom agent file can pin its own (e.g. read-only).

no matches in this section

Hooks

Deterministic scripts on lifecycle events, configured in hooks.json or inline [hooks] in config.toml. Non-managed hooks must be reviewed and trusted in /hooks before they run.

~/.codex/hooks.json · <repo>/.codex/hooks.jsonThe usual locations (plus inline [hooks] in either config.toml). All matching hooks from every layer run; project hooks need a trusted project.
SessionStart · SubagentStartThread-scope events — e.g. load session notes on startup|resume matchers.
PreToolUse · PermissionRequest · PostToolUseAround tool calls and approval requests, filtered by matcher (e.g. Bash).
UserPromptSubmitIntercept the prompt before the model sees it — e.g. scan for pasted API keys.
PreCompact · PostCompactAround conversation compaction.
Stop · SubagentStopTurn boundaries — e.g. run a validation check when a turn ends.
event → matcher → handlersMatching command hooks launch concurrently; one hook can't block another from starting.
Trust by hashTrust is recorded against the hook's definition hash — new or changed hooks are skipped until re-trusted in /hooks.

no matches in this section