Doramagic Project Pack · Human Manual

codex

Codex CLI serves as the primary interface for interacting with OpenAI's coding agent capabilities directly from the terminal. The Rust implementation (codex-rs) is the maintained codebase ...

Getting Started with Codex

Related topics: Installation Guide, System Architecture Overview

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Key Capabilities

Continue reading this section for the full explanation and source context.

Section Package Manager Installation

Continue reading this section for the full explanation and source context.

Section Verifying Installation

Continue reading this section for the full explanation and source context.

Related topics: Installation Guide, System Architecture Overview

Getting Started with Codex

Codex CLI is a coding agent from OpenAI that runs locally on your computer. It provides an intelligent command-line interface that understands your codebase, assists with coding tasks, and integrates seamlessly with your development workflow.

Overview

Codex CLI serves as the primary interface for interacting with OpenAI's coding agent capabilities directly from the terminal. The Rust implementation (codex-rs) is the maintained codebase and serves as the default experience for all users.

Key Capabilities

FeatureDescription
Code UnderstandingAnalyzes and understands your codebase context
Multi-file EditingReads and modifies files across your project
Shell Command ExecutionRuns terminal commands on your behalf
Git IntegrationShows diffs, manages branches, and tracks changes
IDE ContextIncludes selections, open files, and IDE context
Session ManagementResumes, forks, and manages coding sessions

Sources: README.md:1-15

Installation

Codex CLI can be installed using multiple package managers. The recommended methods are npm and Homebrew.

Package Manager Installation

# Install using npm
npm install -g @openai/codex
# Install using Homebrew
brew install --cask codex

Alternatively, you can download platform-specific releases directly from the GitHub Releases page.

Sources: README.md:18-32

Verifying Installation

After installation, verify Codex is properly installed by running:

codex

This launches the interactive terminal interface.

Sources: codex-rs/README.md:8-15

Quick Start Workflow

graph TD
    A[Install Codex] --> B[Run codex command]
    B --> C[Configure API Access]
    C --> D[Create or Resume Session]
    D --> E[Start Coding Task]
    E --> F[Review Changes]
    F --> G[Apply or Iterate]

Starting Your First Session

  1. Run codex in your terminal
  2. Codex initializes the TUI (Terminal User Interface)
  3. Configure your API access when prompted
  4. Start interacting with the agent

Sources: docs/getting-started.md

Slash Commands Reference

Codex provides numerous slash commands for controlling the agent's behavior. Access these by typing / in the chat interface.

CommandPurpose
/resumeResume a saved chat session
/clearClear the terminal and start a new chat
/forkFork the current chat into a new session
/quit or /exitExit Codex
/modelChoose what model and reasoning effort to use
/ideInclude current selection, open files, and IDE context
/themeChoose a syntax highlighting theme
/diffShow git diff including untracked files
/permissionsChoose what Codex is allowed to do
/statusShow current session configuration and token usage

Sources: codex-rs/tui/src/slash_command.rs:1-50

Experimental Commands

CommandPurpose
/realtimeToggle realtime voice mode
/collabChange collaboration mode
/mcpList configured MCP tools
/settingsConfigure realtime microphone/speaker

Sources: codex-rs/tui/src/slash_command.rs:45-70

Configuration System

Codex uses a layered configuration system with config.toml (not config.json as in legacy versions). Configuration layers are applied in order of precedence.

graph LR
    A[System Config] --> B[User Config]
    B --> C[Project Config]
    C --> D[Session Flags]
    D --> E[Effective Config]
    
    style A fill:#ffcccc
    style B fill:#ccffcc
    style C fill:#ccccff
    style D fill:#ffffcc

Configuration Layer Precedence

LayerSourcePrecedence
SystemSystem-wide config fileLowest
UserUser home directory configMedium
Project.codex/config.toml in projectHigh
SessionCommand-line flagsHighest

Sources: codex-rs/config/src/state.rs:1-30

Configuration Files

FileLocationPurpose
config.tomlUser/system/project dirsMain configuration
.codex/Project rootProject-specific settings
hooks.toml.codex/ folderLifecycle hook definitions

Sources: codex-rs/README.md:20-35

Terminal User Interface

Status Line Elements

The TUI displays important information in the status line:

ElementDescription
ModelCurrent model and reasoning effort
ContextContext window usage percentage
TokensTotal input/output token counts
Git BranchCurrent branch and change stats
PermissionsCurrent permission level
Session IDUnique identifier for the session

Sources: codex-rs/tui/src/chatwidget/status_surfaces.rs:1-40

Status Line Accents

Status line items use semantic color coding:

Accent TypeScopesDefault Color
ModelKeywords, storage typesCyan
StateGeneral UI stateCyan
UsageToken and progress infoGreen
BranchGit-related infoMagenta
ThreadConversation threadingMagenta

Sources: codex-rs/tui/src/bottom_pane/status_line_style.rs:1-30

Keyboard Shortcuts

Codex supports extensive keyboard shortcuts for navigation and control.

Core Navigation

ActionDefault Binding
NewlineEnter
Queue MessageTab
File PathsCtrl+Shift+P
Paste ImageCtrl+Shift+V
External EditorCtrl+E
Edit PreviousCtrl+Up
History SearchCtrl+R
QuitCtrl+C

Pager Controls

ActionKey
Move UpArrow Up / k
Move DownArrow Down / j
Jump to Topg
Jump to BottomG
Closeq / Escape

Sources: codex-rs/tui/src/bottom_pane/footer.rs:1-50

Vim Mode

Vim mode can be toggled for the composer using /vim. This enables Vim-style editing for composing messages.

Sources: codex-rs/tui/src/slash_command.rs:55

Model Context Protocol (MCP) Support

MCP Client

Codex CLI functions as an MCP client, allowing connections to MCP servers on startup. Configure MCP servers in your config.toml:

[mcp]
servers = ["my-mcp-server"]

Use /mcp to list configured MCP tools and /mcp verbose for detailed information.

MCP Server (Experimental)

Codex can be launched as an MCP server by running:

codex mcp-server

This allows other MCP clients to interact with Codex.

Sources: codex-rs/README.md:40-55

Environment Context

Codex automatically captures environment information to provide context to the agent:

<environment>
  <cwd>/path/to/project</cwd>
  <shell>bash</shell>
</environment>
<subagents>
  <!-- Subagent information -->
</subagents>

Sources: codex-rs/core/src/context/environment_context.rs:1-30

Profiles

Codex supports multiple configuration profiles for different environments or use cases.

Profile Features

FeatureDescription
model_instructions_fileCustom instructions for the model
experimental_compact_prompt_fileCompact prompt template
tui.session_picker_viewLayout preference for session picker
featuresProfile-scoped feature toggles

Sources: codex-rs/config/src/profile_toml.rs:1-50

Next Steps

Sources: codex-rs/README.md:15-25

Sources: README.md:1-15

System Architecture Overview

Related topics: Agent System, Terminal UI, Command Execution

Section Related Pages

Continue reading this section for the full explanation and source context.

Section 3.1 Core Library (codex-rs/core)

Continue reading this section for the full explanation and source context.

Section 3.2 Environment Context

Continue reading this section for the full explanation and source context.

Section 3.3 Goals Manager

Continue reading this section for the full explanation and source context.

Related topics: Agent System, Terminal UI, Command Execution

System Architecture Overview

1. Introduction

The Codex CLI is a coding agent from OpenAI that operates locally on a developer's computer. The system is primarily implemented in Rust and provides a terminal-based user interface for interacting with AI-powered code assistance. The architecture follows a modular design pattern with clear separation between core logic, configuration management, protocol definitions, and UI components.

Sources: codex-rs/README.md:1-10

2. High-Level Architecture

The Codex system is composed of several interconnected modules that work together to provide a seamless coding experience:

graph TD
    subgraph "Presentation Layer"
        TUI[TUI Module<br/>codex-rs/tui]
        MARKDOWN[Markdown Renderer]
        STATUS[Status Surfaces]
    end
    
    subgraph "Core Logic"
        CORE[Core Module<br/>codex-rs/core]
        GOALS[Goals Manager]
        ENV[Environment Context]
    end
    
    subgraph "Configuration"
        CONFIG[Config Module<br/>codex-rs/config]
        STATE[State Management]
        PROFILE[Profile TOML]
    end
    
    subgraph "Protocol Layer"
        SERVER[App Server<br/>codex-rs/app-server]
        PROTOCOL[App Server Protocol]
    end
    
    TUI --> CORE
    TUI --> STATUS
    TUI --> MARKDOWN
    CORE --> GOALS
    CORE --> ENV
    CONFIG --> STATE
    PROTOCOL --> SERVER
    SERVER --> CORE

Sources: codex-rs/core/src/lib.rs

3. Core Modules

3.1 Core Library (`codex-rs/core`)

The core library contains the fundamental business logic for the Codex agent. It handles:

  • Environment context management
  • Goals and objective tracking
  • Session state management
  • Task execution and orchestration

Sources: codex-rs/core/src/lib.rs

3.2 Environment Context

The environment context module captures and reports system state to the AI model:

ComponentDescription
current_dateSystem date and time
timezoneSystem timezone
shellActive shell configuration
cwdCurrent working directory
subagentsRunning subagent processes

