~/wiki / rabochee-mesto / kak-rabotat-s-codex-polnoe-rukovodstvo

How to Work with Codex: A Complete Guide to OpenAI Codex CLI

Main chat

A chat for vibe coders: news, guides, live cases, marketplace, and finding executors.

$ cd section/ $ join vibe dev
How to Work with Codex: A Complete Guide to OpenAI Codex CLI - обложка

Codex is an AI agent from OpenAI that works directly in the computer terminal and can write, read and edit code on its own. Codex CLI is an open-source coding agent written in Rust that runs in a terminal and works with a local code base.

Unlike a regular chatbot that needs to manually copy the code back and forth, Codex sees your project files, can run commands in the terminal, fix bugs, write tests, and make commits in git – all by text query in natural language.

In short: you write a task with words (“fix a bug in the authorization function” or “add a dark topic to the site”), and Codex itself opens the desired files, makes changes, checks the result and reports what it has done.


How Codex CLI differs from the old Codex 2021

An important clarification for those who remember an earlier history. In 2021, OpenAI released the Codex model as a code-trained version of GPT-3 – it was the basis of early GitHub Copilot and worked through an auto-addition in the editor.

Codex CLI is a completely different product. It is a full-fledged autonomous agent 2025-2026 that:

  • works in the terminal, not as an auto-addition in the editor
  • can perform chains of actions: read → analyze → change → test → commit
  • it uses modern models of the GPT-5 family (GPT-5.3-Codex, GPT-5.4 and later)
  • supports sandboxes, action approval policies, MCP servers and custom instructions

When they say “Codex” in the context of development in 2026, they almost always mean the agent, not the 2021 auto-addition model.


Where Codex is Available: Three Ways to Use

Codex is available in several formats, and it’s important to understand the difference between them.

1. Codex CLI is a terminal client

The main tool for developers working in the command line. It is installed via npm and runs directly from the terminal of any operating system.

2. Codex in the browser (chatgpt.com/codex)

Cloud version – open chatgpt.com/codex in the browser, connect the GitHub repository and work without local installation. Suitable when there is no possibility or desire to put something on the computer.

3. Extension for VS Code

It is installed from the VS Code marketplace and works directly in the usual development environment. He also works in editors based on VS Code - Cursor and Windsurf.

4. Desktop application

Codex Desktop was originally released for macOS, and in March 2026 OpenAI added support for Windows. Downloaded from the official OpenAI website.

In this article, the focus is on Codex CLI – it is the most functional and most often used for serious work.


How to install Codex CLI: step-by-step instructions

Step 1. Check out the version of Node.js

To install via npm, you need Node.js version 22 or higher. Check the current version:

bash
node --version

If version is below 22, update Node.js before installing.

Step 2. Install Codex via npm

bash
npm i -g @openai/codex

The most common installation error is to write npm i -g codex instead of the full @openai/codex packet name. These are different packages, and the wrong name will lead to the wrong installation.

Step 3. Launch and log in

bash
codex

At the first start, a browser with authorization through a ChatGPT account will open. Once logged in, Codex is tied to your ChatGPT plan.

Alternative: Installation through an API key

If you want to use Codex through an API instead of a ChatGPT subscription, set the environment variable:

bash
export OPENAI_API_KEY="sk-..."

To keep the configuration constant, create a .env file in the root directory of the project:

plaintext
OPENAI_API_KEY=sk-...

First start: how to set a task

The easiest way is to run Codex and write a natural language task:

bash
codex

After launching interactively, just describe what to do:

plaintext
fix all the places where the function does not handle errors, and add try-catch

For one-time commands without interactive mode, codex exec is used:

bash
codex exec "update changelog based on the latest diff"
codex e "run tests and fix all fallen ones"

codex e is an abbreviated form of the codex exec command.


Autonomous modes: read-only, auto-edit, full-auto

One of the key questions when working with Codex is how much freedom to give an agent. There are three main levels:

Read-only: The agent analyzes the code, answers questions, suggests changes, but doesn’t change anything. Safe mode for first acquaintance or analysis of an unfamiliar project.

**auto-edit - Codex edits files itself, but does not run commands in the terminal. You can start the task and check the result later.

**full-auto - Codex writes code, runs tests, fixes errors on its own, without confirming each step.

Important safety recommendation: Full-auto mode should be used on a separate git branch, not on the main branch – so that you can easily roll back changes if the agent does something wrong.


Codex Security: Sandbox and Approval Policy

Since an agent runs commands and edits files, it’s important to understand what it’s allowed to do. Codex security is built on two independent levels.

Sandbox Level 1 – What an agent can technically do

The sandbox determines which files and network resources the agent has access to at the operating system level. Codex uses native OS sandbox: Seatbelt on macOS and Bubblewrap on Linux are system isolation mechanisms that safely limit execution of commands.

Basic sandbox modes:

Режим Что разрешено
read-only Только чтение файлов проекта, без изменений
workspace-write Чтение свободное, запись только в рамках текущего проекта
danger-full-access Полный доступ к файловой системе (использовать с осторожностью)

