1use std::path::PathBuf;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum OutputStream {
9 Stdout,
11 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#[derive(Debug, thiserror::Error)]
30#[non_exhaustive]
31pub enum Error {
32 #[error("codex binary not found in PATH")]
34 NotFound,
35
36 #[error("codex {stream} exceeded the {limit_bytes}-byte capture limit")]
49 OutputLimitExceeded {
50 stream: OutputStream,
52 limit_bytes: usize,
54 },
55
56 #[error("codex authentication failed: {}", first_line(message))]
63 Auth {
64 message: String,
67 command: String,
68 exit_code: i32,
69 working_dir: Option<PathBuf>,
70 },
71
72 #[error("codex rejected the configuration: {}", first_line(message))]
76 Config {
77 message: String,
79 command: String,
80 exit_code: i32,
81 working_dir: Option<PathBuf>,
82 },
83
84 #[error("codex refused an untrusted directory: {}", first_line(message))]
87 NotTrustedDirectory {
88 message: String,
90 command: String,
91 exit_code: i32,
92 working_dir: Option<PathBuf>,
93 },
94
95 #[error("codex session not found: {}", first_line(message))]
97 SessionNotFound {
98 message: String,
100 command: String,
101 exit_code: i32,
102 working_dir: Option<PathBuf>,
103 },
104
105 #[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 #[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 #[error("codex command timed out after {timeout_seconds}s")]
126 Timeout { timeout_seconds: u64 },
127
128 #[error("token budget exceeded: {total_tokens} of {max_tokens} tokens")]
133 TokenBudgetExceeded {
134 total_tokens: u64,
137 max_tokens: u64,
139 },
140
141 #[error("invalid Codex rollout budget: {message}")]
143 InvalidRolloutBudget {
144 message: String,
146 },
147
148 #[cfg(feature = "config")]
154 #[error("failed to parse {}: {message}", path.display())]
155 ConfigParse {
156 path: PathBuf,
158 message: String,
160 },
161
162 #[error("bypassing codex safety controls requires {variable} to be set")]
166 DangerousNotAllowed {
167 variable: &'static str,
169 },
170
171 #[error("codex run cancelled (after a {grace_seconds}s grace period)")]
177 Cancelled {
178 grace_seconds: u64,
180 },
181
182 #[cfg(feature = "json")]
184 #[error("json parse error: {message}")]
185 Json {
186 message: String,
187 #[source]
188 source: serde_json::Error,
189 },
190
191 #[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 #[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 #[cfg(feature = "app-server")]
223 #[error("codex app-server rejected `{method}`: {message} (code {code})")]
224 AppServerRpc {
225 method: String,
227 code: i64,
229 message: String,
231 data: Option<serde_json::Value>,
233 },
234
235 #[cfg(feature = "app-server")]
242 #[error("codex app-server protocol error: {message}")]
243 AppServerProtocol {
244 message: String,
246 },
247
248 #[error("{reason}; cleanup of the codex process then failed, so it may not have been reaped")]
265 CleanupFailed {
266 reason: Box<Error>,
268 #[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
284pub type Result<T> = std::result::Result<T, Error>;
286
287fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
300#[non_exhaustive]
301pub enum FailureKind {
302 Auth,
304 Config,
306 NotTrustedDirectory,
308 SessionNotFound,
310 Unclassified,
312}
313
314const 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 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 #[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 #[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 #[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 #[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 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 #[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 #[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 #[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 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 #[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 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}