Building Module 6 · CLI Tools Setup

Codex CLI

Last reviewed · content updated

Beginner

What you'll learn

~15 min
  • Install Codex CLI with the installer script, npm, or Homebrew
  • Sign in with your ChatGPT account or set up an API key
  • Run your first autonomous task with cautious permissions
  • Understand the approval policies and sandbox modes
ℹCloud Equivalent

Codex Cloud at chatgpt.com/codex runs async coding tasks in a sandboxed cloud environment and opens PRs when done — no local install required. Codex itself is now included on every ChatGPT plan (Free and Go get the lighter GPT-5.6 Terra model; cloud tasks are confirmed from Plus up), and local CLI work, cloud tasks, and the ChatGPT desktop app all share one usage pool. See the Cloud Sandbox Cheat Sheet for current pricing, or set up your sandbox.

By the end of this lesson, you’ll have Codex CLI installed and understand its unique strength: the ability to plan, execute, and iterate on tasks with minimal hand-holding.

What is Codex CLI?

Codex CLI is OpenAI’s open-source command-line coding agent, written in Rust. It’s designed for autonomous task execution — you assign it a task, and it can plan, implement, test, and iterate with minimal guidance, but outputs still require human review. OpenAI lists GPT-5.6 Sol as its flagship tier; Terra is the balanced, cheaper sibling — and the only model on Free and Go — and Luna the fastest. Use /model to see what your plan offers and to pick both the model and its reasoning effort. (GPT-5.4 and GPT-5.4 mini are retired from Codex for ChatGPT sign-ins as of August 31, 2026, replaced by gpt-5.6-terra and gpt-5.6-luna in saved configs, custom agents, and scheduled tasks — if you authenticate with your own API key instead, this deprecation doesn’t apply to you.)

Key features:

  • Autonomous multi-step task execution
  • Can work with git workflows (including branches) when used inside a git repository
  • Sandboxed execution for safety
  • Web search (--search), MCP servers, plugins, and skills
  • Session resume (codex resume) to pick up where you left off
  • codex exec for non-interactive scripting and CI pipelines
  • Subagents for parallel work — the ultra reasoning setting fans a task out to four of them
  • /import pulls your settings and MCP servers over from Claude Code or Cursor
  • Open source (Rust)
🔍Mental model: Codex as a junior colleague

Think of Codex CLI like delegating a task to a capable junior colleague. You wouldn’t explain every keystroke — you’d say “Build me a to-do list app” and let them figure out the implementation. Codex works the same way. In its most cautious mode, your colleague checks in before every step (“Should I use localStorage for persistence?”). In a middle mode, they handle file changes on their own but ask before running commands. In full-auto mode, they just deliver the finished result. Like a junior teammate, it can be very helpful but still needs supervision and review. Start cautious while you’re learning to trust the tool.

ℹTool status — under active development

Codex CLI ships roughly weekly. Run codex update to stay current, and if a command below doesn’t match what you see, check codex --help or the Codex docs — the tool is the source of truth.

Installation

ℹWindows users: WSL recommended for the CLI

Codex CLI’s sandboxing features work best on Linux/macOS/WSL. A native Windows installer exists, but use WSL2 for the most reliable experience. The CLI instructions below assume WSL or macOS/Linux.

Step 1: Install Codex CLI

Option A — Installer script (recommended; no Node.js needed):

Terminal window
curl -fsSL https://chatgpt.com/codex/install.sh | sh

On Windows native (PowerShell): powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex"

Option B — npm (if you already have Node.js):

Terminal window
npm install -g @openai/codex

Option C — Homebrew (macOS):

Terminal window
brew install --cask codex

Verify (any install method):

Terminal window
codex --version

Later, codex update upgrades in place and codex doctor diagnoses install, config, and auth problems.

Step 2: Sign in

The easiest way to authenticate is with your ChatGPT account — no API key needed:

Terminal window
codex

On first launch, Codex opens a browser sign-in. Sign in with your ChatGPT account and you’re done. This works with every ChatGPT plan, including Free and Go (with tighter limits and the Terra model only).

On a remote server over SSH, use the device-code flow instead — it prints a URL and a code you enter on any browser:

Terminal window
codex login --device-auth
🔍Alternative: API key

If you prefer API-key authentication (or need it for CI/scripting), you can use an OpenAI API key instead — usage is then billed per token to your OpenAI Platform account:

  1. Go to platform.openai.com
  2. Create an account or sign in
  3. Navigate to API Keys and create a new secret key
  4. Set it as an environment variable and hand it to Codex:
Terminal window
export OPENAI_API_KEY="your-key-here"
printenv OPENAI_API_KEY | codex login --with-api-key

To make the variable permanent, add the export line to your shell config:

Terminal window
echo 'export OPENAI_API_KEY="your-key-here"' >> ~/.bashrc
source ~/.bashrc

