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.
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/codexbrew install --cask codexcodex --versioncodex logincodex login --with-api-keycodex login --device-authcodex logoutInteractive Mode 5
codexcodex "Explain this codebase"codex --search "Fix the login bug"codex -i ./screenshot.png "Implement this UI"codex --ossNon-interactive (codex exec) 5
codex exec "Fix the failing tests"echo "Refactor utils" | codex exec --osscodex exec --json "List all API endpoints"codex exec -o result.txt "Summarize the architecture"codex exec --output-schema '{...}' "Extract config"Session Management 5
codex resumecodex forkcodex applycodex --restorecodex --historyModel & Config 5
codex -m gpt-5.4 "Complex task"codex -p openai "Generate a component"codex -C /path/to/repocodex -ccodex completion bashSandbox & Approval 8
codex -s read-onlycodex -s workspace-writecodex -s danger-full-accesscodex -a untrustedcodex -a nevercodex --full-auto "Complete the implementation"codex --yolo "Emergency fix"codex --dangerously-bypass-approvals-and-sandboxMCP & Codex Cloud 7
codex mcp listcodex mcp add -- <args...>codex mcp add --url https://example.com/mcpcodex mcp get <name>codex mcp remove <name>codex cloud exec --env "task"codex cloud exec --env --attempts 3 "task"Interactive Slash Commands 12
/clear/compact/new/fork/diff/status/init/review/plan/model/permissions/exitParameter matrix
| Parameter | Effect | Example |
|---|---|---|
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> | 加载命名配置 profile | codex -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-failure | codex --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确认安装与登录状态
codex --version先确认 CLI 在 PATH 中且能输出版本号;无头/SSH 环境用 `codex login --device-auth` 完成登录。
2把单次任务的完整回答落到文件便于审阅
codex exec -o /tmp/result.txt "总结架构"执行完读 /tmp/result.txt,能确认模型确实产出了内容,而不是静默失败。
3让输出可直接被脚本消费
codex exec --json "列出所有 API 端点"输出为 JSONL,逐行 json.loads 即可;管道场景注意不要混入非 JSON 的横幅信息。
4排查 MCP 服务器是否注册成功
codex mcp list列出的每个名字对应一条配置,配合 `codex mcp get <name>` 查看完整参数。
5管道输入 + 本地模型的最小验证
echo "重构 utils" | codex exec --oss这条同时验证了非交互输入通道与本地模型连通性,两步里任一失败都能立刻定位。
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