非交互模式
非交互模式
使用 codex exec 在脚本和 CI 中运行 Codex
非交互模式让你无需打开交互式 TUI,即可从脚本(例如持续集成 (CI) 作业)运行 Codex。
可通过 codex exec 调用该模式。
有关各标志的详细信息,请参阅 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,并仅将智能体的最终消息打印到 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>"
请仅在受控环境中(例如隔离的 CI 运行器或容器)使用 danger-full-access。
Codex 保留 codex exec --full-auto 作为已弃用的兼容性标志,并会打印警告。在新脚本中,请优先使用明确的 --sandbox workspace-write 标志。
如果需要运行时不加载 $CODEX_HOME/config.toml,请使用 --ignore-user-config;如果需要在受控自动化环境中跳过用户和项目的 execpolicy .rules 文件,请使用 --ignore-rules。
如果你使用 required = true 配置了已启用的 MCP 服务器,而该服务器初始化失败,codex exec 将报错退出,而不会在缺少该服务器的情况下继续运行。
让输出可供机器读取
如需在脚本中使用 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)。
使用 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"]
}在自动化环境中进行身份验证
默认情况下,codex exec 会复用已保存的 CLI 身份验证。在 CI 中,通常会明确提供凭据:
使用 API key 身份验证
对于 GitHub Actions,请使用 Codex GitHub Action,而不是自行安装 CLI 并进行身份验证。该 action 会安装 Codex、启动 Responses API 代理,并使用可配置的安全策略运行 Codex,从而减少 API key 暴露。
在会检出或运行仓库所控制代码的工作流中,请勿将 OPENAI_API_KEY 或 CODEX_API_KEY 设置为作业级环境变量。同一作业中的构建脚本、测试、依赖项生命周期钩子或遭到入侵的 action 都可以读取这些环境变量。
对于其他自动化环境,请仅为需要凭据的 Codex
调用设置 CODEX_API_KEY,并确保同一
进程环境中不运行任何不受信任的代码。
如需在单次运行中使用其他 API key,请以内联方式设置 CODEX_API_KEY:
CODEX_API_KEY=<api-key> codex exec --json "triage open bug reports"你可以将 CODEX_API_KEY 与 codex exec、codex review、TypeScript
SDK 和 codex exec-server --remote 配合使用。
API key 是自动化场景的合理默认选择,因为其配置和轮换 更简单。仅当你明确需要以自己的 Codex 账户 身份运行时,才使用此方式。
请勿对公共或开源仓库使用此工作流。如果运行器上无法使用 codex login,
请通过安全存储植入 auth.json,在运行器上运行
Codex 以便 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 失败
对于 GitHub Actions 工作流,请使用 openai/codex-action,而不是安装 Codex 并将 API key 传递给 shell 步骤。该 action 会为 OpenAI API key 启动安全代理。
当 CI 工作流失败时,你可以使用 Codex 自动提出修复方案。该模式如下:
- 主 CI 工作流以错误结束时,触发后续工作流。
- 仅使用仓库读取权限检出失败的提交。
- 在运行 Codex 之前执行设置命令,且不向这些步骤暴露 OpenAI API key。
- 运行 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 模式。如果你已经知道指令,并希望将管道输出作为上下文传入,请使用提示加 stdin 模式。如果希望 stdin 成为完整提示,请使用 codex exec -。
使用提示加 stdin
当另一个命令已经生成了希望 Codex 检查的数据时,提示加 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 日志起草拉取请求评论
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