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
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
222pub type Result<T> = std::result::Result<T, Error>;
224
225fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238#[non_exhaustive]
239pub enum FailureKind {
240 Auth,
242 Config,
244 NotTrustedDirectory,
246 SessionNotFound,
248 Unclassified,
250}
251
252const 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 #[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 #[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 #[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 #[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 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 #[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 #[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 #[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 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}