(If your shell is zsh — check with echo $SHELL — use ~/.zshrc instead.)

⚠Keep API keys safe

If you use an API key, never commit it to a git repository or share it publicly. Treat it like a password. If you accidentally expose it, revoke it immediately from the OpenAI dashboard and create a new one.

ℹInvesting in Codex — know your window

Codex usage is metered against a shared five-hour window plus weekly limits; /status and /usage show where you stand. What each plan gets you (August 2026):

PlanPriceWhat it gets you
Free$0Limited Codex access for quick tasks; GPT-5.6 Terra only
Go$8/moLightweight coding tasks; Terra only
Plus$20/moSol, Terra, and Luna, with GPT-6 Astra as the rollout reaches your account; roughly 10–100 Sol-class messages per five-hour window — the practical “I use Codex regularly” tier
Pro$100/mo5× Plus limits, plus Sol Pro in ChatGPT
Pro (20×)$200/mo20× Plus limits; highest included usage
Business$20/user/mo (annual; $25 monthly)Plus-level limits per seat, then shared workspace credits + admin controls

A typical Sol task costs a few dozen credits if you’re on a credit-based plan, and Plus/Pro subscribers can buy top-up credits without changing plan. Treat the window like a project budget: start a long agentic run early in a fresh window, and watch the meter on the first run of a new task type. If you’re using API-key auth instead, standard API billing applies — check platform.openai.com/settings.

Your first interaction

Step 1: Create a project folder

Terminal window
mkdir hello-codex && cd hello-codex

Step 2: Start Codex CLI

Terminal window
codex

Step 3: Give it a task

Create a simple to-do list app in a single HTML file. It should:
- Let users type a task and press Enter to add it
- Show tasks in a list with checkboxes to mark as done
- Have a "Clear completed" button
- Dark theme, clean design
- Save tasks to localStorage so they persist on refresh

Codex will:

  1. Plan the implementation
  2. Create the file
  3. Write the code
  4. Verify it meets requirements

In the most cautious setting, Codex will ask for your approval before each step. Type y to approve or n to reject. Use /permissions to switch autonomy levels (see /help), or Ctrl+C to quit.

Step 4: Check the result

Terminal window
ls
cat index.html

Open in your browser to test the todo list functionality.

Codex CLI modes

Codex CLI controls autonomy through two independent policies — approval (when it asks permission) and sandbox (what it can access):

Approval Policy (-a)What it doesBest for
untrustedAsks before anything beyond a short list of safe read-only commandsLearning, careful work
on-requestMakes file changes automatically, asks before risky commandsGeneral use
never (full auto)Executes everything autonomouslyWhen you trust the task
Sandbox Policy (-s)What it allows
read-onlyCan read files but not write
workspace-writeCan write within your project directory
danger-full-accessUnrestricted file and network access

Combine them on the command line — codex -a on-request -s workspace-write is the everyday setting — or switch mid-session with /permissions, which offers named permission profiles (read-only, workspace, full access). The old --full-auto shortcut is now a deprecated compatibility flag on codex exec — it still runs but prints a warning; substitute --sandbox workspace-write instead. Names shift between releases, so prefer reading them from /help over memorizing.

Start with the most cautious profile while learning, then open up autonomy as you get comfortable. Full autonomy is best reserved for low-stakes prototypes where you can easily discard the results.

📊In Your Field: MIS / Businessclick to expand

Codex CLI’s autonomous execution model is particularly useful for MIS projects where you need to scaffold repetitive structures — like generating CRUD endpoints for a database, creating form validation logic, or building report templates. You can describe the business requirement (“Create an expense report form that calculates totals by category and exports to CSV”) and let Codex handle the implementation details. The read-only profile is ideal here because Codex stays consultative — it won’t change anything without your approval, so you can confirm each step matches your organization’s data standards.

🧬In Your Field: Biotechclick to expand

For bioinformatics workflows, Codex CLI’s sandboxed execution is a meaningful safety feature. When you ask it to “Write a Python script that processes all .fastq.gz files in a directory and generates quality reports,” it runs in an isolated environment — it won’t accidentally overwrite your precious sequencing data. Start in the read-only profile for any task that touches research data, and switch to workspace only for scaffolding new analysis scripts from scratch.

Tips

  1. Be specific about requirements. Codex excels when you give it a clear, well-defined task. The more specific your instructions, the better the result.

  2. Start with small tasks. Build confidence with simple, single-file tasks before trying multi-file projects.

  3. Use the sandbox. Codex runs in a sandboxed environment that reduces blast radius. It is not a substitute for review — read the diff before accepting changes, especially on important projects.

  4. Review before accepting. In the cautious permission profile, Codex shows you what it wants to do before doing it. Use this to learn what good code looks like.

Power features

