# Custom Instructions Source: https://openai-codex.mintlify.app/advanced/custom-instructions Provide project-specific guidance and preferences to Codex ## Overview Custom instructions let you provide Codex with context, preferences, and guidelines that persist across sessions. This is especially useful for: * Defining coding standards and style preferences * Documenting project-specific conventions * Providing context about architecture decisions * Setting workflow preferences Think of custom instructions as a persistent system prompt that Codex reads at the start of every session. ## AGENTS.md Files Custom instructions are defined in `AGENTS.md` files. Codex looks for these files in three locations and merges them in order: `~/.codex/AGENTS.md` - Personal preferences that apply to all projects Example use cases: * Your preferred coding style * Tools you always want to use * Communication preferences `AGENTS.md` at repo root - Team-wide project guidance Example use cases: * Project architecture overview * Team coding standards * Important constraints or requirements Commit this file to version control so all team members share the same context. `AGENTS.md` in current working directory - Subsystem-specific notes Example use cases: * Feature-specific guidelines * Module architecture notes * Local development setup ## File Format AGENTS.md files use standard Markdown format. Codex treats all content as guidance: ```markdown AGENTS.md theme={null} # Project Guidelines ## Code Style - Use TypeScript for all new files - Prefer functional components with hooks - Always include JSDoc comments for exported functions ## Architecture This project uses a feature-based folder structure: ``` src/ features/ auth/ dashboard/ settings/ ``` ## Testing - Write tests for all business logic - Use Vitest for unit tests - Place test files adjacent to source: `component.tsx` → `component.test.tsx` ## Important Do NOT modify files in the `generated/` directory - they are auto-generated. ``` ## Example Configurations ### Personal Preferences ```markdown ~/.codex/AGENTS.md theme={null} # My Coding Preferences - I prefer verbose variable names over abbreviations - Always use `const` over `let` when possible - Add comments explaining the "why", not the "what" - Run prettier after making changes - Use conventional commits format: `type(scope): description` # Tools - Prefer `pnpm` over npm or yarn - Use `just` for task running instead of npm scripts ``` ### Team Standards ```markdown AGENTS.md (repo root) theme={null} # Acme Corp - Frontend Guidelines ## Tech Stack - React 18 + TypeScript - Vite for builds - TanStack Query for data fetching - Radix UI for components - Tailwind CSS for styling ## Code Standards - Follow the Airbnb TypeScript style guide - Maximum line length: 100 characters - Use named exports (no default exports) ## State Management - Use React hooks for local state - Use TanStack Query for server state - Use Zustand for global client state (sparingly) ## API Integration - All API calls go through `src/api/` modules - Use OpenAPI types from `src/api/generated/` - Handle errors with the `useErrorHandler` hook ## Security - Never commit API keys or secrets - All user input must be sanitized - Use environment variables for configuration ## Before Committing 1. Run `pnpm typecheck` 2. Run `pnpm test` 3. Run `pnpm lint:fix` ``` ### Feature-Specific ````markdown src/features/auth/AGENTS.md theme={null} # Authentication Module ## Overview This module handles user authentication using OAuth 2.0 + PKCE. ## Architecture - `AuthProvider.tsx` - Context provider for auth state - `useAuth.ts` - Hook for accessing auth context - `oauth.ts` - OAuth flow implementation - `tokens.ts` - Token storage and refresh logic ## Important Notes - Tokens are stored in httpOnly cookies (not localStorage) - Token refresh happens automatically 5 minutes before expiry - All auth routes require HTTPS in production ## Testing Auth Use the mock auth provider in tests: ```tsx import { MockAuthProvider } from './test-utils'; ```` ## Related * API integration: `src/api/auth.ts` * Backend docs: `docs/auth-api.md` ```` ## Common Use Cases Example AGENTS.md showing code style preferences: - Use single quotes for strings - Include trailing commas in multiline arrays/objects - Prefer arrow functions over function declarations - Use template literals instead of string concatenation Keep your style preferences documented so Codex follows them consistently. Use AGENTS.md to document key architectural decisions for your project, such as: - Monorepo structure and workspace organization - Data flow patterns (e.g., unidirectional data flow) - Module boundaries and dependencies - Coding patterns that should be followed This helps Codex understand and maintain your architecture. Document technical constraints in AGENTS.md: - Browser support requirements - Bundle size limits - Performance targets (FCP, TTI, Lighthouse scores) - Dependency management policies - Security and compliance requirements Clear constraints help Codex make appropriate trade-offs. Document team workflows in AGENTS.md: - Git workflow (branching strategy, commit conventions) - Code review requirements - Development commands and scripts - Testing practices - Deployment procedures Consistent workflows improve code quality and team productivity. Set communication preferences in AGENTS.md: - Explanation depth (concise vs thorough) - When to ask clarifying questions - How to handle ambiguous requirements - Code example preferences - Technical writing style This helps Codex communicate in the style you prefer. ## Best Practices Provide concrete examples and explicit rules rather than vague guidelines Review and update instructions as your project evolves Include information Codex can't infer from code alone Organize with headers and lists for easy scanning ### What to Include **DO** include: - Coding standards and conventions - Architecture principles - Project-specific constraints - Workflow preferences - Important context about design decisions - Links to relevant documentation **AVOID** including: - Information that's obvious from the code - Detailed API documentation (use inline comments instead) - Temporary notes (use regular comments or TODOs) - Secrets or sensitive information ## Disabling Project Docs You can disable loading of AGENTS.md files: ### Command-Line Flag ```bash codex --no-project-doc ```` ### Environment Variable ```bash theme={null} export CODEX_DISABLE_PROJECT_DOC=1 codex ``` This only disables project-specific AGENTS.md files. Your personal `~/.codex/AGENTS.md` is still loaded. ## Advanced Examples ### Multi-Language Project ```markdown theme={null} # Polyglot Project Guidelines ## Backend (Rust) - Follow the Rust API guidelines - Use `cargo fmt` and `cargo clippy` - Write doc comments with examples - Place unit tests in the same file using `#[cfg(test)]` ## Frontend (TypeScript) - Use strict TypeScript mode - No `any` types without explicit justification - Prefer type inference over explicit types when obvious ## Database (PostgreSQL) - All schema changes go through migrations - Use snake_case for column names - Always add indexes for foreign keys - Include `created_at` and `updated_at` timestamps ## API Contracts - Use OpenAPI 3.0 specification - Version APIs with `/v1/`, `/v2/` prefixes - Never remove fields from existing endpoints (deprecate instead) ``` ### Microservices Architecture ```markdown theme={null} # Microservices Guidelines ## Service Boundaries - auth-service: Authentication and authorization - user-service: User profiles and preferences - payment-service: Payment processing and billing - notification-service: Email, SMS, push notifications ## Inter-Service Communication - Use gRPC for synchronous calls - Use message queue (RabbitMQ) for async events - Never make database calls across services - Each service owns its data exclusively ## Observability - Instrument all endpoints with OpenTelemetry - Log structured JSON with trace IDs - Set up alerts for error rate > 1% - Dashboard: https://grafana.internal/services ## Deployment - Services run in Kubernetes - Use Helm charts in `k8s/charts/` - Staging: `kubectl config use-context staging` - Production: Requires approval + deploy script ``` ## Troubleshooting 1. Verify file location: `ls -la AGENTS.md` 2. Check file is valid Markdown 3. Ensure `CODEX_DISABLE_PROJECT_DOC` is not set 4. Try `codex --no-project-doc` to confirm it's the AGENTS.md causing issues * Simplify global `~/.codex/AGENTS.md` to only personal preferences * Keep repo-level `AGENTS.md` focused on critical standards * Use directory-level files sparingly for truly module-specific notes * Be more explicit and specific in your wording * Provide examples that illustrate the rule * Move critical rules to the top of the file * Consider if the instruction conflicts with model knowledge ## Real-World Examples ```text theme={null} # Contributing to XYZ ## Development Setup 1. Fork and clone the repository 2. Install dependencies: npm install 3. Run tests: npm test 4. Start dev server: npm run dev ## Commit Guidelines Follow conventional commits: - feat: New features - fix: Bug fixes - docs: Documentation changes - refactor: Code restructuring - test: Test changes ## Pull Request Process 1. Update README.md with any new functionality 2. Add tests for new features 3. Ensure CI passes 4. Request review from maintainers ## Code of Conduct Be respectful and inclusive. See CODE_OF_CONDUCT.md. ``` ```text theme={null} # Enterprise CRM - Development Guide ## Security Requirements - All data must be encrypted at rest - Use parameterized queries (never string concatenation) - Validate all user input server-side - Audit logs for all data modifications ## Compliance - GDPR: Users can export/delete their data - SOC 2: All changes must be tracked - HIPAA: PHI must be specially marked ## Performance SLAs - API response time less than 200ms (p95) - Page load time less than 2s - 99.9% uptime requirement ## Deployment - Staging deploys: Automatic on merge to develop - Production deploys: Manual approval required - Rollback plan must be documented ``` ```text theme={null} # Startup MVP Guidelines ## Move Fast - Prioritize shipping over perfection - Technical debt is okay if documented - Use managed services (less infra to maintain) ## Core Principles - Simple is better than Complex - Boring technology unless necessary - Monolith first, split later if needed ## Stack - Next.js (full-stack) - Postgres (via Supabase) - Vercel (hosting) - Stripe (payments) ## Iteration Speed - Deploy to staging: On every commit - Deploy to production: Multiple times per day - Feature flags: For incomplete features ``` ## See Also Global Codex configuration options Control command execution How Codex remembers context Tips for using Codex effectively # Exec Mode (Non-Interactive) Source: https://openai-codex.mintlify.app/advanced/exec-mode Run Codex programmatically in CI/CD pipelines and automation scripts ## Overview Exec mode allows you to run Codex non-interactively for automation, CI/CD pipelines, and scripted workflows. Instead of launching the interactive TUI, Codex executes your prompt, completes the task, and exits automatically. Exec mode is ideal for automated workflows where you need Codex to complete a task without human intervention. ## Basic Usage The `codex exec` command runs Codex in non-interactive mode: ```bash theme={null} codex exec "your prompt here" ``` You can also pass the prompt via stdin: ```bash theme={null} echo "update the changelog" | codex exec ``` Or from a file: ```bash theme={null} codex exec < task.txt ``` ## Command-Line Options Run without persisting session rollout files to disk. Useful for temporary automation tasks. Print events to stdout as JSONL for programmatic parsing. Write the last message from the agent to the specified file. ```bash theme={null} codex exec -o response.md "explain the architecture" ``` Path to a JSON Schema file describing the model's final response shape. Control color output: `always`, `never`, or `auto`. Force cursor-based progress updates in exec mode. ## CI/CD Integration ### GitHub Actions Example ```yaml GitHub Actions theme={null} name: Update Changelog on: push: branches: [main] jobs: changelog: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Codex run: npm install -g @openai/codex - name: Update changelog via Codex env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} run: | codex exec --sandbox workspace-write \ "update CHANGELOG.md for the latest release" - name: Commit changes run: | git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" git add CHANGELOG.md git commit -m "docs: update changelog [skip ci]" git push ``` ```yaml GitLab CI theme={null} update-docs: image: node:20 script: - npm install -g @openai/codex - codex exec --sandbox workspace-write "generate API documentation" only: - main ``` ```yaml CircleCI theme={null} version: 2.1 jobs: codex-task: docker: - image: cimg/node:20.0 steps: - checkout - run: name: Install Codex command: npm install -g @openai/codex - run: name: Run Codex task command: codex exec --ephemeral "analyze test coverage" ``` ### Environment Variables Always store API keys and sensitive credentials as secrets in your CI/CD platform. ```bash theme={null} # Required: OpenAI API key export OPENAI_API_KEY="sk-..." # Optional: Suppress interactive UI prompts export CODEX_QUIET_MODE=1 # Optional: Enable verbose logging (see Tracing guide) export RUST_LOG=info ``` ## Approval Modes for Automation Use `--full-auto` for complete automation with sandboxing: ```bash theme={null} codex exec --full-auto "fix all linting errors" ``` This is equivalent to: ```bash theme={null} codex exec --sandbox workspace-write "fix all linting errors" ``` Only for externally sandboxed environments: ```bash theme={null} codex exec --dangerously-bypass-approvals-and-sandbox "run tests" ``` This disables all safety checks. Only use inside Docker or other isolated environments. ## Output Formats ### Human-Readable Output By default, exec mode prints human-readable progress to stderr: ```bash theme={null} codex exec "summarize the project" ``` Output: ``` ⚙ Reading project files... ✓ Analysis complete 📝 Writing summary... [Summary content appears here] ``` ### JSON Lines (JSONL) Output For programmatic parsing, use `--json`: ```bash theme={null} codex exec --json "list all API endpoints" > results.jsonl ``` Each line is a JSON event: ```json theme={null} {"type":"AgentMessage","content":"Analyzing API routes..."} {"type":"FileChange","path":"api_summary.md","status":"created"} {"type":"TurnComplete","success":true} ``` ### Structured Output with Schema Provide a JSON Schema to enforce structured output: ```bash theme={null} codex exec \ --output-schema schema.json \ --output-last-message result.json \ "extract all dependencies" ``` ```json schema.json theme={null} { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "dependencies": { "type": "array", "items": { "type": "object", "properties": { "name": {"type": "string"}, "version": {"type": "string"}, "type": {"enum": ["runtime", "dev", "peer"]} }, "required": ["name", "version", "type"] } } }, "required": ["dependencies"] } ``` ## Working with Images Attach images to your exec prompt: ```bash theme={null} # Single image codex exec --image screenshot.png "implement this design" # Multiple images codex exec --image design1.png,design2.png "compare these mockups" ``` ## Session Management ### Ephemeral Sessions Use `--ephemeral` to avoid writing session data to disk: ```bash theme={null} codex exec --ephemeral "quick analysis task" ``` Benefits: * Faster startup (no session loading) * No disk I/O overhead * Clean environment for one-off tasks ### Resume Previous Sessions You can resume a previous exec session: ```bash theme={null} # Resume the most recent session codex exec resume --last # Resume by session ID codex exec resume # Resume with additional prompt codex exec resume --last "continue with unit tests" ``` ## Error Handling Exec mode exits with status codes for automation: Task completed successfully Task failed or error occurred Example with error handling: ```bash theme={null} #!/bin/bash set -e if codex exec --ephemeral "run tests and report failures"; then echo "Tests passed!" notify-send "Codex: Tests passed" else echo "Tests failed. Check logs." exit 1 fi ``` ## Best Practices For CI/CD tasks that don't need session persistence Use `--output-last-message` to save results Parse events programmatically with `--json` Use `--full-auto` for safe automation ## Examples ```bash theme={null} codex exec \ --sandbox workspace-write \ --output-last-message docs/api.md \ "generate comprehensive API documentation from source code" ``` ```bash theme={null} # Review uncommitted changes codex exec review --uncommitted # Review against base branch codex exec review --base main # Review specific commit codex exec review --commit abc123 --title "feat: add new feature" ``` ```bash theme={null} #!/bin/bash for file in src/*.js; do codex exec --ephemeral "add JSDoc comments to $file" done ``` ```bash theme={null} # Cron job: daily dependency updates 0 2 * * * cd /path/to/project && \ codex exec --full-auto "update dependencies and run tests" \ >> /var/log/codex-maintenance.log 2>&1 ``` ## Troubleshooting Ensure you're using an appropriate approval mode: * Use `--full-auto` for automated execution * Check that your prompt is clear and has defined completion criteria * Enable verbose logging to see what's happening: `RUST_LOG=debug codex exec ...` * Set explicit timeouts in your CI configuration * Use `--ephemeral` to reduce startup overhead * Consider breaking large tasks into smaller steps * Verify `OPENAI_API_KEY` is set correctly * Check that the API key has sufficient permissions * Ensure your organization allows API access ## See Also Control which commands can be executed Debug with verbose logging Add project-specific guidance Configure sandboxing behavior # Execution Policies Source: https://openai-codex.mintlify.app/advanced/exec-policies Control which commands Codex can execute with fine-grained rules ## Overview Execution policies let you define rules that control which shell commands Codex can execute. This provides an additional security layer on top of sandboxing, allowing you to: * **Allowlist** safe commands that can run without approval * **Blocklist** dangerous commands that should never execute * **Require prompts** for commands that need human review Execution policies are evaluated before sandboxing and work alongside approval modes to provide defense-in-depth security. ## Policy Language Policies are written in **Starlark** (a Python-like syntax) using the `prefix_rule()` function: ```starlark theme={null} prefix_rule( pattern = ["command", ["arg1", "arg2"]], # Ordered tokens; lists = alternatives decision = "allow", # allow | prompt | forbidden justification = "Why this rule exists", # Human-readable explanation match = [["command", "arg1"]], # Examples that MUST match not_match = [["command", "other"]] # Examples that must NOT match ) ``` ### Pattern Matching Ordered list of tokens to match. Each element can be: * A string: exact token match (e.g., `"git"`) * A list of strings: match any alternative (e.g., `["commit", "push"]`) ```starlark theme={null} # Matches: git status, git diff, git log pattern = ["git", ["status", "diff", "log"]] ``` What action to take when the pattern matches: * `allow`: Execute without prompting * `prompt`: Ask user for approval * `forbidden`: Block execution entirely Explanation shown to users. For `forbidden` rules, include a recommended alternative: ```starlark theme={null} justification = "Use `jj` instead of `git` for version control." ``` Example commands that should match this rule (unit tests). Example commands that should NOT match this rule (unit tests). ## Policy Examples ### Safe Read-Only Commands ```starlark theme={null} # Allow common read-only operations prefix_rule( pattern = ["git", ["status", "diff", "log", "show"]], decision = "allow", justification = "Read-only git commands are safe", match = [ ["git", "status"], ["git", "log", "--oneline"], ], ) prefix_rule( pattern = ["ls"], decision = "allow", justification = "Listing files is safe", ) prefix_rule( pattern = ["cat"], decision = "allow", justification = "Reading file contents is safe", ) ``` ### Commands Requiring Approval ```starlark theme={null} # Prompt before destructive operations prefix_rule( pattern = ["rm"], decision = "prompt", justification = "File deletion requires approval", match = [ ["rm", "file.txt"], ["rm", "-rf", "directory"], ], ) prefix_rule( pattern = ["git", ["push", "commit"]], decision = "prompt", justification = "Version control changes should be reviewed", ) prefix_rule( pattern = ["npm", "publish"], decision = "prompt", justification = "Publishing packages requires manual review", ) ``` ### Forbidden Commands ```starlark theme={null} # Block dangerous operations prefix_rule( pattern = ["sudo"], decision = "forbidden", justification = "Privilege escalation is not allowed. Run Codex without sudo.", not_match = [ ["sudoku"], # Don't match similar words! ], ) prefix_rule( pattern = ["curl"], decision = "forbidden", justification = "Network access is blocked. Use the sandbox's network restrictions instead.", ) prefix_rule( pattern = ["dd"], decision = "forbidden", justification = "Direct disk operations are forbidden for safety.", ) ``` ## Host Executable Resolution You can restrict which absolute paths are allowed for specific commands: ```starlark theme={null} host_executable( name = "git", paths = [ "/opt/homebrew/bin/git", "/usr/bin/git", ], ) host_executable( name = "python", paths = [ "/usr/bin/python3", "/usr/local/bin/python3", ], ) ``` ### Matching Semantics Codex always tries exact first-token matches first. Example: `/usr/bin/git status` only matches if a rule starts with `/usr/bin/git` If no exact match exists and `--resolve-host-executables` is enabled: * `/usr/bin/git` falls back to basename rules for `git` * Only allowed if the path is in the `host_executable()` list * If no `host_executable()` exists, basename fallback is allowed for any path ## Using Policies ### Command-Line Interface Check if a command is allowed: ```bash theme={null} codex execpolicy check --rules policy.rules git status ``` With hostname resolution: ```bash theme={null} codex execpolicy check \ --rules policy.rules \ --resolve-host-executables \ /usr/bin/git status ``` Merge multiple policy files: ```bash theme={null} codex execpolicy check \ --rules base-policy.rules \ --rules team-policy.rules \ --rules project-policy.rules \ git push ``` ### Response Format The output is JSON: ```json Match Found theme={null} { "matchedRules": [ { "prefixRuleMatch": { "matchedPrefix": ["git", "status"], "decision": "allow", "resolvedProgram": "/usr/bin/git", "justification": "Read-only git commands are safe" } } ], "decision": "allow" } ``` ```json No Match theme={null} { "matchedRules": [] } ``` ```json Forbidden theme={null} { "matchedRules": [ { "prefixRuleMatch": { "matchedPrefix": ["sudo"], "decision": "forbidden", "justification": "Privilege escalation is not allowed." } } ], "decision": "forbidden" } ``` ### Decision Priority When multiple rules match, the **strictest** decision wins: ``` forbidden > prompt > allow ``` If any matching rule is `forbidden`, the command is blocked regardless of other rules. ## Configuration Policy files can be stored in: 1. **Global policies**: `~/.codex/execpolicy.rules` 2. **Project policies**: `.codex/execpolicy.rules` in your repo 3. **Custom location**: Specify with `--rules` flag Commit project-specific policies to version control so all team members share the same rules. ## Advanced Examples ### Development Workflow ```starlark theme={null} # Allow common dev commands prefix_rule( pattern = [["npm", "yarn", "pnpm"], ["install", "test", "build"]], decision = "allow", justification = "Standard package manager operations", ) prefix_rule( pattern = ["cargo", ["build", "test", "check"]], decision = "allow", justification = "Rust development commands", ) # Prompt before publishing prefix_rule( pattern = [["npm", "cargo"], "publish"], decision = "prompt", justification = "Publishing requires review", ) ``` ### CI/CD Integration ```starlark theme={null} # Allow CI-specific commands prefix_rule( pattern = ["docker", ["build", "run", "ps"]], decision = "allow", justification = "Docker operations for CI", ) prefix_rule( pattern = ["kubectl", "get"], decision = "allow", justification = "Read-only cluster inspection", ) # Block cluster modifications prefix_rule( pattern = ["kubectl", ["apply", "delete", "patch"]], decision = "forbidden", justification = "Cluster modifications must go through GitOps.", ) ``` ### Database Access ```starlark theme={null} # Allow read-only queries prefix_rule( pattern = ["psql", "-c", "SELECT"], decision = "allow", justification = "Read-only database queries", ) # Prompt for writes prefix_rule( pattern = ["psql", "-c", ["INSERT", "UPDATE", "DELETE"]], decision = "prompt", justification = "Database modifications require approval", ) # Block schema changes prefix_rule( pattern = ["psql", "-c", ["DROP", "ALTER", "CREATE"]], decision = "forbidden", justification = "Schema changes must go through migrations.", ) ``` ## Testing Policies ### Inline Tests Use `match` and `not_match` to validate rules: ```starlark theme={null} prefix_rule( pattern = ["git", "push"], decision = "prompt", match = [ "git push", ["git", "push", "origin", "main"], "git push --force", ], not_match = [ "git pull", "git commit", "github push", # Don't match similar names ], ) ``` ### Validation on Load Policies are validated when loaded. Invalid rules cause an error: ```bash theme={null} $ codex execpolicy check --rules bad-policy.rules ls Error: Rule validation failed: - Pattern is empty - Invalid decision: "maybe" (must be allow/prompt/forbidden) ``` ## Best Practices Begin with `allow` for most commands, add restrictions as needed Always include clear `justification` text Use `match` and `not_match` to prevent regressions Combine policies with sandboxing for defense-in-depth ## Common Patterns ```starlark theme={null} prefix_rule( pattern = ["git", ["status", "diff", "log"]], decision = "allow", ) prefix_rule( pattern = ["git"], # Catch-all for other git commands decision = "prompt", ) ``` ```starlark theme={null} # Allow only these specific commands prefix_rule(pattern = ["ls"], decision = "allow") prefix_rule(pattern = ["cat"], decision = "allow") prefix_rule(pattern = ["git", "status"], decision = "allow") # Everything else requires approval (handled by Codex default behavior) ``` ```starlark theme={null} # Block specific dangerous commands prefix_rule(pattern = ["rm", "-rf", "/"], decision = "forbidden") prefix_rule(pattern = ["sudo"], decision = "forbidden") prefix_rule(pattern = ["dd"], decision = "forbidden") # Everything else is allowed (or controlled by approval mode) ``` ## Troubleshooting * Check token boundaries: `"git push"` is TWO tokens (`["git", "push"]`) * Use the `check` command to test: `codex execpolicy check --rules policy.rules git push` * Add `match` examples to validate behavior * Use `--pretty` for readable output: `codex execpolicy check --rules policy.rules --pretty command` * Check if multiple rules match (strictest wins) * Verify `justification` text for the reason * Enable host executable resolution: `--resolve-host-executables` * Define `host_executable()` entries for the command * Check that the absolute path is in the allowed list ## See Also Configure OS-level sandboxing Control when Codex asks for permission Run Codex non-interactively Comprehensive security guidance # Tracing & Verbose Logging Source: https://openai-codex.mintlify.app/advanced/tracing Enable detailed logging to debug Codex behavior and troubleshoot issues ## Overview Codex provides comprehensive tracing and logging capabilities to help you understand what's happening under the hood. This is especially useful for: * Debugging unexpected behavior * Troubleshooting integration issues * Understanding performance characteristics * Filing detailed bug reports Verbose logging can generate large amounts of output and may include sensitive information. Use with caution in production environments. ## Quick Start Enable verbose logging with the `RUST_LOG` environment variable: ```bash theme={null} # Basic verbose logging RUST_LOG=debug codex # Trace-level logging (very verbose) RUST_LOG=trace codex # Info-level logging (default for Codex crates) RUST_LOG=info codex ``` ## RUST\_LOG Environment Variable The `RUST_LOG` variable controls logging verbosity using the standard Rust tracing infrastructure. ### Log Levels Only critical errors that prevent operation Warning messages about potential issues High-level informational messages (default for Codex crates) Detailed debugging information Extremely verbose tracing output ### Syntax Set the same level for all modules: ```bash theme={null} RUST_LOG=debug codex ``` Set different levels for specific modules: ```bash theme={null} # Debug Codex core, info for everything else RUST_LOG=info,codex_core=debug codex # Trace exec module, debug for core RUST_LOG=codex_exec=trace,codex_core=debug codex ``` Use patterns to target specific modules: ```bash theme={null} # Debug all codex-* crates RUST_LOG=codex=debug codex # Trace specific function RUST_LOG=codex_core::agent::process_event=trace codex ``` ## Common Logging Scenarios ### Debug API Requests ```bash theme={null} # See all API request/response details RUST_LOG=codex_core::api=debug codex ``` Output includes: * Request URLs and headers * Request body payloads * Response status codes * Response bodies * Timing information ### Debug File Operations ```bash theme={null} # Trace file reading, writing, and patching RUST_LOG=codex_core::files=debug codex ``` Shows: * Files being read * Patches being applied * File system operations * Permission checks ### Debug Command Execution ```bash theme={null} # See all shell commands and output RUST_LOG=codex_exec=debug codex exec "run tests" ``` Includes: * Commands being executed * Working directory * Environment variables * stdout/stderr output * Exit codes ### Debug Sandboxing ```bash theme={null} # Trace sandbox setup and policy enforcement RUST_LOG=codex_sandbox=debug,codex_process_hardening=debug codex ``` Reveals: * Sandbox initialization * Policy rules being applied * Permission checks * Blocked operations ## Exec Mode Logging In exec mode, logs are written to a file to avoid interfering with output: ### Log File Location By default, logs are written to: ``` ~/.codex/logs/codex-tui-.log ``` ### Enable File Logging Logs are automatically written to file when you set `RUST_LOG`: ```bash theme={null} RUST_LOG=debug codex exec "analyze code" # Check the log file: tail -f ~/.codex/logs/codex-tui-*.log ``` ### Log Rotation Log files are rotated automatically. Old logs are kept for debugging but can be safely deleted. ## OpenTelemetry Integration Codex supports OpenTelemetry for distributed tracing: ### Configuration ```toml ~/.codex/config.toml theme={null} [otel] enabled = true endpoint = "http://localhost:4317" # OTLP gRPC endpoint # Optional: Sample rate (0.0 to 1.0) sampling_ratio = 1.0 # Optional: Service name service_name = "codex-cli" ``` ### Environment Variables Alternatively, use standard OTEL env vars: ```bash theme={null} export OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4317" export OTEL_SERVICE_NAME="codex-cli" export OTEL_TRACES_SAMPLER="always_on" codex ``` ### Viewing Traces Use Jaeger or another OTEL-compatible backend: ```bash theme={null} docker run -d --name jaeger \ -p 4317:4317 \ -p 16686:16686 \ jaegertracing/all-in-one:latest ``` ```bash theme={null} export OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4317" codex ``` Open [http://localhost:16686](http://localhost:16686) in your browser ## Legacy TypeScript CLI For the legacy TypeScript implementation, use `DEBUG`: ```bash theme={null} # Full API request/response logging DEBUG=true codex ``` The TypeScript CLI is deprecated. Consider migrating to the Rust implementation for better performance and features. ## Practical Examples ```bash theme={null} # Enable timing information RUST_LOG=debug,codex_core::timing=trace codex ``` Look for: * API request latency * File I/O timing * Long-running operations ```bash theme={null} # Trace auth flow RUST_LOG=codex_core::auth=debug,codex_api::auth=debug codex ``` Shows: * Token acquisition * Token refresh attempts * Authentication errors * API key validation ```bash theme={null} # Trace MCP server communication RUST_LOG=codex_core::mcp=debug codex ``` Reveals: * MCP server initialization * Tool calls and responses * Connection errors * Message parsing ```bash theme={null} # Trace config resolution RUST_LOG=codex_core::config=debug codex ``` Displays: * Config file locations checked * Loaded configuration values * Override application * Validation errors ```bash theme={null} # Everything at debug level RUST_LOG=codex=debug codex 2>&1 | tee codex-debug.log ``` Captures all Codex modules at debug level and saves to file. ## Performance Considerations Higher log levels (trace/debug) can slow down execution by 10-50% Writing logs to disk adds latency, especially with trace level Verbose logging increases memory usage for buffering OTEL tracing adds \~5-10ms per span to network requests For production use, stick with `info` or `warn` level logging. Use `debug` or `trace` only for active troubleshooting. ## Filtering Output ### Grep for Specific Events ```bash theme={null} # Find all error messages RUST_LOG=debug codex 2>&1 | grep ERROR # Find API calls RUST_LOG=debug codex 2>&1 | grep "http request" # Find file operations RUST_LOG=debug codex 2>&1 | grep "file:" ``` ### Focus on Specific Modules ```bash theme={null} # Only log Codex crates, silence dependencies RUST_LOG=codex=debug codex # Log multiple specific modules RUST_LOG=codex_core=debug,codex_exec=info codex ``` ## Troubleshooting Logging * Verify `RUST_LOG` is set: `echo $RUST_LOG` * Check log file location: `ls -lh ~/.codex/logs/` * Try higher verbosity: `RUST_LOG=trace` * Ensure Codex has write permissions to log directory * Lower the log level: `RUST_LOG=info` instead of `debug` * Filter to specific modules: `RUST_LOG=codex_core=debug` * Use grep to filter: `RUST_LOG=debug codex 2>&1 | grep pattern` * Increase verbosity: `RUST_LOG=debug` or `RUST_LOG=trace` * Check you're targeting the right module * Some modules may not have debug logging implemented * Codex attempts to redact secrets automatically * Review logs before sharing publicly * Use `RUST_LOG=info` in production to minimize exposure * Set `otel.sampling_ratio = 0.1` to reduce trace data ## Filing Bug Reports When reporting issues, include relevant logs: ```bash theme={null} RUST_LOG=debug codex 2>&1 | tee codex-issue.log ``` Review the log file and remove: * API keys * Tokens * Personal information * Proprietary code Include the redacted log file when filing a GitHub issue: [https://github.com/openai/codex/issues/new](https://github.com/openai/codex/issues/new) ## Advanced Configuration ### Custom Log Format Codex uses `tracing-subscriber` for logging. You can customize the format: ```bash theme={null} # JSON format logs RUST_LOG=debug RUST_LOG_FORMAT=json codex # Compact format RUST_LOG=debug RUST_LOG_FORMAT=compact codex ``` ### Span Tracing View function call spans: ```bash theme={null} # Show span enter/exit events RUST_LOG=trace codex ``` Output includes: ``` → entering span: process_event ← exiting span: process_event (took 42ms) ``` ## See Also Non-interactive execution for automation Configure Codex behavior Common issues and solutions Help improve Codex # Apps Source: https://openai-codex.mintlify.app/api/apps Connector app discovery and invocation Apps (connectors) integrate external services with Codex. They expose tools and data sources that the agent can use during conversations. ## List Apps Fetch available apps with optional pagination and thread context. ### Method ``` app/list ``` ### Parameters Opaque pagination cursor from previous response Page size (server defaults if unset) Thread ID for feature gating (uses global config if omitted) Bypass app caches and fetch fresh data from sources ### Response Array of app metadata Cursor for next page (null if no more pages) ### Notifications Emitted when app sources finish loading **Payload:** `{ data: AppInfo[] }` ## App Object Unique app identifier (connector ID) Human-readable app name App description Light theme logo URL Dark theme logo URL Distribution channel identifier App branding metadata Additional app metadata App category labels URL to install or configure the app Whether the user has access to this app Whether the app is enabled in config ## Example ```json Request theme={null} { "method": "app/list", "id": 50, "params": { "cursor": null, "limit": 50, "threadId": "thr_123", "forceRefetch": false } } ``` ```json Response theme={null} { "id": 50, "result": { "data": [ { "id": "github", "name": "GitHub", "description": "Access GitHub repositories, issues, and pull requests.", "logoUrl": "https://example.com/github-logo.png", "logoUrlDark": "https://example.com/github-logo-dark.png", "distributionChannel": null, "branding": { "primaryColor": "#181717" }, "appMetadata": null, "labels": ["Development", "Version Control"], "installUrl": "https://chatgpt.com/apps/github/github", "isAccessible": true, "isEnabled": true }, { "id": "slack", "name": "Slack", "description": "Send messages and read channels in Slack.", "logoUrl": "https://example.com/slack-logo.png", "logoUrlDark": null, "distributionChannel": null, "branding": { "primaryColor": "#4A154B" }, "appMetadata": null, "labels": ["Communication", "Productivity"], "installUrl": "https://chatgpt.com/apps/slack/slack", "isAccessible": true, "isEnabled": false } ], "nextCursor": null } } ``` ```json Notification theme={null} { "method": "app/list/updated", "params": { "data": [ { "id": "github", "name": "GitHub", "description": "Access GitHub repositories, issues, and pull requests.", "logoUrl": "https://example.com/github-logo.png", "logoUrlDark": "https://example.com/github-logo-dark.png", "installUrl": "https://chatgpt.com/apps/github/github", "isAccessible": true, "isEnabled": true } ] } } ``` ## Invoking an App To invoke an app, include `$` in the text input and add a `mention` input item with the app path. The slug is derived from the app name: lowercase with non-alphanumeric characters replaced by `-`. **Examples:** * "GitHub" becomes `$github` * "Demo App" becomes `$demo-app` ```json turn/start with app theme={null} { "method": "turn/start", "id": 51, "params": { "threadId": "thr_123", "input": [ { "type": "text", "text": "$github List open issues in the main repository." }, { "type": "mention", "name": "GitHub", "path": "app://github" } ] } } ``` ```json Response theme={null} { "id": 51, "result": { "turn": { "id": "turn_600", "status": "inProgress", "items": [], "error": null } } } ``` Always include the `mention` input item so the server uses the exact `app://` path rather than guessing by name. ## App Sources Apps are loaded from two sources: Apps the user has authorized and can access **Source:** ChatGPT account integrations Public apps available in the app directory **Source:** ChatGPT app marketplace The `app/list` response merges both sources. Cache entries are only replaced when refetches succeed. ## App Availability Indicates whether the user has authorized this app **false**: User needs to install/authorize the app via `installUrl` **true**: App is ready to use Indicates whether the app is enabled in Codex config Apps can be disabled via `config.toml` even if accessible. ## App Configuration Apps can be configured in `config.toml`: ```toml theme={null} [apps.github] enabled = true destructive_enabled = true open_world_enabled = true [apps.github.tools] # Per-tool configuration [apps.github.tools.create_issue] enabled = true approval_mode = "auto" # "auto", "prompt", or "approve" ``` ### Configuration Options Enable or disable the entire app Allow destructive operations (delete, modify) Allow operations that affect external systems Default approval mode for all tools * `auto` - Execute without asking * `prompt` - Ask for approval * `approve` - Always approve Enable all tools by default ## Next Steps Review the API architecture Initialize your connection # Initialization Source: https://openai-codex.mintlify.app/api/initialization Initialize the App Server connection Clients must send a single `initialize` request per transport connection before invoking any other method, then acknowledge with an `initialized` notification. ## Initialization Handshake The server returns the user agent string it will present to upstream services. Subsequent requests issued before initialization receive a `"Not initialized"` error, and repeated `initialize` calls on the same connection receive an `"Already initialized"` error. Send an `initialize` request with your client metadata. The server responds with initialization details. Acknowledge with an `initialized` notification. ## Request ### Method ``` initialize ``` ### Parameters Client identification information Client identifier (used for OpenAI Compliance Logs Platform) If you are developing a new Codex integration for enterprise use, contact us to get it added to the known clients list. See: [https://chatgpt.com/admin/api-reference#tag/Logs:-Codex](https://chatgpt.com/admin/api-reference#tag/Logs:-Codex) Human-readable client name Client version (semantic versioning recommended) Client capability flags Enable experimental API methods and fields List of exact notification method names to suppress for this connection * Matching is exact (no wildcards/prefixes) * Unknown method names are accepted and ignored * Example: `["codex/event/session_configured", "item/agentMessage/delta"]` ## Response User agent string the server will present to upstream services ## Examples ### Basic Initialization ```json Request theme={null} { "method": "initialize", "id": 0, "params": { "clientInfo": { "name": "codex_vscode", "title": "Codex VS Code Extension", "version": "0.1.0" } } } ``` ```json Response theme={null} { "id": 0, "result": { "userAgent": "codex/1.0.0" } } ``` ```json Notification (client sends) theme={null} { "method": "initialized" } ``` ### With Experimental API & Notification Opt-out ```json Request theme={null} { "method": "initialize", "id": 1, "params": { "clientInfo": { "name": "my_client", "title": "My Client", "version": "0.1.0" }, "capabilities": { "experimentalApi": true, "optOutNotificationMethods": [ "codex/event/session_configured", "item/agentMessage/delta" ] } } } ``` ```json Response theme={null} { "id": 1, "result": { "userAgent": "codex/1.0.0" } } ``` ## Experimental API Some app-server methods and fields are gated behind an experimental capability with no backwards-compatible guarantees. **Stable surface only (default):** No opt-in, no experimental methods/fields exposed. **Experimental surface:** Set `capabilities.experimentalApi: true` during initialization. ### Without Opt-in If a request uses an experimental method or field without opting in, the server rejects it with a JSON-RPC error: ``` requires experimentalApi capability ``` Examples: * `mock/experimentalMethod` (method-level gate) * `thread/start.mockExperimentalField` (field-level gate) ### Schema Generation Generate stable vs experimental schemas: ```bash theme={null} # Stable-only output (default) codex app-server generate-ts --out DIR codex app-server generate-json-schema --out DIR # Include experimental API surface codex app-server generate-ts --out DIR --experimental codex app-server generate-json-schema --out DIR --experimental ``` ## Notification Opt-out Clients can suppress specific notifications per connection by sending exact method names in `capabilities.optOutNotificationMethods`. **Behavior:** * Exact-match only: `item/agentMessage/delta` suppresses only that method * Unknown method names are ignored * Applies to both legacy (`codex/event/*`) and v2 (`thread/*`, `turn/*`, `item/*`) notifications * Does not apply to requests/responses/errors **Examples:** * Opt out of legacy session setup event: `codex/event/session_configured` * Opt out of streamed agent text deltas: `item/agentMessage/delta` ## Next Steps Start or resume a conversation thread # Items Source: https://openai-codex.mintlify.app/api/items Thread item types and streaming notifications **ThreadItem** is the core data structure representing user inputs and agent outputs within a turn. Items are persisted and used as context for future conversations. ## Item Lifecycle All items follow a consistent lifecycle: Emits the full `item` when a new unit of work begins ```json theme={null} { "method": "item/started", "params": { "threadId": "thr_123", "turnId": "turn_456", "item": { "type": "agentMessage", "id": "item_789", "text": "" } } } ``` Zero or more streaming updates * `item/agentMessage/delta` - Agent text streaming * `item/commandExecution/outputDelta` - Command output streaming * `item/reasoning/summaryTextDelta` - Reasoning summary streaming Sends the final `item` once work finishes ```json theme={null} { "method": "item/completed", "params": { "threadId": "thr_123", "turnId": "turn_456", "item": { "type": "agentMessage", "id": "item_789", "text": "Here's the complete response..." } } } ``` ## Item Types ### userMessage User text or image input. Item identifier Array of user input items (text, image, localImage, skill, mention) **Example:** ```json theme={null} { "type": "userMessage", "id": "turn_456", "content": [ { "type": "text", "text": "Run tests" } ] } ``` ### agentMessage Agent response text. Item identifier Accumulated agent reply text Message phase (when applicable) **Streaming:** ```json theme={null} { "method": "item/agentMessage/delta", "params": { "threadId": "thr_123", "turnId": "turn_456", "itemId": "item_789", "delta": "Here is " } } ``` Concatenate `delta` values for the same `itemId` to reconstruct the full reply. ### plan **EXPERIMENTAL** - Proposed plan item content. Item identifier Plan text **Streaming:** ```json theme={null} { "method": "item/plan/delta", "params": { "threadId": "thr_123", "turnId": "turn_456", "itemId": "item_plan", "delta": "Step 1: Run tests\n" } } ``` The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text. ### reasoning Agent reasoning traces. Item identifier Streamed reasoning summaries (applicable for most OpenAI models) Raw reasoning blocks (applicable for open source models) **Streaming notifications:** ```json Summary Delta theme={null} { "method": "item/reasoning/summaryTextDelta", "params": { "threadId": "thr_123", "turnId": "turn_456", "itemId": "item_reasoning", "summaryIndex": 0, "delta": "Analyzing the test suite..." } } ``` ```json Summary Part Added theme={null} { "method": "item/reasoning/summaryPartAdded", "params": { "threadId": "thr_123", "turnId": "turn_456", "itemId": "item_reasoning", "summaryIndex": 1 } } ``` ```json Text Delta (raw) theme={null} { "method": "item/reasoning/textDelta", "params": { "threadId": "thr_123", "turnId": "turn_456", "itemId": "item_reasoning", "contentIndex": 0, "delta": "Let me think through this..." } } ``` ### commandExecution Sandboxed shell command. Item identifier The command to execute Command working directory PTY process identifier (when available) `inProgress`, `completed`, `failed`, or `declined` Best-effort parsing of command actions Combined stdout/stderr output Command exit code Execution duration in milliseconds **Streaming:** ```json theme={null} { "method": "item/commandExecution/outputDelta", "params": { "threadId": "thr_123", "turnId": "turn_456", "itemId": "item_cmd", "delta": "Running tests...\n" } } ``` ### fileChange Proposed or applied file edits. Item identifier Array of file changes with path, kind, and diff `inProgress`, `completed`, `failed`, or `declined` **Streaming:** ```json theme={null} { "method": "item/fileChange/outputDelta", "params": { "threadId": "thr_123", "turnId": "turn_456", "itemId": "item_file", "delta": "Applying patch to src/main.rs...\n" } } ``` ### mcpToolCall MCP (Model Context Protocol) tool invocation. Item identifier MCP server name Tool name `inProgress`, `completed`, or `failed` Tool arguments (JSON) Tool result (when completed) Error details (when failed) Call duration in milliseconds **Example:** ```json theme={null} { "type": "mcpToolCall", "id": "item_mcp", "server": "github", "tool": "create_issue", "status": "completed", "arguments": { "title": "Bug report", "body": "Description" }, "result": { "issue_url": "https://github.com/..." }, "durationMs": 1234 } ``` ### dynamicToolCall Dynamic tool call executed on the client. Item identifier Tool name Tool arguments (JSON) `inProgress`, `completed`, or `failed` Output content items (text/images) Whether the tool call succeeded Call duration in milliseconds ### webSearch Web search request issued by the agent. Item identifier Search query Action payload (search, open\_page, find\_in\_page) **Example:** ```json theme={null} { "type": "webSearch", "id": "item_search", "query": "rust async trait error handling", "action": { "type": "search", "query": "rust async trait error handling" } } ``` ### imageView Image viewer tool invocation. Item identifier Path to the image file **Example:** ```json theme={null} { "type": "imageView", "id": "item_img", "path": "/tmp/screenshot.png" } ``` ### enteredReviewMode Emitted when the reviewer starts. Item identifier Short user-facing label (e.g., `"current changes"`, `"commit abc123"`) ### exitedReviewMode Emitted when the reviewer finishes. Item identifier Full plain-text review (overall notes plus bullet point findings) **Example:** ```json theme={null} { "type": "exitedReviewMode", "id": "turn_900", "review": "Looks solid overall...\n\n- Prefer Stylize helpers — app.rs:10-20\n ..." } ``` ### contextCompaction Emitted when Codex compacts conversation history. Item identifier **Example:** ```json theme={null} { "type": "contextCompaction", "id": "item_compact" } ``` Context compaction can happen automatically when the conversation history grows too large. ## Item Notifications Summary Emits the full `item` when work begins Sends the final `item` once work finishes Streams agent message text Streams plan content (experimental) Streams reasoning summary text Marks reasoning summary section boundaries Streams raw reasoning text (open source models) Streams command stdout/stderr Streams file change tool output MCP tool call progress updates ## Approvals Certain actions (shell commands or file changes) may require explicit user approval depending on the approval policy. ### Command Execution Approval Order of messages: Shows pending `commandExecution` item ```json theme={null} { "method": "item/commandExecution/requestApproval", "id": 100, "params": { "threadId": "thr_123", "turnId": "turn_456", "itemId": "item_cmd", "command": ["rm", "-rf", "/tmp/test"], "cwd": "/Users/me/project", "commandActions": [...], "reason": "Potentially destructive command" } } ``` ```json theme={null} { "id": 100, "result": { "decision": "accept" } } ``` Possible decisions: * `accept` - Approve the command * `acceptForSession` - Approve and cache for session * `acceptWithExecpolicyAmendment` - Approve with persistent rule * `applyNetworkPolicyAmendment` - Apply network policy rule * `decline` - Deny the command * `cancel` - Deny and interrupt turn Confirms the request was resolved Final item with execution result ### File Change Approval Order of messages: Emits `fileChange` item with diff summaries ```json theme={null} { "method": "item/fileChange/requestApproval", "id": 101, "params": { "threadId": "thr_123", "turnId": "turn_456", "itemId": "item_file", "reason": "File changes require approval" } } ``` ```json theme={null} { "id": 101, "result": { "decision": "accept" } } ``` Possible decisions: * `accept` - Approve the changes * `decline` - Deny the changes Confirms the request was resolved Final item with `status: "completed"`, `"failed"`, or `"declined"` ## Next Steps List available models and capabilities Manage and invoke skills # Models Source: https://openai-codex.mintlify.app/api/models List and configure available models The `model/list` API returns available models with their capabilities, reasoning effort options, and upgrade paths. ## List Models Fetch available models with optional pagination and filtering. ### Method ``` model/list ``` ### Parameters Opaque pagination cursor from previous response Page size (server defaults if unset) When true, include models with `hidden: true` ### Response Array of model objects Cursor for next page (null if no more pages) ## Model Object Unique model identifier Model name (e.g., `gpt-5.1-codex`) Human-readable model name Model description Whether the model is hidden from default picker Whether this is the default model (only one model should be marked default) Whether the model supports personality customization Supported input modalities (e.g., `["text", "image"]`) Available reasoning effort levels Effort level: `low`, `medium`, or `high` Human-readable effort name Effort description Default reasoning effort for this model (`low`, `medium`, `high`) Legacy upgrade model ID (deprecated) Model upgrade information Recommended upgrade model Upgrade message text URL to model information Markdown migration guide Model availability message Availability message (e.g., "Upgrade to Pro for access") ## Example ```json Request theme={null} { "method": "model/list", "id": 6, "params": { "cursor": null, "limit": 25, "includeHidden": false } } ``` ```json Response theme={null} { "id": 6, "result": { "data": [ { "id": "gpt-5.1-codex", "model": "gpt-5.1-codex", "displayName": "GPT-5.1 Codex", "description": "Latest Codex model with advanced reasoning", "hidden": false, "isDefault": true, "supportsPersonality": true, "inputModalities": ["text", "image"], "supportedReasoningEfforts": [ { "effort": "low", "displayName": "Low", "description": "Fast responses" }, { "effort": "medium", "displayName": "Medium", "description": "Balanced performance" }, { "effort": "high", "displayName": "High", "description": "Deep reasoning" } ], "defaultReasoningEffort": "medium", "upgrade": null, "upgradeInfo": null, "availabilityNux": null }, { "id": "gpt-5-codex", "model": "gpt-5-codex", "displayName": "GPT-5 Codex", "description": "Previous generation Codex model", "hidden": false, "isDefault": false, "supportsPersonality": true, "inputModalities": ["text"], "supportedReasoningEfforts": [ { "effort": "medium", "displayName": "Medium", "description": "Standard reasoning" } ], "defaultReasoningEffort": "medium", "upgrade": "gpt-5.1-codex", "upgradeInfo": { "model": "gpt-5.1-codex", "upgradeCopy": "Upgrade to GPT-5.1 Codex for improved performance", "modelLink": "https://openai.com/models/gpt-5-1-codex", "migrationMarkdown": "## Migration Guide\n\nGPT-5.1 offers..." }, "availabilityNux": null } ], "nextCursor": null } } ``` ## Reasoning Effort Models support different reasoning effort levels that affect response quality and latency. Fast responses with minimal reasoning Best for: Quick edits, simple queries Balanced performance and quality Best for: General development tasks Deep reasoning for complex problems Best for: Architecture, debugging, optimization ### Setting Reasoning Effort You can set the reasoning effort at the thread or turn level: ```json Thread-level (thread/start) theme={null} { "method": "thread/start", "id": 10, "params": { "model": "gpt-5.1-codex", "effort": "high" } } ``` ```json Turn-level (turn/start) theme={null} { "method": "turn/start", "id": 30, "params": { "threadId": "thr_123", "input": [{"type": "text", "text": "Optimize this algorithm"}], "effort": "high" } } ``` ## Input Modalities Models may support different input modalities: Text input (all models) Image input (vision-capable models) Audio input (audio-capable models) ## Model Selection When selecting a model, consider: 1. **Task complexity**: Use higher reasoning effort for complex problems 2. **Input type**: Ensure the model supports your input modality (text, images) 3. **Personality**: Check `supportsPersonality` if you want to customize the agent's tone 4. **Availability**: Check `availabilityNux` for plan requirements 5. **Default**: Start with `isDefault: true` model if unsure ## Next Steps List and manage skills Discover and use apps # Overview Source: https://openai-codex.mintlify.app/api/overview App Server API architecture and JSON-RPC protocol The Codex App Server provides a JSON-RPC 2.0 API that powers rich interfaces like the [Codex VS Code extension](https://marketplace.visualstudio.com/items?itemName=openai.chatgpt). ## Protocol The App Server uses bidirectional JSON-RPC 2.0 communication with the `"jsonrpc":"2.0"` header omitted on the wire for efficiency. ### Supported Transports Default transport using newline-delimited JSON (JSONL) ```bash theme={null} codex app-server --listen stdio:// ``` Experimental transport (unsupported for production) ```bash theme={null} codex app-server --listen ws://IP:PORT ``` WebSocket transport is currently experimental and unsupported. Do not rely on it for production workloads. ## Core Primitives The API exposes three top-level primitives representing interactions between a user and Codex: A conversation between a user and the Codex agent. Each thread contains multiple turns. **Key Operations:** * `thread/start` - Create a new thread * `thread/resume` - Continue an existing thread * `thread/fork` - Branch from an existing thread * `thread/list` - List stored threads * `thread/archive` - Archive a thread One turn of the conversation, typically starting with a user message and finishing with an agent message. Each turn contains multiple items. **Key Operations:** * `turn/start` - Send user input and begin generation * `turn/interrupt` - Cancel an in-flight turn * `turn/steer` - Add input to an active turn Represents user inputs and agent outputs as part of a turn, persisted and used as context for future conversations. **Item Types:** * `userMessage` - User text/image input * `agentMessage` - Agent response * `reasoning` - Agent reasoning traces * `commandExecution` - Shell commands * `fileChange` - File edits * `mcpToolCall` - MCP tool invocations * `webSearch` - Web search requests ## Message Schema You can generate TypeScript or JSON Schema definitions for the current version: ```bash theme={null} codex app-server generate-ts --out DIR codex app-server generate-json-schema --out DIR ``` For experimental API surface: ```bash theme={null} codex app-server generate-ts --out DIR --experimental codex app-server generate-json-schema --out DIR --experimental ``` ## Backpressure Behavior The server uses bounded queues between transport ingress, request processing, and outbound writes. When request ingress is saturated, new requests are rejected with JSON-RPC error code `-32001` and message `"Server overloaded; retry later."` Clients should treat this as retryable and use exponential backoff with jitter. ## Tracing & Logging Controls log filtering and verbosity ```bash theme={null} RUST_LOG=debug codex app-server ``` Set to `json` to emit structured logs to stderr ```bash theme={null} LOG_FORMAT=json codex app-server ``` ## Next Steps Learn how to initialize a connection Manage conversation threads Start and control conversation turns Understand item types and notifications # Skills Source: https://openai-codex.mintlify.app/api/skills Skill discovery and invocation Skills are specialized capabilities that extend Codex's functionality. They can be user-defined, project-scoped, or shared across workspaces. ## List Skills Fetch available skills for one or more working directories. ### Method ``` skills/list ``` ### Parameters Working directories to scan for skills (defaults to current session cwd if empty) Bypass the skills cache and re-scan from disk Additional roots to scan as user-scoped skills for specific cwds Working directory path Absolute paths to scan as user scope ### Response Array of skills grouped by working directory Working directory Array of skill metadata Skill loading errors ## Skill Object Skill identifier (e.g., `skill-creator`) Brief skill description Whether the skill is enabled in config UI metadata for the skill Human-readable skill name Short description for UI Small icon filename Large icon filename Hex color code (e.g., `#111111`) Default prompt text ## Example ```json Request theme={null} { "method": "skills/list", "id": 25, "params": { "cwds": ["/Users/me/project", "/Users/me/other-project"], "forceReload": true } } ``` ```json Response theme={null} { "id": 25, "result": { "data": [ { "cwd": "/Users/me/project", "skills": [ { "name": "skill-creator", "description": "Create or update a Codex skill", "enabled": true, "interface": { "displayName": "Skill Creator", "shortDescription": "Create or update a Codex skill", "iconSmall": "icon.svg", "iconLarge": "icon-large.svg", "brandColor": "#111111", "defaultPrompt": "Add a new skill for triaging flaky CI." } }, { "name": "code-review", "description": "Perform automated code review", "enabled": true, "interface": { "displayName": "Code Review", "shortDescription": "Automated code review", "iconSmall": "review.svg", "iconLarge": "review-large.svg", "brandColor": "#4A90E2", "defaultPrompt": "Review my recent changes" } } ], "errors": [] }, { "cwd": "/Users/me/other-project", "skills": [], "errors": [] } ] } } ``` ## Invoking a Skill To invoke a skill, include `$` in the text input and add a `skill` input item. ```json turn/start with skill theme={null} { "method": "turn/start", "id": 101, "params": { "threadId": "thr_123", "input": [ { "type": "text", "text": "$skill-creator Add a new skill for triaging flaky CI and include step-by-step usage." }, { "type": "skill", "name": "skill-creator", "path": "/Users/me/.codex/skills/skill-creator/SKILL.md" } ] } } ``` ```json Response theme={null} { "id": 101, "result": { "turn": { "id": "turn_500", "status": "inProgress", "items": [], "error": null } } } ``` If you omit the `skill` input item, the model will still parse `$` and try to locate the skill, but this adds latency. Always include the `skill` item when possible. ## Enable or Disable a Skill Use `skills/config/write` to enable or disable a skill by path. ### Method ``` skills/config/write ``` ### Parameters Absolute path to the skill's SKILL.md file Whether the skill should be enabled ### Response Empty object on success ### Example ```json Request theme={null} { "method": "skills/config/write", "id": 26, "params": { "path": "/Users/me/.codex/skills/skill-creator/SKILL.md", "enabled": false } } ``` ```json Response theme={null} { "id": 26, "result": {} } ``` ## Skill Scopes Skills are discovered from multiple scopes: Bundled with Codex **Location:** Codex installation directory User-level skills **Location:** `~/.codex/skills/` Project-specific skills **Location:** `{cwd}/.codex/skills/` ## Skill Structure A skill is defined by a `SKILL.md` file containing: ```markdown theme={null} # Skill Name Brief description of what the skill does. ## Instructions Detailed instructions for the agent on how to use this skill. ## Examples Example usage scenarios. ## Dependencies Required tools, packages, or configurations. ``` Optional companion files: * `icon.svg` - Small icon * `icon-large.svg` - Large icon * `config.toml` - Skill configuration (display name, brand color, default prompt) ## Remote Skills (Under Development) The remote skills API is under development. Do not call from production clients yet. ### List Remote Skills ``` skills/remote/list ``` List public remote skills from the skill directory. ### Export Remote Skill ``` skills/remote/export ``` Download a remote skill by `hazelnutId` into the user's `skills` directory. ## Next Steps Discover and use connector apps Start a turn with skill invocation # Threads Source: https://openai-codex.mintlify.app/api/threads Thread lifecycle and management APIs A **Thread** is a conversation between a user and the Codex agent. Each thread contains multiple turns and persists as a rollout file on disk. ## Thread Object Unique thread identifier (e.g., `thr_123`) Usually the first user message in the thread, if available Whether the thread is ephemeral and should not be materialized on disk Model provider used for this thread (e.g., `openai`) Unix timestamp (seconds) when the thread was created Unix timestamp (seconds) when the thread was last updated Current runtime status for the thread * `notLoaded` - Thread not currently loaded in memory * `idle` - Thread loaded but no active turn * `systemError` - Thread encountered a system error * `active` - Thread has an active turn (includes `activeFlags` array) Path to the thread rollout file on disk (null for ephemeral threads) Working directory captured for the thread Array of turns (only populated when explicitly requested) ## Start a Thread Create a new conversation thread with optional configuration. ### Method ``` thread/start ``` ### Parameters Model to use (e.g., `gpt-5.1-codex`) Model provider (e.g., `openai`) Working directory for the thread Approval policy for commands and file changes * `never` - Never ask for approval * `untrusted` - Ask for approval on untrusted operations * `on-request` - Always ask for approval * `on-failure` - Ask for approval on failures * `reject` - Reject all approval requests Sandbox mode * `read-only` - Read-only file system access * `workspace-write` - Write access to workspace * `danger-full-access` - Full system access Agent personality * `friendly` - Friendly and conversational * `pragmatic` - Direct and efficient * `none` - No personality modifier Optional metrics tag (`service_name`) ### Response The created thread object Active model for the thread Active model provider Working directory Active approval policy Active sandbox policy ### Notifications Emitted when the thread starts ```json theme={null} { "method": "thread/started", "params": { "thread": { "id": "thr_123", ... } } } ``` ### Example ```json Request theme={null} { "method": "thread/start", "id": 10, "params": { "model": "gpt-5.1-codex", "cwd": "/Users/me/project", "approvalPolicy": "never", "sandbox": "workspaceWrite", "personality": "friendly" } } ``` ```json Response theme={null} { "id": 10, "result": { "thread": { "id": "thr_123", "preview": "", "modelProvider": "openai", "createdAt": 1730910000, "status": { "type": "idle" } }, "model": "gpt-5.1-codex", "modelProvider": "openai", "cwd": "/Users/me/project", "approvalPolicy": "never", "sandbox": { "type": "workspaceWrite", "writableRoots": ["/Users/me/project"], "networkAccess": true } } } ``` ```json Notification theme={null} { "method": "thread/started", "params": { "thread": { "id": "thr_123", "preview": "", "modelProvider": "openai", "createdAt": 1730910000 } } } ``` ## Resume a Thread Reopen an existing thread by ID to continue the conversation. ### Method ``` thread/resume ``` ### Parameters Thread ID to resume Override personality for resumed thread ### Response Same as `thread/start` response. ### Example ```json Request theme={null} { "method": "thread/resume", "id": 11, "params": { "threadId": "thr_123", "personality": "friendly" } } ``` ```json Response theme={null} { "id": 11, "result": { "thread": { "id": "thr_123", "preview": "Help me debug this issue", "modelProvider": "openai", "createdAt": 1730910000 }, "model": "gpt-5.1-codex", "modelProvider": "openai" } } ``` ## Fork a Thread Branch from an existing thread into a new thread ID with copied history. ### Method ``` thread/fork ``` ### Parameters Thread ID to fork from ### Response The newly created forked thread (with a new ID) ### Notifications Emitted for the new forked thread ### Example ```json Request theme={null} { "method": "thread/fork", "id": 12, "params": { "threadId": "thr_123" } } ``` ```json Response theme={null} { "id": 12, "result": { "thread": { "id": "thr_456", "preview": "Help me debug this issue", "modelProvider": "openai", "createdAt": 1730910100 } } } ``` ```json Notification theme={null} { "method": "thread/started", "params": { "thread": { "id": "thr_456", ... } } } ``` ## List Threads Page through stored rollouts with optional filtering and pagination. ### Method ``` thread/list ``` ### Parameters Opaque pagination cursor from previous response Page size (server defaults if unset) Sort key: `created_at` (default) or `updated_at` Filter by model providers (empty/null includes all) Filter by source kinds (`cli`, `vscode`, etc.) When `true`, list archived threads only. When `false`/`null`, list non-archived threads Filter by exact working directory path Filter by substring match in thread title (case-sensitive) ### Response Array of thread objects Cursor for next page (null if no more pages) ### Example ```json Request theme={null} { "method": "thread/list", "id": 20, "params": { "cursor": null, "limit": 25, "sortKey": "created_at" } } ``` ```json Response theme={null} { "id": 20, "result": { "data": [ { "id": "thr_a", "preview": "Create a TUI", "modelProvider": "openai", "createdAt": 1730831111, "updatedAt": 1730831111, "status": { "type": "notLoaded" } }, { "id": "thr_b", "preview": "Fix tests", "modelProvider": "openai", "createdAt": 1730750000, "updatedAt": 1730750000, "status": { "type": "notLoaded" } } ], "nextCursor": "opaque-token-or-null" } } ``` ## Read a Thread Fetch a stored thread by ID without resuming it. ### Method ``` thread/read ``` ### Parameters Thread ID to read When true, include turns and their items from rollout history ### Response Thread object with `status` and optional `turns` ### Example ```json Request (without turns) theme={null} { "method": "thread/read", "id": 22, "params": { "threadId": "thr_123" } } ``` ```json Request (with turns) theme={null} { "method": "thread/read", "id": 23, "params": { "threadId": "thr_123", "includeTurns": true } } ``` ```json Response theme={null} { "id": 23, "result": { "thread": { "id": "thr_123", "status": { "type": "notLoaded" }, "turns": [ { "id": "turn_1", "items": [...], "status": "completed" } ] } } } ``` ## Archive a Thread Move a thread's rollout file into the archived directory. ### Method ``` thread/archive ``` ### Parameters Thread ID to archive ### Response Empty object on success ### Notifications Emitted after successful archive ```json theme={null} { "method": "thread/archived", "params": { "threadId": "thr_b" } } ``` ### Example ```json Request theme={null} { "method": "thread/archive", "id": 21, "params": { "threadId": "thr_b" } } ``` ```json Response theme={null} { "id": 21, "result": {} } ``` ```json Notification theme={null} { "method": "thread/archived", "params": { "threadId": "thr_b" } } ``` ## Other Thread Operations Move an archived thread back to sessions directory **Returns:** Restored `thread` object Set or update a thread's user-facing name **Returns:** Empty object `{}` List thread IDs currently loaded in memory **Returns:** `{ data: string[], nextCursor: string | null }` Unsubscribe from thread events (unloads if last subscriber) **Returns:** `{ status: "unsubscribed" | "notSubscribed" | "notLoaded" }` Drop last N turns from thread history **Returns:** Updated `thread` with `turns` populated Trigger conversation history compaction **Returns:** Empty object `{}` (progress via notifications) ## Thread Notifications Emitted when a new thread starts or forks Emitted when a loaded thread's status changes ```json theme={null} { "method": "thread/status/changed", "params": { "threadId": "thr_123", "status": { "type": "active", "activeFlags": [] } } } ``` Emitted after archiving a thread Emitted after unarchiving a thread Emitted when a thread is unloaded (no more subscribers) Emitted when a thread's name changes Emitted with token usage updates during turns ## Next Steps Send user input and start a turn Understand turn items and streaming # Turns Source: https://openai-codex.mintlify.app/api/turns Turn lifecycle and control APIs A **Turn** represents one round of conversation, typically starting with a user message and finishing with an agent message. Each turn contains multiple items that stream as notifications. ## Turn Object Unique turn identifier (e.g., `turn_456`) Array of items in this turn Only populated on `thread/resume` or `thread/fork` responses. For all other responses and notifications, this field is an empty array. Use `item/*` notifications to track items. Current turn status * `inProgress` - Turn is actively running * `completed` - Turn finished successfully * `interrupted` - Turn was cancelled * `failed` - Turn encountered an error Error details (only populated when `status` is `failed`) Human-readable error message Structured error classification Common values: * `ContextWindowExceeded` * `UsageLimitExceeded` * `HttpConnectionFailed` * `ResponseStreamDisconnected` * `Unauthorized` * `BadRequest` * `InternalServerError` * `Other` Additional error context ## Start a Turn Send user input to a thread and begin Codex generation. ### Method ``` turn/start ``` ### Parameters Thread ID to add the turn to Array of user input items **Text input:** ```json theme={null} { "type": "text", "text": "Run tests" } ``` **Image from URL:** ```json theme={null} { "type": "image", "url": "https://example.com/image.png" } ``` **Local image:** ```json theme={null} { "type": "localImage", "path": "/tmp/screenshot.png" } ``` **Skill invocation:** ```json theme={null} { "type": "skill", "name": "skill-creator", "path": "/Users/me/.codex/skills/skill-creator/SKILL.md" } ``` **App mention:** ```json theme={null} { "type": "mention", "name": "Demo App", "path": "app://demo-app" } ``` Override working directory for this turn and subsequent turns Override approval policy Override sandbox policy **Danger full access:** ```json theme={null} { "type": "dangerFullAccess" } ``` **Read-only:** ```json theme={null} { "type": "readOnly", "access": { "type": "fullAccess" } } ``` **Workspace write:** ```json theme={null} { "type": "workspaceWrite", "writableRoots": ["/Users/me/project"], "networkAccess": true } ``` **External sandbox:** ```json theme={null} { "type": "externalSandbox", "networkAccess": "enabled" } ``` Override model for this turn and subsequent turns Override reasoning effort (`low`, `medium`, `high`) Override reasoning summary mode (`concise`, `verbose`) JSON Schema to constrain the final assistant message (applies only to this turn) ```json theme={null} { "type": "object", "properties": { "answer": { "type": "string" } }, "required": ["answer"], "additionalProperties": false } ``` ### Response Initial turn object with `status: "inProgress"` and empty `items` array ### Notifications The server streams JSON-RPC notifications while the turn is running: Initial turn notification ```json theme={null} { "method": "turn/started", "params": { "threadId": "thr_123", "turn": { "id": "turn_456", "status": "inProgress", "items": [], "error": null } } } ``` See [Items](/api/items) for full item lifecycle * `item/started` - New item begins * `item/agentMessage/delta` - Streamed text * `item/completed` - Item finishes Final turn notification with status ```json theme={null} { "method": "turn/completed", "params": { "threadId": "thr_123", "turn": { "id": "turn_456", "status": "completed", "items": [], "error": null } } } ``` ### Example: Basic Turn ```json Request theme={null} { "method": "turn/start", "id": 30, "params": { "threadId": "thr_123", "input": [ { "type": "text", "text": "Run tests" } ] } } ``` ```json Response theme={null} { "id": 30, "result": { "turn": { "id": "turn_456", "status": "inProgress", "items": [], "error": null } } } ``` ### Example: Invoke a Skill Include `$` in the text input and add a `skill` input item. ```json Request theme={null} { "method": "turn/start", "id": 33, "params": { "threadId": "thr_123", "input": [ { "type": "text", "text": "$skill-creator Add a new skill for triaging flaky CI" }, { "type": "skill", "name": "skill-creator", "path": "/Users/me/.codex/skills/skill-creator/SKILL.md" } ] } } ``` ```json Response theme={null} { "id": 33, "result": { "turn": { "id": "turn_457", "status": "inProgress", "items": [], "error": null } } } ``` ### Example: Invoke an App Include `$` in text and add a `mention` input with `app://`. ```json Request theme={null} { "method": "turn/start", "id": 34, "params": { "threadId": "thr_123", "input": [ { "type": "text", "text": "$demo-app Summarize the latest updates." }, { "type": "mention", "name": "Demo App", "path": "app://demo-app" } ] } } ``` ```json Response theme={null} { "id": 34, "result": { "turn": { "id": "turn_458", "status": "inProgress", "items": [], "error": null } } } ``` ## Interrupt a Turn Cancel a running turn. ### Method ``` turn/interrupt ``` ### Parameters Thread ID Turn ID to interrupt ### Response Empty object on success ### Notifications After interruption, the server emits `turn/completed` with `status: "interrupted"`. ### Example ```json Request theme={null} { "method": "turn/interrupt", "id": 31, "params": { "threadId": "thr_123", "turnId": "turn_456" } } ``` ```json Response theme={null} { "id": 31, "result": {} } ``` ```json Notification theme={null} { "method": "turn/completed", "params": { "threadId": "thr_123", "turn": { "id": "turn_456", "status": "interrupted", "items": [], "error": null } } } ``` ## Steer a Turn Append additional user input to a currently active turn without starting a new turn. ### Method ``` turn/steer ``` ### Parameters Thread ID Additional user input to append Required active turn ID precondition. Fails if no active turn or ID doesn't match. ### Response The active turn ID that accepted the input ### Example ```json Request theme={null} { "method": "turn/steer", "id": 32, "params": { "threadId": "thr_123", "input": [ { "type": "text", "text": "Actually focus on failing tests first." } ], "expectedTurnId": "turn_456" } } ``` ```json Response theme={null} { "id": 32, "result": { "turnId": "turn_456" } } ``` ## Turn Notifications Emitted when a turn begins **Payload:** `{ threadId: string, turn: Turn }` Emitted when a turn finishes (completed, interrupted, or failed) **Payload:** `{ threadId: string, turn: Turn }` Emitted after every `fileChange` item with turn-level unified diff **Payload:** `{ threadId: string, turnId: string, diff: string }` Emitted when the agent shares or changes its plan **Payload:** ```json theme={null} { "threadId": "thr_123", "turnId": "turn_456", "explanation": "Breaking down the task...", "plan": [ { "step": "Run tests", "status": "completed" }, { "step": "Fix errors", "status": "inProgress" }, { "step": "Commit changes", "status": "pending" } ] } ``` Emitted when the backend reroutes to a different model **Payload:** `{ threadId: string, turnId: string, fromModel: string, toModel: string, reason: string }` Emitted on mid-turn errors **Payload:** `{ error: TurnError, willRetry: boolean, threadId: string, turnId: string }` ## Next Steps Understand item types and streaming notifications List available models and their capabilities # Architecture Overview Source: https://openai-codex.mintlify.app/architecture/overview High-level architecture of the Codex CLI monorepo Codex CLI is built as a native, zero-dependency executable with a hybrid architecture combining Rust and TypeScript components. ## Monorepo Structure The Codex repository is organized as a monorepo with two primary components: Core business logic, TUI, and native execution (codex-rs/) Wrapper for distribution and platform-specific integration ## Architecture Layers The Codex architecture is structured in distinct layers: ### 1. Distribution Layer (TypeScript) The TypeScript CLI wrapper provides: * **npm packaging** — Install via `npm i -g @openai/codex` * **Platform detection** — Routes to the correct native binary * **Zero-dependency install** — All native binaries are bundled ### 2. Core Implementation (Rust) The `codex-rs` Rust workspace contains the complete implementation: The `codex-core` crate implements all Codex business logic: * Conversation management and turn execution * Model interaction and streaming * Tool execution and sandboxing * Configuration and state management * Designed as a library crate for reuse across UIs Multiple frontend options built on `codex-core`: * **TUI (codex-tui)** — Fullscreen terminal interface using Ratatui * **Exec (codex-exec)** — Headless CLI for automation and scripts * **App Server (codex-app-server)** — JSON-RPC server for IDEs and integrations * **CLI (codex-cli)** — Multitool that provides all above via subcommands Platform-specific sandboxing and security: * **macOS** — Seatbelt sandbox profiles * **Linux** — Landlock and Bubblewrap isolation * **Windows** — Process isolation and restrictions * **Cross-platform** — Process hardening and security primitives ### 3. Integration Points Codex integrates with external systems through multiple interfaces: ```mermaid theme={null} graph TB CLI[Codex CLI] TUI[TUI Interface] AppServer[App Server] VSCode[VS Code Extension] MCP[MCP Servers] CLI --> Core[codex-core] TUI --> Core AppServer --> Core VSCode --> AppServer MCP --> Core Core --> Sandbox[Platform Sandbox] Core --> Models[AI Models] ``` ## Key Design Principles Built in Rust for fast startup and efficient resource usage OS-specific sandboxing on macOS, Linux, and Windows Shared core library with multiple interface options Self-contained binaries with no runtime requirements ## Workspace Organization The Rust workspace in `codex-rs/` uses Cargo workspaces with 60+ crates organized by function: * **Core crates** — `core`, `cli`, `tui`, `exec`, `app-server` * **Sandbox crates** — `linux-sandbox`, `process-hardening` * **Protocol crates** — `protocol`, `app-server-protocol`, `rmcp-client` * **Integration crates** — `mcp-server`, `lmstudio`, `ollama` * **Utility crates** — `utils/*` for common functionality All workspace crates are prefixed with `codex-`. For example, the `core` folder contains the `codex-core` crate. ## Configuration Management Codex uses a layered configuration system: * **User config** — `~/.codex/config.toml` (TOML format) * **Requirements** — `requirements.toml` for constraints and policies * **MDM integration** — Enterprise management on supported platforms The Rust implementation uses `config.toml` instead of the legacy `config.json` format. ## Next Steps Explore the workspace structure and crate purposes Learn about the terminal interface implementation Understand platform-specific security isolation JSON-RPC protocol for IDE integration # Rust Workspace Structure Source: https://openai-codex.mintlify.app/architecture/rust-crates Overview of the Cargo workspace and crate organization in codex-rs The `codex-rs` directory is the root of a Cargo workspace containing the complete Rust implementation of Codex CLI. ## Workspace Members The workspace includes 60+ crates organized by functionality. All crate names are prefixed with `codex-`. **Naming Convention**: The `core` folder contains the `codex-core` crate, `tui` contains `codex-tui`, etc. ## Core Crates These crates form the foundation of Codex CLI: ### codex-core The core business logic for Codex, designed as a reusable library crate. **Responsibilities:** * Conversation and turn management * Model interaction and streaming responses * Tool execution and sandboxing coordination * Configuration loading and validation * Session state management **Platform Requirements:** * **macOS**: Expects `/usr/bin/sandbox-exec` (Seatbelt) * **Linux**: Expects binary to handle `codex-linux-sandbox` arg0 * **All**: Supports `--codex-run-as-apply-patch` for virtual apply\_patch CLI ### codex-cli The main CLI multitool that provides all Codex functionality via subcommands. **Subcommands:** * Default (no subcommand) — Launches TUI * `exec` — Headless execution * `app-server` — JSON-RPC server * `sandbox` — Sandbox testing * `mcp` — MCP server management * `config` — Configuration utilities ### codex-tui Fullscreen terminal interface built with Ratatui. **Features:** * Real-time conversation rendering * Interactive approvals and prompts * Diff visualization * Keyboard-driven navigation * See [TUI Architecture](/architecture/tui) for details ### codex-exec Non-interactive CLI for automation and programmatic use. **Usage:** ```bash theme={null} codex exec "your prompt here" codex exec --ephemeral "run without persisting" ``` **Features:** * Non-interactive execution * Output to stdout * Ephemeral mode (no session persistence) * RUST\_LOG support for debugging ### codex-app-server JSON-RPC 2.0 server for IDE integrations (VS Code, etc.). **Protocol:** * Bidirectional JSON-RPC over stdio or WebSocket * Thread/Turn/Item primitives * Streaming notifications * Approval flows **Clients:** * Official VS Code extension * Custom integrations via protocol ## Sandbox & Security Crates Platform-specific sandboxing implementations: Linux sandboxing using Landlock and Bubblewrap. **Components:** * Standalone `codex-linux-sandbox` executable * Library exposing `run_main()` for arg0 routing * Vendored bubblewrap for filesystem isolation **Current Behavior:** * Legacy: Landlock + mount protections * Modern: Bubblewrap pipeline (feature gated) * Read-only by default via `--ro-bind / /` * Writable roots with `--bind` * Protected paths (`.git`, `.codex`) re-applied as read-only * PID namespace isolation via `--unshare-pid` * Network isolation via `--unshare-net` * Managed proxy mode with internal routing bridge Cross-platform process hardening applied pre-main. **Hardening Steps:** * Disable core dumps * Disable ptrace attach (Linux/macOS) * Remove dangerous environment variables * `LD_PRELOAD` * `DYLD_*` variables **Usage:** ```rust theme={null} #[ctor::ctor] fn harden() { codex_process_hardening::pre_main_hardening(); } ``` Execution policy management for trusted commands. **Purpose:** * Allow-lists for approved commands * Session-scoped approvals * Policy persistence * Trust decision tracking ## Protocol & Communication Crates Core protocol types and message definitions. **Contents:** * Agent instructions and prompts * System message templates * Collaboration modes * Personality presets App Server JSON-RPC schema and types. **Features:** * TypeScript generation * JSON Schema export * Experimental API gating * Wire format validation Remote MCP (Model Context Protocol) client. **Purpose:** * Connect to MCP servers * Tool discovery and invocation * Resource access * OAuth flows Codex as an MCP server. **Usage:** ```bash theme={null} codex mcp-server npx @modelcontextprotocol/inspector codex mcp-server ``` ## Integration Crates * **codex-lmstudio** — LM Studio integration * **codex-ollama** — Ollama integration * **codex-backend-client** — OpenAI backend client * **codex-responses-api-proxy** — Responses API proxy server * **codex-config** — Configuration loading and validation * **codex-state** — Session state management * **codex-cloud-requirements** — Requirements.toml parsing * **codex-cloud-tasks** — Task execution framework * **codex-login** — Authentication flows * **codex-feedback** — Feedback submission * **codex-hooks** — Git hook management * **codex-skills** — Skill discovery and loading * **codex-secrets** — Secret management ## Utility Crates The `utils/` directory contains shared utilities: ```text Path Utils theme={null} utils/absolute-path — Absolute path handling utils/home-dir — Home directory detection utils/cache — Caching utilities ``` ```text Process Utils theme={null} utils/pty — PTY management utils/cargo-bin — Cargo binary location utils/sleep-inhibitor — Prevent system sleep ``` ```text Developer Utils theme={null} utils/git — Git operations utils/fuzzy-match — Fuzzy string matching utils/stream-parser — Stream parsing utils/approval-presets — Approval presets ``` ## Specialized Crates * **codex-file-search** — File search and indexing * **codex-apply-patch** — Patch application logic * **codex-ansi-escape** — ANSI escape sequence handling * **codex-shell-command** — Shell command parsing * **codex-shell-escalation** — Privilege escalation * **codex-stdio-to-uds** — stdio to Unix domain socket bridge * **codex-otel** — OpenTelemetry integration * **codex-network-proxy** — Network proxy support * **codex-test-macros** — Test utilities * **app-server-test-client** — App server test client * **debug-client** — Debug client for testing ## Workspace Configuration The workspace uses shared configuration in `codex-rs/Cargo.toml`: ### Edition & Versioning ```toml theme={null} [workspace.package] version = "0.0.0" edition = "2024" license = "Apache-2.0" ``` ### Dependency Management * All workspace crates share dependency versions * Internal crates use path dependencies * External dependencies locked in workspace * Custom patches for ratatui, crossterm, tungstenite ### Build Configuration ```toml Release Profile theme={null} [profile.release] lto = "fat" # Link-time optimization split-debuginfo = "off" strip = "symbols" # Minimal binary size codegen-units = 1 # Maximum optimization ``` ```toml CI Test Profile theme={null} [profile.ci-test] inherits = "test" debug = 1 # Reduced debug symbols opt-level = 0 ``` ### Linting Workspace enforces strict Clippy lints: * `expect_used = "deny"` * `unwrap_used = "deny"` * `manual_*` patterns denied * Format args must be inlined * Redundant operations denied ## Bazel Integration The workspace supports Bazel builds alongside Cargo: * `runfiles` integration for test resources * `cargo-bin` utility for binary location * Platform-specific build configurations After changing dependencies, run `just bazel-lock-update` from repo root to refresh `MODULE.bazel.lock`. ## Next Steps Deep dive into the Ratatui-based interface Platform-specific security implementations # Sandboxing Architecture Source: https://openai-codex.mintlify.app/architecture/sandboxing Platform-specific security isolation and execution policies Codex implements defense-in-depth sandboxing to isolate AI-executed commands from sensitive system resources, using platform-native security primitives. ## Overview All commands executed by Codex run inside a sandbox that restricts: * **Filesystem access** — Read-only by default, configurable write permissions * **Network access** — Optional restrictions or proxy routing * **Process capabilities** — Reduced privileges and system call filtering * **Protected paths** — `.git`, `.codex` always read-only even in writable roots Seatbelt sandbox profiles via `/usr/bin/sandbox-exec` Landlock LSM + Bubblewrap container isolation Process isolation and token restrictions ## Sandbox Modes Codex provides three sandbox policies: ### Read-Only (Default) Maximum security: entire filesystem is read-only, network blocked. **Use case:** Exploring unfamiliar code, running untrusted prompts ```bash theme={null} codex --sandbox read-only ``` ### Workspace Write Balanced security: write access within workspace, network optional. **Use case:** Active development, file modifications needed ```bash theme={null} codex --sandbox workspace-write ``` **Protected paths (always read-only):** * `.git` directory or pointer file * Resolved `gitdir:` target * `.codex` directory ### Danger Full Access No sandbox enforcement: full system access. **Use case:** Running in external container/VM, advanced users ```bash theme={null} codex --sandbox danger-full-access ``` Only use this mode if you are already running Codex inside a container or other isolated environment. ## Platform Implementations ### macOS (Seatbelt) Codex uses Apple's Seatbelt sandbox via `/usr/bin/sandbox-exec`. **Location:** `codex-core` expects `/usr/bin/sandbox-exec` **Features:** * Network access control via `SandboxPolicy` * Filesystem read/write roots configuration * Protected path enforcement (`.git`, `.codex`) * Seatbelt profile generation at runtime Seatbelt supports macOS-specific permission extensions: **No extension profile:** * Legacy default preferences read access (`user-preference-read`) **Extension profile with no `macos_preferences` grant:** * No preferences access clauses added **`macos_preferences = "readonly"`:** * cfprefs read clauses * `user-preference-read` operation **`macos_preferences = "readwrite"`:** * All readonly clauses * `user-preference-write` operation * cfprefs shm write clauses **`macos_automation = true`:** * Broad Apple Events send permissions **`macos_automation = ["com.apple.Notes", ...]`:** * Apple Events send only to listed bundle IDs **`macos_accessibility = true`:** * `com.apple.axserver` mach lookup **`macos_calendar = true`:** * `com.apple.CalendarAgent` mach lookup Test sandbox behavior with: ```bash theme={null} codex sandbox macos [--full-auto] [--log-denials] [COMMAND]... # Legacy alias codex debug seatbelt [--full-auto] [--log-denials] [COMMAND]... ``` **Flags:** * `--full-auto` — Run command automatically * `--log-denials` — Log all denied operations ### Linux (Landlock + Bubblewrap) Codex uses a dual-mode Linux sandbox with legacy and modern pipelines. **Crate:** `codex-linux-sandbox` **Produces:** * Standalone `codex-linux-sandbox` executable (bundled with npm CLI) * Library crate exposing `run_main()` for arg0 routing **arg0 Routing:** When the binary detects arg0 is `codex-linux-sandbox`, it executes sandbox logic instead of normal CLI. Original implementation using Landlock LSM and mount namespaces. **Features:** * Landlock filesystem restrictions * Mount protection * Default when `use_linux_sandbox_bwrap` feature is off Standardized container-based isolation using vendored bubblewrap. **Feature gate:** `use_linux_sandbox_bwrap` (temporary during rollout) **CLI flag:** `-c features.use_linux_sandbox_bwrap=true` **Isolation mechanisms:** 1. **Process hardening:** * `PR_SET_NO_NEW_PRIVS` applied in-process * seccomp network filter 2. **Filesystem isolation:** * Read-only by default: `--ro-bind / /` * Writable roots: `--bind ` * Protected subpaths re-applied: `--ro-bind` for `.git`, `gitdir:`, `.codex` * Symlink blocking: mount `/dev/null` on symlinks or missing components 3. **Namespace isolation:** * PID namespace: `--unshare-pid` * Network namespace: `--unshare-net` (when network restricted) * Fresh `/proc`: `--proc /proc` (skip with `--no-proc` in restricted containers) 4. **Managed proxy mode:** * `--unshare-net` + internal TCP→UDS→TCP bridge * Tool traffic reaches only configured proxy endpoints * seccomp blocks new `AF_UNIX`/`socketpair` creation for user command Test sandbox behavior with: ```bash theme={null} codex sandbox linux [--full-auto] [COMMAND]... # Legacy alias codex debug landlock [--full-auto] [COMMAND]... ``` **Flags:** * `--full-auto` — Run command automatically ### Vendored Bubblewrap Codex vendors bubblewrap for consistent behavior across distributions. **Location:** `codex-rs/vendor/bubblewrap/` The vendored build ensures Codex doesn't depend on system package versions. ### Windows Sandbox Platform-specific process isolation for Windows. **Crate:** `codex-windows-sandbox` (inferred from Cargo.toml) **Testing:** ```bash theme={null} codex sandbox windows [--full-auto] [COMMAND]... ``` **Setup:** App-server exposes `windowsSandbox/setupStart` for elevated/unelevated modes. ## Process Hardening All Codex processes apply security hardening pre-main. Cross-platform hardening applied via `#[ctor::ctor]` before `main()`. **Hardening steps:** 1. **Disable core dumps** * Prevents process memory dumps * Protects sensitive data (API keys, tokens) 2. **Disable ptrace attach (Linux/macOS)** * Blocks debugger attachment * Prevents runtime inspection 3. **Remove dangerous environment variables** * `LD_PRELOAD` — Prevents shared library injection * `DYLD_*` — Blocks macOS dynamic linker attacks **Usage:** ```rust theme={null} #[ctor::ctor] fn harden() { codex_process_hardening::pre_main_hardening(); } ``` ## Execution Policy Codex tracks command trust decisions via execution policies. Modern execution policy management. **Features:** * Command allow-lists * Session-scoped approvals (`acceptForSession`) * Persistent trust decisions * Amendment proposals from approvals Legacy execution policy support for backwards compatibility. ## Approval Flows Codex implements interactive approval for sensitive operations. ### Command Approvals Agent proposes a shell command. Based on `approval_policy` config, Codex may request approval. **Available decisions:** * `accept` — Run this command once * `acceptForSession` — Trust for current session * `acceptWithExecpolicyAmendment` — Add to allow-list * `applyNetworkPolicyAmendment` — Allow network host * `decline` — Reject command * `cancel` — Cancel entire turn If approved, command runs in sandbox with configured permissions. Output, exit code, and duration returned to agent. ### File Change Approvals Agent proposes file modifications (edits, creates, deletes). User sees unified diff of all changes. User accepts or declines the entire patch. **Available decisions:** * `accept` — Apply changes * `decline` — Reject changes If approved, changes written to disk. ## Network Access Control Codex supports multiple network access modes: ```toml Restricted (Default) theme={null} [sandbox] network_access = "restricted" ``` ```toml Enabled theme={null} [sandbox] network_access = "enabled" ``` ```toml Managed Proxy theme={null} [sandbox] network_access = "managed_proxy" [[sandbox.proxy_endpoints]] host = "api.openai.com" action = "allow" ``` ### Managed Proxy Mode Linux bubblewrap pipeline supports managed proxy routing: 1. **Network namespace isolation** — `--unshare-net` 2. **Internal bridge** — TCP→UDS→TCP routing 3. **Endpoint filtering** — Only configured hosts reachable 4. **seccomp enforcement** — Block new socket creation after bridge setup ## Configuration Sandbox settings are configured in `~/.codex/config.toml`: ```toml Top-level Flag theme={null} # Quick sandbox mode selection sandbox_mode = "workspace-write" ``` ```toml Detailed Configuration theme={null} [sandbox] mode = "workspace-write" writable_roots = ["/Users/me/project"] network_access = "restricted" # Protected paths (always read-only) # .git, .codex are automatically protected ``` ### CLI Override Override sandbox mode per-invocation: ```bash theme={null} # Read-only codex --sandbox read-only # Workspace write codex --sandbox workspace-write # Danger mode codex --sandbox danger-full-access ``` Same setting available via: ```bash theme={null} codex -c sandbox_mode=workspace-write ``` ## External Sandbox Mode For pre-sandboxed environments (containers, VMs): Tell Codex it's already sandboxed externally: ```json theme={null} { "sandboxPolicy": { "type": "externalSandbox", "networkAccess": "enabled" } } ``` **Behavior:** * Codex won't enforce its own sandbox * Agent sees full filesystem access in context * `networkAccess` state passed through environment context **Use cases:** * Docker containers * Kubernetes pods * VMs with dedicated Codex instances ## Testing Sandboxes Codex provides dedicated commands to test sandbox behavior: ```bash macOS theme={null} codex sandbox macos [--full-auto] [--log-denials] [COMMAND]... ``` ```bash Linux theme={null} codex sandbox linux [--full-auto] [COMMAND]... ``` ```bash Windows theme={null} codex sandbox windows [--full-auto] [COMMAND]... ``` **Flags:** * `--full-auto` — Automatically run the command (non-interactive) * `--log-denials` — Log all denied operations (macOS only) **Example usage:** ```bash theme={null} # Test file write restrictions codex sandbox linux --full-auto touch /tmp/test.txt # Test network access codex sandbox macos --log-denials curl https://example.com ``` ## Security Properties Multiple security layers: * Process hardening * Sandbox isolation * Approval flows * Execution policies Minimum required permissions: * Read-only by default * Writable roots explicit * Network opt-in * Protected paths enforced OS security primitives: * macOS Seatbelt * Linux Landlock/Bubblewrap * Windows token restrictions User in the loop: * Interactive approvals * Configurable policies * Session-scoped trust * Persistent allow-lists ## Documentation References For more information, see: * [Official Sandbox Documentation](https://developers.openai.com/codex/security) — Codex sandboxing and approvals * `docs/sandbox.md` — Additional sandbox details * `codex-rs/core/README.md` — Core sandbox expectations * `codex-rs/linux-sandbox/README.md` — Linux implementation details ## Next Steps High-level architecture of Codex CLI Workspace structure and crate organization # TUI Architecture Source: https://openai-codex.mintlify.app/architecture/tui Terminal user interface implementation using Ratatui The Codex TUI is a fullscreen terminal interface built with [Ratatui](https://ratatui.rs/), providing an interactive experience for conversing with AI agents. ## Overview The `codex-tui` crate implements the default interactive mode for Codex CLI, launched when you run `codex` without subcommands. * **Ratatui 0.29.0** — Terminal UI framework * **Crossterm** — Cross-platform terminal manipulation * **Custom patches** — Forked ratatui and crossterm for color query support ## Architecture Components ### App State Management The TUI follows a centralized state model: ```mermaid theme={null} graph TD App[App State] Core[codex-core] Terminal[Terminal/Ratatui] Events[Event Loop] Events -->|User Input| App App -->|Actions| Core Core -->|State Updates| App App -->|Render| Terminal ``` ### Rendering Pipeline Crossterm captures keyboard input, terminal resize, and other events. Events are processed and update the app state, potentially triggering `codex-core` operations. Ratatui widgets are built from the current state. The terminal frame is rendered with the new widget tree. ## Style System The TUI follows strict style conventions defined in `codex-rs/tui/styles.md`: ### Color Palette ```rust Headers theme={null} // Headers use bold "Header".bold() ``` ```rust Primary Text theme={null} // Default foreground color (no style) "Primary text".into() ``` ```rust Secondary Text theme={null} // Use dim for secondary text "Secondary text".dim() ``` ### Semantic Colors Colors are used semantically, not decoratively: **User input**, selection, status indicators ```rust theme={null} "User input".cyan() ``` **Success** messages and additions ```rust theme={null} "+ Added".green() ``` **Errors**, failures, deletions ```rust theme={null} "- Deleted".red() ``` **Codex** agent identity ```rust theme={null} "Codex".magenta() ``` **Avoid:** * Custom colors (no guarantee of contrast) * ANSI black/white as foreground * ANSI blue/yellow (not in style guide) * Hardcoded `.white()` calls ## Styling Conventions The TUI uses Ratatui's `Stylize` trait for concise styling: ### Basic Patterns ```rust Plain Text theme={null} // Simple spans "text".into() ``` ```rust Styled Spans theme={null} // Chain style helpers "text".red().bold() "url".cyan().underlined() ``` ```rust Building Lines theme={null} // Prefer vec![...].into() for obvious types let line: Line = vec![ " └ ".into(), "M".red(), " ".dim(), "tui/src/app.rs".dim() ].into(); ``` ### Style Helper Priority Use `.dim()`, `.bold()`, `.cyan()`, `.italic()`, `.underlined()` instead of manual `Style` construction. Use `"text".into()` for spans and `vec![...].into()` for lines when type is obvious. Use `Line::from(spans)` or `Span::from(text)` when inference is ambiguous. For computed styles, `Span::styled(text, style)` is acceptable. ### Compactness Guidelines From `AGENTS.md` TUI styling rules: * Prefer the form that stays on one line after rustfmt * If only one of `Line::from(vec![...])` or `vec![...].into()` avoids wrapping, choose that * If both wrap, pick the one with fewer wrapped lines * Don't refactor between equivalent forms without readability gain ## Text Wrapping The TUI uses dedicated wrapping utilities: ```rust Plain Strings theme={null} // Use textwrap::wrap for plain text use textwrap::wrap; let lines = wrap(text, width); ``` ```rust Ratatui Lines theme={null} // Use helpers from tui/src/wrapping.rs use codex_tui::wrapping::{word_wrap_lines, word_wrap_line}; let wrapped = word_wrap_line(&line, width); ``` ```rust Indentation theme={null} // Use RtOptions for indent control use codex_tui::wrapping::RtOptions; let options = RtOptions { width: 80, initial_indent: " ", subsequent_indent: " ", ..Default::default() }; ``` For prefixing lines (e.g., bullet points), use `prefix_lines` from `line_utils`: ```rust theme={null} use codex_tui::line_utils::prefix_lines; let prefixed = prefix_lines( lines, "- ", // first line prefix " ", // subsequent lines prefix ); ``` ## Key Components ### Conversation View The main conversation rendering: * **Turn items** — User messages, agent messages, reasoning * **Tool execution** — Command output, file changes, MCP calls * **Approvals** — Interactive prompts for commands/file changes * **Streaming** — Real-time delta updates ### Bottom Pane Input and status area: * **Input field** — Multi-line text input * **Status indicators** — Model, sandbox mode, approval policy * **Shortcuts** — Quick action hints See `codex-rs/tui/src/bottom_pane/AGENTS.md` for implementation details. ### Diff Visualization Syntax-highlighted diffs for file changes: * **syntect** integration for syntax highlighting * **similar** crate for diff generation * Inline diff rendering with line numbers * Collapse/expand for large changes ## Testing Strategy The TUI uses snapshot testing via `insta`: ### Snapshot Tests **Requirement**: Any UI change must include corresponding snapshot coverage. ```bash theme={null} cargo test -p codex-tui ``` ```bash theme={null} cargo insta pending-snapshots -p codex-tui ``` Review `.snap.new` files directly or: ```bash theme={null} cargo insta show -p codex-tui path/to/file.snap.new ``` Only if all changes are intentional: ```bash theme={null} cargo insta accept -p codex-tui ``` ### Why Snapshot Tests? * **Visual regression detection** — Catch unintended UI changes * **Review-friendly** — Diffs show exactly what changed visually * **Fast feedback** — No need for manual UI testing * **Future-proof** — Changes are explicit and reviewable ## Development Workflow From `AGENTS.md` TUI development guidelines: Implement your TUI feature or fix. ```bash theme={null} cargo test -p codex-tui ``` ```bash theme={null} just fmt ``` No approval needed — always run after changes. For large changes: ```bash theme={null} just fix -p codex-tui ``` Do not re-run tests after `fix` or `fmt` unless you made code changes. ## Performance Considerations ### Efficient Rendering * **Frame diffing** — Ratatui only updates changed cells * **Lazy evaluation** — Widgets built on demand * **Scroll virtualization** — Only render visible content * **Delta streaming** — Incremental updates from `codex-core` ### Memory Management * **Bounded buffers** — Limit conversation history in memory * **On-demand loading** — Load full history from disk when needed * **String interning** — Reuse common strings (status indicators, etc.) ## Accessibility ### Keyboard Navigation All TUI functionality is keyboard-accessible: * **Arrow keys** — Navigation * **Tab/Shift+Tab** — Focus cycling * **Enter** — Submit/confirm * **Esc** — Cancel/back * **Ctrl+C** — Interrupt/exit ### Screen Reader Support Terminal content is naturally screen-reader friendly: * Plain text rendering * Semantic color usage * Clear status indicators * No mouse-only interactions ## Platform-Specific Behavior ### Windows Terminal (WSL 2) When `WT_SESSION` is set: * Fall back to native Windows toast notifications * OSC 9 sequences not implemented in Windows Terminal * Approval prompts surface even when terminal is backgrounded ### macOS Notifications Supports custom notification scripts via config: ```toml theme={null} [notify] script = "/path/to/notification-script.sh" ``` Example using `terminal-notifier` in docs. ## Customization The TUI respects terminal color schemes: * Uses ANSI colors (adapt to theme) * No hardcoded RGB values * Respects terminal background * Works with light and dark themes Custom colors are avoided to ensure compatibility across terminal themes. ## Next Steps Explore the full workspace structure Platform-specific security isolation # Authentication Source: https://openai-codex.mintlify.app/authentication Sign in with ChatGPT or configure API key authentication for Codex CLI # Authentication Codex CLI supports multiple authentication methods to suit your workflow. You can sign in with your ChatGPT account (recommended) or use an OpenAI API key. ## Authentication methods Codex CLI offers three authentication methods: 1. **ChatGPT login** (recommended): Sign in with your ChatGPT Plus, Pro, Team, Edu, or Enterprise account 2. **Device code flow**: For remote or headless machines 3. **API key**: For users with OpenAI API access We recommend using ChatGPT login to use Codex as part of your ChatGPT plan. [Learn more about what's included](https://help.openai.com/en/articles/11369540-codex-in-chatgpt). ## Sign in with ChatGPT This is the recommended authentication method. It allows you to use Codex with your ChatGPT Plus, Pro, Team, Edu, or Enterprise plan. Start the authentication process: ```bash theme={null} codex login ``` Or if you're running Codex for the first time: ```bash theme={null} codex ``` Then select **Sign in with ChatGPT** from the prompt. Codex will: 1. Start a local login server on `http://localhost` (random port) 2. Automatically open your browser to the authentication page 3. Prompt you to sign in with your ChatGPT credentials You'll see output like: ``` Starting local login server on http://localhost:3000. If your browser did not open, navigate to this URL to authenticate: https://auth.openai.com/authorize?... On a remote or headless machine? Use `codex login --device-auth` instead. ``` After signing in through the browser: 1. Authorize Codex to access your ChatGPT account 2. You'll be redirected back to a success page 3. Return to your terminal You'll see: ``` Successfully logged in ``` You're now authenticated and can start using Codex: ```bash theme={null} codex "explain this codebase" ``` ## Device code authentication Use device code flow when you're on a remote machine, in SSH, or in a headless environment where opening a browser isn't possible. Start the device code authentication flow: ```bash theme={null} codex login --device-auth ``` Codex will display a URL and a code: ``` Visit https://auth.openai.com/activate Enter code: ABCD-EFGH ``` Open this URL on any device with a browser (your phone, laptop, etc.). On the browser: 1. Navigate to the URL 2. Enter the displayed code 3. Sign in with your ChatGPT credentials 4. Authorize the application Return to your terminal. Once you complete authentication in the browser, you'll see: ``` Successfully logged in ``` You can now use Codex on the remote machine. ## API key authentication If you have an OpenAI API key, you can authenticate using the API key method. This requires [additional setup](https://platform.openai.com/api-keys) but gives you direct API access. Using an API key with Codex will incur costs based on your API usage. ChatGPT login is included in your ChatGPT plan at no additional cost. ### Using the login command Codex accepts API keys via stdin for security: ```bash theme={null} printenv OPENAI_API_KEY | codex login --with-api-key ``` Or: ```bash theme={null} echo "sk-proj-..." | codex login --with-api-key ``` For security reasons, Codex does not accept API keys as command-line arguments. Always pipe the key via stdin. After successful authentication, you'll see: ``` Reading API key from stdin... Successfully logged in ``` ### Using environment variables Alternatively, you can set your API key as an environment variable: Set the `OPENAI_API_KEY` environment variable: ```bash theme={null} export OPENAI_API_KEY="sk-proj-..." ``` This sets the key only for your current terminal session. To make it permanent, add the export line to your shell configuration file (e.g., `~/.zshrc`, `~/.bashrc`). Run Codex normally. It will automatically use the environment variable: ```bash theme={null} codex "explain this code" ``` ### Using a .env file For project-specific API keys, create a `.env` file in your project root: Create a `.env` file in your project directory: ```bash .env theme={null} OPENAI_API_KEY=sk-proj-... ``` Codex will automatically load the API key from the `.env` file: ```bash theme={null} codex "refactor this function" ``` The CLI automatically loads environment variables from `.env` using `dotenv/config`. **Security best practice:** Never commit your `.env` file to version control. Add it to `.gitignore`: ```bash .gitignore theme={null} .env ``` ## Using other AI providers Codex supports other AI providers that implement the OpenAI Chat Completions API. Use the `--provider` flag or configure it in your config file. ### Supported providers * `openai` (default) * `openrouter` * `azure` * `gemini` * `ollama` * `mistral` * `deepseek` * `xai` * `groq` * `arceeai` * Any provider compatible with the OpenAI API ### Configure a custom provider Export the API key for your chosen provider: ```bash theme={null} export AZURE_OPENAI_API_KEY="your-azure-key" ``` Or for a custom provider: ```bash theme={null} export MYPROVIDER_API_KEY="your-key" export MYPROVIDER_BASE_URL="https://api.myprovider.com/v1" ``` Specify the provider when running Codex: ```bash theme={null} codex --provider azure "explain this code" ``` Or configure it permanently in `~/.codex/config.yaml` (see [Configuration](/configuration)). ## Check login status To verify your current authentication status: ```bash theme={null} codex login status ``` This will show: * **ChatGPT login**: `Logged in using ChatGPT` * **API key**: `Logged in using an API key - sk-proj-***ABCDE` (key is partially masked) * **Not logged in**: `Not logged in` ## Logout To remove stored authentication credentials: ```bash theme={null} codex logout ``` You'll see: ``` Successfully logged out ``` Your credentials are removed from `~/.codex/`. You'll need to authenticate again to use Codex. ## Troubleshooting If the browser doesn't open automatically: 1. Copy the URL displayed in the terminal 2. Manually paste it into your browser 3. Complete authentication Or use device code authentication: ```bash theme={null} codex login --device-auth ``` If you're using an API key and Codex isn't authenticating: 1. Verify the key is correct: ```bash theme={null} printenv OPENAI_API_KEY ``` 2. Check that the key hasn't expired on the [OpenAI platform](https://platform.openai.com/api-keys) 3. Ensure you're using the correct provider: ```bash theme={null} codex --provider openai "test" ``` If you see permission errors with stored credentials: 1. Check the permissions on `~/.codex/`: ```bash theme={null} ls -la ~/.codex/ ``` 2. Fix permissions if needed: ```bash theme={null} chmod 700 ~/.codex/ chmod 600 ~/.codex/auth.json ``` If ChatGPT login fails on a remote machine: Use device code authentication instead: ```bash theme={null} codex login --device-auth ``` This works on headless systems and in SSH sessions. ## Next steps Run your first commands with Codex Customize Codex with config files Explore all available commands Learn about sandboxing and permissions # codex app-server Source: https://openai-codex.mintlify.app/cli/app-server Start Codex as an app server for IDE integrations ## Syntax ```bash theme={null} codex app-server [OPTIONS] ``` ## Description The `app-server` command starts Codex as a JSON-RPC server for IDE integrations. This is primarily used by the VS Code extension and other editor plugins. Most users don't need to run this command directly. It's automatically started by IDE extensions like the VS Code Codex extension. ## Usage ### Start with stdio Transport (Default) ```bash theme={null} codex app-server ``` Communicates over stdin/stdout using JSON-RPC. ### Start with WebSocket Transport ```bash theme={null} codex app-server --listen ws://127.0.0.1:4500 ``` Starts a WebSocket server for multiple client connections. ## Options Transport endpoint URL. Supported values: * `stdio://` - Standard input/output (default) * `ws://IP:PORT` - WebSocket server Examples: * `stdio://` * `ws://127.0.0.1:4500` * `ws://0.0.0.0:8080` Enable analytics by default. Analytics are disabled for app-server unless explicitly enabled. Users can still opt out in `config.toml`: ```toml theme={null} [analytics] enabled = false ``` ## Examples ### stdio Transport ```bash theme={null} # Start with stdio (used by VS Code extension) codex app-server # With analytics enabled codex app-server --analytics-default-enabled ``` ### WebSocket Transport ```bash theme={null} # Local WebSocket server codex app-server --listen ws://127.0.0.1:4500 # Bind to all interfaces codex app-server --listen ws://0.0.0.0:8080 # Custom port codex app-server --listen ws://127.0.0.1:9999 ``` ### IDE Integration VS Code extension typically starts the app-server automatically: ```json theme={null} // settings.json { "codex.serverCommand": "codex", "codex.serverArgs": ["app-server", "--listen", "ws://127.0.0.1:4500"] } ``` ## Transport Types ### stdio (Default) **When to use:** * Single client connections * VS Code and editor extensions * Process-based communication **Characteristics:** * One client per server instance * Communicates via stdin/stdout * Terminates when client disconnects ### WebSocket **When to use:** * Multiple concurrent clients * Remote connections * Web-based interfaces **Characteristics:** * Multiple clients per server * Network-based communication * Persists after client disconnects ## Protocol The app-server uses JSON-RPC 2.0 over the specified transport. It implements the Codex App Server Protocol v2. ### Example Request ```json theme={null} { "jsonrpc": "2.0", "id": 1, "method": "thread/start", "params": { "cwd": "/path/to/project" } } ``` ### Example Response ```json theme={null} { "jsonrpc": "2.0", "id": 1, "result": { "threadId": "550e8400-e29b-41d4-a716-446655440000" } } ``` ## Subcommands The `app-server` command has experimental subcommands for protocol development: ### generate-ts Generate TypeScript bindings for the app server protocol: ```bash theme={null} codex app-server generate-ts --out ./generated codex app-server generate-ts --out ./generated --prettier ./node_modules/.bin/prettier codex app-server generate-ts --out ./generated --experimental ``` Output directory for generated TypeScript files. Path to Prettier executable for formatting generated files. Include experimental API methods and fields in generated types. ### generate-json-schema Generate JSON Schema for the app server protocol: ```bash theme={null} codex app-server generate-json-schema --out ./schemas codex app-server generate-json-schema --out ./schemas --experimental ``` Output directory for schema bundle. Include experimental API surface in generated schema. ## Configuration The app-server respects all standard Codex configuration in `~/.codex/config.toml`: ```toml theme={null} # Model settings model = "gpt-4.1" # Permissions [permissions] approval_policy = "on-request" sandbox_policy = "workspace-write" # Analytics (opt-out) [analytics] enabled = false ``` ## Graceful Shutdown ### stdio Mode The server shuts down when stdin closes (client disconnects). ### WebSocket Mode The server handles graceful shutdown on Ctrl+C: 1. Stops accepting new connections 2. Waits for running assistant turns to complete 3. Disconnects all clients 4. Exits Press Ctrl+C twice to force immediate shutdown. ## Logging App-server logs to stderr. Control log level with `RUST_LOG`: ```bash theme={null} # Error-level logs only (default) RUST_LOG=error codex app-server # Info-level logs RUST_LOG=info codex app-server # Debug-level logs RUST_LOG=debug codex app-server # JSON-formatted logs LOG_FORMAT=json RUST_LOG=info codex app-server ``` ## Troubleshooting ### Port Already in Use If WebSocket port is in use: ```bash theme={null} # Check what's using the port lsof -i :4500 # Use a different port codex app-server --listen ws://127.0.0.1:4501 ``` ### Connection Issues For WebSocket connection problems: 1. Verify server is running: ```bash theme={null} lsof -i :4500 ``` 2. Test connection: ```bash theme={null} curl -i -N -H "Connection: Upgrade" \ -H "Upgrade: websocket" \ -H "Sec-WebSocket-Version: 13" \ -H "Sec-WebSocket-Key: test" \ http://127.0.0.1:4500 ``` 3. Check firewall settings ### stdio Issues For stdio communication problems: 1. Ensure client is sending JSON-RPC messages 2. Check stderr for error logs 3. Verify stdin/stdout aren't being buffered ## Related Resources * [VS Code Extension](https://marketplace.visualstudio.com/items?itemName=OpenAI.codex) * [App Server Protocol Documentation](https://developers.openai.com/codex/app-server-protocol) * [Building Editor Integrations](https://developers.openai.com/codex/ide-integrations) # codex apply Source: https://openai-codex.mintlify.app/cli/apply Apply the latest diff produced by Codex agent to your local working tree The `apply` command takes the most recent diff generated by the Codex agent and applies it to your local working tree using `git apply`. ## Usage ```bash theme={null} codex apply codex a # Short alias ``` ## Description When Codex generates code changes during an interactive session, it produces a diff that can be applied to your files. The `apply` command: 1. Finds the latest diff from your most recent Codex session 2. Applies it to your local working tree using `git apply` 3. Reports any conflicts or issues This is useful when you want to: * Apply changes after reviewing them in the TUI * Quickly accept Codex's proposed changes * Integrate Codex changes into your current work ## Examples ### Basic Usage Apply the latest diff from your most recent session: ```bash theme={null} codex apply ``` Using the short alias: ```bash theme={null} codex a ``` ## Exit Codes * `0` - Diff applied successfully * `1` - Error applying diff (conflicts, file not found, etc.) ## Related Commands Run interactive Codex session Run non-interactive execution # codex Source: https://openai-codex.mintlify.app/cli/codex Run Codex interactively with optional initial prompt ## Syntax ```bash theme={null} codex [OPTIONS] [PROMPT] ``` ## Description The `codex` command launches the interactive Codex TUI (Terminal User Interface). If you provide a prompt as an argument, Codex starts with that prompt pre-filled. Without arguments, you'll see an empty prompt where you can type your request. ## Usage ### Interactive Mode Start Codex with an empty prompt: ```bash theme={null} codex ``` ### With Initial Prompt Start Codex with a specific task: ```bash theme={null} codex "refactor the Dashboard component to use React hooks" ``` ### With Images Attach images to your prompt: ```bash theme={null} codex -i screenshot.png "implement this design" codex -i mockup1.png,mockup2.png "create a landing page matching these designs" ``` ## Options Initial prompt to send to Codex. If not provided, starts with empty prompt. ### Model & Provider AI model to use (e.g., `gpt-4.1`, `o4-mini`). Defaults to configured model. Use open-source/local model provider instead of OpenAI. Specify OSS provider: `ollama`, `lmstudio`. Only valid with `--oss`. ### Approval & Sandbox Run in full-auto mode with workspace-write sandbox. No approvals required for file writes or shell commands. Sandbox mode: `workspace-write`, `workspace-read-network-write`, `read-only`, `danger-full-access`. Approval policy: `never`, `on-request`, `for-risky-ops`. Skip all approval checks and sandbox restrictions. Use with extreme caution. ### Input Comma-separated list of image paths to attach. Supports PNG, JPEG, GIF, WebP. Additional directories to make writable in sandbox (repeatable). Enable web search for this session. ### Session Management Working directory for this session. Don't save this session to history. Skip the check for being inside a Git repository. ### Configuration Use a specific config profile. Override config.toml setting (repeatable). Format: `key=value` or `section.key=value`. Examples: * `-c model=gpt-4.1` * `-c permissions.approval_policy=never` Enable a feature flag (repeatable). Equivalent to `-c features.=true`. Disable a feature flag (repeatable). Equivalent to `-c features.=false`. ## Examples ### Basic Usage ```bash theme={null} # Start interactive session codex # Start with a prompt codex "explain this codebase" # Use a specific model codex -m gpt-4.1 "implement OAuth authentication" ``` ### Full Auto Mode ```bash theme={null} # Let Codex run autonomously with file write permissions codex --full-auto "build a REST API with Express" # With custom sandbox configuration codex --sandbox workspace-write "create integration tests" ``` ### With Images ```bash theme={null} # Implement a design from a mockup codex -i design-mockup.png "build this UI component" # Multiple images codex -i dashboard.png,sidebar.png "recreate this interface" ``` ### Local/OSS Models ```bash theme={null} # Use Ollama codex --oss --local-provider ollama "write unit tests" # Use LM Studio codex --oss --local-provider lmstudio -m codellama "refactor this module" ``` ### Configuration Overrides ```bash theme={null} # Temporarily change settings codex -c sandbox_mode=workspace_write "scaffold a new project" # Multiple overrides codex -c model=o4 -c web_search=live "research best practices for API design" # Use a profile codex -p production "deploy the latest changes" ``` ### Special Directories ```bash theme={null} # Run in a different directory codex -C ~/projects/api "add health check endpoint" # Add extra writable directories codex --add-dir /tmp/cache "generate and cache API responses" ``` ## Terminal Requirements Codex's interactive TUI requires a terminal that supports: * ANSI escape codes * UTF-8 encoding * Terminal dimensions (rows/columns) If `TERM=dumb`, Codex will warn you and ask for confirmation before starting. ## Related Commands * [`codex exec`](/cli/exec) - Non-interactive execution for automation * [`codex resume`](/cli/resume) - Continue a previous session * [`codex fork`](/cli/fork) - Fork a previous session # codex completion Source: https://openai-codex.mintlify.app/cli/completion Generate shell completion scripts for Codex CLI The `completion` command generates shell completion scripts that enable tab-completion for Codex commands, subcommands, and flags. ## Usage ```bash theme={null} codex completion [SHELL] ``` ## Supported Shells * `bash` (default) * `zsh` * `fish` * `powershell` * `elvish` ## Installation ### Bash Add to your `~/.bashrc`: ```bash theme={null} eval "$(codex completion bash)" ``` Or generate to a file: ```bash theme={null} codex completion bash > ~/.local/share/bash-completion/completions/codex ``` ### Zsh Add to your `~/.zshrc`: ```bash theme={null} eval "$(codex completion zsh)" ``` Or generate to a file: ```bash theme={null} codex completion zsh > ~/.zsh/completions/_codex ``` Make sure `~/.zsh/completions` is in your `$fpath`: ```bash theme={null} fpath=(~/.zsh/completions $fpath) ``` ### Fish Generate to Fish's completions directory: ```bash theme={null} codex completion fish > ~/.config/fish/completions/codex.fish ``` ### PowerShell Add to your PowerShell profile: ```powershell theme={null} codex completion powershell | Out-String | Invoke-Expression ``` ## Examples ### Generate Bash Completions ```bash theme={null} codex completion bash ``` ### Generate for Specific Shell ```bash theme={null} codex completion zsh codex completion fish ``` ### Save to File ```bash theme={null} codex completion bash > /usr/local/etc/bash_completion.d/codex ``` ## What Gets Completed Shell completion works for: * Commands: `codex ` shows all available commands * Subcommands: `codex mcp ` shows MCP subcommands * Flags: `codex --` shows all global flags * Options: `codex -m ` suggests model names ## Troubleshooting ### Completions Not Working 1. Make sure you've reloaded your shell: ```bash theme={null} exec $SHELL ``` 2. Verify the completion file is in the right location: ```bash theme={null} # Bash echo $BASH_COMPLETION_USER_DIR # Zsh echo $fpath ``` 3. Check that the completion function is loaded: ```bash theme={null} # Bash complete -p codex # Zsh which _codex ``` ## Related Commands Main Codex CLI command # codex debug Source: https://openai-codex.mintlify.app/cli/debug Debugging tools for Codex app server and internal components The `debug` command provides debugging utilities for troubleshooting Codex internals, primarily focused on app server communication. ## Usage ```bash theme={null} codex debug ``` ## Subcommands ### app-server Debug app server communication and protocol issues: ```bash theme={null} codex debug app-server ``` #### send-message-v2 Send a test message to a running app server (V2 protocol): ```bash theme={null} codex debug app-server send-message-v2 [OPTIONS] ``` This is useful for testing app server integrations and debugging JSON-RPC communication. ## Examples ### Test App Server Connection Start an app server in one terminal: ```bash theme={null} codex app-server ``` In another terminal, send a test message: ```bash theme={null} codex debug app-server send-message-v2 ``` ### Debug Protocol Issues When debugging IDE integration issues, you can manually send messages to verify the app server is responding correctly. ## Use Cases ### IDE Integration Development When building IDE extensions that communicate with the Codex app server: 1. Start the app server with debug logging 2. Use debug commands to send test messages 3. Verify responses match expected schema ### Protocol Debugging Test JSON-RPC message handling: ```bash theme={null} # Send various message types to app server codex debug app-server send-message-v2 --method "thread/start" ``` ### CI Testing Verify app server functionality in automated tests: ```bash theme={null} # Start server codex app-server & APP_SERVER_PID=$! # Test communication codex debug app-server send-message-v2 # Cleanup kill $APP_SERVER_PID ``` ## Internal Use These commands are primarily intended for internal development and debugging. Regular users typically don't need these tools. The debug commands access internal APIs that may change between versions. ## Related Commands Start the app server App server API documentation ## Troubleshooting ### App Server Not Responding If the app server doesn't respond to debug commands: 1. Verify the app server is running 2. Check that stdio transport is being used 3. Review app server logs for errors ### Protocol Errors If you see JSON-RPC protocol errors: 1. Ensure you're using the correct protocol version (V2) 2. Verify message format matches the schema 3. Check for missing required fields For more debugging help, see the [Tracing guide](/advanced/tracing). # codex exec Source: https://openai-codex.mintlify.app/cli/exec Run Codex non-interactively for automation and CI/CD ## Syntax ```bash theme={null} codex exec [OPTIONS] [PROMPT] ``` ## Description The `exec` command runs Codex non-interactively, making it ideal for automation, CI/CD pipelines, and scripting. It reads a prompt, executes the task, and exits when complete. Use `codex exec` when you need: * Headless operation (no interactive TUI) * Structured JSON output * Automation in scripts or CI/CD * Output piped to other commands ## Usage ### Basic Execution ```bash theme={null} codex exec "explain this codebase" codex exec "run tests and fix any failures" ``` ### From stdin Read the prompt from stdin: ```bash theme={null} echo "add error handling" | codex exec codex exec < prompt.txt codex exec - # Force reading from stdin ``` ### JSON Output Get structured JSON events: ```bash theme={null} codex exec --json "list all API endpoints" > output.jsonl codex exec --json "analyze code quality" | jq '.msg' ``` ## Options Prompt to send to Codex. Use `-` to read from stdin. ### Output Output events as JSON Lines (JSONL). Each line is a valid JSON object representing an event. Write the final message to a file. Useful for capturing Codex's response. Path to a JSON schema file. Codex will format its final output to match this schema. ### Model & Provider AI model to use (e.g., `gpt-4.1`, `o4-mini`). Use open-source/local model provider. OSS provider: `ollama`, `lmstudio`. ### Approval & Sandbox Run in full-auto mode. No approvals required. Sandbox mode: `workspace-write`, `workspace-read-network-write`, `read-only`, `danger-full-access`. Skip all approvals and sandbox restrictions. Use with extreme caution. ### Input Comma-separated list of image paths. Additional writable directories (repeatable). ### Progress Indicators Control colored output: `auto`, `always`, `never`. Show progress indicator. Auto-detected by default. ### Session Working directory. Don't save session to history. Skip Git repository check. ## Examples ### CI/CD Integration ```bash theme={null} # GitHub Actions - name: Update changelog run: | codex exec --full-auto "update CHANGELOG.md for v2.0.0" # GitLab CI script: - codex exec "run security scan and create report" ``` ### JSON Output for Processing ```bash theme={null} # Get JSON events codex exec --json "analyze code coverage" > coverage-analysis.jsonl # Extract specific fields codex exec --json "list dependencies" | jq -r 'select(.msg.type=="text") | .msg.content' # Save final message codex exec -o response.txt "summarize recent changes" ``` ### Structured Output Schema ```bash theme={null} # Define schema cat > schema.json < quality-report.jsonl ``` ### Reading from stdin ```bash theme={null} # From echo echo "add logging to main.ts" | codex exec # From file codex exec < task-description.txt # From here-doc codex exec < Use the `--enable` flag: ```bash theme={null} codex --enable js_repl codex --enable multi_agent --enable apps ``` Add to your `config.toml`: ```toml theme={null} [features] js_repl = true multi_agent = true apps = true ``` Use the `-c` flag: ```bash theme={null} codex -c features.js_repl=true ``` ## Disabling Features Disable features that are enabled by default: Use the `--disable` flag: ```bash theme={null} codex --disable shell_tool codex --disable unified_exec --disable undo ``` Set to `false` in `config.toml`: ```toml theme={null} [features] shell_tool = false unified_exec = false ``` ## Managing Features The `features` subcommand helps you manage feature flags: ### List All Features ```bash theme={null} codex features list ``` Displays all available features with their stage and current state: ``` apps experimental false js_repl experimental false multi_agent experimental false shell_tool stable true unified_exec stable true undo stable false ``` ### Enable a Feature ```bash theme={null} codex features enable js_repl ``` This updates your `config.toml` file to enable the feature. ### Disable a Feature ```bash theme={null} codex features disable shell_tool ``` This updates your `config.toml` file to disable the feature. ## Experimental Features Experimental features are accessible through the `/experimental` menu in the interactive TUI. Here are the currently available experimental features: ### JavaScript REPL Enable a persistent Node-backed JavaScript REPL for interactive website debugging and other inline JavaScript execution capabilities. **Requirements:** * Node.js >= v22.22.0 **Example:** ```bash theme={null} codex --enable js_repl ``` ### Multi-Agents Allow Codex to spawn multiple agents to parallelize work and improve efficiency. **Example:** ```bash theme={null} codex --enable multi_agent "refactor the entire codebase" ``` The legacy key `collab` is also accepted but deprecated. Use `multi_agent` instead. ### Apps (ChatGPT Connectors) Use connected ChatGPT Apps using "\$" mentions. Install Apps via the `/apps` command. **Example:** ```bash theme={null} codex --enable apps ``` After enabling, restart Codex and use: ``` $AppName help me with X ``` ### Bubblewrap Sandbox (Linux) Use the new Linux sandbox based on bubblewrap for stronger filesystem and network controls. **Platform:** Linux only **Benefits:** * Keeps `.git` and `.codex` read-only inside writable workspaces * Stronger controls than Landlock alone **Example:** ```bash theme={null} codex --enable use_linux_sandbox_bwrap ``` ### Prevent Sleep While Running Keep your computer awake while Codex is running a thread. **Platforms:** macOS, Linux, Windows **Example:** ```bash theme={null} codex --enable prevent_idle_sleep ``` ## Stable Features Stable features are production-ready and enabled by default: Enable the default shell tool for command execution. **Default:** Enabled Disable if you want to prevent all shell command execution: ```bash theme={null} codex --disable shell_tool ``` Use the single unified PTY-backed exec tool for command execution. **Default:** Enabled (except on Windows) Provides better handling of interactive commands and consistent behavior across platforms. Enable shell snapshotting to track environment changes. **Default:** Enabled Helps track shell state changes between commands. Persist rollout metadata and session state to a local SQLite database. **Default:** Enabled Location: `~/.codex/state.db` Enable personality selection in the TUI. **Default:** Enabled Allows customizing the agent's communication style. Enforce UTF-8 output in PowerShell. **Default:** Enabled (Windows only) Ensures consistent text encoding on Windows. Compress request bodies (zstd) when sending streaming requests to codex-backend. **Default:** Enabled Reduces bandwidth usage for large requests. Allow prompting and installing missing MCP dependencies. **Default:** Enabled Automatically handles MCP server dependencies. Create a ghost commit at each turn for easy undo. **Default:** Disabled Enable with: ```bash theme={null} codex --enable undo ``` When enabled, you can undo changes by resetting to the previous ghost commit. ## Under Development Features Under-development features are incomplete and may behave unpredictably. They are not shown in the `/experimental` menu and should only be enabled for testing purposes. These features are actively being developed: * `js_repl_tools_only` - Only expose js\_repl tools directly to the model * `shell_zsh_fork` - Route shell tool execution through the zsh exec bridge * `apply_patch_freeform` - Include the freeform apply\_patch tool * `request_permissions` - Request additional filesystem permissions while sandboxed * `codex_git_commit` - Enable git commit attribution guidance * `runtime_metrics` - Enable runtime metrics snapshots * `memories` - Enable startup memory extraction and file-backed consolidation * `child_agents_md` - Append additional AGENTS.md guidance to user instructions * `apps_mcp_gateway` - Route apps MCP calls through the configured gateway * `skill_env_var_dependency_prompt` - Prompt for missing skill env var dependencies * `default_mode_request_user_input` - Allow request\_user\_input in Default collaboration mode * `voice_transcription` - Enable voice transcription in the TUI composer * `realtime_conversation` - Enable experimental realtime voice conversation mode * `responses_websockets` - Use Responses API WebSocket transport for OpenAI by default * `responses_websockets_v2` - Enable Responses API websocket v2 mode ## Deprecated and Removed Features Some features have been deprecated or removed: ### Deprecated * `web_search_request` - Use top-level `web_search = "live"` in config instead * `web_search_cached` - Use top-level `web_search = "cached"` in config instead ### Removed * `search_tool` - Superseded by web search functionality * `request_rule` - Removed in favor of improved approval system * `experimental_windows_sandbox` - Removed * `elevated_windows_sandbox` - Removed * `remote_models` - Removed * `steer` - Now default behavior (Enter submits immediately) * `collaboration_modes` - Now always enabled ## Feature Lifecycle ```mermaid theme={null} graph LR A[Under Development] --> B[Experimental] B --> C[Stable] C --> D[Deprecated] D --> E[Removed] style A fill:#ff6b6b style B fill:#ffd93d style C fill:#6bcf7f style D fill:#a8a8a8 style E fill:#4a4a4a ``` ### Stage Descriptions Feature is incomplete and not ready for users. Not shown in `/experimental` menu. Default: disabled. Feature is ready for testing. Available in `/experimental` menu. May have rough edges. Default: disabled. Feature is production-ready. Can be toggled on/off as needed. Default: varies per feature. Feature is being phased out. Use alternative approaches. May show warnings. Feature no longer exists. Flag kept for backward compatibility only. ## Configuration Precedence When feature flags are specified in multiple places: 1. `--enable` / `--disable` flags (highest priority) 2. `-c features.name=true` overrides 3. Profile `[features]` section 4. Base config.toml `[features]` section 5. Built-in defaults (lowest priority) ## Suppress Unstable Feature Warning If you enable under-development features, Codex will show a warning. To suppress it: ```toml config.toml theme={null} suppress_unstable_features_warning = true ``` ## Examples ```bash Enable Multiple Experimental Features theme={null} codex --enable js_repl --enable multi_agent --enable apps ``` ```bash Test with Specific Features theme={null} codex --disable shell_tool --enable unified_exec "dry run" ``` ```toml config.toml theme={null} # Enable experimental features in config [features] js_repl = true multi_agent = true apps = true # Disable default features shell_tool = false ``` ```bash Check Feature Status theme={null} # List all features and their current state codex features list # With a specific profile codex --profile experimental features list ``` ## Related Learn about command-line options Configure features in config.toml # codex features Source: https://openai-codex.mintlify.app/cli/features Inspect and manage feature flags in Codex CLI The `features` command allows you to view, enable, and disable experimental and beta features in Codex. ## Usage ```bash theme={null} codex features ``` ## Subcommands ### list List all available feature flags with their current state: ```bash theme={null} codex features list ``` ### enable Enable a specific feature flag: ```bash theme={null} codex features enable ``` ### disable Disable a specific feature flag: ```bash theme={null} codex features disable ``` ## Examples ### View All Features ```bash theme={null} codex features list ``` Output shows: * Feature name * Current state (enabled/disabled) * Stage (stable, beta, experimental, under development) * Description ### Enable Experimental Feature ```bash theme={null} codex features enable js_repl ``` ### Disable Feature ```bash theme={null} codex features disable multi_agent ``` ### Use Feature for Single Command Instead of permanently enabling a feature, use the `--enable` flag: ```bash theme={null} codex --enable js_repl exec "run this code in a REPL" ``` ## Feature Stages Features go through different stages of development: | Stage | Description | Stability | | --------------------- | ------------------------------------ | --------- | | **stable** | Production-ready, enabled by default | High | | **beta** | Generally stable, ready for testing | Medium | | **experimental** | Early development, may change | Low | | **under development** | Not ready for use | Very low | | **deprecated** | Being phased out | N/A | ## Common Features ### Experimental Features * `js_repl` - JavaScript REPL environment * `multi_agent` - Multi-agent collaboration * `apps` - ChatGPT apps integration * `prevent_idle_sleep` - Prevent system sleep during long operations ### Stable Features * `shell_tool` - Enhanced shell command execution * `unified_exec` - Unified execution engine * `shell_snapshot` - Shell command snapshots * `sqlite` - SQLite-backed state storage * `personality` - Agent personality customization ## Configuration Feature flags can also be set in `~/.codex/config.toml`: ```toml theme={null} [features] js_repl = true multi_agent = false ``` ## Priority Order Feature flags are resolved in this order (highest to lowest): 1. Command-line flags (`--enable`, `--disable`) 2. Environment variables (`CODEX_ENABLE_`) 3. Config file (`~/.codex/config.toml`) 4. Default value ## Warnings Experimental features may: * Change behavior without notice * Be removed in future versions * Cause unexpected errors * Affect performance Beta features are more stable but may still undergo breaking changes before becoming stable. ## Related Commands Complete list of all feature flags Configure Codex settings # Feedback Source: https://openai-codex.mintlify.app/cli/feedback Submit feedback and report issues with Codex ## Submitting Feedback We welcome your feedback to help improve Codex! There are several ways to share your thoughts, report bugs, or request features. ## How to Provide Feedback ### GitHub Issues (Recommended) Report issues or request features on our GitHub repository: **Repository:** [https://github.com/openai/codex](https://github.com/openai/codex) ```bash theme={null} # Quick link to create an issue open https://github.com/openai/codex/issues/new ``` ### In-App Feedback While using Codex interactively, press `Ctrl+P` and select "Give Feedback" to: * Report bugs * Request features * Share suggestions * Report security issues ## What to Include When submitting feedback, please include: ### For Bug Reports 1. **Codex Version:** ```bash theme={null} codex --version ``` 2. **Operating System:** * macOS version * Linux distribution and version * Windows version (if using WSL) 3. **Steps to Reproduce:** * Exact commands run * Expected behavior * Actual behavior 4. **Error Messages:** * Full error output * Relevant logs from stderr 5. **Configuration:** * Relevant sections from `~/.codex/config.toml` * Any `-c` overrides used ### For Feature Requests 1. **Use Case:** Describe what you're trying to accomplish 2. **Current Workaround:** How you're handling it now (if applicable) 3. **Proposed Solution:** Your idea for how it should work 4. **Examples:** Show how it would be used ## Example Bug Report ```markdown theme={null} # codex exec fails with "Invalid API key" despite valid key ## Environment - Codex version: 0.5.0 - OS: Ubuntu 22.04 - Shell: bash 5.1.16 ## Steps to Reproduce 1. Run: `echo "$OPENAI_API_KEY" | codex login --with-api-key` 2. Verify: `codex login status` (shows authenticated) 3. Run: `codex exec "explain main.rs"` 4. Error: "Invalid API key" ## Expected Behavior Should execute the prompt using the stored API key ## Actual Behavior Fails with "Invalid API key" error ## Logs ``` \[stderr output here] ```` ## Config ```toml [relevant config.toml sections] ```` ```` ## Example Feature Request ```markdown # Add support for output templates in codex exec ## Use Case I frequently run `codex exec` in CI to generate reports. I want the output to follow a consistent template format (e.g., markdown, HTML, JSON). ## Current Workaround I provide template instructions in every prompt: ```bash codex exec "analyze code quality. Format as markdown with sections: ## Summary ## Issues Found ## Recommendations" ```` This is repetitive and error-prone. ## Proposed Solution Add a `--template` flag: ```bash theme={null} codex exec --template quality-report.md "analyze code quality" ``` Where `quality-report.md` contains: ```markdown theme={null} # Code Quality Report ## Summary {{summary}} ## Issues Found {{issues}} ## Recommendations {{recommendations}} ``` ## Examples ```bash theme={null} codex exec --template report.md "analyze security" codex exec --template api-docs.json "document API endpoints" ``` ``` ## Community Guidelines When providing feedback: - **Be Kind**: Treat others with respect - **Be Constructive**: Focus on solutions, not just problems - **Be Specific**: Provide clear, actionable details - **Search First**: Check if someone already reported the issue ## Security Issues For security vulnerabilities, **do not open a public issue**. Instead: **Email:** security@openai.com Include: - Description of the vulnerability - Steps to reproduce - Potential impact - Your contact information ## Response Times We review all feedback, but response times vary: - **Critical bugs**: Within 1-2 business days - **General bugs**: Within 1 week - **Feature requests**: Reviewed during planning cycles ## Feature Voting On GitHub, you can: - 👍 Upvote issues you care about - 💬 Comment with your use case - 👀 Subscribe to updates Highly-voted issues get prioritized in our roadmap. ## Contributing Interested in contributing code? See our [Contributing Guide](https://github.com/openai/codex/blob/main/CONTRIBUTING.md). Areas where we especially welcome contributions: - Bug fixes - Documentation improvements - Example prompts and workflows - Editor integrations - MCP server implementations ## Stay Updated - **GitHub Releases**: [Watch for new releases](https://github.com/openai/codex/releases) - **Changelog**: Read about new features and fixes - **Discussions**: Join community conversations ## Related Resources - [GitHub Repository](https://github.com/openai/codex) - [Contributing Guide](https://github.com/openai/codex/blob/main/CONTRIBUTING.md) - [Documentation](https://developers.openai.com/codex) - [Community Forum](https://community.openai.com) ``` # codex fork Source: https://openai-codex.mintlify.app/cli/fork Fork a previous interactive session to explore alternative approaches The `fork` command creates a new session based on an existing one, allowing you to explore different approaches while preserving the original conversation. ## Usage ```bash theme={null} codex fork # Shows picker to select session to fork codex fork --last # Fork most recent session ``` ## Description Forking creates a copy of a previous session's history and starts a new interactive session from that point. This is useful when you want to: * Try a different approach to solving a problem * Explore alternative implementations * Experiment without affecting the original session * Branch off from a specific point in a conversation The fork creates a new thread ID with the copied history, leaving the original session unchanged. ## Options Fork the most recent session without showing the picker. ## Examples ### Interactive Picker Show a picker to select which session to fork: ```bash theme={null} codex fork ``` ### Fork Latest Automatically fork your most recent session: ```bash theme={null} codex fork --last ``` ## How It Works 1. Codex loads the selected session's history 2. Creates a new thread ID 3. Copies all conversation history to the new thread 4. Opens the interactive TUI with the forked session 5. You can now continue in a different direction ## Use Cases * **A/B testing approaches**: Try two different solutions to the same problem * **Experimentation**: Test ideas without losing your original work * **Decision points**: Fork when you reach a critical architectural choice * **Learning**: Explore "what if" scenarios with the same context ## Comparison: Fork vs Resume | Feature | Fork | Resume | | ---------------- | ---------------- | ------------- | | Original session | Unchanged | Continued | | New thread ID | Yes | No | | History | Copied | Shared | | Use case | Try alternatives | Continue work | ## Related Commands Resume an existing session Start a new interactive session # Global Options Source: https://openai-codex.mintlify.app/cli/global-options Global command-line options available across all Codex CLI commands ## Overview Global options can be used with any Codex CLI command. They are processed before subcommands and affect the behavior of the entire CLI session. ## Configuration Override Override configuration values using key=value pairs. Can be specified multiple times. **Examples:** ```bash theme={null} codex -c model=gpt-4.1 -c sandbox_mode=workspace-write codex exec -c features.js_repl=true "test the app" ``` Common configuration keys: * `model` - Override the AI model * `sandbox_mode` - Control sandbox restrictions * `approval_policy` - Set approval mode * `features.` - Toggle feature flags ## Profile Selection Select a configuration profile from config.toml **Example:** ```bash theme={null} codex --profile production codex exec --profile experimental "refactor utils" ``` Profiles allow you to maintain different sets of configuration for different use cases (development, production, experimental, etc.). ## Working Directory Change the working directory before executing the command **Example:** ```bash theme={null} codex -C /path/to/project "fix tests" codex --cwd ~/projects/app exec "run linter" ``` ## Model Selection Specify the AI model to use for the session **Example:** ```bash theme={null} codex -m gpt-4.1 codex --model o4-mini "explain this code" ``` Common models: * `o4-mini` - Fast, efficient reasoning model (default) * `gpt-4.1` - Advanced reasoning and coding * `o3` - Advanced reasoning model with extended thinking ## Open Source Models Use open-source models instead of proprietary models **Example:** ```bash theme={null} codex --oss "help me debug" ``` ## Sandbox Control Control the sandbox mode for command execution **Options:** * `workspace-write` - Allow writes within the workspace directory * `full-access` - Allow full filesystem access (use with caution) **Example:** ```bash theme={null} codex --sandbox workspace-write codex exec --sandbox full-access "system diagnostic" ``` ## Approval Policy Set when the agent should ask for approval before executing commands **Options:** * `on-request` - Ask for approval when the agent requests it * `always` - Always ask before executing any command * `never` - Never ask (use with caution) **Example:** ```bash theme={null} codex --ask-for-approval always codex exec --ask-for-approval never "run tests" ``` Enable fully automatic mode (equivalent to `--ask-for-approval never`) **Example:** ```bash theme={null} codex --full-auto "create a todo app" ``` In full-auto mode, commands execute automatically. Use in sandboxed environments or Git-tracked directories. Bypass both approval prompts and sandbox restrictions **DANGEROUS:** This option removes all safety guardrails. Only use in completely isolated test environments. ## Web Search Enable web search capabilities for the agent **Example:** ```bash theme={null} codex --search "find the latest React best practices" ``` ## Image Input Provide image files as input (comma-separated paths) **Example:** ```bash theme={null} codex -i screenshot.png "implement this UI" codex --images "design.png,mockup.png" "create components" ``` ## Directory Context Add directories to the agent's context (can be specified multiple times) **Example:** ```bash theme={null} codex --add-dir src --add-dir tests codex --add-dir lib "explain the architecture" ``` ## Version Information Display the Codex CLI version **Example:** ```bash theme={null} codex --version ``` Display help information **Example:** ```bash theme={null} codex --help codex exec --help ``` ## Combining Options Global options can be combined to create powerful workflows: ```bash High-Performance Dev Mode theme={null} codex -m gpt-4.1 --profile dev -C ~/project --search ``` ```bash Safe Experimentation theme={null} codex --sandbox workspace-write --ask-for-approval always ``` ```bash Full Auto with Features theme={null} codex --full-auto --enable js_repl -c model=o4-mini ``` ```bash Multi-Directory Context theme={null} codex --add-dir src --add-dir tests --add-dir docs \ "document the API" ``` ## Order of Precedence When the same option is specified in multiple places, Codex uses this priority: 1. Command-line flags (highest priority) 2. `-c` config overrides 3. Environment variables 4. Profile settings (from `--profile`) 5. `config.toml` base configuration 6. Built-in defaults (lowest priority) ## Related Enable experimental features Learn about config.toml # codex login Source: https://openai-codex.mintlify.app/cli/login Authenticate with ChatGPT or provide an API key ## Syntax ```bash theme={null} codex login [OPTIONS] codex login status ``` ## Description The `login` command authenticates Codex with OpenAI. You can sign in with your ChatGPT account (recommended) or provide an API key. We recommend signing in with ChatGPT to use Codex as part of your Plus, Pro, Team, Edu, or Enterprise plan. [Learn more about ChatGPT plans](https://help.openai.com/en/articles/11369540-codex-in-chatgpt). ## Usage ### Sign In with ChatGPT (Recommended) ```bash theme={null} codex login ``` This opens your browser to sign in with your ChatGPT account. ### Sign In with Device Code If you can't open a browser, use device code authentication: ```bash theme={null} codex login --device-auth ``` You'll receive a code to enter at a URL. ### Sign In with API Key API keys require [additional setup](https://developers.openai.com/codex/auth#sign-in-with-an-api-key) and are billed separately from ChatGPT plans. Provide an API key from stdin: ```bash theme={null} printenv OPENAI_API_KEY | codex login --with-api-key echo "sk-..." | codex login --with-api-key ``` ### Check Login Status View your current authentication status: ```bash theme={null} codex login status ``` ## Options Use device code authentication instead of browser-based login. Shows a code to enter at a URL. Read an API key from stdin instead of using ChatGPT authentication. ### Advanced OAuth Options Custom OAuth issuer base URL. Advanced use only. This is an experimental flag for custom deployments. Custom OAuth client ID. Advanced use only. This is an experimental flag for custom deployments. ## Examples ### Standard Login Flow ```bash theme={null} # Sign in with ChatGPT (opens browser) codex login # Check your authentication status codex login status ``` ### Device Code Flow ```bash theme={null} # Start device code authentication codex login --device-auth # Output: # Visit https://chatgpt.com/activate # Enter code: ABCD-1234 # Waiting for authentication... ``` ### API Key from Environment ```bash theme={null} # From environment variable printenv OPENAI_API_KEY | codex login --with-api-key # From file cat api-key.txt | codex login --with-api-key # Inline (avoid for security) echo "sk-proj-..." | codex login --with-api-key ``` ### Verify Authentication ```bash theme={null} # Check login status codex login status # Sample output: # Authenticated: Yes # Method: ChatGPT OAuth # Account: user@example.com ``` ### CI/CD Authentication For automation, use API keys: ```yaml theme={null} # GitHub Actions - name: Login to Codex run: | echo "${{ secrets.OPENAI_API_KEY }}" | codex login --with-api-key ``` ```bash theme={null} # GitLab CI script: - echo "$OPENAI_API_KEY" | codex login --with-api-key - codex exec "run tests" ``` ## Authentication Methods ### ChatGPT OAuth (Recommended) **Pros:** * Uses your existing ChatGPT subscription * No additional billing * Includes plan features (Plus, Pro, Team, etc.) **How it works:** 1. Run `codex login` 2. Browser opens to ChatGPT 3. Sign in and authorize 4. Credentials stored securely ### Device Code **When to use:** * Remote servers without browser access * Terminal-only environments * Restricted network access **How it works:** 1. Run `codex login --device-auth` 2. Get a device code 3. Visit URL in any browser 4. Enter code 5. Credentials stored ### API Key **When to use:** * CI/CD pipelines * Automation scripts * Separate billing requirements **How it works:** 1. Get API key from [OpenAI Platform](https://platform.openai.com/api-keys) 2. Pipe to `codex login --with-api-key` 3. Key stored securely API keys are billed separately on the OpenAI Platform. ChatGPT subscriptions don't include API credits. ## Credential Storage Codex stores credentials securely using your system's keychain: * **macOS**: Keychain Access * **Linux**: Secret Service API (gnome-keyring, KWallet) * **Windows**: Windows Credential Manager You can configure storage with the `cli_auth_credentials_store` setting in `config.toml`. ## Troubleshooting ### Browser Doesn't Open Use device code authentication instead: ```bash theme={null} codex login --device-auth ``` ### "Invalid API Key" Error Ensure your API key: * Starts with `sk-proj-` or `sk-` * Has not expired * Has correct permissions * Is from [OpenAI Platform](https://platform.openai.com/api-keys) ### Credentials Not Persisting Check credential storage configuration: ```bash theme={null} codex login status ``` Configure in `~/.codex/config.toml`: ```toml theme={null} [cli_auth] credentials_store = "keychain" # or "file" ``` ## Related Commands * [`codex logout`](/cli/logout) - Remove stored credentials # codex logout Source: https://openai-codex.mintlify.app/cli/logout Remove stored authentication credentials ## Syntax ```bash theme={null} codex logout ``` ## Description The `logout` command removes your stored authentication credentials from Codex. After logging out, you'll need to run `codex login` again to authenticate. ## Usage ```bash theme={null} codex logout ``` This removes: * ChatGPT OAuth tokens * API keys * Any other stored credentials ## Examples ### Standard Logout ```bash theme={null} # Remove credentials codex logout # Output: # Logged out successfully ``` ### Verify Logout ```bash theme={null} # Log out codex logout # Check status codex login status # Output: # Authenticated: No ``` ### Switch Accounts ```bash theme={null} # Log out of current account codex logout # Log in with different account codex login ``` ### CI/CD Cleanup ```yaml theme={null} # GitHub Actions - cleanup after job - name: Cleanup Credentials if: always() run: codex logout ``` ## What Gets Removed The `logout` command removes: 1. **OAuth Tokens**: ChatGPT authentication tokens 2. **API Keys**: Stored OpenAI API keys 3. **Session Data**: Any active session information ## Credential Storage Credentials are stored in your system's secure storage: * **macOS**: Keychain Access * **Linux**: Secret Service API (gnome-keyring, KWallet) * **Windows**: Windows Credential Manager The `logout` command removes entries from these secure stores. ## After Logout To use Codex again, you must re-authenticate: ```bash theme={null} # Log out codex logout # Log back in codex login # Or use API key echo "$OPENAI_API_KEY" | codex login --with-api-key ``` ## Troubleshooting ### Credentials Still Present If credentials persist after logout: 1. Check login status: ```bash theme={null} codex login status ``` 2. Manually remove from keychain (macOS): ```bash theme={null} security delete-generic-password -s "codex-cli" -a "oauth" ``` 3. Or remove config file: ```bash theme={null} rm ~/.codex/auth.json ``` ### Permission Errors If you see permission errors: ```bash theme={null} # macOS - may need to allow terminal access to keychain # Go to: System Preferences > Privacy & Security > Privacy > Keychain ``` ## Related Commands * [`codex login`](/cli/login) - Authenticate with Codex * [`codex login status`](/cli/login#check-login-status) - View authentication status # codex mcp Source: https://openai-codex.mintlify.app/cli/mcp Manage external MCP (Model Context Protocol) servers ## Syntax ```bash theme={null} codex mcp [OPTIONS] ``` ## Description The `mcp` command manages external MCP servers that extend Codex's capabilities. MCP servers can provide additional tools, data sources, and integrations. ## Subcommands * `list` - List configured MCP servers * `get` - Show details for a specific server * `add` - Add a new MCP server * `remove` - Remove an MCP server * `login` - Authenticate with an MCP server (OAuth) * `logout` - Remove MCP server credentials ## codex mcp list List all configured MCP servers. ```bash theme={null} codex mcp list [--json] ``` Output server list as JSON. ### Examples ```bash theme={null} # List servers in table format codex mcp list # Output: # Name Command Args Env Cwd Status Auth # github-mcp node main.js - - enabled authenticated # local-tools /usr/local/bin/mcp - - - enabled unsupported # Get JSON output codex mcp list --json ``` ## codex mcp get Show detailed configuration for a specific MCP server. ```bash theme={null} codex mcp get [--json] ``` Name of the MCP server to display. Output server details as JSON. ### Examples ```bash theme={null} # Show server details codex mcp get github-mcp # Output: # github-mcp # enabled: true # transport: stdio # command: node # args: /path/to/github-mcp/main.js # env: GITHUB_TOKEN=ghp_*** # remove: codex mcp remove github-mcp # Get JSON output codex mcp get github-mcp --json ``` ## codex mcp add Add a new MCP server configuration. ```bash theme={null} # Add stdio server codex mcp add -- [ARGS...] # Add streamable HTTP server codex mcp add --url ``` Name for the MCP server. Must contain only letters, numbers, hyphens, and underscores. ### For stdio servers: Command to launch the MCP server. Environment variables in KEY=VALUE format (repeatable). ### For HTTP servers: URL for a streamable HTTP MCP server. Environment variable name containing a bearer token for authentication. ### Examples ```bash theme={null} # Add stdio server with Node.js codex mcp add github-mcp -- node /path/to/server.js # Add with environment variables codex mcp add slack-mcp \ --env SLACK_TOKEN=xoxb-... \ --env SLACK_WORKSPACE=myteam \ -- node slack-server.js # Add Python-based MCP server codex mcp add python-tools -- python3 -m mcp_server # Add streamable HTTP server codex mcp add remote-mcp --url https://mcp.example.com # Add HTTP server with bearer token codex mcp add api-mcp \ --url https://api.example.com/mcp \ --bearer-token-env-var API_TOKEN ``` ## codex mcp remove Remove an MCP server configuration. ```bash theme={null} codex mcp remove ``` Name of the MCP server to remove. ### Examples ```bash theme={null} # Remove a server codex mcp remove github-mcp # Output: # Removed global MCP server 'github-mcp'. # Attempt to remove non-existent server codex mcp remove unknown # Output: # No MCP server named 'unknown' found. ``` ## codex mcp login Authenticate with an MCP server using OAuth. ```bash theme={null} codex mcp login [--scopes ] ``` Name of the MCP server to authenticate with. Comma-separated list of OAuth scopes to request. OAuth login is only supported for streamable HTTP servers. ### Examples ```bash theme={null} # Login to MCP server codex mcp login github-mcp # Login with specific scopes codex mcp login github-mcp --scopes repo,user # Output: # Starting OAuth flow... # Visit: https://github.com/login/oauth/authorize?client_id=... # Successfully logged in to MCP server 'github-mcp'. ``` ## codex mcp logout Remove OAuth credentials for an MCP server. ```bash theme={null} codex mcp logout ``` Name of the MCP server to deauthenticate. ### Examples ```bash theme={null} # Logout from MCP server codex mcp logout github-mcp # Output: # Removed OAuth credentials for 'github-mcp'. # If no credentials stored codex mcp logout github-mcp # Output: # No OAuth credentials stored for 'github-mcp'. ``` ## Configuration MCP servers are stored in `~/.codex/config.toml`: ```toml theme={null} [mcp_servers.github-mcp] enabled = true transport = { type = "stdio", command = "node", args = ["/path/to/server.js"] } env = { GITHUB_TOKEN = "ghp_***" } [mcp_servers.remote-api] enabled = true transport = { type = "streamable_http", url = "https://api.example.com" } bearer_token_env_var = "API_TOKEN" ``` ## MCP Server Types ### stdio Servers Local servers that communicate via stdin/stdout: ```bash theme={null} codex mcp add my-tool -- python3 -m my_mcp_server ``` **Use cases:** * Local tools and utilities * File system access * Development and testing ### Streamable HTTP Servers Remote servers over HTTP: ```bash theme={null} codex mcp add remote-service --url https://mcp.example.com ``` **Use cases:** * Cloud services * Shared team tools * OAuth-authenticated APIs ## Troubleshooting ### Server Won't Start Check server configuration: ```bash theme={null} codex mcp get ``` Verify command is executable: ```bash theme={null} which ``` ### Environment Variables Not Set Ensure environment variables are available: ```bash theme={null} codex mcp add my-server \ --env TOKEN=$MY_TOKEN \ -- command ``` Or set in `config.toml`: ```toml theme={null} [mcp_servers.my-server] transport = { type = "stdio", command = "command" } env = { TOKEN = "value" } ``` ### OAuth Issues For OAuth authentication problems: 1. Verify server supports OAuth: ```bash theme={null} codex mcp get --json | jq .transport.type ``` 2. Check credentials: ```bash theme={null} codex mcp list --json | jq '.[] | select(.name=="") | .auth_status' ``` 3. Re-authenticate: ```bash theme={null} codex mcp logout codex mcp login ``` ## Related Resources * [Model Context Protocol Specification](https://spec.modelcontextprotocol.io/) * [MCP Server Examples](https://github.com/modelcontextprotocol/servers) * [Building MCP Servers Guide](https://modelcontextprotocol.io/docs/building-servers) # codex mcp-server Source: https://openai-codex.mintlify.app/cli/mcp-server Run Codex as an MCP server for integration with MCP clients The `mcp-server` command starts Codex in MCP (Model Context Protocol) server mode, allowing it to be used as a tool provider for MCP-compatible clients. ## Usage ```bash theme={null} codex mcp-server ``` ## Description When run as an MCP server, Codex exposes its capabilities through the Model Context Protocol over stdio. This allows other applications and AI systems to use Codex as a tool provider. The server runs on stdio by default and communicates using JSON-RPC messages conforming to the MCP specification. ## MCP Tools Exposed When running as an MCP server, Codex exposes various tools that clients can invoke: * **Shell execution**: Run shell commands in a sandboxed environment * **File operations**: Read, write, and modify files * **Code analysis**: Analyze code structure and dependencies * **Git operations**: Interact with version control ## Use Cases ### Claude Desktop Integration Configure Claude Desktop to use Codex as an MCP server: ```json theme={null} { "mcpServers": { "codex": { "command": "codex", "args": ["mcp-server"] } } } ``` ### Custom MCP Clients Build custom clients that leverage Codex capabilities: ```typescript theme={null} import { MCPClient } from '@modelcontextprotocol/sdk'; const client = new MCPClient({ command: 'codex', args: ['mcp-server'] }); await client.connect(); const tools = await client.listTools(); ``` ### CI/CD Integration Use Codex as an MCP server in automated workflows: ```yaml theme={null} - name: Run Codex MCP Server run: | codex mcp-server & SERVER_PID=$! # Your MCP client operations kill $SERVER_PID ``` ## Configuration The MCP server respects your `~/.codex/config.toml` settings, including: * Authentication credentials * Sandbox policies * Model preferences * Approval modes ## Authentication The MCP server uses the same authentication as regular Codex: 1. ChatGPT OAuth credentials (if logged in with `codex login`) 2. API key from environment variables or config 3. Device code flow Make sure you're authenticated before starting the server: ```bash theme={null} codex login codex mcp-server ``` ## Security Considerations The MCP server can execute code and modify files based on client requests. Ensure you trust the MCP client connecting to the server. Sandbox policies still apply when running as an MCP server. Configure appropriate sandbox modes in your config file. ## Debugging Enable verbose logging to debug MCP communication: ```bash theme={null} RUST_LOG=info codex mcp-server ``` For detailed protocol debugging: ```bash theme={null} RUST_LOG=debug codex mcp-server 2> mcp-server.log ``` ## Protocol Compliance Codex's MCP server implementation follows the [Model Context Protocol specification](https://modelcontextprotocol.io/). It supports: * Tool discovery and invocation * Resource access * Prompt management * Sampling requests (when applicable) ## Related Commands Manage external MCP servers Configure MCP servers # CLI Overview Source: https://openai-codex.mintlify.app/cli/overview Complete reference for all Codex CLI commands Codex CLI provides a powerful command-line interface for interacting with the Codex coding agent. You can run Codex interactively, execute tasks non-interactively, manage authentication, configure MCP servers, and more. ## Interactive vs Non-Interactive **Interactive Mode** (default): ```bash theme={null} codex codex "create a todo app" ``` **Non-Interactive Mode** (exec command): ```bash theme={null} codex exec "explain this codebase" codex exec --json "run tests" ``` ## Core Commands Run Codex interactively or with a prompt Run Codex non-interactively for automation Run code reviews on commits or branches ## Session Management Apply latest diff from Codex to working tree Resume a previous interactive session Fork a previous interactive session ## Authentication Authenticate with ChatGPT or API key Remove stored credentials ## Integration & Tooling Manage external MCP servers Run Codex as an MCP server (stdio) Start Codex as an app server for IDEs ## Utilities Generate shell completion scripts Run commands within Codex sandbox Inspect and manage feature flags Submit feedback about Codex Debugging tools for app server ## Global Flags These flags work with most commands: * `-c, --config ` - Override config.toml settings * `-p, --profile ` - Use a specific config profile * `-m, --model ` - Specify the AI model to use * `--oss` - Use open-source/local model providers * `--enable ` - Enable a feature flag * `--disable ` - Disable a feature flag ## Common Usage Patterns ### Quick One-Off Tasks ```bash theme={null} codex exec "add error handling to utils.ts" codex exec --json "list all API endpoints" > endpoints.json ``` ### Code Reviews ```bash theme={null} codex review --uncommitted codex review --base main codex review --commit abc123 ``` ### Using Different Models ```bash theme={null} codex -m gpt-4.1 "complex refactoring task" codex --oss --local-provider ollama "local task" ``` ### Configuration Overrides ```bash theme={null} codex -c sandbox_mode=workspace_write "build a CLI tool" codex -p production exec "deploy to staging" ``` ## Exit Codes Codex CLI uses standard exit codes: * `0` - Success * `1` - Error occurred during execution ## Next Steps Explore individual command documentation for detailed usage, flags, and examples. # codex resume Source: https://openai-codex.mintlify.app/cli/resume Resume a previous interactive Codex session The `resume` command allows you to continue a previous interactive Codex session, preserving the full conversation history and context. ## Usage ```bash theme={null} codex resume # Shows picker to select session codex resume --last # Resume most recent session ``` ## Description Resume lets you pick up where you left off with a previous Codex session. The full conversation history, including: * User messages * Agent responses * Executed commands * File changes * Reasoning and plans All of this context is restored, allowing you to continue the conversation naturally. ## Options Resume the most recent session without showing the picker. ## Examples ### Interactive Picker Show a picker to select from your previous sessions: ```bash theme={null} codex resume ``` This displays a list of recent sessions with: * Session date and time * Initial prompt or topic * Number of turns ### Resume Latest Automatically resume your most recent session: ```bash theme={null} codex resume --last ``` ## How It Works 1. Codex loads the session rollout file from `~/.codex/sessions/` 2. Restores the full conversation history 3. Reopens the interactive TUI 4. You can continue the conversation from where you left off ## Use Cases * **Long-running tasks**: Resume work on multi-step implementations * **Context preservation**: Keep the agent's understanding of your project * **Incremental development**: Build features across multiple sessions * **Review and iterate**: Review previous changes and make adjustments ## Related Commands Fork a session to try alternatives Start a new interactive session # codex review Source: https://openai-codex.mintlify.app/cli/review Run code reviews on commits, branches, or custom instructions ## Syntax ```bash theme={null} codex review [OPTIONS] ``` ## Description The `review` command runs Codex in code review mode. You can review uncommitted changes, compare against a base branch, review a specific commit, or provide custom review instructions. The `review` command runs non-interactively like `codex exec`. Use `codex review --help` for all available options. ## Usage ### Review Uncommitted Changes ```bash theme={null} codex review --uncommitted ``` ### Review Against Base Branch Compare current branch with `main`: ```bash theme={null} codex review --base main codex review --base develop ``` ### Review Specific Commit ```bash theme={null} codex review --commit abc123 codex review --commit HEAD~1 ``` With commit title for context: ```bash theme={null} codex review --commit abc123 --commit-title "Add user authentication" ``` ### Custom Review Instructions Provide specific review criteria: ```bash theme={null} codex review "focus on security vulnerabilities" codex review "check for performance issues" codex review "ensure code follows project style guide" ``` From stdin: ```bash theme={null} echo "review for accessibility issues" | codex review codex review < review-checklist.txt ``` ## Options ### Review Target Review uncommitted changes in the working directory. Review changes compared to a base branch (e.g., `main`, `develop`). Review a specific commit by SHA or reference (e.g., `abc123`, `HEAD~1`). Provide a commit title for context. Only valid with `--commit`. Custom review instructions. Use `-` to read from stdin. ### Output Save the review report to a file. Output review events as JSON Lines. ### Model & Execution AI model to use for the review. Control colored output: `auto`, `always`, `never`. ## Examples ### Pre-Commit Review ```bash theme={null} # Review before committing codex review --uncommitted # Save review to file codex review --uncommitted -o pre-commit-review.md ``` ### Pull Request Review ```bash theme={null} # Review changes in current branch vs main codex review --base main # Review with JSON output for CI codex review --base main --json > pr-review.jsonl ``` ### Commit Review ```bash theme={null} # Review the last commit codex review --commit HEAD # Review a specific commit with context codex review --commit abc123 --commit-title "Fix authentication bug" # Review a range of commits for commit in $(git log --format=%H -n 5); do codex review --commit $commit -o "review-$commit.md" done ``` ### Focused Reviews ```bash theme={null} # Security review codex review --uncommitted "focus on security vulnerabilities and input validation" # Performance review codex review --base main "identify performance bottlenecks and optimization opportunities" # Code quality review codex review < review.jsonl codex review --base ${{ github.base_ref }} -o review-report.md - name: Upload Review uses: actions/upload-artifact@v3 with: name: code-review path: review-report.md ``` ### Pre-Commit Hook ```bash theme={null} #!/bin/bash # .git/hooks/pre-commit echo "Running Codex review on uncommitted changes..." codex review --uncommitted -o /tmp/codex-review.txt if [ $? -ne 0 ]; then echo "Review failed. See /tmp/codex-review.txt for details." exit 1 fi echo "Review complete. See /tmp/codex-review.txt" ``` ### Different Models ```bash theme={null} # Use GPT-4.1 for thorough reviews codex review --base main -m gpt-4.1 # Quick review with o4-mini codex review --uncommitted -m o4-mini ``` ## Review Output By default, Codex outputs the review to stderr. Use `-o` to save to a file: ```bash theme={null} codex review --uncommitted -o review.md ``` With `--json`, events are emitted as JSON Lines: ```bash theme={null} codex review --base main --json | jq -r 'select(.msg.type=="text") | .msg.content' ``` ## Exit Codes * `0` - Review completed successfully * `1` - Error occurred during review The exit code indicates whether the review *ran* successfully, not whether the code *passed* review. Check the review content for findings. ## Related Commands * [`codex exec`](/cli/exec) - Non-interactive execution * [`codex`](/cli/codex) - Interactive mode # codex sandbox Source: https://openai-codex.mintlify.app/cli/sandbox Run commands within the Codex-provided sandbox environment The `sandbox` command allows you to manually execute commands within the same sandbox environment that Codex uses for command execution. ## Usage ```bash theme={null} codex sandbox [OPTIONS] -- ``` ## Description This command is primarily used for testing and debugging sandbox behavior. It runs the specified command with the same security restrictions that Codex applies when executing commands on your behalf. The sandbox environment varies by platform: * **Linux**: Landlock LSM + seccomp filters (or Bubblewrap if enabled) * **macOS**: Seatbelt sandbox profiles * **Windows**: Restricted token with limited privileges ## Options Sandbox mode to use. Options: `read-only`, `workspace-write`, `danger-full-access` Default: `read-only` Working directory for the command. Default: current directory ## Examples ### Run Command in Read-Only Sandbox ```bash theme={null} codex sandbox -- ls -la ``` ### Test Workspace Write Access ```bash theme={null} codex sandbox --sandbox workspace-write -- touch test.txt ``` ### Run in Specific Directory ```bash theme={null} codex sandbox --cwd /tmp -- pwd ``` ### Test Network Restrictions ```bash theme={null} # This should fail in read-only mode codex sandbox -- curl https://example.com ``` ## Sandbox Modes ### read-only * Read access to workspace files * No write access * No network access * Cannot modify system files ### workspace-write * Read access to workspace files * Write access within workspace directory * No network access * Cannot modify system files outside workspace ### danger-full-access * Full file system access * Network access allowed * Can modify any accessible files * Use with caution ## Use Cases ### Testing Sandbox Policies Verify that your sandbox configuration works as expected: ```bash theme={null} codex sandbox --sandbox read-only -- cat ~/.codex/config.toml ``` ### Debugging Command Failures When a command fails in Codex, test it manually: ```bash theme={null} codex sandbox -- npm install ``` ### Validating Execpolicy Rules Test whether a command would be allowed: ```bash theme={null} codex execpolicy check "git push origin main" codex sandbox -- git push origin main ``` ## Exit Codes The command returns the exit code of the executed command. ## Security Notes The `danger-full-access` sandbox mode disables most security restrictions. Only use it when you fully trust the command being executed. Sandbox behavior may vary between platforms. Always test critical workflows on your target platform. ## Related Commands Learn about Codex sandboxing Configure execution policies # Approvals Source: https://openai-codex.mintlify.app/concepts/approvals Control when Codex requires human oversight for sensitive operations The approval system gives you fine-grained control over when Codex can execute commands, modify files, or perform other sensitive operations without human oversight. ## Approval policies Codex supports four approval policies that determine when to prompt for permission: **On-request** (recommended default): * Prompts when the agent needs to escape the sandbox * Auto-approves operations that stay within sandbox boundaries * Balances safety and productivity ```bash theme={null} codex --ask-for-approval on-request "install dependencies" ``` Use for: General development work **Unless-trusted**: * Always prompts for approval * Skips prompts only for commands covered by execpolicy rules * Maximum oversight ```bash theme={null} codex --ask-for-approval unless-trusted "make changes" ``` Use for: Sensitive codebases, production systems **Never**: * Never prompts for approval * Auto-approves all operations (within sandbox limits) * Fastest, least safe ```bash theme={null} codex --ask-for-approval never "run tests" ``` Use for: Sandboxed environments, trusted automation **On-failure**: * Runs commands in sandbox first * Only prompts if sandbox execution fails * Optimistic execution ```bash theme={null} codex --ask-for-approval on-failure "build project" ``` Use for: Commands likely to succeed in sandbox ## Approval prompts When approval is required, you'll see an interactive prompt with details about the operation: ### Command execution approval ``` ┌─ Command Approval Required ────────────────────────────┐ │ codex wants to run: │ │ npm install express cors dotenv │ │ │ │ Working directory: /Users/me/project │ │ Reason: Package installation requires network access │ │ │ │ Suggested rule: ["npm", "install"] │ │ │ │ [a] Accept once │ │ [s] Accept for session │ │ [p] Accept and add to policy │ │ [d] Decline │ │ [c] Cancel turn │ └────────────────────────────────────────────────────────┘ ``` ### File change approval ``` ┌─ File Change Approval Required ────────────────────────┐ │ codex wants to modify: │ │ • src/auth.ts (edit) │ │ • src/middleware/rate-limit.ts (create) │ │ • tests/auth.test.ts (edit) │ │ │ │ Reason: Changes to authentication system │ │ │ │ [a] Accept │ │ [d] Decline │ └────────────────────────────────────────────────────────┘ ``` ## Approval decisions When prompted, you can choose from several approval levels: Approve this specific operation only. The next similar operation will require approval again. Approve this operation and automatically approve identical operations for the rest of this session. Resets when you restart Codex. Approve this operation and add an execpolicy rule so similar commands never require approval again (persists across sessions). Reject this operation. The agent will receive an error and may try an alternative approach. Abort the entire current operation. The agent stops processing your request. ## Execpolicy rules Execpolicy is Codex's policy engine for defining which commands are trusted. Rules are written in Starlark syntax and stored in `.codex/execpolicy/` files. ### Rule structure ```starlark theme={null} # Allow npm install without approval prefix_rule( pattern = ["npm", "install"], decision = "allow", justification = "Package installation is routine and safe in sandbox" ) # Always prompt for git push prefix_rule( pattern = ["git", "push"], decision = "prompt", justification = "Pushing code requires review" ) # Forbid rm -rf prefix_rule( pattern = ["rm", "-rf"], decision = "forbidden", justification = "Use git clean or individual file removal instead" ) ``` ### Decision levels * **`allow`** - Auto-approve matching commands (no prompt) * **`prompt`** - Always prompt for approval * **`forbidden`** - Never allow (show justification to agent) ### Pattern matching Patterns match command prefixes in order: ```starlark theme={null} # Matches: cargo test # Matches: cargo test --all # Doesn't match: cargo build prefix_rule( pattern = ["cargo", "test"] ) # Alternatives using lists prefix_rule( pattern = ["git", ["pull", "fetch"]] ) # Matches: git pull # Matches: git fetch # Doesn't match: git push ``` ### Host executables Constrain which absolute paths can match basename rules: ```starlark theme={null} host_executable( name = "git", paths = [ "/usr/bin/git", "/opt/homebrew/bin/git" ] ) ``` With this definition: * `/usr/bin/git status` can match `["git", "status"]` rules * `/usr/local/bin/git status` cannot (not in allowed paths) ### Testing rules Add inline tests to validate your rules: ```starlark theme={null} prefix_rule( pattern = ["npm", "run", ["dev", "start"]], decision = "allow", # These should match match = [ ["npm", "run", "dev"], "npm run start" ], # These should not match not_match = [ ["npm", "run", "build"], "npm install" ] ) ``` ### Checking rules Test a command against your policies: ```bash theme={null} codex execpolicy check \ --rules ~/.codex/execpolicy/default.rules \ --pretty \ npm install express ``` Output: ```json theme={null} { "matchedRules": [ { "prefixRuleMatch": { "matchedPrefix": ["npm", "install"], "decision": "allow", "justification": "Package installation is routine and safe in sandbox" } } ], "decision": "allow" } ``` ## Configuration Configure approval behavior in `~/.codex/config.toml`: ```toml theme={null} # Global approval policy approval_policy = "on-request" # never | on-request | unless-trusted | on-failure # Execpolicy files to load [execpolicy] user_rules = [ "~/.codex/execpolicy/default.rules", "~/.codex/execpolicy/project-specific.rules" ] ``` ### Per-project configuration Create project-specific rules in your repository: ```bash theme={null} # Project root .codex/ execpolicy/ rules.star # Project-specific rules ``` Codex automatically loads rules from `.codex/execpolicy/` in your working directory. ## Convenience flags Codex provides shortcuts for common approval configurations: ### Full-auto mode Combines `--ask-for-approval on-request` with `--sandbox workspace-write`: ```bash theme={null} codex --full-auto "set up development environment" ``` This is ideal for: * Sandboxed CI/CD environments * Development tasks in trusted directories * Quick prototyping ### YOLO mode (dangerous) Completely bypasses approvals and sandboxing: ```bash theme={null} codex --yolo "install system packages" ``` **NEVER use `--yolo` on untrusted inputs or in production.** This disables all safety checks. Only use in externally sandboxed environments. ## Approval prompts in app-server When using the app-server API, approval requests are JSON-RPC requests that clients must respond to: ### Command approval request ```json theme={null} { "method": "item/commandExecution/requestApproval", "id": 42, "params": { "threadId": "thr_123", "turnId": "turn_456", "itemId": "cmd_789", "command": ["npm", "install", "express"], "cwd": "/Users/me/project", "reason": "Package installation requires network access", "proposedExecpolicyAmendment": { "prefix": ["npm", "install"] } } } ``` ### Client response ```json theme={null} { "id": 42, "result": { "decision": "accept" // accept | acceptForSession | acceptWithExecpolicyAmendment | decline | cancel } } ``` ## Best practices Provides good balance between safety and usability Add rules as you approve common operations Carefully examine suggested rules before accepting Maximum oversight for production or critical systems Use `codex execpolicy check` to validate rules Add clear justifications to help future you understand rules ## Advanced: Network approval Codex can prompt for network access on a per-host basis: ``` ┌─ Network Access Required ──────────────────────────────┐ │ codex wants to connect to: │ │ registry.npmjs.org │ │ │ │ [a] Accept once │ │ [s] Accept for session │ │ [p] Allow this host permanently │ │ [d] Decline │ └────────────────────────────────────────────────────────┘ ``` Network approvals integrate with the same decision levels as command approvals. ## Troubleshooting Check your approval policy: ```bash theme={null} codex -c approval_policy=unless-trusted "test" ``` Or verify config: ```toml theme={null} # ~/.codex/config.toml approval_policy = "unless-trusted" ``` Build execpolicy rules to auto-approve trusted commands: * Accept with `[p]` when prompted to create rules * Manually write rules in `.codex/execpolicy/` * Use `--ask-for-approval on-request` instead of `unless-trusted` Test your rules explicitly: ```bash theme={null} codex execpolicy check --rules ~/.codex/execpolicy/default.rules npm install ``` Check pattern syntax and ensure prefixes match exactly. Session approvals only last for the current thread. Use execpolicy rules for persistent approvals across sessions. ## Next steps Understand how sandboxing complements approvals Use approvals in automation # Interactive mode Source: https://openai-codex.mintlify.app/concepts/interactive-mode Use the Codex TUI for real-time AI assistance Interactive mode provides a rich terminal user interface (TUI) for working with Codex. Launch it by running `codex` with or without an initial prompt. ## Starting interactive mode ```bash Start with prompt theme={null} codex "add unit tests for the auth module" ``` ```bash Start without prompt theme={null} codex ``` ```bash With images theme={null} codex --image screenshot.png "explain this error" ``` ```bash With configuration theme={null} codex --sandbox workspace-write --model gpt-5.2-codex "run the test suite" ``` ## TUI overview The interactive interface consists of several key areas: ### Main conversation view The primary area displays: * **User messages** - Your prompts and inputs * **Agent messages** - Responses from Codex * **Command execution** - Shell commands with live output * **File changes** - Diffs and modifications * **Reasoning** - Internal agent reasoning (when available) Content streams in real-time as the agent works, providing immediate feedback. ### Status bar The bottom status bar shows: * Current model and provider * Sandbox mode and approval policy * Working directory * Network status * Token usage for the current turn ### Input composer The input area at the bottom allows you to: * Type multi-line messages (Shift+Enter for newlines) * Attach images with `--image` or drag-and-drop * Invoke skills with `$skill-name` * Reference apps with `$app-name` ## Keyboard shortcuts ### Navigation | Shortcut | Action | | --------------- | -------------------------------- | | `Ctrl+C` | Cancel current operation or exit | | `Ctrl+D` | Exit Codex (when input is empty) | | `Ctrl+L` | Clear screen | | `↑` / `↓` | Navigate command history | | `PgUp` / `PgDn` | Scroll conversation | | `Home` / `End` | Jump to start/end of input | ### Input control | Shortcut | Action | | ------------- | ----------------------------- | | `Enter` | Send message | | `Shift+Enter` | Insert newline | | `Ctrl+U` | Clear current line | | `Ctrl+W` | Delete word backward | | `Tab` | Autocomplete (when available) | ### Advanced | Shortcut | Action | | -------- | --------------------------------- | | `Ctrl+R` | Resume previous session | | `Ctrl+P` | Open command palette (if enabled) | | `Esc` | Cancel current input | Keyboard shortcuts may vary slightly by terminal emulator and operating system. ## Features ### Live streaming output Commands and agent messages stream in real-time. You'll see: * Text appearing character-by-character * Command output as it's generated * Diffs as files are modified * Progress indicators for long operations ### Approval prompts When the agent needs to perform sensitive operations, you'll see an inline approval prompt: ``` ┌─ Command Approval Required ────────────────────────────────┐ │ codex wants to run: │ │ npm install express │ │ │ │ Working directory: /Users/me/project │ │ │ │ [a] Accept once │ │ [s] Accept for session │ │ [p] Accept and add to policy │ │ [d] Decline │ │ [c] Cancel turn │ └────────────────────────────────────────────────────────────┘ ``` Carefully read what the agent wants to execute Select how broadly to approve the operation Watch the command output stream in real-time ### Command history Use the up/down arrow keys to cycle through: * Previous prompts in this session * Previously executed commands * Resumed conversation inputs History persists across sessions. ### Session management Interactive mode automatically: * Saves your conversation to disk * Maintains context across turns * Allows resuming from where you left off Threads are stored in `~/.codex/sessions/` as JSONL files. ## Display options ### Alternate screen mode By default, Codex uses the alternate screen buffer (like `vim` or `less`). This: * Preserves your terminal scrollback * Cleans up when you exit * Works well in most terminals To disable alternate screen mode: ```bash theme={null} codex --no-alt-screen ``` This is useful for terminal multiplexers like Zellij that strictly follow xterm specs. ### Color output The TUI automatically detects your terminal's color support and adapts: * 24-bit true color (recommended) * 256 colors * 16 colors (fallback) Colors are used to highlight: * Syntax in code blocks * Diff additions (green) and deletions (red) * Status indicators * Error messages ## Working with images Attach images to your prompts for visual context: ```bash Command line theme={null} codex --image screenshot.png "what's wrong with this UI?" ``` ```bash Multiple images theme={null} codex --image fig1.png,fig2.png,chart.jpg "compare these visualizations" ``` Supported formats: * PNG, JPEG, GIF, WebP * Local file paths * Data URLs (via app-server) ## Advanced usage ### Resume sessions Return to a previous conversation: ```bash Resume last session theme={null} codex resume --last ``` ```bash Resume by ID theme={null} codex resume thr_abc123 ``` ```bash Resume with new prompt theme={null} codex resume --last "continue the refactoring" ``` ### Fork conversations Create a new branch from an existing thread: ```bash theme={null} codex fork thr_abc123 ``` This copies the conversation history into a new thread, allowing you to explore alternative approaches. ### Custom working directory Change the agent's working directory: ```bash theme={null} codex --cd /path/to/project ``` All file operations and commands will execute relative to this directory. ### Configuration profiles Use predefined configuration profiles: ```bash theme={null} codex --profile production ``` Profiles are defined in `~/.codex/config.toml`. ## Troubleshooting ### Screen rendering issues If you see garbled output or rendering glitches: 1. Try disabling alternate screen mode: ```bash theme={null} codex --no-alt-screen ``` 2. Check your `TERM` environment variable: ```bash theme={null} echo $TERM # Should be xterm-256color or similar ``` 3. Update your terminal emulator to the latest version ### Input not working If keyboard input seems unresponsive: * Ensure your terminal supports the required features * Check that no other process is capturing input * Try restarting your terminal emulator ### Performance issues If the TUI feels sluggish: * Large conversation histories can slow rendering * Consider starting a new thread for unrelated tasks * Archive old threads to keep your session list manageable The TUI requires a minimum terminal size of 80x24 characters. Smaller terminals may not render correctly. ## Next steps Learn about headless execution Configure approval policies # Non-interactive mode Source: https://openai-codex.mintlify.app/concepts/non-interactive-mode Run Codex headlessly for automation and CI/CD integration Non-interactive mode allows you to run Codex without the terminal UI, making it ideal for automation, scripts, and CI/CD pipelines. Use the `exec` and `review` commands for headless execution. ## The exec command Run a one-off task without the interactive TUI: ```bash Basic usage theme={null} codex exec "run the test suite and fix any failures" ``` ```bash From stdin theme={null} echo "analyze code coverage and suggest improvements" | codex exec ``` ```bash With dash theme={null} codex exec - < ### Output formats By default, `exec` provides human-readable output with progress indicators. For programmatic use, enable JSON output: ```bash theme={null} codex exec --json "run tests" > events.jsonl ``` This streams JSONL (JSON Lines) events that you can parse: ```jsonl theme={null} {"method":"turn/started","params":{"turn":{"id":"turn_123","status":"inProgress"}}} {"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_1"}}} {"method":"item/agentMessage/delta","params":{"itemId":"msg_1","delta":"Running"}} {"method":"item/agentMessage/delta","params":{"itemId":"msg_1","delta":" tests..."}} {"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_1","text":"Running tests..."}}} {"method":"turn/completed","params":{"turn":{"id":"turn_123","status":"completed"}}} ``` ### Exit codes `codex exec` returns meaningful exit codes for automation: | Exit Code | Meaning | | --------- | ---------------------------- | | `0` | Success - task completed | | `1` | General error | | `2` | Authentication failed | | `3` | Configuration error | | `4` | Model/API error | | `130` | Interrupted by user (Ctrl+C) | ### Command options ```bash theme={null} codex exec [OPTIONS] [PROMPT] Options: -m, --model Model to use (e.g., gpt-5.2-codex) -s, --sandbox Sandbox mode: read-only, workspace-write, danger-full-access -C, --cd Working directory -i, --image Attach images (comma-separated) --json Output JSONL events --ephemeral Don't persist session to disk --output-schema JSON Schema for structured output -o, --output-last-message Write final agent message to file --color Color output: auto, always, never --full-auto Auto-approve with workspace-write sandbox --yolo Bypass all approvals (DANGEROUS) ``` ## The review command Request an automated code review from Codex: ```bash Review uncommitted changes theme={null} codex review ``` ```bash Review specific commit theme={null} codex review abc1234 ``` ```bash Review against base branch theme={null} codex review --base main ``` ```bash Custom review instructions theme={null} codex review --instructions "Focus on security and performance" ``` ### Review targets The review command supports multiple targets: Review staged, unstaged, and untracked files: ```bash theme={null} codex review ``` Review a specific commit by SHA: ```bash theme={null} codex review 1234567 ``` Review changes since branching from main: ```bash theme={null} codex review --base main ``` Provide free-form instructions: ```bash theme={null} codex review --instructions "Check for SQL injection vulnerabilities" ``` ### Review output Reviews produce structured feedback: ``` ╭─ Code Review ──────────────────────────────────────────╮ │ Overall: The changes look solid with minor suggestions │ │ │ │ Findings: │ │ │ │ • Consider adding error handling — auth.ts:42-55 │ │ The login function doesn't handle network failures │ │ │ │ • Extract magic number — config.ts:18 │ │ Use a named constant for the timeout value │ │ │ │ • Add input validation — api.ts:91 │ │ Validate user input before database queries │ ╰─────────────────────────────────────────────────────────╯ ``` ## Resume and continue Non-interactive mode supports resuming previous sessions: ```bash Resume last session theme={null} codex exec resume --last "add more test cases" ``` ```bash Resume by ID theme={null} codex exec resume thr_abc123 "now deploy to staging" ``` ```bash Resume with JSON output theme={null} codex exec --json resume --last ``` ## CI/CD integration Codex is designed to integrate seamlessly into automated workflows. ### GitHub Actions ```yaml Automated testing theme={null} name: Codex Auto-fix on: [push] jobs: auto-fix: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Codex run: | curl -fsSL https://codex.openai.com/install.sh | sh echo "$HOME/.codex/bin" >> $GITHUB_PATH - name: Run tests and auto-fix env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} run: | codex exec --full-auto --json "run tests and fix any failures" | tee results.jsonl - name: Check success run: | if [ $? -ne 0 ]; then echo "Codex failed to fix tests" exit 1 fi ``` ```yaml Code review theme={null} name: Codex Review on: [pull_request] jobs: review: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - name: Install Codex run: | curl -fsSL https://codex.openai.com/install.sh | sh echo "$HOME/.codex/bin" >> $GITHUB_PATH - name: Run review env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} run: | codex review --base origin/main -o review.txt - name: Post review uses: actions/github-script@v7 with: script: | const fs = require('fs'); const review = fs.readFileSync('review.txt', 'utf8'); github.rest.issues.createComment({ owner: context.repo.owner, repo: context.repo.repo, issue_number: context.issue.number, body: '## Codex Review\n\n' + review }); ``` ### GitLab CI ```yaml .gitlab-ci.yml theme={null} codex-review: stage: test image: ubuntu:latest before_script: - curl -fsSL https://codex.openai.com/install.sh | sh - export PATH="$HOME/.codex/bin:$PATH" script: - codex review --base origin/main --json > review.jsonl artifacts: paths: - review.jsonl expire_in: 1 week only: - merge_requests ``` ### Jenkins ```groovy Jenkinsfile theme={null} pipeline { agent any environment { OPENAI_API_KEY = credentials('openai-api-key') } stages { stage('Install Codex') { steps { sh 'curl -fsSL https://codex.openai.com/install.sh | sh' } } stage('Run Tests') { steps { sh ''' export PATH="$HOME/.codex/bin:$PATH" codex exec --full-auto --json "run the test suite" > results.jsonl ''' } } stage('Analyze Results') { steps { script { def results = readJSON file: 'results.jsonl' // Process JSONL events } } } } } ``` ## Structured output Constrain the agent's response to a specific JSON schema: ```bash theme={null} codex exec \ --output-schema schema.json \ --json \ "analyze test coverage" ``` **schema.json:** ```json theme={null} { "type": "object", "properties": { "coverage_percentage": { "type": "number" }, "uncovered_files": { "type": "array", "items": { "type": "string" } }, "recommendations": { "type": "array", "items": { "type": "string" } } }, "required": ["coverage_percentage", "uncovered_files", "recommendations"], "additionalProperties": false } ``` The final agent message will conform to this schema. ## Ephemeral sessions Run without persisting to disk: ```bash theme={null} codex exec --ephemeral "quick calculation: 2^16" ``` Useful for: * One-off queries * Sensitive data that shouldn't be logged * Reducing disk I/O in high-volume scenarios ## Automation best practices In sandboxed CI runners, use `--full-auto` to auto-approve operations: ```bash theme={null} codex exec --full-auto "install deps and run tests" ``` Always use `--json` in automation to get structured events: ```bash theme={null} codex exec --json "task" | jq -r 'select(.method=="turn/completed")' ``` Handle failures gracefully in scripts: ```bash theme={null} if ! codex exec "run tests"; then echo "Tests failed" exit 1 fi ``` Use `--output-last-message` for the agent's final response: ```bash theme={null} codex exec -o result.txt "summarize changes" cat result.txt ``` Never use `--yolo` (dangerously bypass approvals) in production or on untrusted inputs. This disables all safety checks. ## Parsing JSONL output ### Using jq ```bash theme={null} # Extract all agent messages codex exec --json "task" | jq -r 'select(.method=="item/agentMessage/delta") | .params.delta' # Get final turn status codex exec --json "task" | jq -r 'select(.method=="turn/completed") | .params.turn.status' # Count commands executed codex exec --json "task" | jq -r 'select(.method=="item/started" and .params.item.type=="commandExecution")' | wc -l ``` ### Using Python ```python theme={null} import json import subprocess proc = subprocess.Popen( ["codex", "exec", "--json", "run tests"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) for line in proc.stdout: event = json.loads(line) if event["method"] == "item/commandExecution/outputDelta": print(event["params"]["delta"], end="") elif event["method"] == "turn/completed": print(f"\nStatus: {event['params']['turn']['status']}") ``` ## Next steps Learn about the TUI for development Understand security in automation # Core concepts Source: https://openai-codex.mintlify.app/concepts/overview Understand how Codex CLI structures conversations and executes tasks Codex CLI is built around three core primitives that structure how you interact with the AI agent. Understanding these concepts will help you work more effectively with Codex. ## Architecture Codex uses a conversation-based model where each interaction is structured into distinct units: Conversations between you and the agent Individual exchanges within a conversation Atomic units of input and output ## Threads A **thread** represents a complete conversation between you and the Codex agent. Each thread: * Contains a history of all interactions (turns) * Maintains context across multiple exchanges * Persists to disk as a JSONL rollout file * Has its own configuration (model, working directory, sandbox settings) Threads are identified by a unique ID (e.g., `thr_123`) and can be: * Started fresh with `codex` or `thread/start` * Resumed from disk with `codex resume` or `thread/resume` * Forked into new branches with `thread/fork` * Archived when no longer needed ### Thread lifecycle ```mermaid theme={null} stateDiagram-v2 [*] --> NotLoaded NotLoaded --> Idle: Start/Resume Idle --> Active: Begin turn Active --> Idle: Complete turn Active --> SystemError: Error occurs Idle --> NotLoaded: Unsubscribe SystemError --> NotLoaded: Unload ``` ## Turns A **turn** represents one round of interaction, typically: 1. You provide input (message, image, skill invocation) 2. The agent processes your request 3. The agent responds and executes actions Each turn has a status: * `inProgress` - Currently executing * `completed` - Finished successfully * `interrupted` - Cancelled by user * `failed` - Encountered an error Turns are identified by IDs like `turn_456` and can be interrupted mid-execution using `turn/interrupt`. ## Items Items are the atomic units that make up a turn. They represent both inputs and outputs: ### Input items * **userMessage** - Text or images you provide * **skill** - Skill invocations (e.g., `$skill-creator`) * **mention** - App invocations ### Output items * **agentMessage** - Text responses from the agent * **reasoning** - Internal reasoning steps (for supported models) * **plan** - High-level plan for multi-step tasks * **commandExecution** - Shell commands executed in the sandbox * **fileChange** - File modifications (edits, creates, deletes) * **mcpToolCall** - MCP (Model Context Protocol) tool invocations * **webSearch** - Web search queries and results * **imageView** - Image viewing operations ### Item lifecycle Every item follows a consistent lifecycle: The `item/started` event is emitted with initial metadata Item-specific delta events stream incremental progress (e.g., `item/agentMessage/delta`) The `item/completed` event provides the final, authoritative state ## Execution modes Codex supports two primary execution modes: Full TUI with rich display, history, and navigation Headless execution for automation and CI/CD ### Interactive mode Launched with the `codex` command, interactive mode provides: * Real-time terminal user interface (TUI) * Streaming output as the agent works * Keyboard shortcuts for navigation and control * Visual feedback for approvals and errors Best for: Development, debugging, exploratory tasks ### Non-interactive mode Launched with `codex exec` or `codex review`, non-interactive mode provides: * Programmatic execution without a TUI * JSONL event streaming for parsing * Exit codes for automation * Structured output formats Best for: CI/CD pipelines, scripts, automated workflows ## Security model Codex implements multiple security layers: Platform-specific filesystem and network isolation User control over sensitive operations ### Sandboxing All commands run in a sandbox by default, using platform-specific technologies: * **Linux**: Landlock + seccomp (or Bubblewrap) * **macOS**: Seatbelt (App Sandbox) * **Windows**: Restricted tokens + job objects Sandbox modes: * `read-only` - Only file reads permitted * `workspace-write` - Writes allowed in working directory * `danger-full-access` - No sandbox restrictions ### Approvals The approval system controls when human oversight is required: * **never** - Auto-approve all operations * **on-request** - Approve when sandbox escalation needed * **unless-trusted** - Always approve unless trusted by policy * **on-failure** - Only approve after sandbox failures ## Data persistence Codex stores data in your Codex home directory (typically `~/.codex/`): * **Sessions** (`sessions/`) - Active thread rollouts * **Archived** (`sessions_archived/`) - Archived conversations * **Config** (`config.toml`) - User configuration * **Skills** (`skills/`) - Custom skills and tools * **Cache** (`cache/`) - Temporary data and indexes Thread data is stored as JSONL (JSON Lines) for human readability and easy processing with standard tools. ## Next steps Learn keyboard shortcuts and TUI features Integrate Codex into your automation Understand the security model Configure approval policies # Sandboxing Source: https://openai-codex.mintlify.app/concepts/sandboxing Understand Codex's security model and platform-specific isolation Codex executes all commands in a sandbox by default, isolating filesystem access and network operations to protect your system. The sandbox uses platform-specific technologies to enforce security boundaries. ## Sandbox modes Codex supports three sandbox modes with increasing levels of access: **Read-only mode** permits: * Reading files anywhere on the filesystem * No write operations * Network access (if enabled) Use for: Code analysis, searching, reviewing ```bash theme={null} codex --sandbox read-only "analyze the codebase structure" ``` **Workspace-write mode** (default) permits: * Reading files anywhere * Writing files in the working directory (`cwd`) * Writing to additional directories specified with `--add-dir` * Protected paths like `.git/` remain read-only * Network access (if enabled) Use for: Development, testing, file modifications ```bash theme={null} codex --sandbox workspace-write "add unit tests" ``` **Full-access mode** disables the sandbox: * No filesystem restrictions * No network restrictions * Full system access Only use in trusted environments. The agent can modify any file and execute any command. ```bash theme={null} codex --sandbox danger-full-access "install system packages" ``` ## Platform-specific implementation Codex uses different sandboxing technologies depending on your operating system: ### Linux: Landlock + seccomp On Linux, Codex uses **Landlock** (kernel-level access control) combined with **seccomp** (system call filtering): * **Landlock** enforces filesystem access rules * Available on kernel 5.13+ (full support on 5.19+) * Hierarchical path-based access control * Restricts file read/write at the syscall level * **seccomp** restricts system calls * Blocks network operations when network access is disabled * Prevents privilege escalation * Filters dangerous syscalls **Bubblewrap pipeline** (experimental): Codex also supports **Bubblewrap** for more comprehensive isolation: * Namespace isolation (PID, network, mount) * Read-only root filesystem with selective bind mounts * Protected paths (`.git`, `.codex`) re-bound as read-only * Managed network proxy for restricted network access Enable with: ```bash theme={null} codex -c features.use_linux_sandbox_bwrap=true ``` ### macOS: Seatbelt (App Sandbox) On macOS, Codex uses **Seatbelt**, Apple's sandbox profile system: * Enforces filesystem access rules via sandbox profiles * Restricts network access when disabled * Integrates with macOS security frameworks * Uses `sandbox-exec` to apply profiles The Seatbelt profile is dynamically generated based on: * Sandbox mode (`read-only`, `workspace-write`, etc.) * Writable roots (`cwd` and `--add-dir` paths) * Protected paths (`.git`, `.codex`, etc.) * Network access settings ### Windows: Restricted tokens + job objects On Windows, Codex uses **restricted tokens** and **job objects**: * **Restricted tokens** limit privileges * Removes admin rights * Restricts access to sensitive resources * **Job objects** enforce resource limits * Process isolation * Resource quotas * Network policy enforcement Windows sandboxing supports both elevated and unelevated modes. Use `windowsSandbox/setupStart` via the app-server API to configure. ## Protected paths Even in `workspace-write` mode, certain paths are always read-only: * **`.git/`** - Git repository data * **`.codex/`** - Codex configuration and data * **`gitdir:` symlinks** - Git worktree references These protections prevent accidental corruption of critical data. Protected paths are enforced recursively. For example, `.git/hooks/` is also read-only. ## Network access Network access is controlled independently of filesystem sandboxing: ```bash theme={null} # Enable network access codex -c sandbox_policy.network_access=enabled "fetch latest API docs" # Disable network access (default in some modes) codex -c sandbox_policy.network_access=restricted "work offline" ``` ### Network proxy (Linux Bubblewrap) When using Bubblewrap with restricted network: * Network namespace is isolated via `--unshare-net` * A managed proxy routes allowed traffic * TCP connections are bridged through Unix domain sockets * seccomp blocks new socket creation after setup This allows fine-grained network policy enforcement. ## Additional writable directories Extend the writable scope beyond `cwd`: ```bash theme={null} codex --add-dir /tmp/scratch --add-dir ~/documents "process data files" ``` All specified directories: * Must be absolute paths * Are added to the sandbox's writable roots * Still respect protected path rules ## Sandbox escalation When a command needs to escape the sandbox (e.g., to install packages, access `/usr/local`, or make network requests), the agent can request escalation. ### How escalation works The command fails due to sandbox constraints (e.g., permission denied, network unreachable) Codex prompts you to run the command outside the sandbox: ``` Command failed in sandbox. Allow running unrestricted? npm install express [a] Accept once [s] Accept for session [p] Accept and add to policy [d] Decline ``` Choose the appropriate approval level based on trust and scope If approved, the command executes outside the sandbox with full access ### Approval integration Sandbox escalation integrates with the [approval system](/concepts/approvals): * **never** - Auto-approve escalation (no sandbox) * **on-request** - Prompt for escalation approval * **unless-trusted** - Always prompt unless covered by policy * **on-failure** - Only prompt after sandbox failures ## Debugging sandbox issues If commands fail unexpectedly in the sandbox: ### Check sandbox status ```bash theme={null} # View current sandbox mode codex -c sandbox_policy.mode=read-only --help # Test a specific command codex exec "ls -la /etc" ``` ### Enable full access temporarily ```bash theme={null} codex --sandbox danger-full-access "install dependencies" ``` ### Review sandbox logs On Linux with Landlock: ```bash theme={null} # Check kernel support codex debug landlock # View sandbox diagnostics RUST_LOG=debug codex "test command" ``` On macOS with Seatbelt: ```bash theme={null} # Check Seatbelt denials log show --predicate 'eventMessage contains "Sandbox"' --last 1h ``` ### Common issues `/usr/local` is outside the workspace. Either: * Use `--add-dir /usr/local` to make it writable * Use `--sandbox danger-full-access` for full access * Allow the agent to request escalation Network access may be restricted. Enable with: ```bash theme={null} codex -c sandbox_policy.network_access=enabled ``` `.git` is protected by default. Use `danger-full-access` or manually run git commands outside Codex. Landlock requires Linux kernel 5.13+. On older kernels: * Upgrade your kernel, or * Use `danger-full-access` mode (no sandbox) ## Configuration Configure sandboxing in `~/.codex/config.toml`: ```toml theme={null} [sandbox_policy] mode = "workspace-write" # read-only | workspace-write | danger-full-access network_access = "enabled" # enabled | restricted # Additional writable roots writable_roots = [ "/tmp/codex-scratch", "/Users/me/data" ] # Protected paths (added to defaults) protected_paths = [ ".env", "secrets/" ] ``` ## Best practices Provides good balance between safety and functionality Only enable when tasks require internet access Carefully examine commands before approving escalation Reserve `danger-full-access` for trusted environments only ## Next steps Configure when to prompt for permission Use sandboxing in CI/CD # Advanced Configuration Source: https://openai-codex.mintlify.app/configuration/advanced Advanced Codex CLI configuration options for power users This guide covers advanced configuration features including profiles, reasoning effort, SQLite state, and experimental options. ## Configuration Profiles Profiles let you define multiple configuration presets and switch between them: ```toml theme={null} # Active profile profile = "careful" [profiles.careful] model = "gpt-4.1" approval_policy = "untrusted" sandbox_mode = "workspace-write" model_reasoning_effort = "high" [profiles.fast] model = "o4-mini" approval_policy = "on-request" sandbox_mode = "workspace-write" model_reasoning_effort = "low" [profiles.auto] model = "gpt-5.1" approval_policy = "never" sandbox_mode = "workspace-write" model_reasoning_effort = "medium" ``` Switch profiles at runtime: ```bash theme={null} codex --profile fast codex --profile careful ``` CLI flags always override profile settings. Profile settings override global config. ## Reasoning Effort Control how much computational effort reasoning models spend on tasks: ```toml theme={null} # Global default model_reasoning_effort = "medium" # Separate effort for Plan mode plan_mode_reasoning_effort = "high" ``` Default reasoning effort for reasoning models. **Options:** `"none"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"xhigh"` Reasoning effort override for Plan mode specifically. When unset, Plan mode uses its built-in default (currently `"medium"`). When explicitly set (including `"none"`), it overrides the Plan preset. ### Reasoning Effort Guide Fastest responses with no extended reasoning process. Use for simple queries or when speed is critical. Minimal reasoning overhead for straightforward tasks. Light reasoning for tasks with moderate complexity. Balanced reasoning effort suitable for most tasks. Extended reasoning for complex problems requiring careful analysis. Maximum reasoning effort for the most challenging problems. ## Reasoning Summaries Configure how reasoning summaries are presented: ```toml theme={null} model_reasoning_summary = "auto" ``` Controls reasoning summary detail level. **Options:** * `"auto"` - Let the model decide * `"concise"` - Brief summaries * `"detailed"` - Comprehensive summaries * `"none"` - Disable reasoning summaries ## Model Verbosity Control output length for GPT-5 models: ```toml theme={null} model_verbosity = "medium" ``` Controls output detail for GPT-5 models via Responses API. **Options:** `"low"`, `"medium"`, `"high"` ## SQLite State Database Codex stores thread state, memories, and other persistent data in a SQLite database: ```toml theme={null} sqlite_home = "/custom/path/to/sqlite" ``` Directory for SQLite state database. **Default behavior:** * If `CODEX_SQLITE_HOME` env var is set, use that * For workspace-write sandbox, default to temp directory * Otherwise, default to `$CODEX_HOME` The SQLite database contains thread history, memories, and state. Back it up regularly if important. ## Custom Developer Instructions Provide model-specific instructions that appear as developer role messages: ```toml theme={null} developer_instructions = """ You are working in a monorepo with these packages: - apps/web (Next.js) - apps/api (Express) - packages/shared (shared utilities) Always consider cross-package dependencies. """ ``` Or load from a file: ```toml theme={null} model_instructions_file = "~/.codex/instructions.md" ``` Using `model_instructions_file` overrides Codex's built-in instructions and may degrade performance. Use with caution. ## Shell Environment Policy Control which environment variables are inherited when running shell commands: ```toml theme={null} [shell_environment_policy] inherit = "core" exclude = ["AWS_.*", "SECRET_.*"] include_only = [] [shell_environment_policy.set] PATH = "/usr/local/bin:/usr/bin:/bin" LANG = "en_US.UTF-8" ``` Which environment variables to inherit. **Options:** * `"core"` - Only essential variables (HOME, PATH, USER, etc.) * `"all"` - Inherit full parent environment * `"none"` - Start with empty environment Regex patterns for variables to exclude (applied after inherit) If set, only inherit variables matching these patterns Explicitly set environment variables ## Agent Configuration Configure multi-agent and hierarchical agent settings: ```toml theme={null} [agents] max_threads = 10 max_depth = 3 job_max_runtime_seconds = 3600 ``` Maximum concurrent agent threads. When unset, no limit is enforced. Maximum nesting depth for spawned agents. Root sessions start at depth 0. Default maximum runtime in seconds for agent job workers. ### Agent Roles Define custom agent roles with specific configurations: ```toml theme={null} [agents.researcher] config_file = "~/.codex/roles/researcher.toml" description = "Research-focused agent for gathering information" [agents.implementer] config_file = "~/.codex/roles/implementer.toml" description = "Implementation-focused agent for writing code" ``` ## Tool Configuration Enable or disable specific tools: ```toml theme={null} [tools] view_image = true web_search = true ``` Enable the `view_image` tool for attaching local images Enable web search capabilities ### Web Search Mode ```toml theme={null} web_search = "cached" ``` Controls web search tool behavior. **Options:** * `"disabled"` - No web search * `"cached"` - Use cached search results * `"live"` - Perform live web searches ## Network Permissions Configure network proxy and access controls: ```toml theme={null} [permissions.network] enabled = true mode = "limited" allowed_domains = ["api.example.com", "cdn.example.com"] denied_domains = ["malicious.com"] ``` Enable network proxy functionality Network access mode. **Options:** * `"limited"` - Restricted to allowed domains * `"full"` - Full network access List of allowed domain patterns List of explicitly denied domains ## Memories Configuration Configure Codex's memory system: ```toml theme={null} [memories] use_memories = true generate_memories = true max_rollout_age_days = 30 min_rollout_idle_hours = 12 ``` Inject memory usage instructions into developer prompts Enable automatic memory generation from threads Maximum age of threads used for memory generation Minimum idle time before creating memories from a thread (hours) ## Ghost Snapshots (Undo) Configure ghost snapshots for the undo feature: ```toml theme={null} [ghost_snapshot] ignore_large_untracked_files = 10485760 # 10MB ignore_large_untracked_dirs = 1000 # files disable_warnings = false ``` Exclude untracked files larger than this many bytes Ignore untracked directories with this many files or more ## OpenTelemetry Configuration Configure observability and tracing: ```toml theme={null} [otel] environment = "production" log_user_prompt = false [otel.trace_exporter.otlp-http] endpoint = "https://otel-collector.example.com" protocol = "binary" ``` Environment tag for traces (dev, staging, prod, test) Include user prompts in trace logs ## JavaScript REPL Configuration Configure the JavaScript REPL feature: ```toml theme={null} js_repl_node_path = "/usr/local/bin/node" js_repl_node_module_dirs = [ "/usr/local/lib/node_modules", "~/.npm-global/lib/node_modules" ] ``` Absolute path to Node.js runtime for js\_repl Ordered list of directories to search for Node modules ## Feature Flags Enable experimental features: ```toml theme={null} [features] multi_agent = true memories = true web_search = true sqlite = true undo = true ``` Feature flags control access to experimental or unstable features. Check the release notes for details on specific flags. ## Windows-Specific Settings ```toml theme={null} [windows] sandbox = "elevated" ``` Windows sandbox mode. **Options:** * `"elevated"` - Run with elevated permissions * `"unelevated"` - Run without elevation ## Example Advanced Configuration ```toml theme={null} # ~/.codex/config.toml profile = "development" [profiles.development] model = "gpt-5.1-codex" approval_policy = "on-request" sandbox_mode = "workspace-write" model_reasoning_effort = "medium" model_verbosity = "medium" [profiles.production] model = "gpt-4.1" approval_policy = "never" sandbox_mode = "workspace-write" model_reasoning_effort = "high" sqlite_home = "~/.codex/data" developer_instructions = """ Working in a TypeScript monorepo. Follow conventional commits. """ [shell_environment_policy] inherit = "core" exclude = ["AWS_.*", "SECRET_.*"] [agents] max_threads = 5 max_depth = 3 [tools] view_image = true web_search = true web_search = "cached" [permissions.network] enabled = true mode = "limited" allowed_domains = ["api.example.com"] [memories] use_memories = true generate_memories = true max_rollout_age_days = 30 [tui] notifications = true alternate_screen = "auto" [history] persistence = "save-all" max_bytes = 20971520 # 20MB ``` ## Next Steps Configure alternative AI providers Integrate Model Context Protocol servers Complete reference of all options # Basic Configuration Source: https://openai-codex.mintlify.app/configuration/basic Essential Codex CLI configuration options This guide covers the most common configuration options you'll need to get started with Codex CLI. ## Model Selection Choose which AI model Codex uses for conversations: ```toml theme={null} # Use GPT-4.1 as the default model model = "gpt-4.1" # Or use o4-mini for faster, more cost-effective responses model = "o4-mini" ``` The default model is `o4-mini`. Run `codex --model ` to override for a single session. ### Available Models Common model options: * `o4-mini` - Fast, cost-effective reasoning model (default) * `gpt-4.1` - Latest GPT-4 with enhanced capabilities * `gpt-5.1` - Advanced GPT-5 model * `gpt-5.1-codex` - GPT-5 optimized for code ## Approval Policies Control when Codex asks for permission before executing commands: ```toml theme={null} approval_policy = "on-request" ``` Determines when the user is consulted to approve operations. **Options:** * `"untrusted"` - Only auto-approve safe read operations; ask for everything else * `"on-request"` - The model decides when to ask for approval * `"on-failure"` - DEPRECATED: Auto-approve sandboxed commands, escalate on failure * `"never"` - Never ask; failures return immediately to the model ### Approval Policy Details Under this policy, only "known safe" commands that **only read files** are auto-approved. Everything else will ask the user to approve. **Best for**: Interactive use when you want visibility into all operations The AI model decides when to ask the user for approval based on the operation's risk and context. **Best for**: Balanced interactive use with intelligent approval prompting Commands are never escalated to the user for approval. Failures are immediately returned to the model to handle programmatically. **Best for**: Fully automated workflows, CI/CD pipelines ## Sandbox Mode Define execution boundaries for safety: ```toml theme={null} sandbox_mode = "workspace-write" ``` Controls where Codex can read and write files. **Options:** * `"read-only"` - Can only read files, no writes allowed * `"workspace-write"` - Can read anywhere, write only in workspace * `"danger-full-access"` - Full filesystem access (use with caution) `danger-full-access` mode disables safety restrictions. Only use in trusted environments. ### Workspace Write Configuration Customize the `workspace-write` sandbox behavior: ```toml theme={null} [sandbox_workspace_write] network_access = false exclude_slash_tmp = false exclude_tmpdir_env_var = false writable_roots = ["/additional/writable/path"] ``` Allow network access in workspace-write mode Additional directories where writes are allowed (absolute paths) ## API Authentication ### OpenAI API Key Set your OpenAI API key via environment variable: ```bash theme={null} export OPENAI_API_KEY="sk-..." ``` Or store it in a `.env` file in your project root: ```bash theme={null} OPENAI_API_KEY=sk-... ``` ### ChatGPT Login Alternatively, authenticate with your ChatGPT account: ```bash theme={null} codex login ``` ### Credential Storage Configure where Codex stores authentication credentials: ```toml theme={null} cli_auth_credentials_store = "auto" ``` Where to store CLI authentication credentials. **Options:** * `"file"` - Store in `~/.codex/auth.json` * `"keyring"` - Use OS keyring (most secure) * `"auto"` - Prefer keyring, fall back to file * `"ephemeral"` - Memory only (current process) ## System Instructions Customize Codex's behavior with custom instructions: ```toml theme={null} instructions = """ Always use TypeScript for new files. Prefer functional programming patterns. Write tests for all new functions. """ ``` For project-specific guidance, use `AGENTS.md` files instead of global instructions. See [Custom Instructions](/guides/custom-instructions). ## TUI Settings Customize the terminal interface: ```toml theme={null} [tui] # Enable desktop notifications notifications = true # Control alternate screen mode alternate_screen = "auto" # Enable animations animations = true # Show startup tooltips show_tooltips = true ``` Enable desktop notifications when terminal is unfocused Controls whether the TUI uses alternate screen buffer. **Options:** * `"auto"` - Disable in Zellij, enable elsewhere * `"always"` - Always use alternate screen * `"never"` - Never use alternate screen (preserves scrollback) Enable welcome screen animations and effects ## Notification Command Run a custom command when Codex completes a turn: ```toml theme={null} notify = ["terminal-notifier", "-title", "Codex", "-message", "Task complete"] ``` The notification hook receives a JSON payload on stdin with turn details. ## History Settings Configure conversation history persistence: ```toml theme={null} [history] persistence = "save-all" max_bytes = 10485760 # 10MB limit ``` Whether to save conversation history. **Options:** * `"save-all"` - Save all history to `~/.codex/history.jsonl` * `"none"` - Don't save history to disk Maximum history file size in bytes. Oldest entries are dropped when exceeded. ## Analytics & Telemetry ```toml theme={null} [analytics] enabled = true [feedback] enabled = true ``` Enable usage analytics collection Enable feedback prompts in the UI ## Example Basic Configuration Here's a complete basic configuration: ```toml theme={null} # ~/.codex/config.toml # Core settings model = "gpt-4.1" approval_policy = "on-request" sandbox_mode = "workspace-write" # Custom instructions instructions = """ Prefer TypeScript over JavaScript. Write comprehensive tests. """ # TUI preferences [tui] notifications = true alternate_screen = "auto" animations = true # History [history] persistence = "save-all" max_bytes = 10485760 # Privacy [analytics] enabled = true ``` ## Next Steps Explore profiles, reasoning effort, and more Use alternative AI providers # Custom AI Providers Source: https://openai-codex.mintlify.app/configuration/custom-providers Configure Codex to use alternative AI providers like Anthropic, Ollama, or custom endpoints Codex supports any AI provider that implements an OpenAI-compatible API. This guide shows you how to configure custom providers. ## Built-in Provider Support Codex includes built-in support for these providers: * **OpenAI** (default) - OpenAI's models including GPT-4, GPT-5, o-series * **Azure OpenAI** - Enterprise Azure deployment * **Anthropic** - Claude models via OpenAI-compatible endpoint * **OpenRouter** - Access to multiple model providers * **Ollama** - Local model inference * **LM Studio** - Local model hosting * **Together AI** - Fast inference for open models * **Mistral AI** - Mistral and Mixtral models * **DeepSeek** - DeepSeek models * **Groq** - Ultra-fast LLM inference * **xAI** - Grok models * **Gemini** - Google's Gemini models ## Configuring a Custom Provider Define custom providers in the `[model_providers]` section: ```toml theme={null} model_provider = "anthropic" [model_providers.anthropic] name = "Anthropic" base_url = "https://api.anthropic.com/v1" env_key = "ANTHROPIC_API_KEY" ``` Then set your API key: ```bash theme={null} export ANTHROPIC_API_KEY="sk-ant-..." ``` ## Provider Configuration Options Friendly display name for the provider Base URL for the provider's OpenAI-compatible API Environment variable name that stores the API key Help text for obtaining and setting the API key Static HTTP headers to include in requests (key-value pairs) HTTP headers with values from environment variables (header name → env var name) Query parameters to append to API requests Whether this provider requires OpenAI authentication (for proxies/gateways) Which wire protocol the provider expects (currently only `"responses"` is supported) Whether the provider supports Responses API WebSocket transport ## Common Provider Examples ### Ollama (Local Models) Run models locally with Ollama: ```toml theme={null} model_provider = "ollama" model = "codestral" [model_providers.ollama] name = "Ollama" base_url = "http://localhost:11434/v1" env_key = "OLLAMA_API_KEY" # Can be empty for local ``` Download from [ollama.ai](https://ollama.ai) ```bash theme={null} ollama pull codestral ``` ```bash theme={null} codex --model codestral ``` ### Azure OpenAI Use Azure's OpenAI deployment: ```toml theme={null} model_provider = "azure" model = "gpt-4" [model_providers.azure] name = "Azure OpenAI" base_url = "https://YOUR_RESOURCE.openai.azure.com/openai" env_key = "AZURE_OPENAI_API_KEY" [model_providers.azure.query_params] "api-version" = "2024-02-15-preview" ``` Set your credentials: ```bash theme={null} export AZURE_OPENAI_API_KEY="your-key-here" export AZURE_OPENAI_API_VERSION="2024-02-15-preview" # Optional ``` ### OpenRouter Access multiple providers through OpenRouter: ```toml theme={null} model_provider = "openrouter" model = "anthropic/claude-3.5-sonnet" [model_providers.openrouter] name = "OpenRouter" base_url = "https://openrouter.ai/api/v1" env_key = "OPENROUTER_API_KEY" ``` ```bash theme={null} export OPENROUTER_API_KEY="sk-or-..." ``` ### Anthropic (Claude) Use Claude models via Anthropic's API: ```toml theme={null} model_provider = "anthropic" model = "claude-3-5-sonnet-20241022" [model_providers.anthropic] name = "Anthropic" base_url = "https://api.anthropic.com/v1" env_key = "ANTHROPIC_API_KEY" ``` ```bash theme={null} export ANTHROPIC_API_KEY="sk-ant-..." ``` Anthropic's API may require adapter middleware for full OpenAI compatibility. Consider using OpenRouter for easier Claude access. ### Together AI Use open models via Together AI: ```toml theme={null} model_provider = "together" model = "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo" [model_providers.together] name = "Together AI" base_url = "https://api.together.xyz/v1" env_key = "TOGETHER_API_KEY" ``` ### DeepSeek Use DeepSeek models: ```toml theme={null} model_provider = "deepseek" model = "deepseek-chat" [model_providers.deepseek] name = "DeepSeek" base_url = "https://api.deepseek.com" env_key = "DEEPSEEK_API_KEY" ``` ### Groq Fast inference with Groq: ```toml theme={null} model_provider = "groq" model = "llama-3.1-70b-versatile" [model_providers.groq] name = "Groq" base_url = "https://api.groq.com/openai/v1" env_key = "GROQ_API_KEY" ``` ### Mistral AI Use Mistral models: ```toml theme={null} model_provider = "mistral" model = "mistral-large-latest" [model_providers.mistral] name = "Mistral AI" base_url = "https://api.mistral.ai/v1" env_key = "MISTRAL_API_KEY" ``` ## Advanced Provider Configuration ### Custom HTTP Headers Include static headers in requests: ```toml theme={null} [model_providers.custom] name = "Custom Provider" base_url = "https://api.custom.com/v1" env_key = "CUSTOM_API_KEY" [model_providers.custom.http_headers] "X-Custom-Header" = "value" "X-Organization-ID" = "org-123" ``` ### Dynamic Headers from Environment Load header values from environment variables: ```toml theme={null} [model_providers.custom] name = "Custom Provider" base_url = "https://api.custom.com/v1" env_key = "CUSTOM_API_KEY" [model_providers.custom.env_http_headers] "X-Organization-ID" = "ORG_ID_ENV_VAR" "X-User-ID" = "USER_ID_ENV_VAR" ``` Then set: ```bash theme={null} export ORG_ID_ENV_VAR="org-123" export USER_ID_ENV_VAR="user-456" ``` ### Retry and Timeout Configuration ```toml theme={null} [model_providers.custom] name = "Custom Provider" base_url = "https://api.custom.com/v1" env_key = "CUSTOM_API_KEY" request_max_retries = 5 stream_idle_timeout_ms = 30000 stream_max_retries = 3 ``` Maximum HTTP request retries on failure Idle timeout in milliseconds before treating streaming connection as lost Maximum reconnection attempts for dropped streams ## Switching Providers You can switch providers in several ways: ### In Configuration ```toml theme={null} model_provider = "ollama" model = "codestral" ``` ### Via CLI Flag ```bash theme={null} codex --provider ollama --model codestral ``` ### Via Environment Variable ```bash theme={null} export CODEX_PROVIDER=ollama export CODEX_MODEL=codestral codex ``` ### Using Profiles ```toml theme={null} profile = "local" [profiles.local] model_provider = "ollama" model = "codestral" [profiles.cloud] model_provider = "openai" model = "gpt-4.1" ``` Switch with: ```bash theme={null} codex --profile local codex --profile cloud ``` ## Testing Provider Configuration Test your provider setup: ```bash theme={null} # Test connection and basic functionality codex "What is 2+2?" # Verbose mode to debug connection issues DEBUG=true codex "test" ``` ## Troubleshooting * Verify the base URL is correct * Check if the service is running (for local providers) * Test with curl: `curl $BASE_URL/models` * Check firewall/network settings * Verify the API key environment variable is set * Check the environment variable name matches `env_key` * Ensure the API key has required permissions * Try authenticating with the provider's native CLI * Verify the provider implements OpenAI-compatible endpoints * Check if the model name is valid for the provider * Review provider documentation for any non-standard behaviors * Some providers may need middleware for full compatibility * Verify the model name exists on the provider * Check capitalization and exact spelling * For local providers (Ollama), ensure model is pulled * Try listing available models via provider API ## Provider Compatibility Notes While Codex supports any OpenAI-compatible API, some features may have varying support: * **Streaming** - Most providers support streaming responses * **Function calling** - Required for Codex tool use; verify provider support * **Vision** - Image input requires multimodal model support * **Reasoning effort** - Only supported by reasoning-capable models (o-series) * **WebSocket transport** - Optional; falls back to HTTP streaming ## Complete Example Here's a full configuration with multiple providers: ```toml theme={null} # Default provider model_provider = "openai" model = "gpt-4.1" # Define multiple providers [model_providers.openai] name = "OpenAI" base_url = "https://api.openai.com/v1" env_key = "OPENAI_API_KEY" [model_providers.ollama] name = "Ollama" base_url = "http://localhost:11434/v1" env_key = "OLLAMA_API_KEY" [model_providers.azure] name = "Azure OpenAI" base_url = "https://myorg.openai.azure.com/openai" env_key = "AZURE_OPENAI_API_KEY" [model_providers.groq] name = "Groq" base_url = "https://api.groq.com/openai/v1" env_key = "GROQ_API_KEY" # Use profiles to switch easily [profiles.local] model_provider = "ollama" model = "codestral" [profiles.fast] model_provider = "groq" model = "llama-3.1-70b-versatile" [profiles.enterprise] model_provider = "azure" model = "gpt-4" ``` ## Next Steps Integrate Model Context Protocol servers Complete reference documentation # MCP Servers Source: https://openai-codex.mintlify.app/configuration/mcp-servers Configure Model Context Protocol (MCP) servers to extend Codex with custom tools and integrations Model Context Protocol (MCP) servers allow you to extend Codex with custom tools, resources, and integrations. This guide shows you how to configure and use MCP servers with Codex. ## What are MCP Servers? MCP servers are processes that expose tools, resources, and prompts that Codex can use. They communicate over the Model Context Protocol, providing: * **Custom tools** - Extend Codex with domain-specific operations * **Resources** - Provide access to external data sources * **Prompts** - Add specialized prompt templates * **OAuth integration** - Secure authentication for external services ## Configuration Location MCP servers are configured in `~/.codex/config.toml` under the `[mcp_servers]` section: ```toml theme={null} [mcp_servers.my-server] command = "npx" args = ["-y", "@my-org/my-mcp-server"] enabled = true ``` ## Server Transport Types MCP servers can connect via two transport mechanisms: ### Stdio Transport (Local) Run a local process that communicates over stdin/stdout: ```toml theme={null} [mcp_servers.filesystem] command = "npx" args = ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/data"] enabled = true [mcp_servers.filesystem.env] DEBUG = "mcp:*" ``` ### Streamable HTTP Transport (Remote) Connect to a remote MCP server over HTTP: ```toml theme={null} [mcp_servers.remote-server] url = "https://mcp.example.com" bearer_token_env_var = "MCP_TOKEN" enabled = true ``` ## Configuration Options Executable command to launch the MCP server (stdio only) Arguments to pass to the command (stdio only) URL for streamable HTTP MCP server (HTTP only) Whether the server is enabled. Set to `false` to disable without removing config. If `true`, Codex will fail to start if this server cannot connect Environment variables to set when launching the server (stdio only) List of environment variable names to inherit from parent process Working directory for the server process (stdio only) Environment variable containing bearer token for authentication (HTTP only) Static HTTP headers to include in requests (HTTP only) HTTP headers with values from environment variables (HTTP only) Maximum time to wait for server startup (seconds) Maximum time to wait for tool execution (seconds) If set, only these tools are exposed (whitelist) List of tools to disable (blacklist) OAuth scopes to request during authentication OAuth resource identifier for this server ## Managing MCP Servers Codex provides CLI commands for managing MCP server configurations: ### List Configured Servers ```bash theme={null} # List all configured MCP servers codex mcp list # Output as JSON codex mcp list --json ``` ### Add a Server ```bash theme={null} # Add a stdio server codex mcp add my-server -- npx -y @my-org/my-mcp-server # Add with environment variables codex mcp add my-server --env DEBUG=mcp:* -- npx -y @my-org/my-server # Add a remote HTTP server codex mcp add remote-server --url https://mcp.example.com --bearer-token-env-var MCP_TOKEN ``` ### Get Server Details ```bash theme={null} # Show server configuration codex mcp get my-server # Output as JSON codex mcp get my-server --json ``` ### Remove a Server ```bash theme={null} codex mcp remove my-server ``` ## OAuth Authentication Some MCP servers require OAuth authentication. Codex provides built-in OAuth flow support: ### Login to an MCP Server ```bash theme={null} # Authenticate with default scopes codex mcp login my-server # Authenticate with specific scopes codex mcp login my-server --scopes read,write ``` Codex will: 1. Open your browser to the OAuth authorization page 2. Start a local callback server 3. Receive the authorization code 4. Exchange it for tokens 5. Store credentials securely ### Logout from an MCP Server ```bash theme={null} codex mcp logout my-server ``` This removes stored OAuth credentials. ### OAuth Credential Storage Configure where OAuth tokens are stored: ```toml theme={null} mcp_oauth_credentials_store = "auto" ``` Where to store MCP OAuth credentials. **Options:** * `"auto"` - Prefer OS keyring, fallback to file * `"keyring"` - Use OS keyring (most secure) * `"file"` - Store in `~/.codex/.credentials.json` ### OAuth Callback Configuration ```toml theme={null} mcp_oauth_callback_port = 3000 mcp_oauth_callback_url = "http://localhost:3000/callback" ``` Fixed port for OAuth callback server. When unset, uses ephemeral port. Redirect URI to use in OAuth flow. Local listener still binds to 127.0.0.1. ## Tool Control ### Whitelist Specific Tools Only enable specific tools from a server: ```toml theme={null} [mcp_servers.my-server] command = "npx" args = ["-y", "@my-org/my-server"] enabled_tools = ["read_file", "write_file"] ``` ### Blacklist Specific Tools Disable specific tools: ```toml theme={null} [mcp_servers.my-server] command = "npx" args = ["-y", "@my-org/my-server"] disabled_tools = ["delete_file", "execute_command"] ``` If both `enabled_tools` and `disabled_tools` are set, `enabled_tools` takes precedence (whitelist mode). ## Example Configurations ### Filesystem MCP Server Provide Codex access to local filesystem: ```toml theme={null} [mcp_servers.filesystem] command = "npx" args = ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"] enabled = true startup_timeout_sec = 30 ``` ### GitHub MCP Server Integrate with GitHub repositories: ```toml theme={null} [mcp_servers.github] command = "npx" args = ["-y", "@modelcontextprotocol/server-github"] enabled = true scopes = ["repo", "read:user"] [mcp_servers.github.env] GITHUB_PERSONAL_ACCESS_TOKEN = "${GITHUB_TOKEN}" ``` Then authenticate: ```bash theme={null} codex mcp login github --scopes repo,read:user ``` ### Slack MCP Server Connect to Slack workspace: ```toml theme={null} [mcp_servers.slack] command = "npx" args = ["-y", "@modelcontextprotocol/server-slack"] enabled = true scopes = ["channels:read", "channels:history", "chat:write"] ``` ### Database MCP Server Query PostgreSQL databases: ```toml theme={null} [mcp_servers.postgres] command = "npx" args = ["-y", "@modelcontextprotocol/server-postgres"] enabled = true [mcp_servers.postgres.env] DATABASE_URL = "postgresql://user:pass@localhost/mydb" ``` ### Custom HTTP MCP Server Connect to a remote custom server: ```toml theme={null} [mcp_servers.custom-api] url = "https://mcp.mycompany.com/api" bearer_token_env_var = "COMPANY_MCP_TOKEN" enabled = true tool_timeout_sec = 60 [mcp_servers.custom-api.http_headers] "X-Organization-ID" = "org-123" ``` Set the token: ```bash theme={null} export COMPANY_MCP_TOKEN="your-token-here" ``` ## App-Level Tool Controls Codex also provides app-level controls for MCP tools: ```toml theme={null} [apps.github] enabled = true default_tools_enabled = true default_tools_approval_mode = "auto" destructive_enabled = false open_world_enabled = true [apps.github.tools.delete_repo] enabled = false approval_mode = "prompt" ``` Enable or disable the entire app/connector Whether tools are enabled by default for this app Default approval mode: `"auto"`, `"prompt"`, or `"approve"` Allow tools marked as destructive Allow tools with open world access hints ## Troubleshooting * Check that the command and args are correct * Verify the executable is in PATH or use absolute path * Check `startup_timeout_sec` if server is slow to start * Review server logs (set `DEBUG=mcp:*` in env) * Ensure required environment variables are set * Verify the server supports OAuth * Check that callback port is not blocked by firewall * Ensure browser can reach callback URL * Try specifying a fixed port with `mcp_oauth_callback_port` * Check server OAuth configuration and scopes * Verify server is enabled (`enabled = true`) * Check if tools are in `disabled_tools` list * If using `enabled_tools`, ensure tools are listed * Verify server process is running successfully * Check that server implements MCP protocol correctly * Increase `tool_timeout_sec` for slow operations * Check network connectivity for HTTP servers * Review server implementation for performance issues * Verify server is not rate-limited or throttled * For stdio servers, use `env` section to set variables * For HTTP servers, use `env_http_headers` for header values * Check environment variable names for typos * Verify variables are exported in your shell * Use `env_vars` to inherit specific parent environment variables ## Security Considerations MCP servers run with the same permissions as Codex and can access files and networks. Only use trusted MCP servers. ### Best Practices 1. **Review server code** - Inspect open-source servers before use 2. **Use tool whitelisting** - Enable only necessary tools with `enabled_tools` 3. **Disable destructive operations** - Set `destructive_enabled = false` for apps 4. **Use OAuth when available** - More secure than static API keys 5. **Store credentials securely** - Prefer keyring over file storage 6. **Set timeouts** - Prevent hung operations with `tool_timeout_sec` 7. **Monitor server logs** - Watch for unexpected behavior 8. **Keep servers updated** - Update MCP servers regularly ## Complete Configuration Example ```toml theme={null} # OAuth credential storage mcp_oauth_credentials_store = "auto" mcp_oauth_callback_port = 3000 # MCP servers [mcp_servers.filesystem] command = "npx" args = ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"] enabled = true startup_timeout_sec = 30 tool_timeout_sec = 120 [mcp_servers.github] command = "npx" args = ["-y", "@modelcontextprotocol/server-github"] enabled = true scopes = ["repo", "read:user"] required = false [mcp_servers.github.env] DEBUG = "mcp:*" [mcp_servers.slack] command = "npx" args = ["-y", "@modelcontextprotocol/server-slack"] enabled = false # Disabled by default scopes = ["channels:read", "chat:write"] [mcp_servers.custom-api] url = "https://mcp.example.com/api" bearer_token_env_var = "MCP_TOKEN" enabled = true tool_timeout_sec = 60 [mcp_servers.custom-api.http_headers] "X-API-Version" = "2024-01" # App-level controls [apps.github] enabled = true default_tools_approval_mode = "auto" destructive_enabled = false [apps.github.tools.delete_repo] enabled = false [apps.slack] enabled = true default_tools_approval_mode = "prompt" ``` ## Next Steps Complete reference of all configuration options Learn to build your own MCP servers # Configuration Overview Source: https://openai-codex.mintlify.app/configuration/overview Learn how to configure Codex CLI with config.toml Codex CLI uses a configuration file located at `~/.codex/config.toml` to customize behavior, model settings, approval policies, and integrations. ## Configuration File Location Codex looks for configuration in the following locations: * **Global config**: `~/.codex/config.toml` - Your personal configuration * **Project config**: `.codex/config.toml` in your project root - Project-specific settings * **Environment variables**: Override config values using environment variables Configuration files are merged with project settings taking precedence over global settings. ## Basic Structure Here's a minimal `config.toml` example: ```toml theme={null} # Model selection model = "o4-mini" # Approval policy for command execution approval_policy = "on-request" # Sandbox mode for safety sandbox_mode = "workspace-write" # Enable desktop notifications [tui] notifications = true ``` ## Configuration Sections Codex configuration is organized into several sections: ### Core Settings * **Model configuration** - Select AI models and providers * **Approval policies** - Control when Codex asks for permission * **Sandbox mode** - Define execution boundaries * **Authentication** - API keys and login methods ### Advanced Features * **MCP servers** - Connect to Model Context Protocol servers * **Custom instructions** - Personalize agent behavior * **Profiles** - Switch between different configuration sets * **Network permissions** - Control network access for tools ### UI & Experience * **TUI settings** - Customize terminal interface * **Notifications** - Desktop notification preferences * **History** - Conversation history settings * **Analytics** - Usage data collection preferences ## Quick Start If you don't have a config file yet, Codex will create one automatically on first run. To create or edit your configuration: ```bash theme={null} # Create the config directory mkdir -p ~/.codex # Edit your config file $EDITOR ~/.codex/config.toml ``` ## Configuration Schema Codex includes a JSON schema for `config.toml` validation at: ``` codex-rs/core/config.schema.json ``` This schema documents all available configuration options and is kept in sync with the codebase. ## Next Steps Learn about essential configuration options Explore advanced features and customization Configure alternative AI providers Integrate Model Context Protocol servers ## Configuration Layers Codex merges configuration from multiple sources in this order (later sources override earlier ones): 1. Built-in defaults 2. Global config (`~/.codex/config.toml`) 3. Project config (`.codex/config.toml`) 4. Profile overrides (when using `--profile`) 5. CLI flags (e.g., `--model`, `--approval-policy`) 6. Environment variables This layering allows you to set defaults globally while customizing behavior per-project or per-invocation. # Configuration Reference Source: https://openai-codex.mintlify.app/configuration/reference Complete reference for all Codex configuration options This page provides a comprehensive reference of all configuration options available in `config.toml`. ## Configuration File **Location**: `~/.codex/config.toml` **Format**: TOML (Tom's Obvious, Minimal Language) **Schema**: `codex-rs/core/config.schema.json` ## Top-Level Options ### Model Configuration Default model to use for conversations. Examples: `"gpt-4.1"`, `"gpt-5.1"`, `"gpt-5.1-codex"`, `"o4-mini"` Key from `model_providers` map identifying which provider to use. Example: `"openai"`, `"azure"`, `"ollama"` Default reasoning effort for reasoning-capable models. Options: `"none"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"xhigh"` Controls reasoning summary presentation. Options: `"auto"`, `"concise"`, `"detailed"`, `"none"` Output detail level for GPT-5 models. Options: `"low"`, `"medium"`, `"high"` Reasoning effort override specifically for Plan mode. When unset, Plan mode uses built-in default (`"medium"`). When set (including `"none"`), overrides Plan preset. Context window size for the model in tokens. Token threshold that triggers automatic conversation compaction. Path to file containing custom model instructions. ⚠️ **Warning**: Overriding built-in instructions may degrade performance. Path to JSON model catalog file (applied on startup only). Force-enable reasoning summaries for the configured model. ### Approval & Execution When to ask user for approval before executing operations. **String options:** * `"untrusted"` - Auto-approve only safe read operations * `"on-request"` - Model decides when to ask * `"on-failure"` - DEPRECATED: Auto-approve sandboxed, escalate on failure * `"never"` - Never ask; return failures to model **Object form** (fine-grained rejection): ```toml theme={null} [approval_policy.reject] rules = true sandbox_approval = false mcp_elicitations = true ``` Filesystem access boundaries. Options: * `"read-only"` - Read-only access * `"workspace-write"` - Read anywhere, write in workspace * `"danger-full-access"` - Full filesystem access Whether model may request login shell for shell tools. If `false`, `login = true` requests are rejected and default is non-login shell. ### Sandbox Workspace Write Allow network access in workspace-write mode. Exclude `/tmp` from writable paths. Exclude `$TMPDIR` from writable paths. Additional absolute paths where writes are allowed. Example: `["/additional/path", "/another/path"]` ### Authentication Where to store CLI authentication credentials. Options: * `"file"` - `~/.codex/auth.json` * `"keyring"` - OS keyring service * `"auto"` - Prefer keyring, fallback to file * `"ephemeral"` - Memory only (current process) Restrict login mechanism. Options: `"chatgpt"`, `"api"` When set, restricts ChatGPT login to specific workspace. Base URL for ChatGPT (as opposed to OpenAI API) requests. ### Instructions Global system instructions for the agent. Developer role message instructions. Custom prompt for conversation history compaction. Path to file containing custom compaction prompt. ### Profiles Active profile name from the `profiles` map. Named configuration profiles for easy switching. Each profile can override any configuration option. Example: ```toml theme={null} [profiles.fast] model = "o4-mini" model_reasoning_effort = "low" [profiles.careful] model = "gpt-4.1" approval_policy = "untrusted" ``` ### Personality Agent personality mode. Options: `"none"`, `"friendly"`, `"pragmatic"` ## Model Providers User-defined provider configurations. Example: ```toml theme={null} [model_providers.ollama] name = "Ollama" base_url = "http://localhost:11434/v1" env_key = "OLLAMA_API_KEY" ``` ### Provider Configuration Friendly display name for the provider. Base URL for provider's OpenAI-compatible API. Environment variable storing the API key. Help text for obtaining and setting the API key. Whether provider requires OpenAI API key or ChatGPT login. Static HTTP headers (key-value pairs). Headers with values from environment variables (header → env var name). Query parameters to append to requests. Maximum HTTP request retries. Idle timeout (ms) before treating streaming connection as lost. Maximum streaming reconnection attempts. Whether provider supports Responses API WebSocket transport. Wire protocol the provider expects. Currently only `"responses"` supported. ## MCP Servers MCP server configurations keyed by server name. Example: ```toml theme={null} [mcp_servers.github] command = "npx" args = ["-y", "@modelcontextprotocol/server-github"] enabled = true ``` ### MCP Server Configuration Executable to launch (stdio transport). Command arguments (stdio transport). Server URL (streamable HTTP transport). Whether server is enabled. If true, Codex fails to start if server connection fails. Environment variables for server process (stdio only). Environment variable names to inherit from parent. Working directory for server process (stdio only). Environment variable with bearer token (HTTP only). Static HTTP headers (HTTP only). Headers from environment variables (HTTP only). Maximum server startup time (seconds). Maximum tool execution time (seconds). Whitelist of enabled tools. If set, only these are exposed. Blacklist of disabled tools. OAuth scopes to request. OAuth resource identifier. ### MCP OAuth Settings Where to store MCP OAuth credentials. Options: `"auto"`, `"file"`, `"keyring"` Fixed port for OAuth callback server. If unset, uses ephemeral port. Redirect URI for OAuth flow. Local listener still binds to 127.0.0.1. ## Apps Configuration App/connector control settings. Example: ```toml theme={null} [apps._default] enabled = true destructive_enabled = false [apps.github] enabled = true default_tools_approval_mode = "auto" ``` ### App Settings Default enabled state for all apps. Whether destructive tools are allowed by default. Whether open-world tools are allowed by default. Enable or disable specific app. Whether tools are enabled by default for this app. Default approval mode for app tools. Options: `"auto"`, `"prompt"`, `"approve"` Allow destructive tools for this app. Allow open-world tools for this app. Enable/disable specific tool. Approval mode for specific tool. ## Shell Environment Policy Which environment to inherit. Options: * `"core"` - Essential variables only (HOME, PATH, USER, etc.) * `"all"` - Full parent environment * `"none"` - Empty environment If set, only inherit variables matching these regex patterns. Regex patterns for variables to exclude (after inherit). Ignore built-in exclude patterns. Explicitly set environment variables. Experimental: Use shell profile during initialization. ## Agent Configuration Maximum concurrent agent threads. If unset, no limit. Maximum nesting depth for spawned agents (root = 0). Default maximum runtime for agent job workers (seconds). Path to role-specific config layer. Human-facing role documentation. ## Tools Enable `view_image` tool for attaching local images. Enable web search tool. Web search mode. Options: `"disabled"`, `"cached"`, `"live"` Token budget for tool/function output storage. ## Permissions Enable network proxy. Network access mode. Options: `"limited"`, `"full"` Allowed domain patterns. Explicitly denied domains. Allowed Unix socket paths. Allow all Unix sockets (use with caution). Allow binding to local ports. Allow proxying to upstream servers. HTTP proxy URL. SOCKS proxy URL. Admin interface URL. Enable SOCKS5 proxy. Enable SOCKS5 UDP support. ## TUI Settings Enable desktop notifications when terminal unfocused. Notification method. Options: `"auto"`, `"osc9"`, `"bel"` Alternate screen buffer mode. Options: * `"auto"` - Disable in Zellij, enable elsewhere * `"always"` - Always use alternate screen * `"never"` - Never use (preserves scrollback) Enable TUI animations and effects. Show startup tooltips in welcome screen. Syntax highlighting theme name (kebab-case). Overrides automatic light/dark detection. Custom themes in `$CODEX_HOME/themes`. Ordered list of status line item identifiers. Default: `["model-with-reasoning", "context-remaining", "current-dir"]` ## History History persistence mode. Options: * `"save-all"` - Save to `~/.codex/history.jsonl` * `"none"` - Don't save to disk Maximum history file size (bytes). Oldest entries dropped when exceeded. ## Memories Inject memory usage instructions into prompts. Enable automatic memory generation. Maximum age of threads for memory generation (days). Minimum idle time before memory creation (hours, >12 recommended). Maximum rollout candidates processed per pass. Maximum days since last use before memory becomes ineligible. Maximum recent raw memories retained for global consolidation. Model for thread summarization. Model for memory consolidation. ## Ghost Snapshots Exclude untracked files larger than this (bytes). Ignore untracked dirs with this many files or more. Disable ghost snapshot warning events. ## Skills User-level skill configurations. Example: ```toml theme={null} [[skills.config]] enabled = true path = "~/.codex/skills/custom-skill" ``` ## Project Settings Markers for detecting project root when searching for `.codex` folders. Fallback filenames when `AGENTS.md` is missing. Maximum bytes to include from `AGENTS.md` files. Trust level for project directory. Options: `"trusted"`, `"untrusted"` ## Notices Tracks whether user acknowledged full access warning. Tracks whether user opted out of rate limit model nudge. Tracks acknowledged model migrations (old → new mappings). ## Notification External command to run for notifications. Example: `["terminal-notifier", "-title", "Codex", "-message", "Done"]` ## Analytics & Feedback Enable usage analytics. Enable feedback prompts. ## Logging & Storage Directory for log files. Defaults to `$CODEX_HOME/log`. SQLite database directory. Defaults to `$CODEX_SQLITE_HOME` or `$CODEX_HOME`. ## JavaScript REPL Absolute path to Node.js runtime for js\_repl. Ordered list of Node module search directories. ## Miscellaneous URI-based file opener for file citations. Options: `"vscode"`, `"vscode-insiders"`, `"windsurf"`, `"cursor"`, `"none"` Commit attribution text for co-author trailers. Empty string disables. Check for Codex updates on startup. Disable burst-paste detection for typed input. Hide `AgentReasoning` events from UI. Show raw agent reasoning content events. Suppress warnings about unstable features. Maximum poll window for background terminal output (ms). Model override for `/review` feature. Preferred OSS provider for local models (e.g., `"lmstudio"`, `"ollama"`). Absolute path to patched zsh for zsh-exec-bridge shell execution. ## Windows Settings Windows sandbox mode. Options: `"elevated"`, `"unelevated"` Tracks whether Windows onboarding screen was acknowledged. ## OpenTelemetry Environment tag for traces (dev, staging, prod, test). Include user prompts in trace logs. Log exporter configuration. Trace exporter configuration. Metrics exporter configuration. ## Audio Realtime audio microphone device preference. Realtime audio speaker device preference. ## Feature Flags Centralized feature flags for experimental features. Available flags: * `multi_agent` * `memories` * `web_search` * `sqlite` * `undo` * `collaboration_modes` * `realtime_conversation` * `voice_transcription` * And many more... ## Configuration Priority Configuration is merged in this order (later overrides earlier): 1. Built-in defaults 2. Global config (`~/.codex/config.toml`) 3. Project config (`.codex/config.toml` in project root) 4. Profile settings (when `profile` is set or `--profile` flag used) 5. CLI flags (`--model`, `--approval-policy`, etc.) 6. Environment variables (`CODEX_MODEL`, etc.) ## Validation Codex validates configuration against JSON Schema at `codex-rs/core/config.schema.json`. Common validation errors: * Invalid enum values (e.g., unknown `approval_policy`) * Type mismatches (string vs integer) * Missing required fields in nested objects * Invalid path formats for file paths ## Next Steps Get started with essential options Explore power user features # Building Codex Source: https://openai-codex.mintlify.app/contributing/building Learn how to build Codex CLI from source for Rust and TypeScript implementations This guide covers building Codex CLI from source, including both the Rust and legacy TypeScript implementations. ## Building the Rust Implementation The Rust implementation is the maintained version of Codex CLI and lives in `codex-rs/`. ### Quick Start ```bash theme={null} cd codex/codex-rs ``` ```bash theme={null} cargo build ``` For optimized builds, use `cargo build --release` Launch the TUI with a sample prompt: ```bash theme={null} cargo run --bin codex -- "explain this codebase to me" ``` ### Build-Related Commands After making changes, use these workspace helpers: ```bash Format code theme={null} just fmt ``` ```bash Fix linter issues theme={null} # Scope to specific crate you touched just fix -p codex-tui # Or run for all crates (slower) just fix ``` ```bash Update config schema theme={null} # Run after changing ConfigToml or nested config types just write-config-schema ``` ```bash Update Bazel lockfile theme={null} # Run after changing Rust dependencies just bazel-lock-update just bazel-lock-check ``` **Important:** Run `just fmt` automatically after making Rust code changes. Do not re-run tests after running `fix` or `fmt`. ### Workspace Organization The `codex-rs/` directory is a Cargo workspace with these key crates: | Crate | Purpose | | -------------------------- | --------------------------------------------------------------- | | **`core/`** | Business logic for Codex - intended as a reusable library crate | | **`tui/`** | Fullscreen TUI built with [Ratatui](https://ratatui.rs/) | | **`exec/`** | Headless CLI for automation and non-interactive use | | **`cli/`** | CLI multitool providing TUI and exec via subcommands | | **`app-server/`** | App server protocol implementation | | **`app-server-protocol/`** | Protocol types and schemas | For detailed information about each crate, read the module-level `README.md` files under each crate directory. ## Building the TypeScript Implementation The TypeScript implementation is **legacy** and has been superseded by the Rust implementation. This section is for reference only. The legacy TypeScript CLI lives in `codex-cli/`. ```bash theme={null} cd codex/codex-cli ``` ```bash theme={null} pnpm build ``` ```bash theme={null} # Get usage and options node ./dist/cli.js --help # Run the CLI node ./dist/cli.js # Or link globally pnpm link ``` ### TypeScript Build Commands ```bash Build theme={null} pnpm build ``` ```bash Type Check theme={null} pnpm typecheck ``` ```bash Lint theme={null} pnpm lint ``` ```bash Fix Formatting theme={null} pnpm lint:fix pnpm format:fix ``` ## Debugging ### Debugging the Rust CLI Set the `RUST_LOG` environment variable: ```bash theme={null} export RUST_LOG=codex_core=debug,codex_tui=debug cargo run --bin codex ``` The TUI logs to `~/.codex/log/codex-tui.log` by default: ```bash theme={null} tail -F ~/.codex/log/codex-tui.log ``` Override the log directory with: ```bash theme={null} cargo run --bin codex -- -c log_dir=./.codex-log ``` The TUI defaults to `RUST_LOG=codex_core=info,codex_tui=info,codex_rmcp_client=info`. Non-interactive mode (`codex exec`) defaults to `RUST_LOG=error` with messages printed inline. See the [Rust documentation on `RUST_LOG`](https://docs.rs/env_logger/latest/env_logger/#enabling-logging) for more configuration options. ### Debugging the TypeScript CLI ```bash theme={null} cd codex-cli pnpm run build ``` This generates `cli.js.map` alongside `cli.js` in the `dist` folder. ```bash theme={null} node --inspect-brk ./dist/cli.js ``` The program waits until a debugger is attached. Choose one: * **VS Code:** Run **Debug: Attach to Node Process** from the command palette and select the option with debug port `9229` * **Chrome:** Go to `chrome://inspect` and find **localhost:9229**, then click **inspect** ### Enable Debug Output For the TypeScript CLI, enable full API request and response logging: ```bash theme={null} DEBUG=true codex ``` ## Troubleshooting Ensure all required tools are installed: ```bash theme={null} # For Rust cargo install just cargo-nextest cargo-insta # For TypeScript corepack enable ``` Make sure you're running tests from the correct directory: * Rust: Run from `codex-rs/` * TypeScript: Run from `codex-cli/` See [Testing](/contributing/testing) for detailed test commands. Run the automatic fixers: ```bash theme={null} # Rust just fmt just fix -p # TypeScript pnpm lint:fix pnpm format:fix ``` ## Next Steps Learn about testing workflows Review coding standards # Contribution Guidelines Source: https://openai-codex.mintlify.app/contributing/guidelines Code style, conventions, and best practices for contributing to Codex CLI This guide outlines the coding standards, conventions, and best practices for invited contributors to the Codex CLI project. ## Development Workflow If you've been invited by a Codex team member to contribute a PR, follow this recommended workflow: Create a branch from `main` with a descriptive name: ```bash theme={null} git checkout -b feat/interactive-prompt git checkout -b fix/snapshot-rendering ``` Multiple unrelated fixes should be opened as separate PRs. Focus on one problem at a time. Before pushing, ensure your change is free of: * Lint warnings * Test failures * Type errors (TypeScript) Each commit should: * Compile successfully * Pass all tests * Be logically independent (makes reviews and rollbacks easier) ## Guidance for Invited Code Contributions Open a new issue or comment on an existing discussion to agree on the solution before writing code. Bug fixes should come with test coverage that fails before your change and passes afterwards. Aim for meaningful assertions. If your change affects user-facing behavior, update the README, inline help (`codex --help`), or relevant example projects. Each commit should compile and tests should pass. This makes reviews and potential rollbacks easier. ## Rust Code Conventions ### General Rules Crate names are prefixed with `codex-`. For example, the `core` folder's crate is named `codex-core`. * Always run `just fmt` after making Rust code changes * Run `just fix -p ` to fix linter issues before finalizing changes * Do not re-run tests after running `fix` or `fmt` * Always collapse if statements per [clippy::collapsible\_if](https://rust-lang.github.io/rust-clippy/master/index.html#collapsible_if) * When possible, make `match` statements exhaustive and avoid wildcard arms * Always inline format! args when possible per [clippy::uninlined\_format\_args](https://rust-lang.github.io/rust-clippy/master/index.html#uninlined_format_args) * Use method references over closures per [clippy::redundant\_closure\_for\_method\_calls](https://rust-lang.github.io/rust-clippy/master/index.html#redundant_closure_for_method_calls) Do not create small helper methods that are referenced only once. Keep code inline for clarity. ### TUI Code Conventions For the terminal user interface (`codex-tui`), follow these ratatui styling conventions: ```rust Stylize helpers (preferred) theme={null} use ratatui::style::Stylize; // Basic spans "text".into() // Styled spans "error".red() "success".green() "info".cyan() "muted".dim() // Chained styling url.cyan().underlined() header.bold().magenta() ``` ```rust Building lines theme={null} // Prefer vec![...].into() when type is obvious let line: Line = vec![" └ ".into(), "M".red(), " ".dim(), "tui/src/app.rs".dim()].into(); // Use Line::from when type isn't obvious let line = Line::from(vec![span1, span2]); ``` ```rust Avoid hardcoded white theme={null} // Don't do this: "text".white() // Do this instead (use default foreground): "text".into() ``` See `codex-rs/tui/styles.md` for complete TUI styling conventions. ### Text Wrapping * Always use `textwrap::wrap` to wrap plain strings * For ratatui `Line` wrapping, use helpers in `tui/src/wrapping.rs` (e.g., `word_wrap_lines`, `word_wrap_line`) * Use `initial_indent`/`subsequent_indent` options from `RtOptions` for indenting wrapped lines * Use `prefix_lines` helper from `line_utils` for prefixing lines ## TypeScript Code Conventions The TypeScript implementation is **legacy**. These conventions are for reference only. ### Code Quality Tools * **Vitest** for unit tests * **ESLint** for linting * **Prettier** for code formatting * **TypeScript** for type checking ### Before Pushing ```bash theme={null} pnpm test && pnpm run lint && pnpm run typecheck ``` ## Opening a Pull Request Remember: Pull requests must be **explicitly invited** by a Codex team member. Include: * **What?** - What does this PR change? * **Why?** - Why is this change necessary? * **How?** - How does it work? * Link to the bug report or enhancement request ```bash theme={null} just fmt just fix -p cargo test -p ``` ```bash theme={null} pnpm test && pnpm run lint && pnpm run typecheck ``` CI failures that could have been caught locally slow down the process. Make sure your branch is up-to-date with `main` and resolve any merge conflicts. Only mark the PR as **Ready for review** when you believe it is in a merge-able state. ## Model Metadata Updates When updating model catalogs or model metadata (`/models` payloads, presets, or fixtures): * Set `input_modalities` explicitly for any model that does not support images * Keep compatibility defaults in mind: omitted `input_modalities` currently implies text + image support * Ensure client surfaces that accept images (e.g., TUI paste/attach) consume the same capability signal * Add/update tests that cover unsupported-image behavior and warning paths ## App-Server API Development When working on app-server protocol in `codex-rs`: ### Core Rules All active API development should happen in app-server v2. Do not add new API surface area to v1. * `*Params` for request payloads * `*Response` for responses * `*Notification` for notifications Expose as `/` with singular `` (e.g., `thread/read`, `app/list`) Use camelCase on the wire with `#[serde(rename_all = "camelCase")]` ### Development Workflow Update `app-server/README.md` when API behavior changes. ```bash theme={null} just write-app-server-schema # If experimental API is affected: just write-app-server-schema --experimental ``` ```bash theme={null} cargo test -p codex-app-server-protocol ``` ## Review Process One maintainer will be assigned as a primary reviewer. If your invited PR introduces scope or behavior that was not previously discussed and approved, the PR may be closed. We may ask for changes. Please do not take this personally. We value the work, but also value consistency and long-term maintainability. When there is consensus that the PR meets the bar, a maintainer will squash-and-merge. ## Contributor License Agreement (CLA) All contributors **must** accept the CLA. The process is lightweight: Create and submit your PR. Paste the following comment (or reply `recheck` if you've signed before): ```text theme={null} I have read the CLA Document and I hereby sign the CLA ``` The CLA-Assistant bot records your signature and marks the status check as passed. No special Git commands, email attachments, or commit footers required. ## Configuration Changes If you change `ConfigToml` or nested config types: ```bash theme={null} just write-config-schema ``` This updates `codex-rs/core/config.schema.json`. ## Dependency Changes If you change Rust dependencies (`Cargo.toml` or `Cargo.lock`): ```bash theme={null} # From repo root just bazel-lock-update just bazel-lock-check ``` Include the lockfile update in the same change. ## Community Values Treat others with respect. We follow the [Contributor Covenant](https://www.contributor-covenant.org/). Written communication is hard - err on the side of generosity. If you spot something confusing, open an issue or discussion with suggestions or clarifications. ## Getting Help If you run into problems: * Open a **Discussion** topic * Jump into the relevant **issue** * Ask in community channels We are happy to help. Together we can make Codex CLI an incredible tool. ## Security & Responsible AI Have you discovered a vulnerability or have concerns about model output? Please email **[security@openai.com](mailto:security@openai.com)** and we will respond promptly. ## Next Steps Set up your development environment Learn how to build the project Run tests to validate changes # Contributing Overview Source: https://openai-codex.mintlify.app/contributing/overview Learn how to contribute to the Codex CLI project and get involved with the community Welcome to the Codex CLI contributing guide! We're building Codex in the open with the community and value your input. ## Contribution Policy **External contributions are by invitation only** At this time, the Codex team does not accept unsolicited code contributions. Pull requests that have not been explicitly invited by a member of the Codex team will be closed without review. ### How You Can Help While we don't accept unsolicited PRs, there are many ways to contribute: Open a bug report or verify that an existing report already covers the issue you encountered. Contribute reproduction details, root-cause hypotheses, or high-level fix outlines in issue threads. Open an issue describing your proposal or upvote existing enhancement requests. Participate in GitHub Discussions to help shape the future of Codex. ## When PRs Are Invited The Codex team may invite an external contributor to submit a pull request when: * The problem is well understood * The proposed approach aligns with the team's intended solution * The issue is deemed high-impact and high-priority The most valuable contributions consistently come from community members who demonstrate deep understanding of a problem domain. That expertise is most helpful when shared early through detailed bug reports, analysis, and design discussion in issues. ## Why This Policy? In the past, the Codex team accepted external pull requests for bug fixes. While we appreciated the effort and engagement from the community, this model did not scale well. Many contributions were made without full visibility into: * Architectural context * System-level constraints * Near-term roadmap considerations Reviewing and iterating on these PRs often took more time than implementing the fix directly, and diverted attention from higher-priority work. **We focus external contributions on discussion, analysis, and feedback**, and reserve code changes for cases where a targeted invitation makes sense. ## Getting Started If you've been invited to contribute code, here's where to begin: Follow the [development environment setup guide](/contributing/setup) to prepare your local workspace. Learn how to [build Codex from source](/contributing/building) for both Rust and TypeScript components. Familiarize yourself with the [testing workflows](/contributing/testing) to validate your changes. Review our [contribution guidelines](/contributing/guidelines) for code style and commit conventions. ## Community Values Treat others with respect; we follow the [Contributor Covenant](https://www.contributor-covenant.org/). Written communication is hard - err on the side of generosity. If you spot something confusing, open an issue or discussion with suggestions. ## Getting Help If you run into problems setting up the project, would like feedback on an idea, or just want to say hi: * Open a **Discussion** topic * Jump into the relevant **issue** * Reach out in the community channels We are happy to help. Together we can make Codex CLI an incredible tool. ## Security & Responsible AI Have you discovered a vulnerability or have concerns about model output? Please email **[security@openai.com](mailto:security@openai.com)** and we will respond promptly. # Development Setup Source: https://openai-codex.mintlify.app/contributing/setup Set up your development environment for contributing to Codex CLI This guide covers the prerequisites and steps needed to set up a development environment for Codex CLI. ## System Requirements Ensure your system meets these minimum requirements before proceeding. | Requirement | Details | | --------------------- | ----------------------------------------------------------- | | **Operating systems** | macOS 12+, Ubuntu 20.04+/Debian 10+, or Windows 11 via WSL2 | | **RAM** | 4 GB minimum (8 GB recommended) | | **Git** | 2.23+ (optional, recommended for built-in PR helpers) | ## Rust Development Setup The primary Codex CLI implementation is written in Rust and lives in the `codex-rs/` directory. ```bash theme={null} git clone https://github.com/openai/codex.git cd codex/codex-rs ``` Install Rust and required components: ```bash theme={null} curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y source "$HOME/.cargo/env" rustup component add rustfmt rustup component add clippy ``` Install workspace helper tools: ```bash theme={null} # Required: justfile command runner cargo install just # Optional: nextest for faster test runs cargo install --locked cargo-nextest # Optional: insta for snapshot testing cargo install cargo-insta ``` Build Codex to verify your setup: ```bash theme={null} cargo build ``` If the build succeeds, you're ready to start developing! ## TypeScript Development Setup The TypeScript implementation is **legacy** and has been superseded by the Rust implementation. This section is provided for reference only. The legacy TypeScript CLI lives in the `codex-cli/` directory. ```bash theme={null} cd codex/codex-cli ``` ```bash theme={null} corepack enable ``` ```bash theme={null} pnpm install ``` On Linux, download prebuilt sandboxing binaries (requires `gh` and `zstd`): ```bash theme={null} ./scripts/install_native_deps.sh ``` ## DotSlash (Optional) GitHub Releases contain a [DotSlash](https://dotslash-cli.com/) file for the Codex CLI named `codex`. Using a DotSlash file makes it possible to commit a lightweight reference to source control to ensure all contributors use the same version of an executable, regardless of platform. ## Alternative: Nix Flake Development **Prerequisite:** Nix >= 2.4 with flakes enabled (`experimental-features = nix-command flakes` in `~/.config/nix/nix.conf`). ### Enter Development Shell ```bash theme={null} # For Rust implementation nix develop .#codex-rs # For TypeScript implementation nix develop .#codex-cli ``` This shell includes Node.js (for TypeScript) or Rust toolchain, installs dependencies, builds the CLI, and provides a `codex` command alias. ### Build Directly ```bash theme={null} # Build Rust implementation nix build .#codex-rs ./result/bin/codex --help # Build TypeScript implementation nix build .#codex-cli ./result/bin/codex --help ``` ### Run via Flake App ```bash theme={null} # Run Rust implementation nix run .#codex-rs # Run TypeScript implementation nix run .#codex-cli ``` ### Use with direnv If you have `direnv` installed, automatically enter the Nix shell when you `cd` into the project: ```bash theme={null} cd codex-rs echo "use flake ../flake.nix#codex-rs" >> .envrc && direnv allow cd ../codex-cli echo "use flake ../flake.nix#codex-cli" >> .envrc && direnv allow ``` ## Next Steps Now that your environment is set up: Learn how to build the project Run tests to verify your setup Review contribution guidelines Explore configuration options # Testing Source: https://openai-codex.mintlify.app/contributing/testing Learn how to run tests and validate your changes to Codex CLI This guide covers the testing workflows for Codex CLI, including unit tests, integration tests, and snapshot tests. ## Rust Testing The Rust implementation uses standard `cargo test` along with specialized tools. ### Running Tests Always start by testing the specific crate you modified: ```bash theme={null} cargo test -p codex-tui cargo test -p codex-core cargo test -p codex-app-server-protocol ``` This is the fastest way to get feedback on your changes. If you changed `common`, `core`, or `protocol` crates, run the complete test suite: ```bash theme={null} # Standard cargo test cargo test # Or with nextest (faster) just test ``` Avoid `--all-features` for routine local runs. It expands the build matrix and significantly increases build time and disk usage. Only use it when you specifically need full feature coverage. Review test output for any failures or warnings. ### Snapshot Tests Codex uses snapshot tests via `insta` to validate rendered output, especially in `codex-tui`. **Requirement:** Any change that affects user-visible UI must include corresponding `insta` snapshot coverage. ```bash theme={null} cargo test -p codex-tui ``` ```bash theme={null} cargo insta pending-snapshots -p codex-tui ``` Review the generated `*.snap.new` files directly, or preview a specific file: ```bash theme={null} cargo insta show -p codex-tui path/to/file.snap.new ``` Only accept if you've verified the changes are correct: ```bash theme={null} cargo insta accept -p codex-tui ``` If you don't have the tool installed: ```bash theme={null} cargo install cargo-insta ``` ### Test Assertions Best Practices ```rust Use pretty_assertions theme={null} use pretty_assertions::assert_eq; #[test] fn test_example() { let result = calculate_something(); let expected = ExpectedStruct { /* ... */ }; // Prefer deep equals on entire objects assert_eq!(result, expected); } ``` ```rust Avoid field-by-field assertions theme={null} // Don't do this: assert_eq!(result.field1, expected.field1); assert_eq!(result.field2, expected.field2); // Do this instead: assert_eq!(result, expected); ``` ### Integration Tests When writing end-to-end Codex tests, use the utilities in `core_test_support::responses`. ```rust Typical test pattern theme={null} use core_test_support::responses; #[tokio::test] async fn test_function_call() -> Result<()> { let mock = responses::mount_sse_once(&server, responses::sse(vec![ responses::ev_response_created("resp-1"), responses::ev_function_call(call_id, "shell", &serde_json::to_string(&args)?), responses::ev_completed("resp-1"), ])).await; codex.submit(Op::UserTurn { /* ... */ }).await?; // Assert request body let request = mock.single_request(); assert_eq!(request.function_call_output(call_id)?, expected_output); Ok(()) } ``` ```rust Response mock helpers theme={null} // All mount_sse* helpers return a ResponseMock let mock = responses::mount_sse_once(&server, payload).await; // Single POST assertion let request = mock.single_request(); // Multiple POST assertions let requests = mock.requests(); // Inspect structured payloads request.body_json()? request.input()? request.function_call_output(call_id)? request.custom_tool_call_output(call_id)? request.call_output(call_id)? request.header("X-Custom")? request.path() request.query_param("key") ``` **Best practices for integration tests:** * Prefer `wait_for_event` over `wait_for_event_with_timeout` * Prefer `mount_sse_once` over `mount_sse_once_match` or `mount_sse_sequence` * Avoid mutating process environment in tests ### Spawning Workspace Binaries in Tests Use `codex_utils_cargo_bin::cargo_bin("...")` instead of `assert_cmd::Command::cargo_bin(...)` when tests need to spawn first-party binaries. ```rust theme={null} use codex_utils_cargo_bin::cargo_bin; #[test] fn test_cli_binary() { let codex_bin = cargo_bin("codex"); // Use codex_bin path... } ``` This ensures paths resolve correctly under both Cargo and Bazel runfiles. ## TypeScript Testing The TypeScript implementation is **legacy**. This section is for reference only. The TypeScript CLI uses **Vitest** for unit tests. ### Running TypeScript Tests ```bash Watch mode (recommended) theme={null} pnpm test:watch ``` ```bash Single run theme={null} pnpm test ``` ```bash With type checking theme={null} pnpm test && pnpm typecheck ``` ```bash Full validation suite theme={null} pnpm test && pnpm run lint && pnpm run typecheck ``` ### Git Hooks The TypeScript project uses [Husky](https://typicode.github.io/husky/) to enforce code quality: * **Pre-commit hook:** Runs lint-staged to format and lint files * **Pre-push hook:** Runs tests and type checking These hooks help maintain code quality and prevent pushing code with failing tests. ## App-Server Protocol Testing After changing API shapes in `app-server-protocol`: ```bash theme={null} just write-app-server-schema # If experimental API fixtures are affected: just write-app-server-schema --experimental ``` ```bash theme={null} cargo test -p codex-app-server-protocol ``` ## Sandbox Testing Test commands under the Codex sandbox using dedicated subcommands: ```bash macOS Seatbelt theme={null} codex sandbox macos [--full-auto] [--log-denials] [COMMAND]... # Legacy alias codex debug seatbelt [--full-auto] [--log-denials] [COMMAND]... ``` ```bash Linux Landlock theme={null} codex sandbox linux [--full-auto] [COMMAND]... # Legacy alias codex debug landlock [--full-auto] [COMMAND]... ``` ```bash Windows theme={null} codex sandbox windows [--full-auto] [COMMAND]... ``` Use `--log-denials` on macOS to see what file accesses are being blocked by Seatbelt. ## Before Submitting a PR Before marking your PR as ready for review, run all checks locally: ```bash theme={null} # Format code just fmt # Fix linter issues just fix -p # Run tests cargo test -p # If you changed core crates: cargo test ``` ```bash theme={null} # Run full validation suite pnpm test && pnpm run lint && pnpm run typecheck ``` CI failures that could have been caught locally slow down the review process. Always run checks before pushing. ## Next Steps Review contribution guidelines Learn how to build the project # Apps & Connectors Source: https://openai-codex.mintlify.app/features/apps-connectors Connect Codex to external services and ChatGPT apps for enhanced capabilities ## What are Apps & Connectors? Apps & Connectors allow Codex to integrate with external services and ChatGPT apps, extending its capabilities beyond the terminal. This feature enables Codex to access data from connected services and use tools provided by ChatGPT apps. Apps & Connectors bring ChatGPT's ecosystem of integrations into your command-line workflow. ## Using Connectors in Composer The easiest way to use apps is through the composer with the `$` prefix. ### Inserting a Connector Type `$` in the composer to trigger the connector popover: Start typing your prompt in Codex. ```bash theme={null} > $ ``` A popover appears listing accessible apps. Use arrow keys to navigate and press Enter to select an app. The connector is inserted into your prompt: ```bash theme={null} > $MyApp Tell me about recent notifications ``` ### Which Apps Appear? The popover lists: * **Connected apps** - Apps you've already authorized, labeled as "connected" * **Available apps** - Apps that can be installed Connected apps appear first for easy access. ## Managing Apps Use the `/apps` slash command to manage your connected apps. ### Listing Available Apps ```bash theme={null} > /apps ``` This shows: * All available ChatGPT apps * Which apps are currently connected * Which apps can be installed ### Example Output ``` Available Apps: 1. GitHub (connected) - Access repository data and create issues 2. Linear (connected) - Query and update Linear issues 3. Slack - Send messages and search conversations - Status: Can be installed 4. Google Calendar - Read and create calendar events - Status: Can be installed ``` ## Configuring MCP Servers Codex can connect to Model Context Protocol (MCP) servers configured in `~/.codex/config.toml`. ### What is MCP? The Model Context Protocol is a standardized way for AI applications to connect to external data sources and tools. MCP servers expose resources and tools that Codex can use. ### Configuration Add MCP server configuration to your `config.toml`: ```toml theme={null} # ~/.codex/config.toml [[mcp_servers]] name = "filesystem" command = "npx" args = ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/directory"] env = {} [[mcp_servers]] name = "github" command = "npx" args = ["-y", "@modelcontextprotocol/server-github"] env = { GITHUB_TOKEN = "${GITHUB_TOKEN}" } ``` ### Available MCP Servers Popular MCP servers include: `@modelcontextprotocol/server-filesystem` Provides file system access to specified directories. `@modelcontextprotocol/server-github` Access GitHub repositories, issues, and pull requests. `@modelcontextprotocol/server-gdrive` Read and write Google Drive documents. `@modelcontextprotocol/server-slack` Send messages and search Slack conversations. See the [MCP documentation](https://modelcontextprotocol.io/) for a complete list of available servers. ### Managing MCP Servers via CLI Codex provides commands to manage MCP servers: ```bash theme={null} # List configured MCP servers codex mcp list # Add a new MCP server codex mcp add [args...] # Get details about a specific MCP server codex mcp get # Remove an MCP server codex mcp remove ``` ### Example: Adding GitHub MCP Server ```bash theme={null} codex mcp add github npx -y @modelcontextprotocol/server-github ``` ## Using Codex as an MCP Server Codex can also function as an MCP server, allowing other MCP clients to use Codex as a tool. ### Starting the MCP Server ```bash theme={null} codex mcp-server ``` This launches Codex in MCP server mode, exposing its capabilities to other agents. ### Testing with MCP Inspector Test Codex as an MCP server using the official inspector: ```bash theme={null} npx @modelcontextprotocol/inspector codex mcp-server ``` This opens a web interface where you can: * See available tools * Test tool calls * View responses ### Using Codex as a Tool Other agents can use Codex to: * Execute code in a sandboxed environment * Analyze codebases * Perform refactoring * Generate code with context awareness ## Common Use Cases ### Querying External Services ```bash theme={null} > $GitHub List all open PRs in the openai/codex repository ``` ```bash theme={null} > $Linear Show me all high-priority issues assigned to me ``` ### Integrating Data into Code ```bash theme={null} > $GoogleSheets Read the data from the "Sales Q1" sheet and generate a Python script to analyze it ``` ### Cross-Service Workflows ```bash theme={null} > $GitHub Get the latest issues labeled "bug" and $Linear create corresponding Linear issues for them ``` ## Configuration Reference ### Full MCP Server Configuration ```toml theme={null} # ~/.codex/config.toml [[mcp_servers]] # Name used to identify the server name = "my-service" # Command to launch the MCP server command = "node" # Arguments passed to the command args = ["/path/to/mcp-server.js"] # Environment variables env = { API_KEY = "${MY_API_KEY}", # Can reference env vars BASE_URL = "https://api.example.com" } # Optional: Working directory workdir = "/path/to/working/directory" # Optional: Timeout in seconds timeout = 30 ``` ### Environment Variable Substitution MCP server configurations support environment variable substitution: ```toml theme={null} [[mcp_servers]] name = "authenticated-service" command = "npx" args = ["-y", "@company/mcp-server"] env = { API_KEY = "${COMPANY_API_KEY}", ENDPOINT = "${COMPANY_ENDPOINT}" } ``` Codex will substitute `${VAR_NAME}` with the value from your environment. ## Security Considerations Apps and MCP servers can access external services on your behalf. Only connect apps you trust and review permissions carefully. ### Best Practices Before connecting an app, review what data it can access and what actions it can perform. Store API keys and tokens in environment variables, not directly in config.toml: ```toml theme={null} env = { API_KEY = "${MY_SECRET_KEY}" } ``` For filesystem servers, only grant access to specific directories: ```toml theme={null} args = ["-y", "@modelcontextprotocol/server-filesystem", "~/Documents/safe-directory"] ``` Periodically review connected apps with `/apps` and disconnect ones you no longer use. ## Troubleshooting ### App Not Appearing in Popover 1. Verify the app is installed and connected 2. Run `/apps` to check connection status 3. Restart Codex to refresh app connections ### MCP Server Connection Failed 1. Check that the server command is correct and accessible: ```bash theme={null} # Test the command directly npx -y @modelcontextprotocol/server-github ``` 2. Verify environment variables are set: ```bash theme={null} echo $GITHUB_TOKEN ``` 3. Check Codex logs for detailed error messages: ```bash theme={null} RUST_LOG=debug codex ``` ### Permission Errors 1. Ensure API keys have the necessary permissions 2. Check that OAuth tokens haven't expired 3. Re-authenticate the app if needed ## Examples ### Example: GitHub Integration ```toml theme={null} # ~/.codex/config.toml [[mcp_servers]] name = "github" command = "npx" args = ["-y", "@modelcontextprotocol/server-github"] env = { GITHUB_TOKEN = "${GITHUB_TOKEN}" } ``` Usage: ```bash theme={null} > $GitHub List all open issues with label "bug" in openai/codex > Create a summary of the most common issues ``` ### Example: Notion Integration ```toml theme={null} # ~/.codex/config.toml [[mcp_servers]] name = "notion" command = "npx" args = ["-y", "@notionhq/mcp-server-notion"] env = { NOTION_API_KEY = "${NOTION_API_KEY}" } ``` Usage: ```bash theme={null} > $Notion Read the contents of my "Project Ideas" database and create a prioritized TODO list ``` ### Example: Custom MCP Server ```toml theme={null} # ~/.codex/config.toml [[mcp_servers]] name = "company-api" command = "python" args = ["/opt/mcp-servers/company_api.py"] env = { API_KEY = "${COMPANY_API_KEY}", ENVIRONMENT = "production" } workdir = "/opt/mcp-servers" ``` Usage: ```bash theme={null} > $company-api Fetch customer data for account ID 12345 and generate a usage report ``` ## Next Steps Learn more about the Model Context Protocol Complete configuration reference Create skills that use MCP servers Understand Codex's security model # Code Review Source: https://openai-codex.mintlify.app/features/code-review Get AI-powered code reviews that catch bugs, security issues, and maintainability problems ## What is Code Review? Codex includes a specialized code review mode that analyzes your changes for bugs, security vulnerabilities, and maintainability issues. It provides structured feedback with priority levels, helping you catch problems before they reach production. Code review in Codex is powered by a dedicated review agent with specialized instructions focused on finding actionable issues. ## Starting a Review Trigger a code review using the `/review` slash command: ```bash theme={null} > /review ``` Codex will: 1. Analyze your current changes (staged and unstaged) 2. Spawn a sub-agent with specialized review instructions 3. Provide structured feedback with priority levels 4. Output an overall correctness verdict 5. Automatically exit review mode when complete ## How It Works When you run `/review`, Codex enters a specialized review mode. A dedicated review sub-agent is created with: * Specialized review prompt and guidelines * Auto-approval enabled (no interruptions) * Web search and collaborative tools disabled * Custom review model (if configured) The review agent analyzes your changes, looking for: * Bugs and logic errors * Security vulnerabilities * Performance issues * Maintainability problems * Style violations (only if they obscure meaning) The agent provides findings with: * Priority level (P0-P3) * Clear title and description * Code location (file and line range) * Confidence score * Suggestion blocks (when applicable) An overall correctness assessment: * "Patch is correct" - No blocking issues found * "Patch is incorrect" - Blocking issues that must be addressed ## Review Output Format ### Finding Structure Each finding includes: * **Title**: Short, imperative description (≤80 chars) with priority tag * **Body**: Explanation of why it's a problem, with file/line/function references * **Priority**: P0 (critical) to P3 (nice-to-have) * **Confidence Score**: 0.0-1.0 indicating reviewer confidence * **Code Location**: Absolute file path and line range * **Suggestion Block** (optional): Concrete replacement code ### Priority Levels | Level | Description | When to Use | | ------ | ---------------------- | --------------------------------------------------------------- | | **P0** | Drop everything to fix | Blocking release, operations, or major usage. Universal issues. | | **P1** | Urgent | Should be addressed in the next cycle | | **P2** | Normal | To be fixed eventually | | **P3** | Low | Nice to have | ### Example Output ```` Review Findings: [P1] Unvalidated user input in database query The function `getUserById` in src/db.ts:42 uses user input directly in the SQL query without validation or parameterization, creating a SQL injection vulnerability. Attackers could execute arbitrary SQL commands. Location: src/db.ts:42-45 Confidence: 0.95 ```suggestion const result = await db.query( 'SELECT * FROM users WHERE id = $1', [userId] ); ```` *** \[P2] Missing error handling for async operation The `fetchData` call in src/api.ts:88 lacks error handling. If the request fails, the error will propagate unhandled, potentially crashing the application. Location: src/api.ts:88 Confidence: 0.85 ```suggestion theme={null} try { const data = await fetchData(url); return data; } catch (error) { logger.error('Failed to fetch data', { error }); throw new AppError('Data fetch failed', { cause: error }); } ``` *** Overall Correctness: Patch is incorrect The P1 security vulnerability must be addressed before merging. The P2 error handling issue should also be fixed to improve reliability. ```` ## Review Guidelines The review agent follows these principles: ### What Gets Flagged Issues are flagged when they: 1. **Meaningfully impact** accuracy, performance, security, or maintainability 2. **Are discrete and actionable** (not general codebase issues) 3. **Match the codebase's rigor level** (don't demand excessive rigor for scripts) 4. **Were introduced in the current changes** (not pre-existing bugs) 5. **The author would likely fix** if made aware 6. **Don't rely on unstated assumptions** about the codebase 7. **Are provably affected** (not just speculation) 8. **Aren't intentional changes** by the author ### What Doesn't Get Flagged - Trivial style issues (unless they obscure meaning) - Personal preferences - Issues that violate unstated conventions - Pre-existing bugs not touched by this change - Speculative problems without concrete evidence - Intentional design decisions ### Comment Guidelines Review comments: 1. Are **clear about why** the issue is a bug 2. **Appropriately communicate severity** (no exaggeration) 3. Are **brief** (body is at most 1 paragraph) 4. Include **code chunks ≤3 lines** (use inline code or blocks) 5. **Explicitly state scenarios** where the bug arises 6. Use **matter-of-fact tone** (not accusatory or overly positive) 7. Are **immediately graspable** without close reading 8. **Avoid excessive flattery** and unhelpful comments ## Configuration ### Using a Different Review Model You can configure a specific model for code review: ```toml # ~/.codex/config.toml # Use a more powerful model for reviews review_model = "gpt-4o" # Or use a specialized reasoning model review_model = "o1-mini" ```` If not set, reviews use the same model as your current session. ### Custom Review Guidelines Add project-specific review guidelines to your `AGENTS.md`: ```markdown theme={null} # Code Review Guidelines ## Security - All database queries must use parameterized statements - Never log sensitive data (passwords, API keys, PII) - All user input must be validated before processing ## Performance - Database queries in loops are not allowed - Large datasets (>1000 items) must be paginated - Heavy computations should be async or background jobs ## Testing - All public API endpoints must have integration tests - Business logic must have unit test coverage - Mock external services in tests ``` The review agent will see these guidelines and apply them. ## Use Cases ### Pre-Commit Review ```bash theme={null} # Make your changes git add . # Run review before committing codex > /review # Address any findings # Commit when review passes git commit -m "Add user authentication" ``` ### PR Review ```bash theme={null} # Checkout the PR branch git checkout feature-branch # Review the changes codex > /review # Leave feedback or approve ``` ### CI Integration Run code review in CI/CD pipelines: ```yaml theme={null} # .github/workflows/review.yml name: Code Review on: [pull_request] jobs: review: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Run Codex Review run: | codex exec "/review" --ephemeral env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} ``` ## Advanced Usage ### Reviewing Specific Files Review only specific files: ```bash theme={null} > /review > "Review only the changes in src/auth/" ``` ### Focused Review Ask for a focused review: ```bash theme={null} > /review > "Focus on security vulnerabilities" ``` ```bash theme={null} > /review > "Check for performance issues only" ``` ### Re-reviewing After Fixes ```bash theme={null} # First review > /review # Fix the issues # ... # Review again > /review > "Verify that the P1 security issue is fixed" ``` ## Interpreting Results ### Overall Correctness: "Patch is correct" Meaning: * No blocking issues found * Existing code and tests won't break * The patch is free of bugs and blocking problems * Non-blocking issues (style, formatting, nits) are ignored You can proceed with confidence. ### Overall Correctness: "Patch is incorrect" Meaning: * At least one blocking issue (usually P0 or P1) was found * The issue will cause bugs, security problems, or breakage * You should address the findings before merging Review the findings and fix blocking issues. ### Confidence Scores Each finding includes a confidence score (0.0-1.0): * **0.9-1.0**: Very confident - almost certainly a real issue * **0.7-0.9**: Confident - likely a real issue * **0.5-0.7**: Moderate confidence - worth investigating * **Less than 0.5**: Low confidence - may be a false positive Prioritize high-confidence findings. ## Tips for Better Reviews Stage related changes together for more coherent reviews: ```bash theme={null} # Review authentication changes git add src/auth/ codex > /review # Then review API changes separately git add src/api/ codex > /review ``` Give the reviewer context about your changes: ```bash theme={null} > /review > "This refactors the authentication system to use JWT tokens instead of sessions. The old session code is being removed." ``` For large changes, review in stages: 1. Review the core logic first 2. Then review the integration 3. Finally review tests and documentation Document your standards in AGENTS.md so the reviewer knows what to look for. Configure a reasoning model for more thorough reviews: ```toml theme={null} review_model = "o1-mini" ``` ## Limitations Code review is a helpful tool but not a replacement for human review, especially for: * Architecture decisions * API design * User experience considerations * Business logic correctness * Complex domain-specific requirements Best used as: * A first pass to catch obvious issues * A sanity check before requesting human review * A teaching tool to learn about common mistakes ## Next Steps Learn about other slash commands Configure review model and settings Add project-specific review guidelines Integrate code review into your pipeline # Memory & Project Docs Source: https://openai-codex.mintlify.app/features/memory Give Codex persistent context and guidance through AGENTS.md files ## What is Memory? Codex can remember project-specific instructions, preferences, and context through `AGENTS.md` files. These files act as "project documentation for AI agents" and help Codex understand your codebase, workflows, and conventions. Think of `AGENTS.md` as persistent memory that travels with your project—Codex reads these files on startup and uses them to inform every action. ## How AGENTS.md Files Work Codex looks for `AGENTS.md` files in multiple locations and merges them top-down: `~/.codex/AGENTS.md` - Personal preferences that apply to all projects `AGENTS.md` at repo root - Shared project notes for all team members `AGENTS.md` in the current working directory - Sub-folder/feature specifics All three files are merged together, with more specific (closer) files taking priority when there are conflicts. ## Use Cases ### Personal Preferences (\~/.codex/AGENTS.md) Your global `AGENTS.md` file can include personal coding preferences: ```markdown theme={null} # Personal Coding Preferences - Always use functional components in React (no class components) - Prefer `const` over `let` unless mutation is necessary - Use Prettier for formatting with 2-space indentation - Write descriptive commit messages in conventional commit format - Only use git commands when explicitly requested ``` ### Project Standards (Project Root AGENTS.md) The project-level file should document team conventions: ```markdown theme={null} # Project Guidelines ## Architecture This is a Next.js application with: - `/app` - Next.js app router pages - `/components` - Reusable React components - `/lib` - Utility functions and helpers - `/api` - API route handlers ## Coding Standards - Use TypeScript for all new files - Follow the ESLint configuration (run `npm run lint`) - Write unit tests for business logic in `__tests__` directories - Use Tailwind CSS for styling (no inline styles) ## Database We use Prisma with PostgreSQL. Schema lives in `prisma/schema.prisma`. Always run `npx prisma migrate dev` after schema changes. ## Testing Run tests with `npm test` before committing. We use: - Vitest for unit tests - Playwright for E2E tests ## Deployment Deploys happen automatically via Vercel when merging to `main`. Staging environment: `staging` branch ``` ### Feature-Specific Context (Subdirectory AGENTS.md) Add context for specific parts of the codebase: ```markdown theme={null} # Authentication Module This directory implements authentication using NextAuth.js. ## Key Files - `auth-config.ts` - NextAuth configuration - `auth-provider.tsx` - React context provider - `middleware.ts` - Auth middleware for protected routes ## Important Notes - Never modify the session token structure without updating the middleware - All auth errors should be logged to Sentry - Password reset emails use the template in `/emails/reset-password.tsx` ## Testing Auth Use the test accounts in `.env.test` for local testing. ``` ## What to Include Explain the organization of your codebase: * Key directories and their purposes * Where different types of files live * How modules are organized Document the technologies you're using: * Frameworks and libraries * Package managers and build tools * Runtime environments and versions Define your conventions: * Code style and formatting rules * Naming conventions * File organization patterns * Testing requirements Explain processes and procedures: * How to run the project locally * Testing and linting commands * Build and deployment processes * Git workflow and branching strategy Provide context-specific information: * Business logic and rules * API integrations and authentication * Database schemas and relationships * External services and their purposes Warn about common mistakes: * Known bugs or limitations * Performance considerations * Security requirements * Things that are easy to break ## Best Practices ### Keep It Concise Codex's context window is limited. Include only information that: * Isn't obvious from the code itself * Codex would struggle to infer * Affects how Codex should work Don't duplicate information that's already in documentation, comments, or the code. Focus on conventions, workflows, and non-obvious context. ### Use Clear Structure Organize your AGENTS.md with headers: ```markdown theme={null} # Project Name ## Architecture ... ## Coding Standards ... ## Testing ... ``` ### Be Specific Instead of: ```markdown theme={null} - Use TypeScript ``` Write: ```markdown theme={null} - Use TypeScript with strict mode enabled - All API responses must have defined types in `/types/api.ts` - Use Zod for runtime validation of external data ``` ### Include Examples Codex learns better from examples: ````markdown theme={null} ## Error Handling Wrap async operations in try-catch blocks and log errors: ```typescript try { const result = await fetchData(); return result; } catch (error) { logger.error('Failed to fetch data', { error }); throw new AppError('Data fetch failed', { cause: error }); } ```` ```` ## Advanced Usage ### Conditional Instructions You can include instructions that apply only in certain contexts: ```markdown ## API Development When working with API routes: - All routes must have request validation using Zod - Use the middleware in `/lib/api-middleware.ts` - Return errors in the format: `{ error: string, code: string }` ## Frontend Development When working with React components: - Use the custom hooks in `/hooks` for common patterns - Keep components under 200 lines (split if larger) - Use Storybook for component development ```` ### Tool-Specific Configuration ```markdown theme={null} ## Database Migrations Always use Prisma for database changes: 1. Update `prisma/schema.prisma` 2. Run `npx prisma migrate dev --name descriptive-name` 3. Review the generated migration SQL 4. Test locally before committing Never modify migration files after they're committed. ``` ### Team Conventions ```markdown theme={null} ## Pull Request Guidelines - PR titles must follow conventional commits format - Include a description of what changed and why - Link to the relevant Linear issue - Request review from @team-backend for API changes - Request review from @team-frontend for UI changes ## Commit Messages Format: `type(scope): description` Examples: - `feat(auth): add password reset flow` - `fix(api): handle null user in session` - `docs(readme): update installation steps` ``` ## Disabling Project Docs If you want Codex to ignore AGENTS.md files: ### Via Command Line ```bash theme={null} codex --no-project-doc ``` ### Via Environment Variable ```bash theme={null} export CODEX_DISABLE_PROJECT_DOC=1 codex ``` ### In Configuration ```toml theme={null} # ~/.codex/config.toml [project_docs] enabled = false ``` ## Examples ### Example: TypeScript Project ```markdown theme={null} # TypeScript Project Guidelines ## Structure - `/src` - Source code - `/src/types` - TypeScript type definitions - `/tests` - Test files (use `.test.ts` suffix) - `/build` - Compiled output (gitignored) ## TypeScript Configuration - Use `strict: true` mode - Prefer `type` over `interface` for object types - Use `unknown` instead of `any` for truly unknown types - Export types alongside implementations ## Testing Run `npm test` to run all tests. Run `npm run test:watch` during development. All public functions should have unit tests. ``` ### Example: Python/Django Project ````markdown theme={null} # Django Project Guidelines ## Apps - `users/` - User authentication and profiles - `api/` - REST API endpoints - `core/` - Shared utilities and models ## Django Conventions - All models must have `__str__` methods - Use class-based views for complex views - Use function-based views for simple views - Migrations should be reviewed before committing ## Database We use PostgreSQL. Local database: `codex_dev` Create migrations: ```bash python manage.py makemigrations python manage.py migrate ```` ## Testing Run tests: ```bash theme={null} python manage.py test ``` Use factories from `tests/factories.py` for test data. ```` ### Example: Monorepo ```markdown # Monorepo Structure This is a pnpm monorepo with multiple packages: - `/packages/ui` - Shared React component library - `/packages/utils` - Shared utility functions - `/apps/web` - Main Next.js application - `/apps/admin` - Admin dashboard ## Working with Packages Install dependencies from the root: ```bash pnpm install ```` Add a dependency to a specific package: ```bash theme={null} pnpm add --filter @myapp/web ``` ## Building Build all packages: ```bash theme={null} pnpm build ``` Build a specific package: ```bash theme={null} pnpm --filter @myapp/ui build ``` ``` ## Tips for Effective Memory Begin with a minimal AGENTS.md and add to it as you discover what Codex needs to know. Keep AGENTS.md in sync with your project as it evolves. Stale information is worse than no information. Generic advice like "write good code" doesn't help. Specific conventions and examples do. After updating AGENTS.md, test that Codex follows the new instructions by asking it to perform relevant tasks. ## AGENTS.md vs Skills Both AGENTS.md and Skills provide context to Codex, but they serve different purposes: | AGENTS.md | Skills | |-----------|--------| | Project-specific context | Reusable, domain-specific knowledge | | Always loaded | Loaded on-demand when relevant | | Lightweight guidelines | Can include scripts, references, and assets | | Personal or project preferences | Procedural knowledge and workflows | | Easy to edit (just a markdown file) | More structured (requires SKILL.md format) | **Use AGENTS.md for:** Project conventions, team preferences, codebase structure **Use Skills for:** Reusable workflows, tool integrations, complex procedures ## Next Steps Learn about skills for reusable workflows Configure Codex for your project ``` # Skills Source: https://openai-codex.mintlify.app/features/skills Extend Codex with specialized knowledge, workflows, and tool integrations through modular skill packages ## What are Skills? Skills are modular, self-contained folders that extend Codex's capabilities by providing specialized knowledge, workflows, and tools. Think of them as "onboarding guides" for specific domains or tasks—they transform Codex from a general-purpose agent into a specialized agent equipped with procedural knowledge. ### What Skills Provide Skills can include: 1. **Specialized workflows** - Multi-step procedures for specific domains 2. **Tool integrations** - Instructions for working with specific file formats or APIs 3. **Domain expertise** - Company-specific knowledge, schemas, business logic 4. **Bundled resources** - Scripts, references, and assets for complex and repetitive tasks ## How Skills Work Skills use a three-level progressive disclosure system to manage context efficiently: Always loaded in context (\~100 words). This helps Codex determine when to use the skill. Loaded when the skill triggers (less than 5k words). Contains instructions and workflows. Loaded as needed by Codex. Scripts can be executed without reading into context. ## Skill Structure Every skill follows this structure: ``` skill-name/ ├── SKILL.md (required) │ ├── YAML frontmatter metadata (required) │ │ ├── name: (required) │ │ └── description: (required) │ └── Markdown instructions (required) ├── agents/ (recommended) │ └── openai.yaml - UI metadata for skill lists └── Bundled Resources (optional) ├── scripts/ - Executable code (Python/Bash/etc.) ├── references/ - Documentation loaded as needed └── assets/ - Files used in output (templates, icons, etc.) ``` ### SKILL.md (Required) The main skill file consists of: * **Frontmatter (YAML)**: Contains `name` and `description` fields. These are critical—Codex reads them to determine when to use the skill. * **Body (Markdown)**: Instructions and guidance for using the skill. Only loaded after the skill triggers. The description in the frontmatter is the primary triggering mechanism. Include both what the skill does and specific triggers/contexts for when to use it. ### Bundled Resources (Optional) Executable code for tasks requiring deterministic reliability. Token efficient and may be executed without loading into context. Example: `scripts/rotate_pdf.py` for PDF rotation Documentation loaded as needed to inform Codex's process. Keeps SKILL.md lean. Example: `references/api_docs.md` for API specifications Files used in output, not loaded into context. Example: `assets/logo.png` for brand assets ## Installing Skills Skills are stored in `$CODEX_HOME/skills/` (typically `~/.codex/skills/`). ### System Skills (Built-in) Codex comes with built-in system skills that are automatically installed to `$CODEX_HOME/skills/.system/` on startup. These include: * **skill-creator**: Guide for creating effective skills * **skill-installer**: Install skills from GitHub repositories System skills are updated automatically when you update Codex. ### Installing Additional Skills Use the built-in `skill-installer` skill to install additional skills: ```bash List Available Skills theme={null} # In Codex, type: /use skill-installer "List available skills" ``` ```bash Install a Skill theme={null} # In Codex, type: "Install the [skill-name] skill" ``` ```bash Install from GitHub theme={null} # Install from a GitHub repository: "Install the skill from github.com/owner/repo/path/to/skill" ``` After installing a new skill, restart Codex to pick it up. ## Creating a Skill Codex includes a built-in `skill-creator` skill that guides you through the skill creation process. ### Quick Start ```bash theme={null} /use skill-creator ``` Tell Codex what you want the skill to do and provide examples: "I want to create a skill for rotating and editing PDF files. Users should be able to say things like 'rotate this PDF 90 degrees' or 'extract text from this PDF'." Codex will: * Plan the reusable skill contents (scripts, references, assets) * Initialize the skill directory with proper structure * Generate SKILL.md with frontmatter and instructions * Create any necessary helper scripts ```bash theme={null} # Codex will run validation automatically scripts/quick_validate.py path/to/skill-folder ``` ### Skill Creation Process The skill-creator follows this workflow: 1. **Understand the skill** - Gather concrete examples of how the skill will be used 2. **Plan reusable contents** - Identify scripts, references, and assets needed 3. **Initialize the skill** - Run `init_skill.py` to create the structure 4. **Edit the skill** - Implement resources and write SKILL.md 5. **Validate the skill** - Run `quick_validate.py` to check for issues 6. **Iterate** - Test on real tasks and improve based on feedback ## Skill Design Principles ### Concise is Key The context window is a public good. Skills share it with everything else Codex needs: system prompt, conversation history, other skills' metadata, and the actual user request. Default assumption: Codex is already very smart. Only add context Codex doesn't already have. Challenge each piece of information: "Does Codex really need this explanation?" Prefer concise examples over verbose explanations. ### Progressive Disclosure Keep SKILL.md under 500 lines. When approaching this limit, split content into separate files: ```markdown Pattern 1: High-level guide with references theme={null} # PDF Processing ## Quick start Extract text with pdfplumber: [code example] ## Advanced features - **Form filling**: See [FORMS.md](FORMS.md) for complete guide - **API reference**: See [REFERENCE.md](REFERENCE.md) for all methods ``` ```markdown Pattern 2: Domain-specific organization theme={null} # BigQuery Skill For domain-specific queries, see: - **Finance metrics**: See references/finance.md - **Sales data**: See references/sales.md - **Product analytics**: See references/product.md ``` ### Set Appropriate Degrees of Freedom Match the level of specificity to the task's fragility: * **High freedom** (text instructions): Multiple approaches are valid, decisions depend on context * **Medium freedom** (pseudocode/parameterized scripts): Preferred pattern exists, some variation acceptable * **Low freedom** (specific scripts): Operations are fragile, consistency is critical ## Using Skills ### Automatic Triggering Codex automatically loads skills based on the context of your request. The skill's `description` in the frontmatter determines when it triggers. ### Manual Loading You can explicitly load a skill using the `/use` command: ```bash theme={null} /use skill-name ``` This ensures the skill is loaded for your current task. ## Managing Skills ### Disabling Project Docs Skills can be disabled using: ```bash theme={null} codex --no-project-doc ``` Or set the environment variable: ```bash theme={null} export CODEX_DISABLE_PROJECT_DOC=1 ``` ### Skills Location Skills are installed to: * **User skills**: `$CODEX_HOME/skills/` (typically `~/.codex/skills/`) * **System skills**: `$CODEX_HOME/skills/.system/` (auto-installed) ## Examples ### Example: PDF Editor Skill A skill for PDF operations: ```yaml theme={null} --- name: pdf-editor description: Edit and manipulate PDF files. Use when the user needs to rotate, merge, extract text, or perform other PDF operations. --- ``` Bundled resources: * `scripts/rotate_pdf.py` - Rotate PDF pages * `scripts/merge_pdfs.py` - Merge multiple PDFs * `references/pdf_operations.md` - Advanced PDF manipulation guide ### Example: BigQuery Skill A skill for querying a company database: ```yaml theme={null} --- name: bigquery-analytics description: Query company BigQuery database for analytics. Use when the user asks questions about user metrics, revenue, or product usage data. --- ``` Bundled resources: * `references/schema.md` - Database schema documentation * `references/finance.md` - Finance and revenue metrics * `references/product.md` - Product usage metrics ## Best Practices Each skill should have a clear, single purpose. Don't create mega-skills that try to do everything. Always test bundled scripts by running them to ensure they work correctly. Scripts should be deterministic and reliable. Information should live in either SKILL.md or reference files, not both. Prefer reference files for detailed information. Don't create README.md, CHANGELOG.md, or other auxiliary documentation. Skills should only contain information needed for the AI agent to do the job. Use lowercase letters, digits, and hyphens only. Prefer short, verb-led phrases that describe the action (e.g., `rotate-pdf`, not `pdf-rotation-tool`). ## Next Steps Follow the step-by-step guide to create a custom skill Explore curated skills in the official skills repository # Slash Commands Source: https://openai-codex.mintlify.app/features/slash-commands Control Codex with special commands that modify behavior, manage state, and trigger specific features ## What are Slash Commands? Slash commands are special commands that start with `/` and give you control over Codex's behavior. They're used to modify settings, manage conversation state, trigger specific features, and control the agent's workflow. Slash commands are entered in the Codex prompt and are processed before being sent to the AI model. ## Available Commands ### Workflow Control Triggers a specialized code review of your changes. ```bash theme={null} /review ``` **What it does:** * Spawns a sub-agent with specialized review instructions * Analyzes your code changes for bugs, security issues, and maintainability problems * Provides structured feedback with priority levels (P0-P3) * Outputs an overall correctness verdict * Exits automatically when review is complete **Features:** * Uses dedicated review prompt and model * Can be configured with custom review model via `review_model` in config * Auto-approval enabled (no interruptions during review) * Web search and collaborative tools disabled for focused review See [Code Review](/features/code-review) for detailed usage. Explicitly load a specific skill for the current task. ```bash theme={null} /use skill-name ``` **Examples:** ```bash theme={null} /use pdf-editor /use skill-creator /use bigquery-analytics ``` This ensures the skill is loaded into context even if it wouldn't trigger automatically. Lists available and installed ChatGPT app connectors. ```bash theme={null} /apps ``` Shows: * Connected apps (labeled as "connected") * Available apps that can be installed See [Apps & Connectors](/features/apps-connectors) for more details. ### Session Management Clears the current conversation history while keeping configuration. ```bash theme={null} /clear ``` Useful when you want to start fresh without restarting Codex. Resets both conversation history and session state. ```bash theme={null} /reset ``` More thorough than `/clear` - resets all session state. ### Configuration Switch to a different AI model mid-conversation. ```bash theme={null} /model gpt-4o /model o1-mini /model claude-3-5-sonnet-20241022 ``` Changes the model for the current session without restarting. Change the approval policy for the current session. ```bash theme={null} /approval suggest /approval auto-edit /approval full-auto ``` **Approval modes:** * `suggest` - Agent asks for approval on all file writes and shell commands * `auto-edit` - Agent can write files but asks before running commands * `full-auto` - Agent can write files and run commands (sandboxed) Adjust the sandbox policy for the current session. ```bash theme={null} /sandbox read-only /sandbox workspace-write /sandbox danger-full-access ``` See [Security & Sandboxing](/core-concepts/security) for details on each mode. ### Information Display help information and available commands. ```bash theme={null} /help ``` Display current configuration and session state. ```bash theme={null} /status ``` Shows: * Current model * Approval mode * Sandbox mode * Active skills * Session information ## Using Slash Commands ### In the TUI Slash commands are entered at the prompt: ```bash theme={null} > /review > /use pdf-editor > /model gpt-4o ``` Press `Tab` for autocomplete suggestions when typing slash commands. ### In Scripts You can pass slash commands in non-interactive mode: ```bash theme={null} codex exec "/review" --ephemeral ``` ## Command Aliases Some commands have shorter aliases for convenience: | Command | Alias | | --------- | ----- | | `/review` | `/r` | | `/clear` | `/c` | | `/help` | `/h` | | `/status` | `/s` | ## Advanced Usage ### Combining Commands You can chain multiple commands in a single session: ```bash theme={null} > /clear > /model gpt-4o > /approval full-auto > "Now refactor the authentication module" ``` ### Commands in AGENTS.md You can include default slash commands in your `AGENTS.md` project documentation: ```markdown theme={null} # Project Configuration Always use the following settings: - Model: gpt-4o - Approval: auto-edit ``` This sets project-specific defaults without requiring manual slash commands each time. ## Creating Custom Commands While Codex doesn't currently support custom slash commands, you can achieve similar behavior using: 1. **Skills** - Create a skill that triggers on specific phrases 2. **AGENTS.md** - Add project-specific instructions 3. **Aliases** - Use shell aliases to wrap common command patterns ### Example: Custom Workflow Alias ```bash theme={null} # In your shell config (.bashrc, .zshrc, etc.) alias codex-review='codex exec "/review"' alias codex-fast='codex --model gpt-4o-mini --approval full-auto' ``` Then use: ```bash theme={null} codex-review codex-fast "write unit tests" ``` ## Command Reference * `/review` - Code review mode * `/use` - Load a skill * `/apps` - Manage app connectors * `/clear` - Clear history * `/reset` - Full reset * `/model` - Switch model * `/approval` - Change approval mode * `/sandbox` - Change sandbox mode * `/help` - Show help * `/status` - Show status ## Keyboard Shortcuts While not slash commands, these keyboard shortcuts work in the TUI: | Shortcut | Action | | --------- | ---------------------------------------------- | | `Ctrl+C` | Cancel current operation (press twice to quit) | | `Ctrl+D` | Exit Codex (press twice if needed) | | `Tab` | Autocomplete slash commands | | `↑` / `↓` | Navigate command history | | `Ctrl+L` | Clear screen (not history) | ## Best Practices Starting a new task? Use `/clear` to remove irrelevant context from the previous task. This helps Codex focus on what matters. For exploratory tasks, use `/approval suggest` to review each action. For well-defined tasks in sandboxed environments, use `/approval full-auto` for speed. If you know you need a specific skill, use `/use skill-name` at the start to ensure it's loaded, rather than relying on automatic triggering. If Codex behaves unexpectedly, use `/status` to verify your current configuration. ## Next Steps Learn more about the `/review` command Understand how skills work with `/use` # Installation Source: https://openai-codex.mintlify.app/installation Install Codex CLI on macOS, Linux, or Windows (via WSL2) # Installation Codex CLI can be installed using npm, Homebrew, or by downloading pre-built binaries for your platform. ## System requirements Before installing Codex CLI, ensure your system meets these requirements: | Requirement | Details | | --------------------- | ----------------------------------------------------------- | | **Operating systems** | macOS 12+, Ubuntu 20.04+/Debian 10+, or Windows 11 via WSL2 | | **Node.js** | 16 or newer (Node 20 LTS recommended for npm installation) | | **Git** (recommended) | 2.23+ for built-in PR helpers | | **RAM** | 4 GB minimum (8 GB recommended) | Codex CLI does not work directly on Windows. You must use Windows Subsystem for Linux (WSL2). See the [WSL installation guide](https://learn.microsoft.com/en-us/windows/wsl/install). ## Installation methods Install Codex CLI globally using your preferred package manager: ```bash npm theme={null} npm install -g @openai/codex ``` ```bash yarn theme={null} yarn global add @openai/codex ``` ```bash pnpm theme={null} pnpm add -g @openai/codex ``` ```bash bun theme={null} bun install -g @openai/codex ``` Never run `sudo npm install -g`. If you encounter permissions errors, fix your npm permissions instead. Verify that Codex is installed correctly: ```bash theme={null} codex --version ``` You should see the version number printed to your terminal. Install Codex CLI using Homebrew (macOS and Linux): ```bash theme={null} brew install --cask codex ``` Verify that Codex is installed correctly: ```bash theme={null} codex --version ``` You should see the version number printed to your terminal. Go to the [latest GitHub Release](https://github.com/openai/codex/releases/latest) and download the appropriate binary for your platform: **macOS** * Apple Silicon/arm64: `codex-aarch64-apple-darwin.tar.gz` * x86\_64 (older Mac hardware): `codex-x86_64-apple-darwin.tar.gz` **Linux** * x86\_64: `codex-x86_64-unknown-linux-musl.tar.gz` * arm64: `codex-aarch64-unknown-linux-musl.tar.gz` Extract the archive and rename the binary: ```bash theme={null} # Example for Linux x86_64 tar -xzf codex-x86_64-unknown-linux-musl.tar.gz mv codex-x86_64-unknown-linux-musl codex ``` Each archive contains a single entry with the platform name baked in, so you'll want to rename it to `codex`. Make the binary executable and move it to a directory in your PATH: ```bash theme={null} chmod +x codex sudo mv codex /usr/local/bin/ ``` Verify that Codex is installed correctly: ```bash theme={null} codex --version ``` You should see the version number printed to your terminal. Clone the Codex repository and navigate to the CLI package: ```bash theme={null} git clone https://github.com/openai/codex.git cd codex/codex-cli ``` Enable corepack and install dependencies: ```bash theme={null} corepack enable pnpm install ``` Build the CLI: ```bash theme={null} pnpm build ``` **Linux only:** Download prebuilt sandboxing binaries: ```bash theme={null} ./scripts/install_native_deps.sh ``` This requires `gh` (GitHub CLI) and `zstd`. Link the command globally for convenience: ```bash theme={null} pnpm link ``` Or run directly: ```bash theme={null} node ./dist/cli.js ``` ## Verify your installation After installation, verify that Codex is working by running: ```bash theme={null} codex --help ``` You should see the help output with available commands and options. ## Next steps Now that Codex is installed, [set up authentication](/authentication) to start using the CLI. Follow the [quickstart guide](/quickstart) to run your first commands. # Introduction to Codex CLI Source: https://openai-codex.mintlify.app/introduction A local coding agent from OpenAI that runs directly in your terminal # Introduction to Codex CLI Codex CLI is a coding agent from OpenAI that runs locally on your computer. It brings ChatGPT-level reasoning with the power to execute code, manipulate files, and iterate — all under version control. ## What is Codex CLI? Codex CLI is built for developers who live in the terminal and want ChatGPT-level reasoning with the ability to execute code, manipulate files, and iterate. It's chat-driven development that understands and executes your repo. Install Codex CLI and get up and running in minutes Sign in with ChatGPT or configure API key authentication Run your first commands and see Codex in action Learn about approval modes, sandboxing, and more ## Why use Codex CLI? Codex CLI is designed for developers who already work in the terminal and want powerful AI assistance without leaving their workflow. ### Key features **Zero setup** Bring your OpenAI API key or sign in with ChatGPT and it just works. No complex configuration required. **Safe and secure** Codex runs in a sandbox with network disabled and directory restrictions. Full auto-approval is safe because commands are isolated from your system. **Full auto-approval** Let Codex work autonomously while staying secure. In full auto mode, commands run network-disabled and directory-sandboxed. **Multimodal** Pass in screenshots or diagrams to implement features. Codex understands visual context. **Open source** Fully open source so you can see how it works and contribute to development. ## How it works Codex CLI operates in three approval modes, giving you control over how much autonomy the agent has: * **Suggest** (default): Codex reads files and suggests changes. You approve all file writes and shell commands. * **Auto Edit**: Codex reads and writes files automatically. You approve shell commands. * **Full Auto**: Codex reads, writes files, and executes commands. All operations run in a sandbox with network disabled. In full auto mode, every command runs network-disabled and confined to your working directory for defense-in-depth. Codex will warn you if you start in auto modes without Git tracking. ## Example use cases ```bash Refactor code theme={null} codex "Refactor the Dashboard component to React Hooks" ``` ```bash Generate migrations theme={null} codex "Generate SQL migrations for adding a users table" ``` ```bash Write tests theme={null} codex "Write unit tests for utils/date.ts" ``` ```bash Create an app theme={null} codex --approval-mode full-auto "create a fancy todo-list app" ``` Codex rewrites code, runs tests, generates files, and iterates until the task is complete. ## Next steps Follow the [installation guide](/installation) to get Codex running on your system. Sign in with ChatGPT or configure your API key using the [authentication guide](/authentication). Complete the [quickstart](/quickstart) to see Codex in action. # Quickstart Source: https://openai-codex.mintlify.app/quickstart Get up and running with Codex CLI in minutes # Quickstart This guide will help you get Codex CLI running and execute your first commands. You'll go from installation to your first AI-powered task in just a few minutes. ## Before you begin Make sure you have: * Codex CLI installed (see [Installation](/installation)) * A ChatGPT account (Plus, Pro, Team, Edu, or Enterprise) or an OpenAI API key * A terminal running macOS 12+, Linux (Ubuntu/Debian), or Windows 11 with WSL2 ## Get started with Codex Install Codex globally using npm or Homebrew: ```bash npm theme={null} npm install -g @openai/codex ``` ```bash Homebrew theme={null} brew install --cask codex ``` Verify the installation: ```bash theme={null} codex --version ``` Run `codex` and select **Sign in with ChatGPT**. This is the recommended method for using Codex with your ChatGPT plan. ```bash theme={null} codex ``` When you run this command, Codex will: 1. Start a local login server on `http://localhost` (random port) 2. Open your browser to authenticate 3. Complete authentication and return to the terminal We recommend signing into your ChatGPT account to use Codex as part of your Plus, Pro, Team, Edu, or Enterprise plan. [Learn more about what's included in your ChatGPT plan](https://help.openai.com/en/articles/11369540-codex-in-chatgpt). **On a remote or headless machine?** Use device code authentication instead: ```bash theme={null} codex login --device-auth ``` Alternatively, you can use an API key (see [Authentication](/authentication) for details). Once authenticated, run Codex interactively: ```bash theme={null} codex ``` Or provide a prompt directly: ```bash theme={null} codex "explain this codebase to me" ``` Codex will analyze your project and provide an explanation. Let's have Codex write a simple script. Try this command: ```bash theme={null} codex "create a simple Python script that prints Hello World" ``` Codex will: 1. Create a Python file 2. Write the code 3. Ask for your approval before saving (in default "suggest" mode) 4. Show you the result You'll see output similar to: ``` I'll create a simple Python script for you. [Codex proposes changes] Approve? [Y/n]: ``` Type `y` to approve and apply the changes. ## Understanding approval modes Codex operates in three approval modes that control how much autonomy the agent has: **Default mode** Codex reads files and suggests changes. You approve all file writes and shell commands. Codex reads and writes files automatically. You approve shell commands. Use: `codex --approval-mode auto-edit` Codex reads, writes files, and executes commands autonomously. Everything runs in a sandbox. Use: `codex --approval-mode full-auto` In full auto mode, commands run network-disabled and confined to your working directory. Codex will warn you if your directory is not tracked by Git. ## Example workflows Here are some common tasks you can ask Codex to perform: ```bash theme={null} codex "Refactor the Dashboard component to React Hooks" ``` Codex will: * Read the component file * Rewrite it using React Hooks * Run tests to verify the changes * Show you a diff of the changes ```bash theme={null} codex "Write unit tests for utils/date.ts" ``` Codex will: * Analyze the `date.ts` file * Generate comprehensive unit tests * Execute the tests * Iterate until they pass ```bash theme={null} codex --approval-mode full-auto "create a todo-list app with React and TypeScript" ``` Codex will: * Scaffold the project structure * Install dependencies * Write the application code * Run it in the sandbox * Show you the live result ```bash theme={null} codex "fix all TypeScript errors in this project" ``` Codex will: * Run the TypeScript compiler * Identify all type errors * Fix them one by one * Verify the fixes compile ## Interactive vs non-interactive mode **Interactive mode** (default) Run `codex` to start an interactive REPL session: ```bash theme={null} codex ``` You can have a back-and-forth conversation with Codex, approve changes, and iterate on tasks. **Non-interactive mode** Provide a prompt as a command-line argument: ```bash theme={null} codex "create a README for this project" ``` Codex will execute the task and exit when complete. **Quiet mode** (for CI/CD) Run Codex headless in pipelines: ```bash theme={null} codex -q "update CHANGELOG for next release" ``` Or set the environment variable: ```bash theme={null} export CODEX_QUIET_MODE=1 ``` ## Passing images Codex is multimodal and can understand images. Pass screenshots or diagrams: ```bash theme={null} codex -i screenshot.png "implement this design" ``` Codex will analyze the image and implement the visual design. ## Next steps Explore all authentication methods and configuration options Understand approval modes, sandboxing, and security model Customize Codex with config files and environment variables Explore all available commands and options # Installation Source: https://openai-codex.mintlify.app/sdk/installation Install the Codex TypeScript SDK and set up your development environment ## Requirements The Codex TypeScript SDK requires: * **Node.js 18 or higher** * The `@openai/codex` CLI installed and available in your PATH ## Install the SDK Install the SDK using your preferred package manager: ```bash npm theme={null} npm install @openai/codex-sdk ``` ```bash pnpm theme={null} pnpm add @openai/codex-sdk ``` ```bash yarn theme={null} yarn add @openai/codex-sdk ``` ## Verify Installation Create a simple test script to verify the SDK is installed correctly: ```typescript test.ts theme={null} import { Codex } from "@openai/codex-sdk"; const codex = new Codex(); const thread = codex.startThread(); console.log("SDK initialized successfully!"); ``` Run the script: ```bash Node.js theme={null} node --loader tsx test.ts ``` ```bash ts-node theme={null} ts-node test.ts ``` ## Environment Setup ### API Configuration The SDK requires access to the Codex API. Configure your credentials: Set your OpenAI API key as an environment variable: ```bash theme={null} export OPENAI_API_KEY="your-api-key" ``` If you're using a custom API endpoint, set the base URL: ```bash theme={null} export OPENAI_BASE_URL="https://custom-endpoint.example.com/v1" ``` Alternatively, pass credentials directly when creating the client: ```typescript theme={null} const codex = new Codex({ apiKey: process.env.OPENAI_API_KEY, baseUrl: "https://api.openai.com/v1", }); ``` ### TypeScript Configuration Ensure your `tsconfig.json` is configured for ES modules: ```json tsconfig.json theme={null} { "compilerOptions": { "module": "ESNext", "moduleResolution": "node", "target": "ES2020", "lib": ["ES2020"], "esModuleInterop": true, "skipLibCheck": true } } ``` The SDK uses ES module syntax (`import`/`export`). Ensure your project is configured to support ES modules. ## Package Information The SDK is published as `@openai/codex-sdk` with the following characteristics: `@openai/codex-sdk` ES Module (`.js` files with `import`/`export`) `./dist/index.js` `./dist/index.d.ts` Apache-2.0 ## Troubleshooting Ensure you've installed the package and that your `node_modules` is up to date: ```bash theme={null} rm -rf node_modules package-lock.json npm install ``` The SDK requires the `codex` CLI to be installed. Install it globally: ```bash theme={null} npm install -g @openai/codex ``` Or specify a custom path when creating the client: ```typescript theme={null} const codex = new Codex({ codexPathOverride: "/path/to/codex", }); ``` Verify you're using Node.js 18 or higher: ```bash theme={null} node --version ``` Upgrade if needed using [nvm](https://github.com/nvm-sh/nvm) or download from [nodejs.org](https://nodejs.org). ## Next Steps Learn how to use the SDK with code examples and detailed API documentation # Overview Source: https://openai-codex.mintlify.app/sdk/overview Embed the Codex agent in your workflows and applications with the TypeScript SDK ## What is the Codex SDK? The Codex TypeScript SDK allows you to programmatically embed the Codex agent into your workflows and applications. It wraps the `codex` CLI from `@openai/codex`, spawning the CLI process and exchanging JSONL events over stdin/stdout. With the SDK, you can: * Start and manage conversation threads with the Codex agent * Execute autonomous coding tasks programmatically * Stream real-time events as the agent works (tool calls, file changes, responses) * Get structured JSON output conforming to your schemas * Resume previous conversations from persisted sessions * Control sandbox modes, working directories, and approval policies ## When to Use the SDK The TypeScript SDK is ideal for: Integrate Codex into CI/CD pipelines, automated testing, or deployment workflows Build custom development tools and IDEs with embedded AI assistance Process multiple repositories or tasks in parallel with programmatic control Extract structured data or generate reports that conform to specific schemas ## Key Concepts ### Codex Client The `Codex` class is the main entry point. It manages the underlying CLI process and configuration: ```typescript theme={null} import { Codex } from "@openai/codex-sdk"; const codex = new Codex({ baseUrl: "https://api.openai.com/v1", apiKey: process.env.OPENAI_API_KEY, }); ``` ### Threads A `Thread` represents a conversation with the agent. Threads persist across multiple turns and are saved in `~/.codex/sessions`: ```typescript theme={null} const thread = codex.startThread(); ``` ### Turns A turn is a single interaction where you provide input and the agent responds. Each turn can involve multiple tool calls, file changes, and reasoning steps: ```typescript theme={null} const turn = await thread.run("Fix the failing tests"); console.log(turn.finalResponse); ``` ### Events The SDK emits structured events as the agent works. Use `runStreamed()` to access these events in real-time: ```typescript theme={null} const { events } = await thread.runStreamed("Analyze this codebase"); for await (const event of events) { switch (event.type) { case "item.completed": console.log("Completed:", event.item); break; case "turn.completed": console.log("Usage:", event.usage); break; } } ``` ## Core Capabilities Use `run()` to execute a turn and wait for the complete result with all items buffered. Use `runStreamed()` to receive real-time events including tool calls, file changes, and progress updates. Provide a JSON schema to get agent responses in structured format instead of natural language. Attach local images alongside text prompts for visual analysis and debugging. Resume conversations from previous sessions using thread IDs. Configure sandbox modes from read-only to full file system access. ## Next Steps Install the SDK and set up your environment Learn how to use the SDK with detailed examples # Usage Source: https://openai-codex.mintlify.app/sdk/usage Learn how to use the Codex TypeScript SDK with detailed examples and API documentation ## Quick Start The most basic usage involves creating a `Codex` client, starting a thread, and running a turn: ```typescript theme={null} import { Codex } from "@openai/codex-sdk"; const codex = new Codex(); const thread = codex.startThread(); const turn = await thread.run("Diagnose the test failure and propose a fix"); console.log(turn.finalResponse); console.log(turn.items); ``` ## Core SDK Exports The SDK exports the following main classes and types: ### Main Classes Main client for interacting with the Codex agent. Used to create and resume threads. Represents a conversation with the agent. Supports multiple consecutive turns. ### Type Exports ```typescript Events theme={null} import type { ThreadEvent, ThreadStartedEvent, TurnStartedEvent, TurnCompletedEvent, TurnFailedEvent, ItemStartedEvent, ItemUpdatedEvent, ItemCompletedEvent, ThreadError, ThreadErrorEvent, Usage, } from "@openai/codex-sdk"; ``` ```typescript Items theme={null} import type { ThreadItem, AgentMessageItem, ReasoningItem, CommandExecutionItem, FileChangeItem, McpToolCallItem, WebSearchItem, TodoListItem, ErrorItem, } from "@openai/codex-sdk"; ``` ```typescript Options theme={null} import type { CodexOptions, ThreadOptions, TurnOptions, ApprovalMode, SandboxMode, ModelReasoningEffort, WebSearchMode, } from "@openai/codex-sdk"; ``` ```typescript Results theme={null} import type { RunResult, RunStreamedResult, Input, UserInput, } from "@openai/codex-sdk"; ``` ## Creating a Codex Client The `Codex` class accepts optional configuration: ```typescript theme={null} import { Codex } from "@openai/codex-sdk"; const codex = new Codex({ // API configuration baseUrl: "https://api.openai.com/v1", apiKey: process.env.OPENAI_API_KEY, // CLI path override (if codex is not in PATH) codexPathOverride: "/custom/path/to/codex", // Environment variables for the CLI process env: { PATH: process.env.PATH, HOME: process.env.HOME, }, // Additional CLI configuration overrides config: { show_raw_agent_reasoning: true, sandbox_workspace_write: { network_access: true, }, }, }); ``` Custom API base URL. Defaults to the OpenAI API endpoint. OpenAI API key. Can also be set via `OPENAI_API_KEY` environment variable. Path to the `codex` CLI binary. Used when `codex` is not in your PATH. Environment variables passed to the Codex CLI process. When provided, the SDK will not inherit from `process.env`. Additional `--config` overrides passed to the CLI. The SDK flattens this object into dotted paths. ## Starting a Thread Create a new conversation thread with optional configuration: ```typescript theme={null} const thread = codex.startThread({ workingDirectory: "/path/to/project", sandboxMode: "workspace-write", model: "gpt-4", skipGitRepoCheck: false, modelReasoningEffort: "medium", networkAccessEnabled: true, webSearchMode: "cached", approvalPolicy: "on-request", additionalDirectories: ["/path/to/extra/context"], }); ``` ### Thread Options Working directory for the agent. Defaults to the current directory. File system access level for the agent. Model to use for this thread (e.g., `"gpt-4"`, `"gpt-4-turbo"`). Skip the Git repository check. Defaults to `false`. Amount of reasoning effort the model should apply. Enable network access for the agent. Web search configuration for the agent. When to request user approval for actions. Additional directories to include in the agent's context. ## Running a Turn ### Buffered Execution Use `run()` to execute a turn and wait for the complete result: ```typescript theme={null} const turn = await thread.run("Fix the failing tests"); console.log("Response:", turn.finalResponse); console.log("Items:", turn.items); console.log("Usage:", turn.usage); ``` The returned `Turn` object contains: The agent's final text response (or JSON if using structured output). Array of all items produced during the turn (commands, file changes, tool calls, etc.). Token usage statistics for the turn. ### Streaming Events Use `runStreamed()` to receive real-time events as the agent works: ```typescript theme={null} const { events } = await thread.runStreamed("Analyze this codebase"); for await (const event of events) { switch (event.type) { case "thread.started": console.log("Thread ID:", event.thread_id); break; case "turn.started": console.log("Turn started"); break; case "item.started": console.log("Item started:", event.item); break; case "item.updated": console.log("Item updated:", event.item); break; case "item.completed": console.log("Item completed:", event.item); break; case "turn.completed": console.log("Turn completed. Usage:", event.usage); break; case "turn.failed": console.error("Turn failed:", event.error.message); break; case "error": console.error("Fatal error:", event.message); break; } } ``` ## Structured Output Provide a JSON schema to get structured responses: ```typescript theme={null} const schema = { type: "object", properties: { summary: { type: "string" }, status: { type: "string", enum: ["ok", "action_required"] }, issues: { type: "array", items: { type: "object", properties: { file: { type: "string" }, line: { type: "number" }, description: { type: "string" }, }, required: ["file", "description"], }, }, }, required: ["summary", "status"], additionalProperties: false, } as const; const turn = await thread.run("Analyze the codebase for issues", { outputSchema: schema, }); const result = JSON.parse(turn.finalResponse); console.log(result.summary); console.log(result.issues); ``` ### Using Zod Schemas You can also use Zod schemas with the `zod-to-json-schema` package: ```typescript theme={null} import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; const schema = z.object({ summary: z.string(), status: z.enum(["ok", "action_required"]), issues: z.array( z.object({ file: z.string(), line: z.number().optional(), description: z.string(), }) ), }); const turn = await thread.run("Analyze the codebase", { outputSchema: zodToJsonSchema(schema, { target: "openAi" }), }); const result = schema.parse(JSON.parse(turn.finalResponse)); ``` ## Attaching Images Provide images alongside text prompts: ```typescript theme={null} const turn = await thread.run([ { type: "text", text: "Describe these UI screenshots and suggest improvements" }, { type: "local_image", path: "./screenshots/dashboard.png" }, { type: "local_image", path: "./screenshots/settings.png" }, ]); ``` Image entries must use the `local_image` type with an absolute or relative path to the image file. ## Resuming Threads Threads are persisted in `~/.codex/sessions`. Resume a previous conversation: ```typescript theme={null} // Save the thread ID from a previous session const threadId = thread.id; // Later, resume the thread const resumedThread = codex.resumeThread(threadId); const nextTurn = await resumedThread.run("Continue from where we left off"); ``` ## Working with Thread Items Each turn produces various item types representing the agent's work: ```typescript Agent Messages theme={null} if (item.type === "agent_message") { console.log("Agent says:", item.text); } ``` ```typescript Command Execution theme={null} if (item.type === "command_execution") { console.log("Command:", item.command); console.log("Output:", item.aggregated_output); console.log("Exit code:", item.exit_code); console.log("Status:", item.status); } ``` ```typescript File Changes theme={null} if (item.type === "file_change") { console.log("Changes:", item.changes); item.changes.forEach(change => { console.log(`${change.kind}: ${change.path}`); }); console.log("Status:", item.status); } ``` ```typescript MCP Tool Calls theme={null} if (item.type === "mcp_tool_call") { console.log("Server:", item.server); console.log("Tool:", item.tool); console.log("Arguments:", item.arguments); console.log("Result:", item.result); console.log("Status:", item.status); } ``` ```typescript Web Search theme={null} if (item.type === "web_search") { console.log("Query:", item.query); } ``` ```typescript Todo List theme={null} if (item.type === "todo_list") { item.items.forEach(todo => { const status = todo.completed ? "✓" : "○"; console.log(`${status} ${todo.text}`); }); } ``` ```typescript Reasoning theme={null} if (item.type === "reasoning") { console.log("Agent reasoning:", item.text); } ``` ```typescript Errors theme={null} if (item.type === "error") { console.error("Error:", item.message); } ``` ## Token Usage Access detailed token usage after each turn: ```typescript theme={null} const turn = await thread.run("Refactor this module"); if (turn.usage) { console.log("Input tokens:", turn.usage.input_tokens); console.log("Cached input tokens:", turn.usage.cached_input_tokens); console.log("Output tokens:", turn.usage.output_tokens); const total = turn.usage.input_tokens + turn.usage.output_tokens; const cacheHitRate = turn.usage.cached_input_tokens / turn.usage.input_tokens; console.log("Total tokens:", total); console.log("Cache hit rate:", (cacheHitRate * 100).toFixed(2) + "%"); } ``` ## Aborting a Turn Cancel a turn using an `AbortSignal`: ```typescript theme={null} const controller = new AbortController(); // Cancel after 30 seconds setTimeout(() => controller.abort(), 30000); try { const turn = await thread.run("Long running task", { signal: controller.signal, }); } catch (error) { if (error.name === "AbortError") { console.log("Turn was cancelled"); } } ``` ## Error Handling Handle errors gracefully: ```typescript theme={null} try { const turn = await thread.run("Fix the bug"); console.log(turn.finalResponse); } catch (error) { if (error.message.includes("rate limit")) { console.error("Rate limit exceeded. Retrying..."); // Implement retry logic } else if (error.message.includes("authentication")) { console.error("Invalid API key"); } else { console.error("Unexpected error:", error.message); } } ``` ## Advanced Example Here's a complete example combining multiple features: ```typescript theme={null} import { Codex } from "@openai/codex-sdk"; import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; // Define structured output schema const analysisSchema = z.object({ summary: z.string(), filesAnalyzed: z.number(), issues: z.array( z.object({ severity: z.enum(["low", "medium", "high"]), file: z.string(), description: z.string(), }) ), recommendations: z.array(z.string()), }); // Create Codex client const codex = new Codex({ apiKey: process.env.OPENAI_API_KEY, config: { show_raw_agent_reasoning: true, }, }); // Start thread with configuration const thread = codex.startThread({ workingDirectory: "/path/to/project", sandboxMode: "read-only", modelReasoningEffort: "high", }); // Run analysis with streaming const { events } = await thread.runStreamed( "Analyze the codebase for security issues and best practices", { outputSchema: zodToJsonSchema(analysisSchema, { target: "openAi" }), } ); // Process events for await (const event of events) { if (event.type === "item.completed") { const item = event.item; if (item.type === "command_execution") { console.log(`Executed: ${item.command}`); } else if (item.type === "agent_message") { const analysis = analysisSchema.parse(JSON.parse(item.text)); console.log("\nAnalysis Complete"); console.log("Summary:", analysis.summary); console.log("Files analyzed:", analysis.filesAnalyzed); console.log("\nIssues found:"); analysis.issues.forEach(issue => { console.log(` [${issue.severity.toUpperCase()}] ${issue.file}`); console.log(` ${issue.description}`); }); console.log("\nRecommendations:"); analysis.recommendations.forEach((rec, i) => { console.log(` ${i + 1}. ${rec}`); }); } } if (event.type === "turn.completed") { console.log("\nToken usage:", event.usage); } } ```