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