Codex CLI Cheatsheet - OpenAI Terminal Coding Agent Full Reference

Codex CLI is OpenAI official open-source terminal coding agent (Rust) for developers driving GPT-family models to edit code, run tests, and manage approvals directly in a repo — and for CI engineers adopting AI codegen/review. Unlike cloud chat it adds fine-grained sandbox (read-only/workspace-write/full-access) and approval policies, plus headless codex exec --json for pipelines. This sheet covers install/login, non-interactive execution, and the sandbox trade-offs.

AI CLI·54 commands·Last updated 2026-08-05
codexcodex-cliopenaiaicliagentCoding Agent

Typical Use Case

For engineers wiring AI coding capability into development and CI. The distinction to make first is between the interactive TUI, good for exploration and paired editing, and codex exec, the non-interactive mode that belongs in pipelines. Three areas matter most: structured output through --json, -o and --output-schema so scripts can consume results; the four combinations of sandbox and approval settings, chosen by risk level; and adding, removing and listing MCP servers so internal tools reach the model. Session handling is included too, because resuming or forking a prior thread beats restating the background every time.

Install & Auth 7

npm install -g @openai/codex
Install globally via npm (all platforms)
brew install --cask codex
Install on macOS via Homebrew
codex --version
Verify install and show version
codex login
Browser OAuth sign-in to ChatGPT
codex login --with-api-key
Read API key from stdin to log in
codex login --device-auth
Headless/SSH device-code login
codex logout
Sign out

Interactive Mode 5

codex
Start an interactive TUI session
codex "Explain this codebase"
Start the TUI with an initial prompt
codex --search "Fix the login bug"
Enable live web search
codex -i ./screenshot.png "Implement this UI"
Attach an image (comma-separate multiple)
codex --oss
Use a local open-source model (Ollama, etc.)

Non-interactive (codex exec) 5

codex exec "Fix the failing tests"
Non-interactive automation mode (alias codex e)
echo "Refactor utils" | codex exec --oss
Pipe input + local model
codex exec --json "List all API endpoints"
Output JSONL for scripting
codex exec -o result.txt "Summarize the architecture"
Save the final response to a file
codex exec --output-schema '{...}' "Extract config"
Constrain output with a JSON Schema

Session Management 5

codex resume
Resume the previous session
codex fork
Fork the previous session into a new thread
codex apply
Apply the latest diff as git apply (alias codex a)
codex --restore
Restore the previous session (some versions)
codex --history
Browse past session history

Model & Config 5

codex -m gpt-5.4 "Complex task"
Set the model (e.g. gpt-5.4 / gpt-5.4-mini)
codex -p openai "Generate a component"
Load a named config profile
codex -C /path/to/repo
Set the working root directory (--cd)
codex -c
Override config.toml values
codex completion bash
Generate bash completion script

Sandbox & Approval 8

codex -s read-only
Sandbox read-only (default, safest)
codex -s workspace-write
Sandbox can write the working directory
codex -s danger-full-access
Full access (use cautiously in containers)
codex -a untrusted
Prompt for untrusted actions (default)
codex -a never
Never approve (for read-only exploration)
codex --full-auto "Complete the implementation"
Auto-approve: workspace-write + on-failure
codex --yolo "Emergency fix"
Skip all sandbox and approvals (dangerous)
codex --dangerously-bypass-approvals-and-sandbox
Fully bypass sandbox and approvals (in containers)

MCP & Codex Cloud 7

codex mcp list
List configured MCP servers
codex mcp add -- <args...>
Add a stdio MCP server
codex mcp add --url https://example.com/mcp
Add an HTTP MCP server
codex mcp get <name>
Show server configuration
codex mcp remove <name>
Remove a server
codex cloud exec --env "task"
Submit a task to Codex Cloud
codex cloud exec --env --attempts 3 "task"
Submit a task with retry attempts (1-4)

Interactive Slash Commands 12

/clear
Reset UI and conversation
/compact
Summarize conversation to free tokens
/new
Start a fresh conversation in the same session
/fork
Clone current conversation into a new thread
/diff
Show git diff including untracked files
/status
Show session config and token usage
/init
Generate an AGENTS.md project scaffold
/review
Code review of working-tree changes
/plan
Switch to plan (read-only) mode
/model
Choose model and reasoning effort
/permissions
Set what Codex can do without asking
/exit
Quit Codex CLI

Parameter matrix

