About this page
Tutorial- What this page solves
- Your research data is on a local machine or a server, and you want Codex to help you understand an analysis script, run one analysis step and record the results. But after installation it fails to start, or you don't know the project's conventions, and you are not sure how to protect the raw data before you begin.
- Who it is for
- Graduate students and researchers using Codex for the first time. You have used ChatGPT or a command line, but you have not written config.toml or AGENTS.md before.
- What you will have
- After reading, you will have: a working Codex CLI, a ~/.codex/config.toml, an AGENTS.md at the project root, and a RUN.md and results directory left by one run.
- Covers
- Installing Codex CLI and signing in with a ChatGPT account or an API key
- Writing a config.toml that starts correctly, and an AGENTS.md for a research project
- Completing a first task in the project, protecting the raw data and keeping a run record
- Does not cover
- How to use specific research tools such as molecular dynamics or AlphaFold; see the corresponding tutorials
- Operational details of the IDE extension, desktop app and Codex Cloud; only briefly covered in the choice section
- A comparison of costs and risks for network solutions in mainland China; see “How to Use Codex and Claude Code in China”
Main steps
Step 1
Why this stepThe CLI is the program that runs Codex in a terminal. Sign-in, configuration and tasks all run on top of it, so install it first. This page follows the CLI as the main path; for choosing among the IDE extension, desktop app and cloud version, see the choice sections later on.
On macOS and Linux, the official install script is the simplest option, and the same command both installs and upgrades. npm and Homebrew also work and suit people who already manage software with those tools.
If you see Missing optional dependency during installation, or npm installs very slowly, see Troubleshooting: Missing optional dependency and Troubleshooting: npm install takes over ten minutes.
# macOS / Linux: official install script (same command for install and upgrade)
curl -fsSL https://chatgpt.com/codex/install.sh | sh
# Windows: run in a new PowerShell window
powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex"
# npm (Node 16+; in mainland China you can add --registry=https://registry.npmmirror.com)
npm install -g @openai/codex
# Homebrew
brew install --cask codex # upgrade: brew upgrade --cask codex
# Verify
codex --version # version checked on this page: codex-cli 0.162.1
codex doctor --summary # checks installation, configuration, sign-in, network and sandbox one by oneStep 2
Why this stepCodex must call a model, so it needs to know your account or API key. Once you sign in, the credentials are stored on this machine, and from then on you only need to run codex.
Run codex login in the terminal, and a ChatGPT sign-in page opens in your browser. The sign-in information is cached in ~/.codex/auth.json or the system keychain, depending on the cli_auth_credentials_store setting (options: file, keyring, auto, ephemeral). The CLI and the IDE extension share this cache, so if you sign out in one, you must sign in again in both.
To sign in with an API key, or on a server without a browser, see "ChatGPT Account or API Key" and "Using Codex on Restricted Servers". If you still get a 401 error after signing in, see Troubleshooting: 401 Unauthorized.
codex login # sign in with a ChatGPT account in the browser
codex login status # exits with 0 if signed in; prints Not logged in and exits with 1 if not
codex logoutStep 3
Why this stepconfig.toml is Codex's default settings file. It determines which model is used, when Codex asks you to confirm, and which directories it can write files to. Any item you leave out uses the built-in default. For the first setup, you only need to set the four items below; for the rest, see "config.toml Settings and Precedence Order".
The file uses TOML format: key = value, with strings in double quotes. Create a new ~/.codex/config.toml, copy in the content below, then edit it according to the comments.
If you see unknown configuration field or an ignoring notice at startup, see Troubleshooting: Codex is ignoring N unrecognized configuration settings.
# ~/.codex/config.toml
# Root-level keys must come before the first [table]; otherwise they are read as fields of that table and ignored
model = "gpt-6.1-sol" # use gpt-6-luna if your account does not have access
model_reasoning_effort = "medium" # low / medium / high / xhigh, depending on the model
approval_policy = "on-request" # only two values: on-request, never
sandbox_mode = "project-write" # read-only / project-write / danger-full-access
[sandbox_workspace_write]
network_access = false # set to true for pip/conda installs that need network accessStep 4
Why this stepCodex does not know your project's conventions, so it has to learn them from scratch each time it starts. AGENTS.md is an ordinary Markdown file. Codex reads it at the start of each session and includes it in the first turn's context. Use it for rules that stay valid for the whole project: directory conventions, run commands, files that must not be touched, and what counts as done.
Place the file at the root of the research repository, meaning the directory that contains .git. Run codex in the project root directory and type /init to generate a draft, then trim it down to only the necessary rules. The more specific the rules, the more useful they are: “data/raw is read-only” is more effective at getting Codex to comply than “be careful about data safety.”
To check which files Codex actually loaded, ask “list the instruction files you loaded” in an interactive session, or start Codex with codex -c log_dir=./.codex-log and then check codex-tui.log. If a rule has no effect, especially a rule in a subdirectory, see Troubleshooting: AGENTS.md in a subdirectory has no effect.
# AGENTS.md(放在课题仓库根目录)
## 目录约定
- data/raw/:原始数据,只读。不修改、不移动、不覆盖、不重新编码。
- data/processed/:由 scripts/ 中的脚本从 data/raw 生成,可以整体删除重建。
- scripts/:按编号命名(01_qc.py、02_model.R),每个脚本只读上一步的输出。
- results/<日期>_<简述>/:每次运行一个目录,图表、表格、日志都放在里面。
## 运行要求
- 环境:conda 环境 rnaseq-2026(environment.yml)。缺包时先说明,不自行升级已有包。
- 随机过程固定种子 20261010,并写入运行日志。
- 每次运行在结果目录写 RUN.md:执行的命令、输入文件及其 md5、软件与包版本、参数、耗时、输出文件列表。
- 统计检验写明检验方法、多重校正方法和阈值,阈值不在运行中途修改。
## 修改范围
- 只改 scripts/ 和 results/。改动共享函数前先说明影响哪些脚本。
- 结果和预期不符时报告差异,不通过改阈值或删样本让结果"变好"。
## 完成标准
- 脚本可以从干净的 data/processed 重新跑出同样的结果。
- 回复中列出改动的文件和需要我人工核对的地方。Step 5
Why this stepThe configuration above serves this step: letting Codex read, edit and run things in the project while making sure the raw data is not changed and every run can be traced. Research data is usually impossible to regenerate, so protect the data first, then start the task.
- 01
Protect the raw data before you start
First commit the current state of the repository to git, then run chmod -R a-w data/raw to make the raw data read-only. chmod is an operating-system-level restriction and does not depend on Codex's rules. For why you commit to git first, see "Why Commit to Git First Instead of Relying on /undo".
- 02
Start from the project root
cd into the repository root and then run codex; only then will it read the AGENTS.md in the root. For the first run, give a read-only task such as “explain what each script in scripts/ does,” to confirm that it has read the project rules.
- 03
Give the task and require a record
State the inputs, the output location and the record you need in the task, for example: “Run scripts/01_qc.py according to AGENTS.md, write the results to results/<date>_qc/, and generate RUN.md.” RUN.md records the command, the md5 of each input file, software versions, the random seed, parameters and the list of outputs. Review it first, then the results.
- 04
Confirm the environment is installed
project-write does not allow network access by default, so pip and conda installs will fail. Set up the environment yourself before starting the task. If something must be installed during the task, turn on network_access only for that turn and turn it off again after the installation.
Choose by your situation
Choice
These four forms run the same Codex agent. They differ in where they run, which files they can access and their sign-in requirements. The CLI and the IDE extension read the same ~/.codex/config.toml and the same sign-in cache, so signing in once in either one makes the other immediately usable. If you are unsure, use the CLI as described on the main path of this page.
If the data is only on your local machine or your lab's server, choose the CLI or the IDE extension. Codex Cloud tasks can only access repositories and services in the cloud environment: local files, a browser where you are signed in, and your VPN are not carried over, and large raw datasets are not suitable for a GitHub repository.
When working on a lab server, first get the CLI running on the server, then configure the IDE extension with Remote-SSH. The CLI lets you verify the proxy, certificates and sign-in on their own, which makes problems easier to locate if the extension fails.
The free plan and the Go plan can only use GPT-6 Luna in the desktop app (rolling out gradually). Plus (USD 20 per month) and above can be used on the web, in the CLI, in the IDE extension and on iOS, and include GPT-6.1 Sol.
| Form | Install entry | Where it runs | Sign-in | Best for |
|---|---|---|---|---|
| Codex CLI | install.sh / PowerShell script, npm, Homebrew | Local terminal; can also be installed on a server you log into over SSH | ChatGPT account or API key | Lab servers, batch runs with scripts, and precise control over permissions |
| IDE extension | Search for openai.chatgpt in the VS Code / Cursor / Windsurf extension marketplace; in JetBrains, choose Codex in AI Chat under AI Assistant | Local machine, or a server connected via Remote-SSH | ChatGPT account or API key | Editing code while reading it, and reviewing changes |
| ChatGPT desktop app | chatgpt.com/download (macOS, Windows); Linux has separate installation instructions | Local machine; can choose Local, Worktree or Cloud | ChatGPT account or API key | Working on several projects in parallel, and viewing charts and file previews |
| Codex Cloud | Choose Work in > Cloud in the ChatGPT web app, the desktop app or the mobile app | OpenAI-hosted cloud container; you need to create an environment and connect a GitHub repository first | ChatGPT account only | Tasks where the code is on GitHub and work must continue after your computer is off |
Choice
Both methods are available in the local CLI, the IDE extension and the desktop app. The right choice depends on whether you want to use plan quota or pay per token, and whether you need Codex Cloud.
printenv OPENAI_API_KEY | codex login --with-api-key # reads the key from the OPENAI_API_KEY environment variable| Item | ChatGPT account sign-in | API key sign-in |
|---|---|---|
| Billing | Uses the quota included in your ChatGPT plan; additional quota can be purchased on Plus or Pro once it is used up | Charged to your OpenAI Platform account at standard API prices |
| Available models | Depends on your plan; Plus and above include GPT-6.1 Sol and GPT-6 Luna | Depends on which models this key can access in the API |
| Codex Cloud, GitHub code review, Slack | Available | Not available |
| Best for | Everyday interactive use | CI, scheduled scripts, and supplementing plan quota after it runs out |
| How to use it in automation | Maintain auth.json on a trusted machine | Set CODEX_API_KEY only for that one Codex command; do not set it as an environment variable for the whole task |
Choice
Operationally, Codex requires a stable international network connection, plus a ChatGPT account or an OpenAI API key. Below are common proxy and certificate settings.
For proxies, HTTP proxy variables are recommended. Connections through a SOCKS5 proxy drop more often; see Troubleshooting: stream disconnected before completion (chatgpt.com address). On macOS, the ChatGPT desktop app launched from the Dock does not read export statements in the terminal; set its variables separately with launchctl setenv. See Troubleshooting: desktop app launched from the Dock cannot connect.
For a comparison of the three routes (official subscription, API relay services and domestic models), see /compare/codex-claude-code-china.
# Linux / macOS terminal: use HTTP proxy variables; local addresses bypass the proxy
export HTTPS_PROXY=http://127.0.0.1:7890
export HTTP_PROXY=http://127.0.0.1:7890
export NO_PROXY=localhost,127.0.0.1,::1
# Corporate proxy or self-signed root certificate
export CODEX_CA_CERTIFICATE=/path/to/root-ca.pem # falls back to SSL_CERT_FILE if not set
# Change only the address of the built-in OpenAI service (no new provider); write this in ~/.codex/config.toml
openai_base_url = "https://gateway.example.com/v1"Choice
When there is no browser on the server, you can switch to device-code sign-in. When the server has no outside network access, borrow your local machine's proxy.
Device-code sign-in must first be enabled in ChatGPT's security settings (for project accounts, an administrator enables it in project permissions). If sign-in fails, check codex-login.log in the log directory.
How a CSDN author handled a research lab server with no outside network access and no root: in ~/.ssh/config on the local machine, add RemoteForward 17891 127.0.0.1:7890 for the server, which maps the local proxy to the server; on the server, export HTTP(S)_PROXY pointing to 127.0.0.1:17891; when the root certificate is missing, set SSL_CERT_FILE to certifi's cacert.pem; the VS Code extension loads the same set of variables through ~/.vscode-server/server-env-setup, and after changing it, run Remote-SSH: Kill VS Code Server on Host and reconnect. The author recommends getting the CLI working first, then configuring the extension.
If the final step of sign-in fails, see Troubleshooting: Token exchange failed. If a root certificate is missing, see Troubleshooting: no native root CA certificates found.
codex login --device-auth # device-code sign-in: servers and environments without a browser
# No browser on the server and device code unavailable: forward the callback port to this machine, then sign in
ssh -L 1455:localhost:1455 user@server
codex login # open the address printed in the terminal in a browser on this machine
# Or copy this machine's sign-in cache to the server (auth.json is equivalent to a password)
ssh user@server 'mkdir -p ~/.codex && cat > ~/.codex/auth.json' < ~/.codex/auth.jsonChoice
The sandbox determines what a command can technically do, such as which directories it can write to and whether it can access the network. The approval policy determines when Codex stops to ask you. The two are set independently; the table below lists common combinations. For everyday use, the second row is recommended.
When you need finer control than sandbox_mode provides, you can use a permissions profile (beta); see "Use a Permissions Profile to Make data/raw Read-only". For why some directories remain read-only even inside the sandbox, see "The Sandbox Implementation and Read-only Directories".
| Combination | What it can do | Practical consequence |
|---|---|---|
| read-only + on-request | Reads files and runs read-only commands; writing and network access require your approval | Suitable for opening someone else's code for the first time or only explaining it; every change requires an approval click |
| project-write + on-request (the default Auto) | Reads, writes and runs commands within the working directory, /tmp and $TMPDIR; writing outside these locations and network access require approval | Recommended for everyday use. Files in the working directory, including raw data, may be modified or deleted |
| project-write + never | Same as above, but operations outside the boundary fail directly | A common setting for codex exec. After an out-of-bounds failure, the model may try a different approach to get around it |
| project-write + approvals_reviewer = "auto_review" | Requests outside the boundary are first judged by a review agent | Fewer interruptions; the review uses additional quota, and after a review rejection you can use /approve to allow it once |
| danger-full-access or --yolo (--dangerously-bypass-approvals-and-sandbox) | No sandbox and no approvals; can read and write the entire machine and access the network | Official guidance only recommends using it in an isolated container or virtual machine. Untracked files that are deleted by mistake cannot be recovered through Codex |
Choice
By default, Codex only connects to OpenAI. Add the three types of settings below only when you need them.
Add MCP servers when you connect external tools such as paper libraries, databases or browsers. Each MCP server takes up context and quota, so set enabled = false when it is not in use. You can also add them with commands: codex mcp add <name> -- <command>, or codex mcp add <name> --url <address>; both write to config.toml. codex mcp list shows the configured servers and their enabled status.
When connecting a custom gateway, the gateway must support the Responses protocol, and you must write wire_api = "responses". A service that only provides a Chat Completions interface cannot be connected to the current version; switch to a gateway that supports Responses. Codex is tuned for OpenAI models, so results may drop after you switch models.
A project-level .codex/config.toml takes effect only after you trust that project, and it cannot set keys such as model_provider, model_providers, openai_base_url or profile.
# MCP: local stdio server
[mcp_servers.papers]
command = "npx"
args = ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/papers"]
startup_timeout_sec = 20 # default 10
tool_timeout_sec = 60 # default 60
# MCP: remote HTTP server, temporarily disabled
[mcp_servers.context7]
url = "https://mcp.context7.com/mcp"
bearer_token_env_var = "CONTEXT7_API_KEY"
enabled = false
# Custom model gateway (Responses protocol only)
[model_providers.mygateway]
name = "My OpenAI-compatible gateway"
base_url = "https://gateway.example.com/v1"
env_key = "MYGATEWAY_API_KEY" # the name of the environment variable, not the key itself
wire_api = "responses"
request_max_retries = 4
stream_idle_timeout_ms = 300000
# Trust a project so that its .codex/config.toml takes effect
[projects."/Users/me/research/rnaseq-2026"]
trust_level = "trusted"Choice
On one machine, there are three common uses: everyday use, high reasoning effort, and use through a gateway. Write each one as a separate file and switch with -p.
Starting from 0.134.0, each profile is a separate file that contains top-level keys; the [profiles.<name>] table is no longer used. For the old syntax, see Troubleshooting: legacy profile configuration.
# ~/.codex/gateway.config.toml —— codex -p gateway
model_provider = "mygateway"
model = "gpt-6.1-sol"
# ~/.codex/deep.config.toml —— codex -p deep
model_reasoning_effort = "high"
# One-off override; values are parsed as TOML, so strings need quotes
codex -c model_reasoning_effort='"high"' -s read-only
codex exec -p deep "复核 scripts/02_model.py 的统计方法"Choice
chmod is an operating-system-level restriction and applies to all programs. If you want to restrict certain paths only inside Codex, use a permissions profile. It is an alternative to sandbox_mode; choose one or the other.
This is an alternative to sandbox_mode: if sandbox_mode appears in any configuration layer, or --sandbox is passed on the command line, the profile does not take effect. Use a permissions profile (beta) only when you need finer control than sandbox_mode provides, such as setting read, write and deny rules per path and allowlisting domains for network access.
# ~/.codex/config.toml: use a permissions profile to make data/raw read-only
# This section is an alternative to sandbox_mode / [sandbox_workspace_write]; if both exist, the profile has no effect
default_permissions = "research"
[permissions.research]
extends = ":project" # inherit default project permissions (.git/.codex read-only, network off)
[permissions.research.filesystem.":workspace_roots"]
"data/raw" = "read" # relative to each project root
"**/*.env" = "deny"
# Tested on this page (Codex CLI 0.162.1, macOS arm64, codex sandbox -P research):
# echo ok > results/out.txt -> succeeds
# echo x >> data/raw/counts.csv -> Operation not permitted
# rm data/raw/counts.csv -> Operation not permitted
# Control: with the built-in :project profile, appending to data/raw/counts.csv succeedsChoice
codex exec completes one task and then exits. Progress goes to stderr and only the final reply goes to stdout, so you can redirect it or pipe it directly. It differs from interactive mode in three default behaviors, so check them before you write a script.
Session records are saved under ~/.codex/sessions. By default, codex resume --last only looks for sessions in the current directory; add --all when you have changed directories. If a session was saved from a different directory than the current one, Codex asks which one to use; tui.resume_cwd can fix that choice. Sessions run with --ephemeral are not saved to disk and cannot be resumed later.
When you need output in a fixed format (for example, a QC verdict for each sample), use --output-schema schema.json to constrain the final reply to a specified JSON structure, then use -o to write it to a file.
# Run one analysis in the project directory; write the final reply to a file (progress goes to stderr)
cd ~/research/rnaseq-2026
codex exec --sandbox project-write \
-o results/2026-10-10_qc/codex_summary.md \
"按 AGENTS.md 运行 scripts/01_qc.py,结果写到 results/2026-10-10_qc/,并生成 RUN.md"
# Output JSONL when you need step-by-step events (commands, file changes, token usage)
codex exec --json --sandbox project-write "..." > run_events.jsonl
# Continue the previous non-interactive session (--last only searches the current directory)
codex exec resume --last "把 01_qc 的过滤阈值改成 min_counts=10 并重跑"
# Interactive sessions
codex resume # pick from a list
codex resume --last # most recent one in the current directory
codex resume --all # search across directories
codex fork --last # copy a session to try another approach| Default behavior | How to handle it |
|---|---|
| The sandbox is read-only when there is no config file | Add --sandbox project-write, or set sandbox_mode in config.toml |
| The approval policy is fixed at never | Write the permissions you need into the config in advance (writable directories, network) |
| Must run inside a git repository or a trusted directory | Run git init in the data analysis directory, or add --skip-git-repo-check |
Choice
Context is everything the model can see at one time. The longer the task, the more actively you need to manage it.
Use /status to see the remaining context. When the threshold is reached, Codex compacts the context automatically (the threshold can be adjusted with model_auto_compact_token_limit), or you can type /compact manually.
During a long task, ask Codex to write its progress, confirmed parameters and to-do items into NOTES.md. When compaction goes wrong or you start a new session, ask it to read this file first. For the case where history is lost after compaction, see Troubleshooting: forgetting earlier parameters and progress after compaction.
Hand off to an agent
Example instruction: “This is my RNA-seq project repository, with raw counts in data/raw. First read AGENTS.md and scripts/. Without modifying data/raw, run 01_qc through 03_deseq, write a RUN.md for each step, and finally list the results, the differences from the previous run, and the points that need my review.”
Steps the agent takes: read the repository and AGENTS.md in an isolated cloud computer; use the preinstalled environment with pandas, SciPy, statsmodels, scikit-learn and others, and install any missing R or Python packages inside the project; run the scripts in numerical order and record commands, versions and parameters; perform an adversarial review of the results. The task keeps running after your computer is shut down, and when idle it pauses and keeps its state.
Output files: the modified scripts, a results directory and RUN.md for each run, logs, and a record describing the changes and any anomalies.
What you still need to check yourself: whether the statistical methods and thresholds match your research design, whether the sample groups and batch information are correct, and the biological interpretation of the results.
Concepts and judgment
Explainer
An evaluation of AGENTS.md by ETH Zürich (arXiv 2602.11988, ICLR 2026) found that on code tasks such as SWE-bench, context files slightly reduce task success rates overall and raise inference costs by more than 20%. Agents follow what a file says carefully, so extra requirements make the task harder. The authors recommend writing these files by hand and including only the minimum necessary requirements. The official billing documentation also lists “shrinking AGENTS.md” as a way to save quota.
So write only rules that stay valid for this project over the long term and must be followed. A rule that only one subdirectory needs goes in that subdirectory's AGENTS.md, and you start Codex in that subdirectory.
Explainer
/undo has been removed from the CLI. The maintainers explained in GitHub #9203 that the original implementation had several problems, and restoring it would require a redesign. A community workaround is to have Codex reverse the current turn's changes with a patch, but deleted untracked files cannot be recovered that way.
So committing to git once before each round of work is currently the most reliable way to roll back. Tracked files that Codex breaks can be restored with git; raw data that is not in git still needs chmod protection.
Explainer
The sandbox for the CLI and the IDE extension is implemented by the operating system: macOS uses Seatbelt, Linux and WSL2 use bubblewrap / Landlock, and native Windows uses a dedicated sandbox user.
In project-write mode, several locations remain read-only: the .git, .codex and .agents directories inside the project, which is why git commit requires approval; and locations such as ~/.cache in your home directory. This page tested with codex sandbox: writing a file inside the project succeeded, while writing to ~/.cache and git commit both returned Operation not permitted, and curl to an outside address returned Could not resolve host.
Reference and appendix
Reference
Configuration takes effect in the following order, with earlier items overriding later ones: command-line arguments and -c overrides → project-level .codex/config.toml (from the project root down to the current directory; the closer, the higher the priority; applies only to trusted projects) → ~/.codex/<name>.config.toml selected by --profile → ~/.codex/config.toml → system /etc/codex/config.toml → built-in defaults.
# Top-level keys
web_search = "cached" # cached (default) / live / indexed / disabled
file_opener = "vscode" # file paths in output are clickable
project_doc_max_bytes = 65536 # combined AGENTS.md limit, 32768 by default
[sandbox_workspace_write]
writable_roots = ["/Users/me/scratch"] # extra writable directories; use your own path
[history]
persistence = "save-all" # "none" keeps no session transcripts on this machine| Setting | Allowed values and defaults | When to change it |
|---|---|---|
| model | Model IDs available to your account, for example gpt-6.1-sol or gpt-6-luna; if unset, 0.162.1 defaults to gpt-6.1-sol | Change to gpt-6-luna if your account lacks access or you want to save quota. GPT-5.5 will be retired from Codex signed in with ChatGPT on 2026-10-14; configurations that hard-code gpt-5.5 need to be replaced |
| model_reasoning_effort | low / medium / high / xhigh, etc.; available levels depend on the model | Use high for deriving statistical methods and complex debugging; use low for batch format changes. Higher levels take more time and usage |
| approval_policy | on-request, never, or { granular = {...} } | Use on-request for interactive use; codex exec uses never automatically |
| sandbox_mode | read-only / project-write / danger-full-access | Use read-only when only reading code; use project-write when running analyses or editing scripts |
| [sandbox_workspace_write] | network_access defaults to false; writable_roots adds extra writable directories | Turn on network_access when installing packages over the network; add writable_roots when results must be written to a directory outside the project |
| model_provider + [model_providers.<id>] | base_url, env_key (environment variable name), wire_api (responses only), http_headers, request_max_retries, stream_idle_timeout_ms, etc. | When connecting a company gateway, Azure, Bedrock or a local Ollama. To change only the address, use the top-level openai_base_url |
| --profile and <name>.config.toml | Starting from 0.134.0, each profile is a separate file that uses top-level keys | Switching between “everyday,” “high reasoning” and “through gateway” |
| [mcp_servers.<id>] | stdio: command, args, env; HTTP: url, bearer_token_env_var; common: startup_timeout_sec (default 10), tool_timeout_sec (default 60), enabled, required, enabled_tools / disabled_tools | Connect external tools such as paper libraries, databases or browsers. Each MCP server takes up context and quota, so set enabled = false when it is not in use |
| project_doc_max_bytes | Default 32768 bytes | Increase it when the total AGENTS.md size exceeds 32 KiB; a better approach is to split the rules into subdirectories |
| [projects."<path>"] trust_level | trusted / untrusted | Make the project's .codex/config.toml take effect, or require approval for every command in a given project |
- After changing the configuration, run codex exec --strict-config "hi": if the configuration contains a field the current version does not recognize, it reports unknown configuration field and points to the line number; if the configuration is valid, it starts normally (and reports 401 if you are not signed in).
- The config item in codex doctor --all lists ignored fields, for example Codex is ignoring 2 unrecognized configuration settings.
- In an interactive session, /status shows the current model, approval policy, writable directories and remaining context; /debug-config shows which file each configuration layer comes from.
- A project-level .codex/config.toml cannot set model_provider, model_providers, openai_base_url, profile and similar keys; if it does, Codex warns at startup and ignores them.
- codex mcp add <name> -- <command> or codex mcp add <name> --url <address> writes to config.toml; codex mcp list shows the configured servers and their enabled status.
Reference
This page uses codex debug prompt-input to check what is actually injected into the model (Codex CLI 0.162.1, no sign-in required). When Codex is launched from the project root, only the global file and the root AGENTS.md are loaded; AGENTS.md files in subdirectories such as analysis/ are not loaded. When launched in analysis/deseq/, all four files along that path are loaded. When analysis/ contains both AGENTS.override.md and AGENTS.md, only the override is used for that directory. After the root AGENTS.md was enlarged to 40 KB, the root file was truncated under the default limit, and the rules in analysis/ and deseq/ did not enter the context at all.
So rules specific to a subdirectory only take effect when Codex is launched in that subdirectory (codex -C analysis/deseq). Rules that must always apply belong in the root, and the root file should be kept concise.
- 01
Global layer
If ~/.codex/AGENTS.override.md exists, only it is read; otherwise ~/.codex/AGENTS.md is read. Suitable for personal habits that apply across projects, such as the reply language or preferred package manager.
- 02
Project layer
Starting from the project root (by default, the directory containing .git; can be changed with project_root_markers), walk down to the current directory where you launched Codex. In each directory, look for AGENTS.override.md, AGENTS.md and the files listed in project_doc_fallback_filenames, in that order; take at most one file per directory.
- 03
Merge
Concatenate in the order “global → root → current directory.” Files closer to the current directory come later, and in a conflict the later one wins. Empty files are skipped.
- 04
Limit
If the combined total exceeds project_doc_max_bytes (default 32 KiB), the content is truncated, and files deeper along the path are dropped entirely.
Reference
The table below is organized from codex --help and the official Developer commands documentation. It lists only the parts you are likely to use day to day.
Switch the model and reply style
/model switches the model and reasoning level, /fast switches the Fast tier, and /personality sets the reply style.
/permissions
Switch between Auto (project writable) and Read Only within a session; view the current sandbox and writable directories.
Check status and configuration sources
/status shows the current model, approval policy, writable directories and remaining context; /debug-config shows where each configuration layer comes from.
Manage context and sessions
/compact compresses history to free up context; /new starts a new session in the same terminal; /clear clears the screen and starts a new session.
Review changes
/diff shows the git diff, including untracked files; /review asks Codex to review the current changes.
Plan long tasks
/plan produces an execution plan before acting; /goal sets a goal for a long task that is tracked continuously.
Prepare project context
/init generates an AGENTS.md draft; /mention adds a specified file to the conversation; /mcp lists the available MCP tools.
Resume and organize sessions
/resume resumes a past session, /fork copies the current session, and /rename renames a session so it is easier to find later.
Manage background terminals
/ps shows the output of background terminals, where long-running analysis scripts can be checked; /stop stops all background terminals.
Shortcuts
@ searches for files and inserts the path; ! at the start of a line runs a shell command directly; while a task is running, Enter inserts a new instruction and Tab queues it for the next turn; with an empty input box, press Esc twice to edit the previous message and fork from there; Ctrl+R searches prompt history; Ctrl+O copies the most recent output.
| Command | Purpose | Common options |
|---|---|---|
| codex [prompt] | Start an interactive session in the current directory | -m model, -s sandbox, -a approval, -C working directory, --add-dir extra writable directory, -i attach image, --search live web search, -p profile |
| codex exec (alias e) | Non-interactive run, suitable for scripts | -o write the final reply, --json, --output-schema, --ephemeral, --skip-git-repo-check, --ignore-user-config |
| codex resume / codex fork | Resume or copy a past session | --last, --all, session ID or name |
| codex review | Review uncommitted changes, a commit or a branch | Also available as /review inside a session |
| codex apply (alias a) | Apply the diff of a Codex Cloud task locally with git apply | |
| codex mcp add / list / get / remove / login | Manage MCP servers | --url, --bearer-token-env-var, --env |
| codex login / logout | Sign in and sign out | --device-auth, --with-api-key, status |
| codex doctor | Check installation, configuration, sign-in, network and sandbox | --summary, --all, --json |
| codex sandbox | Run an arbitrary command inside Codex's sandbox to test permission settings | -P permissions profile, -C directory |
| codex features list / enable / disable | View and toggle feature flags | |
| codex completion | Generate bash / zsh / fish completion scripts |
Reference
The platform package is large: the darwin-arm64 package for 0.162.1 is 136.6 MB compressed and 323 MB unpacked.
Tested on this page: on 2026-10-11, on macOS arm64 with Node 24.19 and npm 11.17, running npm install @openai/codex@0.162.1 took 16 minutes 55 seconds and returned success, but the platform package was not downloaded, and Missing optional dependency appeared at runtime. It worked after the platform package was downloaded manually. npmmirror has synced all platform packages for 0.162.1 (metadata verified).
Troubleshooting
Start with the URL or path in the error message: it shows where the request was actually sent and which file was rejected. Then run codex doctor, which checks sign-in, WebSocket, proxy variables and the sandbox separately. Items below are sorted by how often they occur. Items labeled “legacy syntax” are patterns from older tutorials that fail if copied as is. Items labeled “community experience” come from practical reports in the Chinese developer community, cross-checked against official documentation or GitHub issues.
stream disconnected before completion: error sending request for url (http://127.0.0.1:port/v1/responses)
Cause: config.toml still contains a model_provider that points to a local proxy that is no longer running. Changing the model back to the official model is not enough, because requests still go through the old provider.
Fix: Delete the model_provider line and the corresponding [model_providers.x] table, then run codex logout and codex login. Community experience: a CSDN author (0.142.0, Windows) recovered after doing this; if token_exchange_failed appears afterward, change the proxy node.
stream disconnected before completion: error sending request for url (https://chatgpt.com/backend-api/codex/responses)
Cause: The network or proxy interrupted the long-lived connection; this is more common under SOCKS5 proxy variables.
Fix: Switch to HTTP proxy variables and set NO_PROXY. When codex doctor reports a websocket failure, Codex attempts an HTTPS fallback. In GitHub #20844, a Windows user switched from a SOCKS5 proxy to an HTTP proxy and the disconnections stopped.
Operation not permitted (when writing a file or running git commit)
Cause: The target is outside the sandbox's writable scope, or is in a protected path such as .git or .codex (see "The Sandbox Implementation and Read-only Directories"). Python packages that write their cache to ~/.cache also fail for this reason.
Fix: Use --add-dir to add a writable directory, or approve the out-of-bounds operation in the session. Cache directories can be set inside the project or to /tmp through conventions in AGENTS.md, for example MPLCONFIGDIR and HF_HOME.
Could not resolve host (pip, curl, git clone)
Cause: project-write has network access turned off by default.
Fix: Set sandbox_workspace_write.network_access = true, or approve network access for that run. After the packages are installed, change it back to false.
Running codex reports Missing optional dependency @openai/codex-darwin-arm64 (or linux-x64, etc.)
Cause: The npm package itself contains only a launcher script; the actual program is in platform-specific optional dependencies. When an optional dependency download fails, npm only logs a single reify failed optional dependency message and still returns success.
Fix: Reinstall. When the network is unstable, add --registry=https://registry.npmmirror.com, or use the official install script or Homebrew.
npm install -g @openai/codex --registry=https://registry.npmmirror.comCodex is ignoring N unrecognized configuration settings
Cause: A field is misspelled, deprecated or placed at the wrong level. Misspelled fields are silently ignored, for example model_reasoning_efort.
Fix: The config item in codex doctor --all lists the ignored fields; correct them using the field paths shown. codex exec --strict-config makes it report these as errors directly.
Not inside a trusted directory and --skip-git-repo-check was not specified.
Cause: codex exec must run inside a git repository or a trusted directory.
Fix: Run git init in the data analysis directory, or add --skip-git-repo-check.
After codex exec finishes, the analysis script did not write any result files
Cause: Without a config file, the sandbox for non-interactive exec is read-only.
Fix: Add --sandbox project-write, or set sandbox_mode in config.toml.
In codex exec, a command that requires approval fails immediately instead of waiting for you
Cause: The approval policy for exec is fixed at never. Operations that need approval fail directly, and the error is returned to the model.
Fix: Write the required permissions into the config in advance, such as writable directories and network access.
AGENTS.md in a subdirectory has no effect
Cause: Codex only reads AGENTS.md files along the path from the project root to the launch directory. When Codex is started in the root, files in subdirectories are not loaded. When the combined total exceeds 32 KiB, deeper files along the path are dropped entirely.
Fix: Launch Codex in that subdirectory (codex -C subdirectory), or write the rules into the root file. Check whether the combined size exceeds project_doc_max_bytes.
Earlier parameters and progress are forgotten after compaction
Cause: GitHub #36642 reports that since 0.145, automatic compaction occasionally loses all history; it still reproduces in 0.150, and the issue remains open.
Fix: Before compaction, ask Codex to write its progress, confirmed parameters and to-do items into NOTES.md. If problems occur, start a new session and ask it to read NOTES.md first. Use /status to check the remaining context.
npm install takes more than ten minutes
Cause: The platform package is large: the darwin-arm64 package for 0.162.1 is 136.6 MB compressed and 323 MB unpacked.
Fix: Use a mirror registry (--registry=https://registry.npmmirror.com), or use the official install script.
Token exchange failed: error sending request for url (https://auth.openai.com/oauth/token)
Cause: The final step of sign-in failed to reach auth.openai.com.
Fix: Check whether your proxy covers that domain. On a server, use codex login --device-auth instead.
The ChatGPT desktop app opened from the Dock cannot connect, but codex in the terminal works
Cause: A proxy exported in .zshrc only applies to codex launched from the terminal. GUI programs launched from the Dock do not read shell variables.
Fix: Set the proxy with launchctl setenv, then restart the app. Community experience: a CSDN author handled it this way. In GitHub #20844, a Windows user only got stable results after setting both the system proxy and the environment variables to an HTTP proxy.
launchctl setenv HTTPS_PROXY http://127.0.0.1:7890
launchctl setenv HTTP_PROXY http://127.0.0.1:7890In WSL, every request reports stream disconnected starting from 0.129.0
Cause: A WSL networking regression reported in GitHub #24511; 0.128.0 worked normally, and the issue remains open.
Fix: Community approach: a NodeSeek user enabled WSL mirrored networking mode (networkingMode=mirrored, dnsTunneling=true) and the problem was resolved. The reporter of GitHub #24511 rolled back to 0.128.0 under an Enterprise account and recovered. What these cases have in common is that you should first run codex doctor inside WSL by itself, to confirm that WSL and Windows use different proxy variables and configuration.
no native root CA certificates found
Cause: The server lacks system root certificates.
Fix: Set CODEX_CA_CERTIFICATE or SSL_CERT_FILE to point to a PEM file; you can use the certificate bundle that comes with Python certifi.
export CODEX_CA_CERTIFICATE=/path/to/root-ca.pemSkipped loading 1 skill(s) due to invalid SKILL.md files ... missing YAML frontmatter
Cause: The local skill file is missing the name and description enclosed by ---.
Fix: Add a YAML header at the top of the file.
Sandbox commands cannot run in WSL1
Cause: Starting from 0.115, the Linux sandbox uses bubblewrap, and WSL1 is only supported up to 0.114.
Fix: Run wsl --set-version <distribution> 2 to upgrade to WSL2.
On Windows 10, the terminal displays incorrectly or fails to start
Cause: Codex requires ConPTY. The official requirement is Windows 10 1809 or later, and Windows 11 is the recommended environment.
Fix: Update the system, or run Codex in WSL2.
codex update reports that it cannot update itself
Cause: codex update only works for installation methods that support self-updating.
Fix: Upgrade using the same method you used to install: reinstall with npm, run brew upgrade, or run the install script again.
Windows sandbox command reports error 1385
Cause: System policy rejects the logon type that the sandbox user requires.
Fix: Ask IT to grant the logon permission; as a temporary measure, set [windows] sandbox to unelevated.
Startup fails: approval_policy = "untrusted" is no longer supported; remove this setting
Cause: Legacy syntax. approval_policy = "untrusted" from older tutorials has been removed in the current version.
Fix: Delete that line and use on-request instead. If you need every command to require approval, set trust_level = "untrusted" under [projects."<path>"].
invalid value ... [possible values: on-request, never]
Cause: Legacy syntax. codex -a untrusted or codex -a on-failure from older tutorials is no longer accepted in the current version.
Fix: Change it to codex -a on-request.
legacy `profile = "fast"` config is no longer supported; use `--profile fast` with `fast.config.toml` instead
Cause: Legacy syntax. Older tutorials wrote profile = "fast" in config.toml and added a [profiles.fast] table.
Fix: Move the keys under [profiles.fast] into ~/.codex/fast.config.toml (written as top-level keys), then delete the original table and the profile line.
--profile `fast` cannot be used while ... config.toml contains legacy ... config
Cause: Legacy syntax. config.toml still contains the old [profiles.fast] table, which conflicts with --profile.
Fix: Same as above: move the keys in the table into fast.config.toml, and delete the old table from config.toml.
`wire_api = "chat"` is no longer supported. How to fix: set `wire_api = "responses"`
Cause: Legacy syntax. The Chat Completions protocol used by older tutorials is no longer supported in the current version.
Fix: Change it to wire_api = "responses". If the upstream only supports Chat Completions, switch to a gateway that supports Responses.
model_providers contains reserved built-in provider IDs: `openai`
Cause: Legacy syntax. Older tutorials changed base_url in [model_providers.openai], but openai is a built-in ID and cannot be overridden.
Fix: Delete that table and use the top-level openai_base_url instead, or choose a custom ID.
error: unexpected argument '--full-auto' found
Cause: Legacy syntax. The official documentation still says it “prints a deprecation warning,” but 0.162.1 reports an error directly.
Fix: Change it to codex exec --sandbox project-write.
string values must be quoted
Cause: It was written as model = gpt-6.1-sol, and the string is not quoted.
Fix: Add double quotes to the string: model = "gpt-6.1-sol".
too few unicode value digits (\U is treated as an escape)
Cause: Backslashes in double-quoted strings are treated as escapes, for example the \U in C:\Users.
Fix: Use a single-quoted literal such as 'C:\Users\me\data', or forward slashes such as C:/Users/me/data.
The model setting has no effect and no error is reported; under --strict-config it reports unknown configuration field `sandbox_workspace_write.model`
Cause: Root-level keys were written after tables such as [sandbox_workspace_write], so they are read as fields of that table.
Fix: Move all root-level keys before the first [table].
The field is ignored without an error; codex doctor shows `mcp_servers.x.type` is ignored
Cause: The field name is misspelled, for example model_reasoning_efort; or the type = "stdio" line was copied over when migrating MCP configuration from Claude Code. Codex determines the type from command or url and does not use type.
Fix: Delete type or correct the spelling. Community experience: the warning mcp_servers.node_repl.type is ignored recorded in a CSDN article is the same issue.
References
- Codex CLI documentation — Four installation methods and upgrade commands
- Codex IDE extension documentation — Entry points for VS Code, Cursor, Windsurf, JetBrains and Xcode
- Codex Cloud and Codex environments documentation — Differences between Local, Worktree and Cloud; cloud tasks do not carry local files
- Authentication documentation — Two sign-in methods, device code, port 1455 forwarding, CODEX_CA_CERTIFICATE, credential storage
- Pricing documentation — Forms and models available in each plan; API keys do not include cloud features
- Models documentation — Currently recommended models and the GPT-5.5 retirement date
- Config basics / Advanced Configuration / Configuration Reference — Configuration precedence, profile files, custom providers, MCP fields, keys that project configuration cannot set
- Custom instructions with AGENTS.md — AGENTS.md discovery order, override, 32 KiB limit
- Agent approvals & security — Sandbox and approval combinations, protected paths, migrating away from untrusted
- Permissions (beta) — Permissions profile syntax; cannot be mixed with sandbox_mode
- Non-interactive mode — codex exec default permissions, output, git check, CODEX_API_KEY
- Developer commands (CLI reference and slash commands) — Subcommands, slash commands, shortcuts
- ChatGPT desktop app for Windows / Windows sandbox — WSL1 no longer supported since 0.115, Windows version requirements, error 1385
- Gloaguen et al. Evaluating AGENTS.md (arXiv 2602.11988, ICLR 2026) — Effect of context files on success rate and cost
- GitHub openai/codex #9203: Please make /undo back — Maintainers explain why /undo was removed; community undo workarounds
- GitHub openai/codex #36642: Auto-compaction silently discards history — Report of automatic compaction losing history since 0.145, and self-check commands
- GitHub openai/codex #20844: SOCKS5 proxy instability — Community experience: recovered after switching from SOCKS5 to an HTTP proxy
- GitHub openai/codex #24511: 0.129.0+ fails in WSL — Report of the WSL disconnection regression
- CSDN: Troubleshooting and fix record for the “stream disconnected before completion” error in local Codex — Community experience, author-tested (0.142.0, Windows): leftover local proxy and token_exchange_failed
- CSDN: Setting up Codex CLI and the VS Code Codex extension on a remote server — Community experience, author-tested: SSH reverse proxy and certificates for a server without outside network access
- CSDN: Complete guide to configuring a proxy for the Codex app on Mac — Community experience: setting proxies for GUI programs with launchctl setenv
- CSDN: Troubleshooting Codex 401 errors and configuration that does not take effect — Community experience: the original unrecognized-field warning; the article's claim about environment variable precedence contradicts the official documentation, so it was not adopted