Automation & CI · As of 2026-11-25

codex exec in CI: Automating Codex CLI in Scripts and GitHub Actions

As of 2026-11-25, the standard way to run Codex in scripts and CI is codex exec. It skips the interactive UI, runs one task and exits, writing progress to stderr and only the final answer to stdout. By default codex exec runs in a read-only sandbox; add --sandbox workspace-write when the job must edit files, and use --json, -o and --output-schema for machine-readable results. This guide shows a CI setup for a third-party Responses endpoint: reading the key from an environment variable with env_key, a GitHub Actions PR-review workflow, a two-job auto-fix pattern, cost control and one sub-key per pipeline.

QCode is an independent third-party API service and is not affiliated with OpenAI. Every flag and config key below was checked against OpenAI's official Codex docs and changelog on 2026-11-25. Sources: OpenAI Codex docs (Non-interactive mode, Command line options, Agent approvals & security, Authentication), the Codex changelog, the openai/codex-action README and QCode's Codex docs, all read 2026-11-25.

Updated 2026-11-26

Key facts

  • codex exec "task" (alias codex e) is the non-interactive mode. The default sandbox is read-only; --sandbox workspace-write allows edits inside the working directory; danger-full-access belongs only in isolated environments.
  • --full-auto is no longer supported (official docs, Nov 2026). Use --sandbox workspace-write; the official non-interactive page also lists --approve-for-me to route approval requests through automatic review, but the flag is missing from the CLI reference, so check codex exec --help before relying on it.
  • --json emits JSON Lines events (thread.started, turn.completed with token usage, and more); -o / --output-last-message writes the final answer to a file; --output-schema makes the final answer match a JSON Schema.
  • Since 0.169.0, codex exec does not load project .codex/config.toml or project MCP servers in untrusted directories, even with --sandbox workspace-write. --trust saves trust explicitly. A freshly checked-out CI repo is untrusted by default, which is the safe outcome.
  • For a third-party endpoint in CI, set env_key = "QCODE_API_KEY" on the provider and inject the key only into the step that runs Codex, never at job level.
  • Use one sub-key per pipeline: a leak means revoking one key, and spend splits cleanly by pipeline.

Why codex exec for automation

Interactive codex is built for a person at a terminal. In CI, cron jobs and Git hooks nobody can press "approve", so you need a deterministic entry point that finishes and exits. codex exec fits:

  1. Pipe-friendly output. Only the final answer reaches stdout, so | tee, > file or gh pr comment --body-file - just work.
  2. stdin as context. In npm test 2>&1 | codex exec "summarize the failing tests and propose the smallest fix", the piped text is context and the argument is the instruction. codex exec - treats all of stdin as the prompt.
  3. Read-only by default. With no flags, Codex can read files and run commands inside a read-only sandbox, which suits analysis, review and summaries.
  4. Resumable. codex exec resume --last "fix the issues you found" continues the latest session. Since 0.172.0 it restores the saved sandbox permissions, working directory and workspace roots unless you override them with -C, --sandbox or --add-dir before resume.
  5. Git repo required. This is a guard rail; pass --skip-git-repo-check only when you really need to run outside a repository.

Step 1: A provider config for CI

For interactive use, QCode's docs recommend requires_openai_auth = true with the key stored as OPENAI_API_KEY in ~/.codex/auth.json (see Codex CLI third-party API setup). In CI an environment variable is cleaner: name it with env_key on the provider. Pick one method, because with requires_openai_auth = true Codex ignores env_key.

# $CODEX_HOME/config.toml (CI only)
model_provider = "qcode"
model = "gpt-6.2-sol"
model_reasoning_effort = "medium"

[model_providers.qcode]
name = "qcode"
base_url = "https://api.qcode.cc/openai"
wire_api = "responses"
env_key = "QCODE_API_KEY"

Notes:

  • Don't add /v1 or a trailing slash to base_url; Codex appends /responses itself. Getting this wrong usually shows up as a 404.
  • wire_api = "responses" is the only value the current docs support.
  • Point CODEX_HOME at a temp directory (for example $RUNNER_TEMP/codex on GitHub Actions) so config and session files never land in the workspace.
  • qcode is a custom ID. Built-in IDs such as openai, ollama, lmstudio, amazon-bedrock and gcp are reserved.

Choosing an auth method

Method How Best for
env_key variable env_key = "QCODE_API_KEY" on the provider, variable injected at run time Hosted runners, containers, one-off jobs (recommended)
requires_openai_auth = true + auth.json printenv QCODE_API_KEY \| codex login --with-api-key stores the credential Long-lived self-hosted runners; treat auth.json like a password
CODEX_API_KEY CODEX_API_KEY=... codex exec ... Documented for codex exec / codex review; with a custom provider, test it first

