Skip to content

codex exec 是 Codex 的非交互模式,适合 CI/CD 任务、脚本自动化和命令行管道。它将进度流式输出到 stderr,只把最终 Agent 消息打印到 stdout,便于重定向。支持 JSON Lines 输出、结构化 JSON Schema、stdin 管道,以及用 API Key 在 CI 中认证。

Codex 非交互模式(codex exec)

非交互模式让你从脚本(如 CI 任务)运行 Codex,不打开交互式 TUI,通过 codex exec 调用。

详细 Flag 说明见 CLI 命令行参考


什么时候用 codex exec

以下场景适合使用 codex exec

  • 作为流水线的一部分运行(CI、合并前检查、定时任务)
  • 将输出管道传给其他工具(如生成 Release Notes 或摘要)
  • 自然融入 CLI 工作流,将命令输出传给 Codex,再把 Codex 输出传给其他工具
  • 使用预先确定的沙箱和审批设置运行

基本用法

将任务 Prompt 作为单个参数传入:

bash
codex exec "summarize the repository structure and list the top 5 risky areas"

运行时,Codex 将进度流式输出到 stderr,只将最终 Agent 消息打印到 stdout,方便重定向或管道传输:

bash
codex exec "generate release notes for the last 10 commits" | tee release-notes.md

不想在磁盘上持久化 session rollout 文件时用 --ephemeral

bash
codex exec --ephemeral "triage this repository and suggest next steps"

如果 stdin 已管道且同时提供了 Prompt 参数,Codex 将 Prompt 作为指令,管道内容作为附加上下文:

bash
curl -s https://jsonplaceholder.typicode.com/comments \
  | codex exec "format the top 20 items into a markdown table" \
  > table.md

权限与安全

默认情况下,codex exec 在只读沙箱中运行。在自动化场景中,设置最小所需权限:

bash
# 允许编辑文件
codex exec --full-auto "<task>"

# 允许更广泛的访问
codex exec --sandbox danger-full-access "<task>"

danger-full-access 仅在受控环境(如隔离的 CI runner 或容器)中使用。

如果某个 MCP Server 配置了 required = true 但初始化失败,codex exec 会报错退出而不是继续运行。


机器可读输出(JSON Lines)

在脚本中消费 Codex 输出时,使用 JSON Lines 输出:

bash
codex exec --json "summarize the repo structure" | jq

启用 --json 后,stdout 变为 JSON Lines(JSONL)流,可以捕获 Codex 运行时发出的每个事件。事件类型包括:thread.startedturn.startedturn.completedturn.faileditem.*error

Item 类型包括 Agent 消息、推理过程、命令执行、文件变更、MCP 工具调用、Web 搜索和计划更新。

示例 JSON 流(每行是一个 JSON 对象):

jsonl
{"type":"thread.started","thread_id":"0199a213-81c0-7800-8aa1-bbab2a035a53"}
{"type":"turn.started"}
{"type":"item.started","item":{"id":"item_1","type":"command_execution","command":"bash -lc ls","status":"in_progress"}}
{"type":"item.completed","item":{"id":"item_3","type":"agent_message","text":"Repo contains docs, sdk, and examples directories."}}
{"type":"turn.completed","usage":{"input_tokens":24763,"cached_input_tokens":24448,"output_tokens":122}}

只需要最终消息时,用 -o <path>/--output-last-message <path> 写入文件(同时仍然打印到 stdout)。


结构化输出(JSON Schema)

需要供下游步骤使用的结构化数据时,用 --output-schema 请求符合 JSON Schema 的最终回复,适合需要稳定字段的自动化工作流(如任务摘要、风险报告、Release 元数据)。

schema.json

json
{
  "type": "object",
  "properties": {
    "project_name": { "type": "string" },
    "programming_languages": {
      "type": "array",
      "items": { "type": "string" }
    }
  },
  "required": ["project_name", "programming_languages"],
  "additionalProperties": false
}
bash
codex exec "Extract project metadata" \
  --output-schema ./schema.json \
  -o ./project-metadata.json

输出示例:

json
{
  "project_name": "Codex CLI",
  "programming_languages": ["Rust", "TypeScript", "Shell"]
}

在 CI 中认证

codex exec 默认复用已保存的 CLI 认证。在 CI 中通常显式提供凭据。

