Claude Code and Codex Devs

Stop Trusting
the Exit Code

Run Codex or Claude Code as a subprocess and get a verified answer back, not a hang, a false success, or a silent switch to API billing.

Codex and Claude Code lie about success. Get the flags wrong and they hang, or bill your API key.

The external problem

You spawn `codex exec` from a script on Windows and it hangs forever because stdin was never closed, or `claude -p` exits 0 while `git status` shows nothing actually changed.

The internal problem

You stop trusting your own automation. Every headless run becomes a run you have to babysit and re-check by hand, which defeats the point of scripting it.

What's at stake

Keep guessing at flags and you either burn real API spend you meant to avoid, or ship a report that says “done” over work that never happened.

Five steps. Each one closes a failure mode this skill has actually hit.

Run the whole flow before your first scripted call, or jump straight to the step where your last run broke.

01

Lock In the Rules

Close stdin on every Codex call so it can’t hang on an unwritten pipe, own the clock since neither CLI enforces a timeout, and set sandbox, approval, and working directory explicitly instead of inheriting global config.

02

Choose the Call Shape

Pick a quick read-only question or a long write-capable run, for either `codex exec` or `claude -p`, down to the specific flags each shape needs, from `--sandbox workspace-write` to `--permission-mode acceptEdits`.

03

Run Under a Timeout

Foreground short calls with the Bash tool’s own timeout, or use `run_in_background` for anything that could pass ten minutes, since the harness notifies on completion instead of making you poll.

04

Verify Against Ground Truth

Read the answer from `--json` output or the `.result` field, never from an exit code, since both CLIs are effectively 0 or 1 and Codex has exited 0 on Ctrl+C. Then check git status, file existence, or a real test run before trusting a claimed success.

05

Retrieve It Later

If the run outlives the conversation, the full transcript is still on disk (Codex under `~/.codex/sessions/`, Claude under `~/.claude/projects/`). Read it through the `estack-read-agent-history` skill, never by raw-parsing the `.jsonl`.

Reference library: Flags, exit codes, and traps, per CLI.

Every claim carries a source URL: official docs for both CLIs, plus the GitHub issues where a behavior is undocumented and had to be reproduced firsthand, like the Windows stdin hang and Codex exiting 0 on Ctrl+C.

Supporting reference files follow the practical guide. Archived source material and author workflow notes are not a current policy certification.

01 Codex ExecFlags, sandbox rules, exit codes you can’t trust, and the Windows stdin hang.

Reference

Codex Exec

Flags

FlagWhat it does
--cd, -C <path>Workspace root for the run
`--sandbox, -s <read-only\workspace-write\danger-full-access>`Sandbox policy. Default with no flags: read-only
`--ask-for-approval, -a <untrusted\on-request\never>`Approval policy. Use never headless
--dangerously-bypass-approvals-and-sandbox (--yolo)Full bypass — "only use inside an isolated runner"
--full-autoDeprecated; use explicit --sandbox instead
-c, --config key=valueInline config override, repeatable (e.g. -c sandbox_workspace_write.network_access=true)
--ignore-user-configSkip $CODEX_HOME/config.toml entirely — use when the global config must not interfere
--jsonstdout becomes a JSONL event stream (see below)
--model, -m <id>Model override
-o, --output-last-message <path>Write final message to a file
--output-schema <path>Enforce final response against a JSON Schema file
--ephemeralDon't persist a session rollout file
--skip-git-repo-checkAllow running outside a git repo (required otherwise)
codex exec resume --last / resume <SESSION_ID>Continue a prior exec session

Prompt input: positional arg, - for stdin-as-prompt, or pipe + positional arg (arg = instruction, piped content = context).

