Skip to main content

Crate codex_wrapper

Crate codex_wrapper 

Source
Expand description

A type-safe Codex CLI wrapper for Rust.

codex-wrapper provides a builder-pattern interface for invoking the codex CLI programmatically. It follows the same design philosophy as claude-wrapper and docker-wrapper: each CLI subcommand is a builder struct that produces typed output.

§Quick Start

use codex_wrapper::{Codex, CodexCommand, ExecCommand, SandboxMode};

let codex = Codex::builder().build()?;

let output = ExecCommand::new("summarize this repository")
    .sandbox(SandboxMode::WorkspaceWrite)
    .ephemeral()
    .execute(&codex)
    .await?;

println!("{}", output.stdout);

§Defaults

§Two-Layer Builder

The Codex client holds shared config (binary path, env vars, timeout, retry policy). Command builders hold per-invocation options and call execute(&codex).

use codex_wrapper::{Codex, CodexCommand, ExecCommand, RetryPolicy};

// Configure once, reuse across commands
let codex = Codex::builder()
    .env("OPENAI_API_KEY", "sk-...")
    .timeout_secs(300)
    .retry(RetryPolicy::new().max_attempts(3).exponential())
    .build()?;

// Each command is a separate builder
let output = ExecCommand::new("fix the failing tests")
    .model("o3")
    .sandbox(codex_wrapper::SandboxMode::WorkspaceWrite)
    .skip_git_repo_check()
    .ephemeral()
    .execute(&codex)
    .await?;

§JSONL Output Parsing

Use execute_json_lines() to get structured events from --json mode:

use codex_wrapper::{Codex, ExecCommand};

let codex = Codex::builder().build()?;
let events = ExecCommand::new("what is 2+2?")
    .ephemeral()
    .execute_json_lines(&codex)
    .await?;

for event in &events {
    println!("{}: {:?}", event.event_type, event.extra);
}

§Child Environment Policy

Child processes inherit the wrapper process’s environment by default. CodexBuilder::clear_env opts into clearing that environment before applying entries from CodexBuilder::env and CodexBuilder::envs. The setting controls the direct child’s environment, not same-user access to files, process metadata, sockets, or other OS resources.

§Available Commands

CommandCLI equivalent
ExecCommandcodex exec <prompt>
ExecResumeCommandcodex exec resume
ReviewCommandcodex exec review
ResumeCommandcodex resume
ForkCommandcodex fork
LoginCommandcodex login
LoginStatusCommandcodex login status
LogoutCommandcodex logout
McpListCommandcodex mcp list
McpGetCommandcodex mcp get
McpAddCommandcodex mcp add
McpRemoveCommandcodex mcp remove
McpLoginCommandcodex mcp login
McpLogoutCommandcodex mcp logout
McpServerCommandcodex mcp-server
CompletionCommandcodex completion
SandboxCommandcodex sandbox
ApplyCommandcodex apply
ArchiveCommandcodex archive
DeleteCommandcodex delete
UnarchiveCommandcodex unarchive
DoctorCommandcodex doctor
UpdateCommandcodex update
PluginAddCommandcodex plugin add
PluginListCommandcodex plugin list
PluginRemoveCommandcodex plugin remove
PluginMarketplaceAddCommandcodex plugin marketplace add
PluginMarketplaceListCommandcodex plugin marketplace list
PluginMarketplaceUpgradeCommandcodex plugin marketplace upgrade
PluginMarketplaceRemoveCommandcodex plugin marketplace remove
FeaturesListCommandcodex features list
FeaturesEnableCommandcodex features enable
FeaturesDisableCommandcodex features disable
VersionCommandcodex --version
RawCommandEscape hatch for arbitrary args

§Error Handling

All commands return Result<T>, with typed errors via thiserror:

use codex_wrapper::{Codex, CodexCommand, ExecCommand, Error};

let codex = Codex::builder().build()?;
match ExecCommand::new("test").execute(&codex).await {
    Ok(output) => println!("{}", output.stdout),
    Err(Error::CommandFailed { stderr, exit_code, .. }) => {
        eprintln!("failed (exit {}): {}", exit_code, stderr);
    }
    Err(Error::Timeout { .. }) => eprintln!("timed out"),
    Err(e) => eprintln!("{e}"),
}

§Cancellation