Sources: codex-rs/core/src/context/environment_context.rs:1-50

3.3 Goals Manager

The goals module handles long-running task management with budget tracking:

  • Objective tracking and updates
  • Budget limit enforcement
  • Terminal metric emission control
  • External goal mutation handling
#[derive(Clone)]
pub struct ExternalGoalPreviousGoal {
    goal_id: String,
    status: codex_state::ThreadGoalStatus,
    objective: String,
}

Sources: codex-rs/core/src/goals.rs:1-60

4. Configuration System

4.1 Configuration Layer Architecture

The configuration system uses a layered approach with precedence ordering:

graph TD
    A[Session Flags<br/>Highest Priority] --> B[MDM Managed]
    B --> C[User Config]
    C --> D[Project Config]
    D --> E[System Config<br/>Lowest Priority]
    
    F[Legacy Configs] --> A

Sources: codex-rs/config/src/state.rs:50-100

4.2 Configuration Layer Sources

LayerSourcePriority
SessionFlagsCommand-line argumentsHighest
MdmMobile Device Management-
UserUser home directory-
Project.codex/ folder-
SystemSystem-wide configLowest

Sources: codex-rs/config/src/state.rs:30-48

4.3 Key Configuration Options

OptionTypeDescription
hide_agent_reasoningboolHide AgentReasoning events from UI
show_raw_agent_reasoningboolShow raw reasoning content
model_reasoning_effortOption<ReasoningEffort>Model reasoning configuration
commit_attributionOption<String>Git commit co-author text
model_instructions_fileOption<AbsolutePathBuf>Custom model instructions

Sources: codex-rs/config/src/config_toml.rs:100-150

5. TUI (Terminal User Interface) Architecture

5.1 Component Overview

The TUI module provides the terminal-based user interface:

graph LR
    A[Slash Commands] --> B[Chat Widget]
    B --> C[Status Surfaces]
    C --> D[Footer/Shortcuts]
    B --> E[Markdown Renderer]

Sources: codex-rs/tui/src/slash_command.rs

5.2 Slash Commands

Codex supports extensive slash commands for user interaction:

CommandDescription
/resumeResume a saved chat
/clearClear terminal and start new chat
/forkFork the current chat
/modelChoose model and reasoning effort
/ideInclude IDE context
/mcpList configured MCP tools
/settingsConfigure realtime microphone/speaker
/planSwitch to Plan mode
/goalSet/view goal for long-running task
/collabChange collaboration mode

Sources: codex-rs/tui/src/slash_command.rs:1-80

5.3 Status Surfaces

Status surfaces display various system information:

Status ItemDisplay Format
AppNameApplication name
ProjectNameCurrent project name
GitBranchCurrent branch name
PullRequestNumberPR #123
BranchChanges+12 -3
ContextUsedContext 0% used
Modelgpt-5.2-codex
TaskProgressTasks 0/0

Sources: codex-rs/tui/src/status_surfaces.rs:1-60

5.4 Markdown Rendering

The TUI includes a custom markdown renderer supporting:

  • Fenced code blocks with language detection
  • Tables and list formatting
  • Links and emphasis styles
  • Footnotes and character entities
let lang = match kind {
    CodeBlockKind::Fenced(lang) => Some(lang.to_string()),
    CodeBlockKind::Indented => None,
};

Sources: codex-rs/tui/src/markdown_render.rs:1-80

6. Protocol Layer

6.1 App Server Protocol

The protocol layer defines communication between components:

graph TD
    subgraph "App Server Protocol"
        APPS[Apps Module]
        GUARDIAN[Guardian/Risk Assessment]
        APPROVALS[Approvals]
    end
    
    subgraph "Risk Levels"
        LOW[Low]
        MEDIUM[Medium]
        HIGH[High]
        CRITICAL[Critical]
    end
    
    APPS --> GUARDIAN
    GUARDIAN --> RISK{Risk Level}
    RISK --> LOW
    RISK --> MEDIUM
    RISK --> HIGH
    RISK --> CRITICAL

Sources: codex-rs/app-server-protocol/src/protocol/v2/apps.rs

6.2 App Information Model

pub struct AppInfo {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub logo_url: Option<String>,
    pub is_accessible: bool,
    pub is_enabled: bool,
    pub plugin_display_names: Vec<String>,
}

Sources: codex-rs/app-server-protocol/src/protocol/v2/apps.rs:50-80

7. Approval and Guardian System

7.1 Risk Assessment Flow

The chat widget handles risk level assessment and user authorization:

graph TD
    A[Review Request] --> B{Risk Level}
    B -->|Low| C[Auto Approve]
    B -->|Medium| D[Request Authorization]
    B -->|High| E[Require Explicit Approval]
    B -->|Critical| F[Block Action]
    
    G[GuardianUserAuthorization] --> H[Agent]
    G --> I[Medium]
    G --> J[High]

Sources: codex-rs/tui/src/chatwidget.rs:1-50

7.2 Guardian Risk Levels

LevelEnum ValueAction
LowGuardianRiskLevel::LowAuto proceed
MediumGuardianRiskLevel::MediumWarn user
HighGuardianRiskLevel::HighRequire confirmation
CriticalGuardianRiskLevel::CriticalBlock action

Sources: codex-rs/tui/src/chatwidget.rs:1-40

8. Profile System

8.1 Profile Configuration

Profiles allow scoped configuration settings:

SettingScopeDescription
session_picker_viewTUILayout for resume/fork session picker
featuresProfileFeature toggles scoped to profile
tuiProfileTUI settings

Sources: codex-rs/config/src/profile_toml.rs:50-100

9. Data Flow Summary

sequenceDiagram
    participant User
    participant TUI
    participant Core
    participant Config
    participant Server
    
    User->>TUI: Input command
    TUI->>Config: Load config layers
    Config-->>TUI: Resolved config
    TUI->>Core: Process request
    Core->>Server: Protocol request
    Server-->>Core: Response
    Core-->>TUI: Rendered output
    TUI-->>User: Display result

10. Summary

The Codex CLI architecture demonstrates a well-structured system with:

  1. Separation of concerns: Clear boundaries between TUI, core logic, configuration, and protocol layers
  2. Layered configuration: Supports multiple config sources with defined precedence
  3. Extensible command system: Slash commands for rich user interaction
  4. Comprehensive status reporting: Multiple status surfaces for system awareness
  5. Safety mechanisms: Guardian/approval system for risk management

This modular design enables maintainability, testability, and future extensibility of the codebase.

Sources: codex-rs/README.md

Sources: codex-rs/README.md:1-10

Installation Guide

Related topics: Getting Started with Codex

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Package Managers

Continue reading this section for the full explanation and source context.

Section Manual Binary Installation

Continue reading this section for the full explanation and source context.

Section macOS

Continue reading this section for the full explanation and source context.

Related topics: Getting Started with Codex

Installation Guide

Overview

The Codex CLI is a coding agent from OpenAI that runs locally on your computer. This guide covers all supported installation methods, platform-specific considerations, and post-installation configuration steps.

The Rust implementation serves as the default and maintained CLI experience, replacing the legacy TypeScript implementation. It provides a zero-dependency standalone executable with enhanced features including Model Context Protocol (MCP) support, rich configuration options via config.toml, and improved performance. Sources: codex-rs/README.md:1-15

Installation Methods

Package Managers

#### npm (Recommended)

Install globally using npm for cross-platform compatibility:

npm i -g @openai/codex

This method automatically handles platform detection and binary management. Sources: README.md:8

#### Homebrew (macOS/Linux)

For systems with Homebrew installed:

brew install --cask codex

This installs the macOS or Linux binary to your Homebrew prefix. Sources: README.md:9

Manual Binary Installation

For users preferring manual installation or environments without package managers, download platform-specific binaries from the GitHub Releases page.

#### Available Binaries

PlatformArchitectureFilename
macOSApple Silicon (arm64)codex-aarch64-apple-darwin.tar.gz
macOSx86_64 (Intel)codex-x86_64-apple-darwin.tar.gz
Linuxx86_64codex-x86_64-unknown-linux-musl.tar.gz
Linuxarm64codex-aarch64-unknown-linux-musl.tar.gz

Each archive contains a single executable with the platform baked into the filename. After extraction, rename the binary to codex and ensure it's in your system PATH. Sources: README.md:26-45

# Example: Linux x86_64 installation
tar -xzf codex-x86_64-unknown-linux-musl.tar.gz
mv codex-x86_64-unknown-linux-musl /usr/local/bin/codex
chmod +x /usr/local/bin/codex

Platform-Specific Considerations

macOS

Requirements:

  • macOS 11 (Big Sur) or later
  • Apple Silicon (M1/M2/M3) or Intel processor
  • Xcode Command Line Tools for Git integration

Installation Steps:

  1. Install via npm or Homebrew (recommended)
  2. Or download the appropriate binary from GitHub Releases
  3. Grant terminal access when prompted for the first time

The macOS binary is signed and notarized for standard installation without security workarounds. Sources: MODULE.bazel:1-50

Linux

Requirements:

  • glibc 2.17+ or musl-based distribution
  • Git installed and available in PATH
  • Terminal with color support (for optimal TUI experience)

