·9 min read

OpenAI Codex CLI: Setup, Configuration, and Custom Instructions

Learn how to configure OpenAI's Codex CLI from initial setup to custom AGENTS.md instructions that improve code generation quality and consistency.

OpenAI Codex CLI: Setup, Configuration, and Custom Instructions

What is the OpenAI Codex CLI?

The OpenAI Codex CLI is a terminal-based AI coding assistant powered by OpenAI's models. Unlike chat interfaces, Codex CLI lives in your shell: you run it from the command line, it reads your project files, executes commands, and writes code directly without switching context.

The key distinction from other AI tools is its agentic design: Codex CLI can autonomously run multi-step tasks. Ask it to "add pagination to the user list endpoint" and it will read the relevant files, write the changes, run tests, and iterate if they fail, all without manual intervention between steps.

This makes it particularly powerful for:

  • Refactoring large codebases where you need to touch many files
  • Generating boilerplate that follows your existing patterns
  • Debugging by reading logs, running commands, and applying fixes iteratively
  • Automating repetitive coding tasks you'd otherwise script manually

Installing and setting up Codex CLI

Getting started requires Node.js 22+ (or you can download a pre-built binary from the GitHub releases page to skip the Node.js requirement entirely).

# Install globally via npm
npm install -g @openai/codex

# Verify installation
codex --version

Then authenticate. The recommended method is signing in with your ChatGPT account (Plus, Pro, Team, or Enterprise):

# Launch Codex and follow the browser sign-in flow
codex

# Or sign in with an API key instead
codex login --with-api-key

If you prefer API key authentication, you can pipe your key directly: printenv OPENAI_API_KEY | codex login --with-api-key.

Running your first command

# Interactive mode — starts a session in your current directory
codex

# Single command mode — run one task and exit
codex "add TypeScript types to all the API response objects in src/api/"

# With a specific model
codex --model o4-mini "refactor the auth middleware to use JWT"

In interactive mode, Codex CLI shows you a plan before executing each step and asks for confirmation. This "approval mode" is configurable: you can set it to auto-approve everything or require explicit approval for file writes.

The AGENTS.md file — Codex CLI's instruction system

The most important configuration feature in Codex CLI is the AGENTS.md file. This is how you teach the AI about your project's conventions, architecture, and preferences.

When Codex CLI starts a session, it looks for AGENTS.md files in a specific order:

  1. ~/.codex/AGENTS.md (your global personal instructions)
  2. AGENTS.md in the project root (project-wide conventions)
  3. AGENTS.md files in subdirectories (scoped to that part of the codebase)

This layered approach means you can set universal preferences (always use TypeScript, prefer functional patterns) at the global level while keeping project-specific conventions in the repo.

What to put in AGENTS.md

Think of AGENTS.md as a briefing for a new contractor. It should cover:

1. Your tech stack and key decisions

