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, 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) die_with_parent: bool,
302    pub(crate) on_spawn: Option<SpawnObserver>,
303    pub(crate) retry_policy: Option<RetryPolicy>,
304    pub(crate) tested_cli_version_range: (CliVersion, CliVersion),
305}
306
307impl Codex {
308    /// Create a new [`CodexBuilder`].
309    #[must_use]
310    pub fn builder() -> CodexBuilder {
311        CodexBuilder::default()
312    }
313
314    /// Path to the resolved `codex` binary.
315    #[must_use]
316    pub fn binary(&self) -> &Path {
317        &self.binary
318    }
319
320    /// Working directory for command execution, if set.
321    #[must_use]
322    pub fn working_dir(&self) -> Option<&Path> {
323        self.working_dir.as_deref()
324    }
325
326    /// Return a clone of this client with a different working directory.
327    #[must_use]
328    pub fn with_working_dir(&self, dir: impl Into<PathBuf>) -> Self {
329        let mut clone = self.clone();
330        clone.working_dir = Some(dir.into());
331        clone
332    }
333
334    /// Read `config.toml` for this client's `CODEX_HOME`.
335    ///
336    /// Uses the same effective environment as spawned commands. A client
337    /// built with [`clear_env`](CodexBuilder::clear_env) does not fall back to
338    /// ambient `CODEX_HOME` or `HOME` values.
339    ///
340    /// `Ok(None)` when there is no config file. Requires the `config` feature.
341    /// See [`crate::config`] for what is typed and what stays raw.
342    #[cfg(feature = "config")]
343    pub fn config(&self) -> Result<Option<crate::config::CodexConfig>> {
344        let home = crate::codex_home::resolve(&|key| self.environment_value(key));
345        crate::config::load_from_home(home)
346    }
347
348    /// Which credential this client's CLI would use, without spawning it.
349    ///
350    /// Honors a `CODEX_HOME` set on this client via
351    /// [`env`](CodexBuilder::env), falling back to the process environment
352    /// unless [`clear_env`](CodexBuilder::clear_env) was selected.
353    /// See [`crate::auth`] for what the strategies mean and how they were
354    /// determined.
355    ///
356    /// ```no_run
357    /// use codex_wrapper::Codex;
358    ///
359    /// # fn example() -> codex_wrapper::Result<()> {
360    /// let codex = Codex::builder().build()?;
361    /// if !codex.auth_status().is_configured() {
362    ///     eprintln!("no credentials; run `codex login`");
363    /// }
364    /// # Ok(())
365    /// # }
366    /// ```
367    #[cfg(feature = "json")]
368    #[must_use]
369    pub fn auth_status(&self) -> crate::auth::AuthStatus {
370        crate::auth::detect_with(|key| self.environment_value(key))
371    }
372
373    /// Resolve one variable exactly as this client's direct child will see
374    /// it. Read-side helpers use the same policy as process spawning so a
375    /// preflight cannot report credentials or config excluded from the child.
376    #[cfg(any(feature = "json", feature = "config"))]
377    fn environment_value(&self, key: &str) -> Option<String> {
378        self.env.get(key).cloned().or_else(|| {
379            if self.clear_env {
380                None
381            } else {
382                std::env::var(key).ok()
383            }
384        })
385    }
386
387    pub async fn cli_version(&self) -> Result<CliVersion> {
388        let output = VersionCommand::new().execute(self).await?;
389        CliVersion::parse_version_output(&output.stdout).map_err(|e| Error::Io {
390            message: format!("failed to parse CLI version: {e}"),
391            source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
392            working_dir: None,
393        })
394    }
395
396    /// Verify the installed CLI meets a minimum version requirement.
397    ///
398    /// Returns [`Error::VersionMismatch`] if the installed version is too old.
399    pub async fn check_version(&self, minimum: &CliVersion) -> Result<CliVersion> {
400        let version = self.cli_version().await?;
401        if version.satisfies_minimum(minimum) {
402            Ok(version)
403        } else {
404            Err(Error::VersionMismatch {
405                found: version,
406                minimum: *minimum,
407            })
408        }
409    }
410
411    /// The tested-against CLI version range this client reports on.
412    ///
413    /// Defaults to [`TESTED_CLI_VERSION_MIN`] and [`TESTED_CLI_VERSION_MAX`];
414    /// override with [`CodexBuilder::tested_cli_version_range`].
415    #[must_use]
416    pub fn tested_cli_version_range(&self) -> (CliVersion, CliVersion) {
417        self.tested_cli_version_range
418    }
419
420    /// Classify the installed CLI against the tested-against range.
421    ///
422    /// Emits a `tracing::warn!` when outside the range, and returns the typed
423    /// status either way. This reports; it does not fail. Most CLI releases
424    /// break nothing, so refusing to run against an unrecognized version is
425    /// worse than saying so. Use
426    /// [`ensure_tested_cli_version`](Self::ensure_tested_cli_version) when you
427    /// do want a hard gate.
428    ///
429    /// Intended for one-shot use at startup rather than before every command:
430    /// it spawns `codex --version`.
431    pub async fn cli_version_status(&self) -> Result<CliVersionStatus> {
432        let (min, max) = self.tested_cli_version_range;
433        let status = self.cli_version().await?.status_within(&min, &max);
434        warn_on_drift(&status);
435        Ok(status)
436    }
437
438    /// Like [`cli_version_status`](Self::cli_version_status), but returns
439    /// [`Error::UntestedCliVersion`] when the installed CLI is outside the
440    /// tested range.
441    ///
442    /// This is the opt-in hard gate. It is a method rather than a
443    /// [`CodexBuilder`] option because [`CodexBuilder::build`] is synchronous
444    /// and never spawns the binary; enforcing a version there would mean
445    /// running a subprocess inside a constructor.
446    pub async fn ensure_tested_cli_version(&self) -> Result<CliVersion> {
447        let (min, max) = self.tested_cli_version_range;
448        let found = self.cli_version().await?;
449        match found.status_within(&min, &max) {
450            CliVersionStatus::Tested => Ok(found),
451            status => {
452                warn_on_drift(&status);
453                Err(Error::UntestedCliVersion {
454                    found,
455                    tested_min: min,
456                    tested_max: max,
457                })
458            }
459        }
460    }
461}
462
463impl fmt::Debug for Codex {
464    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465        let mut env_keys: Vec<&str> = self.env.keys().map(String::as_str).collect();
466        env_keys.sort_unstable();
467
468        f.debug_struct("Codex")
469            .field("binary", &self.binary)
470            .field("working_dir", &self.working_dir)
471            .field("env_keys", &env_keys)
472            .field("clear_env", &self.clear_env)
473            .field("global_args", &self.global_args)
474            .field("timeout", &self.timeout)
475            .field("termination_grace", &self.termination_grace)
476            .field("process_group", &self.process_group)
477            .field("die_with_parent", &self.die_with_parent)
478            .field("has_spawn_observer", &self.on_spawn.is_some())
479            .field("retry_policy", &self.retry_policy)
480            .field("tested_cli_version_range", &self.tested_cli_version_range)
481            .finish()
482    }
483}
484
485fn warn_on_drift(status: &CliVersionStatus) {
486    match status {
487        CliVersionStatus::Tested => {}
488        CliVersionStatus::NewerUntested { found, tested_max } => {
489            tracing::warn!(
490                found = %found,
491                tested_max = %tested_max,
492                "codex CLI is newer than this wrapper's tested-against range; \
493                 semantics may have drifted"
494            );
495        }
496        CliVersionStatus::OlderThanMinimum { found, minimum } => {
497            tracing::warn!(
498                found = %found,
499                minimum = %minimum,
500                "codex CLI is older than this wrapper's tested-against range; \
501                 some emitted arguments are likely to be rejected"
502            );
503        }
504    }
505}
506
507/// Builder for creating a [`Codex`] client.
508///
509/// All options are optional. By default the builder discovers the `codex`
510/// binary via `PATH`.
511#[derive(Default)]
512pub struct CodexBuilder {
513    binary: Option<PathBuf>,
514    working_dir: Option<PathBuf>,
515    env: HashMap<String, String>,
516    clear_env: bool,
517    global_args: Vec<String>,
518    timeout: Option<Duration>,
519    termination_grace: Option<Duration>,
520    process_group: Option<bool>,
521    die_with_parent: bool,
522    on_spawn: Option<SpawnObserver>,
523    retry_policy: Option<RetryPolicy>,
524    tested_cli_version_range: Option<(CliVersion, CliVersion)>,
525}
526
527impl CodexBuilder {
528    /// Override the tested-against CLI version range.
529    ///
530    /// Defaults to the range this crate declares and verifies in CI. Set this
531    /// only when you have validated a different range yourself; widening it
532    /// does not make the wrapper work against versions it was not tested on.
533    #[must_use]
534    pub fn tested_cli_version_range(mut self, min: CliVersion, max: CliVersion) -> Self {
535        self.tested_cli_version_range = Some((min, max));
536        self
537    }
538
539    /// Set an explicit path to the `codex` binary (skips `PATH` lookup).
540    #[must_use]
541    pub fn binary(mut self, path: impl Into<PathBuf>) -> Self {
542        self.binary = Some(path.into());
543        self
544    }
545
546    /// Set the working directory for all commands.
547    #[must_use]
548    pub fn working_dir(mut self, path: impl Into<PathBuf>) -> Self {
549        self.working_dir = Some(path.into());
550        self
551    }
552
553    /// Set a single environment variable for child processes.
554    #[must_use]
555    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
556        self.env.insert(key.into(), value.into());
557        self
558    }
559
560    /// Set multiple environment variables for child processes.
561    #[must_use]
562    pub fn envs(
563        mut self,
564        vars: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
565    ) -> Self {
566        for (key, value) in vars {
567            self.env.insert(key.into(), value.into());
568        }
569        self
570    }
571
572    /// Clear the inherited environment before applying variables supplied by
573    /// [`env`](Self::env) and [`envs`](Self::envs).
574    ///
575    /// By default, child processes inherit the wrapper process's environment.
576    /// This opt-in is call-order independent: explicit variables survive
577    /// whether they are added before or after `clear_env`.
578    ///
579    /// This controls the direct Codex child's environment. It is not OS or
580    /// same-user isolation: the child can still access files, process metadata,
581    /// sockets, and other resources allowed to its user and sandbox.
582    #[must_use]
583    pub fn clear_env(mut self) -> Self {
584        self.clear_env = true;
585        self
586    }
587
588    /// Set the command timeout in seconds.
589    #[must_use]
590    pub fn timeout_secs(mut self, seconds: u64) -> Self {
591        self.timeout = Some(Duration::from_secs(seconds));
592        self
593    }
594
595    /// Set the command timeout as a [`Duration`].
596    #[must_use]
597    pub fn timeout(mut self, duration: Duration) -> Self {
598        self.timeout = Some(duration);
599        self
600    }
601
602    /// How long a cancelled run's process group gets to exit before it is
603    /// killed. Defaults to five seconds.
604    ///
605    /// Applies to cancellable exec methods and buffered client timeouts. They
606    /// send SIGTERM, wait this long, send SIGKILL, and await the direct child.
607    /// A dropped future does not use it: `Drop` cannot wait, so it kills
608    /// immediately.
609    #[must_use]
610    pub fn termination_grace(mut self, duration: Duration) -> Self {
611        self.termination_grace = Some(duration);
612        self
613    }
614
615    /// Whether each run gets its own process group. On by default.
616    ///
617    /// With a group of its own, cancelling a run reaches the subprocesses
618    /// codex spawned for tool use, not just codex itself (#78). That is the
619    /// right contract for a supervisor that cancels programmatically.
620    ///
621    /// Opting out puts the child in the parent's group, so a terminal Ctrl-C
622    /// reaches the whole run directly. Then a wrapper-side kill reaches only
623    /// the direct child, and its subprocesses survive. That is the right
624    /// contract for a terminal-attached host that shells out synchronously and
625    /// treats the terminal as the supervisor.
626    ///
627    /// Matches `claude-wrapper`'s option of the same name. No effect on
628    /// non-unix targets, which have no process groups.
629    #[must_use]
630    pub fn process_group(mut self, enabled: bool) -> Self {
631        self.process_group = Some(enabled);
632        self
633    }
634
635    /// Observe every child this client spawns, at spawn time.
636    ///
637    /// The observer fires before the run produces output, including for
638    /// buffered, streaming, stdin, cancellable, and retried runs. A retry
639    /// fires once per attempt because each attempt is a distinct process.
640    ///
641    /// The observer runs inline on the spawning thread and must not block.
642    /// A supervisor can use it to write a pidfile or send the receipt to a
643    /// channel before the child can be orphaned.
644    #[must_use]
645    pub fn on_spawn(mut self, observer: SpawnObserver) -> Self {
646        self.on_spawn = Some(observer);
647        self
648    }
649
650    /// Ask the kernel to kill spawned children when this process dies.
651    ///
652    /// This uses `PR_SET_PDEATHSIG` on Linux. Check
653    /// [`die_with_parent_supported`](crate::exec::die_with_parent_supported)
654    /// before relying on it; other targets accept the option as a no-op. A
655    /// portable supervisor should combine this with [`on_spawn`](Self::on_spawn)
656    /// and reconcile recorded children after a restart.
657    ///
658    /// The post-fork hook closes the parent-death race by rechecking the
659    /// parent after arming the signal. This is off by default because it is
660    /// appropriate for supervised work but not for deliberately backgrounded
661    /// CLI processes.
662    #[must_use]
663    pub fn die_with_parent(mut self, enabled: bool) -> Self {
664        self.die_with_parent = enabled;
665        self
666    }
667
668    /// Append a raw global argument passed before any subcommand.
669    ///
670    /// When an exec command has a typed rollout budget, conflicting global
671    /// `--enable/--disable rollout_budget` arguments are suppressed at final
672    /// assembly. Codex applies feature toggles after config regardless of argv
673    /// order, so retaining one could silently defeat the typed protection.
674    #[must_use]
675    pub fn arg(mut self, arg: impl Into<String>) -> Self {
676        self.global_args.push(arg.into());
677        self
678    }
679
680    /// Add a global config override (`-c key=value`).
681    #[must_use]
682    pub fn config(mut self, key_value: impl Into<String>) -> Self {
683        self.global_args.push("-c".into());
684        self.global_args.push(key_value.into());
685        self
686    }
687
688    /// Enable a feature flag globally (`--enable <name>`).
689    ///
690    /// A `rollout_budget` toggle is suppressed for an exec command that has a
691    /// typed [`RolloutBudgetConfig`].
692    #[must_use]
693    pub fn enable(mut self, feature: impl Into<String>) -> Self {
694        self.global_args.push("--enable".into());
695        self.global_args.push(feature.into());
696        self
697    }
698
699    /// Disable a feature flag globally (`--disable <name>`).
700    ///
701    /// A `rollout_budget` toggle is suppressed for an exec command that has a
702    /// typed [`RolloutBudgetConfig`].
703    #[must_use]
704    pub fn disable(mut self, feature: impl Into<String>) -> Self {
705        self.global_args.push("--disable".into());
706        self.global_args.push(feature.into());
707        self
708    }
709
710    /// Set a default [`RetryPolicy`] for all commands.
711    #[must_use]
712    pub fn retry(mut self, policy: RetryPolicy) -> Self {
713        self.retry_policy = Some(policy);
714        self
715    }
716
717    /// Build the [`Codex`] client.
718    ///
719    /// Returns [`Error::NotFound`] if no binary path was set and `codex` is
720    /// not found in `PATH`.
721    pub fn build(self) -> Result<Codex> {
722        let binary = match self.binary {
723            Some(path) => path,
724            None => which::which("codex").map_err(|_| Error::NotFound)?,
725        };
726
727        Ok(Codex {
728            binary,
729            working_dir: self.working_dir,
730            env: self.env,
731            clear_env: self.clear_env,
732            global_args: self.global_args,
733            termination_grace: self
734                .termination_grace
735                .unwrap_or_else(|| Duration::from_secs(5)),
736            process_group: self.process_group.unwrap_or(true),
737            die_with_parent: self.die_with_parent,
738            on_spawn: self.on_spawn,
739            timeout: self.timeout,
740            retry_policy: self.retry_policy,
741            tested_cli_version_range: self.tested_cli_version_range.unwrap_or((
742                version::TESTED_CLI_VERSION_MIN,
743                version::TESTED_CLI_VERSION_MAX,
744            )),
745        })
746    }
747}
748
749impl fmt::Debug for CodexBuilder {
750    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
751        let mut env_keys: Vec<&str> = self.env.keys().map(String::as_str).collect();
752        env_keys.sort_unstable();
753
754        f.debug_struct("CodexBuilder")
755            .field("binary", &self.binary)
756            .field("working_dir", &self.working_dir)
757            .field("env_keys", &env_keys)
758            .field("clear_env", &self.clear_env)
759            .field("global_args", &self.global_args)
760            .field("timeout", &self.timeout)
761            .field("termination_grace", &self.termination_grace)
762            .field("process_group", &self.process_group)
763            .field("die_with_parent", &self.die_with_parent)
764            .field("has_spawn_observer", &self.on_spawn.is_some())
765            .field("retry_policy", &self.retry_policy)
766            .field("tested_cli_version_range", &self.tested_cli_version_range)
767            .finish()
768    }
769}
770
771#[cfg(test)]
772mod tests {
773    use super::*;
774
775    #[test]
776    fn builder_with_binary() {
777        let codex = Codex::builder()
778            .binary("/usr/local/bin/codex")
779            .env("FOO", "bar")
780            .timeout_secs(60)
781            .build()
782            .unwrap();
783
784        assert_eq!(codex.binary, PathBuf::from("/usr/local/bin/codex"));
785        assert_eq!(codex.env.get("FOO").unwrap(), "bar");
786        assert!(!codex.clear_env);
787        assert_eq!(codex.timeout, Some(Duration::from_secs(60)));
788    }
789
790    #[test]
791    fn clear_env_is_opt_in_and_keeps_explicit_entries() {
792        let codex = Codex::builder()
793            .binary("/bin/echo")
794            .env("BEFORE_CLEAR", "one")
795            .clear_env()
796            .env("AFTER_CLEAR", "two")
797            .build()
798            .unwrap();
799
800        assert!(codex.clear_env);
801        assert_eq!(
802            codex.env.get("BEFORE_CLEAR").map(String::as_str),
803            Some("one")
804        );
805        assert_eq!(
806            codex.env.get("AFTER_CLEAR").map(String::as_str),
807            Some("two")
808        );
809    }
810
811    #[test]
812    fn client_and_builder_debug_hide_environment_values() {
813        let builder = Codex::builder()
814            .binary("/bin/echo")
815            .env("CODEX_WRAPPER_SECRET", "debug-must-not-leak-this");
816
817        let builder_debug = format!("{builder:?}");
818        assert!(builder_debug.contains("CODEX_WRAPPER_SECRET"));
819        assert!(!builder_debug.contains("debug-must-not-leak-this"));
820
821        let codex = builder.build().unwrap();
822        let client_debug = format!("{codex:?}");
823        assert!(client_debug.contains("CODEX_WRAPPER_SECRET"));
824        assert!(!client_debug.contains("debug-must-not-leak-this"));
825    }
826
827    /// Read-side helpers must answer from the environment the child receives,
828    /// not from ambient values that `clear_env` removes at spawn time.
829    #[cfg(any(feature = "json", feature = "config"))]
830    #[test]
831    fn effective_environment_lookup_obeys_clear_env() {
832        let ambient_path = std::env::var("PATH").expect("test process must have PATH");
833        let inherited = Codex::builder().binary("/bin/echo").build().unwrap();
834        assert_eq!(inherited.environment_value("PATH"), Some(ambient_path));
835
836        let cleared = Codex::builder()
837            .binary("/bin/echo")
838            .clear_env()
839            .build()
840            .unwrap();
841        assert_eq!(cleared.environment_value("PATH"), None);
842
843        let explicit = Codex::builder()
844            .binary("/bin/echo")
845            .clear_env()
846            .env("PATH", "/intentional/bin")
847            .build()
848            .unwrap();
849        assert_eq!(
850            explicit.environment_value("PATH").as_deref(),
851            Some("/intentional/bin")
852        );
853    }
854
855    #[test]
856    fn builder_global_args() {
857        let codex = Codex::builder()
858            .binary("/usr/local/bin/codex")
859            .config("model=\"gpt-5\"")
860            .enable("foo")
861            .disable("bar")
862            .build()
863            .unwrap();
864
865        assert_eq!(
866            codex.global_args,
867            vec![
868                "-c",
869                "model=\"gpt-5\"",
870                "--enable",
871                "foo",
872                "--disable",
873                "bar"
874            ]
875        );
876    }
877
878    #[test]
879    fn client_defaults_to_the_crate_tested_range() {
880        let codex = Codex::builder().binary("/bin/echo").build().unwrap();
881        assert_eq!(
882            codex.tested_cli_version_range(),
883            (
884                version::TESTED_CLI_VERSION_MIN,
885                version::TESTED_CLI_VERSION_MAX
886            )
887        );
888    }
889
890    #[test]
891    fn builder_can_override_the_tested_range() {
892        let min = CliVersion::new(1, 0, 0);
893        let max = CliVersion::new(2, 0, 0);
894        let codex = Codex::builder()
895            .binary("/bin/echo")
896            .tested_cli_version_range(min, max)
897            .build()
898            .unwrap();
899        assert_eq!(codex.tested_cli_version_range(), (min, max));
900    }
901
902    #[test]
903    fn untested_version_error_names_both_bounds() {
904        let err = Error::UntestedCliVersion {
905            found: CliVersion::new(0, 200, 0),
906            tested_min: CliVersion::new(0, 145, 0),
907            tested_max: CliVersion::new(0, 146, 0),
908        };
909        assert_eq!(
910            err.to_string(),
911            "CLI version 0.200.0 is outside the tested range 0.145.0..=0.146.0"
912        );
913    }
914
915    /// A CODEX_HOME set on the client must win over the process environment,
916    /// or a client pointed at a different home reports the wrong credentials.
917    #[cfg(feature = "json")]
918    #[test]
919    fn auth_status_honors_a_client_codex_home() {
920        let dir =
921            std::env::temp_dir().join(format!("codex-wrapper-client-auth-{}", std::process::id()));
922        let _ = std::fs::remove_dir_all(&dir);
923        std::fs::create_dir_all(&dir).unwrap();
924        std::fs::write(
925            dir.join("auth.json"),
926            r#"{"auth_mode":"apikey","OPENAI_API_KEY":"sk-secret"}"#,
927        )
928        .unwrap();
929
930        let codex = Codex::builder()
931            .binary("/bin/echo")
932            .env("CODEX_HOME", dir.to_str().unwrap())
933            .build()
934            .unwrap();
935
936        let status = codex.auth_status();
937        assert_eq!(status.codex_home, dir);
938        assert!(status.is_configured());
939        assert!(
940            !format!("{status:?}").contains("sk-secret"),
941            "the credential leaked into the status"
942        );
943
944        let _ = std::fs::remove_dir_all(&dir);
945    }
946
947    #[cfg(feature = "json")]
948    #[test]
949    fn auth_status_does_not_fall_back_to_ambient_home_when_cleared() {
950        let codex = Codex::builder()
951            .binary("/bin/echo")
952            .clear_env()
953            .build()
954            .unwrap();
955
956        assert_eq!(codex.auth_status().codex_home, PathBuf::from(".codex"));
957    }
958}