Output

  • Plain mode: progress → stderr, final agent message → stdout (only that).
  • --json mode: JSONL events on stdout. Types: thread.started (has thread_id — this is the SESSION_ID for resume), turn.started, item.started/item.updated/item.completed (each with item: {id, type, status, ...}), turn.completed (has usage token counts), turn.failed, error.
  • Final answer = the item.completed event where item.type == "agent_message" (its text field).
  • Field-level shapes beyond the ones above aren't fully documented — inspect one real codex exec --json "ls" < /dev/null run before hard-coding a parser.

Exit codes — don't trust them

No official exit-code table exists, and Codex has exited 0 on Ctrl+C/SIGINT ([#4721](https://github.com/openai/codex/issues/4721)). Verify success via turn.completed in the --json stream or via the -o file's existence + content, then verify claimed *effects* against git/filesystem ground truth.

Sandbox semantics

  • read-only: no writes. workspace-write: writes inside workspace root only, network blocked by default — enable per-run with -c sandbox_workspace_write.network_access=true. danger-full-access: no boundaries.
  • Under -a never, a sandbox-blocked action fails back to the model as a tool-call error — no hang, no prompt.
  • Non-zero exit from a tool the model runs can hide that tool's output from the model ([#1367](https://github.com/openai/codex/issues/1367)) — for linters/tests where non-zero means "findings", have the prompt tell Codex to append || true.
  • Sandboxed "build/tests pass" is not trustworthy when the sandbox network posture differs from the real environment (e.g. a build failing at a font fetch before typechecking ever ran).
  • MCP tool calls in exec mode get auto-cancelled (stdin closed → approval prompt reads EOF as reject); only the full bypass flag works around it — avoid designs that need MCP tools inside headless Codex ([#24135](https://github.com/openai/codex/issues/24135)).

Auth (subscription, no API keys)

  • codex login = browser OAuth against the ChatGPT plan; credentials at ~/.codex/auth.json (treat as a password). Tokens auto-refresh during use; mid-run expiry behavior is undocumented.
  • Setting OPENAI_API_KEY or CODEX_API_KEY switches billing to API rates. Precedence when both auths exist is buggy ([#3286](https://github.com/openai/codex/issues/3286)) — just never set them.

Timeouts and process management

  • No whole-run timeout, and no per-tool-call timeout inside a turn. A runaway shell command inside Codex can hang the turn indefinitely and silently drop turn state. Enforce the deadline from the caller: Bash-tool timeout foreground, or run_in_background for long runs.
  • If a run must be killed: kill the process tree (taskkill /T /F /PID <pid> on Windows), then read the session rollout for partial work.
  • Rollouts: ~/.codex/sessions/YYYY/MM/DD/rollout-<local-timestamp>-<uuid>.jsonl, written incrementally (partial state generally survives a kill; no fsync guarantee documented). --ephemeral or history.persistence = "none" disables. Resume replays history but does not resurrect an in-flight tool call.

Windows specifics

  • The stdin hang (SKILL.md rule 1) is the big one — reproduced with PowerShell spawned by Claude Code, exactly this use case ([#20919](https://github.com/openai/codex/issues/20919)). PowerShell has no < redirection operator, so run Codex calls through Git Bash (< /dev/null) or cmd (< NUL).
  • Two sandbox implementations via [windows] sandbox = "elevated" | "unelevated" in config.toml; unelevated (the non-admin fallback) has documented weaker network isolation ([source](https://learn.chatgpt.com/docs/windows/windows-sandbox)).
  • Sandbox-setup helper can crash with STATUS_DLL_INIT_FAILED (0xC0000142) on specific directories (stale sandbox-user SIDs from old versions) — every command in the run fails instantly with that status. Check ~/.codex/.sandbox/sandbox.<date>.log; often transient.
02 Claude HeadlessFlags, permission modes, session resume, and how `-p` runs actually fail.

Reference

Claude Headless

Flags

FlagWhat it does
-p, --print "<prompt>"Non-interactive run; all other CLI flags compose with it
`--output-format <text\json\stream-json>`json = single result object. stream-json = NDJSON events for live-progress pipelines — not needed for run-and-read use
--json-schema '<schema>'With --output-format json: validated result in .structured_output. Invalid schema → immediate exit with Error: --json-schema is not a valid JSON Schema
--allowedTools "<list>"Auto-approve tools/rules — "Bash,Read,Edit" or scoped Bash(git diff *) (note the space before *)
--disallowedTools "<list>"Bare name removes the tool from context entirely; scoped rule denies matching calls only
--permission-mode <mode>default (alias manual), acceptEdits, plan, auto, dontAsk, bypassPermissions
--dangerously-skip-permissions= bypassPermissions; refuses root/sudo outside a sandbox
--continue, -c / --resume, -r <id> / --session-id <uuid> / --fork-sessionSession continuation
--no-session-persistenceNo transcript write for this run (also breaks --resume for it)
--add-dir <path>Extra directory file access (not restored on --resume — re-pass it)
`--model <alias\id>`opus/sonnet/haiku/fable or full id
--append-system-prompt[-file] / --system-prompt[-file]Extend / replace system prompt
--max-turns <n>Turn cap, print mode only; exits with error at limit
--max-budget-usd <x>Spend cap, print mode only

There is no `--tools` flag. Skills work in -p (put /skill-name in the prompt); interactive-only commands like /login don't.

Auth — subscription-only rules

  • ANTHROPIC_API_KEY set → silently used instead of the subscription in -p mode (interactive mode at least prompts once). Keep it unset.
  • Never use `--bare` for subscription runs. Docs recommend it for scripts and plan to make it the -p default — but bare mode "skips OAuth and keychain reads; Anthropic authentication must come from ANTHROPIC_API_KEY or an apiKeyHelper" ([headless docs](https://code.claude.com/docs/en/headless)). Bare mode = API-key mode.
  • No env var injects an OAuth token. Subscription headless auth requires a prior interactive claude login on the machine, and login expiry has no headless recovery (Login expired · Please run /login, but /login needs a terminal).
  • Usage limits: session/weekly limits block all models until reset; the Opus-only limit can be dodged with --model sonnet. 429s auto-retry with backoff; 529 overload doesn't count against quota.

Output parsing

  • json: object with .result (text), .session_id, .total_cost_usd + usage metadata; .structured_output when --json-schema used. Error-field names aren't documented verbatim — inspect one real error payload before hard-coding error handling.
  • On failure: exit 1 with distinguishing *text* (often on stderr, outside the JSON) — capture stderr to a file, don't discard it.
  • Anthropic's own examples parse with jq (| jq -r '.result').

Exit codes

0 = success, 1 = everything else (auth, permissions, limits, schema, turn cap — all exit 1 with distinguishing text). 137 = OOM during install only. Branch on parsed output, not exit codes. ([errors doc](https://code.claude.com/docs/en/errors))

Permission modes headless

  • dontAsk: auto-denies anything not in permissions.allow / built-in read-only set / --allowedTools. Also denies AskUserQuestion and requiresUserInteraction MCP tools even when allowed. Locked-down CI shape.
  • acceptEdits: auto-approves file edits + mkdir touch rm rmdir mv cp sed (and PowerShell equivalents) in-scope; any other shell command or network request without an allow rule aborts the run — the classic "worked in the quick test, died on the real task" trap.
  • auto: classifier-gated; in -p repeated blocks abort the session (no user to re-prompt), and a network-host deny is cached for the rest of the run.
  • bypassPermissions: needs one prior interactive acceptance on the machine; --bg sessions refuse until then.
  • Protected paths (.git, .claude, .mcp.json, shell rc files…) are never auto-approved except in bypassPermissions — under dontAsk they're flatly denied.

Timeouts / process behavior

  • No whole-process timeout — enforce externally (Bash-tool timeout or run_in_background). Signal-kill behavior on partial output/session state is undocumented.
  • Internal knobs: BASH_DEFAULT_TIMEOUT_MS (2 min), BASH_MAX_TIMEOUT_MS (10 min), API_TIMEOUT_MS (10 min). Background Bash tasks are killed ~5s after the final result; background subagents get CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS (10 min default, 0 = unlimited).
  • Piped stdin is capped at 10 MB — for larger input, write a file and reference the path in the prompt.

Sessions

  • Resume lookup is scoped to the project directory and its git worktrees — resuming elsewhere: No conversation found with session ID. Run follow-ups from the same cwd.
  • -p sessions don't appear in the interactive picker but resume fine by id.
  • Ask-an-old-session pattern: claude -p --resume <id> --output-format json "summarize what we changed" | jq -r '.result'.
  • Transcripts: ~/.claude/projects/<encoded-cwd>/<session-id>.jsonl — format is internal and version-unstable; read via the estack-read-agent-history skill, never raw parsing.

Use it now. It's free.

Works on all platforms. Pick yours and get set up in under a minute.

Claude.ai

Download & upload in 60 seconds

Download the zip, then open Claude.ai to upload it.

01

Download the zip below. With JavaScript enabled, Claude.ai opens in a new tab if your browser allows it. Otherwise, use Open Claude.ai.

02

Click the + button in the skills column on the left.

03

Select Create a skill.

04

Select Upload a skill and upload the zip.

05

Start your cli delegation session by running /estack-drive-cli-agent.

Claude Code

Run one command in any terminal

Works anywhere Node.js is installed — your project directory, home directory, anywhere.

01

Open your terminal app and run this command.

npx elliot-stack@latest
02

Run the command.

03

Start Claude Code by typing claude in your terminal.

04

Start your cli delegation session by running /estack-drive-cli-agent.

ChatGPT / Other

Paste a prompt — the AI does the rest

This prompt tells the AI where to fetch current instructions from the live site. No installs. No version lag.

01

Copy the prompt below.

Preview prompt
# Drive a CLI Agent

Run Codex CLI or Claude Code as a non-interactive subprocess and get a trustworthy result back. Both bill against the already-logged-in subscription — never set `OPENAI_API_KEY`, `CODEX_API_KEY`, or `ANTHROPIC_API_KEY` in the call's environment; each silently switches billing to API-key mode.

Before anything non-trivial, read the matching reference: `https://elliotdrel.com/e-stack/drive-cli-agent/references/codex-exec.md` or `https://elliotdrel.com/e-stack/drive-cli-agent/references/claude-headless.md`. Every claim there carries a source URL — when a flag misbehaves or a claim looks stale, fetch the cited URL for current truth instead of guessing.

## Hard rules

1. **Close stdin on every Codex call** — append `< /dev/null`, and run Codex through the Bash tool (Git Bash), not PowerShell (PowerShell has no `<` operator). Without it, `codex exec` hangs forever when spawned with an unwritten stdio pipe — reproduced in exactly this agent-on-Windows setup. ([openai/codex#20919](https://github.com/openai/codex/issues/20919))
2. **Own the clock.** Neither CLI enforces any timeout — not per-run, and for Codex not even on its own internal tool calls. Short calls: foreground with the Bash tool's `timeout` parameter. Anything that could pass 10 minutes: `run_in_background` (the harness notifies on completion — no PID files or polling loops).
3. **Read results from output, never from exit codes.** Both CLIs are effectively 0/1, and Codex has exited 0 on SIGINT. Codex's plain stdout is *only* the final message by design, so capturing it is fine for prose answers; when you need machine-parseable fields, use `--json`/`--output-schema` (Codex) or `--output-format json`/`--json-schema` (Claude) — never regex an answer out of interleaved text.
4. **Verify claimed effects against ground truth.** "Completed" ≠ "succeeded": check `git status`/`diff`, file existence, or a test run before reporting success. Treat the answer itself as a peer suggestion — a sandboxed "tests pass" can be a false signal (e.g. the build died at a blocked network fetch before the real check ran).
5. **Set sandbox, approval, and working directory explicitly per call.** Don't inherit the user's global config posture — it drifts, and interactive defaults are wrong for headless runs.

## Driving Codex (`codex exec`)

Quick question (default — foreground, Bash-tool timeout ~3–5 min):

```bash
codex exec --skip-git-repo-check -a never "<prompt>" < /dev/null
```

stdout is the final answer, progress goes to stderr. Sandbox defaults to read-only.

Long or write-capable task — same shape plus workspace access, run with `run_in_background`, result mirrored to a unique file:

```bash
codex exec --skip-git-repo-check -C "<workdir>" --sandbox workspace-write -a never \
  -o "<scratchpad>/codex-result-<taskname>.md" "<prompt>" < /dev/null
```

- `workspace-write` blocks network (git push, npm install fail with DNS errors) unless you add `-c sandbox_workspace_write.network_access=true`.
- Need structured fields: add `--json` (final answer = the `item.completed` event with `item.type == "agent_message"`; success = `turn.completed`) or `--output-schema <schema-file>`.
- Follow-ups: `codex exec resume --last "<follow-up>"` — only when no other Codex run happened since; otherwise capture `thread_id` from `--json`'s `thread.started` event and use `codex exec resume <id>`.

## Driving Claude Code (`claude -p`)

Read-only question/review (default — foreground, Bash-tool timeout):

```bash
claude -p "<prompt>" --output-format json \
  --allowedTools "Read,Grep,Glob" --permission-mode dontAsk \
  > "<scratchpad>/claude-result.json" 2> "<scratchpad>/claude-err.log"
```

- Answer = `.result`; follow-ups: capture `.session_id`, then `claude -p --resume "<id>" "<follow-up>"` **from the same directory** (resume is scoped to the project dir and its worktrees). On empty or non-JSON output, read the stderr log — failures exit 1 with distinguishing text there.
- Write-capable: `--permission-mode acceptEdits` plus explicit `--allowedTools` for every shell command it will need (e.g. `"Bash(npm test *),Edit,Write"`) — any unapproved command aborts the run.
- Schema-enforced output: add `--json-schema '<schema>'` → validated result in `.structured_output`.
- Add `--no-session-persistence` only for throwaway runs — it breaks both `--resume` and after-the-fact transcript retrieval.
- **Never use `--bare`** (docs recommend it for scripts, but it skips OAuth — subscription auth stops working). There is no `--tools` flag.

## Retrieval when a run outlives the conversation

Unless `--ephemeral`/`--no-session-persistence` was passed, full transcripts persist on disk (Codex: `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`; Claude: `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl`). Read them via the `estack-read-agent-history` skill — never raw-Read the `.jsonl`.

---

## Skill Feedback

If the user shares feedback about this skill — a bug, something confusing, a missing feature, or a suggestion — ask them to describe it in a bit more detail (what they expected, what happened, and any relevant context). Then file the issue using whichever method is available:

**If `gh` is installed** (`gh --version` succeeds), create the issue directly:

```bash
gh issue create \
  --repo ElliotDrel/e-stack \
  --title "estack-drive-cli-agent: <concise summary>" \
  --body "<description from user feedback — expected vs. actual behavior and context>"
```

**If `gh` is not installed**, build a pre-filled URL:

```bash
python3 -c "
import urllib.parse
title = 'estack-drive-cli-agent: <concise summary>'
body = '<description from user feedback — expected vs. actual behavior and context>'
base = 'https://github.com/ElliotDrel/e-stack/issues/new'
print(base + '?title=' + urllib.parse.quote(title) + '&body=' + urllib.parse.quote(body))
"
```

Share the printed URL with the user and offer to open it in their browser.

They can also click it directly, review the pre-filled title and body, and click **Submit new issue**.
02

Open your platform and paste the prompt.

03

Start your cli delegation session.

Drive CLI Agent ships in E-Stack, a set of 21 free skills installed by one command. See the whole stack.