claude-wrapper 0.13.3

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
//! Shared enums and serde types used across the command builders.
//!
//! Small value types like [`Transport`], [`Scope`], [`Effort`],
//! [`PermissionMode`], [`OutputFormat`], and [`InputFormat`] that map
//! onto `claude` CLI flag values, with `Display`/`FromStr` and serde
//! wiring so they round-trip cleanly through args and JSON.

use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

/// Transport type for MCP server connections.
///
/// # Example
///
/// ```
/// use claude_wrapper::Transport;
/// use std::str::FromStr;
///
/// let t = Transport::from_str("stdio").unwrap();
/// assert_eq!(t, Transport::Stdio);
/// assert_eq!(t.to_string(), "stdio");
///
/// let t: Transport = "http".parse().unwrap();
/// assert_eq!(t, Transport::Http);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Transport {
    /// Standard I/O transport — server runs as a subprocess.
    Stdio,
    /// HTTP transport — server accessible via URL.
    Http,
    /// Server-Sent Events transport — server accessible via URL with SSE.
    Sse,
}

impl fmt::Display for Transport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Stdio => write!(f, "stdio"),
            Self::Http => write!(f, "http"),
            Self::Sse => write!(f, "sse"),
        }
    }
}

/// Error returned when parsing an unknown transport string.
#[derive(Debug, Clone, thiserror::Error)]
#[error("unknown transport: {0}")]
pub struct TransportParseError(pub String);

impl FromStr for Transport {
    type Err = TransportParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "stdio" => Ok(Self::Stdio),
            "http" => Ok(Self::Http),
            "sse" => Ok(Self::Sse),
            other => Err(TransportParseError(other.to_string())),
        }
    }
}

impl TryFrom<&str> for Transport {
    type Error = TransportParseError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        s.parse()
    }
}

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

    #[test]
    fn from_str_accepts_known_variants() {
        assert_eq!("stdio".parse::<Transport>().unwrap(), Transport::Stdio);
        assert_eq!("http".parse::<Transport>().unwrap(), Transport::Http);
        assert_eq!("sse".parse::<Transport>().unwrap(), Transport::Sse);
    }

    #[test]
    fn from_str_returns_error_for_unknown() {
        let err = "websocket".parse::<Transport>().unwrap_err();
        assert!(err.to_string().contains("websocket"));
    }

    #[test]
    fn try_from_str_returns_error_for_unknown() {
        assert!(Transport::try_from("bogus").is_err());
    }
}

/// Output format for `--output-format`.
#[derive(Debug, Clone, Copy, Default)]
pub enum OutputFormat {
    /// Plain text output (default).
    #[default]
    Text,
    /// Single JSON result object.
    Json,
    /// Streaming NDJSON.
    StreamJson,
}

impl OutputFormat {
    pub(crate) fn as_arg(&self) -> &'static str {
        match self {
            Self::Text => "text",
            Self::Json => "json",
            Self::StreamJson => "stream-json",
        }
    }
}

/// Permission mode for `--permission-mode`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum PermissionMode {
    /// Default interactive permissions.
    #[default]
    Default,
    /// Auto-accept file edits.
    AcceptEdits,
    /// Bypass all permission checks.
    ///
    /// **Deprecated.** Reaching for this variant directly puts a
    /// bypass-mode query one keystroke away in any code path, which
    /// is exactly the footgun the variant enables. Use
    /// [`crate::dangerous::DangerousClient`] instead, which gates
    /// construction on the `CLAUDE_WRAPPER_ALLOW_DANGEROUS` env-var
    /// and makes the intent obvious at the call site. The variant
    /// itself will stay available through the current major version
    /// so existing callers keep compiling (with a deprecation
    /// warning).
    #[deprecated(
        since = "0.5.1",
        note = "use claude_wrapper::dangerous::DangerousClient instead; \
                direct BypassPermissions usage is a footgun and will go \
                away in a future major release"
    )]
    BypassPermissions,
    /// Don't ask for permissions (deny by default).
    DontAsk,
    /// Plan mode (read-only).
    Plan,
    /// Auto mode.
    Auto,
}

impl PermissionMode {
    pub(crate) fn as_arg(&self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::AcceptEdits => "acceptEdits",
            #[allow(deprecated)]
            Self::BypassPermissions => "bypassPermissions",
            Self::DontAsk => "dontAsk",
            Self::Plan => "plan",
            Self::Auto => "auto",
        }
    }
}