Level 2 Approval Policy – where an agent must ask for permission

This is the second, independent layer – it determines when Codex is obliged to stop and ask for your confirmation, even if it technically has access.

Политика Поведение
untrusted Спрашивает разрешение почти на каждое действие
on-request Спрашивает только когда сам считает нужным
on-failure Спрашивает только если действие завершилось ошибкой
never Никогда не спрашивает (для CI/CD и автоматизации)

approval_policy = "on-request" and sandbox_mode = "workspace-write" are recommended as a reasonable default balance: read free, write to project only, dangerous commands require confirmation.

toml
# ~/.codex/config.toml
approval_policy = "on-request"
sandbox_mode = "workspace-write"

For automated pipelines (e.g., CI/CD), a separate profile with approval_policy = "never" is often used – but without confirmation, the agent operates entirely independently, so this mode should only be used in a controlled environment with additional restrictions.


AGENTS.md - instructions for the project

AGENTS.md is the equivalent of CLAUDE.md from the Claude Code world, as applied to Codex. This is a project-specific instruction file that Codex uploads at the beginning of each session.

Example of AGENTS.md content:

markdown
My Project

## Build Commands
- Test: `npm test`
- Build: `npm run build`
- Lint: `npm run lint -- --fix`

##Rules
Use TypeScript strict mode for all new files
Write unit tests for each new function
Never make a commit directly into the main branch.
All API endpoints must have OpenAPI documentation

Generate AGENTS.md automatically based on the analysis of your project by the team:

bash
/init

Codex will analyze the design structure, determine the assembly, testing, and leasing commands used, and create a basic instruction file.


Slash Teams: Quick Actions in Sessions

Within the Codex interactive session, special commands starting with / are available. Here are the basics:

/model - Switch the model in the middle of the session. It is useful to switch to a more powerful model before the difficult task.

/plan - ask Codex to make a plan before editing multiple files. Good practice for major changes: first plan, then - after your consent - execution.

/diff - See changes Codex has made or is about to make before recording them.

/review - run code revision changes.

**/compact* – Concise the context in a long session. When the dialogue gets too long and the agent begins to lose some of the context, this command summarizes the story and makes room.

/init - automatically generate an AGENTS.md file based on project analysis.

Managing the Level of Reasoning on the Fly

If you want to raise or lower the "depth of thought" of the model right during the session, without restarting it, you use the key combinations Alt+, and Alt+. to lower and increase the level of reasoning effort.


Configuration: config.toml file

Codex uses TOML configuration files. The main file is located on the ~/.codex/config.toml path.

Configuration hierarchy

Settings are applied according to the following priority - from the highest to the lowest:

  1. Command line flags
  2. Profile values
  3. Project configuration (.codex/config.toml)
  4. User configuration (~/.codex/config.toml)
  5. System configuration (/etc/codex/config.toml)
  6. Default values

That is, the flag transmitted directly to the command always interrupts any settings from the files.

Example of basic config.toml

toml
# Model and mode of reasoning
model = "gpt-5.4"
model reasoning effort = "high"

# Default security settings
sandbox mode = "workspace-write"
approval policy = "on-request"

# Identity of agent
personality = "pragmatic"

#Web search
web search = "cached"

# Productivity
service tier = "fast"

Profiles: different settings for different tasks

A profile is a named set of settings (model, sandbox, approval, MCP) that is activated by a single command. Profiles are a key feature of the Codex CLI configuration: Commands using Codex in production usually configure at least two profiles, select a sandbox mode for a specific load, and connect at least one MCP server.

Activation of the profile occurs explicitly - either by a flag in the command line or through an environment variable:

bash
codex --profile dev
# или
CODEX_PROFILE=ci codex

The best naming practice is to name profiles by Wednesday (dev, ci, prod, agent) rather than by people or specific projects. Profiles named after people (alice, bob) do not scale well to the team; profiles named after specific tasks (migration, refactor-2026) quickly become obsolete.

Example profile for CI:

toml
[profiles.ci]
approval_policy = "never"
sandbox_mode = "read-only"

Connecting MCP servers

MCP (Model Context Protocol) is a protocol that gives Codex access to external systems – task trackers, databases, internal documentation – without manually copying data. The agent pulls the necessary information from the connected source.

The recommendation to start with is not to connect multiple sources at once, but to start with one or two connections that remove the most frequent manual routine in your work.

The MCP server is usually connected via a command:

bash
codex mcp add <название-сервера> <url-или-команда>

Once connected, the agent can call the tools of that server automatically when the task requires it, such as finding a task in a tracker, reading a documentation page, or performing a database query.


Skills: Reused processes

If you have a process that repeats from project to project — for example, a specific way of deploying or a series of pre-committee checks — it can be packaged in a skill.

Skill is a SKILL.md file with instructions that Codex applies the same in every project where the file is present. This makes it possible not to explain the same sequence of actions anew in each new session or in a new project.


