本文为非官方中文翻译,内容以 OpenAI 官方英文文档为准。
官方来源:https://developers.openai.com/codex/noninteractive
非交互模式
使用 codex exec 在脚本和 CI 中运行 Codex
非交互模式让你可以在脚本中(例如持续集成(CI)作业)运行 Codex,而无需打开交互式 TUI。
你可以通过 codex exec 调用它。
有关各个 flag 的详细信息,请参阅 codex exec。
何时使用 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,并且只会将最终的 agent 消息打印到 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 "" - 允许更广泛的访问:
codex exec --sandbox danger-full-access ""
仅在受控环境中使用 danger-full-access(例如,隔离的 CI runner 或容器)。
Codex 保留了 codex exec --full-auto 作为已弃用的兼容性 flag,并会打印警告。在新脚本中,请优先使用显式的 --sandbox workspace-write flag。
当你需要一次不加载 $CODEX_HOME/config.toml 的运行时,请使用 --ignore-user-config;当你需要在受控自动化环境中跳过用户和项目 execpolicy .rules 文件时,请使用 --ignore-rules。
如果你配置了一个已启用且 required = true 的 MCP server,而它初始化失败,那么 codex exec 会直接报错退出,而不是在没有该 server 的情况下继续运行。
让输出可供机器读取
要在脚本中消费 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。
item 类型包括 agent 消息、reasoning、命令执行、文件更改、MCP 工具调用、web 搜索和计划更新。
示例 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 /--output-last-message 将其写入文件。这会将最终消息写入文件,同时仍将其打印到 stdout(详情见 codex exec)。
使用 schema 创建结构化输出
如果你需要为下游步骤提供结构化数据,请使用 --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
}
使用该 schema 运行 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"]
}
在 CI 中进行身份验证
codex exec 默认会复用已保存的 CLI 身份验证。在 CI 中,通常会显式提供凭据:
使用 API key 身份验证(推荐)
- 将
CODEX_API_KEY设置为该作业的 secret 环境变量。 - 留意提示和工具输出:它们可能包含敏感代码或数据。
要为单次运行使用不同的 API key,请内联设置 CODEX_API_KEY:
CODEX_API_KEY=<api-key> codex exec --json "triage open bug reports"
CODEX_API_KEY 仅在 codex exec 中受支持。
如果你需要在 CI/CD 作业中使用 Codex 用户账户而不是 API key 运行,例如企业团队在受信任的 runner 上使用 ChatGPT 管理的 Codex 访问, 或者需要使用 ChatGPT/Codex 速率限制而不是 API key 用量的用户,请阅读以下内容。
API key 是自动化的正确默认选择,因为它们更容易 配置和轮换。只有在你确实需要以自己的 Codex 账户身份运行时,才使用这条路径。
请像对待密码一样对待 ~/.codex/auth.json:它包含访问令牌。不要
提交它,不要把它粘贴到工单中,也不要在聊天里分享它。
不要将此工作流用于公共或开源仓库。如果在 runner 上无法使用 codex login,
请通过安全存储预置 auth.json,在 runner 上运行
Codex 以便 Codex 就地刷新它,并在多次运行之间持久化更新后的文件。
请参阅在 CI/CD 中维护 Codex 账户身份验证(高级)。
恢复非交互会话
如果你需要继续先前的一次运行(例如,两阶段流水线),请使用 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 仓库
Codex 要求命令必须在 Git 仓库内运行,以防止破坏性更改。如果你确定环境是安全的,可以使用 codex exec --skip-git-repo-check 覆盖此检查。
常见自动化模式
示例:在 GitHub Actions 中自动修复 CI 失败
你可以使用 codex exec 在 CI 工作流失败时自动提出修复。典型模式如下:
- 当主 CI 工作流以错误结束时,触发一个后续工作流。
- 检出失败的 commit SHA。
- 安装依赖,并使用范围明确的提示和最小权限运行 Codex。
- 重新运行测试命令。
- 使用生成的补丁打开一个 pull request。
使用 Codex CLI 的最小工作流
下面的示例展示了核心步骤。请根据你的技术栈调整安装和测试命令。
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 --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,可以通过 Codex GitHub Action 运行 codex exec,并将提示作为输入传递。
高级 stdin 管道用法
当另一个命令为 Codex 产生输入时,请根据指令应来自何处选择 stdin 模式。如果你已经知道指令内容,并希望将管道输出作为上下文传入,请使用 prompt-plus-stdin。当 stdin 应该成为完整提示时,请使用 codex exec -。
使用 prompt-plus-stdin
当另一个命令已经生成了你希望 Codex 检查的数据时,prompt-plus-stdin 很有用。在这种模式下,你自己编写指令,并将输出通过管道作为上下文传入,因此它非常适合围绕命令输出、日志和生成数据构建的 CLI 工作流。
npm test 2>&1 \
| codex exec "summarize the failing tests and propose the smallest likely fix" \
| tee test-summary.md
总结日志
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 问题
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 的更新
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 日志起草一条 pull request 评论
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 -
如果你省略提示参数,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