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
| Type | Default variant |
|---|---|
SandboxMode | SandboxMode::WorkspaceWrite |
ApprovalPolicy | ApprovalPolicy::OnRequest |
§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
| Command | CLI equivalent |
|---|---|
ExecCommand | codex exec <prompt> |
ExecResumeCommand | codex exec resume |
ReviewCommand | codex exec review |
ResumeCommand | codex resume |
ForkCommand | codex fork |
LoginCommand | codex login |
LoginStatusCommand | codex login status |
LogoutCommand | codex logout |
McpListCommand | codex mcp list |
McpGetCommand | codex mcp get |
McpAddCommand | codex mcp add |
McpRemoveCommand | codex mcp remove |
McpLoginCommand | codex mcp login |
McpLogoutCommand | codex mcp logout |
McpServerCommand | codex mcp-server |
CompletionCommand | codex completion |
SandboxCommand | codex sandbox |
ApplyCommand | codex apply |
ArchiveCommand | codex archive |
DeleteCommand | codex delete |
UnarchiveCommand | codex unarchive |
DoctorCommand | codex doctor |
UpdateCommand | codex update |
PluginAddCommand | codex plugin add |
PluginListCommand | codex plugin list |
PluginRemoveCommand | codex plugin remove |
PluginMarketplaceAddCommand | codex plugin marketplace add |
PluginMarketplaceListCommand | codex plugin marketplace list |
PluginMarketplaceUpgradeCommand | codex plugin marketplace upgrade |
PluginMarketplaceRemoveCommand | codex plugin marketplace remove |
FeaturesListCommand | codex features list |
FeaturesEnableCommand | codex features enable |
FeaturesDisableCommand | codex features disable |
VersionCommand | codex --version |
RawCommand | Escape 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
ExecCommand::execute_cancellable and
ExecResumeCommand::execute_cancellable accept an explicit cancellation
future. They terminate the owned process group and await the direct child
before returning. Buffered client timeouts use the same settled cleanup
path.
Dropping an ordinary command future is an abrupt fallback. It kills the
direct child and, on Unix, the owned process group, but Drop cannot await
reaping. A supervisor that needs terminal settlement should signal a
cancellable method and keep polling it until it returns.
Process groups are Unix-only. Elsewhere explicit cancellation kills and awaits the direct child, but cannot guarantee descendant cleanup.
§Features
json(enabled by default) - JSONL output parsing viaserde_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
codexbinary, 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 execcommands. - 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.
- Codex
Builder - Builder for creating a
Codexclient.