Expand description
Async helper around the OpenAI Codex CLI for programmatic prompting, streaming, apply/diff helpers, and server flows.
Shells out to codex exec, applies sane defaults (non-interactive color handling, timeouts, model hints), and surfaces single-response, streaming, apply/diff, and MCP/app-server helpers.
§Setup: binary + CODEX_HOME
- Defaults pull
CODEX_BINARYorcodexonPATH; callCodexClientBuilder::binary(optionally fed byresolve_bundled_binary) to pin an app-bundled binary without touching user installs. - Isolate state with
CodexClientBuilder::codex_home(config/auth/history/logs live under that directory) and optionally create the layout withCodexClientBuilder::create_home_dirs.CodexHomeLayoutinspectsconfig.toml,auth.json,.credentials.json,history.jsonl,conversations/, andlogs/. CodexHomeLayout::seed_auth_fromcopiesauth.json/.credentials.jsonfrom a trusted seed home into an isolatedCODEX_HOMEwithout touching history/logs; useAuthSeedOptionsto require files or skip missing ones.AuthSessionHelpercheckscodex login statusand can launch ChatGPT or API key login flows with an app-scopedCODEX_HOMEwithout mutating the parent process env.- Wrapper defaults: temp working dir per call unless
working_diris set,--skip-git-repo-check, 120s timeout (useDuration::ZEROto disable), ANSI colors off,RUST_LOG=errorif unset. - Model defaults:
gpt-5*/gpt-5.1*(including codex variants) getmodel_reasoning_effort="medium"/model_reasoning_summary="auto"/model_verbosity="low"to avoid unsupported “minimal” combos.
§Bundled binary (Workstream J)
- Apps can ship Codex inside an app-owned bundle rooted at e.g.
~/.myapp/codex-bin/<platform>/<version>/codex;resolve_bundled_binaryresolves that path without ever falling back toPATHorCODEX_BINARY. Hosts own downloads and version pins; missing bundles are hard errors. - Pair bundled binaries with per-project
CODEX_HOMEroots such as~/.myapp/codex-homes/<project>/, optionally seedingauth.json+.credentials.jsonfrom an app-owned seed home. History/logs remain per project; the wrapper still injectsCODEX_BINARY/CODEX_HOMEper spawn so the parent env stays untouched. - Default behavior remains unchanged until the helper is used; env/CLI defaults stay as documented above.
use codex::CodexClient;
std::env::set_var("CODEX_HOME", "/tmp/my-app-codex");
let client = CodexClient::builder()
.binary("/opt/myapp/bin/codex")
.model("gpt-5-codex")
.timeout(Duration::from_secs(45))
.build();
let reply = client.send_prompt("Health check").await?;
println!("{reply}");Surfaces:
CodexClient::send_promptfor a single prompt/response with optional--jsonoutput.CodexClient::stream_execfor typed, real-time JSONL events fromcodex exec --json, returning anExecStreamwith an event stream plus a completion future.CodexClient::apply/CodexClient::diffto runcodex apply <TASK_ID>andcodex cloud diff <TASK_ID>, echo stdout/stderr according to the builder (mirror_stdout/quiet), and return captured output + exit status.CodexClient::generate_app_server_bindingsto refresh app-server protocol bindings viacodex app-server generate-ts(optional--prettier) orgenerate-json-schema, returning captured stdout/stderr plus the exit status.CodexClient::run_sandboxto wrapcodex sandbox <platform>(macOS/Linux/Windows), pass--full-auto/--log-denials/--config/--enable/--disable, and return the inner command status + output. macOS is the only platform that emits denial logs; Linux depends on the bundledcodex-linux-sandbox; Windows sandboxing is experimental and relies on the upstream helper (no capability gating—non-zero exits bubble through).CodexClient::check_execpolicyto evaluate shell commands against Starlark execpolicy files with repeatable--policyflags, optional pretty JSON, and parsed decision output (allow/prompt/forbidden or noMatch).CodexClient::list_featuresto wrapcodex features listwith optional--jsonparsing, shared config/profile overrides, and parsed feature entries (name/stage/enabled).CodexClient::start_responses_api_proxyto launch thecodex responses-api-proxyhelper with an API key piped via stdin plus optional port/server-info/upstream/shutdown flags.CodexClient::stdio_to_udsto spawncodex stdio-to-uds <SOCKET_PATH>with piped stdio so callers can bridge Unix domain sockets manually.
§Streaming, events, and artifacts
.json(true)requests JSONL streaming. Expectthread.started/thread.resumed,turn.started/turn.completed/turn.failed, anditem.created/item.updatedwithitem.typesuch asagent_message,reasoning,command_execution,file_change,mcp_tool_call,web_search, ortodo_listplus optionalstatus/content/input. Errors surface as{"type":"error","message":...}.- Sample payloads ship with the streaming examples (
crates/codex/examples/fixtures/*); most examples support--samplefor offline inspection. - Disable
mirror_stdoutwhen parsing JSON so stdout stays under caller control;quietcontrols stderr mirroring.json_event_logtees raw JSONL lines to disk before parsing;idle_timeout,output_last_message, andoutput_schemacover artifact handling. crates/codex/examples/stream_events.rs,stream_last_message.rs,stream_with_log.rs, andjson_stream.rscover typed consumption, artifact handling, log teeing, and minimal streaming.
§Resume + apply/diff
codex exec --json resume --last [-]streams the samethread/turn/itemevents ascodex exec --jsonbut starts from an existing session (thread.resumed).- Apply/diff require task IDs:
codex apply <TASK_ID>applies a diff, andcodex cloud diff <TASK_ID>prints a cloud task diff when supported by the binary. - Convenience:
CodexClient::apply/CodexClient::diffwill append<TASK_ID>fromCODEX_TASK_IDwhen set; otherwise they still spawn the command and return the non-zero exit status/output from the CLI. crates/codex/examples/resume_apply.rsshows a CLI-native resume/apply flow and ships--samplefixtures for offline inspection.
§Servers and capability detection
- Integrate the stdio servers via
codex mcp-server/codex app-server(crates/codex/examples/mcp_codex_flow.rs,mcp_codex_tool.rs,mcp_codex_reply.rs,app_server_turns.rs,app_server_thread_turn.rs) to drive JSON-RPC flows, approvals, and shutdown. probe_capabilitiesand thefeature_detectionexample focus on--output-schema,--add-dir,codex login --mcp, andcodex features listavailability; other subcommand drift (like cloud-only commands) is surfaced by the parity snapshot/reports incli_manifests/codex/.
More end-to-end flows and CLI mappings live in crates/codex/README.md and crates/codex/EXAMPLES.md.
§Capability/versioning surfaces (Workstream F)
probe_capabilitiescaptures--version,features list, and--helphints into aCodexCapabilitiessnapshot withcollected_attimestamps andBinaryFingerprintmetadata keyed by canonical binary path.- Guard helpers (
guard_output_schema,guard_add_dir,guard_mcp_login,guard_features_list) keep optional flags disabled when support is unknown and return operator-facing notes for unsupported features. - Cache controls:
CapabilityCachePolicy::{PreferCache, Refresh, Bypass}plus builder helpers steer cache reuse. UseRefreshfor TTL/backoff windows or hot-swaps that reuse the same binary path; useBypasswhen metadata is missing (FUSE/overlay filesystems) or when you need an isolated probe. - TTL/backoff helper:
capability_cache_ttl_decisioninspectscollected_atto suggest when to reuse, refresh, or bypass cached snapshots and stretches the recommended policy when metadata is missing. - Overrides + persistence:
capability_snapshot,capability_overrides,write_capabilities_snapshot,read_capabilities_snapshot, andcapability_snapshot_matches_binarylet hosts reuse snapshots across processes and fall back to probes when fingerprints diverge.
Re-exports§
pub use jsonl::thread_event_jsonl_file;pub use jsonl::thread_event_jsonl_reader;pub use jsonl::JsonlThreadEventParser;pub use jsonl::ThreadEventJsonlFileReader;pub use jsonl::ThreadEventJsonlReader;pub use jsonl::ThreadEventJsonlRecord;pub use rollout_jsonl::find_rollout_file_by_id;pub use rollout_jsonl::find_rollout_files;pub use rollout_jsonl::rollout_jsonl_file;pub use rollout_jsonl::rollout_jsonl_reader;pub use rollout_jsonl::RolloutBaseInstructions;pub use rollout_jsonl::RolloutContentPart;pub use rollout_jsonl::RolloutEvent;pub use rollout_jsonl::RolloutEventMsg;pub use rollout_jsonl::RolloutEventMsgPayload;pub use rollout_jsonl::RolloutJsonlError;pub use rollout_jsonl::RolloutJsonlFileReader;pub use rollout_jsonl::RolloutJsonlParser;pub use rollout_jsonl::RolloutJsonlReader;pub use rollout_jsonl::RolloutJsonlRecord;pub use rollout_jsonl::RolloutResponseItem;pub use rollout_jsonl::RolloutResponseItemPayload;pub use rollout_jsonl::RolloutSessionMeta;pub use rollout_jsonl::RolloutSessionMetaPayload;pub use rollout_jsonl::RolloutUnknown;
Modules§
- jsonl
- mcp
- Launch and interact with Codex MCP + app servers using stored runtime definitions.
- rollout_
jsonl - wrapper_
coverage_ manifest
Structs§
- AppServer
Codegen Output - Captured output from app-server codegen commands.
- AppServer
Codegen Request - Request for
codex app-server generate-tsorgenerate-json-schema. - Apply
Diff Artifacts - Captured output from task-oriented subcommands such as
codex apply <TASK_ID>orcodex cloud diff <TASK_ID>. - Auth
Seed Options - Options controlling how auth files are seeded from a trusted home.
- Auth
Seed Outcome - Result of seeding Codex auth files into a target home.
- Auth
Session Helper - Helper for checking Codex auth state and triggering login flows with an app-scoped
CODEX_HOME. - Binary
Fingerprint - File metadata used to invalidate cached capability snapshots when the binary changes.
- Bundled
Binary - Resolved bundled Codex binary details.
- Bundled
Binary Spec - Specification for resolving an app-bundled Codex binary.
- Capability
Cache Key - Cache key for capability snapshots derived from a specific Codex binary path.
- Capability
Feature Overrides - Optional overrides for feature detection that can be layered onto probe results.
- Capability
Guard - Result of gating a Codex feature/flag against probed capabilities.
- Capability
Overrides - Caller-supplied capability data that can short-circuit or adjust probing. Manual snapshots override cached/probed data, and feature/version overrides apply on top of whichever snapshot is returned.
- Capability
Probe Plan - Description of how we interrogate the CLI to populate a
CodexCapabilitiessnapshot. - Capability
TtlDecision - Result of applying a TTL/backoff window to a capability snapshot.
- CliOverrides
- Builder-scoped CLI overrides.
- CliOverrides
Patch - Request-level overlay of builder overrides.
- Cloud
Apply Request - Request for
codex cloud apply [--attempt N] <TASK_ID>. - Cloud
Diff Request - Request for
codex cloud diff [--attempt N] <TASK_ID>. - Cloud
Exec Request - Request for
codex cloud exec. - Cloud
List Output - Output from
codex cloud list. - Cloud
List Request - Request for
codex cloud list. - Cloud
Overview Request - Request for
codex cloud(overview/help). - Cloud
Status Request - Request for
codex cloud status <TASK_ID>. - Codex
Capabilities - Snapshot of Codex CLI capabilities derived from probing a specific binary.
- Codex
Client - High-level client for interacting with
codex exec. - Codex
Client Builder - Builder for
crate::CodexClient. - Codex
Feature - Single feature entry reported by
codex features list. - Codex
Feature Flags - Feature gates for Codex CLI flags.
- Codex
Home Layout - Describes the on-disk layout used by the Codex CLI when
CODEX_HOMEis set. - Codex
Latest Releases - Caller-supplied table of known latest Codex releases.
- Codex
Release - Release metadata for a specific Codex build channel.
- Codex
Update Advisory - Update guidance derived from comparing local and latest Codex versions.
- Codex
Version Info - Parsed version details emitted by
codex --version. - Command
Execution Delta - Streaming delta for command execution.
- Command
Execution State - Snapshot of a command execution, including accumulated stdout/stderr.
- Config
Override - Represents a single
--config key=valueoverride. - Debug
AppServer Help Request - Request for
codex debug app-server help [COMMAND].... - Debug
AppServer Request - Request for
codex debug app-server. - Debug
AppServer Send Message V2Request - Request for
codex debug app-server send-message-v2 <USER_MESSAGE>. - Debug
Command Request - Request for
codex debug. - Debug
Help Request - Request for
codex debug help [COMMAND].... - Event
Error - Error payload shared by turn/item failures.
- Exec
Completion - Summary returned when the codex child process exits.
- Exec
Policy Check Request - Request to evaluate a command against Starlark execpolicy files.
- Exec
Policy Check Result - Captured output from
codex execpolicy check. - Exec
Policy Evaluation - Parsed output from
codex execpolicy check. - Exec
Policy Match - Matched execpolicy summary with the merged decision and contributing rules.
- Exec
Policy NoMatch - Response returned when no rules matched.
- Exec
Policy Rule Match - Matched rule entry returned by
codex execpolicy check. - Exec
Request - Options configuring a single exec request.
- Exec
Review Command Request - Request for
codex exec review [OPTIONS] [PROMPT]. - Exec
Stream - Ergonomic container for the streaming surface; produced by
stream_exec(implemented in D2). - Exec
Stream Control - Control-capable variant of
ExecStream, providing a best-effort termination hook. - Exec
Stream Request - Options configuring a streaming exec invocation.
- Exec
Termination Handle - Feature
Toggles - Feature toggles forwarded to
--enable/--disable. - Features
Command Request - Request for
codex features. - Features
Disable Request - Request for
codex features disable <FEATURE>. - Features
Enable Request - Request for
codex features enable <FEATURE>. - Features
List Output - Parsed output from
codex features list. - Features
List Request - Request for
codex features list. - File
Change Delta - Streaming delta describing a file change.
- File
Change State - File change or diff applied by the agent.
- Fork
Session Request - Request for
codex fork [OPTIONS] [SESSION_ID] [PROMPT]. - Help
Command Request - Request for
codex <scope> help [COMMAND].... - Item
Delta - Streaming delta describing the next piece of an item.
- Item
Envelope - Shared wrapper for item events that always include thread/turn context.
- Item
Failure - Terminal item failure event.
- Item
Snapshot - Snapshot of an item at start/completion time.
- McpAdd
Request - Request for
codex mcp add. - McpGet
Request - Request for
codex mcp get <NAME>. - McpList
Output - Output from
codex mcp list. - McpList
Request - Request for
codex mcp list. - McpLogout
Request - Request for
codex mcp logout <NAME>. - McpOauth
Login Request - Request for
codex mcp login <NAME>(OAuth). - McpOverview
Request - Request for
codex mcp(overview/help). - McpRemove
Request - Request for
codex mcp remove <NAME>. - McpTool
Call Delta - Streaming delta for MCP tool call output.
- McpTool
Call State - State of an MCP tool call.
- Reasoning
Overrides - Structured reasoning overrides converted into config entries.
- Responses
ApiProxy Handle - Running responses proxy process and metadata.
- Responses
ApiProxy Info - Parsed
{port,pid}emitted bycodex responses-api-proxy --server-info. - Responses
ApiProxy Request - Request for
codex responses-api-proxy. - Resume
Request - Options configuring a streaming resume invocation.
- Resume
Session Request - Request for
codex resume [OPTIONS] [SESSION_ID] [PROMPT]. - Review
Command Request - Request for
codex review [OPTIONS] [PROMPT]. - Sandbox
Command Request - Request to run an arbitrary command inside a Codex-provided sandbox.
- Sandbox
Run - Captured output from
codex sandbox <platform>. - Stdio
ToUds Request - Request for
codex stdio-to-uds <SOCKET_PATH>. - Text
Content - Human-readable content emitted by the agent.
- Text
Delta - Incremental content fragment for streaming items.
- Thread
Started - Marks the start of a new thread.
- Todo
Item - Single todo item.
- Todo
List Delta - Streaming delta for todo list mutations.
- Todo
List State - Checklist maintained by the agent.
- Turn
Completed - Reports a completed turn.
- Turn
Failed - Indicates a turn-level failure.
- Turn
Started - Indicates the CLI accepted a new turn within a thread.
- WebSearch
Delta - Streaming delta for search results.
- WebSearch
State - Details of a web search step.
Enums§
- AppServer
Codegen Target - Target for app-server code generation.
- Approval
Policy - Approval policy used by
--ask-for-approval. - Auth
Seed Error - Errors that may occur while seeding Codex auth files into a target home.
- Bundled
Binary Error - Errors that may occur while resolving a bundled Codex binary.
- Capability
Cache Policy - Cache interaction policy for capability probes.
- Capability
Feature - Feature/flag tokens that can be guarded based on probed capabilities.
- Capability
Probe Step - Command-level probes used to infer feature support.
- Capability
Snapshot Error - Errors encountered while saving or loading capability snapshots.
- Capability
Snapshot Format - Supported serialization formats for capability snapshots and overrides.
- Capability
Support - High-level view of whether a specific feature can be used safely.
- Codex
Auth Method - Authentication mechanism used to sign in.
- Codex
Auth Status - Current authentication state reported by
codex login status. - Codex
Error - Errors that may occur while invoking the Codex CLI.
- Codex
Feature Stage - Stage labels reported by
codex features list. - Codex
Logout Status - Result of invoking
codex logout. - Codex
Release Channel - Release channel segments inferred from the Codex version string.
- Codex
Update Status - Enum summarizing whether an update is needed based on provided release data.
- Color
Mode - ANSI color behavior for
codex execoutput. - Exec
Policy Decision - Decision returned by execpolicy evaluation.
- Exec
Stream Error - Errors that may occur while consuming the JSONL stream.
- Features
List Format - Format used to parse
codex features listoutput. - File
Change Kind - Type of file operation being reported.
- Flag
State - Three-state flag used when requests can override builder defaults.
- Help
Scope - Selector for
codex help-style command families. - Item
Delta Payload - Delta form of an item payload. Each delta should be applied in order to reconstruct the item.
- Item
Payload - Fully-typed item payload for start/completed events.
- Item
Status - Item status supplied by the CLI for bookkeeping.
- Local
Provider - Local provider selection for OSS backends.
- McpAdd
Transport - Transport for
codex mcp add. - Model
Verbosity - Config values for
model_verbosity. - Reasoning
Effort - Config values for
model_reasoning_effort. - Reasoning
Summary - Config values for
model_reasoning_summary. - Reasoning
Summary Format - Config values for
model_reasoning_summary_format. - Resume
Selector - Selector for
codex resumetargets. - Safety
Override - Safety overrides that collapse approval/sandbox behavior.
- Sandbox
Mode - Sandbox isolation level.
- Sandbox
Platform - Sandbox platform variant; maps to platform subcommands of
codex sandbox. - Thread
Event - Single JSONL event emitted by
codex exec --json. - Tool
Call Status - Lifecycle state for a tool call.
- WebSearch
Status - Search progress indicator.
Functions§
- capability_
cache_ entries - Returns all capability cache entries keyed by canonical binary path.
- capability_
cache_ entry - Returns the cached capabilities for a specific binary path if present.
- capability_
cache_ ttl_ decision - Decides whether a cached capability snapshot should be refreshed based on
collected_at. - capability_
snapshot_ matches_ binary - True when the snapshot was captured for the same binary path and fingerprint.
- clear_
capability_ cache - Clears all cached capability snapshots.
- clear_
capability_ cache_ entry - Removes the cached capabilities for a specific binary. Returns true when an entry was removed.
- default_
bundled_ platform_ label - Default bundled platform label for the current target (e.g.,
darwin-arm64,linux-x64,windows-x64). - deserialize_
capabilities_ snapshot - Parses a capability snapshot from serialized JSON or TOML.
- deserialize_
capability_ overrides - Parses capability overrides from serialized JSON or TOML.
- read_
capabilities_ snapshot - Loads a capability snapshot from disk, inferring format from the file extension when absent.
- read_
capability_ overrides - Reads capability overrides from disk, inferring format from the file extension when absent.
- resolve_
bundled_ binary - Resolves a bundled Codex binary under
<bundle_root>/<platform>/<version>/. - serialize_
capabilities_ snapshot - Serializes a capability snapshot to a JSON or TOML string.
- serialize_
capability_ overrides - Serializes capability overrides (snapshot, version, feature flags) to a JSON or TOML string.
- update_
advisory_ from_ capabilities - Computes an update advisory for a previously probed binary.
- write_
capabilities_ snapshot - Writes a capability snapshot to disk, inferring format from the file extension when absent.
- write_
capability_ overrides - Writes capability overrides to disk, inferring format from the file extension when absent.
Type Aliases§
- DynExec
Completion - Type-erased completion future that resolves when streaming stops.
- DynThread
Event Stream - Type-erased stream of events from the Codex CLI.