Codex CLI: Install on Windows 11, Mac, Kali Linux and WSL, Sign In With ChatGPT or an API Key, config.toml, codex exec, Ollama and Amazon Bedrock, and the 401 "Missing Bearer" Fix

Logeshwaran
—

Codex CLI is OpenAI's coding agent for the terminal: you type codex inside a project, describe what you want, and it reads the files, edits them and runs your build and tests, asking before it steps outside the folder. Installing it takes one command on macOS, Linux and Windows 11, and signing in takes one more. Here is the fact that trips up the most people on day one: the $0 Free plan and the $8 Go plan include Codex only inside the ChatGPT desktop app. The command-line tool, the editor extension and the web version need ChatGPT Plus ($20 a month), Pro, Business, Enterprise or Edu, or an OpenAI API key billed per token. One more date to know: GPT-5.5 left Codex for everyone signed in with ChatGPT on October 14, 2026, so a saved model = "gpt-5.5" now needs to become gpt-6.1-sol. This page walks you through the install on every operating system, the two sign-in methods, the config.toml keys that matter, the sandbox and approval settings, codex exec for scripts, running it against Ollama or Amazon Bedrock instead of OpenAI, and the exact error text you'll see when something is off.

Jake, who runs the phone repair shop, has an $8 ChatGPT Go plan and a shop PC on Windows 11. He has read that "Codex writes the code for you" and wants Ethan, his developer friend, to set it up so the shop's booking page can finally get the fixes Jake keeps asking for. Ethan works on a Kali Linux laptop and a Mac, and has the API key from an old project. Their afternoon covers every path on this page, including the one where Jake's plan turns out not to have the thing he bought it for.

⚡ Quick Answer

• Install (Mac, Linux, Kali, WSL): curl -fsSL https://chatgpt.com/codex/install.sh | sh, or npm install -g @openai/codex, or brew install --cask codex. Details.

• Install (Windows 11, native): powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex" in a new PowerShell window. Native vs WSL.

• Sign in: run codex and pick Sign in with ChatGPT (Plus or higher), or printenv OPENAI_API_KEY | codex login --with-api-key. Check with codex login status. Both paths.

• Scripts and CI: codex exec "task" prints only the final answer to stdout; add --json for events and --sandbox workspace-write to allow edits. The flags.

• Not OpenAI's servers: codex --oss --local-provider ollama for a local model, or model_provider = "amazon-bedrock-runtime" for GPT-6 on AWS. Bedrock setup.

Seeing 401 Unauthorized: Missing bearer or basic authentication in header? You are not signed in; codex doctor says the same thing in its first line. Every error, decoded.

🧭 NEW HERE? READ THESE FIRST

New to coding agents, or deciding which one to pay for? These five pages give you the context for this one:

📌 Bookmark this; the plan table, the config keys and the error table are the parts you'll come back for.

What Codex CLI is, and what it is not

OpenAI ships Codex in four shapes, and the names overlap enough to confuse anyone. The Codex CLI is the open-source terminal program (Apache-2.0, written in Rust, the openai/codex repository on GitHub) that runs on your own machine against your own files. The ChatGPT desktop app on macOS and Windows wraps the same engine in a window with parallel chats and a built-in browser; codex app launches it from the terminal. The IDE extension puts it inside VS Code, Cursor and Windsurf. And Codex Cloud, at chatgpt.com/codex, runs tasks in OpenAI-hosted containers while your laptop sleeps. This page is about the first one, with pointers to the others where they matter.

What the CLI does when you give it a task: it reads your repository, proposes and applies edits, runs commands (tests, builds, linters) inside an operating-system sandbox, and shows you the diff. By default it has no network access inside that sandbox, can write only inside the current workspace, and asks you before doing anything beyond that. You can loosen all three, and the sandbox section explains what each setting actually changes.

Ethan's first sentence to Jake: "It is a very fast junior developer who reads your whole project before touching it, and who has to ask permission to leave the folder." Jake: "Does it need the internet?" Ethan: "To talk to the model, yes. To run your code, no, unless you let it."

Which plan you need: the table that answers "why isn't it working on my account"

The CLI itself is free. What you pay for is the model behind it, and there are two ways to pay: a ChatGPT subscription (the "Sign in with ChatGPT" path, metered in messages and credits) or an OpenAI API key (metered per token at standard API prices). The table is the one Jake wished he had read before buying Go.

PlanPriceCodex CLI?What you get
Free$0NoGPT-6 Luna at Standard speed in the ChatGPT desktop app only, as the rollout reaches you
Go$8/monthNoSame as Free: Luna in the desktop app, for lightweight tasks
Plus$20/monthYesCodex on the web, in the CLI, in the IDE extension and on iOS; GPT-6.1 Sol and GPT-6 Luna; cloud features such as automatic code review and Slack; top up with credits
Pro$100, $200 or $500/monthYesEverything in Plus with higher limits and no five-hour window; Ultrafast mode on the $500 tier
Business$20/seat/monthYesPlus-level access in a managed workspace with SSO and MFA, larger cloud VMs, no training on your data by default
Enterprise and EduContractYesBusiness plus SCIM, audit logs, data residency, admin-enforced configuration; GPT-6.1 Sol is off until an admin turns it on
API keyPer tokenYesCLI, SDK and IDE extension only; no cloud features (GitHub review, Slack); the models your key can call; billed at API prices

