codex

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Codex CLI (Non-Interactive)

Codex CLI (非交互模式)

Codex is OpenAI's coding agent. Use
codex exec
to run it non-interactively from any cli agent.
Codex是OpenAI的编码Agent。使用
codex exec
可从任意CLI Agent以非交互模式运行它。

When to Use Codex

何时使用Codex

Use Codex when:
  • Parallel work: Delegate a task while continuing other work
  • Second opinion: Get an independent implementation or review
  • Long-running tasks: Offload tasks that may take many iterations
  • Code review: Use
    codex exec review
    for PR/diff reviews
Do NOT use Codex for:
  • Simple file reads/edits you can do directly
  • Tasks requiring back-and-forth conversation
  • Tasks needing your current context
适合使用Codex的场景:
  • 并行工作:在处理其他工作的同时委托任务给Codex执行
  • 第二种意见:获取独立的实现方案或评审结果
  • 长耗时任务:卸载可能需要多轮迭代完成的任务
  • 代码评审:使用
    codex exec review
    完成PR/差异评审
不适合使用Codex的场景:
  • 你可以直接完成的简单文件读写/编辑操作
  • 需要来回对话的任务
  • 需要用到你当前上下文的任务

Quick Reference

快速参考

bash
undefined
bash
undefined

Analysis (read-only, default)

分析(只读模式,默认)

codex exec "describe the architecture of this codebase"
codex exec "describe the architecture of this codebase"

Allow file edits

允许文件编辑

codex exec --full-auto "fix the failing tests"
codex exec --full-auto "fix the failing tests"

Code review

代码评审

codex exec review --uncommitted codex exec review --base main
codex exec review --uncommitted codex exec review --base main

Structured JSON output

结构化JSON输出

codex exec --output-schema schema.json -o result.json "extract metadata"
codex exec --output-schema schema.json -o result.json "extract metadata"

Continue previous session (inherits original sandbox settings)

恢复上一次会话(继承原始沙箱设置)

codex exec resume --last "now add tests"
undefined
codex exec resume --last "now add tests"
undefined

Core Concepts

核心概念

Output Streams

输出流

Progress goes to stderr, final result to stdout. To capture only the result:
bash
codex exec "summarize the repo" 2>/dev/null > summary.txt
To see progress while capturing result:
bash
codex exec "generate changelog" 2>&1 | tee output.txt
进度信息输出到stderr,最终结果输出到stdout。如果只需要捕获结果可执行:
bash
codex exec "summarize the repo" 2>/dev/null > summary.txt
如果需要在捕获结果的同时查看进度:
bash
codex exec "generate changelog" 2>&1 | tee output.txt

Sandbox Modes

沙箱模式

In non-interactive mode, no approval prompts are possible. Permissions must be set upfront:
ModeFlagBehavior
Read-only(default)Reads anywhere, writes/commands blocked
Workspace-write
--full-auto
Pre-approves edits and commands in workspace
Full access
--yolo
No restrictions. Use in isolated environments only
Choose based on task:
  • Analysis/explanation → default (read-only)
  • Fix bugs/implement features →
    --full-auto
  • Needs network or system access →
    --yolo
    (dangerous)
Note:
~/.codex/config.toml
can set project trust levels that override defaults.
在非交互模式下不会弹出审批提示,权限必须预先设置:
模式标识行为
只读(默认)可读取任意位置内容,写入/执行命令被拦截
工作区可写
--full-auto
预先审批工作区内的编辑和命令执行操作
完全权限
--yolo
无任何限制,仅可在隔离环境中使用
根据任务选择模式:
  • 分析/解释 → 默认(只读)
  • 修复bug/实现功能 →
    --full-auto
  • 需要网络或系统访问权限 →
    --yolo
    (高风险)
注意:
~/.codex/config.toml
可以设置项目信任等级,会覆盖默认配置。

Models

模型

Default model is
gpt-5.2-codex
. Override with
-m
:
bash
codex exec -m gpt-5 "explain this code"
默认模型为
gpt-5.2-codex
,可通过
-m
参数覆盖:
bash
codex exec -m gpt-5 "explain this code"

Authentication

鉴权

By default, the user should already be authenticated. If not, set
CODEX_API_KEY
:
bash
CODEX_API_KEY=sk-... codex exec "task"
默认情况下用户应已完成鉴权,如果未鉴权可设置
CODEX_API_KEY
环境变量:
bash
CODEX_API_KEY=sk-... codex exec "task"

Code Review

代码评审

Built-in review subcommand:
bash
undefined
内置评审子命令:
bash
undefined

Review uncommitted changes

评审未提交的变更

codex exec review --uncommitted
codex exec review --uncommitted

Review against a base branch

与基准分支对比评审

codex exec review --base main
codex exec review --base main

Review a specific commit

评审指定提交

codex exec review --commit abc123
undefined
codex exec review --commit abc123
undefined

Structured Output

结构化输出

Use
--output-schema
for JSON output. Important: OpenAI requires
additionalProperties: false
on all object types.
bash
codex exec --output-schema schema.json -o result.json "extract API endpoints"
Schema example:
json
{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "endpoints": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "path": { "type": "string" },
          "method": { "type": "string" }
        },
        "required": ["path", "method"],
        "additionalProperties": false
      }
    }
  },
  "required": ["name", "endpoints"],
  "additionalProperties": false
}
使用
--output-schema
参数获取JSON输出。重要提示:OpenAI要求所有对象类型必须设置
additionalProperties: false
bash
codex exec --output-schema schema.json -o result.json "extract API endpoints"
Schema示例:
json
{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "endpoints": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "path": { "type": "string" },
          "method": { "type": "string" }
        },
        "required": ["path", "method"],
        "additionalProperties": false
      }
    }
  },
  "required": ["name", "endpoints"],
  "additionalProperties": false
}