/// Input format for `--input-format`.
#[derive(Debug, Clone, Copy, Default)]
pub enum InputFormat {
    /// Plain text input (default).
    #[default]
    Text,
    /// Streaming JSON input.
    StreamJson,
}

impl InputFormat {
    pub(crate) fn as_arg(&self) -> &'static str {
        match self {
            Self::Text => "text",
            Self::StreamJson => "stream-json",
        }
    }
}

/// Effort level for `--effort`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Effort {
    /// Low effort.
    Low,
    /// Medium effort (default).
    Medium,
    /// High effort.
    High,
    /// Extra-high effort.
    Xhigh,
    /// Maximum effort, most thorough.
    Max,
}

impl Effort {
    pub(crate) fn as_arg(&self) -> &'static str {
        match self {
            Self::Low => "low",
            Self::Medium => "medium",
            Self::High => "high",
            Self::Xhigh => "xhigh",
            Self::Max => "max",
        }
    }
}

/// How far a hermetic seal reaches when sealing the ambient `~/.claude`
/// promptspace (`CLAUDE.md`, agents, skills, MCP servers).
///
/// Chooses the value passed to `--setting-sources`; the seal itself is
/// applied by `hermetic` / `hermetic_scoped` on
/// [`QueryCommand`](crate::QueryCommand) and
/// [`DuplexOptions`](crate::duplex::DuplexOptions), which also set
/// `--strict-mcp-config` and
/// `--exclude-dynamic-system-prompt-sections`.
///
/// A hermetic seal never touches authentication. It is distinct from
/// `--bare`, which forces API-key billing by reading auth strictly from
/// `ANTHROPIC_API_KEY` / `apiKeyHelper`; a seal leaves OAuth and
/// keychain auth working as normal.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum HermeticScope {
    /// Drop every ambient setting source: user, project, and local
    /// (`--setting-sources ""`). Only the CLI's built-in agents and
    /// defaults remain; a user-level `~/.claude` no longer leaks in.
    #[default]
    Full,
    /// Seal only the project and local ambient config while keeping the
    /// user's global `~/.claude` (`--setting-sources user`). A project
    /// `CLAUDE.md` and project-level agents stop being adopted.
    Project,
}

impl HermeticScope {
    /// The value emitted for `--setting-sources` under this scope.
    pub(crate) fn setting_sources_value(self) -> &'static str {
        match self {
            Self::Full => "",
            Self::Project => "user",
        }
    }
}

/// Scope for MCP and plugin commands.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Scope {
    /// Local scope (current directory).
    #[default]
    Local,
    /// User scope (global).
    User,
    /// Project scope.
    Project,
    /// Managed scope -- plugins installed by an outer manager
    /// rather than directly by the user. Accepted by `claude plugin
    /// update --scope managed` as of CLI 2.1.143.
    Managed,
}

impl Scope {
    pub(crate) fn as_arg(&self) -> &'static str {
        match self {
            Self::Local => "local",
            Self::User => "user",
            Self::Project => "project",
            Self::Managed => "managed",
        }
    }
}

/// Authentication status returned by `claude auth status --json`.
///
/// # Example
///
/// ```no_run
/// # async fn example() -> claude_wrapper::Result<()> {
/// let claude = claude_wrapper::Claude::builder().build()?;
/// let status = claude_wrapper::AuthStatusCommand::new()
///     .execute_json(&claude).await?;
///
/// if status.logged_in {
///     println!("Logged in as {}", status.email.unwrap_or_default());
/// }
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "json")]
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthStatus {
    /// Whether the user is currently logged in.
    #[serde(default)]
    pub logged_in: bool,
    /// Authentication method (e.g. "claude.ai").
    #[serde(default)]
    pub auth_method: Option<String>,
    /// API provider (e.g. "firstParty").
    #[serde(default)]
    pub api_provider: Option<String>,
    /// Authenticated user's email address.
    #[serde(default)]
    pub email: Option<String>,
    /// Organization ID.
    #[serde(default)]
    pub org_id: Option<String>,
    /// Organization name.
    #[serde(default)]
    pub org_name: Option<String>,
    /// Subscription type (e.g. "pro", "max").
    #[serde(default)]
    pub subscription_type: Option<String>,
    /// Any additional fields not explicitly modeled.
    #[serde(flatten)]
    pub extra: std::collections::HashMap<String, serde_json::Value>,
}

