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