# How to Run Claude Code and Codex Headless in CI or on a Server

> Run Claude Code (claude -p) and Codex (codex exec) headless: credentials for CI, JSON output, tool allowlists, exit codes, timeouts and resume, from real runs.

Published November 18, 2026 · by the AQ team · Canonical: https://aq.dev/guides/headless-claude-code-and-codex/

To run Claude Code headless, call `claude -p "your prompt"`: it runs the task with no interactive screen, prints the result and exits. The Codex equivalent is `codex exec "your prompt"`. In CI or on a server, add a machine-readable output format (`--output-format json` or `codex exec --json`), an explicit list of what the agent may do, a credential the job owns, and a timeout. Then check the result itself, not only the exit code, because both CLIs can exit 0 on a run that did not do the task.

**AQ runs Claude Code, Codex and other agent CLIs for a team, each task in its own branch and git worktree on a machine the team controls, and you can start and steer those runs from the app, the REST API, MCP or a bot routine.** The rest of this guide is about the two CLIs themselves and works with or without AQ.

This page covers what the official docs leave to you as a team: which credential a job should use, how to parse the output, how to lock down an unattended run, and how to handle failures. For the full flag lists, read Anthropic's [Run Claude Code programmatically](https://code.claude.com/docs/en/headless) and OpenAI's [Codex non-interactive mode](https://developers.openai.com/codex/noninteractive). For step-by-step installation and login on a fresh server, see the [self-hosted setup guide](https://aq.dev/guides/self-hosted-ai-coding-agent-setup/).

## The two commands, side by side

Checked on November 18, 2026 against the docs and the local help of Claude Code 2.1.327 and codex-cli 0.170.0.

| What you need | Claude Code | Codex |
| --- | --- | --- |
| Run once and exit | `claude -p "prompt"` | `codex exec "prompt"` |
| Prompt from stdin | `cat task.md \| claude -p` | `codex exec -` (piped input with a prompt is added as a `<stdin>` block) |
| One JSON result | `--output-format json` | `-o last.txt` writes the final message to a file |
| Event stream | `--output-format stream-json --verbose` | `--json` (JSON Lines) |
| Force a result shape | `--json-schema '<schema>'`, read `structured_output` | `--output-schema schema.json` |
| Limit what it can do | `--allowedTools`, `--disallowedTools`, `--permission-mode` | `--sandbox read-only \| workspace-write \| danger-full-access` |
| Cap the work | `--max-turns`, `--max-budget-usd` | No turn cap flag; use a timeout |
| Continue a session | `--resume <session_id>` or `--continue` | `codex exec resume <thread_id>` or `resume --last` |
| Ignore local config | `--bare` (skips hooks, skills, MCP servers, CLAUDE.md) | `--ignore-user-config`, `--ignore-rules` |
| Leave nothing on disk | No flag | `--ephemeral` |

Codex refuses to run outside a git repository unless you pass `--skip-git-repo-check`. Anthropic describes `--bare` as the recommended mode for scripted calls and says it will become the default for `-p` in a future release, so set it explicitly if your job depends on the repository's CLAUDE.md or MCP servers being loaded.

## A real run of each

We ran both CLIs on November 18, 2026 in a throwaway repository holding `README.md` and a one-function `math.mjs`, signed in with a subscription login. The excerpts are trimmed with `jq`; nothing is edited.

**Claude Code 2.1.327:**

```
claude -p "List the files in this repository and say in one sentence what math.mjs exports. Do not edit anything." \
  --output-format json --allowedTools "Read,Glob,Grep" --permission-mode dontAsk --max-turns 5 > out.json
echo $?   # 0
jq '{subtype, is_error, num_turns, duration_ms, session_id, result}' out.json
```

```
{
  "subtype": "success",
  "is_error": false,
  "num_turns": 2,
  "duration_ms": 3673,
  "session_id": "3692a16d-46f7-469a-80b4-3c1fb077c839",
  "result": "The repository has three files: ... `math.mjs` exports a single function, `add(a, b)`, which returns the sum of its two arguments. I didn't edit anything."
}
```

The third file it listed was `out.json` itself, because we redirected output into the repository. Write results outside the working tree, or the agent reads them on the next run.

**Codex 0.170.0**, with the file passed on stdin and a schema for the answer:

```
cat math.mjs | codex exec --json --sandbox read-only --output-schema schema.json -o last.json \
  "The file math.mjs is in the stdin block. List its exported names and summarize it in one sentence. Do not run commands." > events.jsonl
echo $?   # 0
jq -c '{type, item: .item.type}' events.jsonl
cat last.json
```

```
{"type":"thread.started","item":null}
{"type":"turn.started","item":null}
{"type":"item.completed","item":"agent_message"}
{"type":"turn.completed","item":null}
{"exports":["add"],"summary":"`math.mjs` exports an `add` function that returns the result of applying JavaScript's `+` operator to its two arguments."}
```

The `turn.completed` event carries token usage (`input_tokens`, `cached_input_tokens`, `output_tokens`, `reasoning_output_tokens`), and `thread.started` carries the `thread_id` you need to resume.

## Which credential a server or CI job should use

This is the question the docs answer one person at a time. On a team, decide whose account each job spends, where the credential lives, and when it expires.

**Claude Code** reads credentials in a fixed order, documented on Anthropic's [authentication page](https://code.claude.com/docs/en/authentication): cloud provider settings (Bedrock, Vertex, Foundry), then `ANTHROPIC_AUTH_TOKEN`, then `ANTHROPIC_API_KEY`, then an `apiKeyHelper` script, then `CLAUDE_CODE_OAUTH_TOKEN`, then a subscription login. In `-p` mode an `ANTHROPIC_API_KEY` in the environment is always used when present, so a stray key in a runner's environment silently moves a job off a subscription and onto API billing.

- **API key** (`ANTHROPIC_API_KEY`, or an `apiKeyHelper` that fetches a short-lived key from your secret manager): billed per token to an organization account, not tied to a person, and the only option with `--bare`.
- **Subscription token** (`CLAUDE_CODE_OAUTH_TOKEN`, made with `claude setup-token`): a one-year token that needs a Pro, Max, Ultra, Team or Enterprise plan. It is one person's plan, so every job that uses it counts against that person's limits, and `--bare` ignores it.

**Codex**: OpenAI's auth docs call API keys the recommended default for automation. Set `CODEX_API_KEY` for a single run, or store a key with `printenv OPENAI_API_KEY | codex login --with-api-key`. A ChatGPT login also works headless: `codex login --device-auth` on the machine, or a copy of `~/.codex/auth.json` from a machine where you signed in. OpenAI describes ChatGPT-managed auth in CI as an advanced option for trusted runners, says not to use it for public or open source repositories, and says to treat `auth.json` like a password. Enterprise workspaces can also issue access tokens (`codex login --with-access-token`) for trusted scripts and private runners.

Rules that hold for both:

- **One credential per purpose.** A nightly job, a PR reviewer and a person's own server each get their own key or token, so you can revoke one without stopping the others and read usage per job.
- **Personal tokens stay personal.** A subscription token in a shared CI secret means one person's plan pays for everyone's jobs and their limits stop everyone's work. Use an organization API key for shared automation, and personal logins for jobs a person starts.
- **Keep it out of untrusted code's reach.** OpenAI's docs say not to set `OPENAI_API_KEY` or `CODEX_API_KEY` as a job-level variable in workflows that run repository-controlled code. Scope the secret to the one step that runs the agent, and never on pull requests from forks.
- **Put expiry on a calendar.** A `setup-token` token lasts a year. Record who made it and when, and rotate before it lapses rather than after the first failed night.
- **Check which identity ran.** `codex login status` prints the method in use (ours said "Logged in using ChatGPT") and exits 0 when credentials are present. Run it as a first step so a missing login fails fast.

The [software factory security guide](https://aq.dev/guides/software-factory-security-permissions-secrets-review-gates/) goes further on secrets, scopes and who can approve what.

## Capturing and parsing the output

Use a single JSON result when you only need the answer, and a stream when you want progress, tool calls or a live log.

- **Claude Code, one result.** `--output-format json` prints one object. The fields we used: `result` (the final text), `is_error`, `subtype`, `num_turns`, `session_id`, `permission_denials` and `total_cost_usd`, which Anthropic notes is a client-side estimate. Read the answer with `jq -r .result`.
- **Claude Code, a stream.** `--output-format stream-json --verbose` prints one JSON object per line. Our run produced, in order: `system/init`, an assistant `tool_use`, a `rate_limit_event`, a user `tool_result`, an assistant `text`, then `result/success`. Add `--include-partial-messages` for token-by-token text.
- **Codex.** `--json` prints `thread.started`, `turn.started`, `item.*` events (agent messages, reasoning, commands, file changes, MCP calls), and finally `turn.completed` or `turn.failed`. `-o` writes only the final message to a file, which is the easiest thing to post as a comment.
- **Structured answers.** When a later step reads the answer (a review verdict, a list of files), pass a JSON Schema: `--json-schema` for Claude Code puts the answer in `structured_output`, and `--output-schema` for Codex shapes the final message, as in the run above.

## Permissions for unattended runs

Nobody is there to answer a permission prompt, so decide in advance what the agent may do and make everything else fail closed.

- **Claude Code:** list allowed tools with permission rules, for example `--allowedTools "Read,Edit,Bash(npm test)"`, and add `--permission-mode dontAsk`, which denies every call that would otherwise prompt. Use `--disallowedTools "Bash(rm *)"` for specific refusals. Keep `bypassPermissions` for runners that are thrown away after each job.
- **Codex:** pick a sandbox per job: `read-only` for review and questions, `workspace-write` for builds. `--dangerously-bypass-approvals-and-sandbox` is, in the CLI's own words, intended solely for environments that are externally sandboxed.

A denied action does not fail the run. We asked Claude Code to create a file while only Read, Glob and Grep were allowed. It tried the Write tool, then a shell command, was refused both times, explained this in its result, and exited 0:

```
jq '{subtype, is_error, denied: [.permission_denials[].tool_name]}' deny.json
```

```
{
  "subtype": "success",
  "is_error": false,
  "denied": ["Write", "Bash"]
}
```

If a job should do something, test for it: fail the step when `permission_denials` is not empty, or check that the expected file or commit exists.

## Exit codes, timeouts and safe retries

Anthropic documents that Claude Code exits 0 on success and non-zero when the run fails, and 143 on SIGTERM. OpenAI's page documents almost nothing about Codex exit codes. Here is what we saw on November 18, 2026:

| Case | Exit code | What the output said |
| --- | --- | --- |
| Claude Code, task done | 0 | `is_error: false`, `subtype: "success"` |
| Claude Code, tools denied | 0 | `is_error: false`, two entries in `permission_denials` |
| Claude Code, `--max-turns 1` on a two-step task | 1 | `is_error: true`, `subtype: "error_max_turns"`, `result: null` |
| Claude Code, unknown model name | 1 | `is_error: true` with `subtype: "success"` |
| Claude Code, killed by `timeout 4` | 124 (143 with `--preserve-status`) | Nothing; the JSON file was empty |
| Codex, task done | 0 | Ends with `turn.completed` |
| Codex, its shell sandbox could not start | 0 | `turn.completed`; the final message said it could not list the files |
| Codex, unknown model name | 1 | `error` then `turn.failed` events |
| Codex, killed by `timeout 6` | 124 | The stream stopped after `turn.started` |

The Codex sandbox case happened because our test machine was a container where Codex's Linux sandbox could not start. The agent reported the failure in words and the process still exited 0. That is the general lesson: the exit code tells you the CLI ran, and only the output tells you the task was done.

- **Branch on undefined, not undefined.** The unknown-model run had `subtype: "success"` and `is_error: true`.
- **Wrap every run in a timeout.** Neither CLI has a wall-clock limit of its own in headless mode. A killed run writes no final JSON, so treat empty output as a failure.
- **Retry only what is safe to repeat.** A read-only review can be rerun freely. A build that edits files or commits should restart from a clean checkout of the same commit, never on top of a half-finished worktree, and should not retry after a step that pushed or commented.
- **Close stdin when you do not pipe a prompt.** Without it, `codex exec` printed "Reading additional input from stdin..." and waited for input in our shell; `</dev/null` avoids a hang in CI.

## Resuming a session

Both CLIs keep sessions in files on the machine that ran them, so a resume has to run on the same machine or with that session directory restored.

```
# Claude Code: the session_id comes from the JSON result
SID=$(jq -r .session_id deny.json)
claude -p "In one sentence, what did I ask you to do last time?" --resume "$SID" --output-format json

# Codex: the thread_id comes from the thread.started event
TID=$(jq -r 'select(.type=="thread.started").thread_id' events.jsonl)
codex exec resume "$TID" --json "In one sentence: which export did you report last time?" </dev/null
```

Both answered from the earlier session: Claude Code with "You asked me to create a file named NOTES.md containing hello, but I couldn't because the permission mode blocked file writes," and Codex with "I reported the add export." On ephemeral CI runners, resuming is usually the wrong tool: write what the next step needs (a plan, a review, a list of files) to an artifact and start a fresh session from it.

## Running the same job on Claude Code and Codex

Teams often run one job on both, for example to compare builders or to have one vendor review the other's work. Keep one prompt file and a thin wrapper that normalizes the output to the same three fields:

```
#!/usr/bin/env bash
# usage: run-agent.sh claude|codex prompt.md  ->  {"ok":..,"text":..,"session":..}
set -uo pipefail
out=$(mktemp)
case "$1" in
  claude)
    timeout 1800 claude -p --output-format json --permission-mode dontAsk \
      --allowedTools "Read,Grep,Glob" --max-turns 30 < "$2" > "$out"
    jq -c '{ok: (.is_error == false and (.permission_denials | length) == 0),
            text: .result, session: .session_id}' "$out" ;;
  codex)
    timeout 1800 codex exec --json --sandbox read-only - < "$2" > "$out"
    jq -sc '{ok: (any(.[]; .type == "turn.completed") and (any(.[]; .type == "turn.failed") | not)),
             text: ([.[] | select(.item.type == "agent_message") | .item.text] | last),
             session: (.[] | select(.type == "thread.started") | .thread_id)}' "$out" ;;
esac
```

We ran this script on both with a one-line prompt asking what `math.mjs` exports. Claude Code returned `"ok":true` and the right answer. Codex also returned `"ok":true`, with the text "Please paste or attach `math.mjs` so I can tell you what it exports", because its sandbox could not read files on our machine. So `ok` only means the run finished cleanly; a later step still has to check the answer. An empty output file (a timeout) makes `jq` print nothing, which your pipeline should treat as a failure. Keep the allowed actions equivalent on both sides (here, read-only), or the comparison measures permissions instead of the agents.

## Where headless runs fit in a software factory

In a [software factory](https://aq.dev/software-factory/), headless runs are the stations between people: a task arrives from intake, a headless build implements it on its own branch, a headless review from a different vendor reads the diff, and a person merges. The headless parts are where unattended credentials, allowlists, timeouts and result checks matter; the plan approval and the merge stay with people.

The [guide to building a software factory with Claude Code and Codex](https://aq.dev/guides/build-a-software-factory-with-claude-code-and-codex/) wires that loop end to end, including a DIY version built from `claude -p` and `codex exec`. The [software factory levels guide](https://aq.dev/guides/software-factory-levels-from-autocomplete-to-dark-factory/) explains how much of the loop to automate at each stage.

## Where AQ fits

AQ runs Claude Code, Codex and other agent CLIs for a team, each task in its own branch and git worktree on a machine the team controls, and you can start and steer those runs from the app, the REST API, MCP or a bot routine.

- **Each person's own accounts.** Each person connects their own Claude, Codex or other subscriptions, and their messages run on those accounts, so there is no shared subscription token sitting in a CI secret. AQ does not mark up usage on accounts a team connects.
- **The REST API.** Create a work item with `POST /v1/workspaces`, start a run with `POST /v1/workspaces/{id}/agent`, then follow it with `GET /v1/agent-sessions/{id}/stream` (server-sent events) or poll it. Every POST takes an `Idempotency-Key`, so a retried CI step does not start a second run. See the [API docs](https://aq.dev/docs/api/).
- **MCP.** Connect `https://aq.dev/mcp` to Claude Code, Codex or another MCP client and start or message runs with tools such as `start_agent`. Headless clients use an API key instead of the browser sign-in. See the [MCP docs](https://aq.dev/docs/mcp/).
- **Bot routines.** A [bot](https://aq.dev/docs/bots/) routine runs on a schedule, a webhook, a GitHub event, a Linear label and other triggers, and runs as the person who created it, on their connected subscription or AQ credits.
- **Machines.** On the Free plan agents run on your own Mac with the AQ Mac app. Pro includes an always-on cloud machine, so runs keep going when your laptop is closed. API and MCP access is on every plan. See [pricing](https://aq.dev/pricing/).

AQ does not replace `claude -p` or `codex exec` in a pipeline you already run. It gives a team one place to run, watch and review the same agents.

## Frequently asked questions

### What is Claude Code headless mode?

Headless mode is running Claude Code without its interactive screen: `claude -p "prompt"` runs the task, prints the result and exits. Add `--output-format json` or `stream-json` for machine-readable output, and `--allowedTools` with `--permission-mode dontAsk` so it never waits on a permission prompt. Anthropic documents it as the Agent SDK used through the CLI.

### How do I run Claude Code in a CI pipeline?

Install the CLI in the job, provide a credential as a secret scoped to that step (an `ANTHROPIC_API_KEY`, or a `CLAUDE_CODE_OAUTH_TOKEN` from `claude setup-token`), and run `claude -p` with `--output-format json`, an allowlist of tools, `--max-turns` and a `timeout`. Then fail the step when `is_error` is true, the output is empty, or `permission_denials` is not empty.

### Can I use my Claude subscription instead of an API key in CI?

Yes. `claude setup-token` creates a one-year OAuth token for CI and scripts, and it needs a Pro, Max, Ultra, Team or Enterprise plan. Pass it as `CLAUDE_CODE_OAUTH_TOKEN`. Two caveats: an `ANTHROPIC_API_KEY` in the same environment takes precedence in `-p` mode, and `--bare` ignores the token. Every job that uses it counts against that one person's plan limits.

### What is the Codex equivalent of claude -p?

`codex exec "prompt"`. Use `--json` for a JSON Lines event stream, `-o file` for the final message, `--output-schema` to shape the answer, `--sandbox read-only` or `workspace-write` to limit what it can change, and `codex exec resume <thread_id>` to continue a session.

### Why did my headless run exit 0 when it did not finish the task?

Both CLIs exit 0 when the run completes, even if the agent could not do what you asked. In our tests Claude Code exited 0 after its writes were denied, and Codex exited 0 after its shell sandbox failed to start. Check the output: `is_error` and `permission_denials` for Claude Code, `turn.failed` and the final message for Codex, and the files or commits you expected.

### Can a headless run continue an earlier session?

Yes. Claude Code takes `--resume <session_id>` (from the JSON result) or `--continue` for the latest session in the directory. Codex takes `codex exec resume <thread_id>` or `--last`. Sessions are stored on the machine that ran them, so on throwaway CI runners it is usually simpler to save the needed output as an artifact and start fresh.

---

About AQ: AQ is where teams put AI agents to work on everything they do: code that lands as a reviewed pull request, bots that run the jobs that repeat, and an assistant that starts each day, all on the agents and subscriptions they already have, like Claude Code and Codex, on private cloud machines of their own or on their own Mac. Start at [aq.dev](https://aq.dev/).
