logo

비대화형 모드

비대화형 모드를 사용하면 대화형 TUI를 열지 않고 스크립트에서 Codex를 실행할 수 있습니다. 예를 들어 continuous integration(CI) job에서 사용할 수 있습니다. 실행 명령은 codex exec입니다.

codex exec를 사용할 때

Codex가 다음을 하길 원할 때 codex exec를 사용합니다.

  • pipeline의 일부로 실행합니다. 예: CI, pre-merge check, scheduled job.
  • 다른 도구로 pipe할 수 있는 출력을 만듭니다. 예: release note 또는 summary 생성.
  • 명령 출력이 Codex로 들어가고 Codex 출력이 다른 도구로 전달되는 CLI workflow에 자연스럽게 맞춥니다.
  • 명시적으로 미리 설정된 sandbox와 approval 설정으로 실행합니다.

기본 사용법

작업 프롬프트를 단일 인수로 전달합니다.

codex exec "summarize the repository structure and list the top 5 risky areas"

codex exec가 실행되는 동안 Codex는 진행 상황을 stderr로 stream하고 최종 agent message만 stdout에 출력합니다. 따라서 최종 결과를 쉽게 redirect하거나 pipe할 수 있습니다.

codex exec "generate release notes for the last 10 commits" | tee release-notes.md

session rollout file을 디스크에 유지하고 싶지 않다면 --ephemeral을 사용합니다.

codex exec --ephemeral "triage this repository and suggest next steps"

stdin이 pipe되어 있고 prompt argument도 제공하면 Codex는 prompt를 지시로, pipe된 content를 추가 컨텍스트로 취급합니다.

하나의 명령으로 입력을 만들고 바로 Codex에 넘기기 쉽습니다.

curl -s https://jsonplaceholder.typicode.com/comments \
  | codex exec "format the top 20 items into a markdown table" \
  > table.md

더 고급 stdin piping pattern은 고급 stdin piping을 참고하십시오.

권한과 안전

기본적으로 codex exec는 read-only sandbox에서 실행됩니다. 자동화에서는 workflow에 필요한 최소 권한을 설정합니다.

  • 편집 허용: codex exec --sandbox workspace-write "{task}"
  • 더 넓은 접근 허용: codex exec --sandbox danger-full-access "{task}"

danger-full-access는 isolated CI runner 또는 container처럼 제어된 환경에서만 사용합니다.

Codex는 deprecated compatibility flag로 codex exec --full-auto를 유지하고 warning을 출력합니다. 새 스크립트에서는 명시적인 --sandbox workspace-write flag를 선호하십시오.

$CODEX_HOME/config.toml을 로드하지 않는 실행이 필요하면 --ignore-user-config를 사용하고, 제어된 자동화 환경에서 사용자 및 프로젝트 execpolicy .rules 파일을 건너뛰려면 --ignore-rules를 사용합니다.

활성화된 MCP 서버를 required = true로 구성했는데 초기화에 실패하면 codex exec는 해당 서버 없이 계속하는 대신 오류로 종료합니다.

machine-readable 출력 만들기

스크립트에서 Codex 출력을 소비하려면 JSON Lines 출력을 사용합니다.

codex exec --json "summarize the repo structure" | jq

--json을 활성화하면 stdout이 JSON Lines(JSONL) stream이 되므로 Codex가 실행 중 내보내는 모든 event를 캡처할 수 있습니다. event type에는 thread.started, turn.started, turn.completed, turn.failed, item.*, error가 포함됩니다.

item type에는 agent message, reasoning, command execution, file change, MCP tool call, web search, plan update가 포함됩니다.

JSON stream 예시는 다음과 같습니다. 각 줄은 JSON object입니다.

