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    // Add new variants at the end of the enum, below the last one. The enum has no
212    // `#[repr]`, so inserting a variant earlier shifts the implicit
213    // discriminant of every variant after it, which `cargo-semver-checks`
214    // reports as a breaking change (`enum_no_repr_variant_discriminant_changed`)
215    // and which makes release-plz propose a major version. `Error` carries
216    // data, so no caller can read those values with `as`; the lint is stricter
217    // than it needs to be, and it still decides the version.
218    /// `codex app-server` answered a request with a JSON-RPC error.
219    ///
220    /// `code` and `message` are the server's own. `method` is the request that
221    /// failed, for example `turn/steer`.
222    #[cfg(feature = "app-server")]
223    #[error("codex app-server rejected `{method}`: {message} (code {code})")]
224    AppServerRpc {
225        /// The request method that was rejected.
226        method: String,
227        /// The JSON-RPC error code.
228        code: i64,
229        /// The server's error message.
230        message: String,
231        /// Additional error data, when the server sent any.
232        data: Option<serde_json::Value>,
233    },
234
235    /// The connection to `codex app-server` failed, or the server sent
236    /// something that is not valid JSON-RPC.
237    ///
238    /// Covers the server exiting or being stopped while a request was waiting,
239    /// a session that has already ended, and a stream that could not be read or
240    /// written. When the server wrote to stderr, the last lines are included.
241    #[cfg(feature = "app-server")]
242    #[error("codex app-server protocol error: {message}")]
243    AppServerProtocol {
244        /// What went wrong.
245        message: String,
246    },
247
248    /// A run was being stopped, and stopping or reaping its process failed.
249    ///
250    /// Cancellation, a timeout, an exceeded output limit, a parse error, or an
251    /// I/O error on the child's pipes each end a run by terminating the owned
252    /// process group and waiting on the direct child. When that cleanup
253    /// succeeds the original error is returned unchanged. When it fails, this
254    /// is returned instead, so a caller is never told [`Error::Cancelled`] or
255    /// [`Error::Timeout`] about a child that may not have been reaped and could
256    /// still be running.
257    ///
258    /// Match on `reason` for why the run was stopped. `cleanup` is the
259    /// [`source`](std::error::Error::source) of this error, so a reporter
260    /// walking the chain reaches the underlying I/O failure.
261    ///
262    /// Not retried by [`RetryPolicy`](crate::RetryPolicy), even when `reason`
263    /// is a timeout: the previous attempt's process is not known to be gone.
264    #[error("{reason}; cleanup of the codex process then failed, so it may not have been reaped")]
265    CleanupFailed {
266        /// The error the run would have returned had cleanup succeeded.
267        reason: Box<Error>,
268        /// The failure from stopping or waiting on the child.
269        #[source]
270        cleanup: Box<Error>,
271    },
272}
273
274impl From<std::io::Error> for Error {
275    fn from(e: std::io::Error) -> Self {
276        Self::Io {
277            message: e.to_string(),
278            source: e,
279            working_dir: None,
280        }
281    }
282}
283
284/// Result type alias for codex-wrapper operations.
285pub type Result<T> = std::result::Result<T, Error>;
286
287/// The first non-empty line of a message, for a one-line `Display`.
288fn first_line(message: &str) -> &str {
289    message
290        .lines()
291        .map(str::trim)
292        .find(|line| !line.is_empty())
293        .unwrap_or(message)
294}
295
296/// The class of a failed command, for matching without destructuring.
297///
298/// Returned by [`Error::failure_kind`].
299#[derive(Debug, Clone, Copy, PartialEq, Eq)]
300#[non_exhaustive]
301pub enum FailureKind {
302    /// The CLI could not authenticate.
303    Auth,
304    /// The CLI rejected the configuration before running.
305    Config,
306    /// The working directory was not trusted.
307    NotTrustedDirectory,
308    /// The session or thread being resumed does not exist.
309    SessionNotFound,
310    /// A non-zero exit that matched no known signature.
311    Unclassified,
312}
313
314/// Signatures observed on `codex-cli` 0.145.0, each from a captured failing
315/// run. Matched against stderr, since every one of them exits 1: the exit code
316/// carries no information here.
317///
318/// Deliberately matched on the stable part of each message. The auth line, for
319/// instance, also carries a request id and a `cf-ray` header that differ every
320/// time.
321const SIGNATURES: &[(&str, FailureKind)] = &[
322    ("401 Unauthorized", FailureKind::Auth),
323    ("Missing bearer or basic authentication", FailureKind::Auth),
324    (
325        "Not inside a trusted directory",
326        FailureKind::NotTrustedDirectory,
327    ),
328    ("Error loading config.toml", FailureKind::Config),
329    ("unknown configuration field", FailureKind::Config),
330    (
331        "no rollout found for thread id",
332        FailureKind::SessionNotFound,
333    ),
334];
335
336impl Error {
337    /// The error to return for a run stopped with `reason`, given how cleanup
338    /// of its process went.
339    ///
340    /// Every path that stops a child before returning goes through here, so
341    /// a failed cleanup cannot be reported as the bare stop reason.
342    pub(crate) fn after_cleanup(reason: Error, cleanup: Result<()>) -> Self {
343        match cleanup {
344            Ok(()) => reason,
345            Err(cleanup) => Error::CleanupFailed {
346                reason: Box::new(reason),
347                cleanup: Box::new(cleanup),
348            },
349        }
350    }
351
352    /// Build an error from a failed command, classifying it by stderr.
353    ///
354    /// Every non-zero exit in this crate goes through here, so a caller can
355    /// branch on the class rather than substring-matching stderr themselves.
356    /// An unrecognized failure stays [`Error::CommandFailed`] with its output
357    /// intact, so classification never loses information.
358    ///
359    /// Classification is by message, because it has to be: every failure
360    /// observed on 0.145.0 exits 1. That makes it sensitive to the CLI
361    /// rewording a message, which is the cost of doing it here instead of in
362    /// every caller. `tests/contract.rs` is where a reworded message should be
363    /// caught.
364    #[must_use]
365    pub fn from_command_failure(
366        command: String,
367        exit_code: i32,
368        stdout: String,
369        stderr: String,
370        working_dir: Option<PathBuf>,
371    ) -> Self {
372        let message = stderr.trim().to_string();
373
374        let kind = SIGNATURES
375            .iter()
376            .find(|(needle, _)| message.contains(needle))
377            .map(|(_, kind)| *kind);
378
379        match kind {
380            Some(FailureKind::Auth) => Error::Auth {
381                message,
382                command,
383                exit_code,
384                working_dir,
385            },
386            Some(FailureKind::Config) => Error::Config {
387                message,
388                command,
389                exit_code,
390                working_dir,
391            },
392            Some(FailureKind::NotTrustedDirectory) => Error::NotTrustedDirectory {
393                message,
394                command,
395                exit_code,
396                working_dir,
397            },
398            Some(FailureKind::SessionNotFound) => Error::SessionNotFound {
399                message,
400                command,
401                exit_code,
402                working_dir,
403            },
404            _ => Error::CommandFailed {
405                command,
406                exit_code,
407                stdout,
408                stderr,
409                working_dir,
410            },
411        }
412    }
413
414    /// The class of this failure, or `None` if it is not a command failure.
415    #[must_use]
416    pub fn failure_kind(&self) -> Option<FailureKind> {
417        match self {
418            Error::Auth { .. } => Some(FailureKind::Auth),
419            Error::Config { .. } => Some(FailureKind::Config),
420            Error::NotTrustedDirectory { .. } => Some(FailureKind::NotTrustedDirectory),
421            Error::SessionNotFound { .. } => Some(FailureKind::SessionNotFound),
422            Error::CommandFailed { .. } => Some(FailureKind::Unclassified),
423            _ => None,
424        }
425    }
426
427    /// The process exit code, for any variant that came from one.
428    ///
429    /// Classification moved some failures off [`Error::CommandFailed`], so
430    /// anything reading an exit code should read it here rather than matching
431    /// that one variant.
432    #[must_use]
433    pub fn exit_code(&self) -> Option<i32> {
434        match self {
435            Error::CommandFailed { exit_code, .. }
436            | Error::Auth { exit_code, .. }
437            | Error::Config { exit_code, .. }
438            | Error::NotTrustedDirectory { exit_code, .. }
439            | Error::SessionNotFound { exit_code, .. } => Some(*exit_code),
440            _ => None,
441        }
442    }
443
444    /// Whether re-running the identical command could plausibly succeed.
445    ///
446    /// False for the classified failures: each is a deterministic rejection,
447    /// and the CLI has already retried the auth case internally before it
448    /// surfaces here.
449    #[must_use]
450    pub fn is_deterministic_failure(&self) -> bool {
451        matches!(
452            self,
453            Error::Auth { .. }
454                | Error::Config { .. }
455                | Error::NotTrustedDirectory { .. }
456                | Error::SessionNotFound { .. }
457        )
458    }
459}
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464
465    #[test]
466    fn display_not_found() {
467        let err = Error::NotFound;
468        assert_eq!(err.to_string(), "codex binary not found in PATH");
469    }
470
471    #[test]
472    fn display_command_failed_minimal() {
473        let err = Error::CommandFailed {
474            command: "exec".to_string(),
475            exit_code: 1,
476            stdout: String::new(),
477            stderr: String::new(),
478            working_dir: None,
479        };
480        assert_eq!(err.to_string(), "codex command failed: exec (exit code 1)");
481    }
482
483    #[test]
484    fn display_command_failed_with_all_fields() {
485        let err = Error::CommandFailed {
486            command: "exec".to_string(),
487            exit_code: 2,
488            stdout: "out".to_string(),
489            stderr: "err".to_string(),
490            working_dir: Some(PathBuf::from("/tmp")),
491        };
492        assert_eq!(
493            err.to_string(),
494            "codex command failed: exec (exit code 2) (in /tmp)\nstdout: out\nstderr: err"
495        );
496    }
497
498    #[test]
499    fn display_io_without_working_dir() {
500        let source = std::io::Error::other("disk full");
501        let err = Error::Io {
502            message: source.to_string(),
503            source,
504            working_dir: None,
505        };
506        assert_eq!(err.to_string(), "io error: disk full");
507    }
508
509    #[test]
510    fn display_io_with_working_dir() {
511        let source = std::io::Error::other("disk full");
512        let err = Error::Io {
513            message: source.to_string(),
514            source,
515            working_dir: Some(PathBuf::from("/home/user")),
516        };
517        assert_eq!(err.to_string(), "io error: disk full (in /home/user)");
518    }
519
520    #[test]
521    fn display_timeout() {
522        let err = Error::Timeout {
523            timeout_seconds: 30,
524        };
525        assert_eq!(err.to_string(), "codex command timed out after 30s");
526    }
527
528    #[cfg(feature = "json")]
529    #[test]
530    fn display_json() {
531        let source: serde_json::Error =
532            serde_json::from_str::<serde_json::Value>("invalid").unwrap_err();
533        let err = Error::Json {
534            message: source.to_string(),
535            source,
536        };
537        assert!(err.to_string().starts_with("json parse error:"));
538    }
539
540    #[test]
541    fn display_version_mismatch() {
542        let err = Error::VersionMismatch {
543            found: crate::version::CliVersion::new(0, 100, 0),
544            minimum: crate::version::CliVersion::new(0, 145, 0),
545        };
546        assert_eq!(
547            err.to_string(),
548            "CLI version 0.100.0 does not meet minimum requirement 0.145.0"
549        );
550    }
551
552    // ---------------------------------------------------------------
553    // Classification (#85)
554    // ---------------------------------------------------------------
555
556    fn classify(stderr: &str) -> Error {
557        Error::from_command_failure(
558            "codex exec hi".into(),
559            1,
560            String::new(),
561            stderr.into(),
562            None,
563        )
564    }
565
566    /// Each string is transcribed from a captured codex-cli 0.145.0 failure,
567    /// varying parts and all.
568    #[test]
569    fn classifies_every_captured_signature() {
570        let cases: &[(&str, FailureKind)] = &[
571            (
572                "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",
573                FailureKind::Auth,
574            ),
575            (
576                "Not inside a trusted directory and --skip-git-repo-check was not specified.",
577                FailureKind::NotTrustedDirectory,
578            ),
579            (
580                "Error loading config.toml: unknown configuration field `bogus` in -c/--config override",
581                FailureKind::Config,
582            ),
583            (
584                "Error: thread/resume: thread/resume failed: no rollout found for thread id 00000000-0000-0000-0000-000000000000 (code -32600)",
585                FailureKind::SessionNotFound,
586            ),
587        ];
588
589        for (stderr, expected) in cases {
590            let err = classify(stderr);
591            assert_eq!(
592                err.failure_kind(),
593                Some(*expected),
594                "misclassified: {stderr}"
595            );
596            assert_eq!(err.exit_code(), Some(1));
597            assert!(err.is_deterministic_failure(), "{stderr}");
598        }
599    }
600
601    /// An unrecognized failure must keep its output rather than being forced
602    /// into a class. Classification is allowed to not know.
603    #[test]
604    fn an_unknown_failure_stays_command_failed_with_its_output() {
605        let err = Error::from_command_failure(
606            "codex exec hi".into(),
607            2,
608            "partial stdout".into(),
609            "something new the CLI started saying".into(),
610            None,
611        );
612
613        assert_eq!(err.failure_kind(), Some(FailureKind::Unclassified));
614        assert!(!err.is_deterministic_failure());
615        match err {
616            Error::CommandFailed {
617                stdout,
618                stderr,
619                exit_code,
620                ..
621            } => {
622                assert_eq!(stdout, "partial stdout");
623                assert_eq!(stderr, "something new the CLI started saying");
624                assert_eq!(exit_code, 2);
625            }
626            other => panic!("expected CommandFailed, got {other:?}"),
627        }
628    }
629
630    /// The whole of stderr is kept, not just the matched line, so nothing is
631    /// lost to classification.
632    #[test]
633    fn a_classified_failure_keeps_the_full_message() {
634        let err = classify(
635            "ERROR: Reconnecting... 5/5\nERROR: unexpected status 401 Unauthorized: Missing bearer",
636        );
637        match &err {
638            Error::Auth { message, .. } => {
639                assert!(message.contains("Reconnecting... 5/5"), "{message}");
640                assert!(message.contains("401 Unauthorized"), "{message}");
641            }
642            other => panic!("expected Auth, got {other:?}"),
643        }
644        // Display stays one line, leading with the first thing stderr said.
645        assert_eq!(
646            err.to_string(),
647            "codex authentication failed: ERROR: Reconnecting... 5/5"
648        );
649    }
650
651    #[test]
652    fn successful_cleanup_returns_the_stop_reason_unchanged() {
653        let err = Error::after_cleanup(Error::Timeout { timeout_seconds: 7 }, Ok(()));
654        assert!(
655            matches!(err, Error::Timeout { timeout_seconds: 7 }),
656            "{err:?}"
657        );
658    }
659
660    /// The reason stays matchable and readable, and the cleanup failure is
661    /// the source, so walking the chain reaches the I/O error beneath it.
662    #[test]
663    fn failed_cleanup_carries_the_reason_and_chains_to_the_cleanup_error() {
664        let cleanup = Error::from(std::io::Error::other("wait failed"));
665        let err = Error::after_cleanup(Error::Cancelled { grace_seconds: 2 }, Err(cleanup));
666
667        assert_eq!(
668            err.to_string(),
669            "codex run cancelled (after a 2s grace period); cleanup of the codex process \
670             then failed, so it may not have been reaped"
671        );
672        let Error::CleanupFailed { reason, .. } = &err else {
673            panic!("expected CleanupFailed, got {err:?}");
674        };
675        assert!(
676            matches!(**reason, Error::Cancelled { grace_seconds: 2 }),
677            "{reason:?}"
678        );
679
680        let source = std::error::Error::source(&err).expect("cleanup is the source");
681        assert_eq!(source.to_string(), "io error: wait failed");
682        let io = source.source().expect("the I/O error is reachable");
683        assert_eq!(io.to_string(), "wait failed");
684
685        // The child did not exit on its own terms, so no exit code is
686        // reported even if the wrapped reason were to carry one.
687        assert_eq!(err.failure_kind(), None);
688        assert_eq!(err.exit_code(), None);
689    }
690
691    #[test]
692    fn non_command_errors_have_no_failure_kind() {
693        assert_eq!(Error::NotFound.failure_kind(), None);
694        assert_eq!(Error::Timeout { timeout_seconds: 5 }.failure_kind(), None);
695        assert_eq!(Error::NotFound.exit_code(), None);
696    }
697}