繁體中文

非互動模式

非互動模式

使用 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.startedturn.startedturn.completedturn.faileditem.*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 中,通常會明確提供憑據:

如果你信任的雲端或 CI 執行時已經獲得短期工作負載 令牌,請使用工作負載身份聯合, 而不是儲存 OpenAI 憑據。

使用 API key 身份驗證

對於 GitHub Actions,請使用 Codex GitHub Action,而不是自行安裝 CLI 並進行身份驗證。該 action 會安裝 Codex、啟動 Responses API 代理,並使用可設定的安全策略執行 Codex,從而減少 API key 暴露。

在會檢出或執行儲存庫所控制程式碼的工作流程中,請勿將 OPENAI_API_KEYCODEX_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_KEYcodex execcodex review、TypeScript SDK 和 codex exec-server --remote 配合使用。

如果你需要使用 Codex 使用者帳戶而非 API key 執行 CI/CD 作業,請閱讀本節。例如,企業團隊可能會在受信任的 執行器上使用 ChatGPT 託管的 Codex 存取權限,或者使用者需要使用 ChatGPT/Codex 速率限制而非 API key 用量。

API key 是自動化場景的合理預設選擇,因為其設定和輪換 更簡單。僅當你明確需要以自己的 Codex 帳戶 身份執行時,才使用此方式。

請勿對公共或開源儲存庫使用此工作流程。如果執行器上無法使用 codex login, 請通過安全儲存植入 auth.json,在執行器上執行 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 失敗

對於 GitHub Actions 工作流程,請使用 openai/codex-action,而不是安裝 Codex 並將 API key 傳遞給 shell 步驟。該 action 會為 OpenAI API key 啟動安全代理。

當 CI 工作流程失敗時,你可以使用 Codex 自動提出修復方案。該模式如下:

  1. 主 CI 工作流程以錯誤結束時,觸發後續工作流程。
  2. 僅使用儲存庫讀取權限檢出失敗的提交。
  3. 在執行 Codex 之前執行設定命令,且不向這些步驟暴露 OpenAI API key。
  4. 執行 Codex GitHub Action。
  5. 將 Codex 的本機變更儲存為補丁構件。
  6. 在單獨的作業中應用補丁並建立拉取請求。

下面的 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