Codex / Tutorial

Codex Tutorial: Install the CLI, IDE Extension and App; config.toml, AGENTS.md and Common Commands

This guide follows the order choose a surface → install → sign in → configure → write rules → daily commands → permissions → research use → troubleshooting. Commands, subcommands and config fields were checked against Codex CLI 0.162.1, the latest release on npm, and the official documentation as of October 2026. Settings that no longer work in current versions are listed separately.

Short answer

Codex comes in four forms: the Codex CLI in your terminal, the extension for VS Code / Cursor / JetBrains, Codex inside the ChatGPT desktop app, and Codex Cloud running in the cloud. The first three run on your computer and share the configuration and login under ~/.codex; Codex Cloud requires a ChatGPT account. Install the CLI with npm install -g @openai/codex or the official installer, run codex in a project directory and sign in with a ChatGPT account or an API key. Defaults go in ~/.codex/config.toml and project rules go in AGENTS.md at the repository root. The current version removed the untrusted approval policy, [profiles] tables and the chat wire protocol, so configurations copied from old tutorials fail to start; after editing, check with codex exec --strict-config or codex doctor.

Step one

All four surfaces run the same Codex agent; they differ in where they run, which files they can reach and how you sign in. The CLI and the IDE extension read the same ~/.codex/config.toml and the same login cache, so signing in once covers both.

If your data lives only on your computer or a lab server, use the CLI or the IDE extension. Codex Cloud tasks can only reach repositories and services in the cloud environment; local files, browser sign-ins and VPN access are not transferred, and large raw datasets do not belong in a GitHub repository.

On a lab server, get the CLI working on the server first, then set up the IDE extension over Remote-SSH. The CLI verifies proxy, certificates and login on its own, which makes extension problems easier to locate.

The Free and Go plans can use GPT-6 Luna in the desktop app only (rolling out). From Plus ($20 per month) Codex is available on the web, in the CLI, in the IDE extension and on iOS, including GPT-6.1 Sol.

SurfaceHow to installWhere it runsSign-inBest for
Codex CLIinstall.sh / PowerShell script, npm, HomebrewLocal terminal; also on servers you reach over SSHChatGPT account or API keyLab servers, scripted batch runs, precise permission control
IDE extensionSearch openai.chatgpt in the VS Code / Cursor / Windsurf marketplace; in JetBrains, choose Codex in AI Assistant's AI ChatLocal machine or a Remote-SSH serverChatGPT account or API keyEditing alongside the code and reviewing diffs
ChatGPT desktop appchatgpt.com/download (macOS, Windows); separate Linux instructionsLocal; choose Local, Worktree or CloudChatGPT account or API keySeveral projects in parallel, previewing figures and files
Codex CloudIn ChatGPT web, desktop or mobile, choose Work in > CloudOpenAI-managed cloud containers; you first create an environment and connect GitHub repositoriesChatGPT account onlyCode hosted on GitHub, tasks that must continue after you shut down
Sources: official Codex CLI, IDE extension, ChatGPT desktop app, Codex Cloud and Authentication documentation.

Install

The official documentation lists four install methods; each uses the same command to update. After installing, run codex --version and codex doctor to confirm the binary, configuration, login and network.

Install and verifybash
# macOS / Linux: official installer (same command installs and updates)
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      # update: brew upgrade --cask codex

# Verify
codex --version                # version checked on this page: codex-cli 0.162.1
codex doctor --summary         # checks install, config, auth, network and sandbox
SymptomCauseFix
Running codex prints Missing optional dependency @openai/codex-darwin-arm64 (or linux-x64, etc.)The npm package is only a launcher; the program ships in per-platform optional dependencies. When that download fails, npm logs reify failed optional dependency and still reports successReinstall; on an unstable network add --registry=https://registry.npmmirror.com, or use the official installer / Homebrew
npm install takes over ten minutesPlatform packages are large: the 0.162.1 darwin-arm64 package is 136.6 MB compressed and 323 MB unpackedUse a mirror or the official installer
Sandboxed commands fail in WSL1Since 0.115 the Linux sandbox uses bubblewrap; WSL1 was supported through 0.114Upgrade with wsl --set-version <distro> 2
Garbled terminal or no start on Windows 10Codex needs ConPTY; Windows 10 1809 or newer is required and Windows 11 is recommendedUpdate Windows or run inside WSL2
codex update says it cannot self-updatecodex update only works for installs that support self-updateUpdate with the method you installed with (npm reinstall, brew upgrade, rerun the installer)
Tested on this page: on 2026-10-11, npm install @openai/codex@0.162.1 on macOS arm64 with Node 24.19 and npm 11.17 reported success after 16 min 55 s, but the platform package was missing and the first error above appeared at runtime; installing the platform package manually fixed it. npmmirror carries the 0.162.1 platform packages (metadata checked).

