CLI reference for Claude Code command-line interface. Use when you need help with Claude Code commands, flags, or CLI usage.
Procedural API Reference for Deep Tool Integration and Edge-Case Coverage
Scope: Codex CLI as shipped in the openai/codex repository snapshot provided (Rust core + Node distribution wrapper).
Normative terms: MUST, MUST NOT, SHOULD, SHOULD NOT, MAY.
An “integrator” is any program, agent, IDE, CI system, daemon, or automation that:
This text treats the source tree as the specification. Where behavior is ambiguous, the code path is authoritative.
This text is tuned to Ubuntu 24.04 execution characteristics:
/bin/bash, /bin/sh.codex exec …) with optional JSONL streaming (--json).-c key=value, feature toggles).codex-rs/: Rust workspace implementing the native CLI, core runtime, sandboxing, protocol, exec mode, app server, MCP server.codex-cli/: Node distribution wrapper that selects a platform binary and spawn()s it; used by npm i -g @openai/codex.docs/: developer documentation (not authoritative over code).sdk/, shell-tool-mcp/, etc.: supporting components.codex-rs/cli/: main codex command, subcommand routing, global config overrides (-c), feature toggles (--enable/--disable), interactive session wrappers.codex-rs/exec/: headless execution engine and JSONL event output implementation.codex-rs/core/: config loader, sandbox/policy logic, tool runtime plumbing, session recording.codex-rs/arg0/: “arg0 multiplexer” allowing a single binary to behave as helper executables (Linux sandbox helper, apply-patch helper) based on argv[0] and a secret arg.codex-rs/linux-sandbox/: Linux sandbox helper implementation (Landlock + seccomp; invoked via arg0 dispatch).codex-rs/protocol/: shared data model used for events, sandbox policy, thread/session protocol.codex-rs/app-server/ and codex-rs/app-server-protocol/: JSON-RPC service and message types.codex-cli/bin/codex.js)If Codex is installed via npm/bun globally, the user-visible codex is commonly a Node script which:
Computes a platform target triple (Linux: x86_64-unknown-linux-musl or aarch64-unknown-linux-musl).
Locates the native binary at:
<package>/vendor/<targetTriple>/codex/codex (Linux) or codex.exe (Windows).Optionally prepends <package>/vendor/<targetTriple>/path to PATH if that directory exists.
Sets exactly one env var to indicate package manager provenance:
CODEX_MANAGED_BY_NPM=1 or CODEX_MANAGED_BY_BUN=1.Spawns the native binary asynchronously with:
stdio: "inherit" (TTY and streams are passed through).env: { ...process.env, PATH: updatedPath }Forwards signals SIGINT, SIGTERM, SIGHUP to the child, then mirrors the child exit semantics:
Integrator guidance
stdio: inherit constraint and to control pipes precisely).stdin/stdout/stderr are not independently configurable (inherit mode), unless you modify the wrapper.CODEX_MANAGED_BY_NPM=1 or CODEX_MANAGED_BY_BUN=1 in the environment even when calling the native binary.The Rust binaries frequently begin by calling an “arg0 dispatch” routine. This enables:
codex-linux-sandbox).Integrator guidance
codex binary “only” implements the CLI entrypoint. It also self-hosts helper entrypoints that are selected by argv[0] or specific args.argv[0] stable unless you intend helper behavior..env InjectionCodex resolves “Codex home” (state + config root) as:
If CODEX_HOME is set:
Else:
~/.codex (may or may not exist; callers may create it).Integrator guidance
CODEX_HOME explicitly when isolation is required (e.g., per-project or per-run state segregation).CODEX_HOME, you MUST create the directory first (or accept that Codex will fail early).CODEX_HOME as sensitive state (tokens, session logs, caches)..env file earlyAt startup, Codex attempts to load:
${CODEX_HOME}/.env if it exists.However, Codex applies a safety filter:
CODEX_ are ignored when loading .env.OPENAI_API_KEY, HTTP_PROXY, etc.) may be loaded.Integrator guidance
${CODEX_HOME}/.env to set CODEX_HOME or other CODEX_* variables; they will be ignored.${CODEX_HOME}/.env to set provider credentials (e.g., API keys) or general environment settings..env injection and instead set environment variables explicitly at process launch.Codex attempts to create helper aliases under:
${CODEX_HOME}/tmp/path/<random-suffix>/It then prepends that directory to PATH.
This helper-path directory is used to place:
codex-linux-sandbox.apply_patch.Security guardrail
CODEX_HOME appears to be under the system temp directory (anti-hijack hardening).Integrator guidance
CODEX_HOME to /tmp/... (or similar), you SHOULD expect failures in release builds.codex binary explicitly for sandbox execution (not recommended; the core expects helper availability in some flows).codex)The Rust codex binary is implemented as a multi-tool command:
-c key=valueCodex supports repeatable configuration overrides:
-c <KEY>=<VALUE> or --config <KEY>=<VALUE>Parsing semantics:
Keys are dotted paths; each component becomes a nested table key.
Values are parsed as TOML if possible.
Later overrides override earlier ones.
Precedence semantics in the main CLI:
-c overrides are prepended to subcommand overrides, so subcommand overrides win if they modify the same key.Integrator guidance
codex-rs/core/config.schema.json) when generating overrides.--enable FEATURE, --disable FEATURECodex supports toggling known feature flags:
--enable <FEATURE> is equivalent to -c features.<FEATURE>=true--disable <FEATURE> is equivalent to -c features.<FEATURE>=falseValidation:
Precedence:
-c overrides, meaning toggles override earlier root -c values.-c overrides still take precedence over root-level toggles because of the prepend rule.Integrator guidance
-c features.<name>=… rather than --enable/--disable unless user-facing ergonomics require the latter.This textbook begins with the headless automation path; other subcommands are covered in later parts.
Key subcommands:
codex exec …: headless execution engine (primary automation interface).codex review …: wrapper that internally uses exec review mode.codex app-server …: JSON-RPC service (stdin/stdout) for IDE integration.codex mcp … / codex mcp-server: MCP server integration (stdio) and management tools.codex resume …, codex fork …: interactive session continuation; relevant when your tool wants to drive interactive sessions or replay.codex exec) — Operational Modelcodex exec is designed to run Codex without a TUI. It supports:
codex exec supports multiple command variants inside the exec subsystem:
codex exec (default “exec” action)codex exec reply …codex exec review …Codex also exposes a top-level codex review wrapper that internally maps to codex exec review.
This section covers the default “exec” action unless stated otherwise.
codex exec accepts prompt text via:
--prompt <TEXT> (short -p)--prompt - meaning “read the entire prompt from stdin”If --prompt is omitted, the default is read from stdin (behavioral equivalence to --prompt -).
Stdin reading guardrails:
Prompt decoding:
Prompt bytes are decoded as:
UTF-32 BOM is explicitly rejected.
If decoding fails, Codex exits with an error.
Empty prompt:
trim().is_empty()), Codex exits with an error.Integrator guidance
--prompt <TEXT> when possible.--prompt -, ensuring stdin is not a TTY.codex exec supports attaching images:
--image <PATH> repeatable; also supports comma-delimited values.Images are read from filesystem paths.
Integrator guidance
--output-schema <PATH>:
--output-last-message <PATH>:
Integrator guidance
--output-schema when machine parsing is required and you can provide a stable schema.--output-last-message as an idempotent “best effort” artifact; validate file presence after execution.--json switches the output mode from human-readable printing to JSONL event streaming on stdout.When JSONL mode is enabled:
Integrator guidance
codex exec --json JSONL Event Stream — Normative Contract\n.Consumer algorithm (normative)
\n.event field (string).thread_id when present.Each JSONL line is an ExecEvent with:
event: string discriminatordata: event-specific payloadExample shape:
{"event":"thread_started","data":{"thread_id":"..."}}
This stream is derived from a mapping of core “thread events” into exec-specific events.
thread_startedEmitted when a session is configured and execution begins.
Payload:
thread_id: string (UUID-like)Notes:
turn_startedEmitted when a new “turn” begins (user input is accepted by the agent runtime).
Payload:
turn_id: string (opaque id)input: string (the prompt text used for the run)Notes:
input field is the user prompt as provided/decoded (not necessarily trimmed).turn_id as opaque and unique within the thread.item_completedEmitted when an “item” finishes.
Payload:
item: object with:
id: string (opaque item id)item_type: string discriminatorcontent: type-specific structureitem_type currently maps to ThreadItemDetails variants, including (non-exhaustive):
web_search: includes query and related metadata.exec_command: includes command string, exit code, stdout/stderr, and timing.apply_patch: includes patch text and apply results.agent_message: includes agent message text and/or structured final output.Critical edge case
exec_command item completion fields for full captured output.turn_completedEmitted when the turn finishes successfully.
Payload:
turn_id: stringoutput: string (final agent message, if available; may be empty depending on failure/interrupt)status: "completed"If --output-last-message was provided, Codex attempts to write output to the configured path when this completes.
turn_failedEmitted when the turn ends in a failure state.
Payload:
turn_id: stringerror: string (human-readable error)status: "failed"errorEmitted on runtime errors (distinct from turn failure).
Payload:
message: stringcode: optional numeric or string code (implementation-dependent)fatal: boolean (best-effort indicator)Exit code coupling
error event is emitted during the run, the codex exec process exits with code 1 even if a final message exists.statusEmitted for general progress updates.
Payload:
message: stringWithin a single run:
thread_started occurs before any turn_started.turn_started occurs before the corresponding turn_completed/turn_failed.item_completed events for a turn occur after its turn_started and before its completion event, but consumers MUST tolerate out-of-order items if future implementations change concurrency.In exec mode, Codex automatically refuses interactive elicitation:
Integrator guidance
codex exec.codex exec exits with:
0 when:
1 when:
In native mode, signals behave as normal for a CLI process. In npm/bun distribution mode:
SIGINT, SIGTERM, SIGHUP to the native child.Integrator guidance
When embedding, you SHOULD implement:
SIGINT propagation to Codex.When consuming JSONL, you MUST handle abrupt stream termination (partial lines) if the process is interrupted. Treat incomplete trailing line as discard.
codex execSandbox is controlled by a “sandbox mode” input which maps to a concrete runtime policy:
read-onlyworkspace-writedanger-full-access (often exposed as “dangerously bypass” / “yolo” semantics)external (signals that an external sandbox already exists; behavior may differ by platform)codex exec default approval policy is “never prompt”Exec mode imposes a harness-level override:
Practical effect:
If an operation would require prompting for approval, exec mode cannot prompt and therefore either:
Exec mode provides:
--full-auto:
--dangerously-bypass-approvals-and-sandbox (alias --yolo):
Integrator guidance
--full-auto is the safest “hands off” mode that still attempts to constrain filesystem/network access.--yolo MUST be treated as a hazardous operational mode. Tools SHOULD only expose it behind explicit policy checks and should log/attest when used.On Linux, Codex runs sandboxed commands by spawning a helper entrypoint that:
Is the same executable as codex, but invoked under an alternate name via arg0 dispatch (codex-linux-sandbox).
Receives:
--sandbox-policy-cwd <PATH>--sandbox-policy <SANDBOX_POLICY_JSON_OR_STRUCT>-- <COMMAND> <ARG...>The Linux sandbox helper applies restrictions on the current thread before execvp():
PR_SET_NO_NEW_PRIVS if disk write or network is restricted.
A seccomp filter when network is restricted:
recvfrom explicitly for compatibility with some toolchains (notably those that rely on socketpair/process management).A Landlock filesystem ruleset when disk write is restricted:
/ (entire filesystem)./dev/null.The protocol supports “writable roots” with “read-only subpaths” (e.g., .git, .codex) intended to remain protected even when the workspace is writable.
However, in the current Linux sandbox helper implementation:
Integrator impact
workspace-write sandbox, shell commands may be able to write into .git and .codex if those directories reside under the writable workspace root.Mitigations
read-only sandbox if you must prevent any workspace mutation..git modifications if your threat model includes untrusted codebases.The Linux helper can fail and terminate (panic) if:
execvp fails.In such cases:
Integrator guidance
external or danger-full-access mode with your own sandbox boundary.Execpolicy is a rules engine that classifies shell commands and determines:
In exec mode, execpolicy becomes especially important because:
Execpolicy files are discovered by scanning config folders for each config layer, typically:
.codex folders (including nested repository layers)Policy discovery:
<config_folder>/rules/ for *.rules files.Critical edge case
.codex folder may still be included for execpolicy file discovery in the current implementation.codex execBecause exec mode never prompts:
Integrator guidance
If you depend on automation completing, you SHOULD:
You SHOULD treat execpolicy content as sensitive security configuration and manage it as code with auditing.
Codex records sessions under:
${CODEX_HOME}/sessions/<YYYY>/<MM>/<DD>/rollout-<timestamp>-<uuid>.jsonlThere is also an archive directory:
${CODEX_HOME}/sessions-archived/…When selecting the “most recent session” for resume/fork:
cwd matches the current working directory, unless an “all sessions” flag is used.Integrator guidance
Procedure:
codex exec --prompt <TEXT> as a subprocess.Procedure:
codex exec --json --prompt <TEXT>.thread_id, then turn_id.turn_completed.output.Procedure:
codex exec --output-schema <PATH> --json --prompt <TEXT>.item_completed and turn_completed, prefer structured data if present (implementation-dependent).Procedure:
codex exec --full-auto --json --prompt <TEXT>./tmp) unless you understand helper-path behavior.