{"slug": "codex-cli-setup-12-steps-60-min-2026", "title": "Codex CLI Setup: 12 Steps, 60 Min [2026]", "summary": "OpenAI refreshed Codex CLI on September 29, 2026, adding voice-controlled task steering, an /agents view for delegating and tracking tasks, better prompt editing, session resumption, worktree workflows and a cleaner terminal interface, and the open-source terminal agent remains actively maintained as of November 14, 2026. OpenAI also removed GPT-5.4 and GPT-5.4 mini from Codex for ChatGPT-account users, pointing them to GPT-5.6 Terra and GPT-5.6 Luna, while API-key users were unaffected; in late October OpenAI added GPT-5-Codex-Mini, which Codex CLI offers automatically once a user reaches 90% of the five-hour usage limit. The CLI itself is free to install, with costs paid through a ChatGPT plan or API pricing.", "body_md": "OpenAI has [refreshed Codex CLI with a new look](https://community.openai.com/t/major-codex-cli-refresh-with-a-new-look-and-powerful-new-capabilities/1402400/4) and a broader feature set, and the terminal agent is still open source and actively maintained as of November 14, 2026. The program costs nothing to install. You pay through the ChatGPT plan you sign in with, or through API pricing if you hand it a key. That split decides most of the setup choices you will make below.\n\nCodex CLI is also moving fast. Models changed, plans changed and the interface changed within the past few months, which is why tutorials from early 2026 now point readers at retired models. A quick look at [how Claude Code, Codex CLI and OpenCode updated within four days](https://shattered.io/claude-code-codex-cli-opencode-update-4-days-2026/) shows the pace. The steps here avoid hard-coding anything that expires and tell you where to check the live value instead.\n\nBy the end you will have Codex CLI installed and verified, a small Python project with an `AGENTS.md` rule file, sandbox and approval settings you chose on purpose, an MCP server wired in, a local open-source model running through Ollama as a fallback, a non-interactive `codex exec` check in CI, and a worktree workflow for parallel tasks. Plan on about 60 minutes.\n\nDon't miss new tech stories on Google\n\nAdd Shattered once in the Google app and our stories show up in your news suggestions.\n\n[Add now](https://www.google.com/preferences/source?hl=en&q=https%3A%2F%2Fshattered.io%2F)\n\n## What Codex CLI Is Today and Why It Counts as an Open-Source Assistant\n\nCodex CLI is the terminal front end of OpenAI’s Codex product family. Codex also runs in a desktop app, an IDE extension, on the web and as Codex Cloud, and OpenAI’s current documentation uses those names as distinct but connected products. The CLI is the piece that edits files in your working directory, runs your tests and shows you a diff before anything lands.\n\nThe agent loop is simple to describe. You type a task. The model reads the files it needs, proposes edits, runs shell commands through a sandbox, reads the output and tries again until the task passes or it gives up. Every command and every edit shows up in your terminal, and you can interrupt at any point. Knowing that loop explains most of the settings in this tutorial, because each one controls a step in it.\n\nOpen source here describes the agent program, not the model behind it. The CLI code is public, so you can read how it builds prompts, how the sandbox wraps shell commands and where it sends your data. The default hosted models are not open weights. That distinction matters for the “open-source AI coding assistant” label, and it is why this tutorial includes a step that points the same CLI at a local open-weight model through Ollama. You get the same interface with a model you can run offline.\n\nFor readers choosing between agents, the [coding tools section](https://shattered.io/category/software/) covers the neighbors in this space. The practical difference is that Codex CLI sits closest to a vendor’s own models, while tools like OpenCode, Goose and Aider are model-agnostic from day one.\n\n### What changed in the last three months\n\nOpenAI announced a refreshed Codex CLI on September 29, 2026. The refresh added voice-controlled task steering, an `/agents` view for delegating and tracking tasks, better prompt editing, session resumption, worktree workflows and a cleaner terminal interface. Documentation dated November 9 also lists multi-agent tools, usage statistics and improved terminal rendering.\n\nModel access shifted too. OpenAI removed GPT-5.4 and GPT-5.4 mini from Codex for people signed in with a ChatGPT account and pointed them to GPT-5.6 Terra and GPT-5.6 Luna. API-key users were not affected by that change. In late October, OpenAI added GPT-5-Codex-Mini, a smaller and cheaper model that Codex CLI offers automatically once you reach 90% of your five-hour usage limit. OpenAI says it stretches usage up to four times within a ChatGPT subscription.\n\nOn the newest-model question, OpenAI’s current Work and Codex documentation names GPT-6.1 Sol as the newest option, and it was rolling out to eligible paid plans on November 14. The same pages also list GPT-6 Sol, GPT-6 Luna and GPT-6 Astra, with availability depending on plan, workspace settings and rollout. GPT-5.3-Codex, launched February 5, 2026, is no longer the newest model in the line, so treat it as a predecessor.\n\n## What You Need Before You Start\n\nThe list is short, and none of it is exotic. You need a terminal, a package manager that can install a Node-based CLI, a Git repository to work in and an account that can pay for model usage. The table lists minimums and the command that proves each one.\n\n| Requirement | Minimum | How to check | \n|---|---|---|\n| Operating system | macOS, Linux, or Windows with WSL 2 | `uname -a` | \n| Node.js | 22 LTS or newer | `node --version` | \n| Git | 2.40 or newer (worktree support) | `git --version` | \n| Python (practice project) | Not listed | `python3 --version` | \n| Codex CLI | Latest release. Reportedly 0.153.0 or newer for GPT-6 Astra | `codex --version` | \n| Ollama (step 10 only) | A current build with tool-calling models | `ollama --version` | \n| Account | A ChatGPT plan with Codex access, or an API key | Sign-in test in step 3 | \n\nTrackers disagree on the newest CLI build number. One tracker listed 0.169.0 on November 14, while OpenAI’s documentation names 0.153.0 only as the floor for GPT-6 Astra. Ignore both and trust whatever `codex --version` prints after you install. If a model you expect is missing from the picker, an old CLI is the first suspect.\n\nEditor choice is open. The 2025 Stack Overflow survey reported that “Visual Studio Code was used regularly by 75.9% of all survey respondents,” according to [Stack Overflow’s technology results](https://survey.stackoverflow.co/2025/technology), so many readers will pair the terminal agent with the Codex IDE extension. Nothing below requires an editor. Everything runs in a shell.\n\nTeams weighing several agents at once should read the [team pilot approach to ranking AI coding assistants](https://shattered.io/best-ai-coding-assistants-team-pilot-12-steps-2026/) before standardizing on one. A pilot with a shared task list catches cost and quality differences that a single afternoon of poking does not.\n\n## Steps 1 to 3: Install Codex CLI, Verify It and Sign In\n\n**Step 1. Confirm Node and Git.** Run the version checks from the table. If Node reports anything older than 22, upgrade through your usual manager (nvm, fnm, Homebrew or your distribution) before you continue. Old Node versions fail in confusing ways during the global install, and a clean runtime saves you a troubleshooting detour later.\n\n```\nnode --version\ngit --version\npython3 --version\n```\n\n**Step 2. Install the CLI.** The npm route works on every platform that has Node. macOS users can also use Homebrew. Pick one route and stick with it, because two installs on one PATH produce the classic “I updated but the version did not change” problem.\n\n```\n# npm (macOS, Linux, WSL 2)\nnpm install -g @openai/codex\n\n# or Homebrew on macOS\nbrew install --cask codex\n\n# confirm which binary your shell will run\nwhich codex\ncodex --version\n```\n\nYou should see a version string and a path under your npm prefix or Homebrew directory. A typical result looks like this, with your own build number in place of the placeholder.\n\n```\n/home/you/.nvm/versions/node/v22/bin/codex\ncodex-cli <your-build-number>\n```\n\n**Step 3. Sign in.** OpenAI’s setup instructions are short: open your project directory, run `codex` and sign in with a ChatGPT account when prompted. The browser flow returns a token to the terminal and stores it locally. Signing in this way uses your ChatGPT plan’s usage and billing. If you would rather bill against the API, log in with a personal API key instead, and usage then follows API pricing.\n\n```\nmkdir -p ~/work/tally && cd ~/work/tally\ngit init\ncodex\n# choose \"Sign in with ChatGPT\" in the first-run screen\n\n# alternative for API billing (check `codex login --help` on your build)\nprintenv OPENAI_API_KEY | codex login --with-api-key\n```\n\nPick the sign-in method deliberately, because it changes who pays and which models you see. The next section lays out what each route buys. For now, exit the first-run screen once you see the prompt box, then run `/status` inside the session to confirm the account, working directory and active model. Press `Ctrl+C` twice to leave.\n\n## Plans, Models and Cost: What Your Sign-In Method Pays For\n\nCodex is included across ChatGPT plans, including Free and Go, though limits and model access depend on the plan. That is a change from earlier in the year, when Codex sat behind higher tiers. The table below reflects the plan names and prices on [OpenAI’s pricing page](https://chatgpt.com/pricing) as of November 14, 2026, with access notes from OpenAI’s help documentation.\n\n| Plan | Price | Codex access | \n|---|---|---|\n| Free | $0 | Limited access | \n| Go | Not listed | Limited access | \n| Plus | $20 per month | Included, with expanded usage | \n| Pro | Several tiers, see the pricing page | Expanded access | \n| Business (standard seat) | $20 per user per month billed annually, $25 monthly | Included, governed by workspace settings and credits | \n| Business (premium seat) | $100 per user per month billed annually, $125 monthly | Included, governed by workspace settings and credits | \n\nPro is now split into tiers. Reports describe Pro 100, Pro 200 and Pro 500, with the top tier adding the Ultrafast option for the newest models, but check the live pricing page before you budget around those figures. Codex Cloud, the hosted environment feature, is a separate entitlement. It is available to eligible Plus, all Pro tiers, Business, Enterprise, Healthcare and Education accounts, and it is not included with Free or Go. The terminal CLI does not need it.\n\nBusiness and Enterprise accounts bill Codex through tokens and credits instead of a single comparable monthly price. OpenAI’s own guidance says typical Codex usage averages roughly $100 to $200 per developer per month, though actual cost varies with the model, concurrency, automations and fast mode. Use that as a planning range for a team rather than a promise. [BenchLM’s dated tracker of coding plan changes](https://benchlm.ai/coding-plans/changes) is a handy place to watch limits and prices move.\n\n### ChatGPT sign-in versus API key\n\nThe two routes behave differently in daily use. A ChatGPT sign-in draws on your plan’s included allowance, which resets on a rolling window, and it routes you to the models OpenAI lists for that plan. An API key bills per token with no plan ceiling, so a runaway loop costs real money. For a personal laptop, the plan route is the safer default. For CI, the API key is the only practical route because no human is available to complete a browser login.\n\nOne more behavior to know before you start. When a session reaches 90% of the five-hour usage limit, the CLI offers a switch to GPT-5-Codex-Mini. Accept it for small edits and test fixes, and decline it when you are about to start a complicated refactor. A smaller model is cheaper, but it also makes more planning mistakes on multi-file changes.\n\n## Steps 4 and 5: Build the Practice Project and Write AGENTS.md\n\n**Step 4. Create a project small enough to judge.** A practice repository with known-good behavior lets you tell whether the agent helped or wandered off. The project below is a 25-line Python script called `tally` that reads a CSV of orders and prints revenue per customer. It uses only the standard library, so the sandbox does not need network access to run it.\n\n``` python\n# tally.py\nimport argparse\nimport csv\nimport sys\nfrom collections import defaultdict\n\ndef load_orders(path):\n    with open(path, newline=\"\") as handle:\n        return list(csv.DictReader(handle))\n\ndef revenue_by_customer(orders):\n    totals = defaultdict(float)\n    for row in orders:\n        totals[row[\"customer\"]] += float(row[\"amount\"])\n    return dict(totals)\n\ndef main(argv=None):\n    parser = argparse.ArgumentParser(description=\"Revenue per customer\")\n    parser.add_argument(\"csv_path\")\n    args = parser.parse_args(argv)\n    totals = revenue_by_customer(load_orders(args.csv_path))\n    for customer, total in sorted(totals.items(), key=lambda item: -item[1]):\n        print(f\"{customer:<12} {total:>10.2f}\")\n    return 0\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n# orders.csv\norder_id,customer,amount,date\n1001,acme,120.50,2026-10-02\n1002,globex,75.00,2026-10-09\n1003,acme,30.25,2026-11-01\n1004,initech,200.00,2026-11-03\n1005,globex,15.75,2026-11-10\npython\n# test_tally.py\nfrom tally import revenue_by_customer\n\ndef test_revenue_by_customer_sums_per_customer():\n    orders = [\n        {\"customer\": \"acme\", \"amount\": \"10.00\"},\n        {\"customer\": \"acme\", \"amount\": \"5.50\"},\n        {\"customer\": \"globex\", \"amount\": \"1.00\"},\n    ]\n    assert revenue_by_customer(orders) == {\"acme\": 15.5, \"globex\": 1.0}\n```\n\nRun the script once yourself and commit the baseline. The commit matters more than it looks. It gives you a clean point to diff against and a clean point to reset to if a task goes sideways.\n\n```\npython3 tally.py orders.csv\ngit add tally.py orders.csv test_tally.py\ngit commit -m \"Baseline tally CLI\"\n```\n\nThe expected output ranks customers by total revenue, highest first.\n\n```\ninitech          200.00\nacme             150.75\nglobex            90.75\n```\n\n**Step 5. Write AGENTS.md.** Codex reads an `AGENTS.md` file from the repository and treats it as standing instructions. It is the cheapest quality lever in the whole tool. A few rules about commands, style and off-limits files prevent most of the annoying behavior, such as the agent rewriting your data file or inventing a test runner you do not use. Keep it short, because every line costs tokens on every task.\n\n```\n# AGENTS.md\n\n## Project\ntally is a single-file Python CLI that reports revenue per customer from a CSV.\n\n## Commands\n- Run tests: python -m pytest -q\n- Run the CLI: python tally.py orders.csv\n\n## Rules\n- Python 3.11 or newer, standard library only. Do not add dependencies.\n- Every behavior change needs a test in test_tally.py.\n- Never edit orders.csv. Create a new fixture file if a test needs different data.\n- Keep functions under 25 lines.\n- Show the test command output before you say a task is done.\n```\n\nCommit it. A rule file that lives only on your laptop disappears the first time a teammate or a CI job runs the agent. If you already use Git-centered agents, the pattern will feel familiar, and [Aider’s Git-first local setup](https://shattered.io/aider-local-ai-coding-assistant-ollama-git-2026/) follows the same commit-early habit.\n\n## Steps 6 and 7: Pick a Sandbox and an Approval Policy You Can Defend\n\nTwo settings control how much damage a bad run can do. The sandbox mode decides what a shell command can touch. The approval policy decides when the agent has to stop and ask you. Treat them as separate dials, and set both in the config file rather than by habit. The names below match recent builds. Run `codex --help` to confirm them on yours, because flag spellings have changed across releases.\n\n| Setting | Value | What it allows | Use it for | \n|---|---|---|---|\n| Sandbox | `read-only` | Reads files, writes nothing | Code review, audits, CI checks | \n| Sandbox | `workspace-write` | Writes inside the project, blocks the network by default | Daily development | \n| Sandbox | `danger-full-access` | No filesystem or network limits | Disposable containers only | \n| Approvals | `untrusted` | Asks before anything beyond known-safe reads | Unfamiliar repositories | \n| Approvals | `on-request` | Agent decides when to ask | Trusted repositories, hands-on work | \n| Approvals | `never` | Never asks, fails instead | Unattended runs inside a tight sandbox | \n\n**Step 6. Set the defaults.** Open `~/.codex/config.toml` and write a conservative baseline. Workspace-write plus on-request approvals fits most solo work. The agent edits files freely inside the repository, and it has to ask before it does anything unusual, such as touching a path outside the project.\n\n```\n# ~/.codex/config.toml\napproval_policy = \"on-request\"\nsandbox_mode = \"workspace-write\"\n```\n\nMatch the dials to the repository, not to your mood. A project you wrote yourself earns on-request approvals. A repository you just cloned from a stranger deserves the untrusted policy and a read-only sandbox until you have skimmed its scripts. The cost of one extra approval prompt is a few seconds. The cost of running a hostile install script with write access is your afternoon.\n\n**Step 7. Prove the sandbox works.** Never assume a boundary exists until you have seen it block something. Start a session and ask the agent to run a command the sandbox should refuse, such as fetching a web page or writing outside the repository. With the baseline above, the network call should fail and the outside write should trigger an approval prompt.\n\n```\ncodex \"Run curl -sI https://example.com and tell me what happened. Do not retry.\"\n```\n\nA healthy result is an agent that reports the command failed because network access is blocked, then stops. If the request succeeds, your config did not load or your build defaults differ, so check `/status` for the active sandbox. Teams that need to prove where agent traffic goes can follow the egress checks in [this audit of an open-source coding assistant’s outbound connections](https://shattered.io/open-source-ai-coding-assistant-audit-egress-12-steps-2026/), which applies to any CLI agent.\n\n## Step 8: Run Your First Real Task End to End\n\nNow give the agent a job with a clear finish line. The task below adds a `--since` date filter to the CLI and requires tests. It touches two files, forces a design decision about date parsing and has an objective pass or fail check. Those traits make it a good probe. A vague prompt like “improve this script” tells you nothing about whether the setup works.\n\n```\ncodex \"Add a --since YYYY-MM-DD option to tally.py that only counts orders on or after that date. Reject malformed dates with a clear argparse error. Add tests in test_tally.py for the filter. Follow AGENTS.md and run the tests before finishing.\"\n```\n\nNotice the anatomy of that prompt. It names the file, states the behavior in testable terms, covers the failure case, says where the tests go and ends with a stopping condition. Each clause removes a decision the model would otherwise guess at. Compare it with a weak version, which leaves all of those decisions open.\n\n```\n# weak: no file, no behavior, no tests, no stop condition\ncodex \"make tally support dates\"\n\n# strong: names files, behavior, error case, tests, stop condition\ncodex \"In tally.py add --since YYYY-MM-DD (inclusive). Bad dates must exit with an argparse error. Add two tests. Run pytest and stop.\"\n```\n\nWatch the plan before the edits. A good run reads `tally.py` and `AGENTS.md`, proposes a small change, edits the two files, then runs the test command. When it asks for approval, read the command before you press enter. If it proposes `pip install pytest` and the network is blocked, that is the sandbox doing its job. Install pytest yourself in a virtual environment first, then let the agent retry.\n\nYour diff will differ in naming and layout, but a correct result looks like the sketch below. It adds a pure `filter_since` function, wires one argparse option and leaves `orders.csv` untouched. Review with `/diff` inside the session or `git diff` outside it.\n\n``` python\n+from datetime import date\n...\n+def filter_since(orders, since):\n+    return [row for row in orders if date.fromisoformat(row[\"date\"]) >= since]\n...\n+    parser.add_argument(\"--since\", type=date.fromisoformat, help=\"YYYY-MM-DD\")\n...\n+    if args.since:\n+        orders = filter_since(orders, args.since)\n```\n\nThen verify behavior yourself instead of trusting the agent’s summary. The filter should drop the October orders and keep November’s.\n\n``` bash\n$ python3 tally.py orders.csv --since 2026-11-01\ninitech          200.00\nacme              30.25\nglobex            15.75\n\n$ python3 tally.py orders.csv --since 2026-11-04\nglobex            15.75\n\n$ python3 tally.py orders.csv --since 2026-13-01\nusage: tally.py [-h] [--since SINCE] csv_path\ntally.py: error: argument --since: invalid fromisoformat value: '2026-13-01'\n```\n\nThose three runs check the happy path, the cutoff boundary and the error case. Because the cutoff is inclusive, an order placed on the cutoff date must stay in the results and any later order must drop out. If your agent wrote an exclusive comparison, the boundary run would drop the order placed on the cutoff date, and that is a real bug the tests should have caught. Commit only after you have read every changed line.\n\n```\npython -m pytest -q\n# expected shape (timing varies):\n# ..                                                                   [100%]\n# 2 passed in 0.02s\ngit add -A\ngit commit -m \"Add --since filter to tally\"\n```\n\n## Step 9: Add MCP Servers Without Opening a Hole\n\nModel Context Protocol servers give the agent extra tools, such as reading a docs folder, querying a ticket system or inspecting a database schema. Codex CLI reads MCP server definitions from the same `config.toml`. Start with a read-only filesystem server pointed at a documentation directory. It teaches the mechanics without handing the agent anything dangerous.\n\n```\n# ~/.codex/config.toml (append)\n[mcp_servers.docs]\ncommand = \"npx\"\nargs = [\"-y\", \"@modelcontextprotocol/server-filesystem\", \"/home/you/docs/tally\"]\n```\n\nRestart the session and ask the agent which tools it can see. The server name should appear in the answer. Then give it a task that needs the docs, for example “Summarize the CSV schema from the docs folder, then check that tally.py matches it.” If the tool never shows up, the usual cause is a failed `npx` start, so run the same command by hand and read the error.\n\nTreat every MCP server as code with your permissions. A server can read whatever you point it at, and its output flows straight into the model’s context, which makes it a prompt-injection channel. The recent [GitSpawn flaw that hit seven AI coding agents](https://shattered.io/gitspawn-ai-coding-agent-vulnerability-2026/) is a reminder that repository content and tool output both count as untrusted input. Pin server versions, avoid servers that fetch arbitrary URLs and keep secrets out of the directories you expose.\n\nAdd servers one at a time and test each. A config with six servers and no tests turns every later failure into a guessing game. Keep a short note in `AGENTS.md` naming which servers are expected, so a teammate who sees a missing tool knows where to look first.\n\n## Step 10: Point Codex CLI at a Local Open-Source Model With Ollama\n\nThis step turns the CLI into a fully local assistant. You run an open-weight model with Ollama, expose its OpenAI-compatible endpoint on localhost, and tell Codex to use it through a named profile. Prompts and code never leave your machine. The cost is quality, because local models trail the hosted GPT-6 line on hard multi-file work, and speed, which depends entirely on your hardware.\n\nPick a coding model that supports tool calls, since Codex relies on them to edit files and run commands. A model without tool support will chat happily and then fail at the first edit. The roundup of [open-source AI models and their three run paths](https://shattered.io/open-source-ai-models-3-run-paths-mistral-large-4-kimi-k3-1-glm-5-3-2026/) helps you choose between local weights, hosted open models and API access. The example below uses `gpt-oss:20b`, a 20-billion-parameter open-weight model that fits a single workstation GPU or a recent Mac.\n\n```\nollama pull gpt-oss:20b\nollama run gpt-oss:20b \"Reply with the word ready\"\nollama ps\n```\n\nThe `ollama ps` table shows whether the model loaded fully onto the GPU. A column reading 100% GPU means a full GPU load, 100% CPU means system memory only, and a split such as 48%/52% means partial offload with a speed penalty. Slow generation with a split load usually means the model is too big for your VRAM, so drop to a smaller model instead of fighting it.\n\n```\n# ~/.codex/config.toml (append)\n[model_providers.ollama]\nname = \"Ollama\"\nbase_url = \"http://localhost:11434/v1\"\nwire_api = \"chat\"\n\n[profiles.local]\nmodel_provider = \"ollama\"\nmodel = \"gpt-oss:20b\"\n```\n\nLaunch with the profile, or use the shortcut flag for open-source providers if your build has it.\n\n```\ncodex --profile local \"List the functions in tally.py and what each returns.\"\n\n# shortcut on builds that support it\ncodex --oss\n```\n\nLocal models need a larger context window than Ollama’s small default, or Codex prompts get truncated and the agent loses AGENTS.md mid-task. Build a variant with a bigger window using a Modelfile, then point the profile at that tag. Choose a window your memory can hold, because context costs RAM or VRAM on top of the weights.\n\n```\n# Modelfile\nFROM gpt-oss:20b\nPARAMETER num_ctx 32768\n\n# build and use it\nollama create gpt-oss-coder -f Modelfile\n# then set model = \"gpt-oss-coder\" in [profiles.local]\n```\n\nMeasure the gap instead of guessing. Run the same read-only prompt against the hosted default and the local profile, then compare wall-clock time and how useful each answer is. Do this for three or four of your own typical tasks. The numbers tell you which jobs can move offline and which ones still need the hosted line.\n\n```\ntime codex exec --sandbox read-only \"List every function in tally.py with a one-line summary.\" > out-hosted.txt\ntime codex exec --profile local --sandbox read-only \"List every function in tally.py with a one-line summary.\" > out-local.txt\nwc -w out-hosted.txt out-local.txt\n```\n\nRun the same `--since` task against the local profile too. You will likely see weaker planning and more retries. That is a fair price for offline work and for repositories that cannot leave your network. If local use is your main goal, [OpenCode with Ollama](https://shattered.io/open-source-ai-coding-assistant-opencode-ollama-2026/) was built model-agnostic from the start and may fit better than a vendor CLI.\n\n## Step 11: Run Codex Without a Human Using codex exec in CI\n\nThe `codex exec` subcommand runs a single prompt non-interactively and prints the result, which makes it usable in scripts and pipelines. Use it for read-only jobs first, such as reviewing a pull request diff or summarizing failing tests. Do not let an unattended agent push commits until you have watched it behave for several weeks.\n\n```\ncodex exec --sandbox read-only \"Summarize the risk in the last commit. List files touched and any missing tests.\" > summary.md\ncat summary.md\n```\n\nIn GitHub Actions, give the job the narrowest permissions that work, install the CLI, authenticate with an API key stored as a secret and keep the sandbox read-only. CI has no browser, so ChatGPT sign-in is not an option. The exact login command and environment variable can differ between builds, so confirm them in the official documentation before you copy this into a protected branch.\n\n```\n# .github/workflows/codex-review.yml\nname: codex-review\non: pull_request\njobs:\n  review:\n    runs-on: ubuntu-latest\n    permissions:\n      contents: read\n    steps:\n      - uses: actions/checkout@v4\n        with:\n          fetch-depth: 0\n      - uses: actions/setup-node@v4\n        with:\n          node-version: 22\n      - run: npm install -g @openai/codex\n      - name: Review the diff\n        env:\n          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}\n        run: |\n          printenv OPENAI_API_KEY | codex login --with-api-key\n          codex exec --sandbox read-only \"Review the diff against origin/main. Flag bugs and missing tests. Be brief.\" > review.md\n          cat review.md\n```\n\nPrint the review into the job log first and skip posting comments until you trust the signal. A noisy bot trains reviewers to ignore it. Once the output proves useful, gate on a single keyword. Ask the model to start its answer with a fixed word when it finds a merge-blocking bug, and let a tiny script turn that word into a failing exit code.\n\n``` bash\n#!/usr/bin/env bash\nset -euo pipefail\ncodex exec --sandbox read-only \"Review the diff against origin/main. Start your answer with BLOCKER if a bug must be fixed before merge, otherwise start with OK.\" > review.md\nif head -n 1 review.md | grep -q '^BLOCKER'; then\n  echo \"Codex flagged a blocker\"\n  cat review.md\n  exit 1\nfi\n```\n\nCompare the approach with [running Cursor’s CLI as a headless agent in GitHub Actions](https://shattered.io/cursor-cli-github-actions-headless-agent-2026/), which solves the same problem with a different tool and gives you a second data point on cost per run. Set a spend ceiling too. API-key runs bill per token, so cap the job with a timeout, run it only on pull requests that touch code and put an alert on the key’s monthly usage. A forgotten workflow that fires on every push can quietly cost more than the team’s plan seats.\n\n## Step 12: Use Worktrees and the Agents View for Parallel Tasks\n\nThe refreshed CLI added worktree workflows and an `/agents` view, and both exist to solve one problem. Two agents editing the same checkout collide. A Git worktree gives each task its own directory and branch while sharing one repository history. One release listing credits version 0.154.0 with experimental worktree support for starting and forking tasks, and the feature set has kept changing since, so expect small differences in menus.\n\n```\ngit worktree add ../tally-since -b feat/since\ngit worktree add ../tally-csv-errors -b feat/csv-errors\ngit worktree list\n```\n\nStart one Codex session in each directory with a distinct task. In the first, finish the date filter. In the second, ask for friendlier handling of missing columns and malformed rows. The agents view then lets you watch both, answer questions inline while a task continues and resume a session you left earlier. Voice steering is available too, though most people stay on the keyboard in a shared office.\n\nMerge the branches yourself, one at a time, and rerun the tests after each merge. Parallel agents multiply review work, not just output, so cap yourself at two or three tasks. People who have used [Cline’s VS Code and CLI setup](https://shattered.io/cline-ai-setup-vscode-cli-12-steps-2026/) will recognize the same trade-off between speed and the effort needed to read every diff.\n\n```\ncd ~/work/tally\ngit merge feat/since\npython -m pytest -q\ngit merge feat/csv-errors\npython -m pytest -q\ngit worktree remove ../tally-since\ngit worktree remove ../tally-csv-errors\n```\n\n## Common Pitfalls to Avoid\n\n**Pitfall 1: Reaching for full access.** When a sandboxed command fails, the quick fix is to switch to `danger-full-access`. Resist it. Fix the cause, such as installing dependencies ahead of time or adding a single writable path. Full access belongs inside disposable containers, never on a laptop with your SSH keys on it.\n\n**Pitfall 2: Starting on a dirty tree.** If you have uncommitted work, the agent’s edits mix with yours, and you cannot separate them later. Commit or stash first. A clean tree turns `git diff` into a precise record of what the agent did.\n\n**Pitfall 3: Trusting tests the agent wrote for itself.** A model that writes both the code and the tests can write tests that pass for the wrong reason. Check at least one boundary case by hand, as in step 8, and ask for a failing test before the fix when the bug is subtle.\n\n**Pitfall 4: Mixing billing routes by accident.** A leftover `OPENAI_API_KEY` in your shell can push usage onto API billing when you meant to use your plan. Run `/status` at the start of each session and unset keys you do not want in play.\n\n**Pitfall 5: Vague prompts.** “Make it better” produces sprawling diffs. A good prompt names the files, the behavior, the tests and the stopping condition. Short and specific beats long and fuzzy every time.\n\n**Pitfall 6: Committing secrets in config.** Never paste an API key into `config.toml` or `AGENTS.md`. Keep keys in your shell environment or a secret manager, and add a pre-commit secret scanner to the repository so a mistake gets caught before it ships.\n\n**Pitfall 7: Believing the old model names.** Posts written before the autumn refresh recommend models that no longer appear for ChatGPT sign-ins. Open `/model` and pick from the live list instead of copying a model name from a tutorial.\n\n**Pitfall 8: Ignoring injected instructions.** A README, an issue body or an MCP response can contain text that tells the agent to do something else. Keep the sandbox tight, review each approval prompt and never run an agent with broad permissions on a repository you do not trust.\n\n## Troubleshooting: 12 Problems and Fixes\n\n| Symptom | Likely cause | Fix | \n|---|---|---|\n| `codex: command not found` after install | The npm global bin directory is not on PATH | Run `npm config get prefix` , add its`bin` folder to PATH, then open a new shell | \n| Version does not change after an update | Two installs (npm and Homebrew) on one PATH | Run `which -a codex` , remove the extra install, keep one | \n| Browser sign-in loops or never returns | Remote or headless machine with no local browser | Sign in on a desktop, or use API-key login on the server | \n| A model you expect is missing from `/model` | Old CLI, plan restriction or staged rollout | Update the CLI, check your plan, and recheck later because rollouts stagger | \n| Usage limit reached mid-task | Plan allowance used up in the rolling window | Accept the GPT-5-Codex-Mini fallback, wait for the reset, or add credits | \n| `pip install` or`npm install` fails inside a session | Workspace-write blocks network by default | Install dependencies in your own shell first, then let the agent run tests | \n| Write denied outside the repository | Path is outside the writable workspace | Move the work inside the repo, or approve that one path when prompted | \n| AGENTS.md rules ignored | File is in the wrong directory or was named differently | Keep it at the repository root with exact casing, restart, and confirm in `/status` | \n| Local profile fails on the first edit | The Ollama model has no tool-call support | Switch to a tool-capable model and retest with a trivial edit | \n| Local agent forgets earlier instructions | Context window too small and prompts truncated | Build a Modelfile with a larger `num_ctx` and point the profile at it | \n| TLS or certificate errors behind a proxy | Corporate proxy intercepts HTTPS | Set `HTTPS_PROXY` and`NODE_EXTRA_CA_CERTS` to your company bundle | \n| MCP tool never appears | The server command failed to start | Run the `command` and`args` by hand and fix the error you see | \n\nTwo diagnostics solve most of the rest. First, run `/status` and read the account, model, sandbox and working directory it prints. Second, reproduce the problem in a fresh, empty repository. If the error disappears there, something in your project config or rule file is the cause. If it follows you, the problem lives in your global config or your install.\n\nWhen a hosted-model call fails with a rate or availability message, check OpenAI’s status page and your plan allowance before you change any settings. Many “broken setup” reports turn out to be a temporary service limit. Waiting ten minutes costs less than rewriting a working config.\n\n## Advanced Tips for Daily Use\n\n**Use profiles for modes of work.** Define a `review` profile with a read-only sandbox, a `local` profile for offline work and a default profile for daily edits. Switching modes becomes a flag instead of a config edit, and you stop leaving a permissive setting active by accident.\n\n```\n# ~/.codex/config.toml (append)\n[profiles.review]\nsandbox_mode = \"read-only\"\napproval_policy = \"untrusted\"\n\n# usage\ncodex --profile review \"Audit test_tally.py for weak assertions.\"\n```\n\n**Keep AGENTS.md layered.** Put global habits in a file in your home Codex directory and project rules in each repository. Nested directories can carry their own file for a subsystem with unusual rules. The agent reads the closest one, so a monorepo can hold different conventions without a giant single document.\n\n**Compact long sessions.** Use `/compact` when a conversation gets long, or start a fresh session and resume from a short summary. Long sessions cost more and drift. A tight 20-minute session on one task beats a three-hour wander across five.\n\n**Review in a second pass.** Run the review profile on your own diff before you push. A read-only pass costs little and catches missing tests and leftover debug lines. Pairing a second tool can help, and the [Goose local assistant setup](https://shattered.io/goose-ai-coding-assistant-local-ollama-12-steps-2026/) is a good open-source reviewer to run beside Codex when you want an independent opinion.\n\n**Track cost per accepted change.** Log the task, the model, the number of retries and whether you accepted the result. After two weeks, you will know which model earns its cost on which kind of work, and you can route small edits to the cheaper model on purpose instead of by limit fallback.\n\n``` bash\n#!/usr/bin/env bash\n# log-task.sh  usage: ./log-task.sh since-filter model accepted\nprintf '%s,%s,%s,%s\\n' \"$(date +%F)\" \"$1\" \"$2\" \"$3\" >> ~/codex-task-log.csv\n```\n\n**Pin the CLI in shared environments.** For team devcontainers and CI images, install a specific version and bump it deliberately. Letting every machine auto-update means the same prompt behaves differently on Monday than it did on Friday.\n\n## Frequently Asked Questions\n\n### Is Codex CLI really open source?\n\nThe CLI program is open source and actively maintained as of November 14, 2026. The hosted models it talks to by default are not open weights. You can swap in a local open-weight model through Ollama, as step 10 shows, to run the full stack on your own hardware.\n\n### Do I need a paid ChatGPT plan to use Codex CLI?\n\nNot necessarily. OpenAI lists Codex as included across ChatGPT plans, including Free and Go, with limited access on those two. Heavier daily use fits Plus or a Pro tier better. You can also skip plans entirely and bill an API key per token.\n\n### Which model should I pick in Codex CLI?\n\nOpen `/model` and choose from the live list. OpenAI’s documentation names GPT-6.1 Sol as the newest option, rolling out to eligible paid plans, alongside GPT-6 Sol, GPT-6 Luna and GPT-6 Astra. Use a smaller model such as GPT-5-Codex-Mini for quick edits and a larger one for multi-file work.\n\n### What is the difference between signing in with ChatGPT and using an API key?\n\nA ChatGPT sign-in uses your plan’s usage and billing. An API key uses API pricing, billed per token. CI jobs need the key route because no one can complete a browser login on a build server.\n\n### Can Codex CLI run fully offline?\n\nYes, with a local provider. Configure the Ollama profile from step 10, use a tool-capable open-weight model and raise the context window. Expect lower quality than the hosted GPT-6 line on difficult tasks.\n\n### Is it safe to let the agent run commands on my machine?\n\nIt is safe enough when you keep the sandbox on workspace-write or read-only, commit before each task and read every approval prompt. It is not safe to use full access on a machine holding credentials. Treat repository text and MCP output as untrusted input.\n\n### How much does Codex cost for a team?\n\nBusiness standard seats list at $20 per user per month billed annually or $25 monthly, and premium seats at $100 annually or $125 monthly. Codex usage on Business and Enterprise also runs on credits or tokens. OpenAI’s guidance puts typical usage around $100 to $200 per developer per month, so budget with a range and measure your own.\n\n### Why does my CLI not show the newest model?\n\nUpdate the CLI first, since newer models can require a recent build. If the model is still missing, your plan or workspace may not have it yet, because availability depends on plan, settings and staged rollout.", "url": "https://wpnews.pro/news/codex-cli-setup-12-steps-60-min-2026", "canonical_source": "https://shattered.io/codex-cli-setup-12-steps-2026/", "published_at": "2026-11-14 23:25:55+00:00", "updated_at": "2026-11-14 23:52:13.278137+00:00", "lang": "en", "topics": ["ai-tools", "ai-agents", "developer-tools", "large-language-models", "artificial-intelligence"], "entities": ["OpenAI", "Codex CLI", "GPT-5.4", "GPT-5.4 mini", "GPT-5.6 Terra", "GPT-5.6 Luna", "GPT-5-Codex-Mini", "Ollama"], "also_reported_by": [], "alternates": {"html": "https://wpnews.pro/news/codex-cli-setup-12-steps-60-min-2026", "markdown": "https://wpnews.pro/news/codex-cli-setup-12-steps-60-min-2026.md", "text": "https://wpnews.pro/news/codex-cli-setup-12-steps-60-min-2026.txt", "jsonld": "https://wpnews.pro/news/codex-cli-setup-12-steps-60-min-2026.jsonld"}}