# Codex CLI config.toml: Custom Provider (Windows, macOS)


**Short answer**: In Windows Terminal, paste `irm https://qcode.cc/install/codex.ps1 | iex`, choose `2` to install Codex CLI when prompted, and paste your `cr_` key. The script writes `base_url = "https://api.qcode.cc/openai"` and your key into `%USERPROFILE%\.codex\`, and after that you can run `codex` right away.

| Item | Fill in |
|---|---|
| Endpoint address (`base_url`) | `https://api.qcode.cc/openai` |
| Default model | `gpt-6.2-sol` |
| Config file | `%USERPROFILE%\.codex\config.toml` |
| Key file | `%USERPROFILE%\.codex\auth.json` |
| Key format | `cr_xxxxxxxx` |

Checked on 2026-11-22 · codex-cli 0.171.0 · Windows 11

Latest stable on GitHub Releases on 2026-11-29: Codex CLI 0.172.0 (2026-11-24). The `config.toml` keys used here (`model_provider`, `[model_providers.qcode]`, `base_url`, `wire_api = "responses"`, `requires_openai_auth` / `env_key`) are unchanged in the config reference; screenshots were taken on 0.171.0.


Follow the screenshots below step by step, and in about ten minutes your Windows PC or Mac will have Codex CLI installed and connected to QCode — open Windows Terminal, type `codex`, and you can start chatting.

Using Codex CLI through QCode requires only a QCode API key, with no OpenAI or ChatGPT account needed; native PowerShell on Windows 10 / 11 runs it directly without installing WSL first. Usage is identical in every region, with differences only in download channels.


- **Applies to**: Windows 10 / 11 (64-bit) and macOS
- **Software version**: Codex CLI 0.171.0 · one-line script v2026.11.21.1
- **Screenshots updated**: 2026-11
- **Time needed**: 10 minutes (allow a few extra minutes if Node.js is installed for the first time)
- **You will need**: a QCode API key starting with `cr_`; a Windows PC or a Mac with internet access


> **On a Mac?** Run the same steps in Terminal. The screenshots show Windows PowerShell; on macOS, set a variable with `export NAME="value"` instead of `$env:NAME = "value"`, and read `%USERPROFILE%\` as `~/` in file paths. The **Official install script (macOS / Linux)** section of this page has the commands that differ.


- The computer runs Windows 10 / 11 (64-bit) or macOS, and can open Terminal (Windows Terminal or Windows PowerShell on Windows)
- You have already signed up for QCode.cc and copied your API key starting with `cr_` from the [Dashboard](https://qcode.cc/en/dashboard). No account yet? [Sign up](https://qcode.cc/en/auth/sign-up?utm_source=docs.qcode.cc&utm_medium=tut_before&utm_campaign=knowledge_base&src=docs-ide-codex-before) first, pick a plan on the [pricing page](https://qcode.cc/en/pricing?utm_source=docs.qcode.cc&utm_medium=tut_before&utm_campaign=knowledge_base&src=docs-ide-codex-before), then create a key in the [Dashboard](https://qcode.cc/en/dashboard).
- The PC can reach `qcode.cc`, `api.qcode.cc`, and `probe.qcode.cc`; if downloads fail, see the region notes below
- Set aside 10 uninterrupted minutes; when installing Node.js, Windows will show one User Account Control prompt — click Yes


## Download and install

This one-line script **has no standalone installer**: the command in step 2 below fetches and runs the script directly. The script installs Node.js and Codex CLI automatically as needed, so you do not need to download anything beforehand.

The three components the script uses come from:

- **One-line script**: `https://qcode.cc/install/codex.ps1`
- **Node.js**: installed via winget as LTS by the script; if that fails, download the `.msi` from <https://nodejs.org/>
- **Codex CLI**: installed via `npm install -g @openai/codex`; source and docs at <https://github.com/openai/codex>

The script first tests latency against three ingress domains: `api.qcode.cc` is the global entry, `asia.qcode.cc` serves Asia, and `us.qcode.cc` serves North America and Europe. All three work, and you can pick whichever is faster at the latency step; this walkthrough fixes on `api.qcode.cc`.

The only regional difference is **download channels** — pick your region first:

**Europe / Japan**

- Microsoft Store, winget, and the official websites all work: `winget install Microsoft.WindowsTerminal`, `winget install OpenJS.NodeJS.LTS`; you can also download the Node.js `.msi` from **nodejs.org**.
- The one-line script goes through `qcode.cc`, which is normally reachable directly.


**Mainland China**

- The built-in Windows PowerShell works out of the box, with nothing extra required. If you want a nicer window, install Windows Terminal from Microsoft Store, or run `winget install Microsoft.WindowsTerminal` if the Store will not open.
- Node.js is normally installed by the script via winget. If the script says winget was not found or winget fails to download, get the x64 `.msi` (ARM64 on ARM machines) from **nodejs.org**, install it, and re-run the script. `nodejs.org` can be intermittent; if it does not open, use the matching version from **nodejs.cn** or `npmmirror.com/mirrors/node/`.
- If the official npm registry is unreachable, switch temporarily to a mirror: `npm config set registry https://registry.npmmirror.com`.
- The one-line script itself goes through `qcode.cc`, which is normally reachable directly.


**Arab countries**

- The download channels are the same as Europe / Japan: Microsoft Store, winget, and **nodejs.org** all work.
- The one-line script goes through `qcode.cc`, which is normally reachable directly.


**Russia / Iran**

- Microsoft Store, winget, and **nodejs.org** generally work; if `nodejs.org` does not open, use the matching version from **nodejs.cn** or `npmmirror.com/mirrors/node/`.
- The one-line script goes through `qcode.cc`, which is normally reachable directly.
- If you want to inspect what the script will do before running it, pass `-DryRun`: it only prints the plan without writing files, installing software, or sending requests.


To inspect the source code before running it, open <https://qcode.cc/install/codex.ps1> directly.

## Follow the screenshots: Windows, one step at a time

The 21 steps below each do one thing. The orange numbers on the screenshots (①, ②…) match the numbers in the text one to one — when you see a number, look at the same spot in the picture.



### Open Windows Terminal

Click the Start menu, type `Windows Terminal` or `Windows PowerShell`, and open it. In the screenshot, the tab at ① reads `Windows PowerShell` and ② is the command prompt, where you will enter every command that follows.

