Codex CLI 0.164.0: Install & config.toml
Codex CLI 0.164.0 (2026-10-23): install it, connect QCode.cc through ~/.codex/config.toml and auth.json, then use AGENTS.md, approvals, profiles and MCP.
Need an API key? Sign up →Endpoints & base URLs →
On This Page
Last verified: 2026-10-26 · 📄 Per official docs (latest stable Codex CLI v0.164.0, released 2026-10-23; this pass re-checked the config keys, the 0.164.0 command changes, and installation) · the profile behaviour in 5.4 was additionally tested locally (✅ codex-cli 0.155.0, isolated HOME, no model requests sent)
At a glance¶
| Item | Details |
|---|---|
| Models you can use | GPT ✅ (Responses protocol) · Claude ❌ · Chinese models ❌ (the Responses protocol does not serve them) · Gemini ❌ (QCode does not currently offer Gemini) |
| Protocol & Base URL | OpenAI Responses: base_url = "https://api.qcode.cc/openai" + wire_api = "responses" in config.toml |
| Where to configure | ~/.codex/config.toml (Windows: %USERPROFILE%\.codex\) |
| Official docs | openai/codex |
📖 Why does Codex's
base_urldiffer from Claude'sANTHROPIC_BASE_URL? What's the difference between/openaiand/openai/v1? See Endpoints & API Paths.
This is a complete Codex CLI tutorial for Chinese developers, taking you from zero to installing, configuring, and using OpenAI Codex CLI with GPT models through your QCode.cc API key. Whether you're first touching AI programming tools or already using Claude Code and want to try new tools, this tutorial is suitable for you.
1. Codex Introduction¶
What is OpenAI Codex CLI?¶
Codex CLI is an open-source command-line AI programming assistant (Apache 2.0 license) launched by OpenAI, written in Rust and can run directly in the terminal. It can:
- Read and understand your code repository
- Edit files and generate new code
- Execute commands (such as running tests, installing dependencies)
- Iterate autonomously until the task is complete
The core philosophy of Codex is Autonomous Agent: you describe the task, Codex completes it autonomously in a sandbox, and you review the results at the end. This complements Claude Code's interactive dialogue style.
Development History of Codex¶
The name "Codex" has gone through multiple evolutions in OpenAI's product lineup:
- 2021: The earliest Codex was a code fine-tuned version of GPT-3, powering GitHub Copilot
- 2024: OpenAI reactivated the Codex brand, launching a cloud-based asynchronous AI programming agent
- 2025-2026: Codex CLI developed into a mature local command-line tool, rewritten in Rust, supporting advanced features such as MCP, Skills, and Multi-Agent
Current Codex is a multi-interface product: including CLI command-line tool (focus of this article), macOS desktop app, IDE plugins, and cloud agents integrated into ChatGPT. The version used through QCode.cc is the CLI version.
Core Differences Between Codex and Claude Code¶
| Dimension | Codex CLI | Claude Code |
|---|---|---|
| Execution Style | Autonomous execution, delivers results upon completion | Interactive dialogue, step-by-step confirmation |
| Open Source | Fully open source (Apache 2.0) | Not open source |
| Language | Rust (fast startup, low resource usage) | TypeScript |
| Sandbox Security | Built-in Landlock/seccomp sandbox | Permission prompt confirmation |
| Instruction File | AGENTS.md |
CLAUDE.md |
| Cloud Agent | Supported (built into ChatGPT) | Not supported |
In simple terms: Codex excels at "hands-off tasks" (give a clear requirement, let it run through), Claude Code excels at "pair programming" (discuss and modify while exploring, suitable for exploratory tasks). Using both together yields the best results.
Why Use Codex Through QCode.cc?¶
Codex CLI requires an OpenAI API key or a ChatGPT subscription by default, and in mainland China the OpenAI API cannot be reached directly.
Through QCode.cc, you can:
- Call Claude, GPT and mainstream Chinese models with one key: Codex uses the GPT models, Claude Code uses Claude, and both share the same QCode API key
- Use several endpoints:
api.qcode.ccis the global entry,us.qcode.ccserves North America and Europe,asia.qcode.ccserves Asia, and users in mainland China should preferasia.qcode.cc; no self-built proxy is needed - Pay per token, with per-model rates on qcode.cc/models
- Claude Code and Codex share plan quota, so one plan works for both tools
2. Installing Codex CLI¶
System Requirements¶
Before installing, please confirm your environment meets the following conditions:
- Operating System: macOS 12+, Ubuntu 20.04+, Windows 10+ (WSL2 recommended)
- Node.js: v22 LTS or higher (required for npm installation)
- Git: 2.x or higher (Codex needs Git to recognize the code repository)
- Disk Space: Approximately 200MB (including npm dependencies)
Method 1: npm Installation (Recommended)¶
This is the most common installation method, applicable to all operating systems:
npm install -g @openai/codex
Tip: If you encounter permission issues, macOS/Linux users can add
sudo, or use nvm to manage Node.js to avoid permission issues.Chinese users: If npm download is slow, you can use the Taobao mirror:
bash npm install -g @openai/codex --registry=https://registry.npmmirror.com
Method 2: Homebrew Installation (macOS)¶
macOS users can also install via Homebrew:
brew install --cask codex
Homebrew's advantage is automatic dependency management and updates.
Method 3: Direct Binary Download (Advanced)¶
Download pre-compiled binaries for your platform from the GitHub Releases page and place them in the PATH directory. This method doesn't depend on Node.js. As of 2026-10-26 the latest stable release is v0.164.0 (published 2026-10-23); the 2026-10-15 pass checked v0.162.1 (published 2026-10-09). Assets are named by platform: for example codex-x86_64-unknown-linux-musl.tar.gz for Linux x64, codex-aarch64-apple-darwin.tar.gz for Apple-silicon macOS, and codex-x86_64-pc-windows-msvc.exe for Windows x64.
# Example: download and install the Linux x64 build
curl -fsSLO https://github.com/openai/codex/releases/latest/download/codex-x86_64-unknown-linux-musl.tar.gz
tar -xzf codex-x86_64-unknown-linux-musl.tar.gz
sudo mv codex-x86_64-unknown-linux-musl /usr/local/bin/codex
Method 4: Official Install Script (macOS / Linux)¶
The official OpenAI Codex documentation (as of 2026-10-26) also offers a standalone installer:
curl -fsSL https://chatgpt.com/codex/install.sh | sh
Confirm the installation with codex --version.
Verify Installation¶
codex --version
If you see a version number, the installation succeeded. Do not treat a number in this page as “the current latest” — use GitHub Releases and npm @openai/codex, and check the machine with codex --version.
Configure Shell Auto-Completion (Optional)¶
Codex supports shell auto-completion; press Tab when entering commands for suggestions:
# Zsh users
echo 'eval "$(codex completion zsh)"' >> ~/.zshrc
source ~/.zshrc
# Bash users
echo 'eval "$(codex completion bash)"' >> ~/.bashrc
source ~/.bashrc
If Zsh prompts
command not found: compdef, addautoload -Uz compinit && compinitbeforeeval.
3. QCode.cc Configuration¶
Codex CLI requires configuring two files to connect to QCode.cc service:
~/.codex/config.toml— Server endpoint and model configuration~/.codex/auth.json— API key authentication
Step 1: Create Configuration Directory¶
Windows (PowerShell):
mkdir $HOME\.codex
macOS:
mkdir -p ~/.codex
Linux:
mkdir -p ~/.codex
Step 2: Create config.toml¶
Write the following content to ~/.codex/config.toml:
model_provider = "qcode"
model = "gpt-6.1-sol"
model_reasoning_effort = "high"
[model_providers.qcode]
name = "qcode"
base_url = "https://api.qcode.cc/openai"
wire_api = "responses"
requires_openai_auth = true
config.toml Field Details:
| Field | Description |
|---|---|
model_provider |
Model provider name, set to the custom qcode. The name is up to you as long as it matches [model_providers.<name>]; this documentation uses qcode throughout |
model |
Default model. Recommended: gpt-6.1-sol (the model the official OpenAI Codex documentation recommends for complex coding and agentic work) |
model_reasoning_effort |
Reasoning effort, such as low, medium, high; the available levels depend on the model and client. Higher is more accurate but slower |
base_url |
QCode.cc endpoint address (example uses api.qcode.cc global entry; see Endpoints & API Paths for alternatives) |
wire_api |
API protocol type; Codex currently supports only responses |
requires_openai_auth |
Use OpenAI-style authentication; the key is read from OPENAI_API_KEY in ~/.codex/auth.json. When set to true, Codex ignores env_key (official documentation) |
Step 3: Create auth.json¶
Write the following content to ~/.codex/auth.json:
{
"OPENAI_API_KEY": "cr_xxxxxxxxxx"
}
Replace
cr_xxxxxxxxxxwith your QCode.cc API key. The key starts withcr_.
auth.json Notes:
- This file provides the API key to Codex (with
requires_openai_auth = true, Codex readsOPENAI_API_KEYfrom it) - File permissions recommended as
600(readable/writable only by owner):chmod 600 ~/.codex/auth.json
Step 4: Set Environment Variables (Optional Alternative)¶
To pass the key through an environment variable instead, replace requires_openai_auth = true in [model_providers.qcode] with env_key = "QCODE_API_KEY" and export that variable. Use one or the other: the official documentation states that Codex ignores env_key when requires_openai_auth = true. The full configuration for the environment-variable variant:
model_provider = "qcode"
model = "gpt-6.1-sol"
model_reasoning_effort = "high"
[model_providers.qcode]
name = "qcode"
base_url = "https://api.qcode.cc/openai"
wire_api = "responses"
env_key = "QCODE_API_KEY"
Then set the environment variable:
Windows (PowerShell):
# Temporary setting (current session)
$env:QCODE_API_KEY = "cr_xxxxxxxxxx"
# Permanent setting (write to user environment variable)
[System.Environment]::SetEnvironmentVariable("QCODE_API_KEY", "cr_xxxxxxxxxx", [System.EnvironmentVariableTarget]::User)
macOS:
# Temporary setting
export QCODE_API_KEY="cr_xxxxxxxxxx"
# Permanent setting
echo 'export QCODE_API_KEY="cr_xxxxxxxxxx"' >> ~/.zshrc
source ~/.zshrc
Linux:
# Temporary setting
export QCODE_API_KEY="cr_xxxxxxxxxx"
# Permanent setting (Bash)
echo 'export QCODE_API_KEY="cr_xxxxxxxxxx"' >> ~/.bashrc
source ~/.bashrc
# Permanent setting (Zsh)
echo 'export QCODE_API_KEY="cr_xxxxxxxxxx"' >> ~/.zshrc
source ~/.zshrc
Available Models¶
The following Codex/GPT models are available through QCode.cc:
| Model | Description | Recommended Scenario |
|---|---|---|
gpt-6.1-sol |
GPT-6 Sol update (2026-09-29), 1.05M context, cheaper cached input | General / complex tasks (recommended ★; the official OpenAI Codex documentation recommends GPT-6.1 Sol for complex coding and agentic workflows) |
gpt-6.1-terra |
Mid-tier GPT-6.1, unit price about half that of gpt-6.1-sol (see /models) |
Everyday coding / batch tasks |
gpt-6-sol |
GPT-6 Sol, 1.05M context | General / complex tasks |
gpt-6-astra |
Strongest tier, premium price | Top capability |
gpt-5.6-terra |
GPT-5.6 flagship, code-optimized | Programming / Codex CLI |
QCode does not currently offer gpt-6-luna / gpt-5.6-luna. Please use another GPT model (gpt-6.1-sol / gpt-6.1-terra / gpt-6-sol / gpt-5.6-terra).
Claude Code and Codex use the same QCode API key, and switching models needs no extra setup. QCode bills per token; per-model rates are on qcode.cc/models.
4. Basic Usage Tutorial¶
4.1 Launch Codex¶
Open terminal, go to your project directory, then run:
cd /path/to/your/project
codex
Codex will launch a terminal interactive interface (TUI), where you can enter natural language instructions. The interface consists of:
- Top status bar: Shows current model, approval mode, sandbox status
- Main area: AI's replies and operation logs
- Bottom input box: Where you enter instructions
You can also give tasks directly on the command line (non-interactive mode), suitable for script invocation:
# Interactive launch
codex
# Non-interactive mode: execute single task then exit
codex "Read this project's structure and give me an overview"
# Task with image
codex -i screenshot.png "Fix the UI issue shown in the screenshot"
# Specify model
codex -m gpt-6-sol "Refactor the error handling in the authentication module"
4.2 First Task: Let Codex Write a Function¶
Let's start with a simple example. Run Codex in your project directory and enter:
Write a Python function that accepts a list of strings and returns the longest one. If there are multiple strings with the same length, return the first one. Save to utils.py.
Codex will execute the following steps:
- Plan: Analyze your requirements and formulate implementation plan
- Generate code: Create
utils.pyand write the function - Request confirmation: In the read-only preset, or when a change needs approval (for example writing outside the workspace), Codex shows the pending file modification and waits for your confirmation; in the default preset, edits inside the workspace run automatically
When confirmation is needed, you'll see a prompt like this:
Codex wants to create file: utils.py
─────────────────────────────────────
+ def find_longest(strings: list[str]) -> str:
+ """Return the longest string in the list, or the first one if there are multiple."""
+ if not strings:
+ raise ValueError("List cannot be empty")
+ return max(strings, key=len)
Accept? [y/n]
Enter y to confirm, and Codex will write the code to the file.
Next, you can continue to give more instructions, and Codex will maintain context within the same session:
Write a unit test for this function using pytest
Codex will automatically read the utils.py you just created, then generate the corresponding test file.
4.3 Understanding Codex's Sandbox Execution Mode¶
This is one of Codex's most important security features. Codex executes commands in a sandbox, with three security levels:
| Sandbox Mode | File Read | File Write | Command Execute | Network Access |
|---|---|---|---|---|
read-only |
Allowed | Requires confirmation | Requires confirmation | Requires confirmation |
workspace-write (default) |
Allowed | Allowed within workspace | Allowed within workspace | Denied by default |
danger-full-access |
Allowed | All allowed | All allowed | Allowed |
The default workspace-write mode is the best choice for daily development: Codex can freely read/write files and run commands within the project directory, but cannot access files or network outside the project.
If your task requires network access (such as npm install), you can temporarily enable network access:
codex -c 'sandbox_workspace_write.network_access=true' "Install dependencies and run tests"
4.4 Review and Accept Codex's Changes¶
Codex's file modifications follow an Approval Policy. According to the official documentation (as of 2026-10-26), the default in a Git repository is the "workspace write + on-request approvals" preset:
- File edits and commands inside the workspace: run automatically
- Writing outside the workspace, network access and similar actions: shown to you and wait for confirmation
- Folders that are not Git repositories: read-only by default, so Codex asks before changing anything
When Codex proposes modifications, you can:
- Accept (y): Apply the modification
- Reject (n): Skip this modification
- View details: Carefully review the diff before deciding
Tip: Use the
/diffslash command to view all applied modifications in the current session at any time.
4.5 Common Interaction Tips¶
File reference: Enter @ followed by filename, Codex will automatically read that file's content:
Review @src/app.py and optimize error handling
Execute Shell commands: Start with ! to run commands directly, output will be passed to Codex:
!cat error.log
Analyze the error log above and find the root cause
Append instructions: When Codex is running, press Enter to insert new instructions, press Tab to queue the next round of instructions.
Backtrack editing: When the input box is empty, press Esc twice to return to the previous message and modify/resend. Continue pressing Esc to backtrack to earlier messages, then press Enter to fork a new dialogue line from that point.
Pipe input: You can pipe output from other commands to Codex for analysis:
# Analyze recent git changes
git diff HEAD~3 | codex "Review these changes and identify potential issues"
# Analyze error logs
cat /var/log/app/error.log | codex "Analyze the root causes of these errors"
# Review PR
gh pr diff 42 | codex "Review this PR's code quality and security"
Keyboard shortcuts:
| Shortcut | Function |
|---|---|
Tab |
Auto-complete file path (use with @) |
Enter |
Insert new instruction while Codex is running |
Tab |
Queue next round of instructions while Codex is running |
Esc x 2 |
Backtrack to previous message for editing |
Ctrl+C |
Cancel current operation |
Slash commands:
| Command | Description |
|---|---|
/model |
Choose the model and reasoning effort |
/diff |
View all changes |
/mcp |
View connected MCP servers |
/status |
Show current session status |
/compact |
Compact conversation history to save tokens |
/permissions |
View and modify permission settings |
/review |
Code review |
4.6 Codex CLI 0.164.0 command changes (2026-10-23)¶
Codex CLI 0.164.0 was published on 2026-10-23. Its release notes list these command- and configuration-facing changes (quoted verbatim):
- Save reusable prompts and slash commands in ten numbered
/presetsslots, with a keyboard menu for quick access. - Set model, reasoning effort, speed, and permission profiles directly with inline
/modeland/permissionsarguments. - Authenticate enterprise MCP connections using eligible Codex account grants or dedicated sign-in, including OAuth clients requiring secrets.
- Mask credentials during supported remote Bash commands and Zsh snapshot sessions, including credentials from custom providers.
The keys used in the configuration above remain in the official configuration reference checked on 2026-10-26: model_provider, [model_providers.<id>], base_url, wire_api and requires_openai_auth. Install commands are unchanged in the official README checked the same day: npm install -g @openai/codex, brew install --cask codex, or curl -fsSL https://chatgpt.com/codex/install.sh | sh.
5. Advanced Configuration¶
5.1 Custom Instruction Files (AGENTS.md)¶
Codex supports AGENTS.md files to provide AI with project context and work specifications, functioning similarly to Claude Code's CLAUDE.md.
Project-level instructions: Create AGENTS.md in the project root directory:
# AGENTS.md
## Project Description
This is a FastAPI backend project using PostgreSQL database.
## Code Standards
- All functions must have type annotations
- New API endpoints require corresponding tests
- Run `make lint` to check code style before committing
## Test Commands
- Unit tests: `pytest tests/unit/`
- Integration tests: `pytest tests/integration/`
- Code check: `make lint`
Global instructions: Create global default rules in ~/.codex/AGENTS.md, all projects will inherit:
# Global Instructions
- Always communicate in English
- Code comments use English
- Prefer functional programming style
- Generated code must include error handling
Subdirectory override: Creating AGENTS.override.md in a specific directory can override parent rules:
# services/payments/AGENTS.override.md
- All changes in this directory must be written to audit log
- Amount calculations use Decimal type, no floating point numbers
Codex searches for instruction files in the following order: AGENTS.override.md > AGENTS.md > configured fallback file. The combined total size limit defaults to 32KB, adjustable via project_doc_max_bytes.
5.2 Adjusting Approvals and the Sandbox¶
Codex's security controls come in two layers: the sandbox mode decides what Codex can technically do (where it can write, whether it can reach the network), and the approval policy decides when it must ask you first. As of 2026-10-26, according to the official OpenAI documentation, two command-line options control them:
| Option | Values |
|---|---|
--sandbox / -s |
read-only, workspace-write, danger-full-access |
--ask-for-approval / -a |
on-request, never |
Common combinations (official documentation):
| Goal | Options | Effect |
|---|---|---|
| Default (recommended in Git repositories) | No options, or --sandbox workspace-write --ask-for-approval on-request |
Reads files, edits files and runs commands inside the workspace; asks first before writing outside the workspace or using the network |
| Safe read-only browsing | --sandbox read-only --ask-for-approval on-request |
Reads files and runs commands in the read-only sandbox; actions outside the sandbox can require approval |
| Read-only, non-interactive (CI) | --sandbox read-only --ask-for-approval never |
Never asks for approval |
| Automatic approval review | --approve-for-me (alias --not-so-yolo) |
Uses on-request approvals with the workspace-write sandbox; approval requests are handled by automatic review |
| Full access (not recommended) | --dangerously-bypass-approvals-and-sandbox (alias --yolo) |
No sandbox and no approvals; use only in an externally hardened, isolated environment |
🔴 The
--full-auto,--suggest,--auto-editand--approval-modeforms you may see in older tutorials are not in the current official option list. When you need fully autonomous file writes, use--sandbox workspace-write; for non-interactive runs usecodex exec --sandbox workspace-write.⚠️ Codex flags change quickly. Trust the actual output of
codex --helprather than a flag list copied from any document, including this page.
Set the defaults in config.toml:
# Recommended for personal development
approval_policy = "on-request"
sandbox_mode = "workspace-write"
approval_policy takes on-request, never, or a granular table that splits prompts by category. The official docs state that approval_policy = "untrusted" is no longer supported; if an old configuration still contains that line it can prevent the client from starting, so remove it.
Switching during a session: use the /permissions command to switch between the default preset and read-only without restarting.
Recommended Configuration by Scenario¶
| Scenario | Approval policy | Sandbox mode |
|---|---|---|
| Everyday personal development | on-request |
workspace-write |
| Shared team environment | on-request |
read-only |
| CI/CD (read-only analysis) | never |
read-only |
| CI/CD (needs to write files) | codex exec --sandbox workspace-write |
workspace-write |
| One-off script tasks (isolated environment) | --yolo |
No sandbox |
5.3 Configure MCP Servers¶
Codex supports Model Context Protocol (MCP), which can connect external tools to extend capabilities.
Add MCP server via command line:
codex mcp add my-server -- npx -y @some/mcp-server --config /path/to/config.json
Configure via config.toml:
[mcp_servers.filesystem]
command = "npx"
args = ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/dir"]
[mcp_servers.github]
command = "npx"
args = ["-y", "@modelcontextprotocol/server-github"]
env = { GITHUB_TOKEN = "ghp_your_token" }
After configuration, restart Codex and use /mcp command to view connected servers. MCP tools will automatically appear in Codex's available tools list alongside built-in tools.
Make Codex itself an MCP server: Codex can also run in reverse as an MCP server, called by other AI Agents. This is very useful when building multi-agent systems.
5.4 Configure Profile (Multi-Environment Management)¶
If different projects need different settings (work versus personal, say), use profiles. Since Codex 0.134.0 the old [profiles.<name>] tables inside config.toml are no longer valid — a profile is now its own file: ~/.codex/<name>.config.toml. The three blocks below are the complete new form:
# ~/.codex/config.toml - default config (top-level keys only; no [profiles.x] tables)
model_provider = "qcode"
model = "gpt-6-sol"
[model_providers.qcode]
name = "qcode"
base_url = "https://api.qcode.cc/openai"
wire_api = "responses"
requires_openai_auth = true
# ~/.codex/work.config.toml
model = "gpt-6-sol"
model_reasoning_effort = "high"
# ~/.codex/personal.config.toml
model = "gpt-5.6-terra"
model_reasoning_effort = "medium"
Start with a profile:
codex --profile work "Refactor authentication module"
codex --profile personal "Write a small script"
✅ The three behaviours below are tested on our own machine (codex-cli 0.155.0, linux-x86_64, isolated HOME, no model request sent) and they are the pitfalls people hit:
- Keeping the legacy table and passing
--profileis a hard error, not a silent ignore:
text
Error loading config.toml: --profile `work` cannot be used while ~/.codex/config.toml contains legacy `profile = "work"` or `[profiles.work]` config; move those settings into ~/.codex/work.config.toml and remove the legacy profile selector/table.
- The top-level
profile = "work"selector is retired as well:
text
Error: legacy `profile = "work"` config is no longer supported; use `--profile work` with `work.config.toml` instead
- Without
--profile, leftover[profiles.*]tables are simply not resolved —codex doctorstill reportsconfig.toml parse okand uses the top-level values. "No error" does not mean "it took effect", so delete the legacy tables when migrating.
Also, --profile only applies to runtime subcommands (codex, exec, review, resume, queue, archive, delete, unarchive, fork, mcp, sandbox, debug prompt-input); on doctor it fails with --profile only applies to runtime commands .... The profile file is a layer above your user config and below project and command-line configuration — see 5.6.
5.5 Non-Interactive Mode (Scripts and Automation)¶
Codex can not only be used interactively but also run non-interactively in scripts and CI/CD pipelines: use codex exec to run a task and exit (per the official documentation, it runs non-interactively and streams results to stdout or JSONL).
# Basic usage: execute task then exit
codex exec "Add installation instructions to README.md"
# Allow workspace writes: fully autonomous execution
codex exec --sandbox workspace-write "Run test suite, fix all failing tests"
# Output a JSONL event stream (for auditing or post-processing)
codex exec --json "Refactor error handling module"
Using Codex in CI/CD:
# GitHub Actions example
- name: Auto-fix lint errors
run: |
# Environment-variable variant: use env_key in config.toml, no requires_openai_auth
mkdir -p ~/.codex
cat > ~/.codex/config.toml <<'EOF'
model_provider = "qcode"
model = "gpt-6.1-sol"
[model_providers.qcode]
name = "qcode"
base_url = "https://api.qcode.cc/openai"
wire_api = "responses"
env_key = "QCODE_API_KEY"
EOF
npx @openai/codex exec --sandbox workspace-write "Run eslint --fix to fix all lint errors, then commit the fixes"
env:
QCODE_API_KEY: ${{ secrets.QCODE_API_KEY }}
Codex SDK: If you need to invoke Codex in your own programs, you can use the official SDK for programmatic invocation, embedding Codex into your own development tools or workflows.
5.6 Configuration Priority¶
When multiple configuration sources conflict, Codex resolves them in the following priority order (highest to lowest):
- Command line arguments (
--model,-c, etc.) - Project configuration (
.codex/config.toml, from project root to current directory, closest takes precedence; it loads only once the folder is trusted, and keys such asmodel_provider,model_providers,profileandprofilesare ignored in the project layer) - Profile file (
~/.codex/<name>.config.toml, selected by--profile <name>) - User configuration (
~/.codex/config.toml) - System configuration (
/etc/codex/config.toml, Unix systems) - Built-in defaults
Understanding this priority helps you precisely control behavior at different levels. For example, set general defaults in ~/.codex/config.toml, override specific settings in the project's .codex/config.toml, then use command line arguments for one-time adjustments.
6. Claude Code vs Codex Comparison¶
In one line: Claude Code is interactive pair programming; Codex is autonomous task execution. Claude Code suits exploratory debugging, complex refactors and understanding an architecture; Codex suits well-specified feature work, bulk migrations and CI/CD automation. Their instruction files are CLAUDE.md and AGENTS.md, both fully support MCP, and both share the same QCode.cc plan quota — switching costs nothing.
The full side-by-side across 13 dimensions (execution model, context window, sandboxing, multi-agent, open source and more) → Codex vs Claude Code.
7. Practical Examples¶
The following demonstrates Codex usage through several real-world scenarios. Each example includes specific commands and expected effects.
Example 1: Understanding a New Project¶
When you take over an unfamiliar codebase:
cd /path/to/new/project
codex
In the interactive interface:
What does this project do? Please analyze the directory structure, main modules, tech stack,
and give a concise architecture diagram (using ASCII art).
Codex will scan project files, analyze dependency files like package.json, requirements.txt, go.mod, read key entry files, then provide a comprehensive project overview.
Example 2: Code Review¶
codex "Review all changes from the most recent git commit in the src/ directory. Focus on:
1. Potential bugs (null pointers, boundary conditions)
2. Security risks (SQL injection, XSS, hardcoded keys)
3. Performance issues (N+1 queries, unnecessary loops)
Provide specific code locations and fix suggestions."
Example 3: Batch Refactoring¶
codex --sandbox workspace-write "Replace all Python file print() calls with the logging module.
Specific requirements:
1. Import logging at the top of each file
2. Create logger = logging.getLogger(__name__)
3. Replace print() with logger.info()
4. Keep original formatted strings
5. After replacement, run pytest to ensure nothing is broken"
Codex will process files one by one, maintaining code consistency, and finally run tests for verification.
Example 4: Write Complete Test Suite¶
codex "Write complete unit tests for src/services/user_service.py. Requirements:
1. Use pytest + pytest-mock
2. Cover all public methods
3. Include both happy path and exception path tests
4. Mock external dependencies (database, HTTP requests)
5. Save test file to tests/unit/test_user_service.py
6. Run tests to confirm all pass"
Example 5: Autonomous Test Fixing¶
Classic fully autonomous use case — let Codex fix failing tests on its own:
codex --sandbox workspace-write "Run all tests. If any fail:
1. Analyze the failure reasons
2. Fix the code (not the tests)
3. Re-run tests
4. Repeat above steps until all tests pass
Finally, provide a fix summary."
Example 6: Implement UI from Design Mockup¶
codex -i design.png "Implement this page using React + Tailwind CSS based on this design mockup.
Requirements:
1. Responsive layout (mobile support)
2. Pixel-perfect recreation of the design mockup
3. Reasonable component splitting
4. Add basic interaction states (hover, focus)"
Example 7: Database Migration¶
codex "I need to add an avatar_url field (varchar 500, nullable) to the users table.
Please:
1. Create Alembic migration script
2. Update SQLAlchemy model
3. Update related Pydantic schema
4. Update CRUD operation functions
5. Add corresponding API endpoints (GET/PUT)
6. Run migration and confirm success"
Example 8: Auto-Generate Changelog in CI/CD¶
codex --sandbox workspace-write "Analyze all git commits from the last release tag to now,
categorize them according to conventional commits specification,
and generate CHANGELOG.md update content.
Include: new features, bug fixes, breaking changes, other improvements."
8. FAQ¶
Configuration File Not Found¶
Problem: Codex prompts that configuration file not found or cannot load configuration
Solution:
- Check if configuration directory exists:
ls ~/.codex/ - Confirm both files
config.tomlandauth.jsonexist - Check if
config.tomlTOML syntax is correct (common errors: missing quotes, typos) - Run
codex doctorto generate a diagnostic report covering installation, configuration and authentication
API Key Authentication Failed¶
Problem: Prompt 401 Unauthorized or API Key invalid
Solution:
- Confirm API key format is correct (starts with
cr_) - Check if key in
auth.jsonis complete (no extra spaces or line breaks) - If you use the environment-variable variant, confirm the provider has
env_key = "QCODE_API_KEY", has norequires_openai_auth = true, and the variable is exported - Log in to QCode.cc console to confirm key status and remaining quota
Network Connection Issues¶
Problem: Cannot connect to QCode.cc service, timeout or connection refused
Solution:
- Check if network is normal:
curl -I https://api.qcode.cc - Verify
base_urlconfiguration is correct (must behttps://api.qcode.cc/openai) -
Try another endpoint:
-
Asia endpoint:
https://asia.qcode.cc/openai - If using company proxy/VPN, confirm proxy settings don't block HTTPS requests
Model Selection Advice¶
Problem: Unsure which model to choose
Advice:
| Your Need | Recommended Model | Reason |
|---|---|---|
| Programming tasks | gpt-5.6-terra |
Code-optimized |
| Complex tasks | gpt-6.1-sol |
Recommended by the official Codex documentation, 1.05M context |
| Complex tasks (alternative) | gpt-6-sol |
Strong general capability, 1.05M context |
| Top capability | gpt-6-astra |
Strongest tier |
After setting default model in config.toml, you can also switch temporarily:
codex -m gpt-6-sol "Analyze this complex concurrency bug"
Sandbox Restrictions Causing Command Failures¶
Problem: Commands Codex attempts to execute are rejected by sandbox
Solution:
- If it's a network operation (like
npm install), temporarily enable network:bash codex -c 'sandbox_workspace_write.network_access=true' "Install dependencies" - If you need to write files outside the project directory, temporarily expand writable scope:
bash codex --sandbox danger-full-access "Save output to /tmp/result.txt" - Use
/permissionsduring session to view and adjust current permissions
Cost Explanation¶
Problem: How are Codex and Claude Code costs calculated?
Explanation:
- Codex and Claude Code share QCode.cc plan quota
- The same plan can be used by both tools simultaneously
- Costs are calculated based on actual token consumption, not by tool
- When Codex iterates autonomously for multiple rounds, token consumption for a single task may be higher, but it saves the developer's interaction time
- QCode bills per token; per-model rates are on qcode.cc/models, and you can check usage in the QCode.cc console
Can AGENTS.md and CLAUDE.md Coexist?¶
Yes. If your project is used by both Codex and Claude Code:
- Codex only reads
AGENTS.md, ignoresCLAUDE.md - Claude Code only reads
CLAUDE.md, ignoresAGENTS.md - They don't interfere with each other, you can maintain separate instruction files for different tools
- It's recommended to keep core specifications consistent in both files (such as test commands, code style, etc.)
10. Related Documentation¶
- Environment Variables Configuration — Environment variable settings for Claude Code
- Quick Start — Claude Code quick start guide
- Aider Integration — Configuration for another open-source AI programming assistant
- CLI Tips — Advanced command-line usage for Claude Code
- Workflow Tips — Workflow suggestions for improving AI programming efficiency
Get started with QCode
One API key for Claude Code, Codex and more — billed per token, per-model prices on qcode.cc/models