OpenAI's docs warn against setting OPENAI_API_KEY or CODEX_API_KEY as job-level variables in workflows that run repository code, because build scripts and dependencies can read them. Apply the same rule to QCODE_API_KEY: set it only on the step that calls Codex. Codex also helps: by default its shell_environment_policy strips variables whose names contain KEY, SECRET or TOKEN from the commands it spawns, so an npm test that Codex runs cannot see the key. Don't turn on ignore_default_excludes for convenience.

Step 2: A GitHub Actions PR-review workflow

This workflow runs when a pull request opens or updates. The review runs in a read-only sandbox, and a second job that holds no API key posts the comment.

name: codex-pr-review

on:
  pull_request:
    types: [opened, synchronize]

concurrency:
  group: codex-review-${{ github.event.pull_request.number }}
  cancel-in-progress: true

jobs:
  review:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v5
        with:
          fetch-depth: 0
          persist-credentials: false

      - uses: actions/setup-node@v4
        with:
          node-version: "22"

      - name: Install Codex CLI
        run: npm install -g @openai/codex@0.172.0

      - name: Write Codex config
        run: |
          mkdir -p "$RUNNER_TEMP/codex"
          cat > "$RUNNER_TEMP/codex/config.toml" <<'EOF'
          model_provider = "qcode"
          model = "gpt-6.2-sol"
          model_reasoning_effort = "medium"

          [model_providers.qcode]
          name = "qcode"
          base_url = "https://api.qcode.cc/openai"
          wire_api = "responses"
          env_key = "QCODE_API_KEY"
          EOF
          echo "CODEX_HOME=$RUNNER_TEMP/codex" >> "$GITHUB_ENV"

      - name: Run Codex review
        env:
          QCODE_API_KEY: ${{ secrets.QCODE_CI_KEY }}
          BASE_SHA: ${{ github.event.pull_request.base.sha }}
        run: |
          git diff "$BASE_SHA"...HEAD > pr.diff
          codex exec \
            --sandbox read-only \
            --ephemeral \
            --json \
            -o review.md \
            "Review the changes in pr.diff. List bugs, security risks and missing tests as at most 15 Markdown bullets." \
            > events.jsonl

      - name: Estimate token cost
        run: |
          jq -s '[.[] | select(.type=="turn.completed") | .usage]
            | {input: (map(.input_tokens) | add),
               cached: (map(.cached_input_tokens) | add),
               output: (map(.output_tokens) | add)}
            | . + {est_usd: (((.input - .cached) * 2 + .cached * 0.10 + .output * 10) / 1000000)}' events.jsonl

      - uses: actions/upload-artifact@v4
        with:
          name: codex-review
          path: review.md

  comment:
    needs: review
    runs-on: ubuntu-latest
    permissions:
      pull-requests: write
    steps:
      - uses: actions/download-artifact@v4
        with:
          name: codex-review

      - name: Post review comment
        env:
          GH_TOKEN: ${{ github.token }}
        run: gh pr comment "${{ github.event.pull_request.number }}" --repo "${{ github.repository }}" --body-file review.md

Details worth noticing:

  • Pinned version. @openai/codex@0.172.0 keeps runs reproducible; check that this version is on npm before pinning it, and upgrade in its own PR.
  • Read-only sandbox. A review only needs to read the diff and the source.
  • --ephemeral. No session files are left on the runner.
  • Cost estimate. The usage object in turn.completed has input_tokens, cached_input_tokens and output_tokens. The script uses GPT-6.2 Sol list prices ($2 input, $0.10 cached input, $10 output per million tokens, per OpenAI on 2026-11-17) and treats the result as an estimate: check whether your Codex version already includes reasoning_output_tokens in output_tokens. QCode bills OpenAI models at the official price ×1.0; your bill and /models are the final word.
  • Fork PRs. In public repos, pull_request runs triggered from forks get no secrets. That is GitHub's design; don't work around it with pull_request_target plus a checkout of untrusted code.

OpenAI also ships openai/codex-action@v1, which has a responses-api-endpoint input to override the Responses URL and hardening options such as safety-strategy (default drop-sudo). Using it with a third-party endpoint is untested; try it in a scratch repo first. Calling the CLI directly, as above, keeps every variable in your hands and ports unchanged to GitLab CI or Jenkins.

Step 3: Auto-fixing CI failures in two jobs

When Codex is allowed to change code, split "make a patch" from "push a PR":

  1. Patch job. permissions: contents: read, holds the API key, runs codex exec --sandbox workspace-write "run npm test to reproduce the failure and make only the minimal change that fixes it", then git diff --binary > codex.patch and uploads it as an artifact.
  2. PR job. contents: write and pull-requests: write, no API key. It downloads the patch, runs git apply, pushes a branch and calls gh pr create so a human reviews before merge.

If repository content tricks the model, the job it runs in can't write to the repo, and the job that can write never sees the model key. Network is off by default in the workspace-write sandbox, so install dependencies before the Codex step rather than opening the sandbox network. See Codex sandbox and approval modes for the details.

Step 4: Structured output for downstream scripts

