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