Session Resume

会话恢复

Resume continues a previous session, inheriting its sandbox settings:
bash
undefined
恢复功能可以延续之前的会话,继承原会话的沙箱设置
bash
undefined

Start a task

启动一个任务

codex exec --full-auto "implement rate limiter"
codex exec --full-auto "implement rate limiter"

Continue later (inherits --full-auto from original)

后续继续执行(继承原会话的--full-auto权限)

codex exec resume --last "add unit tests"
codex exec resume --last "add unit tests"

Or resume by session ID

也可以通过会话ID恢复

codex exec resume <SESSION_ID> "follow-up task"

**Note**: Cannot pass `--full-auto` to resume; it inherits from the original session.
codex exec resume <SESSION_ID> "follow-up task"

**注意**:不能在恢复会话时传入`--full-auto`参数,权限会自动从原会话继承。

JSONL Event Stream

JSONL事件流

For programmatic use,
--json
outputs structured events:
bash
codex exec --json "analyze code" 2>/dev/null | jq -c 'select(.type == "item.completed")'
如果需要程序化调用,
--json
参数可以输出结构化事件:
bash
codex exec --json "analyze code" 2>/dev/null | jq -c 'select(.type == "item.completed")'

Performance & Best Practices

性能与最佳实践

Execution Time

执行时间

Complex tasks typically take 60-120+ seconds. Simple analysis tasks complete in 10-30 seconds.
  • Tasks may continue executing even after your timeout
  • Always check if files were modified regardless of timeout status
  • Use
    tail -f <output_file>
    to monitor long-running background tasks
复杂任务通常需要60-120+秒,简单分析任务可在10-30秒内完成。
  • 即使触发超时,任务也可能继续在后台执行
  • 无论超时状态如何,都需要检查文件是否被修改
  • 可以使用
    tail -f <output_file>
    监控后台运行的长耗时任务

Task Granularity

任务粒度

Break complex work into focused tasks:
bash
undefined
将复杂工作拆分为多个聚焦的小任务:
bash
undefined

Good: Focused, single-purpose tasks

良好实践:聚焦的单用途任务

codex exec --full-auto "add star ratings to the skill cards" codex exec --full-auto "add a search filter to the toolbar"
codex exec --full-auto "add star ratings to the skill cards" codex exec --full-auto "add a search filter to the toolbar"

Avoid: Multi-feature requests in one task

应当避免:单个任务包含多个功能需求

codex exec --full-auto "add ratings, search, filters, modal, and animations"
undefined
codex exec --full-auto "add ratings, search, filters, modal, and animations"
undefined

Concurrent Editing

并发编辑

Avoid running multiple Codex sessions on the same file simultaneously. While it may work, concurrent edits risk merge conflicts or overwrites.
避免同时在同一个文件上运行多个Codex会话。虽然有可能正常运行,但并发编辑存在合并冲突或内容被覆盖的风险。

Large Files

大文件处理

Files over ~2000 lines slow execution as Codex reads the entire file multiple times. Consider:
  • Splitting into multiple files when possible
  • Using specific line references in prompts
  • Breaking incremental changes into smaller tasks
超过2000行的文件会拖慢执行速度,因为Codex需要多次读取整个文件。可以考虑:
  • 尽可能拆分为多个小文件
  • 在提示词中指定具体行号
  • 将增量变更拆分为更小的任务

Error Handling

错误处理

Common errors:
  • Timeout: Long tasks may timeout. Check if work completed anyway, or use resume to continue.
  • Sandbox blocked: Task needs writes but running in read-only. Use
    --full-auto
    .
  • Schema validation: Missing
    additionalProperties: false
    in schema objects.
  • Model not supported: Some models unavailable with ChatGPT auth. Use default
    gpt-5.2-codex
    .
常见错误:
  • 超时:长任务可能触发超时。检查任务是否已经完成,或使用恢复功能继续执行
  • 沙箱拦截:任务需要写入权限但当前为只读模式,可使用
    --full-auto
    参数
  • Schema校验失败:Schema对象中缺少
    additionalProperties: false
    配置
  • 模型不支持:部分模型无法通过ChatGPT鉴权使用,建议使用默认的
    gpt-5.2-codex

Detailed References

详细参考

  • exec-reference.md: Complete flag reference
  • prompting.md: Effective prompts and workflow patterns
  • exec-reference.md:完整参数参考
  • prompting.md:高效提示词与工作流模式

Project Context

项目上下文

Codex reads
AGENTS.md
files for project instructions:
  • ~/.codex/AGENTS.md
    - Global defaults
  • <repo>/AGENTS.md
    - Project-specific
markdown
undefined
Codex会读取
AGENTS.md
文件获取项目指令:
  • ~/.codex/AGENTS.md
    - 全局默认配置
  • <repo>/AGENTS.md
    - 项目特定配置
markdown
undefined

AGENTS.md

AGENTS.md

  • Run
    npm test
    after modifying JS files
  • Use pnpm for dependencies
undefined
  • Run
    npm test
    after modifying JS files
  • Use pnpm for dependencies
undefined