claude-wrapper 0.12.1

A type-safe Claude Code CLI wrapper for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
use std::path::PathBuf;

use crate::auth::AuthErrorKind;

/// Errors returned by claude-wrapper operations.
///
/// This enum is `#[non_exhaustive]`: new variants may be added in
/// future releases without a major version bump, so downstream `match`
/// expressions must include a wildcard (`_ =>`) arm. Matching on the
/// specific variants you care about (e.g. [`Error::Auth`],
/// [`Error::MaxTurnsExceeded`]) keeps working across upgrades.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The `claude` binary was not found in PATH.
    #[error("claude binary not found in PATH")]
    NotFound,

    /// A claude command failed with a non-zero exit code.
    #[error("claude 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}") })]
    CommandFailed {
        command: String,
        exit_code: i32,
        stdout: String,
        stderr: String,
        working_dir: Option<PathBuf>,
    },

    /// An I/O error occurred while spawning or communicating with the process.
    #[error("io error: {message}{}", working_dir.as_ref().map(|d| format!(" (in {})", d.display())).unwrap_or_default())]
    Io {
        message: String,
        #[source]
        source: std::io::Error,
        working_dir: Option<PathBuf>,
    },

    /// The command timed out.
    #[error("claude command timed out after {timeout_seconds}s")]
    Timeout { timeout_seconds: u64 },

    /// JSON parsing failed.
    #[cfg(feature = "json")]
    #[error("json parse error: {message}")]
    Json {
        message: String,
        #[source]
        source: serde_json::Error,
    },

    /// The installed CLI version does not meet the minimum requirement.
    #[error("CLI version {found} does not meet minimum requirement {minimum}")]
    VersionMismatch {
        found: crate::version::CliVersion,
        minimum: crate::version::CliVersion,
    },

    /// Construction of a `dangerous::Client` was attempted without
    /// the opt-in env-var set. The env-var name is a compile-time
    /// constant exported from [`crate::dangerous::ALLOW_ENV`].
    #[error(
        "dangerous operations are not allowed; set the env var `{env_var}=1` at process start if you really mean it"
    )]
    DangerousNotAllowed { env_var: &'static str },

    /// A configured [`BudgetTracker`](crate::budget::BudgetTracker) has
    /// hit its `max_usd` ceiling. Raised before the next call is
    /// dispatched, so the CLI is not invoked.
    #[error("budget exceeded: ${total_usd:.4} spent, ${max_usd:.4} max")]
    BudgetExceeded { total_usd: f64, max_usd: f64 },

    /// A [`DuplexSession`](crate::duplex::DuplexSession) operation was
    /// attempted after the session task exited (child died, EOF on
    /// stdout, or the session was closed). Pending replies are
    /// resolved with this error.
    #[cfg(feature = "async")]
    #[error("duplex session is closed")]
    DuplexClosed,

    /// [`DuplexSession::send`](crate::duplex::DuplexSession::send) was
    /// called while another turn is already in flight. Wait for the
    /// outstanding turn to resolve before issuing another.
    #[cfg(feature = "async")]
    #[error("duplex session has a turn in flight")]
    DuplexTurnInFlight,

    /// A control request issued from
    /// [`DuplexSession::interrupt`](crate::duplex::DuplexSession::interrupt)
    /// (or any other outbound `control_request`) was answered by the
    /// CLI with a `subtype: "error"` payload.
    #[cfg(feature = "async")]
    #[error("duplex control request failed: {message}")]
    DuplexControlFailed {
        /// The error message extracted from the CLI's control_response.
        message: String,
    },

    /// A history-module operation (parsing or locating session
    /// JSONL under `~/.claude/projects/`) failed in a way that
    /// doesn't fit the I/O or JSON variants -- e.g. unknown
    /// session id, missing user home directory.
    #[error("history error: {message}")]
    History {
        /// Human-readable description of what went wrong.
        message: String,
    },

    /// An artifacts-module operation (parsing or locating files
    /// under `~/.claude/agents/`, `~/.claude/skills/`, and friends)
    /// failed in a way that doesn't fit the I/O variant -- e.g.
    /// unknown agent/skill name, missing user home directory.
    #[error("artifacts error: {message}")]
    Artifacts {
        /// Human-readable description of what went wrong.
        message: String,
    },

    /// A worktrees-module operation (running or parsing
    /// `git worktree list --porcelain`) failed in a way that
    /// doesn't fit the I/O variant -- e.g. git not on PATH,
    /// path isn't a git repo, malformed porcelain output.
    #[error("worktrees error: {message}")]
    Worktrees {
        /// Human-readable description of what went wrong.
        message: String,
    },

    /// A `claude` invocation failed and looked auth-shaped to the
    /// classifier. Hosts can match on this variant to trigger a
    /// re-auth flow, surface a clean message, or skip retries.
    /// `kind` carries the best-effort subcategory; `message` is the
    /// stderr (or stdout fallback) the classifier matched against.
    ///
    /// Raised at exec time when [`crate::auth::classify_failure`]
    /// returns `Some(_)` for a CLI failure that would otherwise
    /// have been [`Error::CommandFailed`]. Cases the classifier
    /// missed remain `CommandFailed`; call
    /// [`Error::auth_kind`] for opt-in inspection of those.
    #[error("auth error ({kind:?}): {command} (exit code {exit_code}): {message}")]
    Auth {
        /// Best-effort classification.
        kind: AuthErrorKind,
        /// The full command line that failed.
        command: String,
        /// Process exit code.
        exit_code: i32,
        /// Human-readable message extracted from stderr (or stdout).
        message: String,
    },

    /// A `--max-turns`-capped run exhausted its turn budget. The CLI
    /// emits a terminal `result` event with `subtype ==
    /// "error_max_turns"` (exit 1, with the result JSON on stdout),
    /// which would otherwise fold into [`Error::CommandFailed`].
    ///
    /// This is distinct from a genuine failure: the working tree may
    /// be fine and the run simply hit the cap mid-task. Orchestrators
    /// can match this variant to finish the lifecycle (run remaining
    /// gates, commit) rather than treating it as broken or re-parsing
    /// the trace for `error_max_turns`.
    ///
    /// Raised by [`Error::from_command_failure`] ahead of the auth
    /// classifier. Only detected when the result event is present on
    /// stdout (the `json` / `stream-json` output formats); text-mode
    /// failures without it remain [`Error::CommandFailed`].
    #[error("claude hit the --max-turns cap{}: {command} (exit code {exit_code})", max_turns.map(|n| format!(" of {n}")).unwrap_or_default())]
    MaxTurnsExceeded {
        /// The full command line that failed.
        command: String,
        /// Process exit code (1).
        exit_code: i32,
        /// The configured `--max-turns` cap, parsed from the result
        /// event ("Reached maximum number of turns (N)") when present.
        max_turns: Option<u32>,
    },
}