Installation Steps:

  1. Download the appropriate binary for your architecture
  2. Extract and place in a directory in your PATH
  3. Ensure execute permissions: chmod +x codex
# Verify installation
codex --version

Development Container

For contributors, a Dev Container configuration is available:

{
  "name": "Codex Development",
  "image": "mcr.microsoft.com/devcontainers/rust:latest",
  "features": {
    "ghcr.io/devcontainers/features/node:latest": {}
  }
}

The Dev Container includes Rust toolchain and Node.js for full-stack development. Sources: .devcontainer/devcontainer.json:1-20

Post-Installation Configuration

Initial Setup

After installation, run codex to start the interactive setup:

codex

On first launch, you'll be prompted to:

  1. Sign in with your ChatGPT account
  2. Configure workspace permissions
  3. Set up initial preferences

Authentication

Codex supports multiple login methods configurable via settings:

Login MethodDescription
ChatGPTSign in with ChatGPT (Plus, Pro, Business, Edu, or Enterprise)
API KeyUse OpenAI API credentials directly

The preferred backend for storing CLI auth credentials can be configured:

# config.toml
auth_storage_backend = "keyring"  # or "file" (default), "auto"

Sources: codex-rs/config/src/config_toml.rs:80-95

Configuration Files

Codex uses a layered configuration system with the following precedence (highest to lowest):

graph TD
    A[Session Flags] --> B[Project Config]
    B --> C[User Config]
    C --> D[System Config]
    D --> E[MDM Managed Preferences]
    
    F[Config.toml location varies by layer]
Config LayerLocationPriority
Session FlagsCommand-line argumentsHighest
Project.codex/config.tomlHigh
User~/.config/codex/config.tomlMedium
System/etc/codex/config.tomlLow
MDMManaged preferencesLowest

The Rust CLI uses config.toml (not config.json as in the legacy TypeScript CLI). Sources: codex-rs/README.md:20-25

Configuration Options

Key installation-related configuration options:

# Optional: Override Codex home directory
codex_home = "/custom/path"

# SQLite database storage
sqlite_home = "$CODEX_SQLITE_HOME"  # or falls back to $CODEX_HOME

# Log directory (defaults to $CODEX_HOME/log)
log_dir = "/var/log/codex"

# URI-based file opener for citations
file_opener = { uri_scheme = "vscode" }

Sources: codex-rs/config/src/config_toml.rs:100-130

Verification

Check Installation

Verify Codex is correctly installed:

codex --version

Run Health Check

Start an interactive session to verify authentication and permissions:

codex

If installed correctly, you should see the Codex splash screen and prompt for login if not authenticated.

Integrated Development Environments

For IDE integration (VS Code, Cursor, Windsurf), visit the IDE installation guide for platform-specific instructions. Sources: README.md:11-14

Troubleshooting

Common Issues

IssueSolution
command not foundEnsure Codex is in your PATH; restart terminal
Permission deniedchmod +x /path/to/codex
Authentication failsRun codex and sign in again; check internet connection
macOS security blockSystem Preferences → Security → Allow the application

Configuration Debugging

Use the built-in debug command to view configuration layers:

/debug-config

This shows all config layers and their requirement sources for troubleshooting. Sources: codex-rs/tui/src/slash_command.rs:12

Logging

Logs are stored in the log directory (default: $CODEX_HOME/log):

  • codex-tui.log - Terminal UI logs
  • codex-core.log - Core engine logs

Set a custom log directory in config.toml:

log_dir = "/var/log/codex"

Sources: codex-rs/config/src/config_toml.rs:115-118

Upgrading

npm

npm update -g @openai/codex

Homebrew

brew upgrade codex

Manual

Download the latest release from GitHub Releases and replace the existing binary.

Uninstalling

npm

npm uninstall -g @openai/codex

Homebrew

brew uninstall codex

Manual

Remove the binary and configuration files:

# Remove binary
rm /usr/local/bin/codex  # or appropriate location

# Optional: Remove configuration
rm -rf ~/.config/codex
rm -rf ~/.codex

Next Steps

After installation, proceed to:

  1. Getting Started - Learn prompts, keyboard shortcuts, and session management
  2. Configuration - Configure models, tools, and workspace permissions
  3. Contributing - Set up development environment for contributing to Codex

Sources: codex-rs/README.md:8-12

Sources: codex-rs/config/src/config_toml.rs:80-95

SDK Overview

Related topics: Getting Started with Codex

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Python SDK

Continue reading this section for the full explanation and source context.

Section TypeScript SDK

Continue reading this section for the full explanation and source context.

Section Python

Continue reading this section for the full explanation and source context.

Related topics: Getting Started with Codex

SDK Overview

The Codex repository provides official Software Development Kits (SDKs) for integrating with Codex, OpenAI's coding agent. These SDKs enable developers to programmatically interact with Codex's capabilities from Python and TypeScript applications, supporting use cases such as code generation, automation, and IDE integration.

Architecture Overview

Codex offers a layered architecture with multiple interaction points:

graph TD
    subgraph "Client Applications"
        PythonApp[Python Application]
        TypeScriptApp[TypeScript/Node.js Application]
        IDEPlugin[IDE Extension]
    end
    
    subgraph "SDK Layer"
        PythonSDK[Python SDK<br/>openai-codex]
        TypeScriptSDK[TypeScript SDK<br/>@openai/codex-sdk]
    end
    
    subgraph "Protocol Layer"
        JSONRPC[JSON-RPC v2<br/>app-server Protocol]
    end
    
    subgraph "Runtime Layer"
        CodexCLI[Codex CLI<br/>Rust Implementation]
        MCPServer[MCP Server<br/>Experimental]
    end
    
    PythonApp --> PythonSDK
    TypeScriptApp --> TypeScriptSDK
    IDEPlugin --> TypeScriptSDK
    
    PythonSDK --> JSONRPC
    TypeScriptSDK --> JSONRPC
    JSONRPC --> CodexCLI
    CodexCLI --> MCPServer

The SDKs communicate with the Codex runtime using the Codex app-server JSON-RPC v2 protocol. The runtime itself is implemented in Rust (codex-rs) and can be invoked as a standalone executable or as a Model Context Protocol (MCP) server.

Sources: sdk/python/README.md Sources: codex-rs/README.md

Available SDKs

Python SDK

PropertyValue
Package Nameopenai-codex
Runtime Packageopenai-codex-cli-bin
Minimum Python Version>=3.10
Target ProtocolCodex app-server JSON-RPC v2
Versioning RuleSDK version matches underlying Codex runtime version

#### Key Usage Patterns

Context Manager Pattern

with Codex() as codex:
    # Codex runtime starts and initializes in the constructor
    # Shutdown is handled automatically on context exit

The Codex() class is eager, meaning it performs startup and initialize immediately upon construction. Always use context managers to ensure proper shutdown.

Thread-Based Operations

# Common case - run a task
result = thread.run("Write a function to calculate fibonacci")

# Advanced case - streaming, steering, or interrupt control
result = thread.turn(...)
MethodUse Case
thread.run()Standard execution for most use cases
thread.turn()When streaming, steering, or interrupt control is needed

Error Handling

from openai_codex import retry_on_overload

# Handle transient overload conditions
result = retry_on_overload(thread.run, "your task")

Sources: sdk/python/README.md:19-30

TypeScript SDK

PropertyValue
Package Name@openai/codex-sdk
Minimum Node Version>=18
Module TypeESM (import)
Type Definitions./dist/index.d.ts

#### Build and Development Scripts

ScriptPurpose
pnpm buildCompile TypeScript to JavaScript
pnpm build:watchWatch mode for development
pnpm lintRun ESLint
pnpm lint:fixAuto-fix linting issues
pnpm testRun Jest test suite
pnpm coverageGenerate test coverage report
pnpm formatCheck Prettier formatting
pnpm format:fixAuto-fix formatting
pnpm prepareBuild on package install (git hooks)

Sources: sdk/typescript/package.json:8-34

MCP Server Integration

The Codex CLI can function as a Model Context Protocol (MCP) server, enabling other MCP clients to interact with Codex capabilities:

graph LR
    MCPServer[codex mcp-server]
    Client1[MCP Client A]
    Client2[MCP Client B]
    
    Client1 --> MCPServer
    Client2 --> MCPServer
    MCPServer --> CodexRuntime[Codex Runtime]

Run the MCP server with:

codex mcp-server

This allows other MCP-compatible tools and applications to leverage Codex for code generation and understanding tasks.

Sources: codex-rs/README.md:38-45

File Search Component

The repository includes a dedicated file search library (codex_file_search) that provides fast fuzzy file search capabilities:

FeatureDescription
Core Libraryignore crate (used by ripgrep) for directory traversal
Matching Enginenucleo-matcher for fuzzy matching
Git IntegrationHonors .gitignore rules
Use CaseTool for searching codebase files efficiently

Sources: file-search/README.md

SDK Installation

Python

# Install using pip
pip install openai-codex

# Or via poetry
poetry add openai-codex

TypeScript

# Install using npm
npm install @openai/codex-sdk

# Or using pnpm
pnpm add @openai/codex-sdk

Standalone CLI

