# https://github.com/openai/codex 项目说明书

生成时间：2026-05-15 13:52:27 UTC

## 目录

- [Getting Started with Codex](#getting-started)
- [System Architecture Overview](#architecture-overview)
- [Installation Guide](#installation-guide)
- [SDK Overview](#sdk-overview)
- [Agent System](#agent-system)
- [Tools and Handlers](#tools-and-handlers)
- [Session Management](#session-management)
- [Command Execution](#command-execution)
- [Sandboxing](#sandboxing)
- [Terminal UI](#terminal-ui)

<a id='getting-started'></a>

## Getting Started with Codex

### 相关页面

相关主题：[Installation Guide](#installation-guide), [System Architecture Overview](#architecture-overview)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/openai/codex/blob/main/README.md)
- [codex-rs/README.md](https://github.com/openai/codex/blob/main/codex-rs/README.md)
- [docs/getting-started.md](https://github.com/openai/codex/blob/main/docs/getting-started.md)
- [docs/install.md](https://github.com/openai/codex/blob/main/docs/install.md)
- [docs/config.md](https://github.com/openai/codex/blob/main/docs/config.md)
</details>

# 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

| Feature | Description |
|---------|-------------|
| Code Understanding | Analyzes and understands your codebase context |
| Multi-file Editing | Reads and modifies files across your project |
| Shell Command Execution | Runs terminal commands on your behalf |
| Git Integration | Shows diffs, manages branches, and tracks changes |
| IDE Context | Includes selections, open files, and IDE context |
| Session Management | Resumes, forks, and manages coding sessions |

资料来源：[README.md:1-15]()

## Installation

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

### Package Manager Installation

```shell
# Install using npm
npm install -g @openai/codex
```

```shell
# Install using Homebrew
brew install --cask codex
```

Alternatively, you can download platform-specific releases directly from the [GitHub Releases](https://github.com/openai/codex/releases) page.

资料来源：[README.md:18-32]()

### Verifying Installation

After installation, verify Codex is properly installed by running:

```shell
codex
```

This launches the interactive terminal interface.

资料来源：[codex-rs/README.md:8-15]()

## Quick Start Workflow

```mermaid
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

资料来源：[docs/getting-started.md](https://github.com/openai/codex/blob/main/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.

| Command | Purpose |
|---------|---------|
| `/resume` | Resume a saved chat session |
| `/clear` | Clear the terminal and start a new chat |
| `/fork` | Fork the current chat into a new session |
| `/quit` or `/exit` | Exit Codex |
| `/model` | Choose what model and reasoning effort to use |
| `/ide` | Include current selection, open files, and IDE context |
| `/theme` | Choose a syntax highlighting theme |
| `/diff` | Show git diff including untracked files |
| `/permissions` | Choose what Codex is allowed to do |
| `/status` | Show current session configuration and token usage |

资料来源：[codex-rs/tui/src/slash_command.rs:1-50]()

### Experimental Commands

| Command | Purpose |
|---------|---------|
| `/realtime` | Toggle realtime voice mode |
| `/collab` | Change collaboration mode |
| `/mcp` | List configured MCP tools |
| `/settings` | Configure realtime microphone/speaker |

资料来源：[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.

```mermaid
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

| Layer | Source | Precedence |
|-------|--------|------------|
| System | System-wide config file | Lowest |
| User | User home directory config | Medium |
| Project | `.codex/config.toml` in project | High |
| Session | Command-line flags | Highest |

资料来源：[codex-rs/config/src/state.rs:1-30]()

### Configuration Files

| File | Location | Purpose |
|------|----------|---------|
| `config.toml` | User/system/project dirs | Main configuration |
| `.codex/` | Project root | Project-specific settings |
| `hooks.toml` | `.codex/` folder | Lifecycle hook definitions |

资料来源：[codex-rs/README.md:20-35]()

## Terminal User Interface

### Status Line Elements

The TUI displays important information in the status line:

| Element | Description |
|---------|-------------|
| Model | Current model and reasoning effort |
| Context | Context window usage percentage |
| Tokens | Total input/output token counts |
| Git Branch | Current branch and change stats |
| Permissions | Current permission level |
| Session ID | Unique identifier for the session |

资料来源：[codex-rs/tui/src/chatwidget/status_surfaces.rs:1-40]()

### Status Line Accents

Status line items use semantic color coding:

| Accent Type | Scopes | Default Color |
|-------------|--------|---------------|
| Model | Keywords, storage types | Cyan |
| State | General UI state | Cyan |
| Usage | Token and progress info | Green |
| Branch | Git-related info | Magenta |
| Thread | Conversation threading | Magenta |

资料来源：[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

| Action | Default Binding |
|--------|-----------------|
| Newline | Enter |
| Queue Message | Tab |
| File Paths | Ctrl+Shift+P |
| Paste Image | Ctrl+Shift+V |
| External Editor | Ctrl+E |
| Edit Previous | Ctrl+Up |
| History Search | Ctrl+R |
| Quit | Ctrl+C |

### Pager Controls

| Action | Key |
|--------|-----|
| Move Up | Arrow Up / k |
| Move Down | Arrow Down / j |
| Jump to Top | g |
| Jump to Bottom | G |
| Close | q / Escape |

资料来源：[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.

资料来源：[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`:

```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:

```shell
codex mcp-server
```

This allows other MCP clients to interact with Codex.

资料来源：[codex-rs/README.md:40-55]()

## Environment Context

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

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

资料来源：[codex-rs/core/src/context/environment_context.rs:1-30]()

## Profiles

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

### Profile Features

| Feature | Description |
|---------|-------------|
| `model_instructions_file` | Custom instructions for the model |
| `experimental_compact_prompt_file` | Compact prompt template |
| `tui.session_picker_view` | Layout preference for session picker |
| `features` | Profile-scoped feature toggles |

资料来源：[codex-rs/config/src/profile_toml.rs:1-50]()

## Next Steps

- Read the [Getting Started Guide](docs/getting-started.md) for detailed walkthrough
- Configure your setup in [Configuration Reference](docs/config.md)
- Review [Installation Options](docs/install.md) for advanced setup
- Enable Vim mode with `/vim` for enhanced text editing
- Configure MCP servers for extended tool capabilities

资料来源：[codex-rs/README.md:15-25]()

---

<a id='architecture-overview'></a>

## System Architecture Overview

### 相关页面

相关主题：[Agent System](#agent-system), [Terminal UI](#terminal-ui), [Command Execution](#command-execution)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [codex-rs/app-server/src/lib.rs](https://github.com/openai/codex/blob/main/codex-rs/app-server/src/lib.rs)
- [codex-rs/core/src/lib.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/lib.rs)
- [codex-rs/app-server-protocol/src/lib.rs](https://github.com/openai/codex/blob/main/codex-rs/app-server-protocol/src/lib.rs)
- [codex-rs/config/src/state.rs](https://github.com/openai/codex/blob/main/codex-rs/config/src/state.rs)
- [codex-rs/config/src/config_toml.rs](https://github.com/openai/codex/blob/main/codex-rs/config/src/config_toml.rs)
- [codex-rs/tui/src/slash_command.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/slash_command.rs)
- [codex-rs/tui/src/status_surfaces.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/status_surfaces.rs)
- [codex-rs/tui/src/chatwidget.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/chatwidget.rs)
</details>

# 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.

资料来源：[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:

```mermaid
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
```

资料来源：[codex-rs/core/src/lib.rs](https://github.com/openai/codex/blob/main/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

资料来源：[codex-rs/core/src/lib.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/lib.rs)

### 3.2 Environment Context

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

| Component | Description |
|-----------|-------------|
| `current_date` | System date and time |
| `timezone` | System timezone |
| `shell` | Active shell configuration |
| `cwd` | Current working directory |
| `subagents` | Running subagent processes |

资料来源：[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

```rust
#[derive(Clone)]
pub struct ExternalGoalPreviousGoal {
    goal_id: String,
    status: codex_state::ThreadGoalStatus,
    objective: String,
}
```

资料来源：[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:

```mermaid
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
```

资料来源：[codex-rs/config/src/state.rs:50-100]()

### 4.2 Configuration Layer Sources

| Layer | Source | Priority |
|-------|--------|----------|
| `SessionFlags` | Command-line arguments | Highest |
| `Mdm` | Mobile Device Management | - |
| `User` | User home directory | - |
| `Project` | `.codex/` folder | - |
| `System` | System-wide config | Lowest |

资料来源：[codex-rs/config/src/state.rs:30-48]()

### 4.3 Key Configuration Options

| Option | Type | Description |
|--------|------|-------------|
| `hide_agent_reasoning` | `bool` | Hide AgentReasoning events from UI |
| `show_raw_agent_reasoning` | `bool` | Show raw reasoning content |
| `model_reasoning_effort` | `Option<ReasoningEffort>` | Model reasoning configuration |
| `commit_attribution` | `Option<String>` | Git commit co-author text |
| `model_instructions_file` | `Option<AbsolutePathBuf>` | Custom model instructions |

资料来源：[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:

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

资料来源：[codex-rs/tui/src/slash_command.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/slash_command.rs)

### 5.2 Slash Commands

Codex supports extensive slash commands for user interaction:

| Command | Description |
|---------|-------------|
| `/resume` | Resume a saved chat |
| `/clear` | Clear terminal and start new chat |
| `/fork` | Fork the current chat |
| `/model` | Choose model and reasoning effort |
| `/ide` | Include IDE context |
| `/mcp` | List configured MCP tools |
| `/settings` | Configure realtime microphone/speaker |
| `/plan` | Switch to Plan mode |
| `/goal` | Set/view goal for long-running task |
| `/collab` | Change collaboration mode |

资料来源：[codex-rs/tui/src/slash_command.rs:1-80]()

### 5.3 Status Surfaces

Status surfaces display various system information:

| Status Item | Display Format |
|-------------|-----------------|
| `AppName` | Application name |
| `ProjectName` | Current project name |
| `GitBranch` | Current branch name |
| `PullRequestNumber` | `PR #123` |
| `BranchChanges` | `+12 -3` |
| `ContextUsed` | `Context 0% used` |
| `Model` | `gpt-5.2-codex` |
| `TaskProgress` | `Tasks 0/0` |

资料来源：[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

```rust
let lang = match kind {
    CodeBlockKind::Fenced(lang) => Some(lang.to_string()),
    CodeBlockKind::Indented => None,
};
```

资料来源：[codex-rs/tui/src/markdown_render.rs:1-80]()

## 6. Protocol Layer

### 6.1 App Server Protocol

The protocol layer defines communication between components:

```mermaid
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
```

资料来源：[codex-rs/app-server-protocol/src/protocol/v2/apps.rs](https://github.com/openai/codex/blob/main/codex-rs/app-server-protocol/src/protocol/v2/apps.rs)

### 6.2 App Information Model

```rust
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>,
}
```

资料来源：[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:

```mermaid
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]
```

资料来源：[codex-rs/tui/src/chatwidget.rs:1-50]()

### 7.2 Guardian Risk Levels

| Level | Enum Value | Action |
|-------|------------|--------|
| Low | `GuardianRiskLevel::Low` | Auto proceed |
| Medium | `GuardianRiskLevel::Medium` | Warn user |
| High | `GuardianRiskLevel::High` | Require confirmation |
| Critical | `GuardianRiskLevel::Critical` | Block action |

资料来源：[codex-rs/tui/src/chatwidget.rs:1-40]()

## 8. Profile System

### 8.1 Profile Configuration

Profiles allow scoped configuration settings:

| Setting | Scope | Description |
|---------|-------|-------------|
| `session_picker_view` | TUI | Layout for resume/fork session picker |
| `features` | Profile | Feature toggles scoped to profile |
| `tui` | Profile | TUI settings |

资料来源：[codex-rs/config/src/profile_toml.rs:50-100]()

## 9. Data Flow Summary

```mermaid
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.

资料来源：[codex-rs/README.md](https://github.com/openai/codex/blob/main/codex-rs/README.md)

---

<a id='installation-guide'></a>

## Installation Guide

### 相关页面

相关主题：[Getting Started with Codex](#getting-started)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [docs/install.md](https://github.com/openai/codex/blob/main/docs/install.md)
- [.devcontainer/devcontainer.json](https://github.com/openai/codex/blob/main/.devcontainer/devcontainer.json)
- [docs/contributing.md](https://github.com/openai/codex/blob/main/docs/contributing.md)
- [MODULE.bazel](https://github.com/openai/codex/blob/main/MODULE.bazel)
- [README.md](https://github.com/openai/codex/blob/main/README.md)
- [codex-rs/README.md](https://github.com/openai/codex/blob/main/codex-rs/README.md)
</details>

# 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. 资料来源：[codex-rs/README.md:1-15]()

## Installation Methods

### Package Managers

#### npm (Recommended)

Install globally using npm for cross-platform compatibility:

```shell
npm i -g @openai/codex
```

This method automatically handles platform detection and binary management. 资料来源：[README.md:8]()

#### Homebrew (macOS/Linux)

For systems with Homebrew installed:

```shell
brew install --cask codex
```

This installs the macOS or Linux binary to your Homebrew prefix. 资料来源：[README.md:9]()

### Manual Binary Installation

For users preferring manual installation or environments without package managers, download platform-specific binaries from the [GitHub Releases](https://github.com/openai/codex/releases/latest) page.

#### Available Binaries

| Platform | Architecture | Filename |
|----------|-------------|----------|
| macOS | Apple Silicon (arm64) | `codex-aarch64-apple-darwin.tar.gz` |
| macOS | x86_64 (Intel) | `codex-x86_64-apple-darwin.tar.gz` |
| Linux | x86_64 | `codex-x86_64-unknown-linux-musl.tar.gz` |
| Linux | arm64 | `codex-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`. 资料来源：[README.md:26-45]()

```shell
# 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. 资料来源：[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`

```shell
# Verify installation
codex --version
```

### Development Container

For contributors, a Dev Container configuration is available:

```json
{
  "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. 资料来源：[.devcontainer/devcontainer.json:1-20]()

## Post-Installation Configuration

### Initial Setup

After installation, run `codex` to start the interactive setup:

```shell
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 Method | Description |
|-------------|-------------|
| ChatGPT | Sign in with ChatGPT (Plus, Pro, Business, Edu, or Enterprise) |
| API Key | Use OpenAI API credentials directly |

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

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

资料来源：[codex-rs/config/src/config_toml.rs:80-95]()

### Configuration Files

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

```mermaid
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 Layer | Location | Priority |
|-------------|----------|----------|
| Session Flags | Command-line arguments | Highest |
| Project | `.codex/config.toml` | High |
| User | `~/.config/codex/config.toml` | Medium |
| System | `/etc/codex/config.toml` | Low |
| MDM | Managed preferences | Lowest |

The Rust CLI uses `config.toml` (not `config.json` as in the legacy TypeScript CLI). 资料来源：[codex-rs/README.md:20-25]()

### Configuration Options

Key installation-related configuration options:

```toml
# 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" }
```

资料来源：[codex-rs/config/src/config_toml.rs:100-130]()

## Verification

### Check Installation

Verify Codex is correctly installed:

```shell
codex --version
```

### Run Health Check

Start an interactive session to verify authentication and permissions:

```shell
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](https://developers.openai.com/codex/ide) for platform-specific instructions. 资料来源：[README.md:11-14]()

## Troubleshooting

### Common Issues

| Issue | Solution |
|-------|----------|
| `command not found` | Ensure Codex is in your `PATH`; restart terminal |
| Permission denied | `chmod +x /path/to/codex` |
| Authentication fails | Run `codex` and sign in again; check internet connection |
| macOS security block | System 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. 资料来源：[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`:

```toml
log_dir = "/var/log/codex"
```

资料来源：[codex-rs/config/src/config_toml.rs:115-118]()

## Upgrading

### npm

```shell
npm update -g @openai/codex
```

### Homebrew

```shell
brew upgrade codex
```

### Manual

Download the latest release from [GitHub Releases](https://github.com/openai/codex/releases/latest) and replace the existing binary.

## Uninstalling

### npm

```shell
npm uninstall -g @openai/codex
```

### Homebrew

```shell
brew uninstall codex
```

### Manual

Remove the binary and configuration files:

```shell
# 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](../getting-started.md)** - Learn prompts, keyboard shortcuts, and session management
2. **[Configuration](../config.md)** - Configure models, tools, and workspace permissions
3. **[Contributing](../contributing.md)** - Set up development environment for contributing to Codex

资料来源：[codex-rs/README.md:8-12]()

---

<a id='sdk-overview'></a>

## SDK Overview

### 相关页面

相关主题：[Getting Started with Codex](#getting-started)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [sdk/python/README.md](https://github.com/openai/codex/blob/main/sdk/python/README.md)
- [sdk/typescript/package.json](https://github.com/openai/codex/blob/main/sdk/typescript/package.json)
- [codex-rs/README.md](https://github.com/openai/codex/blob/main/codex-rs/README.md)
- [file-search/README.md](https://github.com/openai/codex/blob/main/file-search/README.md)
</details>

# 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:

```mermaid
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.

资料来源：[sdk/python/README.md](../sdk/python/README.md)  
资料来源：[codex-rs/README.md](../codex-rs/README.md)

## Available SDKs

### Python SDK

| Property | Value |
|----------|-------|
| Package Name | `openai-codex` |
| Runtime Package | `openai-codex-cli-bin` |
| Minimum Python Version | `>=3.10` |
| Target Protocol | Codex `app-server` JSON-RPC v2 |
| Versioning Rule | SDK version matches underlying Codex runtime version |

#### Key Usage Patterns

**Context Manager Pattern**

```python
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**

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

# Advanced case - streaming, steering, or interrupt control
result = thread.turn(...)
```

| Method | Use Case |
|--------|----------|
| `thread.run()` | Standard execution for most use cases |
| `thread.turn()` | When streaming, steering, or interrupt control is needed |

**Error Handling**

```python
from openai_codex import retry_on_overload

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

资料来源：[sdk/python/README.md:19-30](../sdk/python/README.md)

### TypeScript SDK

| Property | Value |
|----------|-------|
| Package Name | `@openai/codex-sdk` |
| Minimum Node Version | `>=18` |
| Module Type | ESM (`import`) |
| Type Definitions | `./dist/index.d.ts` |

#### Build and Development Scripts

| Script | Purpose |
|--------|---------|
| `pnpm build` | Compile TypeScript to JavaScript |
| `pnpm build:watch` | Watch mode for development |
| `pnpm lint` | Run ESLint |
| `pnpm lint:fix` | Auto-fix linting issues |
| `pnpm test` | Run Jest test suite |
| `pnpm coverage` | Generate test coverage report |
| `pnpm format` | Check Prettier formatting |
| `pnpm format:fix` | Auto-fix formatting |
| `pnpm prepare` | Build on package install (git hooks) |

资料来源：[sdk/typescript/package.json:8-34](../sdk/typescript/package.json)

## MCP Server Integration

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

```mermaid
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:

```bash
codex mcp-server
```

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

资料来源：[codex-rs/README.md:38-45](../codex-rs/README.md)

## File Search Component

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

| Feature | Description |
|---------|-------------|
| Core Library | `ignore` crate (used by ripgrep) for directory traversal |
| Matching Engine | `nucleo-matcher` for fuzzy matching |
| Git Integration | Honors `.gitignore` rules |
| Use Case | Tool for searching codebase files efficiently |

资料来源：[file-search/README.md](../file-search/README.md)

## SDK Installation

### Python

```bash
# Install using pip
pip install openai-codex

# Or via poetry
poetry add openai-codex
```

### TypeScript

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

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

### Standalone CLI

For scenarios requiring direct CLI usage:

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

# Or via Homebrew
brew install --cask codex
```

资料来源：[sdk/python/README.md](../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.

资料来源：[sdk/python/README.md:11-13](../sdk/python/README.md)

## Related Documentation

- [Getting Started Guide](../docs/getting-started.md) - Onboarding for new users
- [Configuration Reference](../docs/config.md) - SDK and runtime configuration
- [Installation Guide](../docs/install.md) - Detailed installation instructions
- [MCP Configuration](../docs/config.md#connecting-to-mcp-servers) - MCP server setup

---

<a id='agent-system'></a>

## Agent System

### 相关页面

相关主题：[System Architecture Overview](#architecture-overview), [Tools and Handlers](#tools-and-handlers), [Session Management](#session-management)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [codex-rs/core/src/agent/mod.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/agent/mod.rs)
- [codex-rs/core/src/agent/registry.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/agent/registry.rs)
- [codex-rs/core/src/agent/role.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/agent/role.rs)
- [codex-rs/core/src/agent/mailbox.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/agent/mailbox.rs)
- [codex-rs/core/src/agents_md.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/agents_md.rs)
- [codex-rs/core/src/context/environment_context.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/context/environment_context.rs)
- [codex-rs/tui/src/slash_command.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/slash_command.rs)
- [codex-rs/config/src/config_toml.rs](https://github.com/openai/codex/blob/main/codex-rs/config/src/config_toml.rs)
</details>

# 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

资料来源：[codex-rs/core/src/agents_md.rs]()

## Architecture

```mermaid
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:**

| Method | Purpose |
|--------|---------|
| `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 |

资料来源：[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:**

| Role | Description |
|------|-------------|
| `Primary` | Main Codex agent handling user interactions |
| `Subagent` | Specialized worker agent for delegated tasks |
| `Reviewer` | Agent focused on code review and approval |
| `Researcher` | Agent that gathers information and context |
| `Executor` | Agent that executes code and commands |

资料来源：[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:**

| Type | Purpose |
|------|---------|
| `Task` | Work assignment from one agent to another |
| `Result` | Response containing task completion or failure |
| `Event` | Notification of state changes or external events |
| `Query` | Request for information or context |

**Mailbox Operations:**

```rust
// 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>
```

资料来源：[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

资料来源：[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:

| Command | Description | Inline Args Supported |
|---------|-------------|----------------------|
| `/agent` | Switch the active agent thread | No |
| `/multiagents` | Manage multiple agent threads | No |
| `/side` | Start a side conversation in an ephemeral fork | Yes |

资料来源：[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:

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

资料来源：[codex-rs/core/src/context/environment_context.rs:95-98]()

## Configuration

### Profile Configuration

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

```toml
[profile.work]
# Agent-specific settings for the 'work' profile
include_environment_context = true
```

| Setting | Type | Purpose |
|---------|------|---------|
| `include_environment_context` | `bool` | Whether to inject environment context including subagents |
| `include_collaboration_mode_instructions` | `bool` | Include collaboration mode developer block |

资料来源：[codex-rs/config/src/config_toml.rs:89-92]()

## Workflows

### Multi-Agent Thread Switching

```mermaid
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

```mermaid
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

```mermaid
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

```mermaid
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:

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

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

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

资料来源：[codex-rs/core/src/goals.rs:55-60]()

## Status Line Integration

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

| Status Item | Display | Category |
|-------------|---------|----------|
| `ThreadTitle` | Current agent thread title | Thread |
| `TaskProgress` | Tasks X/Y progress | Progress |
| `Model` | Active model name | Type |
| `FastMode` | Fast mode indicator | Mode |

Status items are styled using scope-based syntax highlighting:

| Style | Scopes |
|-------|--------|
| Thread | `markup.heading`, `entity.name.section` |
| Progress | `markup.inserted`, `constant.numeric` |
| Mode | `storage.modifier`, `keyword.operator` |

资料来源：[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:

```rust
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:

```toml
[mcp]
# MCP server configuration for extended agent tools
```

资料来源：[codex-rs/README.md](https://github.com/openai/codex/blob/main/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.

---

<a id='tools-and-handlers'></a>

## Tools and Handlers

### 相关页面

相关主题：[Agent System](#agent-system), [Command Execution](#command-execution), [Sandboxing](#sandboxing)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [codex-rs/core/src/tools/mod.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/tools/mod.rs)
- [codex-rs/core/src/tools/registry.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/tools/registry.rs)
- [codex-rs/core/src/tools/orchestrator.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/tools/orchestrator.rs)
- [codex-rs/tools/src/tool_definition.rs](https://github.com/openai/codex/blob/main/codex-rs/tools/src/tool_definition.rs)
- [codex-rs/core/src/tools/handlers/shell.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/tools/handlers/shell.rs)
- [codex-rs/core/src/tools/handlers/apply_patch.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/tools/handlers/apply_patch.rs)
</details>

# 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:

```mermaid
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:

| Component | Description |
|-----------|-------------|
| `name` | Unique identifier for the tool |
| `description` | Human-readable description of tool purpose |
| `parameters` | JSON Schema defining input parameters |
| `handler` | Reference to the implementation function |
| `capabilities` | Permission scopes required |

资料来源：[codex-rs/tools/src/tool_definition.rs](https://github.com/openai/codex/blob/main/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.

| Function | Purpose |
|----------|---------|
| `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 |

资料来源：[codex-rs/core/src/tools/registry.rs](https://github.com/openai/codex/blob/main/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

资料来源：[codex-rs/core/src/tools/orchestrator.rs](https://github.com/openai/codex/blob/main/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.

```mermaid
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

资料来源：[codex-rs/core/src/tools/handlers/shell.rs](https://github.com/openai/codex/blob/main/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

```mermaid
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

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `include_apply_patch_tool` | bool | true | Enable/disable the tool |
| `experimental_use_freeform_apply_patch` | bool | false | Allow unstructured patches |

资料来源：[codex-rs/core/src/tools/handlers/apply_patch.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/tools/handlers/apply_patch.rs)

## Tool Execution Flow

The complete tool execution lifecycle follows this sequence:

```mermaid
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

资料来源：[codex-rs/core/src/tools/mod.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/tools/mod.rs)

## Configuration Integration

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

| Config Section | Setting | Purpose |
|----------------|---------|---------|
| `[features]` | Feature toggles | Enable/disable specific tools |
| `[profile.tui]` | UI settings | Configure tool presentation |
| `[permissions]` | Capability scope | Restrict tool access |

资料来源：[codex-rs/config/src/config_toml.rs](https://github.com/openai/codex/blob/main/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:

| Command | Related Tool |
|---------|--------------|
| `/review` | Code review tool |
| `/plan` | Plan mode activation |
| `/goal` | Task goal management |
| `/mcp` | MCP tool listing |
| `/ide` | IDE context integration |

资料来源：[codex-rs/tui/src/slash_command.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/slash_command.rs)

## Error Handling

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

| Error Type | Description | Recovery Action |
|------------|-------------|-----------------|
| `ToolNotFound` | Requested tool does not exist | Suggest alternatives |
| `PermissionDenied` | Insufficient capabilities | Request authorization |
| `ExecutionFailed` | Handler execution error | Log and retry |
| `TimeoutExceeded` | Command exceeded time limit | Kill and report |
| `InvalidParameters` | Malformed input | Return 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

资料来源：[codex-rs/core/src/tools/handlers/shell.rs](https://github.com/openai/codex/blob/main/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

资料来源：[codex-rs/tui/src/markdown_render_tests.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/markdown_render_tests.rs)

---

<a id='session-management'></a>

## Session Management

### 相关页面

相关主题：[Agent System](#agent-system)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [codex-rs/app-server-protocol/src/protocol/v2/thread_data.rs](https://github.com/openai/codex/blob/main/codex-rs/app-server-protocol/src/protocol/v2/thread_data.rs)
- [codex-rs/config/src/state.rs](https://github.com/openai/codex/blob/main/codex-rs/config/src/state.rs)
- [codex-rs/tui/src/slash_command.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/slash_command.rs)
- [codex-rs/tui/src/bottom_pane/status_surface_preview.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/bottom_pane/status_surface_preview.rs)
- [codex-rs/tui/src/chatwidget/status_surfaces.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/chatwidget/status_surfaces.rs)
- [codex-rs/README.md](https://github.com/openai/codex/blob/main/codex-rs/README.md)

Note: The core session management module files (`session/mod.rs`, `session/session.rs`, `session/turn.rs`, `context_manager/mod.rs`, `thread_manager.rs`) were referenced in the query but not included in the retrieved context. This page is based on the available files and related session-related components found in the codebase.

</details>

# 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`). 资料来源：[README.md:1-10]()

The Rust implementation serves as the maintained Codex CLI and provides a rich set of configuration options through `config.toml`. 资料来源：[codex-rs/README.md:1-20]()

---

## Session Architecture

### Session Sources

Sessions in Codex can originate from multiple entry points, each represented by a `SessionSource` enum that tracks where a session was initiated. The core session sources are mapped between the application protocol and core protocol layers.

```mermaid
graph TD
    A[SessionSource] --> B[CoreSessionSource]
    A --> C[App Server Protocol]
    B --> D[Core Implementation]
    
    A1[Cli] --> B1[Cli]
    A2[VsCode] --> B2[VSCode]
    A3[Exec] --> B3[Exec]
    A4[Mcp] --> B4[MCP - AppServer]
    A5[Custom] --> B5[Custom source]
    A6[SubAgent] --> B6[SubAgent]
    
    A7[Internal] --> B7[Unknown - Not rendered]
    A8[Unknown] --> B8[Unknown]
```

**SessionSource Enum (App Server Protocol)**

| Variant | Description |
|---------|-------------|
| `Cli` | Session initiated from command-line interface |
| `VsCode` | Session from VS Code IDE extension |
| `Exec` | Session from direct execution mode |
| `AppServer` | Session via Model Context Protocol server |
| `Custom(source)` | Custom-defined session source |
| `SubAgent(sub)` | Session created by a sub-agent |
| `Unknown` | Unclassified session source |

资料来源：[codex-rs/app-server-protocol/src/protocol/v2/thread_data.rs:1-50]()

The mapping between `CoreSessionSource` and `SessionSource` ensures consistent session tracking across protocol layers, with internal sources filtered out at the app-server level. 资料来源：[codex-rs/app-server-protocol/src/protocol/v2/thread_data.rs:50-80]()

---

## Thread Management

### Thread Sources

Threads represent individual conversational contexts within a session. Each thread has a `ThreadSource` that categorizes its origin:

| ThreadSource | Description |
|--------------|-------------|
| `User` | Thread initiated by direct user interaction |
| `Subagent` | Thread created by an agent subprocess |
| `MemoryConsolidation` | Thread generated during memory consolidation |

资料来源：[codex-rs/app-server-protocol/src/protocol/v2/thread_data.rs:80-100]()

---

## Configuration Layers and Session State

### Config Layer Sources

Codex uses a layered configuration system where session behavior can be controlled through multiple sources. The precedence order (from lowest to highest) determines which setting takes effect.

| ConfigLayerSource | Description | Path Reference |
|-------------------|-------------|-----------------|
| `System` | System-wide configuration | `/etc/codex/config.toml` |
| `User` | Per-user configuration | `~/.config/codex/config.toml` |
| `Project` | Project-specific configuration | `./.codex/config.toml` |
| `SessionFlags` | Command-line session flags | Runtime arguments |
| `Mdm` | Mobile Device Management policy | MDM enrollment |
| `LegacyManagedConfigTomlFromFile` | Legacy managed config | Specified file path |
| `LegacyManagedConfigTomlFromMdm` | Legacy MDM config | MDM enrollment |

资料来源：[codex-rs/config/src/state.rs:1-50]()

The `ConfigLayerStack` struct manages layers from lowest precedence (base) to highest (top), where later entries override earlier ones. 资料来源：[codex-rs/config/src/state.rs:50-80]()

### Session Configuration Folder

The hooks configuration folder determines where lifecycle hooks are declared:

```mermaid
graph LR
    A[Hooks Config Folder] --> B{Hooks Override Set?}
    B -->|Yes| C[Use Override Path]
    B -->|No| D{Project Layer Exists?}
    D -->|Yes| E[Use .codex/ Folder]
    D -->|No| F[Use Config Folder]
    
    G[Git Worktree] --> H[Point to Root .codex/]
```

资料来源：[codex-rs/config/src/state.rs:80-120]()

---

## Status Line Integration

### Session Status Display

The status line provides real-time session information. The `StatusLineItem` enum controls what information appears:

| Status Item | Display Format | Description |
|-------------|-----------------|-------------|
| `SessionId` | `550e8400-e29b-41d4` | Current thread identifier |
| `Model` | `gpt-5.2-codex` | Current model name |
| `ModelWithReasoning` | `gpt-5.2-codex medium` | Model with reasoning level |
| `ThreadTitle` | User-defined or ID | Current thread title |
| `TaskProgress` | `Tasks 0/0` | Progress from update_plan |

资料来源：[codex-rs/tui/src/bottom_pane/status_surface_preview.rs:1-30]()

### Session Status Categories

Status items are grouped by semantic category for styling and filtering:

| Category | Items | Syntax Scope |
|----------|-------|--------------|
| `Model` | Model name | `entity.name.type` |
| `Path` | File/directory paths | `string` |
| `Branch` | Git branch info | `entity.name.function` |
| `State` | Run state (Ready/Working) | `keyword.control` |
| `Usage` | Token counts | `constant.numeric` |
| `Limit` | Usage limits | `constant.language` |
| `Metadata` | Version, Session ID | `comment` |
| `Mode` | Fast mode, permissions | `storage.modifier` |
| `Thread` | Thread titles | `markup.heading` |
| `Progress` | Task progress | `markup.inserted` |

资料来源：[codex-rs/tui/src/bottom_pane/status_line_style.rs:1-40]()

---

## Slash Commands for Session Control

Codex provides slash commands that interact with session management:

| Command | Function |
|---------|----------|
| `/resume` | Resume a saved chat |
| `/fork` | Fork the current chat into a new session |
| `/title` | Configure terminal title items |
| `/status` | Show current session configuration and token usage |
| `/clear` | Clear terminal and start new chat |
| `/quit` or `/exit` | Exit Codex |
| `/permissions` | Choose what Codex is allowed to do |

资料来源：[codex-rs/tui/src/slash_command.rs:1-50]()

### Session Debugging

The `/debug-config` command displays config layers and requirement sources for debugging purposes:

```mermaid
graph TD
    A[/debug-config] --> B[Show Config Layers]
    A --> C[Show Requirement Sources]
    
    B --> D[System Config]
    B --> E[User Config]
    B --> F[Project Config]
    B --> G[Session Flags]
    
    C --> H[Sandbox Mode]
    C --> I[Residency Requirements]
    C --> J[Network Constraints]
```

| Requirement Type | Values |
|------------------|--------|
| Sandbox Mode | `read-only`, `workspace-write`, `danger-full-access`, `external-sandbox` |
| Residency | `us` |
| Network Constraints | HTTP/SOCKS ports, domain allowlists, proxy settings |

资料来源：[codex-rs/tui/src/debug_config.rs:1-40]()

---

## Token Usage Tracking

### Session Usage Metrics

Codex tracks token usage throughout a session with the following metrics:

| Metric | Display | Description |
|--------|---------|-------------|
| `UsedTokens` | `0 used` | Total tokens used in session |
| `TotalInputTokens` | `0 in` | Total input tokens |
| `TotalOutputTokens` | `0 out` | Total output tokens |
| `ContextRemaining` | `Context 0% left` | Context window remaining |
| `ContextUsed` | `Context 0% used` | Context window used |
| `ContextWindowSize` | `0 window` | Total context window size |

Usage is omitted when values are zero or unavailable. 资料来源：[codex-rs/tui/src/bottom_pane/status_line_setup.rs:1-50]()

### Usage Limits

Session tracking includes usage limit monitoring:

| Limit Type | Display Format | Description |
|------------|-----------------|-------------|
| `FiveHourLimit` | `5h 0%` | Remaining on 5-hour usage limit |
| `WeeklyLimit` | `weekly 0%` | Remaining weekly limit |

资料来源：[codex-rs/tui/src/chatwidget/status_surfaces.rs:1-40]()

---

## Multi-Agent Session Support

Codex supports multi-agent sessions where sub-agents can create their own threads. The session source mapping includes special handling for sub-agents:

```mermaid
graph TD
    A[Main Session] --> B[User Session]
    A --> C[SubAgent Session]
    
    C --> D[SubAgent Thread]
    C --> E[Memory Consolidation Thread]
    
    B --> F[Main Conversation]
    D --> G[Agent Task Execution]
```

The `CoreSessionSource::SubAgent(sub)` variant tracks sessions created by agent subprocesses, while `ThreadSource::MemoryConsolidation` identifies threads generated during memory consolidation operations. 资料来源：[codex-rs/app-server-protocol/src/protocol/v2/thread_data.rs:80-120]()

---

## Summary

Session Management in Codex CLI encompasses:

1. **Session Lifecycle**: Tracking sessions from multiple sources (CLI, VS Code, MCP, Exec)
2. **Thread Management**: Maintaining conversational contexts with source tracking
3. **Configuration Layers**: Layered config precedence from system to session level
4. **Status Integration**: Real-time session information display in status line and title bar
5. **Token Usage**: Comprehensive tracking of input/output tokens and context utilization
6. **Multi-Agent Support**: Sub-agent session isolation and memory consolidation threads

The architecture uses protocol-layer mapping to ensure consistent session tracking across the application and core layers, with configuration-driven behavior through TOML files. 资料来源：[codex-rs/README.md:1-30]()

---

<a id='command-execution'></a>

## Command Execution

### 相关页面

相关主题：[Sandboxing](#sandboxing), [Tools and Handlers](#tools-and-handlers)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [codex-rs/tui/src/slash_command.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/slash_command.rs)
- [codex-rs/core/src/context/environment_context.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/context/environment_context.rs)
- [codex-rs/tui/src/bottom_pane/approval_overlay.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/bottom_pane/approval_overlay.rs)
- [codex-rs/config/src/state.rs](https://github.com/openai/codex/blob/main/codex-rs/config/src/state.rs)
- [codex-rs/core/src/agent/control.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/agent/control.rs)
- [codex-rs/tui/src/chatwidget/status_surfaces.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/chatwidget/status_surfaces.rs)
</details>

# 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

```mermaid
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:

| Command | Description | Inline Args |
|---------|-------------|-------------|
| `/resume` | Resume a saved chat session | No |
| `/clear` | Clear terminal and start new chat | No |
| `/fork` | Fork the current chat | No |
| `/ps` | List background terminals | No |
| `/stop` | Stop all background terminals | No |
| `/status` | Show current session configuration and token usage | No |

资料来源：[codex-rs/tui/src/slash_command.rs:1-50](https://github.com/openai/codex/blob/main/codex-rs/tui/src/slash_command.rs)

### Approval Decisions

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

| Option | Decision | Effect |
|--------|----------|--------|
| "Yes, proceed" | `FileChangeApprovalDecision::Accept` | Execute immediately |
| "Yes, don't ask again for these files" | `FileChangeApprovalDecision::AcceptForSession` | Execute and bypass for session |
| "No, tell Codex what to do differently" | Decline | Abort with feedback |

资料来源：[codex-rs/tui/src/bottom_pane/approval_overlay.rs:1-30](https://github.com/openai/codex/blob/main/codex-rs/tui/src/bottom_pane/approval_overlay.rs)

### Environment Context

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

```xml
<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>
```

资料来源：[codex-rs/core/src/context/environment_context.rs:1-50](https://github.com/openai/codex/blob/main/codex-rs/core/src/context/environment_context.rs)

## Execution Flow

```mermaid
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:

| Layer | Priority | Source |
|-------|----------|--------|
| System | Lowest | System-level config file |
| User | Medium | User home directory config |
| Project | High | `.codex/` folder |
| Session Flags | Highest | Command-line arguments |

资料来源：[codex-rs/config/src/state.rs:1-30](https://github.com/openai/codex/blob/main/codex-rs/config/src/state.rs)

## Status Display

The status line shows execution-related information:

| Status Item | Display Format | Description |
|-------------|----------------|-------------|
| `Status` | Run state text | Current agent operation state |
| `Permissions` | Workspace/Full | Permission level display |
| `ApprovalMode` | on-request/auto | Current approval mode |
| `ContextRemaining` | Context X% left | Remaining context window |

资料来源：[codex-rs/tui/src/chatwidget/status_surfaces.rs:1-50](https://github.com/openai/codex/blob/main/codex-rs/tui/src/chatwidget/status_surfaces.rs)

## Inter-Agent Communication

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

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

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

资料来源：[codex-rs/core/src/agent/control.rs:1-30](https://github.com/openai/codex/blob/main/codex-rs/core/src/agent/control.rs)

## Keyboard Shortcuts

The terminal UI provides shortcuts for managing command execution:

| Shortcut | Action | Description |
|----------|--------|-------------|
| `QueueMessageTab` | Queue Message Tab | Queue commands for batch execution |
| `HistorySearch` | History Search | Search command history |
| `EditPrevious` | Edit Previous | Modify last command |
| `ExternalEditor` | External Editor | Open command in external editor |

资料来源：[codex-rs/tui/src/bottom_pane/footer.rs:1-40](https://github.com/openai/codex/blob/main/codex-rs/tui/src/bottom_pane/footer.rs)

## File System Path Resolution

Commands execute within sandboxed file system contexts:

| Path Type | Format | Description |
|-----------|--------|-------------|
| Root | `:root` | Repository root |
| Minimal | `:minimal` | Minimal sandbox scope |
| Project Roots | `:project_roots` | All project root directories |
| Tmpdir | `:tmpdir` | System temp directory |
| Custom | `/path/to/dir` | User-specified path |

资料来源：[codex-rs/tui/src/bottom_pane/approval_overlay.rs:30-60](https://github.com/openai/codex/blob/main/codex-rs/tui/src/bottom_pane/approval_overlay.rs)

## 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

| Task | Command |
|------|---------|
| View current status | `/status` |
| List background jobs | `/ps` |
| Stop all jobs | `/stop` |
| Clear terminal | `/clear` |
| Fork session | `/fork` |

---

*This page provides technical documentation for the Command Execution system in Codex CLI. For configuration options, see [Config Documentation](../config.md).*

---

<a id='sandboxing'></a>

## Sandboxing

### 相关页面

相关主题：[Command Execution](#command-execution)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [codex-rs/sandboxing/src/lib.rs](https://github.com/openai/codex/blob/main/codex-rs/sandboxing/src/lib.rs)
- [codex-rs/linux-sandbox/src/lib.rs](https://github.com/openai/codex/blob/main/codex-rs/linux-sandbox/src/lib.rs)
- [codex-rs/windows-sandbox-rs/src/lib.rs](https://github.com/openai/codex/blob/main/codex-rs/windows-sandbox-rs/src/lib.rs)
- [codex-rs/core/src/sandboxing/mod.rs](https://github.com/openai/codex/blob/main/codex-rs/core/src/sandboxing/mod.rs)
- [docs/sandbox.md](https://github.com/openai/codex/blob/main/docs/sandbox.md)
</details>

# 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

资料来源：[codex-rs/README.md](https://github.com/openai/codex/blob/main/codex-rs/README.md)

## Sandbox Modes

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

| Mode | Description | Use Case |
|------|-------------|----------|
| `read-only` | Default mode. Codex can read files but cannot modify them | Production environments, sensitive codebases |
| `workspace-write` | Allows file modifications within the workspace and memories | Active development with controlled modifications |
| `danger-full-access` | Disables all sandboxing | Isolated environments (containers), CI/CD pipelines |
| `external-sandbox` | Delegates sandboxing to an external provider | Advanced configurations requiring custom enforcement |

资料来源：[codex-rs/README.md](https://github.com/openai/codex/blob/main/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:

```shell
# 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`:

```toml
sandbox_mode = "workspace-write"
```

#### Inline Configuration Override

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

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

资料来源：[codex-rs/README.md](https://github.com/openai/codex/blob/main/codex-rs/README.md)

## Architecture

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

```mermaid
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

| Component | Path | Purpose |
|-----------|------|---------|
| Sandbox Abstraction | `codex-rs/core/src/sandboxing/mod.rs` | Defines the unified sandbox interface and policy enforcement |
| Linux Implementation | `codex-rs/linux-sandbox/src/lib.rs` | Implements sandboxing using Landlock |
| Windows Implementation | `codex-rs/windows-sandbox-rs/src/lib.rs` | Implements sandboxing using Windows security features |
| macOS Implementation | `codex-rs/sandboxing/src/lib.rs` | Implements 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:

```shell
codex debug landlock [COMMAND]...
```

资料来源：[codex-rs/README.md](https://github.com/openai/codex/blob/main/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

资料来源：[codex-rs/windows-sandbox-rs/src/lib.rs](https://github.com/openai/codex/blob/main/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

```toml
# In workspace-write mode, memories are included in writable roots
# so memory maintenance does not require additional approval
```

资料来源：[codex-rs/README.md](https://github.com/openai/codex/blob/main/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)

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

Parameters:

| Parameter | Description |
|-----------|-------------|
| `--log-denials` | Enable logging of denied access attempts |
| `COMMAND` | Optional subcommand for specific debug operations |

### Landlock Debug (Linux)

```shell
codex debug landlock [COMMAND]...
```

## Configuration Integration

### ConfigLayerSource Mapping

Sandbox requirements are tracked through the configuration layer system:

| ConfigLayerSource | Sandbox Behavior |
|-------------------|------------------|
| System | Uses system-wide sandbox settings |
| User | Uses user-local configuration |
| Project | Uses project `.codex/` configuration |
| SessionFlags | Override via command-line flags |

### State Persistence

The `ConfigLayerStack` maintains sandbox mode across sessions:

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

资料来源：[codex-rs/config/src/state.rs](https://github.com/openai/codex/blob/main/codex-rs/config/src/state.rs)

## Requirements and Constraints

### SandboxModeRequirement Enum

The system tracks sandbox requirements as an enum:

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

### Residency Requirements

Certain configurations may impose residency requirements:

```rust
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

| Environment | Recommended Mode | Rationale |
|-------------|------------------|-----------|
| Production Server | `read-only` | Maximum security |
| Local Development | `workspace-write` | Balance of safety and utility |
| Container (Isolated) | `danger-full-access` | Container provides isolation |
| CI/CD Pipeline | `read-only` or `danger-full-access` | Depends on pipeline isolation |

## External Resources

- [Landlock LSM Documentation](https://docs.kernel.org/userspace-api/landlock.html)
- [Windows Security Documentation](https://learn.microsoft.com/en-us/windows/security/)
- [macOS Seatbelt Documentation](https://developer.apple.com/library/archive/documentation/Security/Conceptual/AppSandboxDesignGuide/)

---

<a id='terminal-ui'></a>

## Terminal UI

### 相关页面

相关主题：[System Architecture Overview](#architecture-overview)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [codex-rs/tui/src/slash_command.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/slash_command.rs)
- [codex-rs/tui/src/bottom_pane/footer.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/bottom_pane/footer.rs)
- [codex-rs/tui/src/bottom_pane/title_setup.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/bottom_pane/title_setup.rs)
- [codex-rs/tui/src/bottom_pane/status_line_style.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/bottom_pane/status_line_style.rs)
- [codex-rs/tui/src/chatwidget/status_surfaces.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/chatwidget/status_surfaces.rs)
- [codex-rs/tui/src/chatwidget/slash_dispatch.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/chatwidget/slash_dispatch.rs)
- [codex-rs/tui/src/markdown.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/markdown.rs)
- [codex-rs/tui/src/markdown_render.rs](https://github.com/openai/codex/blob/main/codex-rs/tui/src/markdown_render.rs)
- [codex-rs/config/src/tui_keymap.rs](https://github.com/openai/codex/blob/main/codex-rs/config/src/tui_keymap.rs)
- [codex-rs/config/src/profile_toml.rs](https://github.com/openai/codex/blob/main/codex-rs/config/src/profile_toml.rs)
- [codex-rs/config/src/config_toml.rs](https://github.com/openai/codex/blob/main/codex-rs/config/src/config_toml.rs)
</details>

# 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. 资料来源：[codex-rs/README.md]()

## Architecture

```mermaid
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

资料来源：[codex-rs/tui/src/chatwidget.rs:1-100]()

### Bottom Pane

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

| Component | File | Purpose |
|-----------|------|---------|
| Footer | `bottom_pane/footer.rs` | Displays keyboard shortcuts and hints |
| Title Setup | `bottom_pane/title_setup.rs` | Terminal title configuration |
| Status Line Style | `bottom_pane/status_line_style.rs` | Status line visual styling |
| Status Surface Preview | `bottom_pane/status_surface_preview.rs` | Preview status items |

资料来源：[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`.

| Command | Description |
|---------|-------------|
| `/resume` | Resume a saved chat |
| `/clear` | Clear terminal and start new chat |
| `/fork` | Fork the current chat |
| `/quit` or `/exit` | Exit Codex |
| `/copy` | Copy last response as markdown |
| `/diff` | Show git diff including untracked files |
| `/model` | Choose model and reasoning effort |
| `/theme` | Choose syntax highlighting theme |
| `/pets` | Choose or hide terminal pet |
| `/keymap` | Remap TUI shortcuts |
| `/settings` | Configure realtime microphone/speaker |
| `/plan` | Switch to Plan mode |
| `/ide` | Include IDE context (selection, open files) |
| `/mcp` | List configured MCP tools |

资料来源：[codex-rs/tui/src/slash_command.rs:1-60]()
资料来源：[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

| Element | Tags Handled |
|---------|--------------|
| Code Blocks | Fenced and indented |
| Tables | Header, rows, cells, alignments |
| Lists | Ordered and unordered |
| Links | Standard and reference-style |
| Images | Block-level images |
| Headings | H1-H6 |
| Emphasis | Italic, bold, strikethrough |
| Blockquotes | Nested blockquotes |
| Footnotes | Definition and reference |

资料来源：[codex-rs/tui/src/markdown.rs:1-40]()
资料来源：[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

| Item | Description |
|------|-------------|
| `AppName` | Codex application name |
| `ProjectName` | Current project name |
| `ProjectRoot` | Project root path |
| `CurrentDir` | Current working directory |
| `Status` | Session run-state (Ready, Working, Thinking) |
| `GitBranch` | Current Git branch |
| `PullRequestNumber` | Current PR number |
| `ContextRemaining` | Context window remaining % |
| `ContextUsed` | Context window used % |
| `FiveHourLimit` | Remaining 5-hour usage |
| `WeeklyLimit` | Remaining weekly usage |
| `UsedTokens` | Total session tokens |
| `TotalInputTokens` | Total input tokens |
| `TotalOutputTokens` | Total output tokens |
| `Model` | Current model name |
| `ModelWithReasoning` | Model with reasoning level |
| `FastMode` | Fast mode status |
| `SessionId` | Current thread identifier |
| `TaskProgress` | Latest task progress |
| `CodexVersion` | Application version |

### Status Line Styling

Status line items are styled with semantic colors:

| Item Type | Default Color | Highlight Scopes |
|-----------|--------------|------------------|
| Model, State, Metadata, Mode | Cyan | `constant.language`, `storage.type` |
| Path, Usage, Progress | Green | N/A |
| Branch, Limit, Thread | Magenta | `markup.heading`, `entity.name.section` |

资料来源：[codex-rs/tui/src/chatwidget/status_surfaces.rs:1-60]()
资料来源：[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

```rust
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
}
```

资料来源：[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

| Category | Bindings |
|----------|----------|
| `Exit` | Exit normal mode |
| `Cancel` | Cancel pending operator |
| `Write` | Enter insert mode |
| `OneDown` / `OneUp` | Line navigation |
| `PageDown` / `PageUp` | Page navigation |
| `Top` / `Bottom` | Jump to start/end |
| `HalfPageDown` / `HalfPageUp` | Half-page scroll |

#### Insert Mode

| Category | Bindings |
|----------|----------|
| `Exit` | Return to normal mode |
| `Cancel` | Return to normal mode |
| `TextInsert` | Insert text |
| `TextOverwrite` | Overwrite text |
| `Newline` | Insert newline |
| `Backspace` | Delete character |
| `Delete` | Delete forward |
| `MotionLeft` / `MotionRight` | Character movement |
| `MotionWordForward` / `MotionWordBackward` | Word movement |
| `MotionLineStart` / `MotionLineEnd` | Line navigation |

#### Visual Mode

| Category | Bindings |
|----------|----------|
| `Exit` | Exit visual mode |
| `MotionLeft` / `MotionRight` | Extend selection |
| `MotionWordForward` / `MotionWordBackward` | Word selection |
| `MotionLineStart` / `MotionLineEnd` | Line selection |

#### Composer/Pager

| Category | Bindings |
|----------|----------|
| `ScrollUp` / `ScrollDown` | Row scroll |
| `PageUp` / `PageDown` | Page scroll |
| `HalfPageUp` / `HalfPageDown` | Half-page scroll |

#### Motion

| Category | Bindings |
|----------|----------|
| `MotionUp` / `MotionDown` | Line movement |
| `MotionWordForward` / `MotionWordBackward` | Word movement |
| `MotionWordEnd` | End of word |
| `MotionLineStart` / `MotionLineEnd` | Line boundaries |

资料来源：[codex-rs/config/src/tui_keymap.rs:1-80]()

## Footer/Hint Bar

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"`

资料来源：[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`:

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

### Global TUI Settings

| Setting | Type | Description |
|---------|------|-------------|
| `hide_agent_reasoning` | bool | Hide `AgentReasoning` events from UI |
| `show_raw_agent_reasoning` | bool | Show raw reasoning content |
| `model_reasoning_effort` | ReasoningEffort | Default reasoning effort |
| `plan_mode_reasoning_effort` | ReasoningEffort | Plan mode reasoning effort |
| `model_reasoning_summary` | ReasoningSummary | Reasoning summary preference |

### Session Picker View Modes

| Mode | Description |
|------|-------------|
| Default | Standard picker layout |
| Compact | Compact layout for limited screen space |

资料来源：[codex-rs/config/src/profile_toml.rs:1-50]()
资料来源：[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.

资料来源：[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

资料来源：[codex-rs/tui/src/markdown_render_tests.rs:1-80]()

---

---

## Doramagic Pitfall Log

Project: openai/codex

Summary: Found 38 potential pitfall items; 31 are high/blocking. Highest priority: installation - 来源证据：Chat Tree lost all my chats.

## 1. installation · 来源证据：Chat Tree lost all my chats

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Chat Tree lost all my chats
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_316a526cbdc34e4a8406883ed5e12db3 | https://github.com/openai/codex/issues/23966 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。

## 2. installation · 来源证据：Chrome plugin fails after reinstall: browser-client is not trusted / native pipe bridge unavailable

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Chrome plugin fails after reinstall: browser-client is not trusted / native pipe bridge unavailable
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_773cc88b045c42269ea29062305a9c79 | https://github.com/openai/codex/issues/23884 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 3. installation · 来源证据：Codex Desktop: cannot enable Computer Use or Mobile Remote on macOS

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Codex Desktop: cannot enable Computer Use or Mobile Remote on macOS
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_4aa7e908bdb841b6b68750ec55df7265 | https://github.com/openai/codex/issues/24000 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。

## 4. installation · 来源证据：Codex app is much slower after latest update: Fast mode feels like Standard, with slow thinking/searching/compaction

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Codex app is much slower after latest update: Fast mode feels like Standard, with slow thinking/searching/compaction
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_1f6f2bb6e0ec469698d2edea17f50a91 | https://github.com/openai/codex/issues/23998 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。

## 5. configuration · 来源证据：Codex App: View > Toggle File Tree is enabled but does not reliably reveal the file tree

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Codex App: View > Toggle File Tree is enabled but does not reliably reveal the file tree
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_d6b72554a15848bfb95172780b532c45 | https://github.com/openai/codex/issues/20552 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。

## 6. configuration · 来源证据：Codex Desktop project chat histories disappeared after recent update

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Codex Desktop project chat histories disappeared after recent update
- User impact: 可能影响升级、迁移或版本选择。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_82944ed619034fcf9aa3f8f130983929 | https://github.com/openai/codex/issues/20741 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。

## 7. configuration · 来源证据：Codex Usage Web Bug: Personal Usage Chart Not Loading

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Codex Usage Web Bug: Personal Usage Chart Not Loading
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_dc1ef6f92a514860b9b5004ef2950202 | https://github.com/openai/codex/issues/23686 | 来源类型 github_issue 暴露的待验证使用条件。

## 8. maintenance · 来源证据：Codex Desktop sidebar chat history disappears and latest update does not restore hidden chats

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：Codex Desktop sidebar chat history disappears and latest update does not restore hidden chats
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_b88b186735994b41ac9546e7c3c4a220 | https://github.com/openai/codex/issues/23999 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。

## 9. security_permissions · 失败模式：security_permissions: Allow interactive editing of sandbox permission requests

- Severity: high
- Evidence strength: source_linked
- Finding: Developers should check this security_permissions risk before relying on the project: Allow interactive editing of sandbox permission requests
- User impact: 该失败模式可能影响开发者安装、配置、运行或升级，需要在能力资产里前置说明。
- Suggested 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.
- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/openai/codex/issues/23227
- Evidence: failure_mode_cluster:unknown | fmev_fea80d3c93f2c2f5715766d1529166bb | security_permissions: Allow interactive editing of sandbox permission requests

## 10. security_permissions · 失败模式：security_permissions: Codex CLI /permissions omits Read-only in WSL2 but shows it in Windows PowerShell

- Severity: high
- Evidence strength: source_linked
- 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
- Suggested 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
- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/openai/codex/issues/23626
- 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_permissions · 失败模式：security_permissions: Codex Desktop voice transcription blocked by Cloudflare challenge on /backend-api/transcribe...

- Severity: high
- Evidence strength: source_linked
- 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
- Suggested 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
- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/openai/codex/issues/21985
- 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_permissions · 失败模式：security_permissions: Codex Desktop: Computer Use blocks get_app_state(Codex) with "not allowed ... for safety reas...

- Severity: high
- Evidence strength: source_linked
- 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: 该失败模式可能影响开发者安装、配置、运行或升级，需要在能力资产里前置说明。
- Suggested 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
- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/openai/codex/issues/23452
- Evidence: failure_mode_cluster:unknown | fmev_bb42283a16108fba99a9036928ce1d26 | security_permissions: Codex Desktop: Computer Use blocks get_app_state(Codex) with "not allowed ... for safety reas...

## 13. security_permissions · 失败模式：security_permissions: Codex feels more like an AI babysitting workflow than an AI agent

- Severity: high
- Evidence strength: source_linked
- Finding: Developers should check this security_permissions risk before relying on the project: Codex feels more like an AI babysitting workflow than an AI agent
- User impact: Developers may expose sensitive permissions or credentials: Codex feels more like an AI babysitting workflow than an AI agent
- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Codex feels more like an AI babysitting workflow than an AI agent. Context: Observed when using windows
- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/openai/codex/issues/23830
- Evidence: failure_mode_cluster:github_issue | fmev_cc8d0a68c3e52801fbd952087749fa66 | https://github.com/openai/codex/issues/23830 | Codex feels more like an AI babysitting workflow than an AI agent

## 14. security_permissions · 失败模式：security_permissions: Codex mobile shows running desktop as offline and Reconnect silently does nothing

- Severity: high
- Evidence strength: source_linked
- Finding: Developers should check this security_permissions risk before relying on the project: Codex mobile shows running desktop as offline and Reconnect silently does nothing
- User impact: 该失败模式可能影响开发者安装、配置、运行或升级，需要在能力资产里前置说明。
- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Codex mobile shows running desktop as offline and Reconnect silently does nothing. Context: Observed when using macos
- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/openai/codex/issues/22898
- Evidence: failure_mode_cluster:unknown | fmev_1e73160c6492bc890c0b775fc557b401 | security_permissions: Codex mobile shows running desktop as offline and Reconnect silently does nothing, failure_mode_cluster:unknown | fmev_82cee73e1c9850dbc427d9e17a8def57 | security_permissions: Codex mobile shows running desktop as offline and Reconnect silently does nothing

## 15. security_permissions · 失败模式：security_permissions: Critical: false-positive cyber-risk warnings still block normal Gov/GSM dev work; thread ID a...

- Severity: high
- Evidence strength: source_linked
- Finding: Developers should check this security_permissions risk before relying on the project: Critical: false-positive cyber-risk warnings still block normal Gov/GSM dev work; thread ID and 2026-05-19 screenshots provided
- User impact: Developers may expose sensitive permissions or credentials: Critical: false-positive cyber-risk warnings still block normal Gov/GSM dev work; thread ID and 2026-05-19 screenshots provided
- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Critical: false-positive cyber-risk warnings still block normal Gov/GSM dev work; thread ID and 2026-05-19 screenshots provided. Context: Observed when using linux
- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/openai/codex/issues/23381
- Evidence: failure_mode_cluster:github_issue | fmev_6264b3ed20b9a052f111c28293f42228 | https://github.com/openai/codex/issues/23381 | Critical: false-positive cyber-risk warnings still block normal Gov/GSM dev work; thread ID and 2026-05-19 screenshots provided

## 16. security_permissions · 失败模式：security_permissions: Expose effective approval reviewer to PermissionRequest hooks or support explicit defer

- Severity: high
- Evidence strength: source_linked
- Finding: Developers should check this security_permissions risk before relying on the project: Expose effective approval reviewer to PermissionRequest hooks or support explicit defer
- User impact: 该失败模式可能影响开发者安装、配置、运行或升级，需要在能力资产里前置说明。
- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Expose effective approval reviewer to PermissionRequest hooks or support explicit defer. Context: Source discussion did not expose a precise runtime context.
- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/openai/codex/issues/23465
- Evidence: failure_mode_cluster:unknown | fmev_c2f83b0d5e8d9dfd12d19f5c474d6833 | security_permissions: Expose effective approval reviewer to PermissionRequest hooks or support explicit defer

## 17. security_permissions · 失败模式：security_permissions: Linux sandbox still fails with `bwrap: Failed to make / slave: Permission denied` on codex-cl...

- Severity: high
- Evidence strength: source_linked
- Finding: Developers should check this security_permissions risk before relying on the project: Linux sandbox still fails with `bwrap: Failed to make / slave: Permission denied` on codex-cli 0.130.0 while legacy Landlock works
- User impact: 该失败模式可能影响开发者安装、配置、运行或升级，需要在能力资产里前置说明。
- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Linux sandbox still fails with `bwrap: Failed to make / slave: Permission denied` on codex-cli 0.130.0 while legacy Landlock works. Context: Observed when using docker, linux
- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/openai/codex/issues/23468
- Evidence: failure_mode_cluster:unknown | fmev_29abd1dd497f5b12f776aa82788bffa7 | security_permissions: Linux sandbox still fails with `bwrap: Failed to make / slave: Permission denied` on codex-cl...

## 18. security_permissions · 失败模式：security_permissions: Project-level skills cannot be edited in workspace-write without danger-full-access

- Severity: high
- Evidence strength: source_linked
- Finding: Developers should check this security_permissions risk before relying on the project: Project-level skills cannot be edited in workspace-write without danger-full-access
- User impact: 该失败模式可能影响开发者安装、配置、运行或升级，需要在能力资产里前置说明。
- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Project-level skills cannot be edited in workspace-write without danger-full-access. Context: Observed when using macos
- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/openai/codex/issues/23286
- Evidence: failure_mode_cluster:unknown | fmev_9a754ead8efbbc82fa7ad30d30fffbb0 | security_permissions: Project-level skills cannot be edited in workspace-write without danger-full-access

## 19. security_permissions · 失败模式：security_permissions: Sandbox bugged, the agent is reading my whole disk

- Severity: high
- Evidence strength: source_linked
- Finding: Developers should check this security_permissions risk before relying on the project: Sandbox bugged, the agent is reading my whole disk
- User impact: 该失败模式可能影响开发者安装、配置、运行或升级，需要在能力资产里前置说明。
- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Sandbox bugged, the agent is reading my whole disk. Context: Observed when using windows
- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/openai/codex/issues/23459
- Evidence: failure_mode_cluster:unknown | fmev_b30075022555c21d1ff46053475edc05 | security_permissions: Sandbox bugged, the agent is reading my whole disk

## 20. security_permissions · 失败模式：security_permissions: Support configuring outbound HTTP proxy via http_proxy in config.toml

- Severity: high
- Evidence strength: source_linked
- Finding: Developers should check this security_permissions risk before relying on the project: Support configuring outbound HTTP proxy via http_proxy in config.toml
- User impact: Developers may expose sensitive permissions or credentials: Support configuring outbound HTTP proxy via http_proxy in config.toml
- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Support configuring outbound HTTP proxy via http_proxy in config.toml. Context: Observed when using python
- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/openai/codex/issues/6060
- Evidence: failure_mode_cluster:github_issue | fmev_33fd60927d450067422762a93e8ceaf9 | https://github.com/openai/codex/issues/6060 | Support configuring outbound HTTP proxy via http_proxy in config.toml

## 21. security_permissions · 失败模式：security_permissions: [Windows] Browser plugin fails with "browser-client is not trusted" despite advertised chrome...

- Severity: high
- Evidence strength: source_linked
- Finding: Developers should check this security_permissions risk before relying on the project: [Windows] Browser plugin fails with "browser-client is not trusted" despite advertised chrome and iab backends
- User impact: Developers may expose sensitive permissions or credentials: [Windows] Browser plugin fails with "browser-client is not trusted" despite advertised chrome and iab backends
- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: [Windows] Browser plugin fails with "browser-client is not trusted" despite advertised chrome and iab backends. Context: Observed when using node, python, playwright, windows
- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/openai/codex/issues/21781
- Evidence: failure_mode_cluster:github_issue | fmev_f03254f0a50be7b9756f823a1ae9d17f | https://github.com/openai/codex/issues/21781 | [Windows] Browser plugin fails with "browser-client is not trusted" despite advertised chrome and iab backends

## 22. security_permissions · 失败模式：security_permissions: arg0 error messages lack path and operation context, making failures hard to diagnose

- Severity: high
- Evidence strength: source_linked
- Finding: Developers should check this security_permissions risk before relying on the project: arg0 error messages lack path and operation context, making failures hard to diagnose
- User impact: 该失败模式可能影响开发者安装、配置、运行或升级，需要在能力资产里前置说明。
- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: arg0 error messages lack path and operation context, making failures hard to diagnose. Context: Observed when using linux
- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/openai/codex/issues/19674
- Evidence: failure_mode_cluster:unknown | fmev_4e0fb1fde9983c4a32c0d6ed88dd3c41 | security_permissions: arg0 error messages lack path and operation context, making failures hard to diagnose

## 23. security_permissions · 失败模式：security_permissions: macOS desktop shows "Computer Use plugin unavailable" even though bundled computer-use plugin...

- Severity: high
- Evidence strength: source_linked
- Finding: Developers should check this security_permissions risk before relying on the project: macOS desktop shows "Computer Use plugin unavailable" even though bundled computer-use plugin exists
- User impact: 该失败模式可能影响开发者安装、配置、运行或升级，需要在能力资产里前置说明。
- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: macOS desktop shows "Computer Use plugin unavailable" even though bundled computer-use plugin exists. Context: Observed when using macos
- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/openai/codex/issues/18803
- Evidence: failure_mode_cluster:unknown | fmev_1d10568fe9c8e7dbf753f01e4d1dc827 | security_permissions: macOS desktop shows "Computer Use plugin unavailable" even though bundled computer-use plugin...

## 24. security_permissions · 失败模式：security_permissions: state runtime: corrupt `state_5.sqlite` (SQLite "file is not a database") wedges startup with...

- Severity: high
- Evidence strength: source_linked
- Finding: Developers should check this security_permissions risk before relying on the project: state runtime: corrupt `state_5.sqlite` (SQLite "file is not a database") wedges startup with no auto-recovery
- User impact: Developers may expose sensitive permissions or credentials: state runtime: corrupt `state_5.sqlite` (SQLite "file is not a database") wedges startup with no auto-recovery
- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: state runtime: corrupt `state_5.sqlite` (SQLite "file is not a database") wedges startup with no auto-recovery. Context: Observed when using macos, linux
- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/openai/codex/issues/21750
- Evidence: failure_mode_cluster:github_issue | fmev_f5941e304f9d08fb26869189afb969b4 | https://github.com/openai/codex/issues/21750 | state runtime: corrupt `state_5.sqlite` (SQLite "file is not a database") wedges startup with no auto-recovery

## 25. security_permissions · 来源证据：Appshot fails after ScreenCapture permission: SkyComputerUseService crashes with EXC_BAD_ACCESS on macOS 15.0

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Appshot fails after ScreenCapture permission: SkyComputerUseService crashes with EXC_BAD_ACCESS on macOS 15.0
- User impact: 可能阻塞安装或首次运行。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_554624015506417d8db2fca57930ffb5 | https://github.com/openai/codex/issues/23992 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。

## 26. security_permissions · 来源证据：Codex Desktop no longer shows visible context/token usage indicator

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Codex Desktop no longer shows visible context/token usage indicator
- User impact: 可能阻塞安装或首次运行。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_bd5ec095b9454d7482a6dc6292725701 | https://github.com/openai/codex/issues/23794 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。

## 27. security_permissions · 来源证据：Codex Desktop remote control remains connected but unusable after remote device revoked permission, and cannot be delet…

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Codex Desktop remote control remains connected but unusable after remote device revoked permission, and cannot be deleted or re-authorized
- User impact: 可能影响授权、密钥配置或安全边界。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_cae14ff3be604b0fbf1885e5f899db4c | https://github.com/openai/codex/issues/23865 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。

## 28. security_permissions · 来源证据：Codex Windows App fails to start: app-server websocket closed, code=3221225501

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Codex Windows App fails to start: app-server websocket closed, code=3221225501
- User impact: 可能阻塞安装或首次运行。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_4667dbe110b443c98949e015b34abe43 | https://github.com/openai/codex/issues/23672 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。

## 29. security_permissions · 来源证据：Desktop app `functions.exec_command` honors custom file permissions but not `allow_local_binding`

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Desktop app `functions.exec_command` honors custom file permissions but not `allow_local_binding`
- User impact: 可能影响授权、密钥配置或安全边界。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_a20c5ec2717a40369e7eed4cb7076afd | https://github.com/openai/codex/issues/23973 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 30. security_permissions · 来源证据：Project hooks in linked worktrees appear to be loaded from the primary checkout but executed from the linked worktree c…

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Project hooks in linked worktrees appear to be loaded from the primary checkout but executed from the linked worktree cwd
- User impact: 可能影响授权、密钥配置或安全边界。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_e3c8d74f07f04c91b5dcbef6e26dd53f | https://github.com/openai/codex/issues/23996 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 31. security_permissions · 来源证据：Remote compaction intermittently fails with stream disconnected before completion

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Remote compaction intermittently fails with stream disconnected before completion
- User impact: 可能影响授权、密钥配置或安全边界。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_462ca17adaa4465e9ae55e8e102d9a7d | https://github.com/openai/codex/issues/17392 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 32. capability · 能力判断依赖假设

- Severity: medium
- Evidence strength: source_linked
- Finding: README/documentation is current enough for a first validation pass.
- User impact: 假设不成立时，用户拿不到承诺的能力。
- Suggested check: 将假设转成下游验证清单。
- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。
- Evidence: capability.assumptions | github_repo:965415649 | https://github.com/openai/codex | README/documentation is current enough for a first validation pass.

## 33. maintenance · 维护活跃度未知

- Severity: medium
- Evidence strength: source_linked
- Finding: 未记录 last_activity_observed。
- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。
- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。
- Evidence: evidence.maintainer_signals | github_repo:965415649 | https://github.com/openai/codex | last_activity_observed missing

## 34. security_permissions · 下游验证发现风险项

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 下游已经要求复核，不能在页面中弱化。
- Suggested check: 进入安全/权限治理复核队列。
- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。
- Evidence: downstream_validation.risk_items | github_repo:965415649 | https://github.com/openai/codex | no_demo; severity=medium

## 35. security_permissions · 存在评分风险

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 风险会影响是否适合普通用户安装。
- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。
- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。
- Evidence: risks.scoring_risks | github_repo:965415649 | https://github.com/openai/codex | no_demo; severity=medium

## 36. security_permissions · 来源证据：Error running remote compact task: stream disconnected before completion: error sending request for url (https://chatgp…

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Error running remote compact task: stream disconnected before completion: error sending request for url (https://chatgpt.com/backend-api/codex/responses/compac…
- User impact: 可能影响授权、密钥配置或安全边界。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_aed03a66e5c44dcbb33040a0f8d4b14f | https://github.com/openai/codex/issues/13906 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。

## 37. maintenance · issue/PR 响应质量未知

- Severity: low
- Evidence strength: source_linked
- Finding: issue_or_pr_quality=unknown。
- User impact: 用户无法判断遇到问题后是否有人维护。
- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。
- Guardrail action: issue/PR 响应未知时，必须提示维护风险。
- Evidence: evidence.maintainer_signals | github_repo:965415649 | https://github.com/openai/codex | issue_or_pr_quality=unknown

## 38. maintenance · 发布节奏不明确

- Severity: low
- Evidence strength: source_linked
- Finding: release_recency=unknown。
- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。
- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。
- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。
- Evidence: evidence.maintainer_signals | github_repo:965415649 | https://github.com/openai/codex | release_recency=unknown

<!-- canonical_name: openai/codex; human_manual_source: deepwiki_human_wiki -->