Tariffs and access to Codex

Codex is available as part of ChatGPT plans. Which model Codex uses by default depends on the CLI version or IDE extension and the current configuration.

Current range of tariffs for 2026:

Тариф Примерная цена Для кого
Plus $20/мес Базовое использование
Pro $100/мес Кратно большие лимиты, работа с агентом весь день
Pro (расширенный) $200/мес Интенсивная многопоточная работа
Business / Enterprise По запросу Командные планы с общим биллингом

Since April 2026, for Business and Enterprise tariffs, pricing has shifted to the consumption model of token loans instead of fixed message limits.

An important privacy point: By default, OpenAI does not use input and output from business-user products — ChatGPT Business, ChatGPT Enterprise, and APIs — to improve models. Owners of organizations with access to APIs may separately agree to transfer API data to OpenAI for this purpose – this does not happen automatically.


Codex CLI vs Claude Code: The Difference

If you choose between agents, both tools are conceptually similar: a terminal AI agent that reads code, edits, executes commands. The main practical differences:

  • AGENTS.md (Codex) and CLAUDE.md (Claude Code) are functionally similar instruction files for the project, but with different expectation formats
  • Codex CLI is written in Rust, uses native OS sandbox (Seatbelt/Bubblewrap)
  • Both agents share a similar concept of profiles, MCP connections, and approval policies, but the specific configuration syntax varies

If your team has already chosen the OpenAI ecosystem (ChatGPT Business/Enterprise, existing API keys), Codex CLI is logically built into the existing billing. If the main subscription is Claude, the same functionality is provided by Claude Code.


Frequent problems and solutions

Installation error: "command not found"

Check that you installed @openai/codex, and not a package with a similar name. Reinstall:

bash
npm uninstall -g codex
npm i -g @openai/codex

Authorization does not pass

Make sure you are using the current version of Node.js (22+) and that the browser that opens to login can access the OpenAI authorization domain.

Codex asks for confirmation too often

This behavior is determined by approval_policy. If untrusted, the agent asks almost every step of the way. Change to on-request in config.toml for less intrusive behavior.

Codex loses context in long session

Use /compact to compress dialog history – this frees up the contextual window while retaining the essence of previous steps.


Checklist to get started

plaintext
Installed Node.js version 22 or higher
● Codex installed: npm i -g @openai/codex
Passed authorization through a ChatGPT account
● AGENTS.md file is created at the root of the project (via /init or manually)
Configured ~/.codex/config.toml with approval policy = "on-request"
and sandbox mode = "workspace-write"
● First problem tested in read-only or auto-edit mode
Full-auto mode is used only on a separate git branch
● If necessary, at least one MCP server is connected

Frequently asked questions

What is Codex in simple words? **

Codex is an AI agent from OpenAI that works in a computer terminal, understands natural language and can independently read, write and edit code, run commands and work with git.

How does Codex CLI differ from Codex 2021? **

Codex 2021 is a GPT-3-based autocomplement model used in early GitHub Copilot. Codex CLI 2025-2026 is a full-fledged standalone terminal agent on the new models of the GPT-5 family, which performs multi-step tasks independently.

How to install Codex CLI? **

Through the npm command npm i -g @openai/codex, Node.js version 22 or higher is required. After installation, start codex - the browser will open for login through the ChatGPT account.

Is it safe to give Codex full access to files? **

Security is built on two levels: a sandbox (what an agent technically can do) and an approval policy (when he is required to ask permission). For everyday work, a combination of workspace-write + on-request is recommended - writing only to the project, with confirmation of risky actions.

** What is Agents.md? **

A file with instructions for a specific project - assembly commands, coding rules, restrictions. Codex downloads it at the beginning of each session. You can automatically generate the /init command.

Can I use Codex without a ChatGPT subscription? **

Yes, through the OPENAI_API_KEY environment variable with access to the OpenAI API – in this case, the payment is based on the API usage model, not on the ChatGPT subscription.

**What is the default model in Codex? **

At the beginning of 2026, the main model is GPT-5.3-Codex, specially optimized for agent work in CLI. GPT-5.4 is also available as a general purpose model. Switching through /model or the --model flag.

What happens if Codex asks for permission too often? **

Change approval_policy to config.toml from untrusted to on-request - the agent will ask only when he considers the action to be risky.


Outcome

Codex CLI is a terminal AI agent from OpenAI that turns text descriptions of tasks into real code changes: from small edits to multi-step refactorings with tests and commits.

Key principles for efficient and safe operation: start with safe modes (read-only, auto-edit) before moving to full-auto, customize AGENTS.md to the specifics of the project, use the combination of workspace-write + on-request as a reasonable balance between autonomy and control, and establish separate profiles for development, CI and production scenarios.

Mastering Codex is not memorizing commands, but building a system: once configured config.toml, AGENTS.md and profiles work for each subsequent project, saving hours of routine work.

$ cd ../ ← back to Workplace