非交互模式允许你在不打开交互式 TUI 的情况下,从脚本(例如,持续集成 (CI) 作业)中运行 Codex。你可以通过以下命令调用它 codex exec.
For flag-level details, see codex exec.
何时使用 codex exec
使用 codex exec 当你希望 Codex 执行以下操作时:
- 作为流水线的一部分运行(CI、合并前检查、定时作业)。
- 生成可以管道传递给其他工具的输出(例如,生成发布说明或摘要)。
- 自然融入将命令输出传递给 Codex,并将 Codex 输出传递给其他工具的 CLI 工作流。
- 使用明确的、预设的沙箱和审批设置运行。
基本用法
将任务提示作为单个参数传递:
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
使用 --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 运行器或容器)。
Codex 保留了 codex exec --full-auto 作为已弃用的兼容性标志,并会打印警告。在新脚本中请优先使用显式的 --sandbox workspace-write 标志。
使用 --ignore-user-config 当你需要运行且不加载 $CODEX_HOME/config.toml,且 --ignore-rules 当你需要跳过用户和项目执行策略 (execpolicy) 文件以适应受控自动化环境时。 .rules 如果你使用
配置了已启用的 MCP 服务器但它未能初始化, required = true 将因错误而退出,而不是在没有该服务器的情况下继续运行。 codex exec 使输出可由机器读取
要在脚本中使用 Codex 输出,请使用 JSON Lines 输出:
将变为 JSON Lines (JSONL) 流,以便你可以捕获 Codex 运行时发出的每一个事件。事件类型包括
codex exec --json "summarize the repo structure" | jq
当你通过提供启用 --json, stdout 项类型包括代理消息、推理、命令执行、文件更改、MCP 工具调用、网络搜索和计划更新。 thread.started, turn.started, turn.completed, turn.failed, item.*,且 error.
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 使用 Schema 创建结构化输出 codex exec for details).
如果你需要下游步骤的结构化数据,请使用
来请求符合 JSON Schema 的最终响应。这对于需要稳定字段的自动化工作流非常有用(例如,作业摘要、风险报告或发布元数据)。 --output-schema 使用 schema 运行 Codex 并将最终的 JSON 响应写入磁盘:
schema.json
{
"type": "object",
"properties": {
"project_name": { "type": "string" },
"programming_languages": {
"type": "array",
"items": { "type": "string" }
}
},
"required": ["project_name", "programming_languages"],
"additionalProperties": false
}
最终输出 (stdout) 示例:
codex exec "Extract project metadata" \
--output-schema ./schema.json \
-o ./project-metadata.json
在自动化中进行身份验证
{
"project_name": "Codex CLI",
"programming_languages": ["Rust", "TypeScript", "Shell"]
}
默认复用已保存的 CLI 身份验证。在 CI 中,通常需要显式提供凭据:
codex exec 使用 API 密钥身份验证
对于 GitHub Actions,请使用
而不是自行安装和验证 CLI。该操作旨在通过安装 Codex、启动 Responses API 代理,并使用可配置的安全策略运行 Codex,来减少 API 密钥的暴露。 Codex GitHub Action 请勿将
设置为检出或运行仓库受控代码的工作流中的作业级环境变量。同一作业中的构建脚本、测试、依赖生命周期钩子或受损操作都可以读取这些环境变量。 OPENAI_API_KEY or CODEX_API_KEY 对于其他自动化环境,请仅针对单个
调用设置 CODEX_API_KEY 并确保同一进程环境中不会运行不受信任的代码。 codex exec 要为单次运行使用不同的 API 密钥,请设置
仅在 CODEX_API_KEY inline:
CODEX_API_KEY=<api-key> codex exec --json "triage open bug reports"
CODEX_API_KEY 中受支持 codex exec.
在 CI/CD 中使用 ChatGPT 管理的身份验证(高级)
如果你需要使用 Codex 用户帐户而不是 API 密钥来运行 CI/CD 作业,例如在受信任的运行器上使用 ChatGPT 管理的 Codex 访问权限的企业团队,或者需要使用 ChatGPT/Codex 速率限制而不是 API 密钥使用量的用户,请阅读此部分。
API 密钥是自动化的正确默认选择,因为它们更容易配置和轮换。仅在你明确需要以 Codex 帐户身份运行时才使用此路径。
将 ~/.codex/auth.json 视为密码:它包含访问令牌。请勿提交它、将其粘贴到工单中或在聊天中分享。
请勿将此工作流用于公共或开源仓库。如果 codex login
在运行器上不是一个可选项,请通过安全存储注入 auth.json 在运行器上运行 Codex 以便其就地刷新,并在运行之间持久化更新后的文件。
恢复非交互式会话
如果您需要继续之前的运行(例如,两阶段的流水线),请使用 resume subcommand:
codex exec "review the change for race conditions"
codex exec resume --last "fix the race conditions you found"
您也可以使用以下命令指定特定的会话 ID codex exec resume <SESSION_ID>.
需要 Git 仓库
Codex 要求在 Git 仓库内运行命令,以防止破坏性更改。如果您确定环境是安全的,请使用 codex exec --skip-git-repo-check 来覆盖此检查。
常见自动化模式
示例:在 GitHub Actions 中自动修复 CI 失败
对于 GitHub Actions 工作流,请使用 openai/codex-action 而不是安装 Codex 并将 API 密钥传递给 shell 步骤。该操作会为 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 管道传递
当其他命令为 Codex 生成输入时,请根据指令的来源选择标准输入 (stdin) 模式。如果您已经知道指令并希望将管道输出作为上下文传递,请使用 prompt-plus-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
更多 prompt-plus-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 问题
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 日志起草拉取请求评论
gh run view 123456 --log \
| codex exec "summarize the failure in 5 bullets for the pull request thread" \
| gh pr comment 789 --body-file -使用 codex exec - 当标准输入作为提示词时
如果省略 prompt 参数,Codex 将从标准输入读取提示词。使用 codex exec - 当您希望显式强制执行此行为时。
The - 当其他命令或脚本动态生成整个提示词时,sentinel 非常有用。这非常适合您将提示词存储在文件中、使用 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