![Opening Windows Terminal from the Start menu: the default tab is Windows PowerShell (1), and the line below is the command prompt (2) where all following commands are entered](https://docs.qcode.cc/static/images/tut/codex/202611/zh/01-terminal-window.webp)


Done right you will see: a dark window with a `Windows PowerShell` tab and `PS C:\Users\<your username>>` before the cursor.


**Stuck? The prompt only shows C:\Users\... with no PS**

That is Command Prompt (CMD), where the command below will not work. Close that window and open Windows Terminal or Windows PowerShell from the Start menu instead.




### Paste the one-line command

Paste the command below at the cursor marked ① and press Enter:

```powershell
irm https://qcode.cc/install/codex.ps1 | iex
```

After a brief pause of a second or two while the script downloads, the two-line banner at ② appears along with `[1/6]`, starting the latency test for the 3 ingress domains (③). The version number in the banner changes as the script updates, so any version you see is normal.

![After pasting the one-line command (1) and pressing Enter: the two-line QCode script banner and version number appear (2), followed by [1/6] starting the latency test for 3 ingress domains (3)](https://docs.qcode.cc/static/images/tut/codex/202611/zh/02-script-start.webp)


Done right you will see: two banner lines showing `QCode.cc · Codex 一键配置` (QCode.cc · Codex one-line setup) and a version number, followed by a latency-test line starting with `[1/6]`.


**Stuck? It says irm is not recognized as an internal or external command**

`irm` is a PowerShell command and CMD does not recognize it. Close that window, open Windows Terminal or Windows PowerShell again, and paste the command once more.




### Wait for the latency test results

Wait a few seconds. The three lines at ① show the latency to the three ingress domains, and the numbers vary on each run; if a line shows `[超时]` (timeout), that domain was unreachable at that moment and does not stop you from picking another. ② is the selection prompt — the number in square brackets is the fastest domain **for this run**, which is not always 1.

![Three latency test lines (1) showing response times for api.qcode.cc, asia.qcode.cc, and us.qcode.cc (numbers vary per run); the last line asks which ingress domain to pick (2), with the lowest-latency one in brackets, and the next step enters 1 for api.qcode.cc](https://docs.qcode.cc/static/images/tut/codex/202611/zh/03-endpoint-pick.webp)


Done right you will see: three lines starting with `1)`, `2)`, and `3)`, ending with a latency figure like `[123ms]` or `[超时]` (timeout).




### Enter 1 to select the ingress domain

On the bottom line (①), type `1` and press Enter — do not press Enter on its own, because pressing Enter accepts the current recommendation, which may not be `api.qcode.cc`. After Enter, ② displays `接入域: api.qcode.cc` (Ingress domain: api.qcode.cc) and `base_url=https://api.qcode.cc/openai`; ③ is the script prompting you to copy your key from `https://qcode.cc/en/dashboard`.

![Entering 1 and pressing Enter (1): ingress domain api.qcode.cc with base_url set to https://api.qcode.cc/openai; the script moves to [2/6] asking for the API key (2), reminding you to copy a cr_ key from https://qcode.cc/en/dashboard (3)](https://docs.qcode.cc/static/images/tut/codex/202611/zh/04-key-prompt.webp)


Done right you will see: `接入域: api.qcode.cc  ->  base_url=https://api.qcode.cc/openai` (Ingress domain: api.qcode.cc), followed on the next line by `[2/6]` asking for the key.


**Stuck? After pressing Enter it shows asia.qcode.cc or us.qcode.cc**

That means you pressed Enter directly and accepted the recommendation for that run. All three domains work and differ only in latency; if you want to lock in `api.qcode.cc`, re-run the script and enter `1` at this line.




### Paste your API key

Copy the string starting with `cr_` from the [Dashboard](https://qcode.cc/en/dashboard), return to the terminal window, paste it, and press Enter.

The line `API 密钥:` (API key:) at ① is the input prompt; once pasted, ② shows only a row of asterisks rather than the real characters. There is one asterisk per character of the key, so even if it looks like nothing real was pasted, it is there. For the same reason, **never paste your key into chat windows, screenshots, or screen recordings**.

![After pasting the key, only a long string of asterisks is shown (2) with no real characters visible; press Enter below to submit](https://docs.qcode.cc/static/images/tut/codex/202611/zh/05-key-asterisks.webp)


Done right you will see: a string of asterisks after `API 密钥:` (API key:), and the next line appears right after you press Enter.


**Need an API key?**

If you do not have a QCode account yet, [Sign up](https://qcode.cc/en/auth/sign-up?utm_source=docs.qcode.cc&utm_medium=tut_key_step&utm_campaign=knowledge_base&src=docs-ide-codex-key) first. If you prefer to pay by usage, buy a [Pay-as-you-go Pack](https://qcode.cc/en/pay-as-you-go?utm_source=docs.qcode.cc&utm_medium=tut_key_step&utm_campaign=knowledge_base&src=docs-ide-codex-key) first, then create the key in the [Dashboard](https://qcode.cc/en/dashboard). Copy the whole string that starts with `cr_` and paste it back above. You can pay by credit/debit card (Visa / Mastercard), Apple Pay / Google Pay, or cryptocurrency — see [Payment methods](/docs/reference/payment-methods).




### Confirm the key was read

After pressing Enter, ① shows `已读取密钥: cr_****` (Key read: cr_****) followed by the last four characters — the script only reveals the last four characters, confirming the key was received and its format is valid.

![After Enter, the script displays only the masked key with its last four characters (1); [3/6] asks which Codex client to configure (2), and this walkthrough enters 2 for the CLI (3)](https://docs.qcode.cc/static/images/tut/codex/202611/zh/06-target-cli.webp)


Done right you will see: a line reading `已读取密钥: cr_****` (Key read: cr_**** plus the last four characters), starting with `cr_`.




### Choose Codex CLI

`[3/6]` at ② asks which Codex client you want to use: `1)` is the desktop app (writes config only, without installing Node.js or the CLI), and `2)` is Codex CLI (also applies to the desktop app, and installs Node.js and Codex CLI as needed). This walkthrough installs the CLI, so type `2` at ③ and press Enter.

![[3/6] asks which Codex client to use (2): 1 is the desktop app, 2 is Codex CLI; this walkthrough enters 2 (3)](https://docs.qcode.cc/static/images/tut/codex/202611/zh/06-target-cli.webp)


Done right you will see: two choices starting with `1)` and `2)`; entering `2` and pressing Enter moves to `[4/6]` to fetch the model list.




### Choose the default model

`[4/6]` fetches the model list (①), 8 models in total. The first item, `gpt-6.2-sol`, is marked `推荐` (recommended, ②) — just press Enter (③) to use it.

![Entering 2 and pressing Enter moves to [4/6] fetching the model list (1); 8 models appear, with the first item gpt-6.2-sol marked recommended (2), and Enter selects it (3)](https://docs.qcode.cc/static/images/tut/codex/202611/zh/07-model-list.webp)


Done right you will see: `gpt-6.2-sol` as the first item in the list, marked recommended; after pressing Enter, the script confirms the default model.




### Watch the script write the config

After Enter, ① confirms the default model `gpt-6.2-sol`; `[5/6]` writes the configuration into `C:\Users\<username>\.codex`, and ② shows `已写入 config.toml + auth.json` (written to config.toml + auth.json).

![After Enter, default model gpt-6.2-sol is confirmed (1), [5/6] writes config into C:\Users\<username>\.codex and prints config.toml + auth.json written (2); [6/6] detects Codex CLI is missing and asks whether to install it with npm (3), press Enter to continue](https://docs.qcode.cc/static/images/tut/codex/202611/zh/08-config-written.webp)


Done right you will see: the two lines `默认模型: gpt-6.2-sol` (Default model: gpt-6.2-sol) and `已写入 config.toml + auth.json` (written to config.toml + auth.json), pointing to `C:\Users\<your username>\.codex`.




### Agree to install Codex CLI with npm

`[6/6]` detects that Codex CLI is not installed on this PC yet, and ③ asks `未检测到 Codex CLI，使用 npm 安装？ [Y/n]:` (Codex CLI not detected, install with npm? [Y/n]:). Press Enter directly (= Y) to let it install.

![[6/6] detects Codex CLI is not installed and asks whether to install via npm (3), followed by [Y/n]; press Enter to continue](https://docs.qcode.cc/static/images/tut/codex/202611/zh/08-config-written.webp)


Done right you will see: `[Y/n]` at the end of the prompt; after Enter, the script moves on to prepare the installation.




### Agree to install Node.js with winget

After answering Y, ② displays `[!] 未检测到 Node.js` (Node.js not detected), and ③ asks `使用 winget 安装 Node.js LTS？ [Y/n]:` (Install Node.js LTS with winget? [Y/n]:) — press Enter again. ① is the npm install prompt from `[6/6]` just above.

![After answering Y, the script reports Node.js not detected (2) and asks whether to install Node.js LTS with winget (3); press Enter to agree. Above it is the [6/6] npm install prompt (1)](https://docs.qcode.cc/static/images/tut/codex/202611/zh/09-node-prompt.webp)


Done right you will see: `[Y/n]` at the end of the second prompt; after Enter, the script starts downloading Node.js, which takes a short while.


**Stuck? A User Account Control dialog popped up**

Windows is asking for administrator permission once to install Node.js. Confirm the publisher says `Windows Package Manager Client` and click Yes (or press `Alt` + `Y`). Clicking No cancels the install; just re-run the script to try again.




### Check the access verification result

The script sends a minimal test request using your key. When ① shows `接入验证通过！模型 gpt-6.2-sol 响应正常` (Access verified! Model gpt-6.2-sol responds normally), the entire chain — key, endpoint address, and network — works end to end.

![The script sends a minimal test request and reports access verified with gpt-6.2-sol responding normally (1); the summary lists ingress domain api.qcode.cc, default model gpt-6.2-sol, and config paths (2); finally it asks whether to launch Codex now (3), where this walkthrough answers n to run it manually](https://docs.qcode.cc/static/images/tut/codex/202611/zh/10-done-summary.webp)


Done right you will see: the line `接入验证通过！模型 gpt-6.2-sol 响应正常` (Access verified! Model gpt-6.2-sol responds normally).


**Stuck? Verification did not pass**

Check the status code printed above: for `401`, double-check your key in the Dashboard; for `404`, check that `base_url` is `https://api.qcode.cc/openai`; on a timeout, re-run the script and pick another ingress domain. Then see Common errors below.




### Read the final summary

The summary at ② lists what was configured: ingress domain `api.qcode.cc`, default model `gpt-6.2-sol`, and the config file paths. Seeing these lines means both configuration and verification are complete.

![Summary listing ingress domain api.qcode.cc, default model gpt-6.2-sol, and config file paths (2)](https://docs.qcode.cc/static/images/tut/codex/202611/zh/10-done-summary.webp)


Done right you will see: ingress domain `api.qcode.cc`, model `gpt-6.2-sol`, and config file paths inside `C:\Users\<your username>\.codex`.




### Choose manual launch

At ③, the script asks whether to launch Codex immediately. In this walkthrough, type `n` and press Enter to return to the shell prompt and run it manually, so you can verify the version in the next step.

![Final prompt asking whether to launch Codex immediately (3); entering n and pressing Enter returns to the shell prompt](https://docs.qcode.cc/static/images/tut/codex/202611/zh/10-done-summary.webp)


Done right you will see: after entering `n`, you return to the `PS` prompt instead of launching straight into Codex.




### Check the codex version

Back at the prompt, run `codex --version`. ① outputs `codex-cli 0.171.0`, confirming the command is installed and `PATH` has taken effect.

![Back at the prompt after answering n, running codex --version outputs codex-cli 0.171.0 (1), confirming the binary is installed and PATH works](https://docs.qcode.cc/static/images/tut/codex/202611/zh/11-codex-version.webp)


Done right you will see: a line reading `codex-cli 0.171.0` (the trailing version number may change with future releases).


**Stuck? It says codex is not found**

The current terminal window has not refreshed `PATH` yet. Close this window, open a new Windows Terminal window, and try again; if it still fails, re-run the one-line script so it reinstalls Codex CLI.




### Choose the non-admin sandbox

The first time you run `codex`, it asks you to pick a sandbox (①): `1. Set up default sandbox (requires Administrator permissions)` is the default sandbox requiring admin rights; `2. Use non-admin sandbox (higher risk if prompt injected)` is the non-admin sandbox (②). Press `↓` then Enter to choose 2 (③ shows the key hints).

![First launch of codex asks about the sandbox (1): 1 is the default sandbox requiring admin permissions, 2 is the non-admin sandbox (2); this walkthrough picks 2 using down arrow then Enter (3 shows key hints)](https://docs.qcode.cc/static/images/tut/codex/202611/zh/12-sandbox-setup.webp)


Done right you will see: after choosing 2, the selector closes and the Codex interactive interface opens; from then on, `config.toml` records `[windows] sandbox = "unelevated"`.




### Enter the Codex interactive interface

Once inside, ① at the top shows the OpenAI Codex version, ② in the middle reads `Sandbox ready`, and ③ on the bottom status bar shows `GPT-6.2-Sol high` — confirming it loaded `gpt-6.2-sol` and `high` from `config.toml`.

![Inside the Codex interactive interface: top header shows the OpenAI Codex version (1), middle shows Sandbox ready (2), and bottom status bar shows GPT-6.2-Sol high (3), confirming it read gpt-6.2-sol and high from config.toml](https://docs.qcode.cc/static/images/tut/codex/202611/zh/13-codex-ready.webp)


Done right you will see: `Sandbox ready` in the middle, `GPT-6.2-Sol high` on the bottom status bar, and an input box ready for typing.




### Send a sentence to verify the reply

In the ① input box, send "Say hello in one sentence" (shown as `用一句话打个招呼` in the screenshot) and press Enter. A few seconds later, the model replies ("Hello, nice to meet you!", shown as `你好，很高兴见到你！` at ②); ③ at the bottom still shows `GPT-6.2-Sol high`, confirming the request ran through QCode's `gpt-6.2-sol`.

![Sending a short greeting prompt in the input box (1), with the model replying a few seconds later (2); the bottom status bar still reads GPT-6.2-Sol high (3), confirming the request used QCode gpt-6.2-sol](https://docs.qcode.cc/static/images/tut/codex/202611/zh/14-codex-reply.webp)


Done right you will see: your message in the conversation area, a complete reply underneath it, and `GPT-6.2-Sol high` still on the bottom status bar.




### Check config.toml manually

Open `C:\Users\<username>\.codex\config.toml` in Notepad: ① the top lines set the provider and model; ② `base_url` must be `https://api.qcode.cc/openai`, with no `/v1` and no trailing slash; ③ `requires_openai_auth = true` tells Codex to use the key from `auth.json`.

![Opening C:\Users\<username>\.codex\config.toml in Notepad (manual config 1 of 3): top 4 lines set provider and model (1), base_url must be https://api.qcode.cc/openai with no /v1 or trailing slash (2), and requires_openai_auth = true uses the key in auth.json (3)](https://docs.qcode.cc/static/images/tut/codex/202611/zh/15-config-toml.webp)


Done right you will see: `model_provider = "qcode"`, `model = "gpt-6.2-sol"`, `model_reasoning_effort = "high"`, `[model_providers.qcode]`, plus `base_url = "https://api.qcode.cc/openai"` and `requires_openai_auth = true`.


**Stuck? base_url has an extra /v1 or trailing slash**

Codex appends `/responses` to `base_url` automatically, so an extra path segment causes a 404. Change that line back to `base_url = "https://api.qcode.cc/openai"`, save the file, and reopen `codex`.




### Check auth.json manually

Open `auth.json` in the same folder (①): the key name must be `OPENAI_API_KEY`, and the value is your `cr_` key (masked in the screenshot). The JSON only needs these three lines, using straight ASCII quotes and colons.

![auth.json in the same folder (manual config 2 of 3): key name must be OPENAI_API_KEY (1) with your cr_ key as the value; only three lines of JSON with straight quotes and colon](https://docs.qcode.cc/static/images/tut/codex/202611/zh/16-auth-json.webp)


Done right you will see: three lines of JSON — `{` on line 1, `"OPENAI_API_KEY": "cr_…"` on line 2, and `}` on line 3.


**Stuck? It shows 401 or Invalid API key**

First confirm the key name is `OPENAI_API_KEY`, not `ANTHROPIC_API_KEY`; then copy the entire `cr_` string again with no spaces or line breaks. Save the file and reopen `codex`.




### Confirm there is no extra .txt

Open File Explorer, enter `%USERPROFILE%\.codex` in the address bar, and press Enter: you will see `auth.json` (①) and `config.toml` (②). Check the Type column at ③ — they should show as JSON File and TOML File (in Chinese Windows, `JSON 文件` and `TOML 文件`), not Text Document (`文本文档`), confirming there is no hidden `.txt` extension.

![Entering %USERPROFILE%\.codex in File Explorer (manual config 3 of 3): auth.json (1) and config.toml (2) appear in the folder, and the Type column (3) shows JSON File / TOML File rather than Text Document, confirming no extra .txt](https://docs.qcode.cc/static/images/tut/codex/202611/zh/17-config-files.webp)


Done right you will see: `auth.json` listed as a JSON File and `config.toml` as a TOML File. Runtime files such as `sessions`, `logs_*.sqlite`, and `memories_*.sqlite` also appear in this folder — that is normal.


**Stuck? The file became config.toml.txt**

Notepad saves as `.txt` by default. Open the file in Notepad, click File → Save As, change "Save as type" to "All Files", set the file name to `config.toml`, and save; then verify in File Explorer that its type changed back to TOML File.




## Verify it works

When all three of these check out, you are done:

- `codex --version` prints a version number, `codex-cli 0.171.0`;
- Running `codex` opens the interactive interface with `GPT-6.2-Sol high` on the bottom status bar, and sending a sentence gets a normal reply;
- To double-check that requests really went through QCode: open [probe.qcode.cc](https://probe.qcode.cc/), enter your key, and you will see the request you just sent with the model name `gpt-6.2-sol`.


### All done

Your Windows PC now has Codex CLI installed and connected to QCode: from now on, open Windows Terminal and run `codex` whenever you want to use it. From here you can:

- [Claude Code complete tutorial](/docs/getting-started/claude-code-tutorial)
- [Codex vs Claude Code comparison](/docs/getting-started/codex-vs-claude-code)
- [Endpoints and API formats](/docs/getting-started/endpoints-and-api-paths)
- [Troubleshooting guide](/docs/reference/troubleshooting)
- Next: compare the plans on the [pricing page](https://qcode.cc/en/pricing?utm_source=docs.qcode.cc&utm_medium=tut_done&utm_campaign=knowledge_base&src=docs-ide-codex-done) and pick the one that suits long-term use
- Go back to your [Dashboard](https://qcode.cc/en/dashboard) to check usage and balance


## Common errors

| Error message | Why | What to do |
|---|---|---|
| `401 invalid_request_error: You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth` | `auth.json` is missing `OPENAI_API_KEY`, the key name is misspelled, or `config.toml` does not have `requires_openai_auth = true`, so Codex did not read the key | Write `{"OPENAI_API_KEY": "cr_xxxxxxxx"}` in `%USERPROFILE%\.codex\auth.json`, keep `requires_openai_auth = true` in `config.toml`, save, and reopen `codex` |
| `Invalid API key` (code `invalid_api_key`) | The key is truncated, has extra spaces or line breaks, or was copied from another account | Go to the [Dashboard](https://qcode.cc/en/dashboard), copy the entire `cr_` key again, replace the value in `auth.json`, save, and reopen `codex` |
| `Not found` (code `not_found`) | `base_url` has an extra `/v1` or trailing slash so Codex builds the wrong `/responses` path, or the ingress domain is mistyped | Set `base_url` back to `https://api.qcode.cc/openai`; if connectivity from Mainland China is unstable, switch to `https://asia.qcode.cc/openai`, save, and reopen `codex` |
| `[!] 未检测到 Node.js` | Node.js is not installed on this PC yet, so the script cannot install Codex CLI with npm | Press Enter at the prompt to let the script install Node.js LTS via winget; click Yes on the User Account Control prompt; once installed, re-run the script |

## FAQ

### What if the configuration file is not found?

First confirm both files exist: `%USERPROFILE%\.codex\config.toml` and `%USERPROFILE%\.codex\auth.json`. Next check the TOML syntax in `config.toml` (common mistakes: missing quotes or a typo in a table header). Finally run `codex doctor` to produce a diagnostic report covering installation, configuration, and authentication.

### What if API key authentication fails?

First make sure the key starts with `cr_`, is copied completely, and has no extra spaces or line breaks in `auth.json`. Then check `config.toml`: when using `auth.json`, keep `requires_openai_auth = true` and do not set `env_key` at the same time; when using an environment variable, switch to `env_key = "QCODE_API_KEY"` and confirm the variable is set. Pick only one of the two methods.

### What if network connections time out?

First verify `base_url` is exactly `https://api.qcode.cc/openai`, with no `/v1` and no trailing slash. If connectivity in Mainland China is unstable, switch to `https://asia.qcode.cc/openai`; in North America or Europe you can try `https://us.qcode.cc/openai`. If your corporate network uses a proxy or VPN, make sure it does not block HTTPS requests.

### Which model should I use?

| What you need | Recommended model | Why |
|---|---|---|
| Daily and complex coding workhorse | `gpt-6.2-sol` | 1.05M context / 128K output, balanced all round |
| Hardest multi-step agent work | `gpt-6.2-astra` | The flagship one tier up, suited to cross-module architecture and long tasks |
| Previous-generation high-end model | `gpt-6-astra` | Still usable; for new tasks switch to `gpt-6.2-astra` |

Edit `model` in `config.toml` to change the default model, or override it for a single run with `codex -m gpt-6.2-sol "your task"`. Note that `gpt-6.2-*` does not support `model_reasoning_effort = "none"`.

### What if sandbox restrictions cause commands to fail?

For network operations (such as `npm install`), you can enable network access temporarily:

```bash
codex -c 'sandbox_workspace_write.network_access=true' "Install dependencies and run tests"
```

If you need to write files outside the project directory, you can relax the sandbox temporarily:

```bash
codex --sandbox danger-full-access "Save the output to a temporary directory"
```

During a session you can also use `/permissions` to inspect and adjust current permissions.

### How is usage billed?

Codex and Claude Code can share the same QCode API key; billing is based on actual token consumption rather than the tool you use. When Codex iterates autonomously across multiple rounds, a single task can consume more tokens; check usage and balance in the [Dashboard](https://qcode.cc/en/dashboard).

### What happens when my key expires?

Two cases:

- A **personal plan** key cannot be renewed when it expires — reopen a plan and use a new key.
- For a **pay-as-you-go pack**, buy another pack after the key expires and the same key starts working again.

After switching keys, remember to update `OPENAI_API_KEY` in `auth.json`.

### Can AGENTS.md and CLAUDE.md coexist?

Yes. Codex reads only `AGENTS.md` and ignores `CLAUDE.md`; Claude Code reads only `CLAUDE.md` and ignores `AGENTS.md`. They do not interfere with each other, and it is a good idea to keep core rules such as test commands and code style aligned across both files.

## Connection overview

| Item | Details |
|---|---|
| Available models | GPT ✅ (Responses protocol) · Claude ❌ · Chinese models ❌ (the Responses protocol does not serve Chinese models) · Gemini ❌ (not offered by QCode) |
| Protocol and Base URL | Codex uses OpenAI Responses: in `config.toml` write `base_url = "https://api.qcode.cc/openai"` + `wire_api = "responses"` |
| Config location | `~/.codex/config.toml` (on Windows, `%USERPROFILE%\.codex\`) |
| Official docs | [openai/codex](https://github.com/openai/codex) |

## What is Codex CLI

[Codex CLI](https://github.com/openai/codex) is an open-source command-line AI coding assistant from OpenAI (Apache 2.0 license), written in Rust and running directly in your terminal. It reads and understands code repositories, edits files, executes commands, and hands the finished results back to you for review.

Codex is built around an **autonomous agent** workflow: you describe the task, it completes the work inside a sandbox, and you review the outcome. It complements Claude Code's interactive pair-programming style: Codex fits clearly defined tasks you can delegate end to end, while Claude Code fits exploratory work where you discuss and iterate along the way.

The name "Codex" has gone through several iterations: in 2021 it was a code-fine-tuned GPT-3 model powering GitHub Copilot; in 2024 OpenAI revived the brand for an asynchronous cloud coding agent; in 2025–2026 it evolved into a mature local command-line tool. Today Codex spans a CLI, desktop app, IDE extensions, and a cloud agent inside ChatGPT — through QCode you use the CLI.

| 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 sandbox and approval policy | Permission prompt confirmation |
| Instruction file | `AGENTS.md` | `CLAUDE.md` |

Using Codex CLI through QCode lets a single `cr_` key call GPT models; the same key also works in Claude Code.

## Other installation methods

On Windows, the one-line script above is the easiest path. To install manually, or on macOS / Linux, choose any method below.

Before installing manually, check your environment: macOS 12+, Ubuntu 20.04+, or Windows 10+; the npm method requires Node.js 22 LTS or higher; Codex needs Git 2.x or higher to detect repositories; keep about 200 MB of disk space available.

### Install via npm (all platforms)

```bash
npm install -g @openai/codex
```

Requires Node.js 22 LTS or higher. On macOS / Linux, add `sudo` if you hit permission errors, or manage Node.js with nvm. If npm downloads slowly, switch to a mirror temporarily:

```bash
npm install -g @openai/codex --registry=https://registry.npmmirror.com
```

### Install via Homebrew (macOS)

```bash
brew install --cask codex
```

Homebrew handles dependencies and updates automatically.

### Direct binary download (advanced)

Download a prebuilt binary for your platform from [GitHub Releases](https://github.com/openai/codex/releases) and place it on your `PATH`. This method does not depend on Node.js. Release 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.

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

### Official install script (macOS / Linux)

```bash
curl -fsSL https://chatgpt.com/codex/install.sh | sh
```

Confirm the installation with `codex --version`. Do not treat version numbers in documentation as "the current latest" — check [GitHub Releases](https://github.com/openai/codex/releases) and the [npm package](https://www.npmjs.com/package/@openai/codex), and run `codex --version` to see what is installed on your machine.

### Configure shell completion (optional)

```bash
# Zsh users
echo 'eval "$(codex completion zsh)"' >> ~/.zshrc
source ~/.zshrc

# Bash users
echo 'eval "$(codex completion bash)"' >> ~/.bashrc
source ~/.bashrc
```

If Zsh reports `command not found: compdef`, add `autoload -Uz compinit && compinit` before `eval`.

## Write the config manually (without the one-line script)

The one-line script already wrote both files for you. If you prefer writing them yourself, or are configuring macOS / Linux, follow the steps below.

### Create the config directory

Windows (PowerShell):

```powershell
mkdir $HOME\.codex
```

macOS / Linux:

```bash
mkdir -p ~/.codex
```

### Create config.toml

Write this into `~/.codex/config.toml`:

```toml
model_provider = "qcode"
model = "gpt-6.2-sol"
model_reasoning_effort = "high"

[model_providers.qcode]
name = "qcode"
base_url = "https://api.qcode.cc/openai"
wire_api = "responses"
requires_openai_auth = true
```

### Create auth.json

Write this into `~/.codex/auth.json`:

```json
{
  "OPENAI_API_KEY": "cr_xxxxxxxx"
}
```

Replace `cr_xxxxxxxx` with your QCode API key (starting with `cr_`). Set file permissions to `600` (owner read/write only): `chmod 600 ~/.codex/auth.json`.

### Environment variable alternative (pick one)

To pass the key through an environment variable instead, replace `requires_openai_auth = true` under `[model_providers.qcode]` with `env_key = "QCODE_API_KEY"` and set that variable. **Pick exactly one**: when `requires_openai_auth = true` is present, Codex ignores `env_key`.

```toml
model_provider = "qcode"
model = "gpt-6.2-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"
```

Windows (PowerShell):

```powershell
# Temporary (current session)
$env:QCODE_API_KEY = "cr_xxxxxxxx"

# Permanent (writes a user environment variable)
[System.Environment]::SetEnvironmentVariable("QCODE_API_KEY", "cr_xxxxxxxx", [System.EnvironmentVariableTarget]::User)
```

macOS / Linux:

```bash
# Temporary
export QCODE_API_KEY="cr_xxxxxxxx"

# Permanent (Bash)
echo 'export QCODE_API_KEY="cr_xxxxxxxx"' >> ~/.bashrc
source ~/.bashrc

# Permanent (Zsh)
echo 'export QCODE_API_KEY="cr_xxxxxxxx"' >> ~/.zshrc
source ~/.zshrc
```

### config.toml field reference

| Field | What it does |
|---|---|
| `model_provider` | Name of the model provider to use; here the custom `qcode`. You can pick any name as long as it matches `[model_providers.<name>]` |
| `model` | Default model; `gpt-6.2-sol` is recommended, or choose `gpt-6.2-astra` for the hardest tasks |
| `model_reasoning_effort` | Reasoning effort; supports `low`, `medium`, `high`, and `xhigh`. `gpt-6.2-*` rejects `none`, so keep `high` or `xhigh` — higher is more accurate but slower |
| `base_url` | QCode ingress address. Codex uses `https://api.qcode.cc/openai`, with no `/v1` and no trailing slash |
| `wire_api` | API protocol type; Codex currently supports only `responses` |
| `requires_openai_auth` | Uses OpenAI-style auth, reading the key from `OPENAI_API_KEY` in `~/.codex/auth.json`. When set to `true`, Codex ignores `env_key` |

The one-line script also writes `review_model = "gpt-6.2-sol"`, `model_reasoning_effort = "high"`, `windows_wsl_setup_acknowledged = true`, `[tui] screen_reader_detection_done = true`, and `[windows] sandbox = "unelevated"`. These are runtime settings left by the script and first launch; do not edit them by hand.

### Available models

Through QCode you can choose from these Codex / GPT models:

| Model | Notes | Recommended for |
|---|---|---|
| **`gpt-6.2-sol`** | Main flagship released 2026-11-17, 1.05M context / 128K max output; rejects `model_reasoning_effort = "none"` | First choice for daily and complex coding (recommended) |
| **`gpt-6.2-astra`** | Top flagship released the same day, 1.05M context / 128K max output; also rejects `none` | Hardest multi-step agents and cross-module architecture |
| `gpt-6-astra` | Previous-generation top tier | High-end capability; for new tasks switch to `gpt-6.2-astra` |

QCode does not currently offer `gpt-6-luna` or `gpt-5.6-luna`. When using `gpt-6.2-*`, never set `model_reasoning_effort` to `"none"` — the API rejects it with an error; keep `"high"` or `"xhigh"`.

## Basic usage

### Launch Codex

Open a terminal, enter your project directory, and run:

```bash
cd /path/to/your/project
codex
```

Codex opens a terminal interactive interface (TUI) made up of three parts: a top status bar showing the current model, approval mode, and sandbox state; a main area showing AI replies and action logs; and a bottom input box for entering instructions.

You can also pass tasks directly on the command line (non-interactive mode), useful for scripts:

```bash
# Interactive launch
codex

# Non-interactive mode: run a single task and exit
codex "Read this project's structure and give me an overview"

# Task with an image
codex -i screenshot.png "Fix the UI issue shown in the screenshot"

# Specify a model
codex -m gpt-6.2-sol "Refactor error handling in the authentication module"
```

### First task: ask Codex to write a function

Run Codex in your project directory and enter:

```text
Write a Python function that accepts a list of strings and returns the longest one. If multiple strings tie for length, return the first one. Save it to utils.py.
```

Codex plans first, generates the code, and then checks the approval policy to decide whether to ask for confirmation. Under the read-only preset, or whenever a change requires approval (such as writing outside the workspace), it displays the proposed file changes and waits for you; under the default preset, edits inside the workspace run automatically.

When confirmation is required, you will see a prompt like this:

```text
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 on a tie."""
+     if not strings:
+         raise ValueError("List cannot be empty")
+     return max(strings, key=len)

Accept? [y/n]
```

Enter `y` to confirm and Codex writes the code to the file. You can keep sending follow-up instructions in the same session and Codex retains context:

```text
Write a unit test for this function using pytest
```

### Understand Codex's sandbox execution modes

Codex runs commands inside a **sandbox**, with three common modes:

| Sandbox mode | File read | File write | Command execution | Network access |
|---|---|---|---|---|
| `read-only` | Allowed | Needs confirmation | Needs confirmation | Needs confirmation |
| `workspace-write` (default) | Allowed | Allowed inside workspace | Allowed inside workspace | Denied by default |
| `danger-full-access` | Allowed | All allowed | All allowed | Allowed |

The default `workspace-write` mode is the best choice for everyday development: Codex can read and write files and run commands inside the project directory, but cannot touch files outside the project or reach the network. When a task needs the network (such as `npm install`), enable it temporarily:

```bash
codex -c 'sandbox_workspace_write.network_access=true' "Install dependencies and run tests"
```

### Review and accept Codex's changes

Codex applies file edits under an **approval policy**. In a Git repository, the default 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**: displayed to you and wait for confirmation;
- **Non-Git directories**: read-only by default, so Codex asks before changing anything.

When Codex proposes a change, you can accept (`y`), reject (`n`), or inspect the diff carefully before deciding. Use the `/diff` slash command at any time to review all edits applied in the current session.

### Everyday interaction tips

**File references**: Type `@` followed by a file path and Codex reads the file automatically:

```text
Review @src/app.py and improve error handling
```

**Run shell commands**: Prefix with `!` to run a command directly and pass its output to Codex:

```text
!cat error.log
Analyze the error log above and find the root cause
```

**Append instructions**: While Codex is running, press `Enter` to insert a new instruction or `Tab` to queue the next turn's instruction.

**Backtrack and edit**: With an empty input box, press `Esc` twice to jump back to the previous message to edit and resend it. Keep pressing `Esc` to step back to earlier messages, then press `Enter` to fork a new conversation branch from that point.

**Pipe input**: Pipe output from other commands directly into Codex:

```bash
# Review recent git changes
git diff HEAD~3 | codex "Review these changes and spot potential issues"

# Analyze error logs
cat /var/log/app/error.log | codex "Analyze the root causes of these errors"

# Review a PR
gh pr diff 42 | codex "Review this PR for code quality and security"
```

**Keyboard shortcuts**:

| Shortcut | Action |
|---|---|
| `Tab` | Autocomplete file paths (with `@`); queue the next turn's instruction while running |
| `Enter` | Insert a new instruction while running |
| `Esc` × 2 | Backtrack to the previous message to edit |
| `Ctrl+C` | Cancel the 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 |

### Command changes since Codex CLI 0.164.0

Codex CLI 0.164.0 was released on 2026-10-23 with these command- and configuration-facing changes:

- Save reusable prompts and slash commands in ten numbered `/presets` slots, with a keyboard menu for quick access;
- Set model, reasoning effort, speed, and permission profiles directly with inline `/model` and `/permissions` arguments;
- 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 configuration keys used above remain in 0.171.0: `model_provider`, `[model_providers.<id>]`, `base_url`, `wire_api`, and `requires_openai_auth`. The install commands are unchanged as well: `npm install -g @openai/codex`, `brew install --cask codex`, or `curl -fsSL https://chatgpt.com/codex/install.sh | sh`.

## Advanced configuration

### Custom instruction files (AGENTS.md)

Codex supports `AGENTS.md` to supply project context and conventions, similar to Claude Code's `CLAUDE.md`.

Place project-level instructions in `AGENTS.md` at the project root:

```markdown
# AGENTS.md

## Project Overview
This is a FastAPI backend project using PostgreSQL.

## Code Standards
- All functions must include type annotations
- New API endpoints require matching tests
- Run `make lint` to check code style before committing

## Test Commands
- Unit tests: `pytest tests/unit/`
- Integration tests: `pytest tests/integration/`
- Lint check: `make lint`
```

Place global instructions in `~/.codex/AGENTS.md` so every project inherits them:

```markdown
# Global Instructions

- Always communicate in English
- Write code comments in English
- Prefer functional programming style
- Generated code must include error handling
```

An `AGENTS.override.md` inside a subdirectory overrides parent rules. Codex searches in the order `AGENTS.override.md` > `AGENTS.md` > configured fallback file. The combined size limit defaults to 32 KB and can be adjusted with `project_doc_max_bytes`.

### Adjusting approvals and the sandbox

Codex's security controls have two layers: the **sandbox mode** defines what Codex can technically do (where it can write and whether it can reach the network), and the **approval policy** defines when it must ask you first. Two CLI flags control them:

| Flag | Allowed values |
|---|---|
| `--sandbox` / `-s` | `read-only`, `workspace-write`, `danger-full-access` |
| `--ask-for-approval` / `-a` | `on-request`, `never` |

Common combinations:

| Goal | Flags | Effect |
|---|---|---|
| Default (recommended in Git repos) | No flags, or `--sandbox workspace-write --ask-for-approval on-request` | Reads files, edits files, and runs commands inside the workspace; asks before writing outside the workspace or using the network |
| Read-only browsing | `--sandbox read-only --ask-for-approval on-request` | Reads files and runs commands inside the read-only sandbox |
| Read-only, non-interactive (CI) | `--sandbox read-only --ask-for-approval never` | Never prompts |
| Automatic approval review | `--approve-for-me` (alias `--not-so-yolo`) | Uses on-request approvals with the workspace-write sandbox, handled by automatic approval review |
| Full access (not recommended) | `--dangerously-bypass-approvals-and-sandbox` (alias `--yolo`) | No sandbox and no approvals; use only inside an externally hardened, isolated environment |

> 🔴 `--yolo` is an alias for `--dangerously-bypass-approvals-and-sandbox`, not a third approval policy. Flags from older tutorials — `--full-auto`, `--suggest`, `--auto-edit`, and `--approval-mode` — are no longer in the current official flag list. For autonomous file edits, use `--sandbox workspace-write`; for non-interactive runs, use `codex exec --sandbox workspace-write`.

> ⚠️ Codex CLI flags evolve rapidly. **Trust the actual output of `codex --help`** rather than a flag list copied from any document, including this page.

Set defaults in `config.toml`:

```toml
# Recommended for personal development
approval_policy = "on-request"
sandbox_mode = "workspace-write"
```

`approval_policy` accepts `on-request`, `never`, or a `granular` table split by category. The legacy `approval_policy = "untrusted"` is no longer supported; if an older config still contains that line it can prevent Codex from starting, so remove it. During a session, use `/permissions` to toggle between the default preset and read-only.

#### 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 file writes) | `codex exec --sandbox workspace-write` | `workspace-write` |
| One-off scripts (isolated environment) | `--dangerously-bypass-approvals-and-sandbox` (alias `--yolo`) | No sandbox |

### Configure MCP servers

Codex supports the Model Context Protocol (MCP) to connect external tools and extend its capabilities.

Add an MCP server from the command line:

```bash
codex mcp add my-server -- npx -y @some/mcp-server --config /path/to/config.json
```

Or configure it in `config.toml`:

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

Restart Codex after editing and run `/mcp` to inspect connected servers. MCP tools appear automatically alongside Codex's built-in tools. Codex can also run in reverse as an MCP server invoked by other AI agents.

### Configure profiles (multi-environment management)

If different projects need different settings (such as work versus personal), use profiles. **Since Codex 0.134.0, legacy `[profiles.<name>]` tables inside `config.toml` are no longer valid** — each profile now lives in its own file: `~/.codex/<name>.config.toml`.

```toml
# ~/.codex/config.toml - default config (top-level keys only; no [profiles.x] tables)
model_provider = "qcode"
model = "gpt-6.2-sol"

[model_providers.qcode]
name = "qcode"
base_url = "https://api.qcode.cc/openai"
wire_api = "responses"
requires_openai_auth = true
```

```toml
# ~/.codex/work.config.toml
model = "gpt-6.2-sol"
model_reasoning_effort = "high"
```

```toml
# ~/.codex/personal.config.toml
model = "gpt-6.2-sol"
model_reasoning_effort = "medium"
```

Select a profile at startup:

```bash
codex --profile work "Refactor the authentication module"
codex --profile personal "Write a small helper script"
```

Three common pitfalls to watch for:

- Keeping a legacy table while passing `--profile` triggers a hard error instead of being silently ignored:

```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 never resolved**: `codex doctor` still reports `config.toml parse ok` and uses the top-level values. "No error" does not mean "it took effect", so remove legacy tables when migrating.

`--profile` applies only to runtime subcommands (`codex`, `exec`, `review`, `resume`, `queue`, `archive`, `delete`, `unarchive`, `fork`, `mcp`, `sandbox`, `debug prompt-input`); passing it to `doctor` fails with `--profile only applies to runtime commands`. Profile files layer above user configuration and below project configuration and CLI flags.

### Non-interactive mode (scripts and automation)

Codex can run non-interactively in scripts and CI/CD pipelines using `codex exec`, which executes a task and exits while streaming output to stdout or JSONL:

```bash
# Basic usage: run a task and exit
codex exec "Add installation instructions to README.md"

# Allow workspace writes: fully autonomous execution
codex exec --sandbox workspace-write "Run the test suite and fix all failing tests"

# Emit a JSONL event stream (for auditing or post-processing)
codex exec --json "Refactor the error handling module"
```

Using Codex in CI/CD (GitHub Actions example):

```yaml
- name: Auto-fix lint errors
  run: |
    # Environment-variable style: use env_key in config.toml, omit requires_openai_auth
    mkdir -p ~/.codex
    cat > ~/.codex/config.toml <<'EOF'
    model_provider = "qcode"
    model = "gpt-6.2-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 programmatically from your own code, use the official SDK to embed Codex into your developer tools or workflows.

### Configuration priority

When multiple configuration sources conflict, Codex resolves them in this order (highest to lowest):

1. **Command-line arguments** (`--model`, `-c`, etc.)
2. **Project configuration** (`.codex/config.toml`, from project root to current directory, closest wins; loaded only after the folder is trusted, and project-level keys such as `model_provider`, `model_providers`, `profile`, and `profiles` are ignored)
3. **Profile file** (`~/.codex/<name>.config.toml`, selected via `--profile <name>`)
4. **User configuration** (`~/.codex/config.toml`)
5. **System configuration** (`/etc/codex/config.toml`, Unix systems)
6. **Built-in defaults**

Set general defaults in `~/.codex/config.toml`, override project-specific settings in `.codex/config.toml`, and use CLI arguments for one-off adjustments.

## Choosing between Claude Code and Codex

In one line: **Claude Code is interactive pair programming; Codex is autonomous task execution.** Claude Code shines at exploratory debugging, complex refactoring, and understanding an architecture; Codex shines at well-specified feature work, batch migrations, and CI/CD automation. Their instruction files are `CLAUDE.md` and `AGENTS.md` respectively, both have full MCP support, and both can share the same QCode API key.

For a full side-by-side comparison, see [Codex vs Claude Code](/docs/getting-started/codex-vs-claude-code).

## Practical examples

### Example 1: Understand a new project

```bash
cd /path/to/new/project
codex
```

In the interactive interface, enter:

```text
What does this project do? Analyze the directory structure, main modules, and tech stack,
and provide a concise architecture diagram (using ASCII art).
```

Codex scans the project files, inspects dependency manifests such as `package.json`, `requirements.txt`, and `go.mod`, reads key entry points, and gives you a project overview.

### Example 2: Code review

```bash
codex "Review all changes from the most recent git commit in src/. Focus on:
1. Potential bugs (null references, boundary conditions)
2. Security risks (SQL injection, XSS, hardcoded secrets)
3. Performance issues (N+1 queries, unnecessary loops)
Provide exact code locations and concrete fix suggestions."
```

### Example 3: Batch refactoring

```bash
codex --sandbox workspace-write "Replace all print() calls across Python files with the logging module.
Requirements:
1. Import logging at the top of each file
2. Create logger = logging.getLogger(__name__)
3. Replace print() with logger.info()
4. Preserve the original formatted strings
5. Run pytest afterwards to confirm nothing broke"
```

Codex processes files one by one, keeps style consistent, and runs the tests at the end to verify.

### Example 4: Write a complete test suite

```bash
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 the test file to tests/unit/test_user_service.py
6. Run the tests and confirm they all pass"
```

### Example 5: Fix failing tests autonomously

```bash
codex --sandbox workspace-write "Run all tests. If any fail:
1. Analyze the root cause of each failure
2. Fix the implementation code (not the tests)
3. Re-run the tests
4. Repeat until all tests pass
Finish with a summary of the fixes."
```

### Example 6: Implement UI from a design mockup

```bash
codex -i design.png "Implement this page in React + Tailwind CSS based on this design mockup.
Requirements:
1. Responsive layout (mobile support)
2. Faithful recreation of the design mockup
3. Clean component breakdown
4. Basic interactive states (hover, focus)"
```

### Example 7: Database migration

```bash
codex "Add an avatar_url column (varchar 500, nullable) to the users table.
Please:
1. Create an Alembic migration script
2. Update the SQLAlchemy model
3. Update the related Pydantic schemas
4. Update the CRUD functions
5. Add matching API endpoints (GET/PUT)
6. Run the migration and verify it succeeds"
```

### Example 8: Auto-generate a changelog in CI/CD

```bash
codex --sandbox workspace-write "Analyze all git commits since the last release tag,
group them according to Conventional Commits,
and generate the update section for CHANGELOG.md.
Include: new features, bug fixes, breaking changes, and other improvements."
```

## Related documentation

- [Claude Code complete tutorial](/docs/getting-started/claude-code-tutorial)
- [Codex vs Claude Code](/docs/getting-started/codex-vs-claude-code)
- [Endpoints and API formats](/docs/getting-started/endpoints-and-api-paths)
- [Environment variables and configuration](/docs/getting-started/environment)
- [Troubleshooting guide](/docs/reference/troubleshooting)
- [Aider integration](/docs/ide/aider)