## Tech stack
- Runtime: Node.js 22 with TypeScript 5.7 strict mode
- Framework: Fastify 5 (NOT Express)
- ORM: Drizzle with PostgreSQL
- Testing: Vitest with \`describe\`/\`it\` blocks (not Jest-style \`test\`)
- Package manager: pnpm (never npm or yarn)

2. Architectural patterns and file conventions

## Architecture
- Route handlers live in src/routes/ — one file per resource
- Business logic goes in src/services/ — never in route handlers
- Database queries are in src/db/queries/ — never inline in services
- All types are defined in src/types/index.ts

3. Explicit prohibitions

## Do NOT
- Do not use \`any\` — always find the proper type
- Do not write raw SQL — use Drizzle's query builder
- Do not create new utility functions in route files
- Do not use \`console.log\` — use the \`logger\` from src/lib/logger.ts

4. Testing expectations

## Testing
- Every new function in src/services/ needs a corresponding test
- Test files live next to source files as *.test.ts
- Use the test factories in tests/factories/ for creating test data
- Mock external APIs, never call them in tests

Writing effective Codex CLI instructions

The difference between mediocre and excellent AGENTS.md files comes down to specificity. Generic instructions produce generic code. Specific instructions produce code that looks like it was written by your best engineer.

Show the pattern, not just the rule

Vague instruction:

Use proper error handling.

Specific instruction:

## Error handling pattern

All async route handlers must wrap logic in try/catch and return structured errors:

async function handler(req, reply) {
  try {
    const result = await someService.doThing(req.body);
    return reply.send({ data: result });
  } catch (error) {
    if (error instanceof ValidationError) {
      return reply.status(400).send({ error: error.message, code: 'VALIDATION_ERROR' });
    }
    logger.error(error, 'Unexpected error in handler');
    return reply.status(500).send({ error: 'Internal server error', code: 'INTERNAL_ERROR' });
  }
}

The second version eliminates ambiguity. Codex CLI knows exactly what structure to produce without guessing.

Reference your actual file structure

Codex CLI can read files, so point it to examples in your codebase:

## Component pattern
Follow the pattern in src/components/UserCard.tsx — props interface defined
above the component, named export, no default exports.

When Codex CLI processes this instruction, it reads UserCard.tsx and extracts the pattern directly, which is much more reliable than trying to describe the pattern in prose.

Calibrate the approval mode

Codex CLI's approval mode controls how much autonomy it has:

ModeBehaviorBest for
suggestShows changes, you apply themCode review workflows
auto-editWrites files, asks before running commandsTypical development
full-autoRuns everything autonomouslyTrusted automation tasks

Set the default in your config:

# ~/.codex/config.toml
approval_policy = "on-request"
model = "o4-mini"

You can also switch modes mid-session using the /mode slash command (/mode suggest, /mode auto-edit, /mode full-auto). For CI pipelines, full-auto makes sense. For day-to-day development, auto-edit is the right balance: it writes code freely but asks before running shell commands.

Scoped AGENTS.md for monorepos

Monorepos benefit from scoped AGENTS.md files. Instead of one giant instructions file that tries to cover everything, you put conventions where they're relevant:

project-root/
  AGENTS.md              # Monorepo-wide: tooling, branching, commit style
  packages/
    api/
      AGENTS.md          # API-specific: Fastify patterns, DB access rules
    web/
      AGENTS.md          # Frontend-specific: React conventions, Tailwind rules
    shared/
      AGENTS.md          # Shared package: export patterns, versioning rules

Codex CLI reads the hierarchy: when working in packages/api/src/, it loads all three AGENTS.md files and merges the context. The more specific file takes precedence for conflicts.

This approach scales. Members of a 10-person team can each maintain the AGENTS.md for their domain without it becoming unwieldy.

Comparing Codex CLI instructions to other AI tools

If you're coming from Cursor or Claude Code, the AGENTS.md concept is analogous to .cursor/rules/ or CLAUDE.md, but there are meaningful differences:

FeatureCodex CLI (AGENTS.md)Cursor (.cursor/rules/)Claude Code (CLAUDE.md)
FormatPlain Markdown.mdc with frontmatterPlain Markdown
ScopingDirectory hierarchyGlob patternsDirectory hierarchy
Global config~/.codex/AGENTS.md~/.cursor/rules/~/.claude/CLAUDE.md
Tool-specificYesYesYes

The philosophy is similar across tools, but the syntax differs enough that maintaining separate files for each tool is a real burden. See our guide on using AI coding rules across tools for a deeper comparison, or Cursor vs Claude Code vs Windsurf if you're still choosing a primary tool.

For teams running multiple AI tools in parallel, maintaining consistent instructions across AGENTS.md, CLAUDE.md, and .cursor/rules/ is a solved problem. Read about best practices for AI coding rules to avoid common pitfalls.

Advanced Codex CLI configuration

Sandboxing

Codex CLI can run in a sandboxed environment that restricts filesystem and network access. This is useful in CI or when running untrusted tasks:

# macOS: uses Apple's Seatbelt (sandbox-exec)
# Linux: uses Landlock + seccomp
codex --sandbox workspace-write "run the full test suite and fix any failures"

The --sandbox flag accepts three levels: read-only (model commands can only read), workspace-write (writes allowed in the current directory), and danger-full-access (unrestricted). In workspace-write mode, Codex CLI can only write to the current working directory, which limits the blast radius of mistakes.

Model selection

Different tasks benefit from different models:

# Fast iteration, quick fixes
codex --model o4-mini "fix the TypeScript error in src/auth.ts"

# Complex reasoning, architectural changes
codex --model o3 "refactor the payment system to support multiple providers"

You can set a per-project default in .codex/config.toml:

# .codex/config.toml (project-level)
model = "o4-mini"

Working with additional directories

For tasks that need write access beyond the current directory, use --add-dir:

# Grant write access to an additional directory
codex --add-dir ../shared "update the shared types to match the new API schema"

You can also reference specific files directly in your prompt — Codex CLI can read any file in the project. For providing persistent context, use your AGENTS.md file to point Codex to key files it should always consider.

Sharing and versioning AGENTS.md files

Here's the collaboration challenge: your AGENTS.md files encode institutional knowledge. New team members need them. Multiple repos need the same conventions. And as your practices evolve, you need a way to propagate updates.

Committing AGENTS.md to git handles single-repository sharing, but what about:

  • The same coding standards across 20 microservices?
  • A company-wide TypeScript style guide that feeds Codex CLI, Cursor, and Claude Code?
  • Open-source conventions you want to share publicly?

localskills.sh is a registry for exactly this. Publish your AGENTS.md as a skill, and anyone can install it:

# Install the CLI
npm install -g @localskills/cli

# Publish your AGENTS.md as a versioned skill
localskills publish

# Install a shared skill into Codex CLI's config
localskills install your-team/api-conventions --target codex

Skills are versioned, so you can pin to a specific version across repos and update on your own schedule. The publish your first skill guide walks through the full workflow.

For teams using multiple AI tools, one skill publishes to all of them:

# Same conventions in Codex CLI, Cursor, and Claude Code
localskills install your-team/api-conventions --target codex cursor claude

The registry handles format differences automatically. Your conventions stay in one place; each tool gets the right format.


Ready to level up your Codex CLI setup? Share your AGENTS.md across tools and teams with a single command. Create a free account and publish your first skill today.

npm install -g @localskills/cli
localskills login
localskills publish