codex_wrapper/error.rs
1//! Error types for `codex-wrapper`.
2
3use std::path::PathBuf;
4#[cfg(feature = "app-server")]
5use std::process::ExitStatus;
6
7/// Which of a child's captured streams an [`Error::OutputLimitExceeded`]
8/// refers to.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10pub enum OutputStream {
11 /// The child's standard output.
12 Stdout,
13 /// The child's standard error.
14 Stderr,
15}
16
17impl std::fmt::Display for OutputStream {
18 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19 f.write_str(match self {
20 Self::Stdout => "stdout",
21 Self::Stderr => "stderr",
22 })
23 }
24}
25
26/// The strongest stop action used on the owned child during app-server shutdown.
27///
28/// Today, only app-server shutdown reports this action.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum ShutdownAction {
32 /// The wrapper sent the configured Unix termination signal. The child
33 /// may have handled or ignored it before exiting.
34 Signal(crate::TerminationSignal),
35 /// The wrapper used the hard stop, SIGKILL on Unix or direct process
36 /// termination on other platforms.
37 Kill,
38}
39
40impl std::fmt::Display for ShutdownAction {
41 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42 f.write_str(match self {
43 Self::Signal(crate::TerminationSignal::Terminate) => "SIGTERM",
44 Self::Signal(crate::TerminationSignal::Interrupt) => "SIGINT",
45 Self::Kill if cfg!(unix) => "SIGKILL",
46 Self::Kill => "process termination",
47 })
48 }
49}
50
51/// Errors returned by `codex-wrapper` operations.
52///
53/// This enum is `#[non_exhaustive]`: match arms must include a `_` catch-all so
54/// new variants can be added without a breaking change. This mirrors
55/// `claude-wrapper`'s `Error` for cross-crate consistency.
56#[derive(Debug, thiserror::Error)]
57#[non_exhaustive]
58pub enum Error {
59 /// The `codex` binary was not found in PATH.
60 #[error("codex binary not found in PATH")]
61 NotFound,
62
63 /// A captured stream passed the ceiling set by
64 /// [`CodexBuilder::output_limit`](crate::CodexBuilder::output_limit).
65 ///
66 /// The run is stopped the same way [`Error::Cancelled`] and
67 /// [`Error::Timeout`] stop it, so the child does not keep writing into a
68 /// buffer nothing will read. No captured bytes are carried here: output
69 /// seen before the ceiling tripped is logged at warn instead, because
70 /// returning a prefix as if it were the result is the truncated success
71 /// this exists to prevent.
72 ///
73 /// The ceiling is off by default and this error cannot occur while it is
74 /// unset.
75 #[error("codex {stream} exceeded the {limit_bytes}-byte capture limit")]
76 OutputLimitExceeded {
77 /// Which captured stream exceeded the ceiling.
78 stream: OutputStream,
79 /// The configured ceiling, in bytes, that was exceeded.
80 limit_bytes: usize,
81 },
82
83 /// The CLI could not authenticate.
84 ///
85 /// Classified from stderr by [`Error::from_command_failure`]; see
86 /// [`FailureKind`] for what that costs. Not retried: the CLI has already
87 /// retried internally by the time this surfaces, and the credentials will
88 /// not have changed.
89 #[error("codex authentication failed: {}", first_line(message))]
90 Auth {
91 /// The CLI's stderr, trimmed. Retained whole rather than reduced to
92 /// the matched line, so nothing is lost to classification.
93 message: String,
94 command: String,
95 exit_code: i32,
96 working_dir: Option<PathBuf>,
97 },
98
99 /// The CLI rejected the configuration before running.
100 ///
101 /// An unknown key under `--strict-config`, or a malformed override.
102 #[error("codex rejected the configuration: {}", first_line(message))]
103 Config {
104 /// The CLI's stderr, trimmed.
105 message: String,
106 command: String,
107 exit_code: i32,
108 working_dir: Option<PathBuf>,
109 },
110
111 /// The working directory is not a trusted directory or git repo, and
112 /// `--skip-git-repo-check` was not set.
113 #[error("codex refused an untrusted directory: {}", first_line(message))]
114 NotTrustedDirectory {
115 /// The CLI's stderr, trimmed.
116 message: String,
117 command: String,
118 exit_code: i32,
119 working_dir: Option<PathBuf>,
120 },
121
122 /// The session or thread being resumed does not exist.
123 #[error("codex session not found: {}", first_line(message))]
124 SessionNotFound {
125 /// The CLI's stderr, trimmed.
126 message: String,
127 command: String,
128 exit_code: i32,
129 working_dir: Option<PathBuf>,
130 },
131
132 /// A codex command failed with a non-zero exit code.
133 #[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}") })]
134 CommandFailed {
135 command: String,
136 exit_code: i32,
137 stdout: String,
138 stderr: String,
139 working_dir: Option<PathBuf>,
140 },
141
142 /// An I/O error occurred while spawning or communicating with the process.
143 #[error("io error: {message}{}", working_dir.as_ref().map(|d| format!(" (in {})", d.display())).unwrap_or_default())]
144 Io {
145 message: String,
146 #[source]
147 source: std::io::Error,
148 working_dir: Option<PathBuf>,
149 },
150
151 /// The command timed out.
152 #[error("codex command timed out after {timeout_seconds}s")]
153 Timeout { timeout_seconds: u64 },
154
155 /// A session's token budget was reached.
156 ///
157 /// Denominated in tokens rather than money because the CLI reports token
158 /// counts and no cost; see [`crate::budget`].
159 #[error("token budget exceeded: {total_tokens} of {max_tokens} tokens")]
160 TokenBudgetExceeded {
161 /// Tokens recorded when the ceiling was hit. May exceed `max_tokens`,
162 /// since a turn's usage is only known once it has been spent.
163 total_tokens: u64,
164 /// The configured ceiling.
165 max_tokens: u64,
166 },
167
168 /// A native rollout-budget configuration was invalid before launch.
169 #[error("invalid Codex rollout budget: {message}")]
170 InvalidRolloutBudget {
171 /// The failed invariant.
172 message: String,
173 },
174
175 /// A file on disk could not be parsed.
176 ///
177 /// Distinct from [`Error::Config`], which is the CLI rejecting a
178 /// configuration it was given. This one never ran a command, so it
179 /// carries no exit code and is not a [`FailureKind`].
180 #[cfg(feature = "config")]
181 #[error("failed to parse {}: {message}", path.display())]
182 ConfigParse {
183 /// The file that could not be parsed.
184 path: PathBuf,
185 /// The parser's message.
186 message: String,
187 },
188
189 /// A bypass of codex's safety controls was requested without permission.
190 ///
191 /// See [`crate::dangerous`]. Never a command failure: nothing ran.
192 #[error("bypassing codex safety controls requires {variable} to be set")]
193 DangerousNotAllowed {
194 /// The environment variable that would have permitted it.
195 variable: &'static str,
196 },
197
198 /// The run was cancelled by the caller.
199 ///
200 /// The process group was asked to stop, given `grace_seconds`, then
201 /// killed. Distinct from [`Error::Timeout`], which is the client's own
202 /// deadline rather than the caller's decision.
203 #[error("codex run cancelled (after a {grace_seconds}s grace period)")]
204 Cancelled {
205 /// How long the group was given to exit before being killed.
206 grace_seconds: u64,
207 },
208
209 /// The wrapper intervened to stop its owned app-server process.
210 ///
211 /// The server has exited and been reaped. Treat the server as stopped,
212 /// with an unclean shutdown even if the status is successful. Processes
213 /// the server started in other process groups may survive.
214 #[cfg(feature = "app-server")]
215 #[non_exhaustive]
216 #[error(
217 "codex app-server forced shutdown used {action} (collected {status}){}",
218 stderr_suffix(stderr)
219 )]
220 AppServerForcedShutdown {
221 /// The strongest stop action used on the server itself. Group
222 /// cleanup may also send SIGKILL after the server has exited.
223 action: ShutdownAction,
224 /// The native status collected when the owned server was reaped.
225 status: ExitStatus,
226 /// The server's final stderr summary, if available.
227 stderr: String,
228 },
229
230 /// The owned app-server died from a signal without wrapper intervention.
231 #[cfg(feature = "app-server")]
232 #[non_exhaustive]
233 #[error(
234 "codex app-server exited after a signal ({status}){}",
235 stderr_suffix(stderr)
236 )]
237 AppServerSignaled {
238 /// The native status, including the signal on Unix.
239 status: ExitStatus,
240 /// The server's final stderr summary, if available.
241 stderr: String,
242 },
243
244 /// JSON parsing failed.
245 #[cfg(feature = "json")]
246 #[error("json parse error: {message}")]
247 Json {
248 message: String,
249 #[source]
250 source: serde_json::Error,
251 },
252
253 /// The installed CLI version does not meet the minimum requirement.
254 #[error("CLI version {found} does not meet minimum requirement {minimum}")]
255 VersionMismatch {
256 found: crate::version::CliVersion,
257 minimum: crate::version::CliVersion,
258 },
259
260 /// The installed CLI is outside the wrapper's tested-against range.
261 ///
262 /// Only returned by
263 /// [`Codex::ensure_tested_cli_version`](crate::Codex::ensure_tested_cli_version).
264 /// The default path reports drift as a
265 /// [`CliVersionStatus`](crate::CliVersionStatus) rather than an error.
266 #[error("CLI version {found} is outside the tested range {tested_min}..={tested_max}")]
267 UntestedCliVersion {
268 found: crate::version::CliVersion,
269 tested_min: crate::version::CliVersion,
270 tested_max: crate::version::CliVersion,
271 },
272
273 // Add new variants at the end of the enum, below the last one. The enum has no
274 // `#[repr]`, so inserting a variant earlier shifts the implicit
275 // discriminant of every variant after it, which `cargo-semver-checks`
276 // reports as a breaking change (`enum_no_repr_variant_discriminant_changed`)
277 // and which makes release-plz propose a major version. `Error` carries
278 // data, so no caller can read those values with `as`; the lint is stricter
279 // than it needs to be, and it still decides the version.
280 /// `codex app-server` answered a request with a JSON-RPC error.
281 ///
282 /// `code` and `message` are the server's own. `method` is the request that
283 /// failed, for example `turn/steer`.
284 #[cfg(feature = "app-server")]
285 #[error("codex app-server rejected `{method}`: {message} (code {code})")]
286 AppServerRpc {
287 /// The request method that was rejected.
288 method: String,
289 /// The JSON-RPC error code.
290 code: i64,
291 /// The server's error message.
292 message: String,
293 /// Additional error data, when the server sent any.
294 data: Option<serde_json::Value>,
295 },
296
297 /// The connection to `codex app-server` failed, or the server sent
298 /// something that is not valid JSON-RPC.
299 ///
300 /// Covers the server exiting or being stopped while a request was waiting,
301 /// a session that has already ended, and a stream that could not be read or
302 /// written. When the server wrote to stderr, the last lines are included.
303 #[cfg(feature = "app-server")]
304 #[error("codex app-server protocol error: {message}")]
305 AppServerProtocol {
306 /// What went wrong.
307 message: String,
308 },
309
310 /// A run was being stopped, and stopping or reaping its process failed.
311 ///
312 /// Cancellation, a timeout, an exceeded output limit, a parse error, or an
313 /// I/O error on the child's pipes each end a run by terminating the owned
314 /// process group and waiting on the direct child. When that cleanup
315 /// succeeds the original error is returned unchanged. When it fails, this
316 /// is returned instead, so a caller is never told [`Error::Cancelled`] or
317 /// [`Error::Timeout`] about a child that may not have been reaped and could
318 /// still be running.
319 ///
320 /// Match on `reason` for why the run was stopped. `cleanup` is the
321 /// [`source`](std::error::Error::source) of this error, so a reporter
322 /// walking the chain reaches the underlying I/O failure.
323 ///
324 /// Not retried by [`RetryPolicy`](crate::RetryPolicy), even when `reason`
325 /// is a timeout: the previous attempt's process is not known to be gone.
326 #[error("{reason}; cleanup of the codex process then failed, so it may not have been reaped")]
327 CleanupFailed {
328 /// The error the run would have returned had cleanup succeeded.
329 reason: Box<Error>,
330 /// The failure from stopping or waiting on the child.
331 #[source]
332 cleanup: Box<Error>,
333 },
334
335 /// An opt-in `codex app-server` transport limit was exceeded.
336 ///
337 /// Set with the `max_*` methods on
338 /// [`AppServerBuilder`](crate::app_server::AppServerBuilder). The
339 /// connection is ended rather than a message dropped: every waiting
340 /// request fails with this error, later sends fail at once, and the
341 /// process the client owns is killed. Distinct from
342 /// [`Error::OutputLimitExceeded`], which is the lifetime total of
343 /// [`CodexBuilder::output_limit`](crate::CodexBuilder::output_limit).
344 #[cfg(feature = "app-server")]
345 #[error("codex app-server {limit} limit of {max} exceeded")]
346 AppServerLimitExceeded {
347 /// Which limit was exceeded.
348 limit: crate::app_server::AppServerLimit,
349 /// The configured maximum.
350 max: usize,
351 },
352
353 /// An [`AppServerBuilder`](crate::app_server::AppServerBuilder) setting is
354 /// invalid. Reported by `start` before anything is spawned.
355 #[cfg(feature = "app-server")]
356 #[error("invalid codex app-server configuration: {message}")]
357 AppServerConfig {
358 /// What is wrong with the configuration.
359 message: String,
360 },
361}
362
363impl From<std::io::Error> for Error {
364 fn from(e: std::io::Error) -> Self {
365 Self::Io {
366 message: e.to_string(),
367 source: e,
368 working_dir: None,
369 }
370 }
371}
372
373/// Result type alias for codex-wrapper operations.
374pub type Result<T> = std::result::Result<T, Error>;
375
376/// The first non-empty line of a message, for a one-line `Display`.
377fn first_line(message: &str) -> &str {
378 message
379 .lines()
380 .map(str::trim)
381 .find(|line| !line.is_empty())
382 .unwrap_or(message)
383}
384
385#[cfg(feature = "app-server")]
386fn stderr_suffix(stderr: &str) -> String {
387 if stderr.is_empty() {
388 String::new()
389 } else {
390 format!("\nstderr: {stderr}")
391 }
392}
393
394/// The class of a failed command, for matching without destructuring.
395///
396/// Returned by [`Error::failure_kind`].
397#[derive(Debug, Clone, Copy, PartialEq, Eq)]
398#[non_exhaustive]
399pub enum FailureKind {
400 /// The CLI could not authenticate.
401 Auth,
402 /// The CLI rejected the configuration before running.
403 Config,
404 /// The working directory was not trusted.
405 NotTrustedDirectory,
406 /// The session or thread being resumed does not exist.
407 SessionNotFound,
408 /// A non-zero exit that matched no known signature.
409 Unclassified,
410}
411
412/// Signatures observed on `codex-cli` 0.145.0, each from a captured failing
413/// run. Matched against stderr, since every one of them exits 1: the exit code
414/// carries no information here.
415///
416/// Deliberately matched on the stable part of each message. The auth line, for
417/// instance, also carries a request id and a `cf-ray` header that differ every
418/// time.
419const SIGNATURES: &[(&str, FailureKind)] = &[
420 ("401 Unauthorized", FailureKind::Auth),
421 ("Missing bearer or basic authentication", FailureKind::Auth),
422 (
423 "Not inside a trusted directory",
424 FailureKind::NotTrustedDirectory,
425 ),
426 ("Error loading config.toml", FailureKind::Config),
427 ("unknown configuration field", FailureKind::Config),
428 (
429 "no rollout found for thread id",
430 FailureKind::SessionNotFound,
431 ),
432];
433
434impl Error {
435 /// The error to return for a run stopped with `reason`, given how cleanup
436 /// of its process went.
437 ///
438 /// Buffered and streaming exec use this to preserve the original stop
439 /// reason alongside a cleanup failure.
440 pub(crate) fn after_cleanup(reason: Error, cleanup: Result<()>) -> Self {
441 match cleanup {
442 Ok(()) => reason,
443 Err(cleanup) => Error::CleanupFailed {
444 reason: Box::new(reason),
445 cleanup: Box::new(cleanup),
446 },
447 }
448 }
449
450 /// Build an error from a failed command, classifying it by stderr.
451 ///
452 /// Ordinary non-zero exits go through here, so a caller can branch on
453 /// the class rather than substring-matching stderr themselves.
454 /// An unrecognized failure stays [`Error::CommandFailed`] with its output
455 /// intact, so classification never loses information.
456 ///
457 /// Classification is by message, because it has to be: every failure
458 /// observed on 0.145.0 exits 1. That makes it sensitive to the CLI
459 /// rewording a message, which is the cost of doing it here instead of in
460 /// every caller. `tests/contract.rs` is where a reworded message should be
461 /// caught.
462 #[must_use]
463 pub fn from_command_failure(
464 command: String,
465 exit_code: i32,
466 stdout: String,
467 stderr: String,
468 working_dir: Option<PathBuf>,
469 ) -> Self {
470 let message = stderr.trim().to_string();
471
472 let kind = SIGNATURES
473 .iter()
474 .find(|(needle, _)| message.contains(needle))
475 .map(|(_, kind)| *kind);
476
477 match kind {
478 Some(FailureKind::Auth) => Error::Auth {
479 message,
480 command,
481 exit_code,
482 working_dir,
483 },
484 Some(FailureKind::Config) => Error::Config {
485 message,
486 command,
487 exit_code,
488 working_dir,
489 },
490 Some(FailureKind::NotTrustedDirectory) => Error::NotTrustedDirectory {
491 message,
492 command,
493 exit_code,
494 working_dir,
495 },
496 Some(FailureKind::SessionNotFound) => Error::SessionNotFound {
497 message,
498 command,
499 exit_code,
500 working_dir,
501 },
502 _ => Error::CommandFailed {
503 command,
504 exit_code,
505 stdout,
506 stderr,
507 working_dir,
508 },
509 }
510 }
511
512 /// The class of this failure, or `None` if it is not a command failure.
513 #[must_use]
514 pub fn failure_kind(&self) -> Option<FailureKind> {
515 match self {
516 Error::Auth { .. } => Some(FailureKind::Auth),
517 Error::Config { .. } => Some(FailureKind::Config),
518 Error::NotTrustedDirectory { .. } => Some(FailureKind::NotTrustedDirectory),
519 Error::SessionNotFound { .. } => Some(FailureKind::SessionNotFound),
520 Error::CommandFailed { .. } => Some(FailureKind::Unclassified),
521 _ => None,
522 }
523 }
524
525 /// The process exit code, for any variant that came from one.
526 ///
527 /// Classification moved some failures off [`Error::CommandFailed`], so
528 /// anything reading an exit code should read it here rather than matching
529 /// that one variant.
530 ///
531 /// An app-server forced shutdown can return `Some(0)` if the child
532 /// responded to a stop action by exiting with code zero. A signal death
533 /// reported by app-server shutdown has no numeric exit code.
534 #[must_use]
535 pub fn exit_code(&self) -> Option<i32> {
536 match self {
537 Error::CommandFailed { exit_code, .. }
538 | Error::Auth { exit_code, .. }
539 | Error::Config { exit_code, .. }
540 | Error::NotTrustedDirectory { exit_code, .. }
541 | Error::SessionNotFound { exit_code, .. } => Some(*exit_code),
542 #[cfg(feature = "app-server")]
543 Error::AppServerForcedShutdown { status, .. } => status.code(),
544 _ => None,
545 }
546 }
547
548 /// Whether re-running the identical command could plausibly succeed.
549 ///
550 /// False for the classified failures: each is a deterministic rejection,
551 /// and the CLI has already retried the auth case internally before it
552 /// surfaces here.
553 #[must_use]
554 pub fn is_deterministic_failure(&self) -> bool {
555 matches!(
556 self,
557 Error::Auth { .. }
558 | Error::Config { .. }
559 | Error::NotTrustedDirectory { .. }
560 | Error::SessionNotFound { .. }
561 )
562 }
563}
564
565#[cfg(test)]
566mod tests {
567 use super::*;
568
569 #[test]
570 fn display_not_found() {
571 let err = Error::NotFound;
572 assert_eq!(err.to_string(), "codex binary not found in PATH");
573 }
574
575 #[test]
576 fn display_command_failed_minimal() {
577 let err = Error::CommandFailed {
578 command: "exec".to_string(),
579 exit_code: 1,
580 stdout: String::new(),
581 stderr: String::new(),
582 working_dir: None,
583 };
584 assert_eq!(err.to_string(), "codex command failed: exec (exit code 1)");
585 }
586
587 #[test]
588 fn display_command_failed_with_all_fields() {
589 let err = Error::CommandFailed {
590 command: "exec".to_string(),
591 exit_code: 2,
592 stdout: "out".to_string(),
593 stderr: "err".to_string(),
594 working_dir: Some(PathBuf::from("/tmp")),
595 };
596 assert_eq!(
597 err.to_string(),
598 "codex command failed: exec (exit code 2) (in /tmp)\nstdout: out\nstderr: err"
599 );
600 }
601
602 #[test]
603 fn display_io_without_working_dir() {
604 let source = std::io::Error::other("disk full");
605 let err = Error::Io {
606 message: source.to_string(),
607 source,
608 working_dir: None,
609 };
610 assert_eq!(err.to_string(), "io error: disk full");
611 }
612
613 #[test]
614 fn display_io_with_working_dir() {
615 let source = std::io::Error::other("disk full");
616 let err = Error::Io {
617 message: source.to_string(),
618 source,
619 working_dir: Some(PathBuf::from("/home/user")),
620 };
621 assert_eq!(err.to_string(), "io error: disk full (in /home/user)");
622 }
623
624 #[test]
625 fn display_timeout() {
626 let err = Error::Timeout {
627 timeout_seconds: 30,
628 };
629 assert_eq!(err.to_string(), "codex command timed out after 30s");
630 }
631
632 #[cfg(feature = "json")]
633 #[test]
634 fn display_json() {
635 let source: serde_json::Error =
636 serde_json::from_str::<serde_json::Value>("invalid").unwrap_err();
637 let err = Error::Json {
638 message: source.to_string(),
639 source,
640 };
641 assert!(err.to_string().starts_with("json parse error:"));
642 }
643
644 #[test]
645 fn display_version_mismatch() {
646 let err = Error::VersionMismatch {
647 found: crate::version::CliVersion::new(0, 100, 0),
648 minimum: crate::version::CliVersion::new(0, 145, 0),
649 };
650 assert_eq!(
651 err.to_string(),
652 "CLI version 0.100.0 does not meet minimum requirement 0.145.0"
653 );
654 }
655
656 // ---------------------------------------------------------------
657 // Classification (#85)
658 // ---------------------------------------------------------------
659
660 fn classify(stderr: &str) -> Error {
661 Error::from_command_failure(
662 "codex exec hi".into(),
663 1,
664 String::new(),
665 stderr.into(),
666 None,
667 )
668 }
669
670 /// Each string is transcribed from a captured codex-cli 0.145.0 failure,
671 /// varying parts and all.
672 #[test]
673 fn classifies_every_captured_signature() {
674 let cases: &[(&str, FailureKind)] = &[
675 (
676 "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",
677 FailureKind::Auth,
678 ),
679 (
680 "Not inside a trusted directory and --skip-git-repo-check was not specified.",
681 FailureKind::NotTrustedDirectory,
682 ),
683 (
684 "Error loading config.toml: unknown configuration field `bogus` in -c/--config override",
685 FailureKind::Config,
686 ),
687 (
688 "Error: thread/resume: thread/resume failed: no rollout found for thread id 00000000-0000-0000-0000-000000000000 (code -32600)",
689 FailureKind::SessionNotFound,
690 ),
691 ];
692
693 for (stderr, expected) in cases {
694 let err = classify(stderr);
695 assert_eq!(
696 err.failure_kind(),
697 Some(*expected),
698 "misclassified: {stderr}"
699 );
700 assert_eq!(err.exit_code(), Some(1));
701 assert!(err.is_deterministic_failure(), "{stderr}");
702 }
703 }
704
705 /// An unrecognized failure must keep its output rather than being forced
706 /// into a class. Classification is allowed to not know.
707 #[test]
708 fn an_unknown_failure_stays_command_failed_with_its_output() {
709 let err = Error::from_command_failure(
710 "codex exec hi".into(),
711 2,
712 "partial stdout".into(),
713 "something new the CLI started saying".into(),
714 None,
715 );
716
717 assert_eq!(err.failure_kind(), Some(FailureKind::Unclassified));
718 assert!(!err.is_deterministic_failure());
719 match err {
720 Error::CommandFailed {
721 stdout,
722 stderr,
723 exit_code,
724 ..
725 } => {
726 assert_eq!(stdout, "partial stdout");
727 assert_eq!(stderr, "something new the CLI started saying");
728 assert_eq!(exit_code, 2);
729 }
730 other => panic!("expected CommandFailed, got {other:?}"),
731 }
732 }
733
734 /// The whole of stderr is kept, not just the matched line, so nothing is
735 /// lost to classification.
736 #[test]
737 fn a_classified_failure_keeps_the_full_message() {
738 let err = classify(
739 "ERROR: Reconnecting... 5/5\nERROR: unexpected status 401 Unauthorized: Missing bearer",
740 );
741 match &err {
742 Error::Auth { message, .. } => {
743 assert!(message.contains("Reconnecting... 5/5"), "{message}");
744 assert!(message.contains("401 Unauthorized"), "{message}");
745 }
746 other => panic!("expected Auth, got {other:?}"),
747 }
748 // Display stays one line, leading with the first thing stderr said.
749 assert_eq!(
750 err.to_string(),
751 "codex authentication failed: ERROR: Reconnecting... 5/5"
752 );
753 }
754
755 #[test]
756 fn successful_cleanup_returns_the_stop_reason_unchanged() {
757 let err = Error::after_cleanup(Error::Timeout { timeout_seconds: 7 }, Ok(()));
758 assert!(
759 matches!(err, Error::Timeout { timeout_seconds: 7 }),
760 "{err:?}"
761 );
762 }
763
764 /// The reason stays matchable and readable, and the cleanup failure is
765 /// the source, so walking the chain reaches the I/O error beneath it.
766 #[test]
767 fn failed_cleanup_carries_the_reason_and_chains_to_the_cleanup_error() {
768 let cleanup = Error::from(std::io::Error::other("wait failed"));
769 let err = Error::after_cleanup(Error::Cancelled { grace_seconds: 2 }, Err(cleanup));
770
771 assert_eq!(
772 err.to_string(),
773 "codex run cancelled (after a 2s grace period); cleanup of the codex process \
774 then failed, so it may not have been reaped"
775 );
776 let Error::CleanupFailed { reason, .. } = &err else {
777 panic!("expected CleanupFailed, got {err:?}");
778 };
779 assert!(
780 matches!(**reason, Error::Cancelled { grace_seconds: 2 }),
781 "{reason:?}"
782 );
783
784 let source = std::error::Error::source(&err).expect("cleanup is the source");
785 assert_eq!(source.to_string(), "io error: wait failed");
786 let io = source.source().expect("the I/O error is reachable");
787 assert_eq!(io.to_string(), "wait failed");
788
789 // The child did not exit on its own terms, so no exit code is
790 // reported even if the wrapped reason were to carry one.
791 assert_eq!(err.failure_kind(), None);
792 assert_eq!(err.exit_code(), None);
793 }
794
795 #[test]
796 fn non_command_errors_have_no_failure_kind() {
797 assert_eq!(Error::NotFound.failure_kind(), None);
798 assert_eq!(Error::Timeout { timeout_seconds: 5 }.failure_kind(), None);
799 assert_eq!(Error::NotFound.exit_code(), None);
800 }
801}