For scenarios requiring direct CLI usage:

# Install globally via npm
npm i -g @openai/codex

# Or via Homebrew
brew install --cask codex

Sources: sdk/python/README.md

SDK Versioning Strategy

The SDK packages maintain strict versioning alignment with the underlying Codex runtime:

SDK Version = Codex Runtime Version

This ensures API compatibility and predictable behavior across all interaction layers. When upgrading Codex, the SDK should be updated to the matching version.

Sources: sdk/python/README.md:11-13

Sources: sdk/python/README.md

Agent System

Related topics: System Architecture Overview, Tools and Handlers, Session Management

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Agent Registry

Continue reading this section for the full explanation and source context.

Section Agent Role

Continue reading this section for the full explanation and source context.

Section Agent Mailbox

Continue reading this section for the full explanation and source context.

Related topics: System Architecture Overview, Tools and Handlers, Session Management

Agent System

Overview

The Agent System in Codex CLI (implemented in Rust under codex-rs/core/src/agent/) provides a multi-agent collaboration framework that enables Codex to coordinate multiple autonomous agents for complex coding tasks. The system implements a message-passing architecture where agents communicate through dedicated mailboxes, with a central registry managing agent lifecycle, roles, and interactions.

The Agent System supports:

  • Multi-Agent Threads: Switch between active agent threads using /agent or /multiagents commands
  • Role-Based Agents: Agents can be assigned specific roles that define their behavior and capabilities
  • Subagent Context: Subagents are injected into the environment context provided to the main Codex agent
  • Side Conversations: Ephemeral fork conversations that can spawn isolated agent work

Sources: codex-rs/core/src/agents_md.rs

Architecture

graph TD
    subgraph "Agent System Core"
        Registry[Agent Registry]
        Mailbox[Agent Mailbox]
        Role[Agent Role]
    end
    
    subgraph "Agent Instances"
        MainAgent[Main Codex Agent]
        SubAgent1[Subagent 1]
        SubAgent2[Subagent 2]
        SideAgent[Side Conversation Agent]
    end
    
    subgraph "External Interfaces"
        SlashCommands[Slash Commands: /agent<br/>/multiagents<br/>/side]
        EnvironmentContext[Environment Context]
        TUI[TUI Integration]
    end
    
    Registry -->|manages| MainAgent
    Registry -->|manages| SubAgent1
    Registry -->|manages| SubAgent2
    Registry -->|manages| SideAgent
    
    Mailbox -->|message passing| MainAgent
    Mailbox -->|message passing| SubAgent1
    Mailbox -->|message passing| SubAgent2
    
    SlashCommands -->|command invocation| Registry
    MainAgent -->|subagents context| EnvironmentContext
    TUI -->|status display| Registry
    
    SideAgent -.->|ephemeral fork| MainAgent

Core Components

Agent Registry

The Agent Registry (registry.rs) maintains a catalog of all active agents and provides lookup and management capabilities.

Key Responsibilities:

  • Register and unregister agents
  • Track active agent threads
  • Provide agent lookup by ID or role
  • Manage multi-agent coordination

Methods:

MethodPurpose
register_agent()Add a new agent to the registry
unregister_agent()Remove an agent from the registry
get_agent()Retrieve an agent by identifier
list_agents()Enumerate all active agents
get_active_thread()Get the currently active agent thread

Sources: codex-rs/core/src/agent/registry.rs

Agent Role

The Agent Role (role.rs) defines the behavioral characteristics and capabilities assigned to an agent. Roles determine how an agent responds to messages and what actions it can perform.

Supported Roles:

RoleDescription
PrimaryMain Codex agent handling user interactions
SubagentSpecialized worker agent for delegated tasks
ReviewerAgent focused on code review and approval
ResearcherAgent that gathers information and context
ExecutorAgent that executes code and commands

Sources: codex-rs/core/src/agent/role.rs

Agent Mailbox

The Agent Mailbox (mailbox.rs) implements the message-passing system that enables inter-agent communication.

Message Types:

TypePurpose
TaskWork assignment from one agent to another
ResultResponse containing task completion or failure
EventNotification of state changes or external events
QueryRequest for information or context

Mailbox Operations:

// Conceptual API (based on mailbox.rs patterns)
fn send(recipient: AgentId, message: Message) -> Result<(), MailboxError>
fn receive(agent: AgentId) -> Option<Message>
fn broadcast(message: Message) -> Result<(), MailboxError>
fn forward(from: AgentId, to: AgentId) -> Result<(), MailboxError>

Sources: codex-rs/core/src/agent/mailbox.rs

Main Agent Module

The main agent module (mod.rs) serves as the entry point and coordinator for the Agent System, integrating all components into a cohesive framework.

Integration Points:

  • Initializes the agent registry on startup
  • Configures mailbox routing
  • Loads role definitions
  • Coordinates with environment context for subagent injection

Sources: codex-rs/core/src/agent/mod.rs

User Interface

Slash Commands for Agent Management

The TUI provides slash commands for interacting with the Agent System:

CommandDescriptionInline Args Supported
/agentSwitch the active agent threadNo
/multiagentsManage multiple agent threadsNo
/sideStart a side conversation in an ephemeral forkYes

Sources: codex-rs/tui/src/slash_command.rs:89

Subagent Integration in Environment Context

Subagents are rendered into the <environment_context> XML block provided to the main Codex agent:

<environment_context>
  <subagents>
    [subagent lines rendered here]
  </subagents>
</environment_context>

Sources: codex-rs/core/src/context/environment_context.rs:95-98

Configuration

Profile Configuration

Agent behavior can be scoped to specific profiles in config.toml:

[profile.work]
# Agent-specific settings for the 'work' profile
include_environment_context = true
SettingTypePurpose
include_environment_contextboolWhether to inject environment context including subagents
include_collaboration_mode_instructionsboolInclude collaboration mode developer block

Sources: codex-rs/config/src/config_toml.rs:89-92

Workflows

Multi-Agent Thread Switching

graph LR
    A[User: /agent] --> B{Registry Lookup}
    B -->|Find Agent| C[Set Active Thread]
    C --> D[TUI Updates]
    D --> E[New Agent Context Active]
    
    B -->|Unknown Agent| F[Error: Agent Not Found]

Side Conversation Flow

graph TD
    A[User: /side] --> B{Create Ephemeral Fork}
    B --> C[Side Agent Spawned]
    C --> D[Isolated Context Created]
    D --> E[Side Conversation Active]
    E --> F{User Exits Side}
    F -->|Done| G[Merge Results]
    F -->|Cancel| H[Discard Changes]

Task Delegation to Subagent

sequenceDiagram
    participant Main as Main Codex Agent
    participant Registry as Agent Registry
    participant Sub as Subagent
    participant Mailbox as Agent Mailbox
    
    Main->>Registry: Register task for subagent
    Registry->>Sub: Assign role and context
    Main->>Mailbox: Send Task message
    Mailbox->>Sub: Deliver Task
    Sub-->>Mailbox: Process task
    Mailbox-->>Main: Return Result message

State Management

Agent State Lifecycle

graph TD
    Uninitialized -->|initialize| Ready
    Ready -->|start_work| Active
    Active -->|pause| Suspended
    Suspended -->|resume| Active
    Active -->|complete| Completed
    Active -->|error| Error
    Error -->|retry| Active
    Completed -->|cleanup| Terminated
    Terminated -->|unregister| Unregistered

Goals Integration

The Agent System integrates with the Goals system to track long-running task progress:

pub enum ExternalGoalPreviousStatus {
    NewGoal,
    Existing(ExternalGoalPreviousGoal),
}

The TaskProgress status item displays progress for agent-managed tasks:

StatusLineItem::TaskProgress => Some(self.task_progress_display_name()),

Sources: codex-rs/core/src/goals.rs:55-60

Status Line Integration

The TUI displays agent-related status through the status line system:

Status ItemDisplayCategory
ThreadTitleCurrent agent thread titleThread
TaskProgressTasks X/Y progressProgress
ModelActive model nameType
FastModeFast mode indicatorMode

Status items are styled using scope-based syntax highlighting:

StyleScopes
Threadmarkup.heading, entity.name.section
Progressmarkup.inserted, constant.numeric
Modestorage.modifier, keyword.operator

Sources: codex-rs/tui/src/bottom_pane/status_line_style.rs:25-27

Extension Points

Custom Agent Roles

New agent roles can be defined by implementing the AgentRole trait:

pub trait AgentRole: Send + Sync {
    fn name(&self) -> &str;
    fn capabilities(&self) -> Vec<Capability>;
    fn process_message(&self, message: Message) -> Response;
}

Mailbox Plugins

The mailbox system supports custom message handlers for specialized inter-agent protocols.

MCP Server Integration

The Agent System can leverage Model Context Protocol (MCP) tools for enhanced agent capabilities:

[mcp]
# MCP server configuration for extended agent tools

Sources: codex-rs/README.md

Summary

The Agent System provides Codex CLI's foundation for multi-agent collaboration. Key architectural elements include:

  • Registry Pattern: Centralized agent management with lifecycle tracking
  • Message Passing: Asynchronous communication via dedicated mailboxes
  • Role-Based Design: Flexible role assignment defining agent capabilities
  • TUI Integration: Slash commands and status displays for user interaction
  • Environment Context: Subagent injection into main agent context
  • Side Conversations: Isolated fork capability for experimental work

