# What Is the exec Directory in Codex? The Engine Behind Scriptable AI Execution

> Discover the exec directory in Codex and understand its role as an event-driven execution engine for scriptable AI. Learn about JSON output, sandbox policies, and automated approvals.

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

---

**The `exec/` directory implements the `codex exec` sub-command, providing an event-driven execution engine that runs prompts in non-interactive mode with support for JSON output, sandbox policies, and automated approvals.**

The OpenAI Codex CLI offers both interactive and scripted execution modes. While the TUI handles interactive sessions, the `exec/` directory within the `codex-rs` crate contains the backend implementation for headless, automation-friendly execution via the `codex exec` command.

## Core Responsibilities of the exec Directory

The `exec/` module is organized around a clear separation of concerns: parsing user input, orchestrating the execution session, and rendering output for either human or machine consumption.

### CLI Parsing and Argument Handling

The command-line interface for `codex exec` is defined in [`src/cli.rs`](https://github.com/openai/codex/blob/main/src/cli.rs). This file contains the `Cli` struct, the `Command` enum, and `ReviewArgs`, which collectively handle flags such as `--json` for JSONL output, `--full-auto` for automated approvals, and `--sandbox-mode` for policy configuration.

### Session Orchestration and Event Processing

The heart of the execution engine lives in [`src/lib.rs`](https://github.com/openai/codex/blob/main/src/lib.rs). The `run_exec_session` function (lines 1050–1120) creates a thread, sends the initial `UserTurn` or `Review` operation, and spawns listeners for thread events. This function manages the lifecycle of the Codex session, including graceful shutdown handling and OSS provider bootstrapping via `ensure_oss_provider_ready`.

### Output Rendering: Human vs. Machine Readable

The `exec/` directory provides two concrete implementations of the `EventProcessor` trait to handle streaming events from the Codex server:

- **`EventProcessorWithHumanOutput`** ([`src/event_processor_with_human_output.rs`](https://github.com/openai/codex/blob/main/src/event_processor_with_human_output.rs)): Renders colored text, progress cursors, and human-readable formatting for terminal output.
- **`EventProcessorWithJsonOutput`** ([`src/event_processor_with_jsonl_output.rs`](https://github.com/openai/codex/blob/main/src/event_processor_with_jsonl_output.rs)): Emits structured JSON-Lines (JSONL) for downstream automation when the `--json` flag is provided.

## Key Files in the exec Directory

| File | Purpose |
|------|---------|
| [`src/main.rs`](https://github.com/openai/codex/blob/main/src/main.rs) | Entry point that sets up tracing, loads configuration, and launches `run_exec_session`. |
| [`src/lib.rs`](https://github.com/openai/codex/blob/main/src/lib.rs) | Core orchestration logic including `run_exec_session`, `resolve_prompt`, and `load_output_schema`. |
| [`src/cli.rs`](https://github.com/openai/codex/blob/main/src/cli.rs) | CLI argument definitions (`Cli`, `Command`, `ReviewArgs`) and flag parsing. |
| [`src/event_processor.rs`](https://github.com/openai/codex/blob/main/src/event_processor.rs) | Trait definition `EventProcessor` and shared processing utilities. |
| [`src/event_processor_with_human_output.rs`](https://github.com/openai/codex/blob/main/src/event_processor_with_human_output.rs) | Human-readable event rendering with color and progress indicators. |
| [`src/event_processor_with_jsonl_output.rs`](https://github.com/openai/codex/blob/main/src/event_processor_with_jsonl_output.rs) | JSONL output mode for machine-readable pipelines. |
| [`src/exec_events.rs`](https://github.com/openai/codex/blob/main/src/exec_events.rs) | Event type definitions (`ExecEvent`, `EventMsg`) for the Codex server stream. |
| `tests/` | Unit and integration tests covering exec workflow, JSON output, sandbox handling, and prompt decoding. |

## How the Exec Engine Processes Prompts

The execution flow through the `exec/` directory follows a deterministic pipeline:

1. **Argument Resolution**: The `resolve_prompt` function handles prompt input from command-line arguments, stdin, or file paths, while `load_output_schema` validates any JSON schema constraints.
2. **Provider Initialization**: `ensure_oss_provider_ready` bootstraps the OSS provider if the `--oss` flag is enabled.
3. **Session Creation**: `run_exec_session` initializes a Codex thread and submits the initial `UserTurn` containing the resolved prompt.
4. **Event Streaming**: The system spawns listeners that receive `ExecEvent` structs from the Codex backend.
5. **Output Processing**: Depending on the `--json` flag, either `EventProcessorWithHumanOutput` or `EventProcessorWithJsonOutput` renders the final result, handling agent-job noise suppression and progress indicators as needed.

## Programmatic Usage Example

You can leverage the `exec/` crate directly in Rust to build custom automation tools. Below is a minimal example that mimics the internal behavior of `codex exec`:

```rust
use codex_exec::{Cli, run_main};
use codex_arg0::Arg0DispatchPaths;
use std::process;

#[tokio::main]
async fn main() {
    // Build a CLI struct as if the user typed:
    //   codex exec "Explain the Rust ownership model"
    let cli = Cli {
        command: None,
        images: vec![],
        model: None,
        oss: false,
        oss_provider: None,
        config_profile: None,
        full_auto: false,
        dangerously_bypass_approvals_and_sandbox: false,
        cwd: None,
        skip_git_repo_check: false,
        add_dir: vec![],
        ephemeral: false,
        color: codex_exec::cli::Color::Auto,
        last_message_file: None,
        json: false,
        sandbox_mode: None,
        prompt: Some("Explain the Rust ownership model".to_string()),
        output_schema: None,
        config_overrides: Default::default(),
        progress_cursor: false,
    };

    // Arg0 paths are auto-derived by the binary; here we use defaults.
    let arg0_paths = Arg0DispatchPaths::default();

    // Run the exec session. Errors are printed and cause a non-zero exit.
    if let Err(err) = run_main(cli, arg0_paths).await {
        eprintln!("Exec failed: {err}");
        process::exit(1);
    }
}

```

Running this binary produces the same output as the command-line invocation:

```bash
$ codex exec "Explain the Rust ownership model"

```

## Summary

- The `exec/` directory powers the **`codex exec`** sub-command for non-interactive, scriptable AI execution.
- It provides an **event-driven architecture** that streams `ExecEvent` structs from the Codex backend through processors for either human-readable or JSONL output.
- Key entry points include **`run_exec_session`** in [`src/lib.rs`](https://github.com/openai/codex/blob/main/src/lib.rs) for orchestration and **`run_main`** for CLI initialization.
- The module handles **sandbox policies**, **automated approvals** (`--full-auto`), and **OSS provider** bootstrapping for flexible deployment in CI/CD pipelines.

## Frequently Asked Questions

### What is the difference between `codex exec` and the interactive TUI?

The interactive TUI (located in the `tui/` directory) provides a rich, terminal-based user interface for conversational coding sessions. In contrast, `codex exec` (implemented in `exec/`) is a headless, non-interactive mode designed for automation, scripts, and CI/CD pipelines where no human interaction is required during execution.

### How do I get JSON output from `codex exec`?

Pass the `--json` flag when invoking the command. This activates `EventProcessorWithJsonOutput` in [`src/event_processor_with_jsonl_output.rs`](https://github.com/openai/codex/blob/main/src/event_processor_with_jsonl_output.rs), which emits structured JSON-Lines (JSONL) instead of human-readable text. This format is ideal for parsing by downstream tools or for storing structured execution logs.

### Can I use `codex exec` in CI/CD pipelines?

Yes. The `exec/` directory is specifically designed for this use case. By combining the `--json` flag for machine-readable output, `--full-auto` for automated approvals, and appropriate sandbox mode settings, you can integrate `codex exec` into GitHub Actions, GitLab CI, or other automation platforms to perform code reviews, generate documentation, or apply patches automatically.

### Where does `codex exec` handle sandbox policies?

Sandbox configuration is managed within the execution orchestration logic in [`src/lib.rs`](https://github.com/openai/codex/blob/main/src/lib.rs). The `Cli` struct defined in [`src/cli.rs`](https://github.com/openai/codex/blob/main/src/cli.rs) accepts a `sandbox_mode` parameter, and the session initialization code ensures the specified policy (or the default sandbox) is applied to all file system operations and command executions performed by the AI agent during the session.