# Agent CLIs as Batch Reasoners: Claude Code and Codex Headless

> How we run Claude Code and Codex headless as the reasoning backend of a local pipeline, with schemas, budgets, quota-safe resume and no surprise API billing.

- URL: https://weaveward.com/blog/agent-cli-batch-reasoning-backend
- Published: 2026-11-12
- Updated: 2026-11-12
- Category: AI
- Tags: claude-code, codex-cli, llm-pipelines
- Author: Weaveward Team

A local pipeline that needs a few dozen careful judgements per run (which moments of a podcast stand alone, where a clip should start) does not need its own API account. The developer running it often already pays for Claude Code or a ChatGPT plan with Codex, and both CLIs have an official non-interactive mode that returns schema-checked JSON. But an agent CLI is not an API client: it loads local configuration, carries an agent system prompt, may pick up an API key from the environment, and shares a usage window with everything else the user does that day.

Our thesis: treat the CLI as a slow, rate-limited subprocess and give it the discipline of a flaky remote dependency. That means a strict invocation contract, envelope parsing, batch sizes chosen from measured per-call overhead, environment scrubbing so billing never changes silently, per-run budgets, clean quota stops and a response cache that makes a stopped run resumable.

Everything below comes from the reasoning layer of our AI Video Clipper prototype, where Python sends compact transcript excerpts to a backend and validates every answer; the video never leaves the machine. Measured numbers come from single runs on one Windows development machine, not a benchmark.

## The contract: a backend is a function, not a chat

The clipper defines one abstract interface. A backend receives a task name, a system prompt, a user prompt and a JSON Schema, and returns a parsed object plus whatever usage numbers the vendor reports. It never sees files, holds no session and decides nothing about what happens next; orchestration, validation and retries stay in Python. An agent CLI wants to do more (tools, project memory, hooks, MCP servers, Git checks), and for batch reasoning each of those is latency, extra input tokens or a way for local configuration to change an answer. So the invocation switches off everything that is not reasoning.

| Backend | Authentication | How it is called | Best use |
|---|---|---|---|
| `claude-code` | the user's `claude` login | `claude -p` with `--json-schema`, no tools | Many small calls (about 1.2k tokens overhead each) |
| `codex` | the user's `codex login` (ChatGPT plan) | `codex exec` with `--output-schema`, read-only sandbox | Fewer, larger calls (about 14k tokens overhead each) |
| `command` | whatever the wrapped CLI uses | argv template, JSON on stdout | Another agent CLI or a local model runner |
| `heuristic` | none | deterministic local scoring | CI, offline work, zero usage |

## Headless invocation, flag by flag

```bash
# Claude Code: prompt on stdin, schema inline, no tools, our own system prompt
claude -p --output-format json \
  --json-schema "$(cat schema.min.json)" \
  --tools "" --no-session-persistence --safe-mode \
  --strict-mcp-config --disable-slash-commands \
  --system-prompt "$(cat system.txt)" --model sonnet < prompt.txt > envelope.json

# Codex: JSONL events on stdout, the schema-checked final message in a file
codex exec --json --output-schema schema.json -o last_message.json \
  --skip-git-repo-check --ephemeral --sandbox read-only --color never \
  -C "$RUN_DIR" -c 'model_reasoning_effort="medium"' - < prompt.txt > events.jsonl
```

For Claude Code, `--tools ""` removes every built-in tool, so the model can only answer. `--system-prompt` replaces the whole default agent prompt rather than appending to it, which is what keeps overhead low. `--safe-mode` stops CLAUDE.md, skills, plugins, hooks and MCP servers from loading while leaving authentication alone, `--strict-mcp-config` ignores MCP configuration not passed on the command line, and `--no-session-persistence` keeps one-shot sessions off disk.

The headless documentation recommends `--bare` for scripts, and we deliberately do not use it: bare mode never reads OAuth credentials, so it only works with an API key, which defeats the point of a subscription. `--safe-mode` gives most of the isolation while keeping the user's login. That isolation is not optional: the docs warn that a plain `-p` run executes the hooks in a folder's project settings without any trust prompt.

Codex has no system prompt flag, so the backend prepends the system text to the prompt with an instruction not to run commands or edit files, and enforces it with `--sandbox read-only`. `--skip-git-repo-check` allows an empty per-call directory, `--ephemeral` skips session rollout files, and the trailing `-` makes stdin the entire prompt. One measured surprise: with a ChatGPT login, Codex 0.167 rejected the user's configured default model as "not supported when using Codex with a ChatGPT account". The backend detects that message and points to `codex debug models`, which the tool's `doctor` command surfaces.

## Parse the envelope, never the prose