This architecture enables complex coding workflows where specialized agents can work in parallel, with results aggregated by the main Codex agent for user presentation.

Sources: codex-rs/core/src/agents_md.rs

Tools and Handlers

Related topics: Agent System, Command Execution, Sandboxing

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Tool Definition

Continue reading this section for the full explanation and source context.

Section Tool Registry

Continue reading this section for the full explanation and source context.

Section Tool Orchestrator

Continue reading this section for the full explanation and source context.

Related topics: Agent System, Command Execution, Sandboxing

Tools and Handlers

Overview

The Tools and Handlers system in Codex CLI (Rust implementation) provides the core mechanism by which the AI agent interacts with the filesystem, executes shell commands, and modifies code. This architecture enables Codex to perform practical software development tasks by bridging the gap between the language model and the actual system operations.

The tool system follows a registry-based plugin architecture where individual tools are registered, orchestrated, and executed through a centralized orchestrator component. This design allows for modular addition of new capabilities while maintaining a consistent interface for all tool interactions.

Architecture Overview

The tools system consists of three primary layers working in coordination:

graph TD
    A[Tool Definition] --> B[Tool Registry]
    B --> C[Tool Orchestrator]
    C --> D[Handler Execution]
    D --> E[Shell Handler]
    D --> F[Apply Patch Handler]
    D --> G[Other Handlers]

Core Components

Tool Definition

Tool definitions describe the interface and metadata for each capability that Codex can perform. Each tool definition includes:

ComponentDescription
nameUnique identifier for the tool
descriptionHuman-readable description of tool purpose
parametersJSON Schema defining input parameters
handlerReference to the implementation function
capabilitiesPermission scopes required

Sources: codex-rs/tools/src/tool_definition.rs

Tool Registry

The registry maintains a centralized catalog of all available tools and their metadata. It provides lookup and discovery capabilities for the orchestrator.

FunctionPurpose
register()Add a new tool to the registry
lookup()Find a tool by name
list_tools()Enumerate all available tools
get_by_capability()Filter tools by permission scope

Sources: codex-rs/core/src/tools/registry.rs

Tool Orchestrator

The orchestrator coordinates tool execution, manages handler lifecycle, and handles error propagation. It acts as the facade between the agent's tool-calling requests and the actual handler implementations.

Key responsibilities include:

  • Parsing tool call requests from the agent
  • Selecting appropriate handlers
  • Managing execution context and state
  • Aggregating results and errors

Sources: codex-rs/core/src/tools/orchestrator.rs

Built-in Tools

Shell Handler

The shell handler provides secure command execution capabilities. It is one of the most frequently used handlers, enabling Codex to run terminal commands within the development environment.

graph LR
    A[Agent Request] --> B[Shell Handler]
    B --> C[Command Validation]
    C --> D[Permission Check]
    D --> E[Execute Command]
    E --> F[Capture Output]
    F --> G[Return Result]

#### Key Features

  • Shell type detection: Automatically detects the user's preferred shell (bash, zsh, fish, etc.)
  • Working directory support: Executes commands in the correct project context
  • Output capture: Captures both stdout and stderr streams
  • Exit code reporting: Returns the command's exit status
  • Timeout handling: Prevents runaway processes

Sources: codex-rs/core/src/tools/handlers/shell.rs

Apply Patch Handler

The apply patch handler manages file modifications using a unified diff-based approach. It allows Codex to make precise changes to source files while maintaining proper context.

#### Workflow

graph TD
    A[Patch Content] --> B[Parse Diff]
    B --> C[Validate Syntax]
    C --> D[Backup Original]
    D --> E[Apply Changes]
    E --> F{Success?}
    F -->|Yes| G[Return Success]
    F -->|No| H[Rollback]
    H --> I[Return Error]

#### Configuration Options

OptionTypeDefaultDescription
include_apply_patch_toolbooltrueEnable/disable the tool
experimental_use_freeform_apply_patchboolfalseAllow unstructured patches

Sources: codex-rs/core/src/tools/handlers/apply_patch.rs

Tool Execution Flow

The complete tool execution lifecycle follows this sequence:

sequenceDiagram
    participant Agent
    participant Orchestrator
    participant Registry
    participant Handler
    participant System

    Agent->>Orchestrator: Request tool execution
    Orchestrator->>Registry: Lookup tool definition
    Registry-->>Orchestrator: Return tool metadata
    Orchestrator->>Handler: Invoke with parameters
    Handler->>System: Perform operation
    System-->>Handler: Return result
    Handler-->>Orchestrator: Format response
    Orchestrator-->>Agent: Return tool result

Tool Registration System

Registration Process

Tools are registered during application initialization through the module system:

  1. Definition Phase: Tool metadata and schema are defined
  2. Handler Binding: Implementation functions are bound to the tool
  3. Registry Entry: Tool is added to the global registry
  4. Orchestrator Integration: Tool becomes available for agent requests

Sources: codex-rs/core/src/tools/mod.rs

Configuration Integration

The tools system integrates with Codex's configuration layer to control availability and behavior:

Config SectionSettingPurpose
[features]Feature togglesEnable/disable specific tools
[profile.tui]UI settingsConfigure tool presentation
[permissions]Capability scopeRestrict tool access

Sources: codex-rs/config/src/config_toml.rs

MCP Integration

Codex supports the Model Context Protocol (MCP) for extending tool capabilities. MCP servers can register additional tools that become available through the standard tool interface.

MCP Tool Discovery

/mcp verbose

This command lists all configured MCP tools with their parameters and descriptions.

Slash Commands Integration

While not strictly tools, slash commands in the TUI provide user-facing access to tool configuration and management:

CommandRelated Tool
/reviewCode review tool
/planPlan mode activation
/goalTask goal management
/mcpMCP tool listing
/ideIDE context integration

Sources: codex-rs/tui/src/slash_command.rs

Error Handling

The tool system implements robust error handling with the following error categories:

Error TypeDescriptionRecovery Action
ToolNotFoundRequested tool does not existSuggest alternatives
PermissionDeniedInsufficient capabilitiesRequest authorization
ExecutionFailedHandler execution errorLog and retry
TimeoutExceededCommand exceeded time limitKill and report
InvalidParametersMalformed inputReturn schema error

Extensibility

The tool system is designed for extensibility. New tools can be added by:

  1. Creating a new handler module in codex-rs/core/src/tools/handlers/
  2. Implementing the ToolHandler trait
  3. Registering the tool in the registry
  4. Adding tests for the new handler

Sources: codex-rs/core/src/tools/handlers/shell.rs

Testing

Tool handlers include comprehensive test coverage:

  • Unit tests for parameter validation
  • Integration tests for handler execution
  • Mock tests for external dependencies
  • Snapshot tests for output formatting

Sources: codex-rs/tui/src/markdown_render_tests.rs

Sources: codex-rs/tools/src/tool_definition.rs

Session Management

Related topics: Agent System

Section Related Pages

Continue reading this section for the full explanation and source context.

Related topics: Agent System

Session Management

Overview

Session Management in Codex CLI is the system responsible for maintaining conversational context, tracking user interactions, and coordinating the lifecycle of coding sessions across different execution environments.

Codex CLI is a coding agent from OpenAI that runs locally on your computer, supporting installation via npm (npm i -g @openai/codex) or Homebrew (brew install --cask codex). Sources: README.md:1-10

The Rust implementation serves as the maintained Codex CLI and provides a rich set of configuration options through config.toml. Sources: codex-rs/README.md:1-20

Source: https://github.com/openai/codex / Human Manual

Command Execution

Related topics: Sandboxing, Tools and Handlers

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Slash Commands for Execution

Continue reading this section for the full explanation and source context.

Section Approval Decisions

Continue reading this section for the full explanation and source context.

Section Environment Context

Continue reading this section for the full explanation and source context.

Related topics: Sandboxing, Tools and Handlers

Command Execution

Command Execution is a core system within Codex CLI that enables the agent to run shell commands, manage process lifecycles, and handle interactive terminal sessions within a sandboxed environment.

Overview

The Command Execution system in Codex provides a unified interface for running shell commands across different contexts. It integrates with the agent's control flow, approval mechanisms, and environment context to ensure safe and controlled command execution.

The execution model supports:

  • Real-time output streaming
  • Approval-based execution for sensitive operations
  • Background terminal management
  • Multi-shell support

Architecture

graph TD
    A[Agent Decision] --> B{Command Execution Request}
    B --> C[Environment Context]
    B --> D[Approval Overlay]
    B --> E[Sandbox Runtime]
    C --> F[<shell> Shell Session]
    D --> G{Approved?}
    G -->|Yes| E
    G -->|No| H[Abort Operation]
    E --> I[Command Output Stream]
    I --> J[Terminal UI]
    F --> K[Background Terminals]

Core Components

Slash Commands for Execution

Codex provides multiple slash commands that interface with the command execution system:

CommandDescriptionInline Args
/resumeResume a saved chat sessionNo
/clearClear terminal and start new chatNo
/forkFork the current chatNo
/psList background terminalsNo
/stopStop all background terminalsNo
/statusShow current session configuration and token usageNo