impl Error {
    /// Construct an [`Error`] from a CLI failure. Runs the
    /// auth-error classifier; if it matches, returns
    /// [`Error::Auth`]. Otherwise returns [`Error::CommandFailed`]
    /// unchanged.
    ///
    /// This is the canonical entry point for raising failures from
    /// `exec.rs`-shaped sites -- replacing direct construction of
    /// `CommandFailed` ensures every consumer benefits from typed
    /// auth errors automatically.
    pub fn from_command_failure(
        command: String,
        exit_code: i32,
        stdout: String,
        stderr: String,
        working_dir: Option<PathBuf>,
    ) -> Self {
        // A --max-turns cap hit is a terminal `result` event with
        // subtype "error_max_turns" on stdout. Surface it as its own
        // typed variant -- ahead of the auth classifier, since it is
        // never auth-shaped -- so consumers can tell "hit the cap"
        // (recoverable) from a genuine failure.
        if stdout.contains("\"error_max_turns\"") {
            return Self::MaxTurnsExceeded {
                command,
                exit_code,
                max_turns: parse_max_turns_cap(&stdout),
            };
        }
        if let Some(kind) = crate::auth::classify_failure(exit_code, &stdout, &stderr) {
            // Prefer stderr for the human-facing message; fall back
            // to stdout when stderr is empty (some CLIs send all
            // diagnostics to stdout).
            let message = if !stderr.trim().is_empty() {
                stderr.trim().to_string()
            } else {
                stdout.trim().to_string()
            };
            Self::Auth {
                kind,
                command,
                exit_code,
                message,
            }
        } else {
            Self::CommandFailed {
                command,
                exit_code,
                stdout,
                stderr,
                working_dir,
            }
        }
    }