ParameterEffectExample
exec非交互模式执行一次性任务(别名 codex e)codex exec "修复失败的测试"
--json输出 JSONL,便于脚本解析codex exec --json "列出所有 API 端点"
-o <file>把最终回答写入文件codex exec -o result.txt "总结架构"
--output-schema <json>用 JSON Schema 约束输出结构codex exec --output-schema '{}' "提取配置"
-m <model>指定模型codex -m gpt-5.4-mini "复杂任务"
-C <dir>设置工作根目录(--cd)codex -C /path/to/repo
-p <profile>加载命名配置 profilecodex -p openai "生成组件"
-c临时覆盖 config.toml 中的配置值codex -c model_reasoning_effort="high"
-s read-only沙箱只读,默认最安全codex -s read-only "审计依赖"
-s workspace-write沙箱可写工作目录codex --full-auto "完成实现"
-a never从不弹批准,适合只读探索codex -a never -s read-only
--full-auto自动批准:workspace-write + on-failurecodex --full-auto "完成实现"
--search启用实时网络搜索codex --search "修复登录 bug"
-i <img>附带图片(可逗号分隔多张)codex -i ./shot.png "实现这个 UI"
--oss使用本地开源模型(Ollama 等)echo "重构 utils" | codex exec --oss
mcp list / get / remove管理已配置的 MCP 服务器codex mcp list
mcp add --url <url>添加 HTTP 类型 MCP 服务器codex mcp add --url https://example.com/mcp
cloud exec --attempts <n>提交 Codex Cloud 任务并指定重试次数(1-4)codex cloud exec --attempts 3 "任务"

Common pitfalls

Symptom自动化脚本里拿不到模型的回答,只有空输出或一段人类可读文本

Cause交互模式(TUI)把回答打在终端界面上,没有给非调用方留结构化出口。

Fix改用 `codex exec --json`,按 JSONL 逐行解析;需要纯文本时用 `-o 文件` 落到文件里再读。

Symptom任务中途卡住,一直等确认,或在没有网络的环境里装依赖失败

Cause默认沙箱是只读、批准模式是逐条确认,联网行为在沙箱内被禁掉。

Fix需要装依赖就跑 `--full-auto`;只在可信环境考虑 `--yolo`,并优先用 `-a never -s read-only` 做纯只读调研。

Symptom任务总是「只说不做」,文件没被改动

Cause当前处于 plan/只读探索模式或沙箱是 read-only,写文件请求会被直接拒绝。

Fix用 `/plan` 之外先退出只读模式,执行阶段改用 `-s workspace-write` 或 `--full-auto`。

Symptom每次都要重复交代项目背景和编码规范

Cause会话是无状态的,约定没有落盘。

Fix把项目约定写进根目录或 ~/.codex/ 下的 AGENTS.md,Codex 会自动合并加载。

Symptom长会话越聊越慢、token 消耗过快,回答质量下降

Cause对话历史一直累积,没有压缩。

Fix会话内用 `/compact` 总结压缩,或 `/clear` 重置;`/status` 可先看当前用量。

Symptom接了 MCP 服务器但工具列表里看不到

Cause服务器配置缺失、名称写错,或需要重新加载会话。

Fix用 `codex mcp list` 确认已注册、`codex mcp get <name>` 看配置,再 `/new` 开新会话让工具重新载入。

Symptom改了文件但没进版本控制,review 时一片混乱

Cause工作区改动没有走 git 流程,`/diff` 只看 diff 不负责提交。

Fix会话内用 `/diff` 先看清改动范围,再自行提交;也可用 `codex apply` 把最新 diff 应用为 git apply。

Troubleshooting

  1. 1确认安装与登录状态

    codex --version

    先确认 CLI 在 PATH 中且能输出版本号;无头/SSH 环境用 `codex login --device-auth` 完成登录。

  2. 2把单次任务的完整回答落到文件便于审阅

    codex exec -o /tmp/result.txt "总结架构"

    执行完读 /tmp/result.txt,能确认模型确实产出了内容,而不是静默失败。

  3. 3让输出可直接被脚本消费

    codex exec --json "列出所有 API 端点"

    输出为 JSONL,逐行 json.loads 即可;管道场景注意不要混入非 JSON 的横幅信息。

  4. 4排查 MCP 服务器是否注册成功

    codex mcp list

    列出的每个名字对应一条配置,配合 `codex mcp get <name>` 查看完整参数。

  5. 5管道输入 + 本地模型的最小验证

    echo "重构 utils" | codex exec --oss

    这条同时验证了非交互输入通道与本地模型连通性,两步里任一失败都能立刻定位。

  6. 6生成补全脚本以确认子命令与标志可用

    codex completion bash

    把输出的补全脚本 source 进当前 shell,即可用 Tab 补全确认已安装版本支持哪些子命令与标志。

