Experimental TypeScript client for the OpenAI Codex native runtime.
This will not conflict with Codex system CLI
π Architecture Documentation - Detailed system design and component overview
- Native Rust Integration β Direct NAPI bindings to codex-rs for maximum performance and CLI compatibility
- Cloud Tasks (NEW v0.1.0) β Remote code generation with best-of-N attempts and local patch application
- Multi-Conversation Management β Orchestrate concurrent conversations with automatic lifecycle management and resumption
- Session Persistence & Replay β Record conversations to JSONL/JSON and resume from any point with full state restoration
- Real-Time Rate Monitoring β Live rate limit tracking with visual progress indicators and usage projections
- Enterprise-Ready Architecture β Connection pooling, retry logic, plugin system, and comprehensive error handling
- Type-Safe Streaming β Fully typed event streams with async iterators and automatic cleanup
This SDK requires a specific codex-rs release tag from https://github.com/openai/codex/tags:
- v0.0.7: Use
rust-v0.42.0for core features - v0.1.0+: Use
rust-v0.45.0or later for cloud tasks support
The Rust toolkit is required for building the native bindings: https://rust-lang.org/tools/install
CODEX_RUST_ROOT=/absolute/path/to/codex/codex-rsβ points at the checked-out codex-rs release tag sonpm run setupcan read its version. Specifying this means the SDK will not conflict with any system-installed codex CLI. Once npm run setup is run, this is no longer required.CODEX_HOME=~/.codexβ tells the runtime where to store credentials and session data (the default is fine).
Setting environment variables:
- macOS/Linux:
export CODEX_HOME="~/.codex" - Windows PowerShell:
Set-Item env:CODEX_HOME "$env:USERPROFILE\.codex"
npm run setup installs dependencies, rebuilds the TypeScript bundle, recompiles the native binding, and verifies that the embedded version matches your codex checkout. The loader automatically uses the freshly compiled native/codex-napi/index.node, so there is no environment flag to manage afterward.
Run the installer:
npm run setupimport { CodexClient, CodexClientBuilder } from 'codex-ts-sdk';
const client = new CodexClientBuilder()
.withCodexHome(process.env.CODEX_HOME!)
.withSandboxPolicy({ mode: 'workspace-write', network_access: false })
.withApprovalPolicy('on-request')
.build();
await client.connect();
await client.createConversation();
await client.sendUserTurn('List the steps for safe git rebases.');
for await (const event of client.events()) {
console.log(event.msg);
}Simple Bundled Example: Monitor your Plan-Based Codex rate limits with visual ASCII charts and usage projections:
node examples/live-rate-limits.cjsConnecting and fetching live data...
Current Rate Limits
Primary (gpt-4.1-mini per-week):
[ββββββββββββββββββββββββββ---------------Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·] 58% (~8.4%/day)
Window: 2025-09-20 08:41 β 2025-09-27 08:41
Safe - won't hit 100% before reset
Secondary (gpt-4.1-mini per-day):
[βββββββββββββββββββββββββββ!-----------Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·] 83%
Projected 100%: 2025-09-26 19:07
To persist an API key for the native runtime, call loginWithApiKey once (this mirrors codex login --api-key ...):
import { loginWithApiKey } from 'codex-ts-sdk';
loginWithApiKey(process.env.OPENAI_API_KEY!, { codexHome: process.env.CODEX_HOME });If you prefer the browser-based ChatGPT OAuth flow, run codex login from the CLI instead.
NEW in v0.1.0: Manage remote Codex tasks for code generation workflows.
Cloud tasks enable you to submit prompts to a cloud backend, execute code generation remotely, and retrieve/apply the results locally. Perfect for distributed teams and cloud-based development workflows.
import { CloudTasksClientBuilder } from 'codex-ts-sdk/cloud';
const client = new CloudTasksClientBuilder()
// baseUrl optional; defaults to process.env.CODEX_CLOUD_TASKS_BASE_URL
// or 'https://chatgpt.com/backend-api' (codex-rs default)
.withBearerToken(process.env.OPENAI_API_KEY!)
.build();
// Create a remote task
const task = await client.createTask({
environmentId: 'prod',
prompt: 'Add error handling to the authentication endpoints',
gitRef: 'main',
bestOfN: 3, // Generate 3 attempts, select the best
});
console.log(`Task created: ${task.id}`);
// Wait for completion (poll)
let tasks;
do {
tasks = await client.listTasks({ limit: 1 });
await new Promise(resolve => setTimeout(resolve, 2000));
} while (tasks[0]?.status === 'pending');
// Get the generated diff
const diff = await client.getTaskDiff(task.id);
console.log('Generated changes:', diff);
// Preview before applying
const preflight = await client.applyTaskPreflight(task.id);
if (preflight.status === 'success') {
// Apply to local working tree
const result = await client.applyTask(task.id);
console.log(result.message);
} else {
console.warn('Conflicts detected:', preflight.conflictPaths);
}
client.close();- Remote Execution β Submit prompts to cloud infrastructure, retrieve results
- Best-of-N β Generate multiple solution attempts, compare and select the best
- Diff Management β Retrieve unified diffs and apply them locally with conflict detection
- Multi-Environment β Organize tasks across different environments (prod, staging, dev)
- Preflight Validation β Dry-run patch application before modifying files
# Basic task management
node examples/cloud-tasks-basic.cjs
# Best-of-N workflow with multiple attempts
node examples/cloud-tasks-best-of-n.cjs
# Safe patch application with conflict handling
node examples/cloud-tasks-apply.cjs- π Cloud Tasks API Reference - Complete API documentation
- π Migration Guide - Upgrading from v0.0.7
npm run setupβ Complete SDK setup: install dependencies, discover codex-rs version, build native bindings, and run smoke tests. RequiresCODEX_RUST_ROOTenvironment variable pointing to your codex-rs checkout.npm run build:nativeβ Compile the Rust NAPI bindings only. Faster than full setup when you just need to rebuild native code.npm run packageβ Full build pipeline: TypeScript compilation (ESM/CJS), type definitions, and native bindings. Used for publishing.
npm run test:live:statusβ Live integration test that connects to Codex runtime, sends a conversation turn, and validates rate limit monitoring. Requires active authentication (viacodex loginor API key).npm run test:live:authβ Authentication system test that verifies API key functionality works correctly, especially when ChatGPT OAuth is already active. Uses intentionally invalid keys to test failure paths.npm run testβ Run full test suite (unit tests only, no live API calls)npm run coverageβ Generate test coverage report
npm run lintβ Run ESLint on source codenpm run typecheckβ TypeScript compilation check without output generation