Skip to main content

codex_wrapper/
error.rs

1//! Error types for `codex-wrapper`.
2
3use std::path::PathBuf;
4
5/// Which of a child's captured streams an [`Error::OutputLimitExceeded`]
6/// refers to.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum OutputStream {
9    /// The child's standard output.
10    Stdout,
11    /// The child's standard error.
12    Stderr,
13}
14
15impl std::fmt::Display for OutputStream {
16    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17        f.write_str(match self {
18            Self::Stdout => "stdout",
19            Self::Stderr => "stderr",
20        })
21    }
22}
23
24/// Errors returned by `codex-wrapper` operations.
25///
26/// This enum is `#[non_exhaustive]`: match arms must include a `_` catch-all so
27/// new variants can be added without a breaking change. This mirrors
28/// `claude-wrapper`'s `Error` for cross-crate consistency.
29#[derive(Debug, thiserror::Error)]
30#[non_exhaustive]
31pub enum Error {
32    /// The `codex` binary was not found in PATH.
33    #[error("codex binary not found in PATH")]
34    NotFound,
35
36    /// A captured stream passed the ceiling set by
37    /// [`CodexBuilder::output_limit`](crate::CodexBuilder::output_limit).
38    ///
39    /// The run is stopped the same way [`Error::Cancelled`] and
40    /// [`Error::Timeout`] stop it, so the child does not keep writing into a
41    /// buffer nothing will read. No captured bytes are carried here: output
42    /// seen before the ceiling tripped is logged at warn instead, because
43    /// returning a prefix as if it were the result is the truncated success
44    /// this exists to prevent.
45    ///
46    /// The ceiling is off by default and this error cannot occur while it is
47    /// unset.
48    #[error("codex {stream} exceeded the {limit_bytes}-byte capture limit")]
49    OutputLimitExceeded {
50        /// Which captured stream exceeded the ceiling.
51        stream: OutputStream,
52        /// The configured ceiling, in bytes, that was exceeded.
53        limit_bytes: usize,
54    },
55
56    /// The CLI could not authenticate.
57    ///
58    /// Classified from stderr by [`Error::from_command_failure`]; see
59    /// [`FailureKind`] for what that costs. Not retried: the CLI has already
60    /// retried internally by the time this surfaces, and the credentials will
61    /// not have changed.
62    #[error("codex authentication failed: {}", first_line(message))]
63    Auth {
64        /// The CLI's stderr, trimmed. Retained whole rather than reduced to
65        /// the matched line, so nothing is lost to classification.
66        message: String,
67        command: String,
68        exit_code: i32,
69        working_dir: Option<PathBuf>,
70    },
71
72    /// The CLI rejected the configuration before running.
73    ///
74    /// An unknown key under `--strict-config`, or a malformed override.
75    #[error("codex rejected the configuration: {}", first_line(message))]
76    Config {
77        /// The CLI's stderr, trimmed.
78        message: String,
79        command: String,
80        exit_code: i32,
81        working_dir: Option<PathBuf>,
82    },
83
84    /// The working directory is not a trusted directory or git repo, and
85    /// `--skip-git-repo-check` was not set.
86    #[error("codex refused an untrusted directory: {}", first_line(message))]
87    NotTrustedDirectory {
88        /// The CLI's stderr, trimmed.
89        message: String,
90        command: String,
91        exit_code: i32,
92        working_dir: Option<PathBuf>,
93    },
94
95    /// The session or thread being resumed does not exist.
96    #[error("codex session not found: {}", first_line(message))]
97    SessionNotFound {
98        /// The CLI's stderr, trimmed.
99        message: String,
100        command: String,
101        exit_code: i32,
102        working_dir: Option<PathBuf>,
103    },
104
105    /// A codex command failed with a non-zero exit code.
106    #[error("codex command failed: {command} (exit code {exit_code}){}{}{}", working_dir.as_ref().map(|d| format!(" (in {})", d.display())).unwrap_or_default(), if stdout.is_empty() { String::new() } else { format!("\nstdout: {stdout}") }, if stderr.is_empty() { String::new() } else { format!("\nstderr: {stderr}") })]
107    CommandFailed {
108        command: String,
109        exit_code: i32,
110        stdout: String,
111        stderr: String,
112        working_dir: Option<PathBuf>,
113    },
114
115    /// An I/O error occurred while spawning or communicating with the process.
116    #[error("io error: {message}{}", working_dir.as_ref().map(|d| format!(" (in {})", d.display())).unwrap_or_default())]
117    Io {
118        message: String,
119        #[source]
120        source: std::io::Error,
121        working_dir: Option<PathBuf>,
122    },
123
124    /// The command timed out.
125    #[error("codex command timed out after {timeout_seconds}s")]
126    Timeout { timeout_seconds: u64 },
127
128    /// A session's token budget was reached.
129    ///
130    /// Denominated in tokens rather than money because the CLI reports token
131    /// counts and no cost; see [`crate::budget`].
132    #[error("token budget exceeded: {total_tokens} of {max_tokens} tokens")]
133    TokenBudgetExceeded {
134        /// Tokens recorded when the ceiling was hit. May exceed `max_tokens`,
135        /// since a turn's usage is only known once it has been spent.
136        total_tokens: u64,
137        /// The configured ceiling.
138        max_tokens: u64,
139    },
140
141    /// A native rollout-budget configuration was invalid before launch.
142    #[error("invalid Codex rollout budget: {message}")]
143    InvalidRolloutBudget {
144        /// The failed invariant.
145        message: String,
146    },
147
148    /// A file on disk could not be parsed.
149    ///
150    /// Distinct from [`Error::Config`], which is the CLI rejecting a
151    /// configuration it was given. This one never ran a command, so it
152    /// carries no exit code and is not a [`FailureKind`].
153    #[cfg(feature = "config")]
154    #[error("failed to parse {}: {message}", path.display())]
155    ConfigParse {
156        /// The file that could not be parsed.
157        path: PathBuf,
158        /// The parser's message.
159        message: String,
160    },
161
162    /// A bypass of codex's safety controls was requested without permission.
163    ///
164    /// See [`crate::dangerous`]. Never a command failure: nothing ran.
165    #[error("bypassing codex safety controls requires {variable} to be set")]
166    DangerousNotAllowed {
167        /// The environment variable that would have permitted it.
168        variable: &'static str,
169    },
170
171    /// The run was cancelled by the caller.
172    ///
173    /// The process group was asked to stop, given `grace_seconds`, then
174    /// killed. Distinct from [`Error::Timeout`], which is the client's own
175    /// deadline rather than the caller's decision.
176    #[error("codex run cancelled (after a {grace_seconds}s grace period)")]
177    Cancelled {
178        /// How long the group was given to exit before being killed.
179        grace_seconds: u64,
180    },
181
182    /// JSON parsing failed.
183    #[cfg(feature = "json")]
184    #[error("json parse error: {message}")]
185    Json {
186        message: String,
187        #[source]
188        source: serde_json::Error,
189    },
190
191    /// The installed CLI version does not meet the minimum requirement.
192    #[error("CLI version {found} does not meet minimum requirement {minimum}")]
193    VersionMismatch {
194        found: crate::version::CliVersion,
195        minimum: crate::version::CliVersion,
196    },
197
198    /// The installed CLI is outside the wrapper's tested-against range.
199    ///
200    /// Only returned by
201    /// [`Codex::ensure_tested_cli_version`](crate::Codex::ensure_tested_cli_version).
202    /// The default path reports drift as a
203    /// [`CliVersionStatus`](crate::CliVersionStatus) rather than an error.
204    #[error("CLI version {found} is outside the tested range {tested_min}..={tested_max}")]
205    UntestedCliVersion {
206        found: crate::version::CliVersion,
207        tested_min: crate::version::CliVersion,
208        tested_max: crate::version::CliVersion,
209    },
210}
211
212impl From<std::io::Error> for Error {
213    fn from(e: std::io::Error) -> Self {
214        Self::Io {
215            message: e.to_string(),
216            source: e,
217            working_dir: None,
218        }
219    }
220}
221
222/// Result type alias for codex-wrapper operations.
223pub type Result<T> = std::result::Result<T, Error>;
224
225/// The first non-empty line of a message, for a one-line `Display`.
226fn first_line(message: &str) -> &str {
227    message
228        .lines()
229        .map(str::trim)
230        .find(|line| !line.is_empty())
231        .unwrap_or(message)
232}
233
234/// The class of a failed command, for matching without destructuring.
235///
236/// Returned by [`Error::failure_kind`].
237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238#[non_exhaustive]
239pub enum FailureKind {
240    /// The CLI could not authenticate.
241    Auth,
242    /// The CLI rejected the configuration before running.
243    Config,
244    /// The working directory was not trusted.
245    NotTrustedDirectory,
246    /// The session or thread being resumed does not exist.
247    SessionNotFound,
248    /// A non-zero exit that matched no known signature.
249    Unclassified,
250}
251
252/// Signatures observed on `codex-cli` 0.145.0, each from a captured failing
253/// run. Matched against stderr, since every one of them exits 1: the exit code
254/// carries no information here.
255///
256/// Deliberately matched on the stable part of each message. The auth line, for
257/// instance, also carries a request id and a `cf-ray` header that differ every
258/// time.
259const SIGNATURES: &[(&str, FailureKind)] = &[
260    ("401 Unauthorized", FailureKind::Auth),
261    ("Missing bearer or basic authentication", FailureKind::Auth),
262    (
263        "Not inside a trusted directory",
264        FailureKind::NotTrustedDirectory,
265    ),
266    ("Error loading config.toml", FailureKind::Config),
267    ("unknown configuration field", FailureKind::Config),
268    (
269        "no rollout found for thread id",
270        FailureKind::SessionNotFound,
271    ),
272];
273
274impl Error {
275    /// Build an error from a failed command, classifying it by stderr.
276    ///
277    /// Every non-zero exit in this crate goes through here, so a caller can
278    /// branch on the class rather than substring-matching stderr themselves.
279    /// An unrecognized failure stays [`Error::CommandFailed`] with its output
280    /// intact, so classification never loses information.
281    ///
282    /// Classification is by message, because it has to be: every failure
283    /// observed on 0.145.0 exits 1. That makes it sensitive to the CLI
284    /// rewording a message, which is the cost of doing it here instead of in
285    /// every caller. `tests/contract.rs` is where a reworded message should be
286    /// caught.
287    #[must_use]
288    pub fn from_command_failure(
289        command: String,
290        exit_code: i32,
291        stdout: String,
292        stderr: String,
293        working_dir: Option<PathBuf>,
294    ) -> Self {
295        let message = stderr.trim().to_string();
296
297        let kind = SIGNATURES
298            .iter()
299            .find(|(needle, _)| message.contains(needle))
300            .map(|(_, kind)| *kind);
301
302        match kind {
303            Some(FailureKind::Auth) => Error::Auth {
304                message,
305                command,
306                exit_code,
307                working_dir,
308            },
309            Some(FailureKind::Config) => Error::Config {
310                message,
311                command,
312                exit_code,
313                working_dir,
314            },
315            Some(FailureKind::NotTrustedDirectory) => Error::NotTrustedDirectory {
316                message,
317                command,
318                exit_code,
319                working_dir,
320            },
321            Some(FailureKind::SessionNotFound) => Error::SessionNotFound {
322                message,
323                command,
324                exit_code,
325                working_dir,
326            },
327            _ => Error::CommandFailed {
328                command,
329                exit_code,
330                stdout,
331                stderr,
332                working_dir,
333            },
334        }
335    }
336
337    /// The class of this failure, or `None` if it is not a command failure.
338    #[must_use]
339    pub fn failure_kind(&self) -> Option<FailureKind> {
340        match self {
341            Error::Auth { .. } => Some(FailureKind::Auth),
342            Error::Config { .. } => Some(FailureKind::Config),
343            Error::NotTrustedDirectory { .. } => Some(FailureKind::NotTrustedDirectory),
344            Error::SessionNotFound { .. } => Some(FailureKind::SessionNotFound),
345            Error::CommandFailed { .. } => Some(FailureKind::Unclassified),
346            _ => None,
347        }
348    }
349
350    /// The process exit code, for any variant that came from one.
351    ///
352    /// Classification moved some failures off [`Error::CommandFailed`], so
353    /// anything reading an exit code should read it here rather than matching
354    /// that one variant.
355    #[must_use]
356    pub fn exit_code(&self) -> Option<i32> {
357        match self {
358            Error::CommandFailed { exit_code, .. }
359            | Error::Auth { exit_code, .. }
360            | Error::Config { exit_code, .. }
361            | Error::NotTrustedDirectory { exit_code, .. }
362            | Error::SessionNotFound { exit_code, .. } => Some(*exit_code),
363            _ => None,
364        }
365    }
366
367    /// Whether re-running the identical command could plausibly succeed.
368    ///
369    /// False for the classified failures: each is a deterministic rejection,
370    /// and the CLI has already retried the auth case internally before it
371    /// surfaces here.
372    #[must_use]
373    pub fn is_deterministic_failure(&self) -> bool {
374        matches!(
375            self,
376            Error::Auth { .. }
377                | Error::Config { .. }
378                | Error::NotTrustedDirectory { .. }
379                | Error::SessionNotFound { .. }
380        )
381    }
382}
383
384#[cfg(test)]
385mod tests {
386    use super::*;
387
388    #[test]
389    fn display_not_found() {
390        let err = Error::NotFound;
391        assert_eq!(err.to_string(), "codex binary not found in PATH");
392    }
393
394    #[test]
395    fn display_command_failed_minimal() {
396        let err = Error::CommandFailed {
397            command: "exec".to_string(),
398            exit_code: 1,
399            stdout: String::new(),
400            stderr: String::new(),
401            working_dir: None,
402        };
403        assert_eq!(err.to_string(), "codex command failed: exec (exit code 1)");
404    }
405
406    #[test]
407    fn display_command_failed_with_all_fields() {
408        let err = Error::CommandFailed {
409            command: "exec".to_string(),
410            exit_code: 2,
411            stdout: "out".to_string(),
412            stderr: "err".to_string(),
413            working_dir: Some(PathBuf::from("/tmp")),
414        };
415        assert_eq!(
416            err.to_string(),
417            "codex command failed: exec (exit code 2) (in /tmp)\nstdout: out\nstderr: err"
418        );
419    }
420
421    #[test]
422    fn display_io_without_working_dir() {
423        let source = std::io::Error::other("disk full");
424        let err = Error::Io {
425            message: source.to_string(),
426            source,
427            working_dir: None,
428        };
429        assert_eq!(err.to_string(), "io error: disk full");
430    }
431
432    #[test]
433    fn display_io_with_working_dir() {
434        let source = std::io::Error::other("disk full");
435        let err = Error::Io {
436            message: source.to_string(),
437            source,
438            working_dir: Some(PathBuf::from("/home/user")),
439        };
440        assert_eq!(err.to_string(), "io error: disk full (in /home/user)");
441    }
442
443    #[test]
444    fn display_timeout() {
445        let err = Error::Timeout {
446            timeout_seconds: 30,
447        };
448        assert_eq!(err.to_string(), "codex command timed out after 30s");
449    }
450
451    #[cfg(feature = "json")]
452    #[test]
453    fn display_json() {
454        let source: serde_json::Error =
455            serde_json::from_str::<serde_json::Value>("invalid").unwrap_err();
456        let err = Error::Json {
457            message: source.to_string(),
458            source,
459        };
460        assert!(err.to_string().starts_with("json parse error:"));
461    }
462
463    #[test]
464    fn display_version_mismatch() {
465        let err = Error::VersionMismatch {
466            found: crate::version::CliVersion::new(0, 100, 0),
467            minimum: crate::version::CliVersion::new(0, 145, 0),
468        };
469        assert_eq!(
470            err.to_string(),
471            "CLI version 0.100.0 does not meet minimum requirement 0.145.0"
472        );
473    }
474
475    // ---------------------------------------------------------------
476    // Classification (#85)
477    // ---------------------------------------------------------------
478
479    fn classify(stderr: &str) -> Error {
480        Error::from_command_failure(
481            "codex exec hi".into(),
482            1,
483            String::new(),
484            stderr.into(),
485            None,
486        )
487    }
488
489    /// Each string is transcribed from a captured codex-cli 0.145.0 failure,
490    /// varying parts and all.
491    #[test]
492    fn classifies_every_captured_signature() {
493        let cases: &[(&str, FailureKind)] = &[
494            (
495                "ERROR: unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: https://api.openai.com/v1/responses, cf-ray: a272310168bcba62-SJC, request id: req_ef11",
496                FailureKind::Auth,
497            ),
498            (
499                "Not inside a trusted directory and --skip-git-repo-check was not specified.",
500                FailureKind::NotTrustedDirectory,
501            ),
502            (
503                "Error loading config.toml: unknown configuration field `bogus` in -c/--config override",
504                FailureKind::Config,
505            ),
506            (
507                "Error: thread/resume: thread/resume failed: no rollout found for thread id 00000000-0000-0000-0000-000000000000 (code -32600)",
508                FailureKind::SessionNotFound,
509            ),
510        ];
511
512        for (stderr, expected) in cases {
513            let err = classify(stderr);
514            assert_eq!(
515                err.failure_kind(),
516                Some(*expected),
517                "misclassified: {stderr}"
518            );
519            assert_eq!(err.exit_code(), Some(1));
520            assert!(err.is_deterministic_failure(), "{stderr}");
521        }
522    }
523
524    /// An unrecognized failure must keep its output rather than being forced
525    /// into a class. Classification is allowed to not know.
526    #[test]
527    fn an_unknown_failure_stays_command_failed_with_its_output() {
528        let err = Error::from_command_failure(
529            "codex exec hi".into(),
530            2,
531            "partial stdout".into(),
532            "something new the CLI started saying".into(),
533            None,
534        );
535
536        assert_eq!(err.failure_kind(), Some(FailureKind::Unclassified));
537        assert!(!err.is_deterministic_failure());
538        match err {
539            Error::CommandFailed {
540                stdout,
541                stderr,
542                exit_code,
543                ..
544            } => {
545                assert_eq!(stdout, "partial stdout");
546                assert_eq!(stderr, "something new the CLI started saying");
547                assert_eq!(exit_code, 2);
548            }
549            other => panic!("expected CommandFailed, got {other:?}"),
550        }
551    }
552
553    /// The whole of stderr is kept, not just the matched line, so nothing is
554    /// lost to classification.
555    #[test]
556    fn a_classified_failure_keeps_the_full_message() {
557        let err = classify(
558            "ERROR: Reconnecting... 5/5\nERROR: unexpected status 401 Unauthorized: Missing bearer",
559        );
560        match &err {
561            Error::Auth { message, .. } => {
562                assert!(message.contains("Reconnecting... 5/5"), "{message}");
563                assert!(message.contains("401 Unauthorized"), "{message}");
564            }
565            other => panic!("expected Auth, got {other:?}"),
566        }
567        // Display stays one line, leading with the first thing stderr said.
568        assert_eq!(
569            err.to_string(),
570            "codex authentication failed: ERROR: Reconnecting... 5/5"
571        );
572    }
573
574    #[test]
575    fn non_command_errors_have_no_failure_kind() {
576        assert_eq!(Error::NotFound.failure_kind(), None);
577        assert_eq!(Error::Timeout { timeout_seconds: 5 }.failure_kind(), None);
578        assert_eq!(Error::NotFound.exit_code(), None);
579    }
580}