Two things the table hides. First, with a ChatGPT sign-in the CLI, the desktop app and the web share one usage allowance, measured in five-hour windows on Plus and Business, with weekly limits on top. Second, the model you pick changes how far that allowance stretches by a factor of roughly fifty. These are the published estimates of local messages per five-hour window on Plus and Standard Business:

ModelMessages per 5 hours (estimate)Credits per 1M input / cached / output tokens
GPT-6 Astra5 to 45250 / 25 / 1,250
GPT-6.1 Sol (default)15 to 16050 / 2.5 / 250
GPT-6 Sol15 to 15050 / 5 / 250
GPT-6 Luna350 to 3,0002.5 / 0.25 / 12.5

The ranges are wide because a message that touches ten files costs more than one that touches one. Fast mode burns included usage at 2.5 times the Standard rate (2 times when paid with credits); Ultrafast, on Pro $500 and eligible Enterprise plans, at 8 times (6 times on credits). You can see where you stand at any moment with /status inside a session, and /usage shows account totals. When you hit the wall, Plus and Pro users can buy credits rather than upgrade.

On the API-key path there are no windows at all, just the per-token bill. For GPT-6.1 Sol that is $2 per million input tokens, $0.10 per million cached input tokens and $10 per million output tokens, with the model's thinking counted as output; our GPT-6.1 Sol guide has the full price sheet and what a typical session costs. A long agent session is many requests over a large, mostly cached context, which is why the cached-input price matters more than the headline one.

Jake's face when Ethan reads the first table out loud: "So Go gets me the app and nothing else?" Ethan: "The app on this PC, yes. The terminal, no. For the terminal you either move to Plus or let me put my API key on it and pay per use. For a shop website that gets touched twice a month, the key will cost less than the upgrade." Jake chose the key, which turns out to be the more interesting setup to document.

Install on macOS, Ubuntu, Debian and Kali Linux

There are four ways in, and they all produce the same codex binary. The standalone installer is the one OpenAI leads with; it downloads a release from releases.openai.com (falling back to GitHub Releases), puts the executable in ~/.local/bin, and keeps the package cache under ~/.codex/packages/standalone. Running the same line again later updates it.

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

If codex --version says the command is not found afterwards, ~/.local/bin is not on your PATH yet; open a new shell, or add export PATH="$HOME/.local/bin:$PATH" to ~/.bashrc or ~/.zshrc. Two installer knobs: CODEX_INSTALL_DIR moves the binary somewhere else, and CODEX_NON_INTERACTIVE=1 skips the installer's prompts for scripted installs. If your network blocks releases.openai.com, CODEX_INSTALLER_USE_RELEASES_OPENAI_COM=false forces the GitHub download.

The npm route is what most existing tutorials show, and it still works: with Node.js 18 or newer installed,

npm install -g @openai/codex
codex --version
# later
codex update        # or: npm install -g @openai/codex

On a Debian 12 host with Node 22, that gives codex-cli 0.162.1 as of October 15, 2026, and the npm package pulls a platform-specific binary (@openai/codex-linux-x64 and friends) rather than JavaScript. If the global install fails with a permissions error, that is the usual npm global-prefix problem, and the standalone installer sidesteps it entirely because it writes to your home directory. codex update ran the npm update in place and asked for a restart; it is the same thing as re-running the install line.

On a Mac, Homebrew has it as a cask:

brew install --cask codex
brew upgrade --cask codex

And for air-gapped or pinned setups, each GitHub Release carries one archive per platform: codex-x86_64-unknown-linux-musl.tar.gz and codex-aarch64-unknown-linux-musl.tar.gz for Linux, codex-aarch64-apple-darwin.tar.gz for Apple Silicon and codex-x86_64-apple-darwin.tar.gz for Intel Macs. The archive holds a single file named after the platform; rename it to codex, chmod +x it, and drop it on your PATH. The musl build is static, which is why the same Linux file works on Ubuntu, Debian, Fedora and Kali without caring about your libc.

Kali specifically: Kali is Debian-based, so the standalone installer and the npm route both apply unchanged. Kali's packaged Node is recent enough for npm, and the sandbox the CLI uses on Linux is bubblewrap, which the Rust binary brings along (that is also why WSL1 stopped being supported at Codex 0.115). The one Kali habit to change is running everything as root: Codex is happiest as a normal user with a home directory, because ~/.codex is where it keeps config, credentials and session transcripts.

System floor on every platform: macOS 12 or newer, Ubuntu 20.04 or Debian 10 or newer, 4 GB of RAM with 8 GB recommended, and Git 2.23 or newer if you want the built-in pull-request helpers. Git is optional for the install but close to mandatory for use, because codex exec refuses to run outside a Git repository unless you tell it to.

Ethan on the Kali laptop: install line, new shell, codex --version, done in under a minute. Jake: "That was it?" Ethan: "That was the easy half. The sign-in is where plans and keys come in."

Install on Windows 11: native PowerShell or WSL2

This changed in 2026. Older guides tell you Windows needs WSL2, and that was true for a long time; today Codex runs natively in PowerShell with a Windows sandbox, and WSL2 is the alternative for people whose tooling already lives in Linux. Pick native if your repositories live on C: and you build with Windows tools; pick WSL2 if you live in a Linux shell anyway.

Native install, in four steps:

  1. Open a new PowerShell window; the installer updates PATH for new sessions only.
  2. Run the installer line below and let it finish.
  3. Close that window, open another new one, and run codex --version.
  4. Run codex inside a project folder and sign in.

