Skip to main content

codex_wrapper/
lib.rs

1//! A type-safe Codex CLI wrapper for Rust.
2//!
3//! `codex-wrapper` provides a builder-pattern interface for invoking the
4//! `codex` CLI programmatically. It follows the same design philosophy as
5//! [`claude-wrapper`](https://crates.io/crates/claude-wrapper) and
6//! [`docker-wrapper`](https://crates.io/crates/docker-wrapper):
7//! each CLI subcommand is a builder struct that produces typed output.
8//!
9//! # Quick Start
10//!
11//! ```no_run
12//! use codex_wrapper::{Codex, CodexCommand, ExecCommand, SandboxMode};
13//!
14//! # async fn example() -> codex_wrapper::Result<()> {
15//! let codex = Codex::builder().build()?;
16//!
17//! let output = ExecCommand::new("summarize this repository")
18//!     .sandbox(SandboxMode::WorkspaceWrite)
19//!     .ephemeral()
20//!     .execute(&codex)
21//!     .await?;
22//!
23//! println!("{}", output.stdout);
24//! # Ok(())
25//! # }
26//! ```
27//!
28//! ## Defaults
29//!
30//! | Type | Default variant |
31//! |------|-----------------|
32//! | [`SandboxMode`] | [`SandboxMode::WorkspaceWrite`] |
33//! | [`ApprovalPolicy`] | [`ApprovalPolicy::OnRequest`] |
34//!
35//! # Two-Layer Builder
36//!
37//! The [`Codex`] client holds shared config (binary path, env vars, timeout,
38//! retry policy). Command builders hold per-invocation options and call
39//! `execute(&codex)`.
40//!
41//! ```no_run
42//! use codex_wrapper::{Codex, CodexCommand, ExecCommand, RetryPolicy};
43//!
44//! # async fn example() -> codex_wrapper::Result<()> {
45//! // Configure once, reuse across commands
46//! let codex = Codex::builder()
47//!     .env("OPENAI_API_KEY", "sk-...")
48//!     .timeout_secs(300)
49//!     .retry(RetryPolicy::new().max_attempts(3).exponential())
50//!     .build()?;
51//!
52//! // Each command is a separate builder
53//! let output = ExecCommand::new("fix the failing tests")
54//!     .model("o3")
55//!     .sandbox(codex_wrapper::SandboxMode::WorkspaceWrite)
56//!     .skip_git_repo_check()
57//!     .ephemeral()
58//!     .execute(&codex)
59//!     .await?;
60//! # Ok(())
61//! # }
62//! ```
63//!
64//! # JSONL Output Parsing
65//!
66//! Use `execute_json_lines()` to get structured events from `--json` mode:
67//!
68//! ```no_run
69//! use codex_wrapper::{Codex, ExecCommand};
70//!
71//! # async fn example() -> codex_wrapper::Result<()> {
72//! let codex = Codex::builder().build()?;
73//! let events = ExecCommand::new("what is 2+2?")
74//!     .ephemeral()
75//!     .execute_json_lines(&codex)
76//!     .await?;
77//!
78//! for event in &events {
79//!     println!("{}: {:?}", event.event_type, event.extra);
80//! }
81//! # Ok(())
82//! # }
83//! ```
84//!
85//! # Child Environment Policy
86//!
87//! Child processes inherit the wrapper process's environment by default.
88//! [`CodexBuilder::env_remove`] excludes a single variable from inheritance.
89//! [`CodexBuilder::clear_env`] opts into clearing that environment before
90//! applying entries from [`CodexBuilder::env`] and [`CodexBuilder::envs`].
91//! The setting controls the direct child's environment, not same-user access
92//! to files, process metadata, sockets, or other OS resources.
93//!
94//! # Available Commands
95//!
96//! | Command | CLI equivalent |
97//! |---------|---------------|
98//! | [`ExecCommand`] | `codex exec <prompt>` |
99//! | [`ExecResumeCommand`] | `codex exec resume` |
100//! | [`ReviewCommand`] | `codex exec review` |
101//! | [`ResumeCommand`] | `codex resume` |
102//! | [`ForkCommand`] | `codex fork` |
103//! | [`LoginCommand`] | `codex login` |
104//! | [`LoginStatusCommand`] | `codex login status` |
105//! | [`LogoutCommand`] | `codex logout` |
106//! | [`McpListCommand`] | `codex mcp list` |
107//! | [`McpGetCommand`] | `codex mcp get` |
108//! | [`McpAddCommand`] | `codex mcp add` |
109//! | [`McpRemoveCommand`] | `codex mcp remove` |
110//! | [`McpLoginCommand`] | `codex mcp login` |
111//! | [`McpLogoutCommand`] | `codex mcp logout` |
112//! | [`McpServerCommand`] | `codex mcp-server` |
113//! | [`CompletionCommand`] | `codex completion` |
114//! | [`SandboxCommand`] | `codex sandbox` |
115//! | [`ApplyCommand`] | `codex apply` |
116//! | [`ArchiveCommand`] | `codex archive` |
117//! | [`DeleteCommand`] | `codex delete` |
118//! | [`UnarchiveCommand`] | `codex unarchive` |
119//! | [`DoctorCommand`] | `codex doctor` |
120//! | [`UpdateCommand`] | `codex update` |
121//! | [`PluginAddCommand`] | `codex plugin add` |
122//! | [`PluginListCommand`] | `codex plugin list` |
123//! | [`PluginRemoveCommand`] | `codex plugin remove` |
124//! | [`PluginMarketplaceAddCommand`] | `codex plugin marketplace add` |
125//! | [`PluginMarketplaceListCommand`] | `codex plugin marketplace list` |
126//! | [`PluginMarketplaceUpgradeCommand`] | `codex plugin marketplace upgrade` |
127//! | [`PluginMarketplaceRemoveCommand`] | `codex plugin marketplace remove` |
128//! | [`FeaturesListCommand`] | `codex features list` |
129//! | [`FeaturesEnableCommand`] | `codex features enable` |
130//! | [`FeaturesDisableCommand`] | `codex features disable` |
131//! | [`VersionCommand`] | `codex --version` |
132//! | [`RawCommand`] | Escape hatch for arbitrary args |
133//!
134//! # Error Handling
135//!
136//! All commands return [`Result<T>`], with typed errors via [`thiserror`]:
137//!
138//! ```no_run
139//! use codex_wrapper::{Codex, CodexCommand, ExecCommand, Error};
140//!
141//! # async fn example() -> codex_wrapper::Result<()> {
142//! let codex = Codex::builder().build()?;
143//! match ExecCommand::new("test").execute(&codex).await {
144//!     Ok(output) => println!("{}", output.stdout),
145//!     Err(Error::CommandFailed { stderr, exit_code, .. }) => {
146//!         eprintln!("failed (exit {}): {}", exit_code, stderr);
147//!     }
148//!     Err(Error::Timeout { .. }) => eprintln!("timed out"),
149//!     Err(e) => eprintln!("{e}"),
150//! }
151//! # Ok(())
152//! # }
153//! ```
154//!
155//! # Cancellation
156//!
157//! [`ExecCommand::execute_cancellable`] and
158//! [`ExecResumeCommand::execute_cancellable`] accept an explicit cancellation
159//! future. They terminate the owned process group and await the direct child
160//! before returning. Buffered client timeouts use the same settled cleanup
161//! path. [`CodexBuilder::termination_signal`] optionally selects SIGINT instead
162//! of SIGTERM so the CLI can handle an interrupt. Descendants in separate
163//! process groups require the CLI's cooperation; the hard-kill fallback cannot
164//! reach them.
165//! A failed stop or wait returns [`Error::CleanupFailed`], retaining both the
166//! original operation error and cleanup failure. This means direct-child
167//! settlement is unconfirmed; do not retry or resume as if cleanup succeeded.
168//!
169//! Dropping an ordinary command future is an abrupt fallback. It kills the
170//! direct child and, on Unix, the owned process group, but `Drop` cannot await
171//! reaping. A supervisor that needs terminal settlement should signal a
172//! cancellable method and keep polling it until it returns.
173//!
174//! Process groups are Unix-only. Elsewhere explicit cancellation kills and
175//! awaits the direct child, but cannot guarantee descendant cleanup.
176//!
177//! # Inherited file descriptors
178//!
179//! On macOS and iOS, the wrapper uses fork and exec to mark inherited file
180//! descriptors above 2 close-on-exec in the child before exec. Rust creates
181//! pipes and sets their close-on-exec flags in separate calls on these targets.
182//! The hook keeps a wrapper child from holding a sibling's pipe past exec and
183//! delaying EOF. A descriptor that the embedding program deliberately makes
184//! inheritable is also excluded if it falls within the scan. There is no opt-out.
185//!
186//! The walk ends at the soft open-file limit or descriptor 65,536, whichever
187//! is lower. Descriptors at or above that bound can still be inherited.
188//! Children started directly by the embedding program can still inherit the
189//! wrapper's pipes during the same window. Other Unix targets retain their
190//! existing spawn behavior.
191//!
192//! # Steering a running turn
193//!
194//! `codex exec` cannot change a turn that is already running. With the
195//! `app-server` feature, `AppServer` drives `codex app-server` so a caller can
196//! add input to a turn (`turn_steer`) or stop it (`turn_interrupt`) while it
197//! reads the turn's events. See the `app_server` module.
198//!
199//! # Features
200//!
201//! - `json` *(enabled by default)* - JSONL output parsing via `serde_json`
202//! - `app-server` - a JSON-RPC client for `codex app-server`; implies `json`
203
204#[cfg(feature = "app-server")]
205pub mod app_server;
206#[cfg(feature = "json")]
207pub mod auth;
208#[cfg(feature = "json")]
209pub mod budget;
210// Only the read-side modules need it, and each sits behind its own feature.
211#[cfg(any(feature = "json", feature = "config"))]
212mod codex_home;
213pub mod command;
214#[cfg(feature = "config")]
215pub mod config;
216pub mod dangerous;
217pub mod error;
218pub mod exec;
219#[cfg(feature = "json")]
220pub mod history;
221pub mod mcp_config;
222pub mod retry;
223pub mod rollout_budget;
224#[cfg(feature = "json")]
225pub mod session;
226#[cfg(feature = "json")]
227pub mod streaming;
228pub mod structured;
229#[cfg(all(test, unix))]
230mod test_support;
231pub mod types;
232pub mod version;
233
234use std::collections::HashMap;
235use std::fmt;
236use std::path::{Path, PathBuf};
237use std::time::Duration;
238
239#[cfg(feature = "app-server")]
240pub use app_server::{AppServer, AppServerBuilder, AppServerHandle};
241#[cfg(feature = "json")]
242pub use auth::{AuthStatus, AuthStrategy};
243#[cfg(feature = "json")]
244pub use budget::{TokenBudget, TokenBudgetBuilder};
245pub use command::CodexCommand;
246pub use command::apply::ApplyCommand;
247pub use command::completion::{CompletionCommand, Shell};
248pub use command::doctor::DoctorCommand;
249pub use command::exec::{ExecCommand, ExecResumeCommand};
250pub use command::features::{FeaturesDisableCommand, FeaturesEnableCommand, FeaturesListCommand};
251pub use command::fork::ForkCommand;
252pub use command::login::{LoginCommand, LoginStatusCommand, LogoutCommand};
253pub use command::mcp::{
254    McpAddCommand, McpGetCommand, McpListCommand, McpLoginCommand, McpLogoutCommand,
255    McpRemoveCommand,
256};
257pub use command::mcp_server::McpServerCommand;
258pub use command::plugin::{
259    PluginAddCommand, PluginListCommand, PluginMarketplaceAddCommand, PluginMarketplaceListCommand,
260    PluginMarketplaceRemoveCommand, PluginMarketplaceUpgradeCommand, PluginRemoveCommand,
261};
262pub use command::raw::RawCommand;
263pub use command::resume::ResumeCommand;
264pub use command::review::ReviewCommand;
265pub use command::sandbox::SandboxCommand;
266pub use command::session_mgmt::{ArchiveCommand, DeleteCommand, UnarchiveCommand};
267pub use command::update::UpdateCommand;
268pub use command::version::VersionCommand;
269#[cfg(feature = "config")]
270pub use config::CodexConfig;
271pub use error::{Error, FailureKind, OutputStream, Result, ShutdownAction};
272pub use exec::CommandOutput;
273#[cfg(feature = "json")]
274pub use history::{SessionFile, SessionLog, SessionMeta, SessionQuery};
275pub use mcp_config::{McpConfigBuilder, McpServerConfig};
276pub use retry::{BackoffStrategy, RetryPolicy};
277pub use rollout_budget::{RolloutBudgetConfig, RolloutBudgetConfigBuilder};
278#[cfg(feature = "json")]
279pub use session::{Session, TurnRecord};
280pub use types::*;
281pub use version::{
282    CliVersion, CliVersionStatus, TESTED_CLI_VERSION_MAX, TESTED_CLI_VERSION_MIN, VersionParseError,
283};
284
285/// What the crate knows about a child the moment it is spawned.
286///
287/// Delivered to the [`CodexBuilder::on_spawn`] observer before the run can
288/// produce output. This lets a supervisor durably record the child while the
289/// run is still in progress.
290#[derive(Debug, Clone, Copy, PartialEq, Eq)]
291#[non_exhaustive]
292pub struct SpawnInfo {
293    /// The child's process id.
294    pub pid: u32,
295    /// The child's process group id, when it leads its own group.
296    ///
297    /// `None` when [`CodexBuilder::process_group`] is disabled. In that case
298    /// the child shares the parent's group and its pid must not be passed to
299    /// `killpg`, which would signal the caller's own process group.
300    pub pgid: Option<u32>,
301}
302
303/// Called with [`SpawnInfo`] each time the crate spawns a CLI child.
304///
305/// Must not block. It runs inline between `spawn` and the first read of the
306/// child's output.
307pub type SpawnObserver = std::sync::Arc<dyn Fn(SpawnInfo) + Send + Sync>;
308
309/// Unix signal sent before the hard-kill fallback during awaited shutdown.
310///
311/// The default is [`Terminate`](Self::Terminate). [`Interrupt`](Self::Interrupt)
312/// lets a CLI handle cancellation as Ctrl-C, including cleaning up tools it
313/// started in separate process groups. Such cleanup depends on the CLI; the
314/// wrapper's fallback only reaches its own process group.
315///
316/// Ignored on non-Unix platforms and with
317/// [`process_group(false)`](CodexBuilder::process_group). Dropping a running
318/// future always kills immediately without sending this signal first.
319#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
320pub enum TerminationSignal {
321    /// Send SIGTERM, preserving the default shutdown behavior.
322    #[default]
323    Terminate,
324    /// Send SIGINT so the CLI can run its interrupt handler.
325    Interrupt,
326}
327
328impl TerminationSignal {
329    #[cfg(unix)]
330    pub(crate) fn as_raw(self) -> i32 {
331        match self {
332            Self::Terminate => libc::SIGTERM,
333            Self::Interrupt => libc::SIGINT,
334        }
335    }
336}
337
338// An absent key inherits. An explicit None suppresses inheritance for that key.
339type EnvironmentOverrides = HashMap<String, Option<String>>;
340
341#[cfg(windows)]
342fn windows_env_key<'a>(env: &'a EnvironmentOverrides, key: &'a str) -> &'a str {
343    use windows_sys::Win32::Globalization::{CSTR_EQUAL, CompareStringOrdinal};
344
345    // Match the case-insensitive ordinal comparison used by std::process::Command.
346    let wide_key: Vec<_> = key.encode_utf16().collect();
347    env.keys()
348        .find(|name| {
349            let wide_name: Vec<_> = name.encode_utf16().collect();
350            // SAFETY: both UTF-16 buffers are live for the supplied lengths.
351            unsafe {
352                CompareStringOrdinal(
353                    wide_name.as_ptr(),
354                    i32::try_from(wide_name.len()).expect("environment name too long"),
355                    wide_key.as_ptr(),
356                    i32::try_from(wide_key.len()).expect("environment name too long"),
357                    1,
358                ) == CSTR_EQUAL
359            }
360        })
361        .map_or(key, String::as_str)
362}
363
364/// Shared Codex CLI client configuration.
365///
366/// Holds the binary path, working directory, environment variables, global
367/// arguments, timeout, and retry policy. Cheap to [`Clone`]; intended to be
368/// created once and reused across many command invocations.
369///
370/// # Example
371///
372/// ```no_run
373/// # fn example() -> codex_wrapper::Result<()> {
374/// let codex = codex_wrapper::Codex::builder()
375///     .env("OPENAI_API_KEY", "sk-...")
376///     .timeout_secs(120)
377///     .build()?;
378/// # Ok(())
379/// # }
380/// ```
381#[derive(Clone)]
382pub struct Codex {
383    pub(crate) binary: PathBuf,
384    pub(crate) working_dir: Option<PathBuf>,
385    pub(crate) env: EnvironmentOverrides,
386    pub(crate) clear_env: bool,
387    pub(crate) global_args: Vec<String>,
388    pub(crate) timeout: Option<Duration>,
389    pub(crate) termination_grace: Duration,
390    pub(crate) termination_signal: TerminationSignal,
391    pub(crate) process_group: bool,
392    pub(crate) output_limit: Option<usize>,
393    pub(crate) die_with_parent: bool,
394    pub(crate) on_spawn: Option<SpawnObserver>,
395    pub(crate) retry_policy: Option<RetryPolicy>,
396    pub(crate) tested_cli_version_range: (CliVersion, CliVersion),
397}
398
399impl Codex {
400    /// Create a new [`CodexBuilder`].
401    #[must_use]
402    pub fn builder() -> CodexBuilder {
403        CodexBuilder::default()
404    }
405
406    /// Path to the resolved `codex` binary.
407    #[must_use]
408    pub fn binary(&self) -> &Path {
409        &self.binary
410    }
411
412    /// Working directory for command execution, if set.
413    #[must_use]
414    pub fn working_dir(&self) -> Option<&Path> {
415        self.working_dir.as_deref()
416    }
417
418    /// Return a clone of this client with a different working directory.
419    #[must_use]
420    pub fn with_working_dir(&self, dir: impl Into<PathBuf>) -> Self {
421        let mut clone = self.clone();
422        clone.working_dir = Some(dir.into());
423        clone
424    }
425
426    /// Read `config.toml` for this client's `CODEX_HOME`.
427    ///
428    /// Uses the same effective environment as spawned commands. A client
429    /// built with [`clear_env`](CodexBuilder::clear_env) does not fall back to
430    /// ambient `CODEX_HOME` or `HOME` values.
431    ///
432    /// `Ok(None)` when there is no config file. Requires the `config` feature.
433    /// See [`crate::config`] for what is typed and what stays raw.
434    #[cfg(feature = "config")]
435    pub fn config(&self) -> Result<Option<crate::config::CodexConfig>> {
436        let home = crate::codex_home::resolve(&|key| self.environment_value(key));
437        crate::config::load_from_home(home)
438    }
439
440    /// Which credential this client's CLI would use, without spawning it.
441    ///
442    /// Honors a `CODEX_HOME` set on this client via
443    /// [`env`](CodexBuilder::env), falling back to the process environment
444    /// unless the variable was removed with [`env_remove`](CodexBuilder::env_remove)
445    /// or inheritance was cleared with [`clear_env`](CodexBuilder::clear_env).
446    /// See [`crate::auth`] for what the strategies mean and how they were
447    /// determined.
448    ///
449    /// ```no_run
450    /// use codex_wrapper::Codex;
451    ///
452    /// # fn example() -> codex_wrapper::Result<()> {
453    /// let codex = Codex::builder().build()?;
454    /// if !codex.auth_status().is_configured() {
455    ///     eprintln!("no credentials; run `codex login`");
456    /// }
457    /// # Ok(())
458    /// # }
459    /// ```
460    #[cfg(feature = "json")]
461    #[must_use]
462    pub fn auth_status(&self) -> crate::auth::AuthStatus {
463        crate::auth::detect_with(|key| self.environment_value(key))
464    }
465
466    /// Resolve one variable exactly as this client's direct child will see
467    /// it. Read-side helpers use the same policy as process spawning so a
468    /// preflight cannot report credentials or config excluded from the child.
469    #[cfg(any(feature = "json", feature = "config"))]
470    fn environment_value(&self, key: &str) -> Option<String> {
471        #[cfg(windows)]
472        let key = windows_env_key(&self.env, key);
473
474        match self.env.get(key) {
475            Some(value) => value.clone(),
476            None if self.clear_env => None,
477            None => std::env::var(key).ok(),
478        }
479    }
480
481    pub async fn cli_version(&self) -> Result<CliVersion> {
482        let output = VersionCommand::new().execute(self).await?;
483        CliVersion::parse_version_output(&output.stdout).map_err(|e| Error::Io {
484            message: format!("failed to parse CLI version: {e}"),
485            source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
486            working_dir: None,
487        })
488    }
489
490    /// Verify the installed CLI meets a minimum version requirement.
491    ///
492    /// Returns [`Error::VersionMismatch`] if the installed version is too old.
493    pub async fn check_version(&self, minimum: &CliVersion) -> Result<CliVersion> {
494        let version = self.cli_version().await?;
495        if version.satisfies_minimum(minimum) {
496            Ok(version)
497        } else {
498            Err(Error::VersionMismatch {
499                found: version,
500                minimum: *minimum,
501            })
502        }
503    }
504
505    /// The tested-against CLI version range this client reports on.
506    ///
507    /// Defaults to [`TESTED_CLI_VERSION_MIN`] and [`TESTED_CLI_VERSION_MAX`];
508    /// override with [`CodexBuilder::tested_cli_version_range`].
509    #[must_use]
510    pub fn tested_cli_version_range(&self) -> (CliVersion, CliVersion) {
511        self.tested_cli_version_range
512    }
513
514    /// Classify the installed CLI against the tested-against range.
515    ///
516    /// Emits a `tracing::warn!` when outside the range, and returns the typed
517    /// status either way. This reports; it does not fail. Most CLI releases
518    /// break nothing, so refusing to run against an unrecognized version is
519    /// worse than saying so. Use
520    /// [`ensure_tested_cli_version`](Self::ensure_tested_cli_version) when you
521    /// do want a hard gate.
522    ///
523    /// Intended for one-shot use at startup rather than before every command:
524    /// it spawns `codex --version`.
525    pub async fn cli_version_status(&self) -> Result<CliVersionStatus> {
526        let (min, max) = self.tested_cli_version_range;
527        let status = self.cli_version().await?.status_within(&min, &max);
528        warn_on_drift(&status);
529        Ok(status)
530    }
531
532    /// Like [`cli_version_status`](Self::cli_version_status), but returns
533    /// [`Error::UntestedCliVersion`] when the installed CLI is outside the
534    /// tested range.
535    ///
536    /// This is the opt-in hard gate. It is a method rather than a
537    /// [`CodexBuilder`] option because [`CodexBuilder::build`] is synchronous
538    /// and never spawns the binary; enforcing a version there would mean
539    /// running a subprocess inside a constructor.
540    pub async fn ensure_tested_cli_version(&self) -> Result<CliVersion> {
541        let (min, max) = self.tested_cli_version_range;
542        let found = self.cli_version().await?;
543        match found.status_within(&min, &max) {
544            CliVersionStatus::Tested => Ok(found),
545            status => {
546                warn_on_drift(&status);
547                Err(Error::UntestedCliVersion {
548                    found,
549                    tested_min: min,
550                    tested_max: max,
551                })
552            }
553        }
554    }
555}
556
557impl fmt::Debug for Codex {
558    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
559        let mut env_keys: Vec<&str> = self.env.keys().map(String::as_str).collect();
560        env_keys.sort_unstable();
561
562        f.debug_struct("Codex")
563            .field("binary", &self.binary)
564            .field("working_dir", &self.working_dir)
565            .field("env_keys", &env_keys)
566            .field("clear_env", &self.clear_env)
567            .field("global_args", &self.global_args)
568            .field("timeout", &self.timeout)
569            .field("termination_grace", &self.termination_grace)
570            .field("termination_signal", &self.termination_signal)
571            .field("process_group", &self.process_group)
572            .field("die_with_parent", &self.die_with_parent)
573            .field("has_spawn_observer", &self.on_spawn.is_some())
574            .field("retry_policy", &self.retry_policy)
575            .field("tested_cli_version_range", &self.tested_cli_version_range)
576            .finish()
577    }
578}
579
580fn warn_on_drift(status: &CliVersionStatus) {
581    match status {
582        CliVersionStatus::Tested => {}
583        CliVersionStatus::NewerUntested { found, tested_max } => {
584            tracing::warn!(
585                found = %found,
586                tested_max = %tested_max,
587                "codex CLI is newer than this wrapper's tested-against range; \
588                 semantics may have drifted"
589            );
590        }
591        CliVersionStatus::OlderThanMinimum { found, minimum } => {
592            tracing::warn!(
593                found = %found,
594                minimum = %minimum,
595                "codex CLI is older than this wrapper's tested-against range; \
596                 some emitted arguments are likely to be rejected"
597            );
598        }
599    }
600}
601
602/// Builder for creating a [`Codex`] client.
603///
604/// All options are optional. By default the builder discovers the `codex`
605/// binary via `PATH`.
606#[derive(Default)]
607pub struct CodexBuilder {
608    binary: Option<PathBuf>,
609    working_dir: Option<PathBuf>,
610    env: EnvironmentOverrides,
611    clear_env: bool,
612    global_args: Vec<String>,
613    timeout: Option<Duration>,
614    termination_grace: Option<Duration>,
615    termination_signal: TerminationSignal,
616    process_group: Option<bool>,
617    output_limit: Option<usize>,
618    die_with_parent: bool,
619    on_spawn: Option<SpawnObserver>,
620    retry_policy: Option<RetryPolicy>,
621    tested_cli_version_range: Option<(CliVersion, CliVersion)>,
622}
623
624impl CodexBuilder {
625    /// Override the tested-against CLI version range.
626    ///
627    /// Defaults to the range this crate declares and verifies in CI. Set this
628    /// only when you have validated a different range yourself; widening it
629    /// does not make the wrapper work against versions it was not tested on.
630    #[must_use]
631    pub fn tested_cli_version_range(mut self, min: CliVersion, max: CliVersion) -> Self {
632        self.tested_cli_version_range = Some((min, max));
633        self
634    }
635
636    /// Set an explicit path to the `codex` binary (skips `PATH` lookup).
637    #[must_use]
638    pub fn binary(mut self, path: impl Into<PathBuf>) -> Self {
639        self.binary = Some(path.into());
640        self
641    }
642
643    /// Set the working directory for all commands.
644    #[must_use]
645    pub fn working_dir(mut self, path: impl Into<PathBuf>) -> Self {
646        self.working_dir = Some(path.into());
647        self
648    }
649
650    /// Set a single environment variable for child processes.
651    #[must_use]
652    pub fn env(self, key: impl Into<String>, value: impl Into<String>) -> Self {
653        self.with_env_override(key.into(), Some(value.into()))
654    }
655
656    /// Set multiple environment variables for child processes.
657    #[must_use]
658    pub fn envs(
659        mut self,
660        vars: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
661    ) -> Self {
662        for (key, value) in vars {
663            self = self.env(key, value);
664        }
665        self
666    }
667
668    /// Remove one variable from the child environment. Other variables continue
669    /// to be inherited unless [`clear_env`](Self::clear_env) is also used.
670    ///
671    /// The last call to `env_remove`, [`env`](Self::env), or [`envs`](Self::envs)
672    /// for the same name wins.
673    #[must_use]
674    pub fn env_remove(self, name: impl Into<String>) -> Self {
675        self.with_env_override(name.into(), None)
676    }
677
678    fn with_env_override(mut self, key: String, value: Option<String>) -> Self {
679        #[cfg(windows)]
680        let key = windows_env_key(&self.env, &key).to_owned();
681        self.env.insert(key, value);
682        self
683    }
684
685    /// Clear the inherited environment before applying variables supplied by
686    /// [`env`](Self::env) and [`envs`](Self::envs).
687    ///
688    /// By default, child processes inherit the wrapper process's environment.
689    /// This opt-in is call-order independent: explicit variables survive
690    /// whether they are added before or after `clear_env`.
691    ///
692    /// This controls the direct Codex child's environment. It is not OS or
693    /// same-user isolation: the child can still access files, process metadata,
694    /// sockets, and other resources allowed to its user and sandbox.
695    #[must_use]
696    pub fn clear_env(mut self) -> Self {
697        self.clear_env = true;
698        self
699    }
700
701    /// Set the command timeout in seconds.
702    #[must_use]
703    pub fn timeout_secs(mut self, seconds: u64) -> Self {
704        self.timeout = Some(Duration::from_secs(seconds));
705        self
706    }
707
708    /// Set the command timeout as a [`Duration`].
709    #[must_use]
710    pub fn timeout(mut self, duration: Duration) -> Self {
711        self.timeout = Some(duration);
712        self
713    }
714
715    /// How long a cancelled run's process group gets to exit before it is
716    /// killed. Defaults to five seconds.
717    ///
718    /// Applies to awaited exec cancellation and timeouts, buffered or streaming.
719    /// These send the configured [`termination_signal`](Self::termination_signal),
720    /// wait this long, send SIGKILL, and await the direct child. Output received
721    /// during shutdown is drained and discarded without extending this budget.
722    /// A dropped future does not use it: `Drop` cannot wait, so it kills
723    /// immediately.
724    ///
725    /// App-server shutdown waits up to this long after closing stdin. With
726    /// Unix process groups enabled, it can wait up to this long again after
727    /// sending the configured termination signal (SIGTERM by default).
728    /// Shutdown returns an error with the reaped status when the server
729    /// needs a stop signal, even if it then exits with code zero.
730    #[must_use]
731    pub fn termination_grace(mut self, duration: Duration) -> Self {
732        self.termination_grace = Some(duration);
733        self
734    }
735
736    /// Select the Unix signal used before the hard-kill fallback.
737    ///
738    /// Defaults to [`TerminationSignal::Terminate`]. Use
739    /// [`TerminationSignal::Interrupt`] to let the CLI handle Ctrl-C and clean
740    /// up its tools. This does not guarantee cleanup of detached descendants.
741    /// [`termination_grace`](Self::termination_grace) controls the wait after
742    /// this signal. The signal setting is ignored with process groups disabled
743    /// or on non-Unix.
744    /// Dropping a future remains an immediate hard kill.
745    #[must_use]
746    pub fn termination_signal(mut self, signal: TerminationSignal) -> Self {
747        self.termination_signal = signal;
748        self
749    }
750
751    /// Whether each run gets its own process group. On by default.
752    ///
753    /// With a group of its own, cancellation reaches the CLI and descendants
754    /// that remain in that group. Tools that create a new group or session need
755    /// cooperative cleanup by the CLI; group signaling cannot reach them.
756    ///
757    /// Opting out puts the child in the parent's group, so a terminal Ctrl-C
758    /// reaches processes in the terminal's foreground group. A wrapper-side
759    /// kill reaches only the direct child, skipping the soft signal and grace.
760    /// This suits a terminal-attached host that shells out synchronously and
761    /// treats the terminal as the supervisor.
762    ///
763    /// Matches `claude-wrapper`'s option of the same name. No effect on
764    /// non-unix targets, which have no process groups.
765    #[must_use]
766    pub fn process_group(mut self, enabled: bool) -> Self {
767        self.process_group = Some(enabled);
768        self
769    }
770
771    /// Stop capturing a stream once it passes `max_bytes`.
772    ///
773    /// Without a ceiling both captured streams are read to EOF, so peak
774    /// memory for a run is whatever the child decides to print. A consumer
775    /// cannot add this itself: by the time it holds a result the bytes are
776    /// already resident, and for a JSON run already parsed.
777    ///
778    /// With a ceiling set, each buffer stays under `max_bytes`, so a run
779    /// holds at most twice that across stdout and stderr. Passing it stops
780    /// the run the way cancellation does and fails with
781    /// [`Error::OutputLimitExceeded`], which carries no captured bytes: a
782    /// prefix returned as though it were the whole result is the failure
783    /// this prevents.
784    ///
785    /// Off by default, so existing behavior is unchanged until a host opts
786    /// in.
787    #[must_use]
788    pub fn output_limit(mut self, max_bytes: usize) -> Self {
789        self.output_limit = Some(max_bytes);
790        self
791    }
792
793    /// Observe every child this client spawns, at spawn time.
794    ///
795    /// The observer fires before the run produces output, including for
796    /// buffered, streaming, stdin, cancellable, and retried runs. A retry
797    /// fires once per attempt because each attempt is a distinct process.
798    ///
799    /// The observer runs inline on the spawning thread and must not block.
800    /// A supervisor can use it to write a pidfile or send the receipt to a
801    /// channel before the child can be orphaned.
802    #[must_use]
803    pub fn on_spawn(mut self, observer: SpawnObserver) -> Self {
804        self.on_spawn = Some(observer);
805        self
806    }
807
808    /// Ask the kernel to kill spawned children when this process dies.
809    ///
810    /// This uses `PR_SET_PDEATHSIG` on Linux. Check
811    /// [`die_with_parent_supported`](crate::exec::die_with_parent_supported)
812    /// before relying on it; other targets accept the option as a no-op. A
813    /// portable supervisor should combine this with [`on_spawn`](Self::on_spawn)
814    /// and reconcile recorded children after a restart.
815    ///
816    /// The post-fork hook closes the parent-death race by rechecking the
817    /// parent after arming the signal. This is off by default because it is
818    /// appropriate for supervised work but not for deliberately backgrounded
819    /// CLI processes.
820    #[must_use]
821    pub fn die_with_parent(mut self, enabled: bool) -> Self {
822        self.die_with_parent = enabled;
823        self
824    }
825
826    /// Append a raw global argument passed before any subcommand.
827    ///
828    /// When an exec command has a typed rollout budget, conflicting global
829    /// `--enable/--disable rollout_budget` arguments are suppressed at final
830    /// assembly. Codex applies feature toggles after config regardless of argv
831    /// order, so retaining one could silently defeat the typed protection.
832    #[must_use]
833    pub fn arg(mut self, arg: impl Into<String>) -> Self {
834        self.global_args.push(arg.into());
835        self
836    }
837
838    /// Add a global config override (`-c key=value`).
839    #[must_use]
840    pub fn config(mut self, key_value: impl Into<String>) -> Self {
841        self.global_args.push("-c".into());
842        self.global_args.push(key_value.into());
843        self
844    }
845
846    /// Enable a feature flag globally (`--enable <name>`).
847    ///
848    /// A `rollout_budget` toggle is suppressed for an exec command that has a
849    /// typed [`RolloutBudgetConfig`].
850    #[must_use]
851    pub fn enable(mut self, feature: impl Into<String>) -> Self {
852        self.global_args.push("--enable".into());
853        self.global_args.push(feature.into());
854        self
855    }
856
857    /// Disable a feature flag globally (`--disable <name>`).
858    ///
859    /// A `rollout_budget` toggle is suppressed for an exec command that has a
860    /// typed [`RolloutBudgetConfig`].
861    #[must_use]
862    pub fn disable(mut self, feature: impl Into<String>) -> Self {
863        self.global_args.push("--disable".into());
864        self.global_args.push(feature.into());
865        self
866    }
867
868    /// Set a default [`RetryPolicy`] for all commands.
869    #[must_use]
870    pub fn retry(mut self, policy: RetryPolicy) -> Self {
871        self.retry_policy = Some(policy);
872        self
873    }
874
875    /// Build the [`Codex`] client.
876    ///
877    /// Returns [`Error::NotFound`] if no binary path was set and `codex` is
878    /// not found in `PATH`.
879    pub fn build(self) -> Result<Codex> {
880        let binary = match self.binary {
881            Some(path) => path,
882            None => which::which("codex").map_err(|_| Error::NotFound)?,
883        };
884
885        Ok(Codex {
886            binary,
887            working_dir: self.working_dir,
888            env: self.env,
889            clear_env: self.clear_env,
890            global_args: self.global_args,
891            termination_grace: self
892                .termination_grace
893                .unwrap_or_else(|| Duration::from_secs(5)),
894            termination_signal: self.termination_signal,
895            process_group: self.process_group.unwrap_or(true),
896            output_limit: self.output_limit,
897            die_with_parent: self.die_with_parent,
898            on_spawn: self.on_spawn,
899            timeout: self.timeout,
900            retry_policy: self.retry_policy,
901            tested_cli_version_range: self.tested_cli_version_range.unwrap_or((
902                version::TESTED_CLI_VERSION_MIN,
903                version::TESTED_CLI_VERSION_MAX,
904            )),
905        })
906    }
907}
908
909impl fmt::Debug for CodexBuilder {
910    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
911        let mut env_keys: Vec<&str> = self.env.keys().map(String::as_str).collect();
912        env_keys.sort_unstable();
913
914        f.debug_struct("CodexBuilder")
915            .field("binary", &self.binary)
916            .field("working_dir", &self.working_dir)
917            .field("env_keys", &env_keys)
918            .field("clear_env", &self.clear_env)
919            .field("global_args", &self.global_args)
920            .field("timeout", &self.timeout)
921            .field("termination_grace", &self.termination_grace)
922            .field("termination_signal", &self.termination_signal)
923            .field("process_group", &self.process_group)
924            .field("die_with_parent", &self.die_with_parent)
925            .field("has_spawn_observer", &self.on_spawn.is_some())
926            .field("retry_policy", &self.retry_policy)
927            .field("tested_cli_version_range", &self.tested_cli_version_range)
928            .finish()
929    }
930}
931
932#[cfg(test)]
933mod tests {
934    use super::*;
935
936    #[test]
937    fn builder_with_binary() {
938        let codex = Codex::builder()
939            .binary("/usr/local/bin/codex")
940            .env("FOO", "bar")
941            .timeout_secs(60)
942            .build()
943            .unwrap();
944
945        assert_eq!(codex.binary, PathBuf::from("/usr/local/bin/codex"));
946        assert_eq!(codex.env["FOO"].as_deref(), Some("bar"));
947        assert!(!codex.clear_env);
948        assert_eq!(codex.timeout, Some(Duration::from_secs(60)));
949        assert_eq!(codex.termination_signal, TerminationSignal::Terminate);
950        assert_eq!(codex.termination_grace, Duration::from_secs(5));
951    }
952
953    #[test]
954    fn clear_env_is_opt_in_and_keeps_explicit_entries() {
955        let codex = Codex::builder()
956            .binary("/bin/echo")
957            .env("BEFORE_CLEAR", "one")
958            .clear_env()
959            .env("AFTER_CLEAR", "two")
960            .build()
961            .unwrap();
962
963        assert!(codex.clear_env);
964        assert_eq!(codex.env["BEFORE_CLEAR"].as_deref(), Some("one"));
965        assert_eq!(codex.env["AFTER_CLEAR"].as_deref(), Some("two"));
966    }
967
968    #[test]
969    fn client_and_builder_debug_hide_environment_values() {
970        let builder = Codex::builder()
971            .binary("/bin/echo")
972            .env("CODEX_WRAPPER_SECRET", "debug-must-not-leak-this");
973
974        let builder_debug = format!("{builder:?}");
975        assert!(builder_debug.contains("CODEX_WRAPPER_SECRET"));
976        assert!(!builder_debug.contains("debug-must-not-leak-this"));
977
978        let codex = builder.build().unwrap();
979        let client_debug = format!("{codex:?}");
980        assert!(client_debug.contains("CODEX_WRAPPER_SECRET"));
981        assert!(!client_debug.contains("debug-must-not-leak-this"));
982    }
983
984    /// Read-side helpers must answer from the environment the child receives,
985    /// not from ambient values that `clear_env` removes at spawn time.
986    #[cfg(any(feature = "json", feature = "config"))]
987    #[test]
988    fn effective_environment_lookup_obeys_clear_env() {
989        let ambient_path = std::env::var("PATH").expect("test process must have PATH");
990        let inherited = Codex::builder().binary("/bin/echo").build().unwrap();
991        assert_eq!(inherited.environment_value("PATH"), Some(ambient_path));
992
993        let cleared = Codex::builder()
994            .binary("/bin/echo")
995            .clear_env()
996            .build()
997            .unwrap();
998        assert_eq!(cleared.environment_value("PATH"), None);
999
1000        let explicit = Codex::builder()
1001            .binary("/bin/echo")
1002            .clear_env()
1003            .env("PATH", "/intentional/bin")
1004            .build()
1005            .unwrap();
1006        assert_eq!(
1007            explicit.environment_value("PATH").as_deref(),
1008            Some("/intentional/bin")
1009        );
1010    }
1011
1012    #[cfg(all(windows, any(feature = "json", feature = "config")))]
1013    #[test]
1014    fn environment_override_names_are_case_insensitive_on_windows() {
1015        let client = Codex::builder()
1016            .binary("unused")
1017            .env("MixedCase", "first")
1018            .env_remove("MIXEDCASE")
1019            .envs([("mixedcase", "last")])
1020            .env("Other", "first")
1021            .env_remove("other")
1022            .build()
1023            .unwrap();
1024        assert_eq!(
1025            client.environment_value("MixedCase").as_deref(),
1026            Some("last")
1027        );
1028        assert_eq!(client.environment_value("OTHER"), None);
1029    }
1030
1031    #[test]
1032    fn builder_global_args() {
1033        let codex = Codex::builder()
1034            .binary("/usr/local/bin/codex")
1035            .config("model=\"gpt-5\"")
1036            .enable("foo")
1037            .disable("bar")
1038            .build()
1039            .unwrap();
1040
1041        assert_eq!(
1042            codex.global_args,
1043            vec![
1044                "-c",
1045                "model=\"gpt-5\"",
1046                "--enable",
1047                "foo",
1048                "--disable",
1049                "bar"
1050            ]
1051        );
1052    }
1053
1054    #[test]
1055    fn client_defaults_to_the_crate_tested_range() {
1056        let codex = Codex::builder().binary("/bin/echo").build().unwrap();
1057        assert_eq!(
1058            codex.tested_cli_version_range(),
1059            (
1060                version::TESTED_CLI_VERSION_MIN,
1061                version::TESTED_CLI_VERSION_MAX
1062            )
1063        );
1064    }
1065
1066    #[test]
1067    fn builder_can_override_the_tested_range() {
1068        let min = CliVersion::new(1, 0, 0);
1069        let max = CliVersion::new(2, 0, 0);
1070        let codex = Codex::builder()
1071            .binary("/bin/echo")
1072            .tested_cli_version_range(min, max)
1073            .build()
1074            .unwrap();
1075        assert_eq!(codex.tested_cli_version_range(), (min, max));
1076    }
1077
1078    #[test]
1079    fn untested_version_error_names_both_bounds() {
1080        let err = Error::UntestedCliVersion {
1081            found: CliVersion::new(0, 200, 0),
1082            tested_min: CliVersion::new(0, 145, 0),
1083            tested_max: CliVersion::new(0, 146, 0),
1084        };
1085        assert_eq!(
1086            err.to_string(),
1087            "CLI version 0.200.0 is outside the tested range 0.145.0..=0.146.0"
1088        );
1089    }
1090
1091    /// A CODEX_HOME set on the client must win over the process environment,
1092    /// or a client pointed at a different home reports the wrong credentials.
1093    #[cfg(feature = "json")]
1094    #[test]
1095    fn auth_status_honors_a_client_codex_home() {
1096        let dir =
1097            std::env::temp_dir().join(format!("codex-wrapper-client-auth-{}", std::process::id()));
1098        let _ = std::fs::remove_dir_all(&dir);
1099        std::fs::create_dir_all(&dir).unwrap();
1100        std::fs::write(
1101            dir.join("auth.json"),
1102            r#"{"auth_mode":"apikey","OPENAI_API_KEY":"sk-secret"}"#,
1103        )
1104        .unwrap();
1105
1106        let codex = Codex::builder()
1107            .binary("/bin/echo")
1108            .env("CODEX_HOME", dir.to_str().unwrap())
1109            .build()
1110            .unwrap();
1111
1112        let status = codex.auth_status();
1113        assert_eq!(status.codex_home, dir);
1114        assert!(status.is_configured());
1115        assert!(
1116            !format!("{status:?}").contains("sk-secret"),
1117            "the credential leaked into the status"
1118        );
1119
1120        let _ = std::fs::remove_dir_all(&dir);
1121    }
1122
1123    #[cfg(feature = "json")]
1124    #[test]
1125    fn auth_status_does_not_fall_back_to_ambient_home_when_cleared() {
1126        let codex = Codex::builder()
1127            .binary("/bin/echo")
1128            .clear_env()
1129            .build()
1130            .unwrap();
1131
1132        assert_eq!(codex.auth_status().codex_home, PathBuf::from(".codex"));
1133    }
1134}