Sources: codex-rs/tui/src/slash_command.rs:1-50

Approval Decisions

When executing commands that modify files or system state, Codex presents approval options:

OptionDecisionEffect
"Yes, proceed"FileChangeApprovalDecision::AcceptExecute immediately
"Yes, don't ask again for these files"FileChangeApprovalDecision::AcceptForSessionExecute and bypass for session
"No, tell Codex what to do differently"DeclineAbort with feedback

Sources: codex-rs/tui/src/bottom_pane/approval_overlay.rs:1-30

Environment Context

The EnvironmentContext captures shell and working directory information for command execution:

<environment_context>
  <environments>
    <environment id="...">
      <cwd>/path/to/project</cwd>
      <shell>bash</shell>
    </environment>
  </environments>
  <current_date>2024-01-15</current_date>
  <timezone>America/Los_Angeles</timezone>
</environment_context>

Sources: codex-rs/core/src/context/environment_context.rs:1-50

Execution Flow

sequenceDiagram
    participant Agent
    participant Control as Control Module
    participant Approval as Approval Overlay
    participant Runtime as Exec Runtime
    participant Terminal as TUI Terminal
    
    Agent->>Control: Request Command Execution
    Control->>Control: Check Permissions
    Control->>Approval: Request Approval if Needed
    Approval-->>Control: Approval Decision
    Control->>Runtime: Execute Command
    Runtime-->>Terminal: Stream Output
    Terminal-->>Agent: Execution Result

Config Layer Integration

Command execution respects configuration layers with the following precedence:

LayerPrioritySource
SystemLowestSystem-level config file
UserMediumUser home directory config
ProjectHigh.codex/ folder
Session FlagsHighestCommand-line arguments

Sources: codex-rs/config/src/state.rs:1-30

Status Display

The status line shows execution-related information:

Status ItemDisplay FormatDescription
StatusRun state textCurrent agent operation state
PermissionsWorkspace/FullPermission level display
ApprovalModeon-request/autoCurrent approval mode
ContextRemainingContext X% leftRemaining context window

Sources: codex-rs/tui/src/chatwidget/status_surfaces.rs:1-50

Inter-Agent Communication

Commands can be used for inter-agent communication through the control system:

Op::InterAgentCommunication { communication } => communication.content.clone()

This allows sub-agents to coordinate execution through message passing.

Sources: codex-rs/core/src/agent/control.rs:1-30

Keyboard Shortcuts

The terminal UI provides shortcuts for managing command execution:

ShortcutActionDescription
QueueMessageTabQueue Message TabQueue commands for batch execution
HistorySearchHistory SearchSearch command history
EditPreviousEdit PreviousModify last command
ExternalEditorExternal EditorOpen command in external editor

Sources: codex-rs/tui/src/bottom_pane/footer.rs:1-40

File System Path Resolution

Commands execute within sandboxed file system contexts:

Path TypeFormatDescription
Root:rootRepository root
Minimal:minimalMinimal sandbox scope
Project Roots:project_rootsAll project root directories
Tmpdir:tmpdirSystem temp directory
Custom/path/to/dirUser-specified path

Sources: codex-rs/tui/src/bottom_pane/approval_overlay.rs:30-60

Session Management

Command execution sessions support:

  • Resume: Restore previous execution state
  • Fork: Create parallel execution branches
  • Clear: Reset execution environment
  • Background Terminals: Run commands asynchronously

Security Model

  1. Permission Checks: Commands validate against permission configuration
  2. Approval Prompts: File-modifying commands require user approval
  3. Sandbox Isolation: Commands run in controlled sandbox environments
  4. Context Scoping: File access restricted by path rules

Quick Reference

TaskCommand
View current status/status
List background jobs/ps
Stop all jobs/stop
Clear terminal/clear
Fork session/fork

Sources: codex-rs/tui/src/slash_command.rs:1-50

Sandboxing

Related topics: Command Execution

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Sandbox Mode Selection

Continue reading this section for the full explanation and source context.

Section Core Components

Continue reading this section for the full explanation and source context.

Section Key Features

Continue reading this section for the full explanation and source context.

Related topics: Command Execution

Sandboxing

Overview

Codex CLI implements a comprehensive sandboxing system that restricts the agent's access to system resources, ensuring safe execution within user-specified boundaries. The sandboxing architecture provides multiple enforcement levels—from strict read-only isolation to full workspace write access with network restrictions.

Sandboxing in Codex serves two primary purposes:

  1. Security Isolation: Prevents Codex from accessing sensitive files or performing unintended operations outside the workspace
  2. Controlled Write Access: Allows the agent to modify workspace files while maintaining restrictions on system-wide changes

Sources: codex-rs/README.md

Sandbox Modes

Codex supports four distinct sandbox modes that can be selected via the --sandbox flag or configuration.

ModeDescriptionUse Case
read-onlyDefault mode. Codex can read files but cannot modify themProduction environments, sensitive codebases
workspace-writeAllows file modifications within the workspace and memoriesActive development with controlled modifications
danger-full-accessDisables all sandboxingIsolated environments (containers), CI/CD pipelines
external-sandboxDelegates sandboxing to an external providerAdvanced configurations requiring custom enforcement

Sources: codex-rs/README.md

Sandbox Mode Selection

#### Command Line Flag

The --sandbox (or -s) flag provides the most direct way to select a sandbox policy:

# Run Codex with read-only sandbox (default)
codex --sandbox read-only

# Allow workspace modifications
codex --sandbox workspace-write

# Disable sandboxing entirely (use with caution)
codex --sandbox danger-full-access

#### Configuration File

The sandbox mode can be persisted in the user configuration file ~/.codex/config.toml:

sandbox_mode = "workspace-write"

#### Inline Configuration Override

For one-off experiments, use the generic -c/--config option:

codex -c 'sandbox_mode="workspace-write"'

Sources: codex-rs/README.md

Architecture

The sandboxing system is organized as a platform-specific implementation with a unified core interface.

graph TD
    A[Codex Core] --> B[core/sandboxing/mod.rs]
    B --> C[Sandbox Abstraction Layer]
    C --> D[Linux Sandbox<br/>linux-sandbox/src]
    C --> E[Windows Sandbox<br/>windows-sandbox-rs/src]
    C --> F[macOS Sandbox<br/>sandboxing/src]
    G[Landlock] --> D
    H[Seatbelt] --> F
    I[Windows ACLs] --> E

Core Components

ComponentPathPurpose
Sandbox Abstractioncodex-rs/core/src/sandboxing/mod.rsDefines the unified sandbox interface and policy enforcement
Linux Implementationcodex-rs/linux-sandbox/src/lib.rsImplements sandboxing using Landlock
Windows Implementationcodex-rs/windows-sandbox-rs/src/lib.rsImplements sandboxing using Windows security features
macOS Implementationcodex-rs/sandboxing/src/lib.rsImplements sandboxing using Seatbelt

Linux Sandbox

On Linux systems, Codex leverages the Landlock Linux Security Module (LSM) for filesystem sandboxing. Landlock provides a hierarchical deny-by-default approach to filesystem access control.

Key Features

  • No Root Dependency: Landlock works without elevated privileges
  • Hierarchical Restrictions: Child processes inherit parent restrictions
  • Filesystem Path Rules: Supports glob patterns for path matching
  • Network Restrictions: Can block outbound network connections

Debugging Landlock

Codex provides debug commands for troubleshooting Landlock policies:

codex debug landlock [COMMAND]...

Sources: codex-rs/README.md

Windows Sandbox

The Windows implementation uses Windows security mechanisms to enforce sandbox boundaries.

Key Features

  • Path-based Rules: Restricts access to specific directories
  • ACL Integration: Leverages Windows Access Control Lists
  • Process Isolation: Prevents child processes from escaping restrictions

Sources: codex-rs/windows-sandbox-rs/src/lib.rs

Sandbox Policies and Enforcement

Read-Only Mode Behavior

In read-only mode, the sandbox enforces:

  1. File Read: Allowed for all workspace files
  2. File Write: Blocked across the entire filesystem
  3. Network Access: Controlled via NetworkConstraints configuration
  4. Process Execution: Limited to read-only operations

Workspace-Write Mode Behavior

In workspace-write mode, the sandbox expands permissions to include:

  1. File Read: Full access to workspace
  2. File Write: Allowed within defined workspace boundaries
  3. Memories Access: Special write access to ~/.codex/memories for memory maintenance
  4. Network Access: Still restricted by default
# In workspace-write mode, memories are included in writable roots
# so memory maintenance does not require additional approval

Sources: codex-rs/README.md

Danger-Full-Access Mode

This mode completely disables sandboxing and should only be used in:

  • Containerized environments with their own isolation
  • CI/CD pipelines with controlled execution contexts
  • Development environments with full user supervision
Warning: Using danger-full-access outside of isolated environments can pose significant security risks.

Debug Commands

Codex includes debugging utilities for sandbox inspection:

Seatbelt Debug (macOS)

codex debug seatbelt [--log-denials] [COMMAND]...

Parameters:

ParameterDescription
--log-denialsEnable logging of denied access attempts
COMMANDOptional subcommand for specific debug operations