The installer line:

powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex"
codex --version

The binary lands in %LOCALAPPDATA%\Programs\OpenAI\Codex\bin. npm install -g @openai/codex works on Windows too if you have Node. Windows 11 is the recommended baseline; a fully updated Windows 10 is best effort and needs version 1809 or newer for the modern console (ConPTY); older Windows 10 builds are not recommended. winget should be present, which it is on any current Windows 11.

The Windows sandbox has three implementations, and which one you get depends on your Windows build:

  • mxc: the recommended one. It uses Microsoft's native process isolation (Microsoft Execution Containers), needs no administrator setup, no extra Windows accounts and no firewall rules. It requires Windows 11 24H2 build 26100.9278 or 25H2 build 26200.9278 or newer. Turn it on with [features] prefer_mxc = true in config.toml, and test it for one command without changing anything saved: codex -c windows.sandbox=mxc sandbox --include-managed-config --permission-profile :workspace -- cmd.exe /d /c echo MXC_OK should print MXC_OK with exit code 0.
  • elevated: the legacy fallback. It needs a one-time administrator-approved setup (/setup-default-sandbox inside a session, or IT runs codex sandbox setup --elevated --user 'DOMAIN\name' --codex-home 'C:\Users\name\.codex'), after which commands run as dedicated lower-privilege users behind firewall rules.
  • unelevated: the weaker fallback for machines where elevated setup is blocked: a restricted token derived from your own user, ACL-based file boundaries, and weaker network isolation.

Set the fallback with [windows] sandbox = "elevated". If you see sandbox errors on a managed corporate laptop, the usual causes are a policy that blocks the elevated setup or a Windows build older than the MXC floor; /status and /debug-config inside a session show which implementation and permission profile are active.

WSL2 install. From an elevated PowerShell, wsl --install (Ubuntu by default), then wsl to enter it, then the same Linux line as above:

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

Two WSL rules that save you an afternoon. Keep repositories under the Linux home (~/code/my-app), not under /mnt/c/...: the Windows-mounted path is markedly slower and brings symlink and permission oddities. And if a large repository still feels slow, wsl --update then wsl --shutdown from PowerShell and give WSL more memory. VS Code opens a WSL window with code . from inside the distro, and the extension then finds the Linux codex on PATH.

Jake's shop PC is a 24H2 machine, so Ethan went native: PowerShell line, new window, codex --version, [features] prefer_mxc = true in the config, and the MXC test printed MXC_OK. Jake: "No Linux at all?" Ethan: "Not on this one. On mine, yes, because that is where my tools are. Same program, same config file format, different sandbox underneath."

Sign in: ChatGPT account or API key

Run codex in any folder and the first screen offers Sign in with ChatGPT. It opens your browser, you sign in, and the browser hands the credentials back to the CLI through a tiny local server on localhost:1455. From then on the CLI refreshes its own tokens; you will rarely see that screen again. codex login does the same thing on demand.

The API-key path reads the key from standard input, so it stays out of your shell history:

export OPENAI_API_KEY=sk-...
printenv OPENAI_API_KEY | codex login --with-api-key
codex login status

codex login status prints Logged in using an API key - sk-test-***valid or Not logged in, and exits 0 only when credentials exist, which makes it a clean check in scripts. codex logout removes both kinds of credential. Keys signed in this way bill at API rates, get the models your key can call, and lose the cloud-side features (GitHub code review, Slack, Codex Cloud), which is the trade Ethan made for Jake.