/// A message from a query result, representing one turn in the conversation.
#[cfg(feature = "json")]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct QueryMessage {
    /// The role of the message sender (e.g., "user", "assistant").
    #[serde(default)]
    pub role: String,
    /// The text content of the message.
    #[serde(default)]
    pub content: serde_json::Value,
    /// Additional fields returned by the CLI not captured in typed fields.
    #[serde(flatten)]
    pub extra: std::collections::HashMap<String, serde_json::Value>,
}

/// Result from a query with `--output-format json`.
#[cfg(feature = "json")]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct QueryResult {
    /// The text content of the query response.
    #[serde(default)]
    pub result: String,
    /// The session ID for continuing conversations.
    #[serde(default)]
    pub session_id: String,
    /// Total cost of the query in USD.
    #[serde(default, rename = "total_cost_usd", alias = "cost_usd")]
    pub cost_usd: Option<f64>,
    /// Duration of the query in milliseconds.
    #[serde(default)]
    pub duration_ms: Option<u64>,
    /// Number of conversation turns in the query.
    #[serde(default)]
    pub num_turns: Option<u32>,
    /// Whether the query resulted in an error.
    #[serde(default)]
    pub is_error: bool,
    /// Additional fields returned by the CLI not captured in typed fields.
    #[serde(flatten)]
    pub extra: std::collections::HashMap<String, serde_json::Value>,
}

#[cfg(all(test, feature = "json"))]
mod tests {
    use super::*;

    #[test]
    fn query_result_deserializes_total_cost_usd() {
        let json =
            r#"{"result":"hello","session_id":"s1","total_cost_usd":0.042,"is_error":false}"#;
        let qr: QueryResult = serde_json::from_str(json).unwrap();
        assert_eq!(qr.cost_usd, Some(0.042));
    }

    #[test]
    fn query_result_deserializes_cost_usd_alias() {
        let json = r#"{"result":"hello","session_id":"s1","cost_usd":0.01,"is_error":false}"#;
        let qr: QueryResult = serde_json::from_str(json).unwrap();
        assert_eq!(qr.cost_usd, Some(0.01));
    }

    #[test]
    fn query_result_missing_cost_defaults_to_none() {
        let json = r#"{"result":"hello","session_id":"s1","is_error":false}"#;
        let qr: QueryResult = serde_json::from_str(json).unwrap();
        assert_eq!(qr.cost_usd, None);
    }

    #[test]
    fn query_result_from_stream_result_event() {
        // Exact shape of a --output-format stream-json "result" event.
        // The flattened `extra` must absorb type/subtype without
        // breaking typed field parsing.
        let json = r#"{"type":"result","subtype":"success","result":"streamed","session_id":"sess-1","total_cost_usd":0.03,"num_turns":1,"is_error":false}"#;
        let qr: QueryResult = serde_json::from_str(json).unwrap();
        assert_eq!(qr.cost_usd, Some(0.03));
        assert_eq!(qr.num_turns, Some(1));
        assert_eq!(qr.session_id, "sess-1");
        assert_eq!(qr.result, "streamed");
        assert_eq!(
            qr.extra.get("type").and_then(|v| v.as_str()),
            Some("result")
        );
    }

    #[test]
    fn query_result_deserializes_num_turns() {
        let json = r#"{"result":"done","session_id":"s2","total_cost_usd":0.1,"num_turns":5,"is_error":false}"#;
        let qr: QueryResult = serde_json::from_str(json).unwrap();
        assert_eq!(qr.num_turns, Some(5));
        assert_eq!(qr.cost_usd, Some(0.1));
    }

    #[test]
    fn query_result_serializes_as_total_cost_usd() {
        let qr = QueryResult {
            result: "ok".into(),
            session_id: "s1".into(),
            cost_usd: Some(0.05),
            duration_ms: None,
            num_turns: Some(3),
            is_error: false,
            extra: Default::default(),
        };
        let json = serde_json::to_string(&qr).unwrap();
        assert!(json.contains("\"total_cost_usd\""));
        assert!(json.contains("\"num_turns\""));
    }
}