Skip to main content

What is the Codex SDK?

The Codex TypeScript SDK allows you to programmatically embed the Codex agent into your workflows and applications. It wraps the codex CLI from @openai/codex, spawning the CLI process and exchanging JSONL events over stdin/stdout. With the SDK, you can:
  • Start and manage conversation threads with the Codex agent
  • Execute autonomous coding tasks programmatically
  • Stream real-time events as the agent works (tool calls, file changes, responses)
  • Get structured JSON output conforming to your schemas
  • Resume previous conversations from persisted sessions
  • Control sandbox modes, working directories, and approval policies

When to Use the SDK

The TypeScript SDK is ideal for:

Automation Workflows

Integrate Codex into CI/CD pipelines, automated testing, or deployment workflows

Custom Applications

Build custom development tools and IDEs with embedded AI assistance

Batch Processing

Process multiple repositories or tasks in parallel with programmatic control

Structured Output

Extract structured data or generate reports that conform to specific schemas

Key Concepts

Codex Client

The Codex class is the main entry point. It manages the underlying CLI process and configuration:
import { Codex } from "@openai/codex-sdk";

const codex = new Codex({
  baseUrl: "https://api.openai.com/v1",
  apiKey: process.env.OPENAI_API_KEY,
});

Threads

A Thread represents a conversation with the agent. Threads persist across multiple turns and are saved in ~/.codex/sessions:
const thread = codex.startThread();

Turns

A turn is a single interaction where you provide input and the agent responds. Each turn can involve multiple tool calls, file changes, and reasoning steps:
const turn = await thread.run("Fix the failing tests");
console.log(turn.finalResponse);

Events

The SDK emits structured events as the agent works. Use runStreamed() to access these events in real-time:
const { events } = await thread.runStreamed("Analyze this codebase");

for await (const event of events) {
  switch (event.type) {
    case "item.completed":
      console.log("Completed:", event.item);
      break;
    case "turn.completed":
      console.log("Usage:", event.usage);
      break;
  }
}

Core Capabilities

Use run() to execute a turn and wait for the complete result with all items buffered.
Use runStreamed() to receive real-time events including tool calls, file changes, and progress updates.
Provide a JSON schema to get agent responses in structured format instead of natural language.
Attach local images alongside text prompts for visual analysis and debugging.
Resume conversations from previous sessions using thread IDs.
Configure sandbox modes from read-only to full file system access.

Next Steps

Installation

Install the SDK and set up your environment

Usage Guide

Learn how to use the SDK with detailed examples