Where the credential lives: a plaintext ~/.codex/auth.json by default (the lab's file after the key login was a two-line JSON with "auth_mode": "apikey" and the key itself), or your operating system's credential store if you set it:

# ~/.codex/config.toml
cli_auth_credentials_store = "keyring"   # file | keyring | auto | ephemeral

file is the JSON; keyring is the OS store and fails if there is none; auto tries the store and falls back to the file; ephemeral keeps the credential in memory for one process only. The CLI and the IDE extension share the cache, so logging out of one logs out the other. Treat auth.json like a password: it holds access tokens, and it has no business in a repository or a support ticket.

Headless machines (a server, a container, a VM without a browser) have three options, in order of preference:

  1. Device-code login. Turn it on in your ChatGPT security settings (or workspace permissions), then codex login --device-auth, open the printed link on any device and type the one-time code.
  2. Copy the cache. Log in on a machine with a browser, then ssh user@remote 'mkdir -p ~/.codex && cat > ~/.codex/auth.json' < ~/.codex/auth.json, or docker cp ~/.codex/auth.json CONTAINER:/root/.codex/auth.json into a container.
  3. Forward the callback port. ssh -L 1455:localhost:1455 user@remote, then run codex login inside that session and open the printed address on your laptop.

Behind a corporate TLS proxy, point CODEX_CA_CERTIFICATE at your PEM bundle before logging in; it covers login, HTTPS and the WebSocket connection, and falls back to SSL_CERT_FILE when unset. Login problems write their own codex-login.log under your log directory.

For scripts and CI there is a third credential type: CODEX_API_KEY set inline on the one command that needs it (CODEX_API_KEY=... codex exec "..."), which the exec section covers, and for Enterprise workspaces a Codex access token piped to codex login --with-access-token.

Ethan, on Jake's PC: printenv is a Unix command, so in PowerShell the equivalent was $env:OPENAI_API_KEY | codex login --with-api-key. codex login status answered with the masked key. Jake: "Can anyone who sits at this PC spend your money now?" Ethan: "Anyone who can read that JSON file, yes. Which is why it's going in the keyring, and why the key gets a spending limit on the OpenAI side tonight."

Your first session: the commands you'll actually use

Go into a Git repository and type codex. Ask for something small and specific the first time ("explain how this project builds and where the tests are"), then something that changes a file. A few habits make the difference between a tool you trust and one you fight:

  • Commit before and after. A Git checkpoint on each side of a task means git diff shows you exactly what the agent did and git checkout . undoes it. The CLI's own /diff shows the working-tree changes, including files Git isn't tracking yet.
  • Give it a brief. /init writes an AGENTS.md scaffold in the folder; fill it with the build command, the test command, the style rules and the hands-off list, and every future session starts with that context. Keep it short: a long AGENTS.md costs tokens on every message.
  • Point at files with @. Typing @ searches the workspace and inserts the path; /mention attaches a file. codex --image shot.png "fix this" attaches a screenshot to the first prompt, and you can paste images into the composer.
  • Run shell commands with !. A line starting with ! runs in your terminal under the same sandbox and approval settings, so you can check the test output yourself without leaving the session.
  • Queue and steer. Press Tab while it is working to queue the next prompt; press Enter to inject an instruction into the current turn; press Escape twice on an empty composer to edit your previous message and fork the chat from there. Ctrl+C or /exit leaves.

The slash commands you'll use in week one:

CommandWhat it does
/modelSwitch model and reasoning effort mid-session (or start with codex -m gpt-6-luna)
/permissionsChange what Codex may do without asking: Read Only, Auto (workspace-write), or full access
/statusSession config, model provider, token usage and your remaining plan limits
/usageAccount-level token usage and rate-limit reset
/reviewHave Codex review the working tree without editing it
/diffShow the Git diff including untracked files
/compactSummarize the chat so far to free context
/planPlan mode: think and propose before touching anything
/initCreate an AGENTS.md scaffold
/mcp, /skills, /pluginsList configured MCP tools, browse skills, browse plugins
/resume, /fork, /newReopen a saved chat, branch the current one, start fresh in the same window
/worktreeContinue in a managed Git worktree so experiments stay off your branch
/fastToggle the Fast service tier where the model offers one
/importBring over settings, projects and chats from Cursor or Claude Code
/export, /recapSave the conversation as Markdown; summarize it
/debug-configPrint which config layer set each value, with managed requirements
/logout, /exitSign out; leave

From the shell, codex resume opens a picker of saved sessions for the current folder (--last for the most recent, --all across folders); codex fork branches one; codex review --uncommitted reviews what you have not committed, --base main reviews a branch against main, --commit SHA reviews one commit. Sessions live under ~/.codex/sessions, and codex archive and codex delete clean them up by ID or name.

Jake watched Ethan type "make the booking form reject phone numbers shorter than ten digits, and add a test." Codex read the project, proposed an edit, ran the tests, and asked once because the test command wanted the network. Jake: "Why did it ask?" Ethan: "Because the sandbox blocks the network and that test tried to reach something. That is the single most useful question it asks."

config.toml: the keys that matter and where they live

Everything the CLI remembers is in ~/.codex/config.toml (TOML, not JSON). A project can add its own .codex/config.toml, loaded only once you have marked the project trusted. Named profiles live in ~/.codex/<name>.config.toml and apply with -p name. The precedence, highest first: command-line flags and -c key=value overrides; project .codex/config.toml files from the project root down to your working directory, closest wins; the profile; your user config; cloud-managed defaults for your workspace; /etc/codex/config.toml; built-in defaults. /debug-config tells you which layer won for any key.

A working starting file for an individual developer:

# ~/.codex/config.toml
model = "gpt-6.1-sol"                 # or gpt-6-luna for cheap, repetitive work
model_reasoning_effort = "medium"     # light | medium | high | ... as the model supports
approval_policy = "on-request"        # or "never" for unattended runs
sandbox_mode = "workspace-write"      # read-only | workspace-write | danger-full-access
web_search = "cached"                 # cached (default) | indexed | live | disabled
personality = "none"                  # drop the built-in chatty persona
cli_auth_credentials_store = "auto"

[sandbox_workspace_write]
network_access = false                # true lets commands reach the network
# writable_roots = ["/home/you/.cache"]

[features]
memories = false

Notes on the keys you will touch most. model accepts the IDs from the model picker: gpt-6.1-sol (the default on a fresh install), gpt-6-luna, gpt-6-astra, gpt-6-sol; anything with gpt-5.5 in it is gone for ChatGPT sign-ins since October 14, though API keys can still call it. web_search defaults to cached, which answers from an OpenAI-maintained index rather than fetching live pages; live is the same as the --search flag. personality = "none" removes the Personality section from the built-in instructions; the older friendly and pragmatic values and the /personality command are gone.

One-off overrides take any key with dotted paths and TOML values: codex -c model="gpt-6-luna" -c 'sandbox_workspace_write.network_access=true'. Feature flags toggle with codex --enable name or [features] name = true; codex features list prints every flag with its stage (stable, experimental, under development) and current value. --strict-config makes the CLI refuse to start if the file has a key this version does not know, which is how you catch typos.

Two environment variables sit above the file: CODEX_HOME moves the whole state directory (config, auth, logs, sessions, skills) somewhere other than ~/.codex, and the directory must already exist; RUST_LOG sets log verbosity. RUST_LOG=debug codex -c log_dir=./.codex-log writes a plaintext codex-tui.log you can tail -F, which is otherwise off.

Jake asked why there was a file at all when the app "just remembers." Ethan: "The app writes this same file. Which means I can copy it to your PC, change one line for the sandbox, and you have my setup." He did, with model = "gpt-6-luna" for Jake's small edits, which stretches the API dollars about twenty-fold on input.

Sandbox and approvals: what each setting really changes

Two settings, two layers. Sandbox mode is what the agent's commands can technically do, enforced by the operating system: bubblewrap on Linux, Seatbelt on macOS, MXC or the legacy sandboxes on Windows. Approval policy is when the agent stops to ask you. They combine like this:

SettingValuesMeaning
sandbox_mode / --sandboxread-onlyCommands can read the workspace and nothing else; no writes, no network. The codex exec default.
workspace-writeWrites inside the current folder (plus --add-dir extras); .git, .agents, .codex and .aws inside writable roots stay protected; network off unless network_access = true.
danger-full-accessNo sandbox. Only inside a throwaway VM or container.
approval_policy / -aon-requestThe model asks when it wants to step outside the sandbox (write elsewhere, use the network). The interactive default.
neverAsks nothing; a blocked action fails and the failure goes back to the model, which tries another way.
{ granular = {...} }Allow or auto-reject individual prompt categories (sandbox escapes, rules, MCP elicitations, permission requests, skill approvals).
approvals_revieweruser / auto_reviewRoute approval prompts to you, or to automatic review (--approve-for-me on the command line).

The everyday combination is --sandbox workspace-write --ask-for-approval on-request, which is what the /permissions command calls Auto: it edits and runs inside the folder on its own and asks for anything beyond. Read Only is the mode for planning and code reading. Two settings have been retired this year: approval_policy = "untrusted", which now stops the CLI from starting at all if it is still in a config file, and the --full-auto flag, replaced by --sandbox workspace-write or --approve-for-me. If you want the old "ask before every command" behavior back, leave approval_policy unset and add the project under [projects."/path"] trust_level = "untrusted", which also stops the project's own .codex layer from loading.

Network inside the sandbox is a separate switch, [sandbox_workspace_write] network_access = true, and once it is on you can narrow it with the proxy feature: [features.network_proxy] enabled = true plus a domains table of allow and deny rules ("*.example.com" matches subdomains, "**.example.com" the apex too, deny beats allow, local and private addresses blocked unless you allow them by name). Adding domain rules without enabling the proxy changes nothing; enabling the proxy without turning the network on also changes nothing. That ordering catches people.

You can run any command under the agent's sandbox yourself to see what it would be allowed: codex sandbox -- echo SANDBOX_OK prints the line on a working Linux setup, and the Windows equivalent with the MXC profile is in the Windows section. One more behavior worth knowing before it surprises you: GPT-6 Astra tasks carry asynchronous safety monitoring that can pause a task it judges unsafe; in the CLI there is no findings-and-resume screen, so the task simply ends and you start a new one.

Jake: "So if I set never, it can't ask me and it can't leave the folder?" Ethan: "Right. It will fail quietly at the fence and try a different route. That is what I use when I run it from a script at three in the morning. For you, sitting at the keyboard, on-request is better: you get one question instead of a silent workaround."

codex exec: scripts, pipelines and CI

codex exec "task" (short form codex e) runs a task without the interface and exits. The design is pipe-friendly: progress streams to stderr, and only the final message goes to stdout, so codex exec "write release notes for the last 10 commits" | tee notes.md gives you a clean file. Everything above a prompt that reaches the model prints a header first, which is also a quick way to see your effective settings:

OpenAI Codex v0.162.1
--------
workdir: /home/you/project
model: gpt-6.1-sol
provider: openai
approval: never
sandbox: read-only
reasoning effort: none
reasoning summaries: none
session id: 01a14113-...
--------

Read that header once and three defaults jump out: exec asks nothing (approval never), exec cannot write (sandbox read-only), and reasoning effort is none unless you set model_reasoning_effort or -c model_reasoning_effort=medium. So a task that should change files needs --sandbox workspace-write, and one that should think needs the effort flag.

The flags that matter, from the --help output of 0.162.1:

  • --json: stdout becomes newline-delimited JSON events (thread.started, turn.started, item.started/item.completed for commands, file changes, MCP calls and messages, turn.completed with token usage, error).
  • -o FILE / --output-last-message FILE: also write the final message to a file; pair it with --json in CI so the log has events and the artifact has the answer.
  • --output-schema schema.json: force the final answer to match a JSON Schema, for job summaries and risk reports that downstream steps parse.
  • --ephemeral: write no session files to disk.
  • --skip-git-repo-check: run outside a Git repository. Without it, in a plain folder you get exactly Not inside a trusted directory and --skip-git-repo-check was not specified. and nothing runs.
  • -C DIR, --add-dir DIR, --worktree: set the working root, add writable folders, or run the task in a fresh managed Git worktree (no mixing --worktree with resume, review or --ephemeral).
  • --ignore-user-config, --ignore-rules: run without your config.toml or without execpolicy rule files, for reproducible automation.
  • -i FILE: attach images; -m MODEL, -p PROFILE, --oss, --local-provider: as in the interactive command.

Stdin works two ways. With a prompt argument, piped input becomes context: npm test 2>&1 | codex exec "summarize the failing tests and propose the smallest fix". With - as the prompt, stdin is the prompt: cat prompt.txt | codex exec -. Two-stage pipelines use codex exec resume --last "now fix what you found" (or a session ID), and codex exec fork SESSION "try another approach" copies a session before continuing it. An MCP server configured with required = true that fails to start makes exec exit with an error rather than carry on without it.

Credentials in automation: set CODEX_API_KEY inline on the Codex command only (CODEX_API_KEY=... codex exec --json "triage open bugs"), not as a job-wide variable in a workflow that also runs the repository's own build scripts, because any of those scripts could read it. On GitHub Actions, openai/codex-action exists for exactly this: it installs the CLI, starts a proxy that holds the key, and runs Codex with the key out of the job environment; the pattern that follows is "Codex job with read-only contents saves a patch artifact, a separate job with write permission opens the pull request."

Ethan's nightly script for Jake's site, in full: cd ~/code/shop && CODEX_API_KEY="$(cat ~/.keys/codex)" codex exec --sandbox workspace-write -m gpt-6-luna --json -o /tmp/last.md "run npm test; if anything fails, make the smallest fix and run it again" > /tmp/events.jsonl. Jake: "And if it breaks something?" Ethan: "It cannot commit. In the morning I read git diff, and either I commit or I throw it away."

Run it against Ollama or LM Studio instead of OpenAI

The CLI has a built-in "OSS mode" that swaps the model provider for a local server. Start Ollama or LM Studio, pull a model, and run:

codex --oss --local-provider ollama
codex --oss --local-provider lmstudio
# make one the default so plain --oss works:
#   oss_provider = "ollama"      in config.toml

In the interactive CLI, --oss with no provider set prompts you to pick one; codex exec --oss with none set exits with an error. If the server is not running you get the message in full: Error: OSS setup failed: No running Ollama server detected. Start it with: `ollama serve` (after installing). Our "could not connect to Ollama" guide covers the port, host-binding and firewall cases behind that line, and the LM Studio load-failure guide the other side.

Any OpenAI-compatible server works through a custom provider block. The IDs openai, ollama and lmstudio are reserved for the built-ins, so name yours something else:

model = "qwen3.8:32b"
model_provider = "local_ollama"

[model_providers.local_ollama]
name = "Ollama"
base_url = "http://localhost:11434/v1"
# no env_key and no requires_openai_auth = no authentication

[model_providers.mistral]
name = "Mistral"
base_url = "https://api.mistral.ai/v1"
env_key = "MISTRAL_API_KEY"

A provider with env_key reads that variable for its key; one with requires_openai_auth = true uses your ChatGPT or OpenAI sign-in (the proxy case, where env_key is ignored); one with neither sends no credentials, which is what a local model wants. To redirect only the built-in OpenAI provider through a proxy, set openai_base_url rather than defining a [model_providers.openai] table, which is refused. model_verbosity and the reasoning settings apply only to providers that speak the Responses API; Chat Completions servers ignore them, and current Codex releases no longer accept wire_api = "chat" as a provider's only route, so a server that offers nothing but /v1/chat/completions is a poor fit.

Expectation-setting: the agent loop was tuned on GPT-6 models with reasoning, tool calls and long contexts. A 7B local model will run the loop and produce edits, but will mis-call tools and lose the thread on large repositories far more often. The honest local sweet spot is a 30B-class coding model on a machine with 24 GB or more of GPU memory, and our runner comparison helps you pick the server side.

Run it against GPT-6 on Amazon Bedrock

If your company's bill and audit trail live in AWS, Codex can send its model requests to Amazon Bedrock instead of OpenAI, signed with AWS credentials. There are two built-in providers, one for each of the two Bedrock endpoints, and they take different model IDs:

# Bedrock Runtime: Global or US Geo cross-Region inference
model_provider = "amazon-bedrock-runtime"
model = "global.openai.gpt-6-sol"      # or us.openai.gpt-6-sol, global.openai.gpt-6-astra, global.openai.gpt-6-luna ...

# or Bedrock Mantle: in-Region inference
# model_provider = "amazon-bedrock"
# model = "openai.gpt-6-sol"           # openai.gpt-6-astra | openai.gpt-6-luna

[model_providers.amazon-bedrock.aws]
profile = "codex-bedrock"              # optional; omit to use the default AWS credential chain
region = "us-east-1"

Then the AWS side: aws sso login --profile codex-bedrock (or any credential the AWS chain accepts, including a credential_process helper), export AWS_REGION=us-east-1 or AWS_PROFILE in your shell (the desktop app and the extension read ~/.codex/.env instead, %USERPROFILE%\.codex\.env on Windows), and permission to invoke the model or inference profile; GPT-6 Sol through Runtime additionally needs bedrock:InvokeModel on the account's default project. The Runtime endpoint is https://bedrock-runtime.{region}.amazonaws.com/openai/v1 and Mantle's is https://bedrock-mantle.{region}.api.aws/openai/v1; GPT-6 Sol and Luna are on Mantle in us-east-1. Start a session, run /status, and check that the provider reads amazon-bedrock-runtime or amazon-bedrock before you trust a reply.

What you lose on this route: hosted ChatGPT Work on the web, Codex Cloud and anything that depends on OpenAI's cloud services; Fast mode (Bedrock's offering is on-demand inference only); hosted web search on Runtime (Mantle has it). And as of mid-October the supported list is GPT-6 Astra, Sol and Luna; GPT-6.1 Sol is on Bedrock as a model but is not yet in Codex's Bedrock picker, which our GPT-6.1 Sol guide tracks. Model availability also varies by Region, and the Bedrock model-ID list is kept current daily. The IAM shape is the same one our other coding-agent-on-Bedrock guide walks through, which helps if your team runs both.

