> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/ComposioHQ/agent-orchestrator/llms.txt
> Use this file to discover all available pages before exploring further.

# Codex Agent Plugin

> Run OpenAI Codex CLI with PATH-based metadata wrappers and native thread resumption

The Codex agent plugin integrates OpenAI's Codex CLI, providing automatic metadata updates via shell wrappers, session introspection from JSONL rollout files, and native thread resumption.

## Overview

Codex is OpenAI's AI coding assistant CLI. The plugin:

* Automatically resolves the Codex binary (npm global, Homebrew, Cargo)
* Injects `~/.ao/bin` into PATH to wrap `gh` and `git` commands
* Updates metadata transparently when agents create PRs or switch branches
* Streams JSONL rollout files to extract token usage and session data
* Supports native thread resumption via `codex resume <thread-id>`

<Info>
  This plugin requires Codex CLI. Install from [OpenAI's repository](https://github.com/openai/codex-cli).
</Info>

## Installation

```bash theme={null}
# Install Codex (varies by distribution)
npm install -g codex-cli
# OR
brew install codex
# OR
cargo install codex-cli

# Verify installation
which codex
codex --version
```

## Configuration

Configure in `agent-orchestrator.yaml`:

```yaml theme={null}
plugins:
  agent: codex

projects:
  - name: my-project
    path: ~/code/my-project
    agentConfig:
      model: o4-mini
      permissions: auto-edit
      systemPromptFile: ~/prompts/senior-engineer.txt
```

### Configuration Options

<ParamField path="model" type="string">
  Codex model (e.g., `o4-mini`, `o3-mini`, `gpt-4-turbo`)
</ParamField>

<ParamField path="permissions" type="enum">
  Approval policy:

  * `skip`: Bypass all approvals and sandbox (`--dangerously-bypass-approvals-and-sandbox`)
  * `auto-edit`: Never ask (`--ask-for-approval never`)
  * `suggest`: Ask for untrusted operations only (`--ask-for-approval untrusted`)
</ParamField>

<ParamField path="systemPrompt" type="string">
  Developer instructions passed via `-c developer_instructions=...`
</ParamField>

<ParamField path="systemPromptFile" type="string">
  Path to instructions file (preferred for long prompts)
  Uses `-c model_instructions_file=...`
</ParamField>

## Automatic Metadata Updates

The plugin installs shell wrappers in `~/.ao/bin/` that intercept `gh` and `git` commands:

### Tracked Commands

| Command | Metadata Updated |
| - | - |
| `gh pr create` | `pr` (URL), `status` (pr\_open) |
| `git checkout -b <branch>` | `branch` |
| `git switch -c <branch>` | `branch` |
| `gh pr merge` | `status` (merged) |

<Accordion title="How PATH wrappers work">
  1. Plugin prepends `~/.ao/bin` to PATH during agent launch
  2. Wrapper scripts intercept `gh`/`git` commands
  3. Wrapper strips `~/.ao/bin` from PATH and calls the real binary
  4. On success, wrapper parses output and updates metadata via `update_ao_metadata()`
  5. All other commands pass through transparently

  The wrappers are installed once in `~/.ao/bin` and reused across all sessions.
</Accordion>

### Wrapper Scripts

**`~/.ao/bin/gh`**

```bash theme={null}
#!/usr/bin/env bash
# Intercepts: gh pr create, gh pr merge
# All other gh commands pass through

real_gh=$(PATH="$clean_path" command -v gh)
exec "$real_gh" "$@"
# (simplified — actual script includes output parsing)
```

**`~/.ao/bin/git`**

```bash theme={null}
#!/usr/bin/env bash
# Intercepts: git checkout -b, git switch -c
# All other git commands pass through

real_git=$(PATH="$clean_path" command -v git)
exec "$real_git" "$@"
```

**`~/.ao/bin/ao-metadata-helper.sh`**

```bash theme={null}
# Provides: update_ao_metadata <key> <value>
# Atomically updates session metadata files
```

<Note>
  Wrappers are versioned. The plugin only rewrites them if `.ao-version` marker changes, minimizing disk writes.
</Note>

## Session Introspection

Codex stores session data in date-sharded JSONL files:

```
~/.codex/sessions/
  2026/
    03/
      04/
        rollout-abc123.jsonl
        rollout-def456.jsonl
```

### Finding Session Files

The plugin:

1. Recursively scans `~/.codex/sessions/` (max depth 4)
2. Reads the first 4 KB of each `.jsonl` file
3. Matches `session_meta` entries where `cwd` equals the workspace path
4. Returns the most recently modified matching file

<Warning>
  For large projects with many Codex sessions, the initial scan can take 1-2 seconds. Results are cached for 30 seconds.
</Warning>

### Extracting Data

The plugin streams JSONL files line-by-line (never loads entire file into memory):

```typescript theme={null}
interface CodexSessionData {
  model: string | null;          // From session_meta
  threadId: string | null;       // For resume support
  inputTokens: number;           // Aggregated from token_count events
  outputTokens: number;
}
```

### Cost Estimation

Token usage is aggregated from `event_msg` lines with `type: "token_count"`:

```json theme={null}
{
  "type": "event_msg",
  "msg": {
    "type": "token_count",
    "input_tokens": 5000,
    "output_tokens": 1200
  }
}
```

Estimated cost uses GPT-4 Turbo pricing ($2.50/1M input, $10/1M output) as a baseline.

<Note>
  Cost estimates are approximate. For accurate billing, check OpenAI's usage dashboard.
</Note>

## Usage Examples

### Spawn an Agent

```bash theme={null}
ao spawn my-project "Implement user authentication"
```

The orchestrator:

1. Resolves the Codex binary (cached after first call)
2. Creates workspace and sets up wrappers
3. Launches Codex with prompt included in command
4. Monitors session file mtime for activity

### Resume a Thread

```bash theme={null}
ao resume my-project agent-123
```

The plugin extracts the `threadId` from the session JSONL and builds:

```bash theme={null}
codex resume abc-123-def-456 --model o4-mini --ask-for-approval never
```

### Check Session Cost

```bash theme={null}
ao list --verbose
```

Output:

```
my-project/agent-123
  Status: active
  Summary: Codex session (o4-mini)
  Cost: $0.45 (50K input, 12K output)
```

## Advanced Features

### Binary Resolution

The plugin auto-detects Codex installation on first launch:

1. Try `which codex`
2. Check common locations:
   * `/usr/local/bin/codex` (Homebrew Intel)
   * `/opt/homebrew/bin/codex` (Homebrew ARM)
   * `~/.cargo/bin/codex` (Cargo)
   * `~/.npm/bin/codex` (npm global)
3. Fallback to `"codex"` (let shell resolve)

Resolved path is cached for the lifetime of the agent instance.

### Reasoning Models (o-series)

The plugin auto-detects o-series models and enables reasoning:

```typescript theme={null}
if (/^o[34]/i.test(model)) {
  parts.push("-c", "model_reasoning_effort=high");
}
```

This sets `model_reasoning_effort=high` for o3/o4 models automatically.

### Session File Caching

To avoid redundant filesystem scans, the plugin caches session file paths:

```typescript theme={null}
const SESSION_FILE_CACHE_TTL_MS = 30_000;
const sessionFileCache = new Map<string, { path: string | null; expiry: number }>();
```

Cache is shared across `getActivityState()` and `getSessionInfo()` calls.

### AGENTS.md Integration

The plugin appends a section to `AGENTS.md` in each workspace:

````markdown theme={null}
## Agent Orchestrator (ao) Session

You are running inside an Agent Orchestrator managed workspace.
Session metadata is updated automatically via shell wrappers.

If automatic updates fail, you can manually update metadata:
```bash
~/.ao/bin/ao-metadata-helper.sh
# Then call: update_ao_metadata <key> <value>
````

This serves as a secondary signal if PATH wrappers are bypassed.

## Troubleshooting

<AccordionGroup>
  <Accordion title="Wrappers not intercepting commands">
    **Cause**: PATH not set correctly or wrappers not executable

    **Solution**:

    1. Check if `~/.ao/bin` is first in PATH:
       ```bash theme={null}
       echo $PATH | tr ':' '\n' | head -1
       ```
    2. Verify wrappers are executable:
       ```bash theme={null}
       ls -l ~/.ao/bin/gh
       chmod +x ~/.ao/bin/gh ~/.ao/bin/git
       ```
    3. Check if real binaries exist:
       ```bash theme={null}
       which -a gh  # Should show wrapper first, then real binary
       ```
  </Accordion>

  <Accordion title="Session file not found">
    **Cause**: No Codex session created yet, or cwd mismatch

    **Solution**:

    1. Check if Codex has created any sessions:
       ```bash theme={null}
       ls -lR ~/.codex/sessions/
       ```
    2. Verify workspace path matches session\_meta cwd:
       ```bash theme={null}
       head -5 ~/.codex/sessions/2026/03/04/rollout-*.jsonl | grep session_meta
       ```
    3. Wait for Codex to make its first API call (session files are created lazily)
  </Accordion>

  <Accordion title="Binary resolution fails">
    **Cause**: Codex installed in non-standard location

    **Solution**: Add Codex to PATH or create a symlink:

    ```bash theme={null}
    # Option 1: Add to PATH in shell config
    export PATH="/custom/path/to/codex:$PATH"

    # Option 2: Symlink to standard location
    ln -s /custom/path/to/codex /usr/local/bin/codex
    ```
  </Accordion>

  <Accordion title="Metadata updates not persisting">
    **Cause**: AO\_DATA\_DIR or AO\_SESSION environment variables not set

    **Solution**: Check agent environment:

    ```bash theme={null}
    # In agent workspace
    echo $AO_DATA_DIR
    echo $AO_SESSION

    # Should be set by orchestrator during launch
    ```

    Verify metadata file exists:

    ```bash theme={null}
    ls -l "$AO_DATA_DIR/$AO_SESSION"
    ```
  </Accordion>

  <Accordion title="Activity detection shows 'idle' when agent is working">
    **Cause**: Codex writes to session file in bursts, not continuously

    **Solution**: This is expected. Activity detection uses file mtime, which only updates when Codex makes API calls or writes events. During long reasoning periods (o-series models), the file may not be modified. Check process status with `ao status <session>` for ground truth.
  </Accordion>
</AccordionGroup>

## Comparison with Other Agents

| Feature | Codex | Claude Code | Aider | OpenCode |
| - | - | - | - | - |
| **Provider** | OpenAI | Anthropic | Aider.chat | OpenCode |
| **Auto-metadata** | ✅ PATH wrappers | ✅ PostToolUse hooks | ❌ None | ❌ None |
| **Cost Tracking** | ✅ Full | ✅ Full | ❌ None | ❌ None |
| **Resume Support** | ✅ Native | ✅ Native | ❌ None | ❌ None |
| **Binary Resolution** | ✅ Auto | ❌ Manual (must be in PATH) | ❌ Manual | ❌ Manual |
| **Session Files** | JSONL (date-sharded) | JSONL (path-encoded) | Markdown | SQLite |
| **Activity Detection** | ✅ File mtime | ✅ JSONL events | ⚠️ Git commits | ❌ None |

## Environment Variables

The plugin sets these variables in the agent environment:

<ParamField path="AO_SESSION_ID" type="string" required>
  Session identifier for metadata lookups
</ParamField>

<ParamField path="AO_PROJECT_ID" type="string">
  Project identifier (set by caller, not the plugin)
</ParamField>

<ParamField path="AO_ISSUE_ID" type="string">
  Issue/ticket identifier if applicable
</ParamField>

<ParamField path="PATH" type="string" required>
  Prepended with `~/.ao/bin` to enable command interception
</ParamField>

<Warning>
  Do not modify PATH in workspace setup scripts (`.bashrc`, `.zshrc`) as it may interfere with wrapper priority.
</Warning>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.