You want Codex to work in a CI step, with nobody in front of the screen, and you do not want to hand that step either your API key or write permissions on the repository. The documentation, opened on 13 November 2026, provides the ingredients. codex exec runs Codex without an interface: it prints progress on stderr and only the final message on stdout, so you can put it in a pipe or in a file. By default it runs in a read-only sandbox, and to let it modify files you need an explicit --sandbox workspace-write. In CI the API key goes to the single command with CODEX_API_KEY, never as a variable of the whole job when the job runs code from the repository. To drive the agent from an existing program there are a TypeScript SDK (@openai/codex-sdk) and a Python one (openai-codex).
The rule that holds everything together is only one: the step that launches the agent must not have write permissions on the repository, and the one that has them must not see the key. Part six of the OpenAI Codex series; it helps to have read part 3 on sandbox and approvals. I have not run Codex, its GitHub Action or the SDK: the scripts run without an agent, on test files, and the blocks that require the tool say so. I am not affiliated with OpenAI.
What codex exec does
The commands below are those of the "Non-interactive mode" page, gathered in one block, and they have not been run: they need Codex installed and an account. The first is the basic case; the second uses --output-schema and -o; the third takes standard input as context, the fourth as the whole prompt with the dash -; the last one resumes with resume the most recent session of the current folder (--last). The prompts and the first comment are in Italian, exactly as in the Italian edition of this article, because the block is a pattern to adapt and is not run.
# schema da adattare, non eseguito: richiede Codex installato e autenticato
codex exec "riassumi la struttura del repository ed elenca le 5 aree più rischiose"
# con schema di risposta: il prompt è obbligatorio e l'ultimo messaggio finisce in un file
codex exec "Estrai i metadati del progetto" \
--output-schema ./schema.json \
-o ./project-metadata.json
# il prompt è l'istruzione, lo standard input è il contesto
npm test 2>&1 | codex exec "riassumi i test che falliscono" | tee riassunto-test.md
# il prompt intero arriva dallo standard input
cat prompt.txt | codex exec -
# riprendere un lavoro precedente
codex exec "controlla se ci sono race condition"
codex exec resume --last "correggi le race condition che hai trovato"
A detail that the commands documentation puts in black and white: with --output-schema, --output-last-message, --ephemeral or with images, the prompt is mandatory. If you pass a prompt as an argument and something on stdin, the argument is the instruction and stdin is context; if you omit the argument, Codex reads the prompt from stdin. The options that matter for a pipeline are these:
--json: stdout becomes a JSON Lines stream of events (thread.started,turn.started,item.*,turn.completed,turn.failed,error).-o <path>or--output-last-message <path>: writes only the final message to a file and prints it anyway.--output-schema <file>: forces the final answer into a JSON schema, and turns the agent from "writes prose" into "produces data a script can count on".--ephemeral: does not save session files to disk.--skip-git-repo-check: overrides the requirement to run inside a Git repository, which Codex imposes to avoid destructive changes.--ignore-user-configand--ignore-rules: ignore your$CODEX_HOME/config.tomland the.rulesrule files.-m(or--model): chooses the model for this run, as seen in part 5.
The two options in the second-to-last item deserve a comment, because they are the ones that change behavior without the command saying so. In CI you want reproducible behavior, and --ignore-user-config removes the variable of a config.toml inherited from the runner. --ignore-rules instead skips the user and project execution rules: the documentation mentions it for a controlled automation environment, and in my view (this is my own judgment, not the source's) in a workflow that touches other people's code it is rarely what you want, because it removes a check. If an MCP server is configured with required = true and fails to initialize, codex exec exits with an error instead of carrying on: it is the right behavior for a step that must not silently produce an incomplete result.
Reading the JSON stream and deciding the outcome
With --json every line of stdout is an event. The script below is the minimal reader you would put after codex exec --json: it takes the agent's last message, the tokens of the last turn, the files touched by the file_change items and the number of commands that ended with a code other than 0, and it returns exit 1 if turn.failed or error appears. It uses only the fields that the TypeScript SDK code, in the public Codex repository, declares for those events.
The first test file, ok.jsonl, is the stream example from the documentation, copied as it is. The second, fallito.jsonl, I built myself following the types in the SDK code: a failing test, two touched files, an optimistic final message and a turn.failed for a usage limit. They are not Codex outputs.
# Reads the JSON Lines stream of `codex exec --json` and decides the outcome of the CI step.
# It uses only the "type" field and the fields the TypeScript SDK code declares.
import json
import sys
def read_stream(path):
final, usage, touched_files, failed_commands, error = None, None, [], 0, None
with open(path, encoding="utf-8") as f:
for line in f:
if not line.strip():
continue
ev = json.loads(line)
kind = ev["type"]
if kind == "item.completed":
item = ev["item"]
if item["type"] == "agent_message":
final = item["text"] # the last message wins
elif item["type"] == "file_change":
touched_files += [c["path"] for c in item["changes"]]
elif item["type"] == "command_execution" and item.get("exit_code", 0) != 0:
failed_commands += 1
elif kind == "turn.completed":
usage = ev["usage"]
elif kind == "turn.failed":
error = ev["error"]["message"]
elif kind == "error":
error = ev["message"]
return final, usage, touched_files, failed_commands, error
outcome = 0
for path in sys.argv[1:]:
final, usage, touched, failed, error = read_stream(path)
print(f"== {path}")
print("final message:", final)
print("tokens (input, cached, output):",
None if usage is None else (usage["input_tokens"], usage["cached_input_tokens"], usage["output_tokens"]))
print("files touched:", touched)
print("commands with non-zero exit:", failed)
if error:
print("ERROR:", error)
outcome = 1
print("exit code:", outcome)
sys.exit(outcome)
# Output:
# == ok.jsonl
# final message: Repo contains docs, sdk, and examples directories.
# tokens (input, cached, output): (24763, 24448, 122)
# files touched: []
# commands with non-zero exit: 0
# == fallito.jsonl
# final message: I fixed the rounding, but one test is still red.
# tokens (input, cached, output): None
# files touched: ['src/discount.js', 'test/discount.test.js']
# commands with non-zero exit: 1
# ERROR: usage limit reached
# exit code: 1
In the second stream the final message says "one test is still red" but the tokens are missing, because the turn never reached turn.completed: a clear sign that the answer must not be treated as complete. The line final = item["text"] overwrites at every message, so the last one wins, as the run() method of the TypeScript SDK does, which in addition raises an error when it sees turn.failed.
The response schema, checked twice
When you use --output-schema, the file schema.json is the one from the documentation example: an object with project_name (string) and programming_languages (list of strings), both required, and additionalProperties: false, which forbids extra fields. The source says the schema serves to obtain a conforming final answer; I propose to verify it anyway before consuming it, because the next step trusts those fields. The script uses the jsonschema library (test dependency, version 4.26.0, installed in a virtual environment) and tries four messages: one conforming and three wrong in different ways.
# Checks that the final message of a CI step respects the schema passed to
# --output-schema, BEFORE feeding it to the next step.
# Test dependency: jsonschema (pip install jsonschema).
import json
from jsonschema import Draft202012Validator
with open("schema.json", encoding="utf-8") as f:
validator = Draft202012Validator(json.load(f))
candidates = {
"conforming": '{"project_name": "demo", "programming_languages": ["Python", "Shell"]}',
"extra field": '{"project_name": "demo", "programming_languages": [], "license": "MIT"}',
"missing field": '{"project_name": "demo"}',
"free text": "The project is called demo.",
}
for name, text in candidates.items():
try:
data = json.loads(text)
except json.JSONDecodeError as e:
print(f"{name}: NOT JSON ({e.msg})")
continue
errors = sorted(e.message for e in validator.iter_errors(data))
print(f"{name}: {'ok' if not errors else '; '.join(errors)}")
# Output:
# conforming: ok
# extra field: Additional properties are not allowed ('license' was unexpected)
# missing field: 'programming_languages' is a required property
# free text: NOT JSON (Expecting value)
The three error lines correspond to three different failures a CI step must be able to deal with: a field the schema does not provide for, a required field that is missing, a text that is not even JSON. In all three cases the step must fail with an understandable message and not pass the value downstream. The check does not replace the schema passed to Codex: it is its safety belt.
Permissions: the default is cautious, and it must stay so
As seen in part 3, codex exec starts in a read-only sandbox. To write: codex exec --sandbox workspace-write "<task>". For broader access: --sandbox danger-full-access, but only in a controlled environment, such as an isolated CI runner or a container. The --full-auto option is no longer supported: the source indicates --sandbox workspace-write or --approve-for-me, which routes approval requests to automatic review with the workspace-write sandbox. Choose the level per task, not per repository: a job that comments on a pull request and a job that fixes the code need different permissions, and the first works read-only.
Credentials in CI: where the real mistakes happen
The page is explicit on three things, and the action's security guide adds the details:
- By default
codex execreuses the saved authentication of the CLI. For a single run you set the key inline:CODEX_API_KEY=<key> codex exec --json "triage the open reports". - Do not set
OPENAI_API_KEYorCODEX_API_KEYas a job-level environment variable in workflows that run code controlled by the repository: build scripts, tests, dependency hooks or a compromised action in the same job can read it. - ChatGPT-managed authentication in CI is an advanced option: treat
~/.codex/auth.jsonlike a password and do not use this route for public or open-source repositories. API keys are the recommended default.
The common thread is that a credential in a shared environment is a target: everything running in the job can read it. For GitHub Actions the documentation recommends using the Codex GitHub Action (openai/codex-action@v1, Apache-2.0 license) instead of installing the CLI and passing the key to a shell step. The action installs the CLI, starts a proxy toward the Responses API to which it entrusts the key (you pass it with the openai-api-key input, from the repository secrets) and launches Codex with a configurable safety strategy. By default only people with write access to the repository can start it, and safety-strategy is drop-sudo: it revokes the sudo of the runner user before launching Codex. The reason, written in the security guide, is counterintuitive: a read-only filesystem with passwordless sudo (the default on GitHub-hosted runners) can expose the key, because Linux makes a lot of process information readable through procfs.
What the agent can read, and who can start it
The same guide lists the sources through which hostile text reaches the model (prompt injection): the body of a pull request, where an HTML comment is visible to the model and almost invisible to a human reader; commit messages; the repository instruction files such as AGENTS.md when they come from the pull request; screenshots. If the workflow runs on the content of external pull requests, that content is untrusted input. The guide also warns that with allow-users: "*" anyone can consume the quota of your key.
The two-job pattern, checked by a script
The page's example separates responsibilities into two jobs, and it is the part to imitate. The generate_fix job has only contents: read, runs Codex through the action and saves the output of git diff as an artifact, a patch; the open_pr job has the write permissions, downloads the patch, applies it, pushes a branch and opens a pull request, and does not receive the key. Below is a reduced version of the documentation example (shortened prompt, pull request opening cut): it has not been run on GitHub, it is a pattern to adapt, and its shape is checked by a script of mine.
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
steps:
- uses: actions/checkout@v5
with:
ref: ${{ github.event.workflow_run.head_sha }}
persist-credentials: false
- name: Run Codex
uses: openai/codex-action@v1
with:
openai-api-key: ${{ secrets.OPENAI_API_KEY }}
permission-profile: ":workspace"
prompt: |
Reproduce the CI failure and propose the smallest change.
- name: Create patch artifact
run: git diff --binary HEAD > codex.patch
- uses: actions/upload-artifact@v4
with:
name: codex-fix-patch
path: codex.patch
open_pr:
needs: generate_fix
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- uses: actions/checkout@v5
- uses: actions/download-artifact@v4
with:
name: codex-fix-patch
- run: git apply --index codex.patch
The lines that carry the weight are four: permissions: contents: read in the agent's job, openai-api-key passed in the with section of the action's step only, persist-credentials: false in the checkout, which prevents actions/checkout from configuring the token for the following git commands (by default it does, according to that action's documentation), and the open_pr job that writes but never names the secret. The check that follows reads the file with PyYAML (test dependency, version 6.0.3) and compares it with those rules, plus another one that the security guide asks for: openai/codex-action should be the last step of the job. I also gave it a deliberately wrong workflow.
# Checks the privilege separation described in the documentation:
# the job that launches the agent only reads, and the key appears only there.
# Test dependency: PyYAML (pip install pyyaml).
import sys
import yaml
KEYS = ("OPENAI_API_KEY", "CODEX_API_KEY")
def uses_action(step):
return str(step.get("uses", "")).startswith("openai/codex-action@")
def check(path):
with open(path, encoding="utf-8") as f:
wf = yaml.safe_load(f)
errors, warnings = [], []
if any(k in str(wf.get("env", "")) for k in KEYS):
errors.append("key in env at workflow level")
for name, job in wf["jobs"].items():
steps = job.get("steps", [])
if any(k in str(job.get("env", "")) for k in KEYS):
errors.append(f"{name}: key in env at job level")
indexes = [i for i, s in enumerate(steps) if uses_action(s)]
if indexes: # job that runs the agent
if job.get("permissions") != {"contents": "read"}:
errors.append(f"{name}: permissions {job.get('permissions')}, only contents: read is needed")
after = len(steps) - 1 - indexes[-1]
if after:
warnings.append(f"{name}: steps after the agent: {after} (the action's security guide wants it last)")
else: # all the other jobs
if "secrets." in str(job):
errors.append(f"{name}: uses a secret but does not launch the agent")
for s in steps:
if "github.event." in str(s.get("run", "")):
errors.append(f"{name}: github.event expression inside run:, pass it with env:")
return errors, warnings
outcome = 0
for path in sys.argv[1:]:
errors, warnings = check(path)
print(f"== {path}: {'ERRORS' if errors else 'ok'}")
for e in errors:
print(" error:", e)
for w in warnings:
print(" warning:", w)
outcome = outcome or int(bool(errors))
sys.exit(outcome)
# Output:
# == buono.yml: ok
# warning: generate_fix: steps after the agent: 2 (the action's security guide wants it last)
# == cattivo.yml: ERRORS
# error: generate_fix: key in env at job level
# error: generate_fix: permissions {'contents': 'write'}, only contents: read is needed
# error: generate_fix: github.event expression inside run:, pass it with env:
# error: open_pr: uses a secret but does not launch the agent
# warning: generate_fix: steps after the agent: 1 (the action's security guide wants it last)
The second file fails in four ways, and each corresponds to a recommendation of the sources: the key in the job's environment, the write permission on the agent's job, a github.event expression inside run: (which the guide asks to pass through env: to avoid command injection), a secret in a job that does not launch the agent. The warning on the first file is honest: the documentation example has two steps after the action, the ones that serialize the patch, while the security guide recommends launching the action last, because after a run with broad permissions the state of the host is not guaranteed. With read-only permissions and a diff as the only residue the compromise is reasonable, but it remains a compromise. The script checks the shape: it does not know whether the secrets exist or how the action will run.
The patch as the only handoff
The pattern holds because only a text file passes between the two jobs. The following shell script reproduces the handoff with git and without an agent: job 1 modifies a file and creates a new one, produces the patch with git diff --binary HEAD, job 2, in another copy of the repository, applies it with git apply --index and commits. It also shows why git add -N . appears before the diff in the documentation example: without that intent-to-add, a new untracked file does not enter the patch.
#!/usr/bin/env bash
# The handoff of the two-job pattern, reproduced with git and without an agent:
# "job 1" produces a patch, "job 2" applies it in another copy of the repository.
set -euo pipefail
export GIT_CONFIG_NOSYSTEM=1
G="git -c user.name=demo -c user.email=demo@example.invalid"
base=$(mktemp -d)
trap 'rm -rf "$base"' EXIT
cd "$base"
$G init -q origin && cd origin
printf 'export const discount = (p) => p * 0.9;\n' > discount.js
$G add . && $G commit -q -m "base"
cd ..
git clone -q origin job1 && git clone -q origin job2
# --- job 1 (read-only on the remote): this is where the agent would work ---
cd job1
sed -i 's/0.9/0.85/' discount.js # modified file
printf 'import { discount } from "./discount.js";\n' > discount.test.js # new, untracked file
git diff --binary HEAD > ../without-N.patch
git add -N .
git diff --binary HEAD > ../with-N.patch
echo "without 'git add -N':" $(grep '^diff --git' ../without-N.patch | awk '{print $4}')
echo "with 'git add -N': " $(grep '^diff --git' ../with-N.patch | awk '{print $4}')
# --- job 2 (with write permissions): sees only the patch file ---
cd ../job2
git apply --stat ../with-N.patch | tail -1
git apply --index ../with-N.patch
$G commit -q -m "Fix proposed by the agent"
git log --format='%s' | head -2
git status --short | wc -l | xargs echo "uncommitted files in job 2:"
# Output:
# without 'git add -N': b/discount.js
# with 'git add -N': b/discount.js b/discount.test.js
# 2 files changed, 2 insertions(+), 1 deletion(-)
# Fix proposed by the agent
# base
# uncommitted files in job 2: 0
The first two output lines are the reason git add -N is there: without it the patch contains only discount.js and the test created by the agent is silently lost. The third says that job 2 applies two files, with two lines added and one removed, and the last that after the commit nothing unversioned is left. If a hidden instruction in a repository file pushes the agent to do something harmful, it can at most produce a patch, which a human sees in a pull request. The cost is an artifact, one more job and the effort of reviewing the PR.
The SDK: when to drive the agent from code
The SDK serves CI/CD pipelines, custom agents, internal tools or embedding Codex in an application. The TypeScript package is installed with npm install @openai/codex-sdk and is to be used server-side with Node.js 18 or later; in the npm registry the current version, on 13 November 2026, is 0.167.2, under the Apache-2.0 license. The Python one is installed with pip install openai-codex, requires Python 3.10 or later and is at the same version 0.167.2; its metadata declares an exact dependency on openai-codex-cli-bin, so installing the SDK also installs a CLI binary, which is worth knowing in an environment where every dependency is vetted. Below is the minimal TypeScript example from the documentation, copied as it is and not run.
// schema da adattare, non eseguito: richiede @openai/codex-sdk e un accesso a Codex
import { Codex } from "@openai/codex-sdk";
const codex = new Codex();
const thread = codex.startThread();
const result = await thread.run(
"Make a plan to diagnose and fix the CI failures"
);
console.log(result.finalResponse);
A thread holds the conversation: another run() on the same thread continues it, and resumeThread(threadId) resumes a past thread. I compared the names with the public source code: startThread, resumeThread and run exist, as do runStreamed to receive events one at a time, the thread options sandboxMode, modelReasoningEffort and threadSource (to label the threads created by your integration, for example as ci), and outputSchema among the turn options. In Python, opening the published package without installing it, I found Codex, AsyncCodex, Sandbox with the presets read_only, workspace_write and full_access, thread_start and final_response. The codex mcp-server command has been removed: existing integrations go through the App Server. For the outcome, remember that run() raises an error if the turn fails: in CI it goes inside a try/catch that makes the process exit with a code other than 0.
SDK or codex exec?
codex execif your flow is already a shell script or a CI step: less code, a single binary, output on stdout.- SDK if you have to orchestrate several tasks, keep threads, handle errors in a real language or embed the agent in a service. It adds a dependency to maintain and one more runtime to update.
If in doubt, start from codex exec and move to the SDK when the shell script starts to have logic you would like to test: the two reading and checking scripts in this article are an example, because they are already logic that deserves tests.
Before putting an agent in CI: three questions
- What happens if it gets it wrong? If the answer is "a patch that nobody reviews", do not do it.
- What can it read? Does its environment contain secrets? If so, the job is wrong.
- How much does a runaway run cost? With an API key there is no automatic ceiling: set a spending limit on your account and a timeout on the job. Consumption per model is in part 5.
The three questions go in this order because the first decides whether it makes sense to proceed, the second how to isolate the agent and the third how much you can afford to get wrong. The two jobs answer the second, the human review of the pull request the first; on the third the source gives no ceiling. Part 7 is about what you can delegate when the agent does not run on your runner.
Frequently asked questions
Which sandbox does codex exec run in?
By default in read-only. To allow changes you pass --sandbox workspace-write; danger-full-access should be used only in an isolated environment such as a CI runner or a container. The --full-auto option is no longer supported.
Where should the API key go in CI?
Only on the single command, with CODEX_API_KEY inline, or in the openai-api-key input of the action's step, and not as an environment variable of the whole job when it runs code from the repository. Better two jobs: one that launches the agent without write permissions and one that applies the patch without seeing the key.
What is not demonstrated here
I have not tried Codex, the GitHub Action or the SDK: the outputs of the listings are those of my scripts, not those of the tool, and the event streams are a copy of the documentation and a file built by me. I do not know how well it holds up under concurrent loads or which rate limits apply to API keys in CI. Before using it in a production flow, try it on a throwaway repository and watch the costs for a week.
The same series also includes the comparison with Claude Code, Copilot and Cursor (part 8).
Sources
- Non-interactive mode -
codex exec, options, authentication in CI, two-job example, consulted on 2026-11-13 - Codex SDK - TypeScript and Python, threads, requirements, minimal example, consulted on 2026-11-13
- Developer commands -
codex exec, mandatory prompt with--output-schema,resumeandfork, consulted on 2026-11-13 - openai/codex-action (README and docs/security.md) - action inputs,
safety-strategy, permission profiles, prompt injection risks, consulted on 2026-11-13 - openai/codex, sdk/typescript/src folder - names and types of events, threads and options, behavior of
run(), consulted on 2026-11-13 - actions/checkout - the default behavior of
persist-credentials, consulted on 2026-11-13
The scripts were run with Python 3.14 and git 2.53, twice each, with identical output; the two that use jsonschema and PyYAML run in a virtual environment. The SDK packages were examined without installing them: the npm and PyPI indexes for versions and requirements, the TypeScript source code and the Python wheel file for the names.
← Part 5: models and costs Part 7: cloud, subagents, skills and MCP →
Commenti
Caricamento commenti...
Sign in to comment