Command Examples

Run headless and emit JSON

codex exec --json "列出项目里所有 API 端点" codex exec -o endpoints.txt "总结架构"

codex exec(别名 codex e)是非交互事实标准,--json 输出 JSONL,-o 把最终回答存为文件。

Output

{"findings":{"endpoint_count":23,"categories":[...]}}
(最终回答同时写入 endpoints.txt,JSONL 便于 CI 解析)

Fully auto-complete an implementation

codex --full-auto "补齐 payment 模块的单测,改动前先看现有测试风格"

默认 --full-auto 等价于 workspace-write 沙箱 + on-failure 批准,安全且省心,是日常首选。

Output

(模型在禁用网络的沙箱内自行读写工作目录,仅在需要联网装依赖时才退出沙箱询问)

Explore a large repo read-only

codex -a never -s read-only "这个项目的构建流程和依赖拓扑是怎样的"

适合审计、调研、理解历史演进;如需写文件再切回 workspace-write 并加批准。

Output

(只读模式可读取全系统文件,不落任何修改、不弹确认)

Add a stdio MCP server

codex mcp add -- npx -y @modelcontextprotocol/server-github codex mcp list

__ 之后的所有参数原样传给服务器,可让模型在会话里直接调用仓库/工具接口。

Output

Added MCP server "server-github" (stdio)

Common Pitfalls

  • --dangerously-bypass-approvals-and-sandbox and --yolo skip all sandbox and approvals so the model can modify the system and run any command — only in isolated/throwaway environments.
  • Only -a never + -s read-only is truly read-only; -a never alone can still let the model edit files in the working directory.
  • Permission rules written into AGENTS.md make Codex follow team conventions by default but also lock in behavior — confirm impact before editing memory files.
  • codex exec runs unattended with no human approvals, so side-effecting commands rely on the sandbox to bound scope (workspace-write), not on -a prompts.

Tips

  • For non-interactive automation always use `codex exec` + `--json` with CI pipelines for codegen/review — Codex's signature use.
  • The default `--full-auto` auto-approves inside a network-disabled sandbox: safe and hands-off; it only exits the sandbox to ask when it needs network (e.g. npm install).
  • Put project conventions in AGENTS.md (repo root or ~/.codex/); Codex merges and loads them automatically — more efficient than repeating them in prompts.
  • For read-only exploration use `-a never -s read-only`: no prompts yet full file read access, ideal for audits/research.

FAQ

What is the difference between codex exec and plain codex?

codex is the interactive TUI with a human in the loop; codex exec is non-interactive, takes one instruction, finishes and exits, which is what you want in scripts and CI. Add --json for JSONL output that programs can parse, -o result.txt to save the final answer, and --output-schema to constrain the shape with a JSON Schema. Never drive automation through the interactive mode.

How should I combine sandbox and approval modes safely?

The sandbox (-s) sets filesystem reach: read-only is safest, workspace-write allows edits in the current directory, danger-full-access removes all limits. Approval mode (-a) decides when it stops to ask: untrusted confirms each action, never never asks. For production prefer workspace-write with untrusted; for read-only exploration use read-only with never; only consider full access inside a container.

How do I resume a session or branch off from one?

codex resume picks up the previous session, while codex fork derives a new thread from it — the difference is that fork creates an independent branch and leaves the original intact. Inside a session, /fork clones the current conversation, /new starts a fresh conversation within the same session without clearing history, and /compact summarizes the conversation to free tokens while keeping context.

How do I use local open-source models with Codex CLI?

Add --oss, which routes to open-source models through a local runtime such as Ollama; combined with codex exec --oss it works without network access. Choose a model with -m, for example -m gpt-5.4 or -m gpt-5.4-mini. Local models are generally weaker than frontier ones, so keep online models for complex refactors.

How do I make Codex output conform to a JSON Schema?

codex exec --output-schema '...' "task" constrains the output structure with a JSON Schema, which is what you want when a downstream program must parse it. Add --json for line-delimited JSON or -o result.txt to write the final answer straight to a file. Schema constraints are far more reliable than asking for JSON in the prompt.

Official References

Each command links to its official documentation below, so you can verify the latest usage and read deeper.

Maintained by LaoHand

Publicly updated on Aug 5, 2026, continuously proofread against official docs.

Contact Us

Wrong command or description? Send us corrections, business inquiries or product feedback by email.

Contact Us