Sign in

Both methods work in the local CLI, IDE extension and desktop app. The choice depends on whether you want to use plan allowances or pay per token, and whether you need Codex Cloud.

Credentials are cached in ~/.codex/auth.json or the OS keychain, controlled by cli_auth_credentials_store (file / keyring / auto / ephemeral). The CLI and IDE extension share this cache; signing out in one signs out both.

Device code sign-in must first be enabled in your ChatGPT security settings (for workspace accounts, by the admin in workspace permissions). If sign-in fails, check codex-login.log in the log directory.

In mainland China, the practical requirements are a stable international connection and a ChatGPT account or an OpenAI API key. Use HTTP proxy variables: a Windows user reported that ChatGPT backend disconnects stopped after switching SOCKS5 proxy variables to HTTP proxy variables and setting NO_PROXY (GitHub #20844). A third-party gateway must support the Responses protocol; services that only offer Chat Completions cannot be connected to the current version. For a comparison of official plans, API relays and domestic models, see /compare/codex-claude-code-china.

Sign in, check status and sign in without a browserbash
codex login                    # browser sign-in with a ChatGPT account
codex login --device-auth      # device code: servers and machines without a browser
printenv OPENAI_API_KEY | codex login --with-api-key   # API key sign-in
codex login status             # exits 0 when signed in; prints Not logged in and exits 1 otherwise
codex logout

# Headless server without device code: forward the callback port, then sign in
ssh -L 1455:localhost:1455 user@server
codex login                    # open the printed URL in your local browser

# Or copy your local login cache (treat auth.json like a password)
ssh user@server 'mkdir -p ~/.codex && cat > ~/.codex/auth.json' < ~/.codex/auth.json
Proxy, certificates and endpoint (for networks in mainland China)bash
# Linux / macOS terminal: use HTTP proxy variables and keep local addresses direct
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

# On macOS the ChatGPT desktop app launched from the Dock ignores shell variables; set them in launchd and restart the app
launchctl setenv HTTPS_PROXY http://127.0.0.1:7890
launchctl setenv HTTP_PROXY http://127.0.0.1:7890

# Corporate proxy or private root CA
export CODEX_CA_CERTIFICATE=/path/to/root-ca.pem   # falls back to SSL_CERT_FILE when unset

# Change only the address of the built-in OpenAI provider (no new provider), in ~/.codex/config.toml
openai_base_url = "https://gateway.example.com/v1"
ItemChatGPT accountAPI key
BillingUses your ChatGPT plan allowance; Plus and Pro can buy extra creditsCharged to your OpenAI Platform account at standard API rates
ModelsDepends on the plan; from Plus, GPT-6.1 Sol and GPT-6 LunaWhatever models the key can access in the API
Codex Cloud, GitHub code review, SlackAvailableNot available
Best forDaily interactive useCI, scheduled scripts, extra usage after the plan allowance runs out
In automationMaintain auth.json on a trusted machineSet CODEX_API_KEY only for the Codex command, not as a job-wide variable
Sources: official Authentication, Pricing and Non-interactive mode documentation.

Configuration

Settings apply in this order, earlier entries overriding later ones: command-line flags and -c overrides → project .codex/config.toml files (from the project root down to the current directory, closest wins, trusted projects only) → ~/.codex/<name>.config.toml selected with --profile → ~/.codex/config.toml → system /etc/codex/config.toml → built-in defaults.

Complete example you can use as istoml
# ~/.codex/config.toml  (validated with --strict-config on Codex CLI 0.162.1)
# Root keys must come before the first [table]; after a table they become fields of that table and are ignored
model = "gpt-6.1-sol"              # switch to gpt-6-luna if your account lacks access
model_reasoning_effort = "medium"  # low / medium / high / xhigh, depending on the model
approval_policy = "on-request"     # only on-request and never are accepted
sandbox_mode = "workspace-write"   # read-only / workspace-write / danger-full-access
web_search = "cached"              # cached (default) / live / indexed / disabled
file_opener = "vscode"             # makes file paths in output clickable
project_doc_max_bytes = 65536      # combined AGENTS.md limit, default 32768

[sandbox_workspace_write]
network_access = false             # set to true when pip/conda need the network
writable_roots = []                # extra writable directories, e.g. ["/Users/me/scratch"]

[history]
persistence = "save-all"           # "none" keeps no local session history

# 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, disabled for now
[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 variable name, not the key itself
wire_api = "responses"
request_max_retries = 4
stream_idle_timeout_ms = 300000

# Trust a project so its .codex/config.toml is loaded
[projects."/Users/me/research/rnaseq-2026"]
trust_level = "trusted"
Profile files and one-off overridesbash
# ~/.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 overrides; values are parsed as TOML, so strings need quotes
codex -c model_reasoning_effort='"high"' -s read-only
codex exec -p deep "Review the statistics in scripts/02_model.py"
SettingValues and defaultsWhen to change it
modelA model ID your account can use, e.g. gpt-6.1-sol or gpt-6-luna; unset defaults to gpt-6.1-sol in 0.162.1Use gpt-6-luna if you lack access or want to save allowance. GPT-5.5 retires from Codex with ChatGPT sign-in on 2026-10-14, so configs that pin gpt-5.5 need a new model
model_reasoning_effortlow / medium / high / xhigh and so on, depending on the modelhigh for deriving statistical methods or hard debugging; low for bulk formatting. Higher levels take longer and use more allowance
approval_policyon-request, never, or { granular = {...} }on-request for interactive work; codex exec always uses never
sandbox_moderead-only / workspace-write / danger-full-accessread-only to inspect code; workspace-write to run analyses and edit scripts
[sandbox_workspace_write]network_access defaults to false; writable_roots adds writable directoriesEnable network_access to install packages; add writable_roots when results must go outside the project
model_provider + [model_providers.<id>]base_url, env_key (variable name), wire_api (responses only), http_headers, request_max_retries, stream_idle_timeout_ms, etc.For a company gateway, Azure, Bedrock or local Ollama. To change only the address, use top-level openai_base_url
--profile and <name>.config.tomlSince 0.134.0 each profile is a separate file with top-level keysSwitching between "daily", "high reasoning" and "via 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_toolsTo connect literature libraries, databases or browsers. Every MCP server consumes context and allowance; set enabled = false when unused
project_doc_max_bytesDefault 32768 bytesRaise it when AGENTS.md exceeds 32 KiB in total; splitting into subdirectories is better
[projects."<path>"] trust_leveltrusted / untrustedLoad a project's .codex/config.toml, or require approval for every command in a project
Sources: official Config basics, Advanced Configuration, Configuration Reference and Model Context Protocol documentation, checked against Codex CLI 0.162.1.
  • After editing, run codex exec --strict-config "hi": fields this version does not recognize produce unknown configuration field with the line number; a valid config starts running normally (and then returns 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 active model, approval policy, writable roots and remaining context; /debug-config shows which file each config layer comes from.
  • A project .codex/config.toml cannot set model_provider, model_providers, openai_base_url, profile and similar keys; they are ignored with a startup warning.
  • codex mcp add <name> -- <command> or codex mcp add <name> --url <url> writes to config.toml; codex mcp list shows configured servers and whether they are enabled.

Version changes

The Codex CLI changes quickly, and many settings from tutorials written in 2025 and early 2026 no longer work. Every error message below was triggered on this page with Codex CLI 0.162.1.

Old settingBehavior in 0.162.1Fix
approval_policy = "untrusted"Fails to start: approval_policy = "untrusted" is no longer supported; remove this settingDelete it and use on-request; to require approval for every command, set trust_level = "untrusted" under [projects."<path>"]
codex -a untrusted or -a on-failureinvalid value ... [possible values: on-request, never]Use -a on-request
profile = "fast" plus [profiles.fast]legacy `profile = "fast"` config is no longer supported; use `--profile fast` with `fast.config.toml` insteadMove the keys under [profiles.fast] into ~/.codex/fast.config.toml as top-level keys, then delete the table and the profile line
Only a [profiles.fast] table, then codex -p fast--profile `fast` cannot be used while ... config.toml contains legacy ... configSame as above
wire_api = "chat"`wire_api = "chat"` is no longer supported. How to fix: set `wire_api = "responses"`Use responses; if the upstream only supports Chat Completions, switch to a gateway that supports Responses
Changing base_url under [model_providers.openai]model_providers contains reserved built-in provider IDs: `openai`Remove the table and use top-level openai_base_url, or pick another custom ID
codex exec --full-autoerror: unexpected argument '--full-auto' found (the docs still say it prints a deprecation warning; 0.162.1 rejects it)Use codex exec --sandbox workspace-write
model = gpt-6.1-sol (unquoted)string values must be quotedPut strings in double quotes
args = ["C:\Users\me\data"]too few unicode value digits (\U is read as an escape)Use a single-quoted literal 'C:\Users\me\data' or forward slashes C:/Users/me/data
model placed after a table such as [sandbox_workspace_write]No error, the model setting has no effect; with --strict-config: unknown configuration field `sandbox_workspace_write.model`Move all root keys above the first [table]
Typos such as model_reasoning_efort; type = "stdio" copied from Claude Code MCP configsNo error, the field is ignored; doctor shows `mcp_servers.x.type` is ignoredDelete or correct it; Codex infers the type from command or url

AGENTS.md

AGENTS.md is a plain Markdown file that Codex reads at the start of every session and places in the first turn's context. Use it for rules that hold for the whole project: directory conventions, run commands, files that must not change and what counts as done.

This page used codex debug prompt-input to view what is actually injected into the model (Codex CLI 0.162.1, no login needed). Started at the project root, only the global file and the root AGENTS.md were loaded; AGENTS.md files in subdirectories such as analysis/ were not. Started in analysis/deseq/, all four files on the path were loaded; when analysis/ also contained AGENTS.override.md, only the override was used for that directory. After growing the root AGENTS.md to 40 KB, the root file was truncated under the default limit and the rules from analysis/ and deseq/ did not reach the context.

So rules specific to a subdirectory only apply when you start Codex in that subdirectory (codex -C analysis/deseq). Rules that must always apply belong in the root file, which should stay short.

/init writes a draft AGENTS.md in the current directory; trim it to the essential rules before committing. ETH Zürich's evaluation of AGENTS.md (arXiv 2602.11988, ICLR 2026) found that on SWE-bench and similar coding tasks, context files slightly reduced task success overall while raising inference cost by more than 20%; agents follow the instructions faithfully, so unnecessary requirements make tasks harder. The authors recommend human-written files with only minimal requirements. The official pricing documentation also lists "reduce the size of your AGENTS.md" as a way to make usage last longer.

To check which files were loaded, ask "list the instruction files you loaded" in a session, or start with codex -c log_dir=./.codex-log and read codex-tui.log.

AGENTS.md example for a research projectmarkdown
# AGENTS.md (at the root of the project repository)

## Directory conventions
- data/raw/: raw data, read-only. Do not modify, move, overwrite or re-encode.
- data/processed/: generated from data/raw by scripts in scripts/; can be deleted and rebuilt.
- scripts/: numbered (01_qc.py, 02_model.R); each script reads only the previous step's output.
- results/<date>_<label>/: one directory per run, holding figures, tables and logs.

## Run requirements
- Environment: conda env rnaseq-2026 (environment.yml). Report missing packages first; do not upgrade existing ones.
- Fix random seeds to 20261010 and record them in the run log.
- Each run writes RUN.md in its results directory: commands, input files with md5, software and package versions, parameters, runtime, list of outputs.
- For statistical tests, state the test, the multiple-testing correction and the thresholds; do not change thresholds mid-run.

## Scope of changes
- Only modify scripts/ and results/. Before changing shared functions, list the scripts affected.
- When results differ from expectations, report the difference; do not change thresholds or drop samples to make results look better.

## Definition of done
- Scripts reproduce the same results from a clean data/processed.
- The reply lists changed files and what I need to check by hand.
  1. 01

    Global layer

    If ~/.codex/AGENTS.override.md exists Codex reads only that file; otherwise it reads ~/.codex/AGENTS.md. Put cross-project personal habits here, such as reply language or preferred package manager.

  2. 02

    Project layer

    From the project root (by default the directory containing .git; change with project_root_markers) down to the directory where you start Codex, each directory is checked for AGENTS.override.md, AGENTS.md and names in project_doc_fallback_filenames, taking at most one file per directory.

  3. 03

    Merge

    Files are concatenated in the order global → root → current directory. Files closer to the current directory come later and take precedence on conflicts. Empty files are skipped.

  4. 04

    Limit

    Once the combined size exceeds project_doc_max_bytes (32 KiB by default), content is truncated and files deeper in the path are dropped entirely.

Commands

Compiled from codex --help and the official Developer commands documentation; only everyday commands are listed.

/model, /fast, /personality

Switch model and reasoning level, toggle the Fast tier, set the reply style.

/permissions

Switch between Auto (workspace writable) and Read Only mid-session, and view the active sandbox and writable roots.

/status, /debug-config

Show the active model, approval policy, writable roots and remaining context; show where each config layer comes from.

/compact, /new, /clear

Summarize history to free context; start a new chat in the same terminal; clear the screen and start fresh.

/diff, /review

Show the git diff including untracked files; ask Codex to review current changes.

/plan, /goal

Get an execution plan before any edits; set a persistent goal for a long task.

/init, /mention, /mcp

Generate a draft AGENTS.md; attach specific files; list available MCP tools.

/resume, /fork, /rename

Resume a saved chat, fork the current one, rename a session so you can find it later.

/ps, /stop

Show background terminals and their output; stop all background terminals. Long-running analysis scripts show up here.

Shortcuts

@ searches files and inserts the path; a line starting with ! runs a shell command; while Codex works, Enter injects new instructions and Tab queues them for the next turn; Esc twice on an empty composer edits the previous message and forks from there; Ctrl+R searches prompt history; Ctrl+O copies the latest output.

CommandPurposeCommon 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 image, --search live web search, -p profile
codex exec (alias e)Non-interactive run for scripts-o write final reply, --json, --output-schema, --ephemeral, --skip-git-repo-check, --ignore-user-config
codex resume / codex forkResume or copy a previous session--last, --all, session ID or name
codex reviewReview uncommitted changes, a commit or a branchAlso /review inside a session
codex apply (alias a)Apply a Codex Cloud task's diff locally with git apply
codex mcp add / list / get / remove / loginManage MCP servers--url, --bearer-token-env-var, --env
codex login / logoutSign in and out--device-auth, --with-api-key, status
codex doctorCheck install, config, auth, network and sandbox--summary, --all, --json
codex sandboxRun any command inside Codex's sandbox to test permission settings-P permission profile, -C directory
codex features list / enable / disableInspect and toggle feature flags
codex completionGenerate bash / zsh / fish completions

Non-interactive and sessions

codex exec runs one task and exits. Progress goes to stderr and only the final reply goes to stdout, so you can redirect or pipe it. Three defaults differ from interactive mode; confirm them before writing scripts.

Session records are stored under ~/.codex/sessions. codex resume --last only searches sessions from the current directory; add --all after changing directories. When the saved directory differs from the current one, Codex asks which to use; tui.resume_cwd fixes that choice. Sessions run with --ephemeral are not saved and cannot be resumed.

When you need a fixed result format (for example a QC verdict per sample), use --output-schema schema.json to constrain the final reply to a JSON structure and -o to write it to a file.

Scripted analysis runs and resumingbash
# Run one analysis in the project directory; final reply goes to a file (progress goes to stderr)
cd ~/research/rnaseq-2026
codex exec --sandbox workspace-write \
  -o results/2026-10-10_qc/codex_summary.md \
  "Following AGENTS.md, run scripts/01_qc.py, write outputs to results/2026-10-10_qc/ and create RUN.md"

# JSONL events (commands, file changes, token usage)
codex exec --json --sandbox workspace-write "..." > run_events.jsonl

# Continue the previous non-interactive session (--last searches the current directory only)
codex exec resume --last "Change the 01_qc filter to min_counts=10 and rerun"

# Interactive sessions
codex resume              # picker
codex resume --last       # most recent in this directory
codex resume --all        # search all directories
codex fork --last         # copy a session to try another approach
DefaultConsequenceWhat to do
Read-only sandbox when no config file sets oneThe analysis runs but cannot write result filesAdd --sandbox workspace-write, or set sandbox_mode in config.toml
Approval policy is always neverActions that need approval fail and the error goes back to the model instead of waiting for youPut the needed permissions (writable directories, network) in the config beforehand
Must run in a git repository or trusted directoryNot inside a trusted directory and --skip-git-repo-check was not specified.Run git init in the analysis directory, or add --skip-git-repo-check
Tested on this page: with Codex CLI 0.162.1, signed out and --ignore-user-config, the exec header showed approval: never, sandbox: read-only.

Approvals and sandbox

The sandbox decides what commands can technically do (which directories they can write, whether they can reach the network); the approval policy decides when Codex stops to ask. They are set independently. In the CLI and IDE extension the operating system enforces the sandbox: Seatbelt on macOS, bubblewrap / Landlock on Linux and WSL2, dedicated sandbox users on native Windows.

Some paths stay read-only under workspace-write: .git, .codex and .agents inside the workspace (so git commit needs approval) and home locations such as ~/.cache. Tested on this page with codex sandbox: writing inside the workspace succeeded, while writing to ~/.cache and git commit both returned Operation not permitted, and curl to an external host returned Could not resolve host. Python packages that write caches to ~/.cache fail for this reason; specify in AGENTS.md that cache directories such as MPLCONFIGDIR and HF_HOME point inside the project or to /tmp.

/undo has been removed from the CLI. A maintainer explained in GitHub #9203 that the old implementation caused many problems and would need a redesign. The community workaround is to ask Codex to reverse its last changes with the patch tool, but deleted untracked files cannot be recovered. Committing to git before each task is currently the most reliable way back.

For finer control than sandbox_mode, use permission profiles (beta): set read, write or deny per path under [permissions.<name>] and allow-list network domains. The next section shows how to make raw data read-only.

CombinationWhat it can doPractical consequence
read-only + on-requestRead files and run read-only commands; writes and network need your approvalFor a first look at someone else's code or explanations only; every change needs a click
workspace-write + on-request (the default Auto)Read, write and run commands in the working directory, /tmp and $TMPDIR; writes outside and network need approvalRecommended for daily work. Every file in the working directory, raw data included, can be changed or deleted
workspace-write + neverSame as above; out-of-bounds actions simply failCommon for codex exec. After a failure the model may try another route around it
workspace-write + approvals_reviewer = "auto_review"Out-of-bounds requests go to a reviewer agent firstFewer interruptions; reviews use extra allowance, and /approve retries one denied action
danger-full-access or --yolo (--dangerously-bypass-approvals-and-sandbox)No sandbox, no approvals; reads and writes the whole machine and the networkOfficially meant only for already-isolated containers or VMs. Deleted untracked files cannot be recovered through Codex

Research code

Research analysis differs from ordinary software work in three ways: raw data cannot be regenerated, results must trace back to exact commands and parameters, and tasks run long. The steps below address each.

Permission profile: data/raw read-onlytoml
# ~/.codex/config.toml: make data/raw read-only with a permission profile
# Use this block OR sandbox_mode / [sandbox_workspace_write]; if both are present the profile is ignored
default_permissions = "research"

[permissions.research]
extends = ":workspace"              # inherit the default workspace profile (.git/.codex read-only, network off)

[permissions.research.filesystem.":workspace_roots"]
"data/raw" = "read"                 # relative to each workspace 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 :workspace profile, appending to data/raw/counts.csv succeeds
  1. 01

    Layer 1: make raw data read-only at the OS level

    The simplest option is chmod -R a-w data/raw. A Codex-only option is a permission profile that extends :workspace and sets data/raw to read (code below). Use it instead of sandbox_mode: if any config layer contains sandbox_mode or you pass --sandbox, the profile has no effect.

  2. 02

    Layer 2: directory conventions in AGENTS.md

    State which directories are read-only, where generated files go and what counts as done. The agent follows these rules, but rules alone cannot block writes, so combine them with layer 1.

  3. 03

    Layer 3: git and per-run directories

    If raw data stays out of git, at least track scripts, configs and RUN.md. Write each run to a new results/<date>_<label>/ directory instead of overwriting old results.

  4. 04

    Require a reproducibility record

    Have AGENTS.md require a RUN.md per run: commands, input file md5s, software and package versions (conda env export or sessionInfo()), random seed, parameters, runtime and outputs. When reviewing, read RUN.md before the results.

  5. 05

    Prepare the environment first

    workspace-write has no network by default, so pip / conda installs fail. Build the environment yourself before the task, or enable network_access only for the turn that installs packages and turn it off afterwards.

  6. 06

    When the context gets long

    Check remaining context with /status. Codex compacts automatically at a threshold (adjust with model_auto_compact_token_limit), or run /compact manually. GitHub #36642 reports that since 0.145 auto-compaction occasionally discards the entire history; it still reproduces on 0.150 and the issue is open. In long tasks, have Codex write progress, confirmed parameters and open items to NOTES.md, and have it read that file first after a failed compaction or in a new session.

Troubleshooting

Read the URL or path in the error first: it shows where the request actually went or which file was refused. Then run codex doctor, which checks login, WebSocket, proxy variables and the sandbox separately.

Error messageCauseFix
unexpected status 401 Unauthorized: Missing bearer or basic authentication in headerNo usable credentials (empty auth.json, or the env_key variable is not exported in this shell)Check with codex login status; with API keys, confirm the variable is exported
stream disconnected before completion: error sending request for url (http://127.0.0.1:<port>/v1/responses)A leftover model_provider in config.toml points to a local proxy that is not runningDelete the model_provider line and its [model_providers.x] table; changing model alone is not enough
stream disconnected before completion: error sending request for url (https://chatgpt.com/backend-api/codex/responses)The network or proxy cuts long-lived connections; more common with SOCKS5 proxy variablesUse HTTP proxy variables with NO_PROXY; when doctor shows websocket failing, Codex tries an HTTPS fallback
Every request in WSL fails with stream disconnected from 0.129.0 onWSL networking regression reported in GitHub #24511; 0.128.0 works; issue openCommunity fix: enable WSL mirrored networking, or run on native Windows
Token exchange failed: error sending request for url (https://auth.openai.com/oauth/token)The last sign-in step could not reach auth.openai.comCheck the proxy covers that domain; on servers use --device-auth
no native root CA certificates foundThe server lacks system root certificatesPoint CODEX_CA_CERTIFICATE or SSL_CERT_FILE to a PEM file, e.g. the one shipped with Python certifi
Not inside a trusted directory and --skip-git-repo-check was not specified.codex exec must run in a git repository or trusted directorygit init or add --skip-git-repo-check
Operation not permitted (writing files or git commit)The target is outside the writable roots or in a protected path such as .git or .codexAdd a writable directory with --add-dir, or approve the action in the session
Could not resolve host (pip, curl, git clone)workspace-write disables the network by defaultSet sandbox_workspace_write.network_access = true, or approve that network request
Codex is ignoring N unrecognized configuration settingsMisspelled, deprecated or misplaced fieldsFix the field path shown; use --strict-config to make it a hard error
Missing optional dependency @openai/codex-<platform>The npm platform package failed to downloadSee the Install section
Windows sandbox commands fail with error 1385System policy denies the logon type the sandbox user needsAsk IT to grant the logon right; temporarily set [windows] sandbox to unelevated
Skipped loading 1 skill(s) due to invalid SKILL.md files ... missing YAML frontmatterA local skill file lacks the --- delimited name and descriptionAdd the YAML header at the top of the file
The first two rows and the leftover-proxy case come from a CSDN post with the author's own test record; 401, Not inside a trusted directory, Operation not permitted and Could not resolve host were triggered on this page with 0.162.1.

Chinese community experience

The following come from posts with original error output or the author's own test record, cross-checked against the official documentation or GitHub issues, with the conditions under which they apply.

Remove custom providers completely when switching back to official sign-in

A CSDN author (Codex 0.142.0, Windows) saw requests going to 127.0.0.1:57321. A local proxy tool installed earlier had left model_provider and [model_providers.CodexPlusPlus] in config.toml, and the proxy was no longer running. Changing model back to an official model still used the old provider; removing both blocks and running codex logout and codex login fixed it. A later token_exchange_failed during sign-in was solved by switching proxy nodes.

Lab servers without internet or root

A CSDN author's tested setup: add RemoteForward 17891 127.0.0.1:7890 for the server in the local ~/.ssh/config to map the local proxy onto the server; export HTTP(S)_PROXY=http://127.0.0.1:17891 on the server; if root certificates are missing, set SSL_CERT_FILE to certifi's cacert.pem; load the same variables for the VS Code extension through ~/.vscode-server/server-env-setup, then run Remote-SSH: Kill VS Code Server on Host and reconnect. The author recommends getting the CLI working before the extension.

The macOS desktop app ignores proxy variables from the terminal

Proxies exported in .zshrc only apply to codex started from a terminal. An app opened from the Dock needs launchctl setenv followed by a restart (CSDN post). In GitHub #20844 a Windows user likewise only became stable after setting both the system proxy and the environment variables to an HTTP proxy.

If config changes do nothing, read doctor's ignore warnings

The warning mcp_servers.node_repl.type is ignored recorded in a CSDN post matches the format this page saw with codex doctor --all on 0.162.1. MCP configs migrated from Claude Code often carry a type field that Codex does not use.

Disagreement: fixing WSL disconnects

A NodeSeek user fixed it with WSL mirrored networking (networkingMode=mirrored, dnsTunneling=true); the reporter of GitHub #24511, on an Enterprise account, only recovered by going back to 0.128.0. Both start by running codex doctor inside WSL on its own, because WSL and Windows use different proxy variables and configs.

Hand it to an agent

Example instruction: "This is my RNA-seq project repository; raw counts are in data/raw. Read AGENTS.md and scripts/ first, run 01_qc through 03_deseq without modifying data/raw, write RUN.md for each step, and finally list how the results differ from the previous run and what I need to check."

Steps the agent performs: in an isolated cloud computer built on Codex, it reads the repository and AGENTS.md; uses the preinstalled pandas, SciPy, statsmodels and scikit-learn environment and installs missing R or Python packages in the workspace; runs the numbered scripts while recording commands, versions and parameters; reviews the results adversarially; keeps running after you close your computer and pauses with its state preserved when idle.

Outputs: modified scripts, a results directory with RUN.md and logs for every run, and a record explaining changes and anomalies.

You still need to check: whether the statistical methods and thresholds fit your study design, whether sample groups and batch information are correct, and the biological interpretation of the results.

References

FAQ

How do I use Codex? What is the minimum?

Three steps: install with npm install -g @openai/codex or the official installer; run codex in a project directory and sign in with a ChatGPT account or an API key; describe the task in plain language, for example "Read this repository and explain what each script in scripts/ does." Commit to git before Codex starts making changes.

Can I use Codex with a free account?

The official pricing page shows that the Free and Go plans can use GPT-6 Luna in the ChatGPT desktop app (rolling out). The CLI, IDE extension and Codex Cloud are available from the Plus plan; you can also pay per use with an API key in the CLI and IDE extension.

What if my config.toml changes have no effect?

Check in order: run echo $CODEX_HOME to confirm you edited the directory in use; run codex exec --strict-config to find misspelled or misplaced fields; use /debug-config in a session to see whether a project config or profile overrides it; a project's .codex/config.toml only loads after you trust the project and cannot set provider-related keys.

Can Codex use DeepSeek or other Chinese models?

Custom providers in the current version only support the Responses protocol, and wire_api = "chat" is an error. If the upstream only offers Chat Completions, you need a gateway that translates to Responses. Codex is tuned for OpenAI models, so results may be worse with other models.

Why does the AGENTS.md in a subdirectory have no effect?

Codex only reads AGENTS.md files on the path from the project root to the directory where you start it. Started at the root, files in subdirectories are not loaded. Start in that subdirectory (codex -C <subdir>) or move the rules into the root file. Also check that the total size is under 32 KiB.

How do I stop Codex from deleting or changing raw data?

Combine three layers: make data/raw read-only at the file system level with chmod or a permission profile; state the directory conventions in AGENTS.md; commit to git before each task and write results to a new directory. AGENTS.md rules alone cannot block writes, and /undo has been removed from the CLI.

Run a Codex-based research agent in the cloud

Scientify's science agent runs in an isolated cloud computer with molecular simulation, bioinformatics and numerical computing environments preinstalled. GPUs are rented per task when needed, and tasks keep running after you close your computer. Model usage costs about 30% of standard API prices, and new users get $5 in free credit.