{"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로 구조화된 출력 만들기

downstream step에 구조화된 데이터가 필요하면 --output-schema를 사용해 JSON Schema를 따르는 최종 응답을 요청합니다. job summary, risk report, release metadata처럼 안정적인 field가 필요한 자동 workflow에 유용합니다.

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에서는 credential을 명시적으로 제공하는 경우가 많습니다.

API 키 인증 사용(권장)

  • job의 secret environment variable로 CODEX_API_KEY를 설정합니다.
  • 프롬프트와 도구 출력에는 민감한 코드나 데이터가 포함될 수 있음을 고려합니다.

한 번의 실행에 다른 API 키를 사용하려면 CODEX_API_KEY를 inline으로 설정합니다.

CODEX_API_KEY={api-key} codex exec --json "triage open bug reports"

CODEX_API_KEYcodex exec에서만 지원됩니다.

CI/CD에서 ChatGPT 관리 인증 사용(고급)

API 키 대신 Codex 사용자 계정으로 CI/CD job을 실행해야 할 때만 이 경로를 사용합니다. 예를 들어 신뢰된 runner에서 ChatGPT 관리 Codex 접근을 사용하는 enterprise team이나 API 키 사용량 대신 ChatGPT/Codex rate limit이 필요한 사용자가 해당됩니다.

자동화에는 API 키가 더 간단하게 provision하고 rotate할 수 있으므로 기본 권장입니다. 특별히 Codex 계정으로 실행해야 할 때만 이 방식을 사용하십시오.

~/.codex/auth.json은 비밀번호처럼 취급하십시오. access token이 포함되어 있습니다. commit하거나 ticket에 붙여 넣거나 chat에서 공유하지 마십시오.

공개 또는 오픈 소스 저장소에는 이 workflow를 사용하지 마십시오. runner에서 codex login을 사용할 수 없다면 secure storage로 auth.json을 seed하고, runner에서 Codex를 실행해 Codex가 그 파일을 제자리에서 refresh하게 한 뒤, 업데이트된 파일을 실행 사이에 유지합니다.

비대화형 세션 재개

이전 실행을 이어가야 한다면, 예를 들어 two-stage pipeline, resume subcommand를 사용합니다.

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로 이 검사를 override합니다.

일반적인 자동화 pattern

예시: GitHub Actions에서 CI 실패 자동 수정

codex exec로 CI workflow가 실패했을 때 자동으로 수정안을 제안할 수 있습니다. 일반적인 pattern은 다음과 같습니다.

  1. main CI workflow가 오류로 완료되면 follow-up workflow를 trigger합니다.
  2. 실패한 commit SHA를 checkout합니다.
  3. 의존성을 설치하고 좁은 프롬프트와 최소 권한으로 Codex를 실행합니다.
  4. 테스트 명령을 다시 실행합니다.
  5. 결과 patch로 pull request를 엽니다.

Codex CLI를 사용하는 최소 workflow

아래 예시는 핵심 단계를 보여 줍니다. install과 test 명령은 사용 중인 stack에 맞게 조정합니다.

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 piping

다른 명령이 Codex 입력을 생성할 때는 지시가 어디서 와야 하는지에 따라 stdin pattern을 선택합니다. 지시를 이미 알고 있고 pipe된 출력을 컨텍스트로 넘기려면 prompt-plus-stdin을 사용합니다. stdin 자체가 전체 prompt가 되어야 하면 codex exec -를 사용합니다.

prompt-plus-stdin 사용

prompt-plus-stdin은 다른 명령이 Codex가 검사할 데이터를 이미 생성할 때 유용합니다. 이 모드에서는 지시를 직접 작성하고 출력은 컨텍스트로 pipe합니다. 명령 출력, 로그, 생성 데이터 중심의 CLI workflow에 자연스럽게 맞습니다.

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
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
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
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이 prompt일 때 codex exec - 사용

prompt argument를 생략하면 Codex는 stdin에서 prompt를 읽습니다. 이 동작을 명시적으로 강제하려면 codex exec -를 사용합니다.

- sentinel은 다른 명령이나 스크립트가 전체 prompt를 동적으로 생성할 때 유용합니다. 파일에 prompt를 저장하거나, shell script로 prompt를 조립하거나, live command output을 지시와 결합한 뒤 전체 prompt를 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
Previous
Windows