```python
import json, os, re, subprocess
from pathlib import Path

QUOTA = re.compile(r"usage limit|rate.?limit|limit reached|quota|too many requests"
                   r"|\b429\b|hit your .*limit|out of credits", re.I)
TRANSIENT = re.compile(r"overloaded|\b5\d\d\b|timed? ?out|temporarily unavailable"
                       r"|connection (reset|error)", re.I)

class QuotaExceeded(RuntimeError): pass
class Transient(RuntimeError): pass

def classify(message: str) -> RuntimeError:
    if QUOTA.search(message):
        return QuotaExceeded(message[:500])
    if TRANSIENT.search(message):
        return Transient(message[:500])
    return RuntimeError(message[:1000])

def run_claude(cli: list[str], system: str, prompt: str, schema: dict,
               workdir: Path, timeout: float = 600.0) -> dict:
    argv = [*cli, "-p", "--output-format", "json",
            "--json-schema", json.dumps(schema, separators=(",", ":")),
            "--tools", "", "--no-session-persistence", "--safe-mode",
            "--strict-mcp-config", "--disable-slash-commands", "--system-prompt", system]
    strip = {"ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"}  # never fall back to API billing
    env = {k: v for k, v in os.environ.items() if k not in strip}
    try:
        proc = subprocess.run(argv, input=prompt, capture_output=True, text=True,
                              encoding="utf-8", errors="replace", cwd=workdir,
                              env=env, timeout=timeout, check=False)
    except subprocess.TimeoutExpired as exc:
        raise Transient(f"claude timed out after {timeout:.0f}s") from exc
    for line in reversed(proc.stdout.strip().splitlines()):  # last JSON line wins
        try:
            envelope = json.loads(line)
        except json.JSONDecodeError:
            continue
        if isinstance(envelope, dict):
            break
    else:
        raise classify(f"claude exited {proc.returncode}: {proc.stderr.strip()[-600:]}")
    if envelope.get("is_error") or envelope.get("subtype") not in (None, "success"):
        raise classify(f"claude error ({envelope.get('subtype')}): {envelope.get('result')}")
    return envelope  # caller reads structured_output, usage, total_cost_usd
```

This is the repository's Claude backend, condensed. The prompt goes on stdin because transcripts are long and command lines are not. The parser takes the last line that parses as a JSON object, so a stray banner on stdout cannot break a run. Errors are classified by text because the reactions differ: a quota error stops the run, a transient error (timeouts included) is retried after 5 and then 20 seconds, and anything else fails the call.

The docs say a run without valid structured output simply lacks the `structured_output` field, and that failures inside a run, such as missing authentication, arrive as the result on stdout. So the backend checks `is_error` and `subtype` first and falls back to extracting JSON from `result`. For usage, it adds `input_tokens`, `cache_creation_input_tokens` and `cache_read_input_tokens` to get the true input size, and records `total_cost_usd`, which the docs call a client-side estimate: an API-equivalent figure, not a bill.

Codex needs a different parser. With `--json`, stdout is a JSONL event stream; the backend reads `turn.completed.usage`, collects messages from `error` and `turn.failed` events, and prefers the file written by `-o` over the last `agent_message` item. Only when there is no final text does it classify the collected errors.

Whatever the backend returns then goes through Pydantic and semantic checks, with up to two repair attempts that feed validator errors back. We cover that loop in depth in [structured LLM output validation and repair](/blog/structured-llm-output-validation-repair).

## Per-call overhead decides your batch shape

We measured the fixed cost of a call on each CLI. Claude Code with the replacement system prompt and no tools used about 1.25k input tokens per call before any task content, and a small Haiku call took about 10 seconds of wall time. Codex used about 14.2k input tokens per call, mostly its own agent instructions, which the backend has no flag to replace.

That twelvefold difference changes the design. The clipper's discovery stage sends 40 prefiltered candidate windows to the reasoner in batches of 8. Simple arithmetic on fixed overhead alone:

| Batch size | Calls for 40 candidates | Claude Code overhead | Codex overhead |
|---|---:|---:|---:|
| 1 | 40 | about 50k tokens | about 568k tokens |
| 8 | 5 | about 6k tokens | about 71k tokens |
| 20 | 2 | about 2.5k tokens | about 28k tokens |

For scale, the measured run in the README (a 21.4-minute interview, Claude Code with `sonnet`) made 14 calls totalling 114k input and 25k output tokens, about $0.53 at API prices, covered by the subscription. The same 14 calls on Codex would carry roughly 199k tokens of overhead alone. Some of that may hit a prompt cache, but OpenAI's plan documentation says usage depends on context, so we budget for it as real.

Bigger batches are not free: one invalid item sends the whole batch back through repair, long prompts dilute attention, and wall time creeps towards the default timeouts (600 seconds for Claude Code, 900 for Codex). Our rule: on Claude Code, batch for quality; on Codex, batch for overhead and accept coarser repair.

