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"(aliascodex e) is the non-interactive mode. The default sandbox is read-only;--sandbox workspace-writeallows edits inside the working directory;danger-full-accessbelongs only in isolated environments.--full-autois no longer supported (official docs, Nov 2026). Use--sandbox workspace-write; the official non-interactive page also lists--approve-for-meto route approval requests through automatic review, but the flag is missing from the CLI reference, so checkcodex exec --helpbefore relying on it.--jsonemits JSON Lines events (thread.started,turn.completedwith token usage, and more);-o/--output-last-messagewrites the final answer to a file;--output-schemamakes the final answer match a JSON Schema.- Since 0.169.0,
codex execdoes not load project.codex/config.tomlor project MCP servers in untrusted directories, even with--sandbox workspace-write.--trustsaves 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:
- Pipe-friendly output. Only the final answer reaches stdout, so
| tee,> fileorgh pr comment --body-file -just work. - 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. - 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.
- 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,--sandboxor--add-dirbeforeresume. - Git repo required. This is a guard rail; pass
--skip-git-repo-checkonly 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
/v1or a trailing slash tobase_url; Codex appends/responsesitself. Getting this wrong usually shows up as a 404. wire_api = "responses"is the only value the current docs support.- Point
CODEX_HOMEat a temp directory (for example$RUNNER_TEMP/codexon GitHub Actions) so config and session files never land in the workspace. qcodeis a custom ID. Built-in IDs such asopenai,ollama,lmstudio,amazon-bedrockandgcpare 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.0keeps 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
usageobject inturn.completedhasinput_tokens,cached_input_tokensandoutput_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 includesreasoning_output_tokensinoutput_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_requestruns triggered from forks get no secrets. That is GitHub's design; don't work around it withpull_request_targetplus 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":
- Patch job.
permissions: contents: read, holds the API key, runscodex exec --sandbox workspace-write "run npm test to reproduce the failure and make only the minimal change that fixes it", thengit diff --binary > codex.patchand uploads it as an artifact. - PR job.
contents: writeandpull-requests: write, no API key. It downloads the patch, runsgit apply, pushes a branch and callsgh pr createso 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-solfor 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.
mediumis usually enough for CI review;lowfor labels and summaries. - Shrink the input. Feed the diff and relevant files, not the whole monorepo.
- Time-box and dedupe.
timeout-minutesplusconcurrencywithcancel-in-progress, so repeated pushes to one PR only run once. - Log usage. Keep the
usagedata from--jsonand 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.