    /// Inspect whether this error is auth-shaped. Returns
    /// `Some(kind)` for [`Error::Auth`] (the auto-typed path) and
    /// also re-runs [`crate::auth::classify_failure`] on
    /// [`Error::CommandFailed`] for cases the constructor missed.
    /// Returns `None` for everything else (`Io`, `Timeout`, etc.).
    ///
    /// Most consumers should match on [`Error::Auth`] directly --
    /// this method is the escape hatch for low-confidence
    /// classifier patterns the constructor was too conservative
    /// about.
    pub fn auth_kind(&self) -> Option<AuthErrorKind> {
        match self {
            Self::Auth { kind, .. } => Some(*kind),
            Self::CommandFailed {
                exit_code,
                stdout,
                stderr,
                ..
            } => crate::auth::classify_failure(*exit_code, stdout, stderr),
            _ => None,
        }
    }
}

/// Parse the configured `--max-turns` cap from a CLI result event's
/// human-readable error ("Reached maximum number of turns (N)").
/// Returns `None` when the phrase or a parseable number is absent.
fn parse_max_turns_cap(stdout: &str) -> Option<u32> {
    stdout
        .split("maximum number of turns (")
        .nth(1)
        .and_then(|rest| rest.split(')').next())
        .and_then(|n| n.trim().parse::<u32>().ok())
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Self::Io {
            message: e.to_string(),
            source: e,
            working_dir: None,
        }
    }
}

/// Result type alias for claude-wrapper operations.
pub type Result<T> = std::result::Result<T, Error>;

#[cfg(test)]
mod tests {
    use super::*;

    fn command_failed(stdout: &str, stderr: &str, working_dir: Option<PathBuf>) -> Error {
        Error::CommandFailed {
            command: "/bin/claude --print".to_string(),
            exit_code: 7,
            stdout: stdout.to_string(),
            stderr: stderr.to_string(),
            working_dir,
        }
    }

    #[test]
    fn command_failed_display_includes_command_and_exit_code() {
        let e = command_failed("", "", None);
        let s = e.to_string();
        assert!(s.contains("/bin/claude --print"));
        assert!(s.contains("exit code 7"));
    }

    #[test]
    fn command_failed_display_omits_empty_stdout_and_stderr() {
        let s = command_failed("", "", None).to_string();
        assert!(!s.contains("stdout:"));
        assert!(!s.contains("stderr:"));
    }

    #[test]
    fn command_failed_display_includes_nonempty_stdout() {
        let s = command_failed("hello", "", None).to_string();
        assert!(s.contains("stdout: hello"));
    }

    #[test]
    fn command_failed_display_includes_nonempty_stderr() {
        let s = command_failed("", "boom", None).to_string();
        assert!(s.contains("stderr: boom"));
    }

    #[test]
    fn command_failed_display_includes_both_streams_when_present() {
        let s = command_failed("out", "err", None).to_string();
        assert!(s.contains("stdout: out"));
        assert!(s.contains("stderr: err"));
    }

    #[test]
    fn command_failed_display_includes_working_dir_when_present() {
        let s = command_failed("", "", Some(PathBuf::from("/tmp/proj"))).to_string();
        assert!(s.contains("/tmp/proj"));
    }

    #[test]
    fn command_failed_display_omits_working_dir_when_absent() {
        let s = command_failed("", "", None).to_string();
        assert!(!s.contains("(in "));
    }

    #[test]
    fn timeout_display_formats_seconds() {
        let s = Error::Timeout {
            timeout_seconds: 42,
        }
        .to_string();
        assert!(s.contains("42s"));
    }

    #[test]
    fn io_error_display_includes_working_dir_when_present() {
        let e = Error::Io {
            message: "spawn failed".to_string(),
            source: std::io::Error::new(std::io::ErrorKind::NotFound, "no file"),
            working_dir: Some(PathBuf::from("/work")),
        };
        let s = e.to_string();
        assert!(s.contains("spawn failed"));
        assert!(s.contains("/work"));
    }

    // -- from_command_failure / auth_kind ---------------------------

    #[test]
    fn from_command_failure_unrelated_stderr_yields_command_failed() {
        let e = Error::from_command_failure(
            "claude --print".into(),
            1,
            String::new(),
            "syntax error".into(),
            None,
        );
        assert!(matches!(e, Error::CommandFailed { .. }));
        assert_eq!(e.auth_kind(), None);
    }

    #[test]
    fn from_command_failure_auth_stderr_yields_auth_variant() {
        let e = Error::from_command_failure(
            "claude --print".into(),
            1,
            String::new(),
            "Not authenticated. Run `claude login`.".into(),
            None,
        );
        match &e {
            Error::Auth { kind, message, .. } => {
                assert_eq!(*kind, AuthErrorKind::NotAuthenticated);
                assert!(message.contains("Not authenticated"));
            }
            other => panic!("expected Auth, got {other:?}"),
        }
        assert_eq!(e.auth_kind(), Some(AuthErrorKind::NotAuthenticated));
    }