## Billing safety: scrub the environment

Claude Code's [authentication precedence](https://code.claude.com/docs/en/authentication) puts `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_API_KEY` above the subscription login, and in `-p` mode the key is always used when present. Anthropic's plan article spells out the result: API usage charges instead of the subscription's included usage. A key exported months ago for another project would quietly move every batch run onto pay-as-you-go. Codex documents `CODEX_API_KEY` for `codex exec`, with `OPENAI_API_KEY` as the usual neighbour.

The clipper removes `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN` from the Claude child environment and `OPENAI_API_KEY` and `CODEX_API_KEY` from the Codex one, unless the user sets `allow_api_key: true`. It is a denylist on purpose: the CLIs need profile variables to find their stored login (on Windows, Claude Code keeps it under `%USERPROFILE%\.claude`), and an allowlist that misses one fails in confusing ways.

A denylist has limits. It cannot see an `apiKeyHelper` in the user's settings, so the tool's `doctor` command runs `claude auth status` and `codex login status` and reports the auth method and plan; check it once per machine. Nor can it see usage credits, an account setting that lets a plan keep running past its limit at extra cost. That one you switch off in the account.

## Budgets, quota stops and resume

Claude Pro and Max plans, and Codex on ChatGPT plans, meter usage in 5-hour and weekly windows that are shared with the vendors' other apps, so a batch tool must assume the window can close mid-run. The clipper combines three mechanisms.

```python
import hashlib, json, threading
from collections.abc import Callable
from concurrent.futures import FIRST_EXCEPTION, ThreadPoolExecutor, wait

class BudgetExceeded(RuntimeError): pass

class Engine:
    def __init__(self, backend: Callable[[str, str, dict], dict], cache: dict, *,
                 max_calls: int = 60, max_chars: int = 1_500_000, max_parallel: int = 2):
        self.backend, self.cache = backend, cache  # cache: SQLite in the real pipeline
        self.max_calls, self.max_chars, self.max_parallel = max_calls, max_chars, max_parallel
        self.calls = self.chars = 0
        self.lock = threading.Lock()

    def _reserve(self, chars: int) -> None:
        with self.lock:  # reserve before spending, so parallel workers cannot overshoot
            if self.calls + 1 > self.max_calls or self.chars + chars > self.max_chars:
                raise BudgetExceeded(f"{self.calls} calls, {self.chars} chars used")
            self.calls += 1
            self.chars += chars

    def call(self, task: str, system: str, prompt: str, schema: dict) -> dict:
        key = hashlib.sha256(json.dumps([task, system, prompt, schema],
                                        sort_keys=True).encode()).hexdigest()
        if (hit := self.cache.get(key)) is not None:
            return hit  # resumed runs pay nothing for answered questions
        self._reserve(len(system) + len(prompt))
        answer = self.backend(system, prompt, schema)  # may raise QuotaExceeded
        self.cache[key] = answer  # only validated answers in the real engine
        return answer

    def map(self, fn: Callable, items: list) -> list:
        workers = max(1, min(self.max_parallel, len(items)))
        with ThreadPoolExecutor(max_workers=workers) as pool:
            futures = [pool.submit(fn, item) for item in items]
            done, pending = wait(futures, return_when=FIRST_EXCEPTION)
            for fut in done:
                if (exc := fut.exception()) is not None:
                    for p in pending:
                        p.cancel()  # queued work never starts; in-flight calls finish
                    raise exc
            return [f.result() for f in futures]
```

**Budgets.** Each run may make at most 60 non-cached calls and send at most 1.5 million prompt characters (roughly 375k tokens at the four-characters-per-token estimate the engine records), and every repair attempt reserves budget too. A typical 20 to 60 minute video needs one global map call, about 5 discovery calls and 8 to 12 verification calls, so the cap leaves room for repairs while stopping a runaway loop. When the budget runs out during verification, that candidate is skipped with a warning; the run degrades instead of dying.

**Quota stops.** A `QuotaExceeded` is different: nothing else will succeed in this window. The engine records the call with status `quota`, the exception propagates, and the CLI says that completed calls are cached and `resume` will continue after the limit resets. The batch command stops the remaining jobs rather than failing each in turn.

**The cache.** The real key is a SHA-256 over the engine version, backend, model, task, system prompt, prompt and schema, stored in SQLite, and cached answers are revalidated before reuse. A resumed run replays finished questions for free; in the measured run, a second job on the same video made zero reasoning calls. The cache also makes quota detection forgiving: the regex will miss some new vendor phrasing one day, but a misclassified stop still leaves every finished answer cached. More on that pattern in [content-addressed pipeline caching](/blog/content-addressed-pipeline-caching).

