Codex CLI Guide: Setup, config.toml, AGENTS.md, Approval Modes and Real Workflows
A practical, independent guide to OpenAI Codex CLI, the open-source coding agent that runs in your terminal. It covers installation and sign-in, config.toml configuration, AGENTS.md project instructions, sandbox and approval modes, codex exec for scripts and CI, MCP servers, profiles, local models, and day-to-day workflows that actually save time. It includes copy-ready templates and a small tool that shows which AGENTS.md files Codex will load.
For developers trying Codex CLI for the first time and for teams standardizing how they use it.
Last reviewed: December 2026, against Codex CLI release notes and the official documentation (latest release at review time:
rust-v0.172.0). Codex ships updates often; flags and config keys occasionally change or are retired. When this guide andcodex --helpor the official docs disagree, trust the official sources. Not affiliated with OpenAI.
Table of Contents
- What Codex CLI is (and is not)
- Install
- Sign in: ChatGPT plan or API key
- Your first 15 minutes
- Permissions: sandbox modes and approval policies
- AGENTS.md: project instructions that stick
- config.toml: the settings that matter
- Profiles
- Slash commands cheat sheet
- CLI commands and flags cheat sheet
- Non-interactive mode: codex exec
- Code review with Codex
- MCP servers
- Skills: reusable workflows
- Hooks: run your own code at lifecycle events
- Local and alternative model providers
- Workflows that work
- Prompting tips for coding agents
- Security checklist
- Troubleshooting
- Codex CLI vs other terminal agents
- FAQ
- Where to go next
- Repository layout
- Contributing
- License
- More free resources
What Codex CLI is (and is not)
Codex CLI is a terminal user interface (TUI) and command-line tool, written in Rust and open source under Apache-2.0 (repository), that lets an OpenAI model read your code, edit files and run commands on your machine inside a sandbox, with approval prompts you control.
The “Codex” name covers several surfaces that share accounts, configuration and usage limits:
| Surface | Where it runs | Use it for |
|---|---|---|
| Codex CLI | Your terminal, your machine | Interactive coding, scripts, CI (codex exec) |
| IDE extension | VS Code and compatible editors | The same agent inside your editor |
| Desktop app | ChatGPT desktop app (codex app opens it) |
A GUI for local and cloud sessions |
| Codex cloud | OpenAI-hosted containers, started from ChatGPT or codex cloud |
Background tasks on a repository; apply results locally with codex apply |
This guide focuses on the CLI. The configuration file and AGENTS.md rules apply to the IDE extension too.
Install
Requirements from the project’s install docs: macOS 12+, Ubuntu 20.04+ / Debian 10+, or Windows; Git 2.23+ recommended; 4 GB RAM minimum (8 GB recommended).
| Method | Command |
|---|---|
| Standalone installer (macOS, Linux) | curl -fsSL https://chatgpt.com/codex/install.sh \| sh |
| Standalone installer (Windows PowerShell) | powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 \| iex" |
| npm | npm install -g @openai/codex |
| Homebrew | brew install --cask codex |
| Binary | Download from GitHub Releases and rename to codex |
Then:
codex --version
codex update # check for and apply an update (or re-run your package manager)
codex doctor # diagnostics for install, config, auth and runtime issues
Shell completions: codex completion zsh > "${fpath[1]}/_codex" (or bash, fish; see codex completion --help).
Windows: Codex supports Windows with its own sandbox implementation; it also works inside WSL2. If you work mainly in Linux tooling, running Codex inside WSL2 keeps the agent and your toolchain in the same environment.
Sign in: ChatGPT plan or API key
| Method | How | Billing |
|---|---|---|
| Sign in with ChatGPT (recommended by OpenAI) | Run codex, choose Sign in with ChatGPT, finish in the browser |
Uses your ChatGPT plan’s Codex usage limits (credits can extend usage on eligible plans) |
| Device code | codex login --device-auth |
Same as above; for remote machines without a browser |
| API key | printenv OPENAI_API_KEY \| codex login --with-api-key |
Pay-as-you-go API pricing |
| API key for one run (automation) | CODEX_API_KEY=... codex exec "..." |
API pricing |
Useful commands: codex login status (exit code 0 when signed in, handy in scripts) and codex logout.
Plans and limits change; see the official pricing page for which ChatGPT plans include Codex and the current usage limits.
Where credentials live: ~/.codex/auth.json or your OS credential store, controlled by cli_auth_credentials_store (file, keyring, auto, ephemeral). If it is a file, treat it like a password: never commit it or paste it anywhere.
Your first 15 minutes
cd ~/code/your-repo
git status # start from a clean tree so every change is reviewable
codex
Inside the TUI:
/statusshows the model, permissions, working directory and token usage./initscaffolds anAGENTS.md. Edit it: add the exact build, test and lint commands.- Ask for orientation: “Explain how a request flows from the HTTP router to the database in this repo. Cite files.”
- Make a small change: “Add input validation to
createUserfor empty emails, with a test. Run the tests.” /diffto review what changed, then commit it yourself or ask Codex to./reviewfor a second pass over your working tree before you open a pull request.
Habits that pay off from day one:
- Commit before each task. Git is your undo button;
/diffandgit diffshow exactly what the agent did. - One task per session, or
/newbetween tasks, so context stays focused. - Use
/compactafter long sessions to free context while keeping key points. - Attach screenshots of UI bugs with
-i screenshot.pngor by pasting an image.
Permissions: sandbox modes and approval policies
Two settings decide what Codex can do without asking.
Sandbox mode (--sandbox / -s, or sandbox_mode) limits what commands can touch:
| Mode | Files | Network | Notes |
|---|---|---|---|
read-only |
Read anywhere the sandbox allows, no writes | Off | Default for codex exec; safe for questions and analysis |
workspace-write |
Write inside the working directory (and --add-dir roots) |
Off unless enabled | .git, .agents, .codex and .aws under writable roots stay read-only |
danger-full-access |
Everything your user can access | On | No sandbox. Only inside a disposable container or VM |
Approval policy (--ask-for-approval / -a, or approval_policy) decides when Codex pauses:
| Policy | Behavior |
|---|---|
on-request |
Actions inside the sandbox run; Codex asks before stepping outside it (writes outside the workspace, network) |
never |
Never asks; actions outside the sandbox fail instead. Use for CI with a tight sandbox |
Granular (approval_policy = { granular = { ... } }) |
Keep some prompt categories interactive while auto-rejecting others |
The older
untrustedapproval policy and the--full-autoflag have been retired in current releases. Remove them from configs and scripts. For a stricter per-project rule, mark the project untrusted in your user config (trust_level = "untrusted"under that project’s entry) or use theread-onlysandbox.
Common combinations (from the official guidance):
| Goal | Flags |
|---|---|
| Default “Auto” preset for a Git repo | no flags, or --sandbox workspace-write --ask-for-approval on-request |
| Look but do not touch | --sandbox read-only --ask-for-approval on-request |
| Read-only CI analysis | codex exec --sandbox read-only --ask-for-approval never |
| Edits in CI | codex exec --sandbox workspace-write |
| Let a reviewer agent handle approval prompts | -c approvals_reviewer=auto_review (or approvals_reviewer = "auto_review") |
| No sandbox, no prompts (disposable containers only) | --dangerously-bypass-approvals-and-sandbox (alias --yolo) |
Change permissions mid-session with /permissions. Enable network for commands only when needed:
[sandbox_workspace_write]
network_access = true
Why it matters: an agent that can run commands with network access can be steered by prompt injection in files, issues, web pages or dependencies to exfiltrate data. Keep network off by default, and never run danger-full-access on a machine with credentials you care about.
AGENTS.md: project instructions that stick
AGENTS.md is a plain Markdown file of instructions that Codex reads before it starts working. It is a cross-tool convention (agents.md) also read by several other coding agents, so one file can serve your whole team.
How Codex finds instruction files
- Global: in
CODEX_HOME(default~/.codex),AGENTS.override.mdif present and non-empty, otherwiseAGENTS.md. - Project: from the project root (usually the Git root) down to your working directory. In each directory, the first non-empty file among
AGENTS.override.md,AGENTS.md, and anyproject_doc_fallback_filenames. At most one file per directory. - Merge: files are concatenated root-first; files closer to your working directory come later and therefore take precedence. Loading stops at
project_doc_max_bytes(32 KiB by default).
Check what will load for any folder with the tool in this repo:
python3 scripts/agents_chain.py ~/code/your-repo/services/payments
# Load order (later files take precedence):
# 1. [global] /Users/you/.codex/AGENTS.md (412 bytes)
# 2. [project] /Users/you/code/your-repo/AGENTS.md (1830 bytes)
# 3. [project] /Users/you/code/your-repo/services/payments/AGENTS.override.md (377 bytes)
# note: AGENTS.md in the same folder is ignored
# Project instructions total: 2207 bytes (limit 32768).
Or ask Codex directly: codex --ask-for-approval never "List the instruction sources you loaded."
What to put in AGENTS.md
Write for a capable new teammate who has never seen the repo:
| Include | Example |
|---|---|
| Exact commands | pnpm test -- path/to/file.test.ts for a single test |
| Definition of done | “Run lint, type check and the tests you touched; report results” |
| Conventions that are not obvious from code | “Errors are returned, never thrown, in core/” |
| Boundaries | “Never edit migrations/ that are merged; ask before adding dependencies” |
| Map of the repo | “API in apps/api, shared types in packages/types” |
| Review rules | A ## Code Review Rules section that Codex code review uses |
Avoid: long style guides your linter already enforces, secrets or internal URLs you would not want in model context, and vague advice (“write clean code”).
Templates in templates/:
| File | Use |
|---|---|
AGENTS.md |
General repository template |
AGENTS.python.md |
Python service with uv, ruff, mypy, pytest |
AGENTS.monorepo-root.md |
Root of a monorepo pointing to package-level files |
global-AGENTS.md |
Personal defaults for ~/.codex/AGENTS.md |
Tips:
- Nested files for specialized areas (
services/payments/AGENTS.md), so rules load only where they apply. AGENTS.override.mdfor temporary rules without editing the shared file; delete it to revert.- Fallback names if your repo already has a guide:
project_doc_fallback_filenames = ["CONTRIBUTING.md"]. - Keep it under a few KB. Every byte is read on every session.
config.toml: the settings that matter
User config lives at ~/.codex/config.toml; trusted projects can add .codex/config.toml. Precedence, highest first:
- CLI flags and
-c key=valueoverrides - Project
.codex/config.tomlfiles (closest wins; trusted projects only) - Profile file selected with
--profile name(~/.codex/name.config.toml) - User config
~/.codex/config.toml - Cloud-managed defaults for your workspace (if any)
- System config
/etc/codex/config.toml(Unix) - Built-in defaults
Organizations can also enforce limits through requirements.toml (for example, disallowing danger-full-access).
A commented starting point is in templates/config.toml. The keys people change most:
| Key | Values | What it does |
|---|---|---|
model |
a model name | Default model (pick with /model; codex debug models prints the catalog you can use) |
model_reasoning_effort |
depends on model | More effort = slower, more thorough |
approval_policy |
on-request, never, granular table |
When to pause for approval |
sandbox_mode |
read-only, workspace-write, danger-full-access |
Command isolation level |
[sandbox_workspace_write] network_access |
true / false |
Network for commands in workspace-write |
[sandbox_workspace_write] writable_roots |
list of paths | Extra writable directories |
web_search |
cached (default), indexed, live, disabled |
Web search tool behavior |
cli_auth_credentials_store |
file, keyring, auto, ephemeral |
Where login tokens are stored |
[shell_environment_policy] |
filters | Which environment variables commands inherit |
project_doc_max_bytes |
bytes | AGENTS.md size budget |
project_doc_fallback_filenames |
list | Extra instruction filenames |
[mcp_servers.<name>] |
table | MCP servers (below) |
oss_provider |
ollama, lmstudio |
Default local provider for --oss |
notify |
command array | Run a program when a turn completes (toasts, webhooks) |
[tui] notifications |
bool or list | Built-in terminal notifications |
[history] persistence |
none to disable |
Local transcript history |
[features] |
flags | Optional features; manage with codex features |
One-off overrides use TOML values: codex -c model_reasoning_effort='"high"' or codex -c sandbox_workspace_write.network_access=true.
Secrets hygiene: by default (ignore_default_excludes = true) Codex does not apply automatic filtering of variables whose names contain KEY, SECRET or TOKEN. Set ignore_default_excludes = false under [shell_environment_policy] if you want them filtered from spawned commands, and add explicit include filters for what tools need.
Profiles
Profiles are separate files layered over your user config, ideal for switching between “careful”, “fast” and “CI” setups.
# ~/.codex/deep-review.config.toml contains only the keys that differ
codex --profile deep-review
codex exec --profile ci-readonly "summarize risky changes in this branch"
Rules (current releases): one file per profile at ~/.codex/<name>.config.toml, with top-level keys only. The legacy [profiles.<name>] tables inside config.toml and the profile = "<name>" selector are no longer read; move them into separate files.
Examples: templates/ci-readonly.config.toml and templates/local-oss.config.toml.
Slash commands cheat sheet
Type / in the TUI to see the full, current list. The ones you will use most:
| Command | What it does |
|---|---|
/init |
Generate an AGENTS.md scaffold |
/status |
Model, approval policy, writable roots, token usage |
/permissions |
Change what Codex may do without asking |
/model |
Choose model and reasoning effort |
/plan |
Switch to plan mode (propose before editing) |
/diff |
Show the Git diff, including untracked files |
/review |
Review your working tree |
/compact |
Summarize the chat to free context |
/new |
New chat in the same CLI session |
/clear |
Clear the terminal and start a fresh chat |
/resume |
Reopen a saved chat |
/fork |
Branch the current chat into a new one |
/mention |
Attach a file to the chat |
/mcp |
List configured MCP tools |
/skills |
Browse and use skills |
/goal |
Set or view a persistent task goal |
/ps and /stop |
Show or stop background terminals |
/copy |
Copy a response or code block |
/export |
Export the conversation as Markdown |
/usage |
View usage and limits |
/debug-config |
See which config layers and requirements apply |
/feedback |
Send feedback or save a diagnostic bundle |
/quit or /exit |
Leave |
Other handy ones: /side (side chat without derailing the main one), /worktree (work in a managed Git worktree), /cd (change working directory), /keymap and /vim (editing), /theme, /statusline.
CLI commands and flags cheat sheet
| Command | Purpose |
|---|---|
codex |
Interactive TUI (optionally with an initial prompt: codex "explain this repo") |
codex exec (alias codex e) |
Non-interactive run for scripts and CI |
codex review |
Non-interactive code review (--uncommitted, --base <branch>, --commit <sha>) |
codex resume |
Continue a previous session (--last for the most recent in this directory, --all for any directory) |
codex fork |
Fork a previous session into a new chat |
codex login / codex logout |
Manage authentication (--device-auth, --with-api-key, status) |
codex mcp |
Add, list, remove and authenticate MCP servers |
codex features |
List and toggle feature flags |
codex cloud |
Browse or run Codex cloud tasks from the terminal |
codex apply (alias codex a) |
Apply the latest diff from a cloud task to your working tree |
codex sandbox |
Run arbitrary commands inside the Codex sandbox |
codex execpolicy |
Check whether a command would be allowed, prompted or blocked by rules |
codex plugin |
Install, list and remove plugins |
codex doctor |
Diagnostic report |
codex update |
Update the CLI |
codex completion |
Shell completion scripts |
Global flags:
| Flag | Meaning |
|---|---|
-m, --model |
Model override |
-s, --sandbox |
read-only, workspace-write, danger-full-access |
-a, --ask-for-approval |
on-request, never |
-C, --cd |
Working directory |
-i, --image |
Attach image files to the first prompt |
--search |
Live web search |
-p, --profile |
Profile layer |
-c, --config key=value |
One-off config override (TOML value) |
--add-dir |
Extra writable directory |
--oss |
Use a local provider (Ollama, LM Studio) |
--enable <feature> |
Force-enable a feature flag |
Non-interactive mode: codex exec
codex exec runs one task without the TUI. Progress goes to stderr, and only the final message goes to stdout, so it composes with pipes.
# Read-only by default: safe for analysis
codex exec "summarize the repository structure and list the 5 riskiest areas"
# Pipe in context
git log --oneline -20 | codex exec "write release notes grouped by feature, fix and chore" > NOTES.md
npm test 2>&1 | tail -n 200 | codex exec "explain the failing tests and propose the smallest fix"
# Prompt from stdin
cat prompt.md | codex exec -
# Allow edits in the workspace
codex exec --sandbox workspace-write "fix the lint errors in src/ and run the linter again"
# Machine-readable event stream (JSON Lines)
codex exec --json "triage open TODO comments" | jq -c 'select(.type)'
# Final message to a file, and structured output validated against a JSON Schema
codex exec "assess this branch for risk" --output-schema templates/output-schema.json -o risk.json
# Two-stage pipeline: continue the last exec session
codex exec "review the change for race conditions"
codex exec resume --last "fix the race conditions you found"
# Don't keep session files on disk
codex exec --ephemeral "explain the build system"
Things to know:
- Codex requires a Git repository by default to protect against destructive changes;
--skip-git-repo-checkoverrides it when you are sure. - Project config and project-defined MCP servers load only for trusted projects;
--trustsaves trust for that run’s project. - An MCP server marked
required = truethat fails to start makescodex execexit with an error. - CI credentials: use
CODEX_API_KEYfor the single Codex step. Do not export API keys as job-wide environment variables in workflows that also run repository-controlled code (tests, build scripts, dependency hooks), which could read them.
CI pattern (safe shape, any CI system):
- Job A (read-only repo token, API key only for the Codex step): run
codex exec --sandbox workspace-write "<fix the failing test>", then savegit diffas an artifact. - Job B (no API key, write token): download the diff, apply it, open a pull request for human review.
Splitting the steps keeps the model-driven job away from write credentials and keeps a human in the loop before merge. OpenAI also publishes a GitHub Action, openai/codex-action; see the non-interactive docs for the current recipe.
Code review with Codex
Three ways to get a review:
| Where | How |
|---|---|
| In the TUI | /review, then choose uncommitted changes, a base branch or a commit |
| From the terminal | codex review --uncommitted, codex review --base main, codex review --commit <sha> |
| On GitHub | Connect Codex cloud to your repository and request reviews on pull requests (see official docs) |
Make reviews match your standards by adding a ## Code Review Rules section to the nearest AGENTS.md, with concrete checks and the safe alternative for each:
## Code Review Rules
- Flag SQL built with string concatenation. Safe path: parameterized queries via `db.query(sql, params)`.
- Flag new endpoints without an authorization check in `middleware/auth.ts`.
- Do not comment on formatting; CI runs the formatter.
MCP servers
Model Context Protocol servers give Codex extra tools: browsers, docs search, issue trackers, databases.
Add one from the command line or in config.toml:
codex mcp add playwright -- npx -y @playwright/mcp@latest
codex mcp list
# stdio server
[mcp_servers.playwright]
command = "npx"
args = ["-y", "@playwright/mcp@latest"]
startup_timeout_sec = 20
tool_timeout_sec = 120
# HTTP server with a bearer token from an environment variable
[mcp_servers.docs]
url = "https://mcp.example.com/mcp"
bearer_token_env_var = "DOCS_MCP_TOKEN"
enabled_tools = ["search", "fetch"] # allow list
Options worth knowing: env (extra environment for stdio servers), startup_timeout_sec (default 10), tool_timeout_sec (default 60), required = true (fail startup if the server is not ready), enabled_tools / disabled_tools. OAuth-protected servers: codex mcp add <name> --url <url> and follow the login flow (see the MCP docs).
Check /mcp in the TUI to confirm tools loaded. Each MCP tool is code you are trusting; add only servers from sources you trust, and prefer allow lists.
Popular servers to try: Playwright MCP (browser automation), Chrome DevTools MCP (debug web apps), GitHub MCP server (issues and PRs), and the reference servers from the MCP project.
Skills: reusable workflows
A skill is a folder with a SKILL.md file (YAML front matter with name and description, then instructions) plus optional scripts/, references/ and assets/. Codex follows the open Agent Skills format, so skills are portable to other tools that support it.
How Codex uses them:
- At startup it lists each skill’s name, description and path (a small slice of context); it loads the full
SKILL.mdonly when a task matches the description or you invoke it. - Invoke explicitly with
/skillsor by typing$and the skill name; built-in$skill-creatordrafts new skills for you. - Locations:
.agents/skillsfolders from your working directory up to the repository root (team skills, checked in),~/.agents/skills(personal),/etc/codex/skills(admin), plus bundled system skills.
Example: templates/skills/release-notes/SKILL.md. Copy the folder into .agents/skills/ in your repo, then ask “write release notes since the last tag”.
Writing good skills:
- The description is the trigger. Front-load the use case and trigger words, and say when not to use it.
- Keep instructions procedural: numbered steps, exact commands, expected output format.
- Put long references in
references/and tell the skill when to read them, so they do not cost context every time. - Ship scripts for deterministic work (formatting, validation) instead of asking the model to do it by hand.
Hooks: run your own code at lifecycle events
Hooks run commands when events happen: before or after a tool runs, when a prompt is submitted, when a session starts, before compaction, when the agent stops. Use them to enforce policy (block dangerous commands), run formatters after edits, or log activity.
Locations: ~/.codex/hooks.json or inline [hooks] in ~/.codex/config.toml, and the same files under a trusted repository’s .codex/ folder.
# ~/.codex/config.toml: run a policy check before every shell command
[[hooks.PreToolUse]]
matcher = "^Bash$"
[[hooks.PreToolUse.hooks]]
type = "command"
command = 'python3 ~/.codex/hooks/check_command.py'
timeout = 30
statusMessage = "Checking command"
Events documented at review time include SessionStart, UserPromptSubmit, PreToolUse, PermissionRequest, PostToolUse, PreCompact, PostCompact, SubagentStart, SubagentStop and Stop; see the hooks docs for input fields and how a hook returns a blocking decision.
Caveats from the docs worth knowing: an error, timeout or malformed response from a PreToolUse hook can let the tool run, so do not treat hooks as your only security boundary; the sandbox is. Project hooks load only for trusted projects; review them like any code that runs on your machine.
Simpler alternative for notifications: notify = ["python3", "/path/to/notify.py"] runs a program when a turn completes (for desktop toasts or chat webhooks), and [tui] notifications handles terminal notifications.
Local and alternative model providers
Local models with --oss: Codex can use a local provider such as Ollama or LM Studio.
ollama pull <a coding model>
codex --oss # prompts for a provider if none is set
codex --oss --local-provider ollama -m <model>
oss_provider = "ollama" # or "lmstudio"; required for `codex exec --oss`
Expect lower quality than frontier hosted models on long, multi-step tasks; local models work best for small edits, explanations and private code you cannot send out.
Other providers and proxies: define [model_providers.<id>] with base_url, env_key and wire settings, then set model_provider = "<id>". To route the built-in OpenAI provider through a proxy or data-residency endpoint, set openai_base_url. Built-in support also exists for Azure, Amazon Bedrock and Google Cloud configurations; see advanced configuration.
Workflows that work
1. Explore an unfamiliar codebase
Read-only. Map this repository: main components, how they talk to each other,
where configuration comes from, and how to run the tests. Cite file paths.
End with the 5 files I should read first.
Run with codex --sandbox read-only so nothing changes.
2. Plan, then implement
Use /plan (or ask for a plan) for anything larger than a one-file change. Approve or edit the plan, then let Codex implement step by step, running tests after each step.
3. Test-first bug fix
Bug: <symptom>. First write a failing test that reproduces it and run it to show it fails.
Then fix the code with the smallest change, run the test again, and run the full test file.
4. Mechanical refactors in batches
Rename `getUserById` to `findUser` across the repo, including tests and docs.
Do it package by package, running that package's tests after each one. Stop on the first failure.
5. Review before you push
codex review --base main
6. Parallel tasks without collisions
Use /worktree (or git worktree add) so two Codex sessions never edit the same checkout.
7. Scripts and chores with codex exec
codex exec "update CHANGELOG.md from commits since the last tag; follow the existing format" --sandbox workspace-write
8. Hand off to the cloud
Start long-running tasks in Codex cloud (codex cloud), keep working locally, then codex apply the result when it is ready.
Prompting tips for coding agents
- State the goal, the constraints and the definition of done. “Make the CSV export stream rows instead of buffering. Keep the public API. Done = tests pass and memory stays flat on the 1 GB fixture.”
- Point to files and examples: “Follow the pattern in
src/handlers/orders.ts.” - Ask for verification: “Run the tests and show the output.” Agents that verify their work make fewer silent mistakes.
- Keep tasks small. Several focused sessions beat one sprawling one.
- Say what not to touch: generated code, migrations, public interfaces.
- Correct course early. Interrupt (Esc) and redirect rather than waiting for a long wrong path to finish.
- Put recurring guidance in AGENTS.md instead of repeating it in every prompt.
Security checklist
- Default to
workspace-writewithon-requestapprovals; network off unless a task needs it. - Never use
danger-full-accessor--yolooutside a disposable container or VM with no real credentials. - Review diffs before committing; protect
mainwith required reviews. - Keep secrets out of the repo and out of AGENTS.md. Consider filtering secret-looking environment variables via
[shell_environment_policy]. - Store login tokens in the OS keychain (
cli_auth_credentials_store = "keyring"or"auto"). - Treat issues, web pages, dependency READMEs and logs as untrusted input: they can contain prompt injection.
- Add only MCP servers and plugins you trust; use tool allow lists.
- In CI, give the Codex step read-only repository permissions and scope the API key to that step.
- Mark unfamiliar repositories as untrusted so their project config and hooks do not load automatically.
Troubleshooting
| Problem | Fix |
|---|---|
| Codex will not start after an upgrade | Remove retired settings such as approval_policy = "untrusted"; run codex doctor |
Script fails with unknown flag --full-auto |
Replace with --sandbox workspace-write |
codex exec refuses to run |
You are outside a Git repo; git init or pass --skip-git-repo-check deliberately |
| AGENTS.md seems ignored | Run python3 scripts/agents_chain.py or ask Codex to list loaded instructions; check for an AGENTS.override.md higher up, empty files, or the byte limit |
| Profile settings ignored | Profiles must be separate ~/.codex/<name>.config.toml files with top-level keys |
Project .codex/config.toml ignored |
The project is not trusted; trust it in the TUI or pass --trust to exec |
| Commands cannot reach the network | Expected in the sandbox; enable network_access for workspace-write or approve the request |
| Tests fail only under Codex | Sandbox blocks writes outside the workspace (caches in ~/.cache); add writable_roots or set cache dirs inside the repo |
| MCP server tools missing | Check /mcp; raise startup_timeout_sec; run the server command manually to see errors |
| Wrong account or workspace | codex logout, then codex login; forced_login_method can pin chatgpt or api |
| Need logs | codex -c log_dir=./.codex-log, then read ./.codex-log/codex-tui.log |
Codex CLI vs other terminal agents
All of these run in a terminal, edit files and execute commands; the differences are models, permission models, extensibility and pricing.
| Agent | Open source | Models | Notable |
|---|---|---|---|
| Codex CLI | Yes (Apache-2.0) | OpenAI models; local via --oss; custom providers |
OS-level sandbox modes, codex exec, ChatGPT plan sign-in, cloud hand-off |
| Claude Code | Distributed via npm and installers; repository hosts docs and issues | Anthropic models | Permission modes, hooks, subagents, skills and plugins |
| Gemini CLI | Yes (Apache-2.0) | Google Gemini models | Large context, Google Search grounding, free tier with a Google account |
| OpenCode | Yes (MIT) | Many providers | Provider-agnostic TUI, client/server design |
| Aider | Yes (Apache-2.0) | Many providers | Git-native pair programming with automatic commits |
Pick by the model you want to use, how much sandboxing you need, and whether your plan already includes usage. Many developers keep two installed and choose per task.
FAQ
Is Codex CLI free?
The CLI is open source. Using it requires model access: either a ChatGPT plan that includes Codex usage (limits vary by plan) or an API key billed per token. Local models via --oss cost only your hardware.
Is Codex CLI the same as the old Codex model? No. The original 2021 Codex model was retired long ago. Today “Codex” is OpenAI’s coding agent product family; the CLI is one surface of it.
Does Codex CLI work on Windows? Yes. Install with the PowerShell script, npm or a release binary. Codex has a Windows sandbox; WSL2 is also supported.
Where is the config file?
~/.codex/config.toml (or $CODEX_HOME/config.toml). Project overrides go in .codex/config.toml inside a trusted repository.
What happened to --full-auto?
It was retired. Use --sandbox workspace-write (with on-request approvals in interactive sessions).
How do I stop Codex from asking for approval all the time?
Use the default Auto preset (workspace-write + on-request) so routine edits and commands inside the repo run without prompts. If prompts are for network access, enable network_access only for projects that need it. Consider approvals_reviewer = "auto_review" to let a reviewer agent handle eligible requests.
Can I use Codex with Claude, Gemini or other models?
Codex can talk to custom providers that implement the wire APIs it supports and to local providers via --oss. Quality and tool-use reliability vary; Codex is tuned for OpenAI models.
Does AGENTS.md work with other tools? Yes. AGENTS.md is a shared convention read by many coding agents; check each tool’s docs for how it discovers and merges files.
How do I run Codex in GitHub Actions safely?
Run codex exec in a job with read-only repository permissions and the API key scoped to that step, save the diff as an artifact, and open the pull request from a separate job without the key.
How do I see token usage?
/status for the session, /usage for account limits.
Can Codex browse the web?
Codex has a web search tool (cached results by default; --search or web_search = "live" for live). For full browser automation, add a browser MCP server.
Where to go next
- Official docs: Codex documentation, configuration reference, AGENTS.md guide, sandbox and approvals, non-interactive mode.
- Source and releases: openai/codex and its releases page.
- The AGENTS.md convention.
- The Model Context Protocol to connect your own tools.
- Copy
templates/AGENTS.mdinto your repo, fill in real commands, and runpython3 scripts/agents_chain.pyto confirm it loads.
Repository layout
codex-cli-guide/
├── templates/
│ ├── AGENTS.md # general project instructions template
│ ├── AGENTS.python.md # Python service variant
│ ├── AGENTS.monorepo-root.md # monorepo root variant
│ ├── global-AGENTS.md # personal ~/.codex/AGENTS.md
│ ├── config.toml # commented ~/.codex/config.toml starting point
│ ├── ci-readonly.config.toml # profile for read-only automation
│ ├── local-oss.config.toml # profile for local models
│ ├── output-schema.json # example schema for codex exec --output-schema
│ └── skills/release-notes/ # example Agent Skill (SKILL.md)
├── scripts/agents_chain.py # show the AGENTS.md files Codex would load (stdlib)
└── tests/test_agents_chain.py # tests for discovery order, overrides, limits, skill front matter
Run the tests: python3 -m unittest discover -s tests
Contributing
PRs are welcome: corrections when Codex changes flags or config keys (please link the release note or doc page), new templates, workflow recipes you use, and troubleshooting entries. Keep entries accurate and current, mark anything version-specific, and run the tests.
License
Code and templates are released under the MIT License.
If this helped you, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.