Jake: "Why would anyone pay Amazon to talk to OpenAI?" Ethan: "Because their security team already approved Amazon. For you, the key is fine. For the hospital I contract for, the only door is the one with the AWS audit log on it."

Every error you'll meet in the first week, decoded

What you seeWhat it meansFix
codex: command not found right after the installer~/.local/bin (or the Windows bin folder) is not on PATH in this shellOpen a new terminal; on Linux add the directory to PATH in your shell rc file
401 Unauthorized: Missing bearer or basic authentication in header, preceded by Reconnecting... 1/5 to 5/5No credential at all; the CLI tried the WebSocket transport, fell back to HTTPS, and was refused five timescodex login, or pipe a key to codex login --with-api-key; confirm with codex login status
401 Unauthorized: Incorrect API key provided ... auth error code: invalid_api_keyA key is stored, and OpenAI rejects it (revoked, mistyped, or from another organization)Make a new key at platform.openai.com, codex logout, log in again
codex doctor prints ✗ auth no Codex credentials were foundSame as above, surfaced by the diagnostic; doctor exits 1 whenever a check failsLog in; re-run doctor to see the rest of the report
⚠ websocket Responses WebSocket failed; HTTPS fallback may still workSomething between you and api.openai.com drops WebSockets: proxy, VPN, firewall, DNS, custom CASet CODEX_CA_CERTIFICATE for a corporate CA; otherwise the HTTPS fallback runs, slower
Not inside a trusted directory and --skip-git-repo-check was not specified.codex exec in a folder that is not a Git repositorygit init, or add --skip-git-repo-check when the folder is safe
Error: OSS setup failed: No running Ollama server detected.--oss with no local server listeningollama serve (or open LM Studio's server), then retry
The CLI refuses to start after an upgradeA retired key such as approval_policy = "untrusted" in a config layerRemove it; use sandbox_mode = "read-only" + on-request, or the project trust_level entry
--full-auto is rejectedThe flag was removed--sandbox workspace-write, or --approve-for-me
The model you saved is "not available"gpt-5.5 retired for ChatGPT sign-ins on October 14, 2026; Free and Go cannot pick Solgpt-6.1-sol on Plus and up, gpt-6-luna otherwise; API keys still see what the key can call
A test or install command fails only inside CodexSandbox network is off, or the path is outside writable rootsApprove the prompt, or set network_access = true / --add-dir; codex sandbox -- cmd reproduces it
Everything is slow on WindowsRepository under /mnt/c inside WSLMove it under ~/code, or use the native Windows install
Usage limit reached mid-taskFive-hour or weekly window on Plus/BusinessThe current turn may finish; /status shows the reset; buy credits or switch to gpt-6-luna
codex exec exits with an MCP errorA server marked required = true failed to initializeFix or unmark the server; exec refuses to continue without a required server

Three of those are worth a sentence more. The 401 with no credentials is the full sequence on a fresh install when you run codex exec before logging in: a warning about falling back from WebSockets to HTTPS, five Reconnecting lines, then the 401 with a request ID. It looks like a network problem and is not; the first line of codex doctor tells you which. The doctor command is the right first move for any "it worked yesterday" report: it checks install consistency, config, auth, runtime, Git, terminal and the app server, and prints the install method and the exact binary path, which matters when an npm install and a standalone install both exist on one machine. And the trusted directory message is not about trust in the security sense; it is the Git check, and it goes away with a repository.

Codex CLI next to the app, the cloud and the other terminal agents

Use the CLI when you live in a terminal, when you want codex exec in scripts, or when you need a local review before a commit. Use the desktop app when you want parallel chats, worktrees, a browser the agent can drive and file previews; it is also the only place the Free and Go plans get Codex at all. Use Codex Cloud (codex cloud submits a task from the terminal and codex apply pulls its diff back) when the work should keep going after your laptop closes. The IDE extension is the CLI with your open files already in context.

Against the other terminal agents the differences are mostly commercial. OpenCode is open source, model-agnostic and happy with any provider from day one; our OpenCode guide covers it, and the Kimi Code CLI comes with its own cheaper models. Codex's edge is the GPT-6 family with a ChatGPT subscription you may already pay for, the sandbox work on Windows, and the Bedrock route for AWS shops. If you also use AWS from the agent, the Agent Toolkit for AWS adds the AWS tools as an MCP server that codex mcp add registers in one line.

Frequently asked questions about Codex CLI

How do I install Codex CLI?

On macOS or Linux: curl -fsSL https://chatgpt.com/codex/install.sh | sh. On Windows, in a new PowerShell window: powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex". npm install -g @openai/codex and brew install --cask codex also work. Then run codex and sign in.

Is Codex CLI free?

The program is free and open source (Apache-2.0). The model behind it needs a ChatGPT Plus, Pro, Business, Enterprise or Edu plan, or an OpenAI API key billed per token. Free and Go plans get Codex only in the desktop app.

Does Codex CLI work with ChatGPT Free or Go?

No. Free and Go include GPT-6 Luna in the ChatGPT desktop app only. The CLI, the IDE extension, the web version and iOS need Plus ($20 a month) or higher, or an API key.

How do I sign in to Codex CLI with an API key?

export OPENAI_API_KEY=sk-..., then printenv OPENAI_API_KEY | codex login --with-api-key (in PowerShell: $env:OPENAI_API_KEY | codex login --with-api-key). codex login status confirms it. API-key sessions bill at API prices and lose the cloud features.

Where does Codex store my login?

In ~/.codex/auth.json as plaintext by default, or in the OS credential store when cli_auth_credentials_store = "keyring" (or "auto") is set in config.toml. The CLI and the IDE extension share it.

Does Codex CLI run natively on Windows 11?

Yes. The PowerShell installer gives a native binary with a Windows sandbox: MXC on Windows 11 24H2 build 26100.9278 or 25H2 build 26200.9278 and newer (prefer_mxc = true), or the legacy elevated and unelevated sandboxes on older builds. WSL2 remains an option for Linux-first workflows.

Does Codex CLI work in WSL?

In WSL2, yes: wsl --install, then the Linux installer inside the distro. WSL1 stopped being supported at Codex 0.115 because the Linux sandbox moved to bubblewrap. Keep repositories under the Linux home, not /mnt/c.

Does Codex CLI run on Kali Linux?

Yes. Kali is Debian-based, so the standalone installer, npm and the static musl binary from GitHub Releases all work. Run it as a normal user with a home directory, since ~/.codex holds config, credentials and sessions.

What is the default model in Codex CLI?

gpt-6.1-sol on a fresh install, as the session header shows. Change it with -m, with /model inside a session, or with model = "..." in config.toml. gpt-6-luna is the cheap choice for small repetitive edits.

Why does Codex say gpt-5.5 is unavailable?

GPT-5.5 retired from Codex for ChatGPT sign-ins on October 14, 2026, at 19:00 UTC. Replace it with gpt-6.1-sol (Plus and up) or gpt-6-luna. API-key sessions are not affected.

What does "401 Unauthorized: Missing bearer or basic authentication in header" mean?

No credential is stored. The CLI tries WebSockets, falls back to HTTPS, retries five times and then prints the 401. Run codex login or pipe a key to codex login --with-api-key, then codex login status.

What does "Not inside a trusted directory and --skip-git-repo-check was not specified" mean?

codex exec was run in a folder that is not a Git repository. Run git init, or add --skip-git-repo-check when the folder is safe to work in.

How do I run Codex without it asking for approval?

codex --sandbox workspace-write --ask-for-approval never, or the same keys in config.toml. Blocked actions then fail back to the model instead of prompting. --full-auto was removed; --approve-for-me routes approvals through automatic review instead.

How do I use Codex CLI in a script or CI pipeline?

codex exec "task" prints only the final message to stdout; add --json for an event stream, -o file for the final message, --output-schema for structured JSON, and --sandbox workspace-write to allow edits. Set CODEX_API_KEY inline on that one command, or use openai/codex-action on GitHub Actions.

Can Codex CLI use a local model with Ollama?

Yes: codex --oss --local-provider ollama (or lmstudio), with oss_provider in config.toml as the default. Any OpenAI-compatible server works through a [model_providers.name] block with base_url and no env_key.

Can Codex CLI use Amazon Bedrock?

Yes. Set model_provider = "amazon-bedrock-runtime" with an inference profile such as global.openai.gpt-6-sol, or model_provider = "amazon-bedrock" with openai.gpt-6-sol for Mantle, plus AWS credentials and a Region. Supported models are GPT-6 Astra, Sol and Luna; Fast mode and the cloud features are not available on this route.

Where is the Codex config file?

~/.codex/config.toml for your defaults, .codex/config.toml inside a trusted project for overrides, ~/.codex/NAME.config.toml for profiles used with -p NAME. /debug-config shows which layer set each value.

How do I check my remaining Codex usage?

/status inside a session shows the session configuration and your plan limits; /usage shows account totals and the reset. Plus and Business meter in five-hour windows with weekly caps; Pro has no five-hour window.

How do I update Codex CLI?

codex update, or re-run the installer line you used (the curl or PowerShell command, npm install -g @openai/codex, or brew upgrade --cask codex). Restart Codex afterwards.

By the end of the afternoon Jake's shop PC had a native Codex install, a keyring-stored API key with a $15 monthly cap on the OpenAI side, gpt-6-luna as the default, and an AGENTS.md that says, in its first line, "the booking page is in /site/book and the tests are npm test." Ethan's Kali laptop had the same config with Sol, and a nightly codex exec that leaves a diff for the morning. Jake: "So the $8 was wasted." Ethan: "The $8 gets you the app, which you'll use for the emails. The terminal was not in that box. Now you know what the box says."

📌 If you keep one line from this page

One install line per operating system, one sign-in (ChatGPT Plus or an API key; Free and Go get the app only), and three settings that decide everything else: the model, the sandbox mode and the approval policy.

Default model gpt-6.1-sol · exec defaults to read-only with approval never · 401 "Missing bearer" = not signed in · Bedrock route = GPT-6 Astra, Sol, Luna.

Revision note. Written October 15, 2026, with Codex CLI 0.162.1 installed from npm on a Debian 12 host and the plan, model and configuration pages as they stood the day after GPT-5.5 left. "Measure twice, cut once," says the proverb; here the measuring is one codex login status before you blame the model.

Related