We ran this sketch against a fake backend that raises a quota error after three calls: the first run stopped with three answers cached, and a second run on the same cache made exactly three new calls to finish all six items.

## Bounded parallelism

Parallelism is capped by `max_parallel`, 2 by default. Threads are fine because each worker mostly waits on a subprocess. More workers do not raise a subscription's ceiling; they reach it sooner and turn a clean stop into a burst of rate-limit errors.

On the first exception, `map` cancels work that has not started and re-raises. Leaving the executor's `with` block waits for calls already in flight, so their answers still land in the cache before the run stops. That is the behaviour you want from a quota stop: nothing new starts, nothing paid for is thrown away.

## Fallbacks: a generic command and a deterministic editor

Two more backends keep the pipeline usable without either CLI. The `command` backend takes an argv template with `{schema_file}`, `{prompt_file}` and `{model}` placeholders, sends the full prompt on stdin by default, and accepts the first JSON object on stdout; its docstring uses Gemini CLI as the example. It does not scrub the environment, because it cannot know which variables the wrapped tool treats as credentials, so that responsibility moves to whoever writes the template.

The `heuristic` backend makes no model calls. Discovery ranks candidates by the local prefilter score and verification uses deterministic span repair: lower quality, but reproducible and free. The caching tests run on it, so CI never depends on anyone's login, while the engine tests drive a fake backend through quota, budget and repair paths. In `auto` mode the tool tries Claude Code, then Codex, then falls back to the heuristic with a logged warning.

## Finding the binary on Windows

Agent CLIs on Windows rarely live in one place. The discovery module checks an explicitly configured path, then `PATH`, then known per-user locations: `~\.local\bin\claude.exe`, the native binary bundled in the Claude Code extension for VS Code, VS Code Insiders, Cursor and Windsurf, `%LOCALAPPDATA%\OpenAI\Codex\bin\*\codex.exe`, and the binary bundled in the OpenAI extension. When several versions exist, the newest file wins. On the development machine, Claude Code 2.1.317 was found only inside the VS Code extension.

`PATH` matches ending in `.cmd`, `.bat` or `.ps1` are skipped. With a batch wrapper, `cmd.exe` re-parses every argument, including an inline JSON Schema and a multi-line system prompt: broken quoting at best, an argument-injection surface at worst.

## Terms-of-service boundaries

This design only holds inside a narrow boundary. Anthropic's legal page says OAuth authentication is meant for subscribers' ordinary use of Claude Code, that advertised usage limits for Pro, Max and Ultra assume "ordinary, individual usage", and that third parties may not route requests through users' plan credentials on their behalf. Where Claude Code runs inside a product, the binary must not be modified. For Codex, signing in with ChatGPT brings the ChatGPT terms with it, and on Plus and Pro, content may be used for training unless the user turns it off, which matters for confidential transcripts.

So the clipper launches the user's own, unmodified `claude` or `codex` binary, on the user's own machine, logged into the user's own account, and never reads or stores credentials. That is a personal tool. A hosted clipping service for customers is a different product: it needs API keys under commercial terms, which is exactly the path `allow_api_key` makes explicit rather than accidental.

## Checklist

- Replace the agent system prompt and disable tools; measure per-call overhead before choosing batch sizes
- Read the JSON envelope or event stream, check error fields first, then validate with your own schema
- Strip API-key variables from the child environment by default and report the active auth method
- Cap calls and prompt characters per run, and reserve budget under a lock before each call
- Classify failures into quota, transient and fatal; stop on quota, retry transient with a short backoff
- Cache validated answers by a hash of everything that affects them, so a stopped run resumes cheaply
- Keep a deterministic no-model backend for CI and offline work
- Stay inside the terms: your machine, your account, the unmodified binary, never a multi-user service

## Primary references

- [Claude Code: run Claude Code programmatically (headless mode)](https://code.claude.com/docs/en/headless)
- [Claude Help Center: use Claude Code with your Pro, Max or Ultra plan](https://support.claude.com/en/articles/11145838-using-claude-code-with-your-pro-or-max-plan)
- [Claude Code: legal and compliance](https://code.claude.com/docs/en/legal-and-compliance)
- [OpenAI Codex: non-interactive mode](https://developers.openai.com/codex/noninteractive)
- [OpenAI Help Center: using Codex with your ChatGPT plan](https://help.openai.com/en/articles/11369540-using-codex-with-your-chatgpt-plan)

## Related reading

- [AI Agent Tool Permissions: Limit Actions and Approvals](/blog/ai-agent-tool-permissions)
- [AI Agents Explained: Actions, Tools and Human Review](/blog/ai-agents-explained)

The full pipeline behind this reasoning layer is in our [AI Video Clipper case study](/work/ai-video-clipper), and our [AI solutions service](/services/ai-solutions) covers building pipelines like it.
