非互動模式
用 codex exec 在指令碼、CI 和自動化流水線中執行 Codex
非互動模式允許你在腳本里直接呼叫 Codex,例如 CI 任務,而不必開啟互動式 TUI。入口命令是 codex exec。
如果你需要檢視更細的 flag 說明,請參閱 codex exec。
何時使用 codex exec
當你希望 Codex:
- 作為流水線的一部分執行,例如 CI、預合併檢查或定時任務
- 輸出可繼續傳給其他工具處理的結果,例如 release notes 或摘要
- 自然嵌入 CLI 工作流程,把命令輸出傳給 Codex,再把 Codex 輸出交給其他命令
- 在一開始就顯式固定沙箱和審批設定
就適合使用 codex exec。
基本用法
最簡單的方式是把任務提示詞作為單個參數傳入:
codex exec "summarize the repository structure and list the top 5 risky areas"執行期間,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 會把命令列提示詞當作指令,把 stdin 內容當作額外上下文。
這很適合“一個命令生成資料,直接交給 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 作為已棄用的相容 flag,並會列印警告。新指令碼請優先使用顯式的 --sandbox workspace-write flag。
如果需要一次不載入 $CODEX_HOME/config.toml 的執行,請使用 --ignore-user-config;如果需要在受控自動化環境中跳過使用者和專案 execpolicy .rules 檔案,請使用 --ignore-rules。
如果你把某個 MCP server 設定成 required = true,並且它初始化失敗,codex exec 會直接報錯退出,而不會在缺少這個 MCP server 的情況下繼續執行。
讓輸出可供機器讀取
如果你要在腳本里消費 Codex 輸出,推薦啟用 JSON Lines:
codex exec --json "summarize the repo structure" | jq啟用 --json 後,stdout 會變成 JSONL 事件流,因此你可以捕獲 Codex 執行期間發出的每個事件。常見事件類型包括 thread.started、turn.started、turn.completed、turn.failed、item.* 和 error。
常見內容項(item)類型包括智能體訊息、推理、命令執行、檔案改動、MCP 工具呼叫、網頁搜尋和計劃更新。
範例 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,"reasoning_output_tokens":0}}如果你只需要最終訊息,可以使用 -o <path> / --output-last-message <path> 把它寫入檔案。Codex 會把最終訊息寫入檔案,同時仍然列印到 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
}執行方式:
codex exec "Extract project metadata" \
--output-schema ./schema.json \
-o ./project-metadata.json最終輸出範例:
{
"project_name": "Codex CLI",
"programming_languages": ["Rust", "TypeScript", "Shell"]
}在自動化中認證
預設情況下,codex exec 會複用 CLI 已儲存的認證狀態。在自動化中,更常見的做法是顯式提供憑據。
使用 API key 認證
對於 GitHub Actions,請優先使用 Codex GitHub Action,而不是自行安裝並認證 CLI。該 action 會安裝 Codex、啟動 Responses API 代理,並用可設定的安全策略執行 Codex,從而減少 API key 暴露面。
不要在會檢出或執行儲存庫受控程式碼的工作流程中,把 OPENAI_API_KEY 或 CODEX_API_KEY 設定為 job 級環境變數。同一個 job 裡的建置指令碼、測試、依賴生命週期 hooks,或被攻陷的 action 都可能讀取這些環境變數。
在其他自動化環境中,只把 CODEX_API_KEY 設定給單次 codex exec 呼叫,並確保同一個程序環境中不會執行不受信任的程式碼。
CODEX_API_KEY=<api-key> codex exec --json "triage open bug reports"CODEX_API_KEY 只在 codex exec 中受支援。
在 CI/CD 中使用 ChatGPT 管理的認證(高階)
如果你需要在 CI/CD 作業中使用 Codex 使用者賬號而不是 API key 來執行,請閱讀本節。例如,企業團隊在受信任的 runner 上使用由 ChatGPT 管理的 Codex 存取,或需要使用 ChatGPT / Codex 的速率限制而不是 API key 配額的使用者,都適合這種方式。
API key 仍然是自動化場景的預設首選,因為它更容易發放和輪換。只有在你明確需要以自己的 Codex 賬號身份執行時,才應選擇這條路徑。
不要在公開儲存庫或開源儲存庫中使用這套流程。如果 runner 上無法執行 codex login,應通過安全儲存預先注入 auth.json,再在 runner 上執行 Codex,讓 Codex 就地重新整理該檔案,並在多次執行之間持久化更新後的檔案。
恢復非互動會話
如果你要在一個多階段流水線中繼續上一次執行,可以使用 resume 子命令:
codex exec "review the change for race conditions"
codex exec resume --last "fix the race conditions you found"你也可以直接指定某個 session 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 key 傳給 shell step。該 action 會為 OpenAI API key 啟動安全代理。
你可以用 Codex 在 CI 失敗後自動提出修復建議。一個典型模式如下:
- 在主 CI 工作流程失敗後觸發後續工作流程。
- 以只讀儲存庫權限檢出失敗的 commit。
- 在執行 Codex 之前執行 setup 命令,不把 OpenAI API key 暴露給這些步驟。
- 執行 Codex GitHub Action。
- 把 Codex 的本機改動儲存為 patch 產物。
- 在另一個 job 中應用 patch 並建立 PR。
Codex job 只有 contents: read 權限。Codex 執行結束後,它只把 diff 序列化為產物。open_pr job 擁有儲存庫寫權限,但不會收到 OPENAI_API_KEY。
下面的範例假定是 Node.js 專案。請按你的技術棧調整 setup 和 test 命令。
更深入的安全檢查清單見 Codex GitHub Action security guidance。
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 模式。如果你已經知道指令,只是想把命令輸出作為上下文傳給 Codex,就用“提示詞 + stdin”;如果 stdin 本身就是完整提示詞,就用 codex exec -。
使用提示詞 + stdin
這種模式適合上游命令已經生成了你想讓 Codex 檢查的資料,而你只需自己補充解釋任務目標:
npm test 2>&1 \
| codex exec "summarize the failing tests and propose the smallest likely fix" \
| tee test-summary.md更多提示詞 + 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 日誌起草 PR 評論
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來源:</zh-TW/docs/non-interactive-mode> 更新時間:2026-05-01(UTC)