# How the OpenAI Codex CLI exec Command Works for Non-Interactive Execution

> Learn how the codex exec command enables non-interactive execution by parsing arguments, initializing sandboxed environments, and processing AI responses.

- Repository: [OpenAI/codex](https://github.com/openai/codex)
- Tags: internals
- Published: 2026-03-06

---

**The `codex exec` command provides a non-interactive interface that parses CLI arguments, initializes sandboxed execution environments, and streams AI-generated responses through specialized event processors to stdout or designated output files.**

The `codex exec` command serves as the primary **non-interactive entry point** for the OpenAI Codex CLI, enabling automated, scriptable AI workflows without interactive approval loops. Located in the `openai/codex` repository, this command orchestrates a Rust-based pipeline that transforms command-line prompts into sandboxed executions, supporting JSONL streams, human-readable output, and session resumption for CI/CD integration.

## CLI Argument Parsing and Configuration

The execution flow begins in **[`codex-rs/exec/src/cli.rs`](https://github.com/openai/codex/blob/main/codex-rs/exec/src/cli.rs)**, which defines the `ExecCli` struct responsible for parsing all command-line flags. This parser collects global options including `--model` for provider selection, `--sandbox` for security policy configuration, and output modifiers like `--json` and `--output-last-message`.

Key flags processed here include:

- `--sandbox` – Specifies the security boundary (`workspace-write`, `workspace-read`, etc.)
- `--dangerously-bypass-approvals-and-sandbox` – Allows automated execution without interactive confirmation
- `--json` – Enables JSONL output mode for downstream tooling
- `--output-last-message` – Designates a file path to capture the final agent response
- `--progress-cursor` – Activates cursor-based progress updates for terminal UIs

## Entry Point Dispatch in the Main CLI

In **[`codex-rs/cli/src/main.rs`](https://github.com/openai/codex/blob/main/codex-rs/cli/src/main.rs)**, the top-level CLI router matches the `Subcommand::Exec` variant and forwards the parsed configuration to the execution engine. The dispatcher extracts the `ExecCli` instance, merges global configuration overrides, and invokes the asynchronous entry point:

```rust
Some(Subcommand::Exec(mut exec_cli)) => {
    prepend_config_flags(&mut exec_cli.config_overrides, root_config_overrides);
    codex_exec::run_main(exec_cli, arg0_paths.clone()).await?;
}

```

This delegation pattern isolates the non-interactive execution logic within the `codex_exec` crate while maintaining a clean separation between CLI parsing and runtime implementation.

## Runtime Initialization and Sandbox Setup

The **[`codex-rs/exec/src/lib.rs`](https://github.com/openai/codex/blob/main/codex-rs/exec/src/lib.rs)** file contains the `run_main` function, which constructs the execution environment before starting the AI agent loop. This initialization phase performs four critical operations:

1. **Model Resolution** – Selects the appropriate backend (OpenAI, OSS, or local providers) based on CLI flags and environment configuration
2. **Policy Configuration** – Establishes the **sandbox policy** controlling filesystem access and the **approval policy** determining whether command execution requires user confirmation (`on-request`) or proceeds automatically (`always-allow`)
3. **Asset Pre-loading** – Loads image attachments, output schemas, and terminal color preferences into the agent context
4. **Agent Thread Initialization** – Spawns the background thread that communicates with the Codex backend and emits event streams containing token usage, command executions, and status updates

## Event Processing and Output Streaming

The core execution loop resides in **[`codex-rs/exec/src/event_processor.rs`](https://github.com/openai/codex/blob/main/codex-rs/exec/src/event_processor.rs)**, with specialized variants in **[`event_processor_with_jsonl_output.rs`](https://github.com/openai/codex/blob/main/event_processor_with_jsonl_output.rs)** and **[`event_processor_with_human_output.rs`](https://github.com/openai/codex/blob/main/event_processor_with_human_output.rs)**. These processors handle the bidirectional communication between the local sandbox and the remote model.

The event processor:

- Streams the user prompt (or resumed session context) to the model backend
- Receives generated commands and executes them under the configured sandbox constraints
- Manages approval workflows when the policy requires explicit permission
- Formats output according to the selected mode:
  - **Human-readable** – Colored, line-by-line terminal output with progress indicators
  - **JSONL** – Structured JSON Lines format via `--json` for machine parsing
  - **Progress cursor** – Minimal terminal updates for non-TTY environments

Upon completion, the processor returns an **`AppExitInfo`** structure containing token consumption metrics, the session thread ID, and any requested update actions. The CLI prints a resume hint (`codex resume <thread-id>`) and exits with the appropriate status code.

## Practical Usage Examples

The following commands demonstrate the non-interactive execution patterns supported by the `codex exec` implementation:

```bash

# Simple one-off command execution

codex exec "ls -la"

# Automated npm install with workspace write permissions and no approval prompts

codex exec --sandbox workspace-write --dangerously-bypass-approvals-and-sandbox \
          "npm install"

# JSONL output for integration with build scripts

codex exec --json "git status"

# Capture final agent response to a file for downstream processing

codex exec -o ./final_message.txt "Summarize the repository structure"

# Resume a previous session and append a new prompt

codex exec resume 123e4567-e89b-12d3-a456-426614174000 "Continue fixing the bug"

```

## Summary

- The **`codex exec` command** acts as a thin orchestration layer for non-interactive AI execution in the OpenAI Codex CLI.
- **Argument parsing** occurs in [`codex-rs/exec/src/cli.rs`](https://github.com/openai/codex/blob/main/codex-rs/exec/src/cli.rs) via the `ExecCli` struct, capturing model selection, sandbox policies, and output formats.
- **Command dispatch** happens in [`codex-rs/cli/src/main.rs`](https://github.com/openai/codex/blob/main/codex-rs/cli/src/main.rs), which delegates to `codex_exec::run_main` for execution.
- **Runtime initialization** in [`codex-rs/exec/src/lib.rs`](https://github.com/openai/codex/blob/main/codex-rs/exec/src/lib.rs) configures sandboxes, approval policies, and model providers before spawning the agent thread.
- **Event processing** in [`codex-rs/exec/src/event_processor.rs`](https://github.com/openai/codex/blob/main/codex-rs/exec/src/event_processor.rs) handles the model communication loop, command execution, and formatted output generation (human, JSONL, or cursor-based).
- The command returns structured exit information including thread IDs for session resumption and token usage statistics.

## Frequently Asked Questions

### What distinguishes `codex exec` from interactive Codex CLI modes?

**`codex exec`** is designed for automation and scripting, bypassing the interactive approval loops required by the standard TUI mode. According to the source code in [`codex-rs/exec/src/lib.rs`](https://github.com/openai/codex/blob/main/codex-rs/exec/src/lib.rs), it initializes the agent thread with pre-configured approval policies (such as `always-allow` when combined with `--dangerously-bypass-approvals-and-sandbox`), enabling unattended execution in CI/CD pipelines.

### How can I parse `codex exec` output programmatically?

Use the **`--json`** flag to enable JSONL output mode handled by [`codex-rs/exec/src/event_processor_with_jsonl_output.rs`](https://github.com/openai/codex/blob/main/codex-rs/exec/src/event_processor_with_jsonl_output.rs). This emits each event—token usage, command execution, and final responses—as newline-delimited JSON objects suitable for parsing with `jq` or ingestion into logging systems.

### Can I resume a session started with `codex exec`?

Yes. The command returns an **`AppExitInfo`** structure containing the thread ID, which the CLI prints as a resume hint. You can pass this ID to `codex exec resume <thread-id>` followed by a new prompt, as implemented in the CLI parser in [`codex-rs/exec/src/cli.rs`](https://github.com/openai/codex/blob/main/codex-rs/exec/src/cli.rs), allowing non-interactive workflows to maintain context across multiple invocations.

### What sandbox options are available for `codex exec`?

The **`--sandbox`** flag accepts policies including `workspace-write`, `workspace-read`, and other filesystem restrictions defined in the execution configuration. These policies are enforced during the event processing loop in [`codex-rs/exec/src/event_processor.rs`](https://github.com/openai/codex/blob/main/codex-rs/exec/src/event_processor.rs), determining whether the AI-generated commands can modify the local filesystem or operate in read-only environments.