Landlock Debug (Linux)

codex debug landlock [COMMAND]...

Configuration Integration

ConfigLayerSource Mapping

Sandbox requirements are tracked through the configuration layer system:

ConfigLayerSourceSandbox Behavior
SystemUses system-wide sandbox settings
UserUses user-local configuration
ProjectUses project .codex/ configuration
SessionFlagsOverride via command-line flags

State Persistence

The ConfigLayerStack maintains sandbox mode across sessions:

pub struct ConfigLayerStack {
    layers: Vec<ConfigLayerEntry>,
    user_layer_index: Option<usize>,
    // ...
}

Sources: codex-rs/config/src/state.rs

Requirements and Constraints

SandboxModeRequirement Enum

The system tracks sandbox requirements as an enum:

enum SandboxModeRequirement {
    ReadOnly,
    WorkspaceWrite,
    DangerFullAccess,
    ExternalSandbox,
}

Residency Requirements

Certain configurations may impose residency requirements:

enum ResidencyRequirement {
    Us,  // Data residency in US region
}

Best Practices

Development Workflow

  1. Default to Read-Only: Start with read-only mode to understand what operations Codex attempts
  2. Increment Permissions: Progressively enable workspace-write once comfortable
  3. Audit Access: Use debug commands to monitor sandbox denials

Security Considerations

EnvironmentRecommended ModeRationale
Production Serverread-onlyMaximum security
Local Developmentworkspace-writeBalance of safety and utility
Container (Isolated)danger-full-accessContainer provides isolation
CI/CD Pipelineread-only or danger-full-accessDepends on pipeline isolation

External Resources

Sources: codex-rs/README.md

Terminal UI

Related topics: System Architecture Overview

Section Related Pages

Continue reading this section for the full explanation and source context.

Section ChatWidget

Continue reading this section for the full explanation and source context.

Section Bottom Pane

Continue reading this section for the full explanation and source context.

Section Key Features

Continue reading this section for the full explanation and source context.

Related topics: System Architecture Overview

Terminal UI

Overview

The Terminal UI (TUI) is the primary command-line interface for Codex CLI, built in Rust using the ratatui library. It provides a rich, interactive terminal experience with features including markdown rendering, syntax highlighting, slash commands, status surfaces, and customizable keybindings.

The Rust TUI implementation is the maintained Codex CLI and serves as the default experience, replacing the legacy TypeScript CLI. Sources: codex-rs/README.md

Architecture

graph TD
    A[TUI Entry Point] --> B[ChatWidget]
    A --> C[Bottom Pane]
    B --> D[Markdown Render]
    B --> E[Slash Dispatch]
    C --> F[Status Surface]
    C --> G[Footer/Hints]
    C --> H[Title Setup]
    E --> I[Command Handlers]
    D --> J[Syntax Highlight]
    F --> K[Status Line Style]

Core Components

ChatWidget

The ChatWidget is the central component handling user interactions, chat history, and message display. It integrates with the approval system for risk-aware operations.

Key Responsibilities:

  • Displaying chat messages with markdown rendering
  • Handling user input and commands
  • Managing approval request events
  • Dispatching slash commands

Sources: codex-rs/tui/src/chatwidget.rs:1-100

Bottom Pane

The bottom pane encompasses several sub-components for user guidance and status information.

ComponentFilePurpose
Footerbottom_pane/footer.rsDisplays keyboard shortcuts and hints
Title Setupbottom_pane/title_setup.rsTerminal title configuration
Status Line Stylebottom_pane/status_line_style.rsStatus line visual styling
Status Surface Previewbottom_pane/status_surface_preview.rsPreview status items

Sources: codex-rs/tui/src/bottom_pane/footer.rs:1-50

Slash Commands

Slash commands provide a command-line interface for various Codex operations. The TUI dispatches these commands through slash_dispatch.rs.

CommandDescription
/resumeResume a saved chat
/clearClear terminal and start new chat
/forkFork the current chat
/quit or /exitExit Codex
/copyCopy last response as markdown
/diffShow git diff including untracked files
/modelChoose model and reasoning effort
/themeChoose syntax highlighting theme
/petsChoose or hide terminal pet
/keymapRemap TUI shortcuts
/settingsConfigure realtime microphone/speaker
/planSwitch to Plan mode
/ideInclude IDE context (selection, open files)
/mcpList configured MCP tools

Sources: codex-rs/tui/src/slash_command.rs:1-60 Sources: codex-rs/tui/src/chatwidget/slash_dispatch.rs:1-50

Markdown Rendering

The TUI provides sophisticated markdown rendering capabilities using pulldown-cmark and custom fence unwrapping logic.