Dropping the future returned by a command kills the spawned codex process. That covers a timeout, an aborted task, and a caller that stops awaiting during a graceful shutdown: cancelling the future cancels the work, rather than leaving codex running and billing with no handle left to stop it.

Two limits are worth knowing:

  • The kill reaps the codex process itself. Subprocesses codex spawned for tool use are not signalled and can outlive it.
  • Reaping needs the tokio runtime to still be running. A future dropped as part of runtime shutdown may not get far enough to kill the child.

§Features

  • json (enabled by default) - JSONL output parsing via serde_json

Re-exports§

pub use auth::AuthStatus;
pub use auth::AuthStrategy;
pub use budget::TokenBudget;
pub use budget::TokenBudgetBuilder;
pub use command::CodexCommand;
pub use command::apply::ApplyCommand;
pub use command::completion::CompletionCommand;
pub use command::completion::Shell;
pub use command::doctor::DoctorCommand;
pub use command::exec::ExecCommand;
pub use command::exec::ExecResumeCommand;
pub use command::features::FeaturesDisableCommand;
pub use command::features::FeaturesEnableCommand;
pub use command::features::FeaturesListCommand;
pub use command::fork::ForkCommand;
pub use command::login::LoginCommand;
pub use command::login::LoginStatusCommand;
pub use command::login::LogoutCommand;
pub use command::mcp::McpAddCommand;
pub use command::mcp::McpGetCommand;
pub use command::mcp::McpListCommand;
pub use command::mcp::McpLoginCommand;
pub use command::mcp::McpLogoutCommand;
pub use command::mcp::McpRemoveCommand;
pub use command::mcp_server::McpServerCommand;
pub use command::plugin::PluginAddCommand;
pub use command::plugin::PluginListCommand;
pub use command::plugin::PluginMarketplaceAddCommand;
pub use command::plugin::PluginMarketplaceListCommand;
pub use command::plugin::PluginMarketplaceRemoveCommand;
pub use command::plugin::PluginMarketplaceUpgradeCommand;
pub use command::plugin::PluginRemoveCommand;
pub use command::raw::RawCommand;
pub use command::resume::ResumeCommand;
pub use command::review::ReviewCommand;
pub use command::sandbox::SandboxCommand;
pub use command::session_mgmt::ArchiveCommand;
pub use command::session_mgmt::DeleteCommand;
pub use command::session_mgmt::UnarchiveCommand;
pub use command::update::UpdateCommand;
pub use command::version::VersionCommand;
pub use config::CodexConfig;
pub use error::Error;
pub use error::FailureKind;
pub use error::Result;
pub use exec::CommandOutput;
pub use history::SessionFile;
pub use history::SessionLog;
pub use history::SessionMeta;
pub use history::SessionQuery;
pub use mcp_config::McpConfigBuilder;
pub use mcp_config::McpServerConfig;
pub use retry::BackoffStrategy;
pub use retry::RetryPolicy;
pub use rollout_budget::RolloutBudgetConfig;
pub use rollout_budget::RolloutBudgetConfigBuilder;
pub use session::Session;
pub use session::TurnRecord;
pub use version::CliVersion;
pub use version::CliVersionStatus;
pub use version::TESTED_CLI_VERSION_MAX;
pub use version::TESTED_CLI_VERSION_MIN;
pub use version::VersionParseError;
pub use types::*;

Modules§

auth
Which credential the CLI would use, without spawning it.
budget
Cumulative token budget tracking across turns.
command
Command builders for every Codex CLI subcommand.
config
Read-side access to $CODEX_HOME/config.toml.
dangerous
Opt-in access to the flags that disable codex’s safety controls.
error
Error types for codex-wrapper.
exec
Process execution layer for spawning and communicating with the codex binary, including timeout and retry support.
history
Read-side access to the CLI’s on-disk session logs.
mcp_config
Build MCP server configuration for a single run, without touching the user’s persistent config.
retry
rollout_budget
Native per-execution rollout-budget configuration.
session
Stateful multi-turn session manager for the Codex CLI.
streaming
Streaming execution for codex exec commands.
types
Domain types shared across commands: enums for CLI options, version parsing, and structured JSONL events.
version
Version parsing and comparison utilities.

Structs§

Codex
Shared Codex CLI client configuration.
CodexBuilder
Builder for creating a Codex client.