使用 API Key(推荐)

CODEX_API_KEY 设为任务的 secret 环境变量。单次运行时:

bash
CODEX_API_KEY=<api-key> codex exec --json "triage open bug reports"

CODEX_API_KEY 只在 codex exec 中支持。


恢复非交互 Session

需要继续前一次运行时(如两阶段流水线),使用 resume 子命令:

bash
codex exec "review the change for race conditions"
codex exec resume --last "fix the race conditions you found"

也可以用 codex exec resume <SESSION_ID> 指定特定 session ID。


必须在 Git 仓库中运行

Codex 要求在 Git 仓库内运行,以防止破坏性修改。如果确认环境安全,用 --skip-git-repo-check 跳过检查。


常见自动化场景

GitHub Actions 自动修复 CI 失败

codex exec 在 CI 工作流失败时自动提出修复方案:

yaml
name: Codex auto-fix on CI failure

on:
  workflow_run:
    workflows: ["CI"]
    types: [completed]

permissions:
  contents: write
  pull-requests: write

jobs:
  auto-fix:
    if: ${{ github.event.workflow_run.conclusion == 'failure' }}
    runs-on: ubuntu-latest
    env:
      OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
      FAILED_HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
      FAILED_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ env.FAILED_HEAD_SHA }}
          fetch-depth: 0

      - uses: actions/setup-node@v4
        with:
          node-version: "20"

      - name: Install dependencies
        run: |
          if [ -f package-lock.json ]; then npm ci; else npm i; fi

      - name: Install Codex
        run: npm i -g @openai/codex

      - name: Authenticate Codex
        run: codex login --api-key "$OPENAI_API_KEY"

      - name: Run Codex
        run: |
          codex exec --full-auto --sandbox workspace-write \
            "Read the repository, run the test suite, identify the minimal change needed to make all tests pass, implement only that change, and stop. Do not refactor unrelated files."

      - name: Verify tests
        run: npm test --silent

      - name: Create pull request
        if: success()
        uses: peter-evans/create-pull-request@v6
        with:
          branch: codex/auto-fix-${{ github.event.workflow_run.run_id }}
          base: ${{ env.FAILED_HEAD_BRANCH }}
          title: "Auto-fix failing CI via Codex"

也可以用 Codex GitHub Action 替代手动安装 CLI。


进阶 stdin 管道模式

Prompt + stdin 模式

已知指令、希望将命令输出作为上下文传入时使用:

bash
npm test 2>&1 \
  | codex exec "summarize the failing tests and propose the smallest likely fix" \
  | tee test-summary.md

更多示例:

bash
# 分析日志
tail -n 200 app.log \
  | codex exec "identify the likely root cause and suggest the next three debugging steps" \
  > log-triage.md

# 检查 TLS/HTTP 问题
curl -vv https://api.example.com/health 2>&1 \
  | codex exec "explain the TLS or HTTP failure and suggest the most likely fix" \
  > tls-debug.md

stdin 作为 Prompt(codex exec -

如果脚本动态生成整个 Prompt,用 codex exec - 强制从 stdin 读取 Prompt:

bash
cat prompt.txt | codex exec -

printf "Summarize this error log in 3 bullets:\n\n%s\n" "$(tail -n 200 app.log)" \
  | codex exec -

generate_prompt.sh | codex exec - --json > result.jsonl

常见问题

Q: codex exec 和普通交互式 codex 的核心区别是什么?

A: codex exec 不打开 TUI,进度输出到 stderr,只有最终结果到 stdout,适合脚本管道。交互式 codex 提供完整的终端界面,适合人机交互。两者共用同一个 Agent 和权限体系。

Q: 在 CI 中该用 API Key 还是 ChatGPT auth.json?

A: 推荐 API Key——更容易生成、轮换和管理权限,不消耗个人积分配额。ChatGPT auth.json 的方式适合企业环境下需要用 ChatGPT 账号速率限制的特殊场景(详见身份认证文档的 CI/CD 部分)。

Q: --ephemeral 有什么用?

A: 加了 --ephemeral 后,Codex 不会在磁盘上持久化 session rollout 文件,适合一次性任务或不希望留下本地记录的场景,但 resume 命令也就无法继续这类 session。