    #[test]
    fn from_command_failure_uses_stdout_message_when_stderr_empty() {
        let e = Error::from_command_failure(
            "claude --print".into(),
            1,
            "Invalid API key".into(),
            String::new(),
            None,
        );
        match &e {
            Error::Auth { message, kind, .. } => {
                assert_eq!(*kind, AuthErrorKind::InvalidCredentials);
                assert_eq!(message, "Invalid API key");
            }
            other => panic!("expected Auth, got {other:?}"),
        }
    }

    #[test]
    fn auth_kind_inspects_command_failed_for_missed_classifications() {
        // The constructor would have caught this, but a hand-built
        // CommandFailed (e.g. constructed by older code or by a
        // caller not going through the helper) is still inspectable.
        let e = Error::CommandFailed {
            command: "claude --print".into(),
            exit_code: 1,
            stdout: String::new(),
            stderr: "401 Unauthorized".into(),
            working_dir: None,
        };
        assert_eq!(e.auth_kind(), Some(AuthErrorKind::InvalidCredentials));
    }

    #[test]
    fn auth_kind_returns_none_for_non_command_errors() {
        assert_eq!(Error::NotFound.auth_kind(), None);
        assert_eq!(Error::Timeout { timeout_seconds: 5 }.auth_kind(), None);
    }

    // -- max-turns classification (#641) ----------------------------

    // Exact shape of a --max-turns cap-hit result event, from the
    // field (claude 2.1.173, --output-format json).
    const MAX_TURNS_STDOUT: &str = r#"{"type":"result","subtype":"error_max_turns","is_error":true,"num_turns":2,"session_id":"s1","total_cost_usd":0.08,"terminal_reason":"max_turns","errors":["Reached maximum number of turns (1)"]}"#;

    #[test]
    fn from_command_failure_max_turns_yields_typed_variant() {
        let e = Error::from_command_failure(
            "claude --print --max-turns 1".into(),
            1,
            MAX_TURNS_STDOUT.into(),
            String::new(),
            None,
        );
        match e {
            Error::MaxTurnsExceeded {
                max_turns,
                exit_code,
                ..
            } => {
                assert_eq!(max_turns, Some(1));
                assert_eq!(exit_code, 1);
            }
            other => panic!("expected MaxTurnsExceeded, got {other:?}"),
        }
    }

    #[test]
    fn max_turns_detected_without_parseable_cap() {
        let stdout = r#"{"type":"result","subtype":"error_max_turns","is_error":true}"#;
        let e = Error::from_command_failure("c".into(), 1, stdout.into(), String::new(), None);
        match e {
            Error::MaxTurnsExceeded { max_turns, .. } => assert_eq!(max_turns, None),
            other => panic!("expected MaxTurnsExceeded, got {other:?}"),
        }
    }

    #[test]
    fn non_max_turns_failure_stays_command_failed() {
        let e =
            Error::from_command_failure("c".into(), 1, "other output".into(), "boom".into(), None);
        assert!(matches!(e, Error::CommandFailed { .. }));
    }

    #[test]
    fn max_turns_check_does_not_swallow_auth() {
        // A genuine auth failure (no error_max_turns) still classifies
        // as Auth -- the max-turns guard precedes but doesn't shadow it.
        let e = Error::from_command_failure(
            "c".into(),
            1,
            String::new(),
            "Not authenticated. Run `claude login`.".into(),
            None,
        );
        assert!(matches!(e, Error::Auth { .. }));
    }

    #[test]
    fn parse_max_turns_cap_variants() {
        assert_eq!(
            parse_max_turns_cap("Reached maximum number of turns (3)"),
            Some(3)
        );
        assert_eq!(parse_max_turns_cap(MAX_TURNS_STDOUT), Some(1));
        assert_eq!(parse_max_turns_cap("no such phrase"), None);
        assert_eq!(parse_max_turns_cap("maximum number of turns (nope)"), None);
    }

    #[test]
    fn max_turns_display_includes_cap() {
        let s = Error::MaxTurnsExceeded {
            command: "claude --print".into(),
            exit_code: 1,
            max_turns: Some(5),
        }
        .to_string();
        assert!(s.contains("--max-turns"), "got: {s}");
        assert!(s.contains("of 5"), "got: {s}");
    }
}