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