非交互模式
非交互模式允许你从脚本中运行 Codex(例如持续集成(CI)作业),而无需打开交互式 TUI。使用 codex exec 调用它。
有关标志级别的详细信息,请参阅 codex exec。
何时使用 codex exec
Section titled “何时使用 codex exec”当你希望 Codex 执行以下操作时,请使用 codex exec:
- 作为流水线的一部分运行(CI、合并前检查、计划任务)。
- 生成可通过管道传递给其他工具的输出(例如生成发布说明或摘要)。
- 自然融入 CLI 工作流,将命令输出传递给 Codex,并将 Codex 输出传递给其他工具。
- 使用明确预设的沙箱和批准设置运行。
将任务提示作为单个参数传入:
codex exec "summarize the repository structure and list the top 5 risky areas"运行 codex exec 时,Codex 会将进度流式输出到 stderr,并仅将最终代理消息输出到 stdout。这样可以轻松地重定向或通过管道传递最终结果:
codex exec "generate release notes for the last 10 commits" | tee release-notes.md如果不希望将会话 rollout 文件持久化到磁盘,请使用 --ephemeral:
codex exec --ephemeral "triage this repository and suggest next steps"如果通过管道传入 stdin,同时又提供了提示参数,Codex 会将该提示视为指令,并将管道内容视为附加上下文。
这样可以轻松地使用一个命令生成输入,并将其直接交给 Codex:
curl -s https://jsonplaceholder.typicode.com/comments \ | codex exec "format the top 20 items into a markdown table" \ > table.md有关更高级的 stdin 管道模式,请参阅高级 stdin 管道。
默认情况下,codex exec 在只读沙箱中运行。在自动化环境中,请根据工作流设置所需的最小权限:
- 允许编辑:
codex exec --sandbox workspace-write "<task>" - 允许更广泛的访问:
codex exec --sandbox danger-full-access "<task>"
仅在受控环境中使用 danger-full-access(例如隔离的 CI runner 或容器)。
Codex 保留 codex exec --full-auto 作为已弃用的兼容性标志,并会打印警告。对于新脚本,建议使用显式的 --sandbox workspace-write 标志。
当你需要运行不加载 $CODEX_HOME/config.toml 的任务时,请使用 --ignore-user-config;当你需要在受控的自动化环境中跳过用户和项目 execpolicy .rules 文件时,请使用 --ignore-rules。
如果你配置了一个启用的 MCP server,并将 required = true,而该服务器初始化失败,codex exec 会退出并报错,而不是在没有该服务器的情况下继续运行。
使输出可供机器读取
Section titled “使输出可供机器读取”要在脚本中使用 Codex 输出,请使用 JSON Lines 输出:
codex exec --json "summarize the repo structure" | jq启用 --json 后,stdout 会变为 JSON Lines(JSONL)流,因此你可以捕获 Codex 运行期间发出的每个事件。事件类型包括 thread.started、turn.started、turn.completed、turn.failed、item.* 和 error。
项目类型包括代理消息、推理、命令执行、文件更改、MCP 工具调用、网页搜索和计划更新。
JSON 流示例(每行都是一个 JSON 对象):
{"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,"reasoning_output_tokens":0}}如果只需要最终消息,请使用 -o <path>/--output-last-message <path> 将其写入文件。这会将最终消息写入文件,同时仍将其打印到 stdout(详情请参阅 codex exec)。
使用架构创建结构化输出
Section titled “使用架构创建结构化输出”如果下游步骤需要结构化数据,请使用 --output-schema,要求最终响应符合 JSON Schema。这对于需要稳定字段的自动化工作流很有用(例如作业摘要、风险报告或发布元数据)。
schema.json
{ "type": "object", "properties": { "project_name": { "type": "string" }, "programming_languages": { "type": "array", "items": { "type": "string" } } }, "required": ["project_name", "programming_languages"], "additionalProperties": false}使用该架构运行 Codex,并将最终 JSON 响应写入磁盘:
codex exec "Extract project metadata" \ --output-schema ./schema.json \ -o ./project-metadata.json最终输出示例(stdout):
{ "project_name": "Codex CLI", "programming_languages": ["Rust", "TypeScript", "Shell"]}在自动化环境中进行身份验证
Section titled “在自动化环境中进行身份验证”默认情况下,codex exec 会重用已保存的 CLI 身份验证信息。在 CI 中,通常需要显式提供凭据:
使用 API 密钥身份验证
Section titled “使用 API 密钥身份验证”对于 GitHub Actions,请使用 Codex GitHub Action,而不是自行安装 CLI 并进行身份验证。该 Action 旨在通过安装 Codex、启动 Responses API 代理,以及使用可配置的安全策略运行 Codex,来减少 API 密钥暴露。
对于会检出或运行由仓库控制的代码的工作流,请勿将 OPENAI_API_KEY 或 CODEX_API_KEY 设置为作业级环境变量。同一作业中的构建脚本、测试、依赖项生命周期钩子或受入侵的 Action 都可能读取这些环境变量。
对于其他自动化环境,仅在单次 codex exec 调用期间设置 CODEX_API_KEY,并确保同一进程环境中不会运行不受信任的代码。
若要为单次运行使用其他 API 密钥,请以内联方式设置 CODEX_API_KEY:
CODEX_API_KEY=<api-key> codex exec --json "triage open bug reports"CODEX_API_KEY 仅支持在 codex exec 中使用。
在 CI/CD 中使用 ChatGPT 管理的身份验证(高级)
Section titled “在 CI/CD 中使用 ChatGPT 管理的身份验证(高级)”如果你需要使用 Codex 用户帐户而不是 API 密钥运行 CI/CD 作业,请阅读本节。例如,企业团队可能需要在受信任的 runner 上使用 ChatGPT 管理的 Codex 访问权限,或者用户可能需要使用 ChatGPT/Codex 速率限制,而不是 API 密钥。
API 密钥是自动化场景的默认选择,因为它们更易于配置和轮换。仅当你确实需要以自己的 Codex 帐户运行时,才使用此方式。
请像对待密码一样保护 ~/.codex/auth.json:其中包含访问令牌。不要提交它、将其粘贴到工单中,也不要在聊天中分享。
不要将此工作流用于公共或开源仓库。如果 runner 上无法使用 codex login,请通过安全存储预置 auth.json,在 runner 上运行 Codex 以便 Codex 就地刷新该文件,并在多次运行之间持久化更新后的文件。
请参阅在 CI/CD 中维护 Codex 帐户身份验证(高级)。
恢复非交互式会话
Section titled “恢复非交互式会话”如果需要继续之前的运行(例如两阶段流水线),请使用 resume 子命令:
codex exec "review the change for race conditions"codex exec resume --last "fix the race conditions you found"你也可以使用 codex exec resume <SESSION_ID> 指定特定的会话 ID。
需要 Git 仓库
Section titled “需要 Git 仓库”Codex 要求命令在 Git 仓库内运行,以防止破坏性更改。如果确定环境安全,可以使用 codex exec --skip-git-repo-check 覆盖此检查。
常见自动化模式
Section titled “常见自动化模式”示例:在 GitHub Actions 中自动修复 CI 失败
Section titled “示例:在 GitHub Actions 中自动修复 CI 失败”对于 GitHub Actions 工作流,请使用 openai/codex-action,而不是安装 Codex 并将 API 密钥传递给 shell 步骤。该 Action 会为 OpenAI API 密钥启动安全代理。
你可以使用 Codex 在 CI 工作流失败时自动提出修复方案。模式如下:
- 在主 CI 工作流完成且出错后,触发后续工作流。
- 仅使用仓库读取权限检出失败的提交。
- 在 Codex 运行前执行设置命令,并且不要将 OpenAI API 密钥暴露给这些步骤。
- 运行 Codex GitHub Action。
- 将 Codex 的本地更改保存为补丁构件。
- 在单独的作业中应用补丁并创建拉取请求。
下面的 Codex 作业只有 contents: read 权限。Codex 运行后,它只会将差异序列化为构件。open_pr 作业会获得仓库写入权限,但不会获得 OPENAI_API_KEY。
该示例假设使用 Node.js 项目。请根据你的技术栈调整设置和测试命令。
有关更深入的安全检查清单,请参阅 Codex GitHub Action 安全指南。
name: Codex auto-fix on CI failure
on: workflow_run: workflows: ["CI"] types: [completed]
jobs: generate_fix: if: ${{ github.event.workflow_run.conclusion == 'failure' }} runs-on: ubuntu-latest permissions: contents: read outputs: has_patch: ${{ steps.diff.outputs.has_patch }} steps: - uses: actions/checkout@v5 with: ref: ${{ github.event.workflow_run.head_sha }} fetch-depth: 0 persist-credentials: false
- uses: actions/setup-node@v4 with: node-version: "20"
- name: Install dependencies run: | if [ -f package-lock.json ]; then npm ci; fi
- name: Run Codex uses: openai/codex-action@v1 with: openai-api-key: ${{ secrets.OPENAI_API_KEY }} prompt: | The CI workflow "${{ github.event.workflow_run.name }}" failed for commit ${{ github.event.workflow_run.head_sha }}.
Run `npm test --silent` to reproduce the failure. Identify the minimal change needed to make the tests pass, implement only that change, and run `npm test --silent` again.
Do not refactor unrelated files.
- name: Create patch artifact id: diff run: | git add -N . git diff --binary HEAD > codex.patch if [ -s codex.patch ]; then echo "has_patch=true" >> "$GITHUB_OUTPUT" else echo "has_patch=false" >> "$GITHUB_OUTPUT" fi
- name: Upload patch artifact if: steps.diff.outputs.has_patch == 'true' uses: actions/upload-artifact@v4 with: name: codex-fix-patch path: codex.patch if-no-files-found: error
open_pr: runs-on: ubuntu-latest needs: generate_fix if: needs.generate_fix.outputs.has_patch == 'true' permissions: contents: write pull-requests: write steps: - uses: actions/checkout@v5 with: ref: ${{ github.event.workflow_run.head_sha }} fetch-depth: 0
- uses: actions/download-artifact@v4 with: name: codex-fix-patch
- name: Apply Codex patch run: git apply --index codex.patch
- name: Open pull request env: GH_TOKEN: ${{ github.token }} FAILED_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }} FAILED_HEAD_SHA: ${{ github.event.workflow_run.head_sha }} RUN_ID: ${{ github.event.workflow_run.run_id }} run: | branch="codex/auto-fix-$RUN_ID"
git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" git switch -c "$branch" git commit -m "Auto-fix failing CI via Codex" git push origin "$branch"
{ echo "Codex generated this patch after CI failed for \`$FAILED_HEAD_SHA\`." echo echo "Review the changes before merging." } > pr-body.md
gh pr create \ --base "$FAILED_HEAD_BRANCH" \ --head "$branch" \ --title "Auto-fix failing CI via Codex" \ --body-file pr-body.md高级 stdin 管道
Section titled “高级 stdin 管道”当另一个命令为 Codex 生成输入时,请根据指令的来源选择 stdin 模式。如果你已经知道指令,并希望将管道输出作为上下文传入,请使用“提示加 stdin”。如果 stdin 应作为完整提示,请使用 codex exec -。
使用提示加 stdin
Section titled “使用提示加 stdin”当另一个命令已经生成了你希望 Codex 检查的数据时,提示加 stdin 模式非常有用。在此模式下,你编写指令,并将输出通过管道作为上下文传入,非常适合围绕命令输出、日志和生成数据构建的 CLI 工作流。
npm test 2>&1 \ | codex exec "summarize the failing tests and propose the smallest likely fix" \ | tee test-summary.md更多提示加 stdin 示例
Section titled “更多提示加 stdin 示例”tail -n 200 app.log \ | codex exec "identify the likely root cause, cite the most important errors, and suggest the next three debugging steps" \ > log-triage.md检查 TLS 或 HTTP 问题
Section titled “检查 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准备可直接发送到 Slack 的更新
Section titled “准备可直接发送到 Slack 的更新”gh run view 123456 --log \ | codex exec "write a concise Slack-ready update on the CI failure, including the likely cause and next step" \ | pbcopy根据 CI 日志草拟拉取请求评论
Section titled “根据 CI 日志草拟拉取请求评论”gh run view 123456 --log \ | codex exec "summarize the failure in 5 bullets for the pull request thread" \ | gh pr comment 789 --body-file -当 stdin 是提示时使用 codex exec -
Section titled “当 stdin 是提示时使用 codex exec -”如果省略提示参数,Codex 会从 stdin 读取提示。当你希望显式强制执行此行为时,请使用 codex exec -。
当另一个命令或脚本动态生成完整提示时,- 占位符非常有用。当你将提示存储在文件中、使用 shell 脚本组装提示,或在将完整提示交给 Codex 前将实时命令输出与指令组合起来时,这种方式非常适合。
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