Key Features

  • Fence Unwrapping: LLMs frequently wrap tables in ``markdown fences. The renderer strips these fences so pulldown-cmark` sees raw table syntax instead of fenced code blocks.
  • Syntax Highlighting: Uses syntect for code block highlighting with theme support.
  • Table Detection: Custom table detection for proper rendering.
  • Escaped Characters: Handles HTML entities (&amp;, &lt;, &gt;, &quot;, &#39;) and escaped pipes.

Supported Markdown Elements

ElementTags Handled
Code BlocksFenced and indented
TablesHeader, rows, cells, alignments
ListsOrdered and unordered
LinksStandard and reference-style
ImagesBlock-level images
HeadingsH1-H6
EmphasisItalic, bold, strikethrough
BlockquotesNested blockquotes
FootnotesDefinition and reference

Sources: codex-rs/tui/src/markdown.rs:1-40 Sources: codex-rs/tui/src/markdown_render.rs:1-80

Status Surfaces

Status surfaces display real-time information about the current session and system state.

Available Status Items

ItemDescription
AppNameCodex application name
ProjectNameCurrent project name
ProjectRootProject root path
CurrentDirCurrent working directory
StatusSession run-state (Ready, Working, Thinking)
GitBranchCurrent Git branch
PullRequestNumberCurrent PR number
ContextRemainingContext window remaining %
ContextUsedContext window used %
FiveHourLimitRemaining 5-hour usage
WeeklyLimitRemaining weekly usage
UsedTokensTotal session tokens
TotalInputTokensTotal input tokens
TotalOutputTokensTotal output tokens
ModelCurrent model name
ModelWithReasoningModel with reasoning level
FastModeFast mode status
SessionIdCurrent thread identifier
TaskProgressLatest task progress
CodexVersionApplication version

Status Line Styling

Status line items are styled with semantic colors:

Item TypeDefault ColorHighlight Scopes
Model, State, Metadata, ModeCyanconstant.language, storage.type
Path, Usage, ProgressGreenN/A
Branch, Limit, ThreadMagentamarkup.heading, entity.name.section

Sources: codex-rs/tui/src/chatwidget/status_surfaces.rs:1-60 Sources: codex-rs/tui/src/bottom_pane/status_line_style.rs:1-40

Terminal Title Configuration

The terminal title can display various information items, configurable by the user.

Title Items

enum TerminalTitleItem {
    Spinner,           // Spinner while working, action-required when blocked
    Status,            // Compact session state (Ready, Working, Thinking)
    Thread,            // Current thread title or identifier
    GitBranch,         // Current Git branch
    ContextRemaining,  // Context window remaining percentage
    ContextUsed,       // Context window used percentage
    FiveHourLimit,     // 5-hour usage limit remaining
    WeeklyLimit,       // Weekly limit remaining
    CodexVersion,      // Application version
    UsedTokens,        // Total tokens used
    TotalInputTokens,  // Total input tokens
    TotalOutputTokens, // Total output tokens
    SessionId,         // Thread identifier
    FastMode,          // Fast mode status
    Model,             // Current model name
    ModelWithReasoning, // Model with reasoning level
    TaskProgress,      // Latest task progress
}

Sources: codex-rs/tui/src/bottom_pane/title_setup.rs:1-50

Keybindings

The TUI supports extensive keybinding customization through tui_keymap.rs.

Keybinding Categories

#### Normal Mode

CategoryBindings
ExitExit normal mode
CancelCancel pending operator
WriteEnter insert mode
OneDown / OneUpLine navigation
PageDown / PageUpPage navigation
Top / BottomJump to start/end
HalfPageDown / HalfPageUpHalf-page scroll

#### Insert Mode

CategoryBindings
ExitReturn to normal mode
CancelReturn to normal mode
TextInsertInsert text
TextOverwriteOverwrite text
NewlineInsert newline
BackspaceDelete character
DeleteDelete forward
MotionLeft / MotionRightCharacter movement
MotionWordForward / MotionWordBackwardWord movement
MotionLineStart / MotionLineEndLine navigation

#### Visual Mode

CategoryBindings
ExitExit visual mode
MotionLeft / MotionRightExtend selection
MotionWordForward / MotionWordBackwardWord selection
MotionLineStart / MotionLineEndLine selection

#### Composer/Pager

CategoryBindings
ScrollUp / ScrollDownRow scroll
PageUp / PageDownPage scroll
HalfPageUp / HalfPageDownHalf-page scroll

#### Motion

CategoryBindings
MotionUp / MotionDownLine movement
MotionWordForward / MotionWordBackwardWord movement
MotionWordEndEnd of word
MotionLineStart / MotionLineEndLine boundaries

Sources: codex-rs/config/src/tui_keymap.rs:1-80

The footer displays contextual keyboard shortcuts to guide users. Commands are organized in columns for readability.

Default Shortcut Categories

  1. Commands
  2. Shell commands
  3. Newline
  4. Queue message tab
  5. File paths
  6. Paste image
  7. External editor
  8. Edit previous
  9. History search
  10. Quit
  11. Reasoning navigation

The footer includes a hint for customizing shortcuts: "customize shortcuts with /keymap"

Sources: codex-rs/tui/src/bottom_pane/footer.rs:1-80

Configuration

TUI Settings in Profile

TUI settings can be scoped to specific profiles in config.toml:

[profile.development.tui]
session_picker_view = "compact"  # Preferred layout for resume/fork picker

Global TUI Settings

SettingTypeDescription
hide_agent_reasoningboolHide AgentReasoning events from UI
show_raw_agent_reasoningboolShow raw reasoning content
model_reasoning_effortReasoningEffortDefault reasoning effort
plan_mode_reasoning_effortReasoningEffortPlan mode reasoning effort
model_reasoning_summaryReasoningSummaryReasoning summary preference

Session Picker View Modes

ModeDescription
DefaultStandard picker layout
CompactCompact layout for limited screen space

Sources: codex-rs/config/src/profile_toml.rs:1-50 Sources: codex-rs/config/src/config_toml.rs:1-80

Theme Support

The TUI supports syntax highlighting themes via .tmtheme files. Themes define:

  • Foreground/background colors
  • Scope-specific styling for syntax elements
  • Diff highlighting (inserted/deleted scopes)

Custom themes can be loaded with diff-specific backgrounds for insertions and deletions.

Sources: codex-rs/tui/src/render/highlight.rs:1-50

Markdown Render Tests

Test cases validate markdown rendering for:

  • Fenced code with tildes and triple backticks
  • Indented code blocks
  • Definition lists
  • Character entities (&amp;, &lt;, &gt;, &quot;, &#39;)
  • Escaped pipes in text
  • URLs with parentheses
  • Reference links
  • Ordered lists with nested code blocks

Sources: codex-rs/tui/src/markdown_render_tests.rs:1-80

Sources: codex-rs/tui/src/chatwidget.rs:1-100

Doramagic Pitfall Log

Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.

high Chat Tree lost all my chats

First-time setup may fail or require extra isolation and rollback planning.

high Chrome plugin fails after reinstall: browser-client is not trusted / native pipe bridge unavailable

First-time setup may fail or require extra isolation and rollback planning.

high Codex Desktop: cannot enable Computer Use or Mobile Remote on macOS

First-time setup may fail or require extra isolation and rollback planning.

high Codex app is much slower after latest update: Fast mode feels like Standard, with slow thinking/searching/compaction

First-time setup may fail or require extra isolation and rollback planning.

Doramagic Pitfall Log

Doramagic extracted 16 source-linked risk signals. Review them before installing or handing real data to the project.

1. Installation risk: Chat Tree lost all my chats

  • Severity: high
  • Finding: Installation risk is backed by a source signal: Chat Tree lost all my chats. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/openai/codex/issues/23966

2. Installation risk: Chrome plugin fails after reinstall: browser-client is not trusted / native pipe bridge unavailable

  • Severity: high
  • Finding: Installation risk is backed by a source signal: Chrome plugin fails after reinstall: browser-client is not trusted / native pipe bridge unavailable. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/openai/codex/issues/23884

3. Installation risk: Codex Desktop: cannot enable Computer Use or Mobile Remote on macOS

  • Severity: high
  • Finding: Installation risk is backed by a source signal: Codex Desktop: cannot enable Computer Use or Mobile Remote on macOS. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/openai/codex/issues/24000

4. Installation risk: Codex app is much slower after latest update: Fast mode feels like Standard, with slow thinking/searching/compaction

  • Severity: high
  • Finding: Installation risk is backed by a source signal: Codex app is much slower after latest update: Fast mode feels like Standard, with slow thinking/searching/compaction. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/openai/codex/issues/23998

5. Configuration risk: Codex App: View > Toggle File Tree is enabled but does not reliably reveal the file tree

  • Severity: high
  • Finding: Configuration risk is backed by a source signal: Codex App: View > Toggle File Tree is enabled but does not reliably reveal the file tree. Treat it as a review item until the current version is checked.
  • User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/openai/codex/issues/20552

6. Configuration risk: Codex Desktop project chat histories disappeared after recent update

  • Severity: high
  • Finding: Configuration risk is backed by a source signal: Codex Desktop project chat histories disappeared after recent update. Treat it as a review item until the current version is checked.
  • User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/openai/codex/issues/20741

7. Configuration risk: Codex Usage Web Bug: Personal Usage Chart Not Loading

  • Severity: high
  • Finding: Configuration risk is backed by a source signal: Codex Usage Web Bug: Personal Usage Chart Not Loading. Treat it as a review item until the current version is checked.
  • User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/openai/codex/issues/23686

8. Maintenance risk: Codex Desktop sidebar chat history disappears and latest update does not restore hidden chats

  • Severity: high
  • Finding: Maintenance risk is backed by a source signal: Codex Desktop sidebar chat history disappears and latest update does not restore hidden chats. Treat it as a review item until the current version is checked.
  • User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/openai/codex/issues/23999

9. Security or permission risk: Developers should check this security_permissions risk before relying on the project: Allow interactive editing of sandbox permission requests

  • Severity: high
  • Finding: Developers should check this security_permissions risk before relying on the project: Allow interactive editing of sandbox permission requests
  • User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
  • Recommended check: Before packaging this project, run the relevant install/config/quickstart check for: Allow interactive editing of sandbox permission requests. Context: Source discussion did not expose a precise runtime context.
  • Evidence: failure_mode_cluster:unknown | fmev_fea80d3c93f2c2f5715766d1529166bb | security_permissions: Allow interactive editing of sandbox permission requests

10. Security or permission risk: Developers should check this security_permissions risk before relying on the project: Codex CLI /permissions omits Read-only in WSL2 but shows it in Windows PowerShell

  • Severity: high
  • Finding: Developers should check this security_permissions risk before relying on the project: Codex CLI /permissions omits Read-only in WSL2 but shows it in Windows PowerShell
  • User impact: Developers may expose sensitive permissions or credentials: Codex CLI /permissions omits Read-only in WSL2 but shows it in Windows PowerShell
  • Recommended check: Before packaging this project, run the relevant install/config/quickstart check for: Codex CLI /permissions omits Read-only in WSL2 but shows it in Windows PowerShell. Context: Observed when using node, windows, linux
  • Evidence: failure_mode_cluster:github_issue | fmev_5ca619a971ee33e92f58a93d31c1a6d8 | https://github.com/openai/codex/issues/23626 | Codex CLI /permissions omits Read-only in WSL2 but shows it in Windows PowerShell

11. Security or permission risk: Developers should check this security_permissions risk before relying on the project: Codex Desktop voice transcription blocked by Cloudflare challenge on /backend-api/transcribe after resolved incident

  • Severity: high
  • Finding: Developers should check this security_permissions risk before relying on the project: Codex Desktop voice transcription blocked by Cloudflare challenge on /backend-api/transcribe after resolved incident
  • User impact: Developers may expose sensitive permissions or credentials: Codex Desktop voice transcription blocked by Cloudflare challenge on /backend-api/transcribe after resolved incident
  • Recommended check: Before packaging this project, run the relevant install/config/quickstart check for: Codex Desktop voice transcription blocked by Cloudflare challenge on /backend-api/transcribe after resolved incident. Context: Observed when using macos
  • Evidence: failure_mode_cluster:github_issue | fmev_b9b2afc6cd0b1f6f74dd58e973d33e44 | https://github.com/openai/codex/issues/21985 | Codex Desktop voice transcription blocked by Cloudflare challenge on /backend-api/transcribe after resolved incident

12. Security or permission risk: Developers should check this security_permissions risk before relying on the project: Codex Desktop: Computer Use blocks get_app_state(Codex) with "not allowed ... for safety reasons" even after reinstall

  • Severity: high
  • Finding: Developers should check this security_permissions risk before relying on the project: Codex Desktop: Computer Use blocks get_app_state(Codex) with "not allowed ... for safety reasons" even after reinstall
  • User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
  • Recommended check: Before packaging this project, run the relevant install/config/quickstart check for: Codex Desktop: Computer Use blocks get_app_state(Codex) with "not allowed ... for safety reasons" even after reinstall. Context: Observed when using macos
  • Evidence: failure_mode_cluster:unknown | fmev_bb42283a16108fba99a9036928ce1d26 | security_permissions: Codex Desktop: Computer Use blocks get_app_state(Codex) with "not allowed ... for safety reas...

Source: Doramagic discovery, validation, and Project Pack records

Community Discussion Evidence

These external discussion links are review inputs, not standalone proof that the project is production-ready.

Sources 12

Count of project-level external discussion links exposed on this manual page.

Use Review before install

Open the linked issues or discussions before treating the pack as ready for your environment.

Source: Project Pack community evidence and pitfall evidence