# Codex

Run OpenAI's GPT models on the Codex harness with a ChatGPT login, an OpenAI API key, or a Responses gateway.

## Overview

The Codex harness runs OpenAI's models with Codex's own prompts and tools. Each model family runs on the harness its vendor built for it, so a GPT model receives the instructions and tool shapes it was trained on.

An `OpenAi` client carries the credentials and the default model. `Nanocode::builder().openai(client)` adds the harness to the runtime, and `.backend::<Codex>()` spawns an agent on it.

#### Rust

```rust
use nanocode::{Codex, Model, Nanocode, OpenAi};

// 1. Sign requests with the ChatGPT login that /login codex stores
let runtime = Nanocode::builder()
    .openai(OpenAi::default())
    .build_async()
    .await?;

// 2. Spawn a Codex agent on Luna
let (agent, _events) = runtime
    .spawn()
    .backend::<Codex>()
    .model(Model::Luna)
    .build()
    .await?;
```

#### TypeScript

```ts
// A Codex session over the Responses API. dispatch adds the key.
await runtime.open(
  {
    endpoint: 'https://api.openai.com/v1',
    model: 'gpt-6-luna',
    provider: 'codex',
    scope: 'owner',
    session_id: Contracts.sessionUuid(),
    subscription: false,
  },
  {
    dispatch: (request, signal) =>
      fetch(request.endpoint, {
        body: request.body as Uint8Array<ArrayBuffer>,
        headers: [
          ...request.headers,
          ['authorization', `Bearer ${process.env.OPENAI_API_KEY}`],
        ],
        method: 'POST',
        redirect: 'error',
        signal,
      }),
  },
)
```

## Walkthrough

The steps below sign in with a ChatGPT plan and run one Codex turn from Rust.

### Sign In

Start `nc` and run `/login codex`. The command opens the ChatGPT sign-in page and saves the login to `auth.json` in the nanocode home, which is `~/.nanocode` unless `NANOCODE_HOME` is set.

```bash
# 1. Open the terminal UI on a Codex model
nc -m gpt-6-luna

# 2. Inside nc, sign in with the ChatGPT plan
/login codex
```

### Run the Agent

`OpenAi::default()` uses `OpenAiAuth::chatgpt()`, which reads that login when the first request needs it. A missing login returns `OpenAiAuthError::LoginRequired`.

```rust title="main.rs"
use nanocode::{Codex, Model, Nanocode, OpenAi};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>>
{
    // 1. Build the runtime with the ChatGPT login
    let runtime = Nanocode::builder()
        .openai(OpenAi::default())
        .build_async()
        .await?;

    // 2. Spawn a Codex agent and run one turn
    let (agent, _events) = runtime
        .spawn()
        .backend::<Codex>()
        .model(Model::Luna)
        .build()
        .await?;
    let result = agent
        .prompt("Name the harness in one sentence.")
        .await?
        .await?;
    println!("{}", result.final_message());

    runtime.shutdown().await?;
    Ok(())
}
```

## Recipes

### Pick a Model

`Model` lists the Codex harness models. `Model::default()` is `Model::Astra`, and `FromStr` accepts the identifier or a short name such as `"luna"`.

| Variant | Identifier    |
| ------- | ------------- |
| `Astra` | `gpt-6-astra` |
| `Luna`  | `gpt-6-luna`  |
| `Sol`   | `gpt-6.1-sol` |

GLM, Kimi, and MiMo also run on the Codex harness. [Models and Types](/docs/api/rust/types#model) lists every variant with its thinking levels.

```bash
# List the models of every harness with their thinking levels
nc models
```

### Use an API Key

`OpenAiAuth::api_key` signs requests with an OpenAI API key. The client then uses `https://api.openai.com/v1`.

```rust
use nanocode::codex::auth::OpenAiAuth;
use nanocode::OpenAi;

// Read the key from the environment
let openai = OpenAi::builder(OpenAiAuth::api_key(std::env::var(
    "OPENAI_API_KEY",
)?))
.build()?;
```

In `nc`, an API key applies to a custom endpoint. `NANOCODE_OPENAI_BASE_URL` sets the Responses API base URL. The key comes from `NANOCODE_OPENAI_API_KEY`, then `OPENAI_API_KEY`.

```bash
# Send Codex requests to the OpenAI API with a key
NANOCODE_OPENAI_BASE_URL=https://api.openai.com/v1 OPENAI_API_KEY=... nc -m gpt-6-luna
```

### Use a Gateway

A `ResponsesGateway` sends Codex requests through OpenRouter, Vercel AI Gateway, or Cloudflare AI Gateway. [Model Gateways](/docs/guides/gateways) covers each gateway and its credentials.

```rust
use nanocode::codex::{auth::OpenAiAuth, transport::ResponsesGateway};
use nanocode::OpenAi;

// Route Codex through OpenRouter with an OpenRouter key
let openai = OpenAi::builder(OpenAiAuth::api_key(std::env::var(
    "OPENROUTER_API_KEY",
)?))
.responses_gateway(ResponsesGateway::openrouter())
.build()?;
```

`--gateway` selects a gateway in `nc`. Its values are `openrouter`, `vercel`, `cloudflare`, and `cloudflare-gateway`.

```bash
# Run nc through OpenRouter
OPENROUTER_API_KEY=... nc --gateway openrouter -m gpt-6-luna
```

### Use a Custom Endpoint

If `NANOCODE_OPENAI_BASE_URL` is set without a key, `nc` uses `OpenAiAuth::gateway_managed()`, and the endpoint adds the credential. `NANOCODE_MODELS_URL` lists the endpoint's models. It defaults to the base URL followed by `/models`.

```bash
# A gateway that holds the provider key itself
NANOCODE_OPENAI_BASE_URL=https://llm.example.com/v1 nc
```

## More

- [Claude](/docs/models/claude): Run Anthropic's models on the Claude harness.

- [Google](/docs/models/google): Run Gemini models on the Antigravity harness.

- [Model Gateways](/docs/guides/gateways): Send Codex models through third-party gateways.

- [OpenAi](/docs/api/rust/OpenAi): Reference for the Codex client builder.