Mid-session mode switching

You do not have to restart Codex to change permission profiles. Use the in-session /permissions command (see /help) to step up or down autonomy. This lets you start careful and open up autonomy as you gain confidence in the task.

Sandbox

By default, Codex CLI uses a restricted execution environment controlled by the sandbox policy. The workspace-write default limits changes to your project directory. Network and file permissions depend on your configuration and OS. The sandbox reduces blast radius, but it does not replace review — verify the behavior in your environment before relying on it for safety-critical work, and always read the diff before accepting changes.

ℹGPT-6 Astra, September 2026

Codex added GPT-6 Astra, OpenAI’s newest flagship, on 2026-09-03, and from CLI 0.153.4 it is the default whenever no model is configured. The rollout to accounts is gradual, so /model may still show Sol as your default for a while; check there rather than assuming. Free and Go stay on Terra. Sol, Terra, and Luna remain available, and nothing you learned about effort levels changes.

Reasoning effort and fast mode

/model sets both the model and how hard it thinks: low → medium → high → xhigh → max, plus ultra on Astra, Sol, and Terra, which adds automatic delegation to parallel subagents (and burns through your window faster — Codex warns you). Sol is strong even at low effort, so start low and raise it for hard problems. /fast trades extra usage for faster responses.

Session resume

Run codex resume to pick up a prior session where you left off — handy if you get interrupted or want to continue a multi-step task later. /new starts a fresh thread and lets you name it.

Headless runs

codex exec "your prompt" runs one task non-interactively and exits — the building block for scripts and CI. Add --json for machine-readable events or -o result.md to save the final message. You’ll use this in Module 19, where agents run headless in CI.

Verify it works

Paste this exact command to confirm everything is set up correctly:

Terminal window
codex --version

You should see a version number printed. If you get “command not found,” revisit the installation step above.

💡Your first real prompt

If the version check worked, try this — your first real interaction with Codex CLI:

Terminal window
codex exec "What is 2 + 2? Reply with just the number."

If you see a response, congratulations — you’re ready to use Codex CLI for real work starting in Module 9.

🔧

When Things Go Wrong

Use the Symptom → Evidence → Request pattern: describe what you see, paste the error, then ask for a fix.

Symptom
Codex CLI says 'invalid API key' after setting OPENAI_API_KEY
Evidence
Error: Incorrect API key provided: your-key-here. You can find your API key at https://platform.openai.com/account/api-keys
What to ask the AI
"Codex CLI is rejecting my OpenAI API key. I set it with export OPENAI_API_KEY and ran codex login --with-api-key, but it says 'incorrect API key.' How do I verify the key is correct and that my environment variable is actually set?"
Symptom
Browser sign-in doesn't open or can't reach the terminal
Evidence
Codex shows a localhost URL but nothing happens, or the browser can't connect back
What to ask the AI
"Codex CLI is trying to sign me in through a browser but I'm on WSL / a remote server and the callback never completes. Should I use codex login --device-auth instead? Walk me through the device-code flow."
Symptom
Codex CLI exits immediately or crashes on startup
Evidence
Segmentation fault or 'Error: Cannot find module' after npm install
What to ask the AI
"Codex CLI crashes when I try to run it. I installed it with npm install -g @openai/codex. Could this be a version compatibility issue? Should I try the installer script (curl -fsSL https://chatgpt.com/codex/install.sh | sh) or codex doctor?"
Symptom
Codex seems to be running but produces no output for a long time
Evidence
Terminal shows 'Thinking...' for several minutes with no progress
What to ask the AI
"Codex CLI has been showing 'Thinking...' for 5+ minutes. Is this normal for a first task at high or ultra reasoning effort, or is something stuck? How do I check /status for a network, limit, or API issue?"
💬Three tools down, one to go

You’ve now set up three AI CLI tools (Claude Code, Antigravity, and Codex CLI), with GitHub Copilot CLI in the next lesson. That’s not redundant — it’s strategic. Different tools excel at different tasks, and knowing when to reach for each one is a professional advantage that most people don’t have. The investment isn’t in any single tool. It’s in the orchestration skill that works across all of them.


Key Takeaways

  • Multiple install options — the installer script (curl -fsSL https://chatgpt.com/codex/install.sh | sh), npm install -g @openai/codex, or brew install --cask codex
  • Sign in with ChatGPT — any plan works, even Free; codex login --device-auth for SSH; API key still works for CI/scripting
  • Two policy axes — approval policy controls when Codex asks permission, sandbox policy controls what it can access (--full-auto is deprecated in favor of --sandbox workspace-write)
  • The sandbox reduces blast radius — Codex runs in isolation, but you still review the diff before accepting
  • Specificity wins — the more precise your task description, the better the result
  • Review is learning — the read-only profile shows you how an AI approaches a problem step by step
Search lessons