When a script consumes the result (labels, merge gates), pin the fields with a JSON Schema:

cat > verdict.schema.json <<'EOF'
{
  "type": "object",
  "properties": {
    "risk": { "type": "string", "enum": ["low", "medium", "high"] },
    "blocking_issues": { "type": "array", "items": { "type": "string" } }
  },
  "required": ["risk", "blocking_issues"],
  "additionalProperties": false
}
EOF

codex exec --sandbox read-only \
  --output-schema ./verdict.schema.json \
  -o ./verdict.json \
  "Assess the risk of the changes in pr.diff"

jq -e '.risk != "high"' verdict.json

jq -e exits non-zero when the expression is false, which fails the CI step.

Plain scripts and other CI systems

Outside GitHub the pattern is the same; you only need to set an environment variable:

# Local script or cron: inject the key for this one command
QCODE_API_KEY="$(cat ~/.secrets/qcode-nightly)" \
  codex exec --sandbox read-only --ephemeral \
  "Summarize the last 20 commits as release notes" > notes.md

In GitLab CI, store the key as a masked, protected CI/CD variable, write the same config.toml in the job's script, then run codex exec. For one-off overrides use -c, for example codex exec -c 'model_reasoning_effort="low"' "...". Fixed combinations (review vs fix) are better as profile files; see Codex config.toml deep dive: profiles, MCP and reasoning effort.

Cost-control checklist

Codex CLI has no built-in "max spend per run" switch, so combine these:

  • Pick the right model. gpt-6.2-sol for reviews and summaries; gpt-6.2-astra (list price $8 / $40 per million tokens, about 4× Sol) only for hard multi-step work.
  • Lower reasoning effort. medium is usually enough for CI review; low for labels and summaries.
  • Shrink the input. Feed the diff and relevant files, not the whole monorepo.
  • Time-box and dedupe. timeout-minutes plus concurrency with cancel-in-progress, so repeated pushes to one PR only run once.
  • Log usage. Keep the usage data from --json and aggregate it per pipeline so anomalies stand out.
  • Cap with quota. Give CI sub-keys their own low quota, so a looping script has a bounded cost.

One sub-key per pipeline

Copying one personal key into every repository is the most common CI risk: one leak forces a rotation everywhere, and nobody can tell which pipeline spent what. Instead:

  • Give review, auto-fix and nightly-report pipelines their own sub-keys, and name secrets by purpose, such as QCODE_CI_REVIEW_KEY.
  • Set a quota on each sub-key and check usage weekly.
  • When someone leaves or a repo goes public, revoke only the affected sub-keys.
  • Watch parallelism: wide matrix jobs are better spread across separate sub-keys or the Team Edition.

FAQ

Do codex exec and interactive codex share the same config?

Yes. Both read $CODEX_HOME/config.toml (default ~/.codex). In CI, point CODEX_HOME at a temp directory with a dedicated config. To skip user config entirely use --ignore-user-config, which cannot be combined with --trust.

Why can't codex exec edit files in my CI job?

codex exec defaults to a read-only sandbox. Add --sandbox workspace-write to allow writes in the working directory. --full-auto is no longer supported, so drop it from old scripts.

Should CI use env_key or requires_openai_auth?

Use env_key = "QCODE_API_KEY" and let the runner inject the variable; no auth.json needed. Don't configure both: with requires_openai_auth = true, Codex ignores env_key.

What does --json output contain?

A JSON Lines event stream: thread.started, turn.started, item.* (command runs, file changes, MCP calls and more), turn.completed with token usage, turn.failed and error. Write the final answer to a file separately with -o.

Why are the repo's .codex/config.toml and MCP servers ignored in CI?

Since 0.169.0, codex exec skips project config and project MCP servers in untrusted directories. Use --trust only when you fully control the repository content, because project MCP servers can run commands outside the sandbox.

Why didn't the review run on a fork's pull request?

Workflows triggered from forks in public repos receive no secrets, so there is no key. That is by design. Have a maintainer trigger reviews of outside contributions from a trusted branch.

How do I stop one run from burning the quota?

Combine a cheaper model, lower reasoning effort, timeout-minutes, concurrency and a dedicated low-quota sub-key, and record token usage for every run.

Next step: team sub-keys for CI

If several repositories and pipelines run Codex, QCode's Team Edition is built for that: each unit provides a $4,000 pooled monthly quota (monthly reset, no daily cap), 35 concurrent requests and sub-keys for members, and it is sized for 3–5 people. See /enterprise. To try things out first, personal plans on /pricing start from $9.

Next step: team sub-keys for CI

One key for both the Anthropic Messages API and OpenAI-compatible APIs. Claude and GPT are billed at the official price ×1.0; live rates are on /models.

Not sure where to start?

Try it for a week

Small Pack: $4 for $30 of quota, valid 7 days

Use it every day

Starter: $9.00/month with $5 of quota every day — just $0.060 per $1 of quota, vs about $0.113 for the Medium Pack