claudecode 0.1.20

A Rust SDK for programmatically interacting with Claude Code
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
use crate::config::MCPConfig;
use crate::config::SessionConfig;
use crate::error::ClaudeError;
use crate::error::Result;
use crate::process::ProcessHandle;
use crate::process::expand_tilde;
use crate::process::find_claude_in_path;
use crate::session::Session;
use crate::types::Result as ClaudeResult;
use std::path::Path;
use std::path::PathBuf;
use tempfile::NamedTempFile;
use tokio::fs;
use tracing::debug;

#[derive(Debug, Clone)]
pub struct Client {
    claude_path: PathBuf,
}

impl Client {
    /// Create a new client by finding claude in PATH
    pub async fn new() -> Result<Self> {
        let claude_path = find_claude_in_path().await?;
        Ok(Self { claude_path })
    }

    /// Create a new client with a specific claude path
    pub async fn with_path(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        if !fs::try_exists(path).await.unwrap_or(false) {
            return Err(ClaudeError::ClaudeNotFoundAtPath {
                path: path.to_path_buf(),
            });
        }
        Ok(Self {
            claude_path: path.to_path_buf(),
        })
    }

    /// Launch a new Claude session asynchronously
    pub async fn launch(&self, config: SessionConfig) -> Result<Session> {
        config.validate()?;

        let (args, mcp_file) = self.build_args(&config).await?;
        debug!("Launching claude with args: {:?}", args);

        // Prepare working directory
        let working_dir = config
            .working_dir
            .as_ref()
            .map(|dir| expand_tilde(dir.to_str().unwrap_or("")));

        let process = ProcessHandle::spawn(
            &self.claude_path,
            args,
            working_dir.as_deref(),
            config.env.as_ref(),
        )
        .await?;

        // Store the temp file in the session to keep it alive
        let mut session = Session::new(config, process).await?;
        if let Some(temp_file) = mcp_file {
            session.set_mcp_temp_file(temp_file);
        }
        Ok(session)
    }

    /// Launch a session and wait for it to complete
    pub async fn launch_and_wait(&self, config: SessionConfig) -> Result<ClaudeResult> {
        let session = self.launch(config).await?;
        session.wait().await
    }

    /// Probe the CLI for supported capabilities.
    ///
    /// This runs `claude --help` and parses the output to detect supported flags.
    /// Useful for validating SDK compatibility with the installed CLI version.
    ///
    /// # Example
    /// ```ignore
    /// let client = Client::new().await?;
    /// let caps = client.probe_cli().await?;
    ///
    /// if caps.supports("--permission-mode") {
    ///     println!("Permission mode is supported");
    /// }
    /// ```
    pub async fn probe_cli(&self) -> Result<crate::probe::CliCapabilities> {
        crate::probe::probe_cli(&self.claude_path).await
    }

    async fn build_args(
        &self,
        config: &SessionConfig,
    ) -> Result<(Vec<String>, Option<NamedTempFile>)> {
        let mut args = Vec::new();
        let mut mcp_file = None;

        // Add print flag for non-interactive mode
        args.push("--print".to_string());

        // Models
        if let Some(model) = config.model {
            args.push("--model".to_string());
            args.push(model.to_string());
        }
        if let Some(model) = config.fallback_model {
            args.push("--fallback-model".to_string());
            args.push(model.to_string());
        }

        // Formats
        args.push("--output-format".to_string());
        args.push(config.output_format.to_string());
        if let Some(ref format) = config.input_format {
            args.push("--input-format".to_string());
            args.push(format.to_string());
        }

        // MCP config
        if let Some(ref mcp) = config.mcp_config {
            let temp_file = self.write_mcp_config(mcp).await?;
            args.push("--mcp-config".to_string());
            args.push(temp_file.path().to_string_lossy().to_string());
            mcp_file = Some(temp_file);
        }
        if config.strict_mcp_config {
            args.push("--strict-mcp-config".to_string());
        }

        // Permissions
        if let Some(ref mode) = config.permission_mode {
            args.push("--permission-mode".to_string());
            args.push(mode.to_string());
        }
        if config.allow_dangerously_skip_permissions {
            args.push("--allow-dangerously-skip-permissions".to_string());
        }
        if config.dangerously_skip_permissions {
            args.push("--dangerously-skip-permissions".to_string());
        }

        // Prompts
        if let Some(ref prompt) = config.system_prompt {
            args.push("--system-prompt".to_string());
            args.push(prompt.clone());
        }
        if let Some(ref prompt) = config.append_system_prompt {
            args.push("--append-system-prompt".to_string());
            args.push(prompt.clone());
        }

        // Tools
        if let Some(ref tools) = config.tools {
            args.push("--tools".to_string());
            args.push(tools.join(","));
        }
        if let Some(ref tools) = config.allowed_tools {
            args.push("--allowedTools".to_string());
            args.push(tools.join(","));
        }
        if let Some(ref tools) = config.disallowed_tools {
            args.push("--disallowedTools".to_string());
            args.push(tools.join(","));
        }

        // Output shaping
        if let Some(ref schema) = config.json_schema {
            args.push("--json-schema".to_string());
            args.push(schema.clone());
        }
        if config.include_partial_messages {
            args.push("--include-partial-messages".to_string());
        }
        if config.replay_user_messages {
            args.push("--replay-user-messages".to_string());
        }

        // Configuration
        if let Some(ref settings) = config.settings {
            args.push("--settings".to_string());
            args.push(settings.clone());
        }
        if let Some(ref sources) = config.setting_sources {
            args.push("--setting-sources".to_string());
            args.push(sources.join(","));
        }

        // Directories and plugins (repeatable flags)
        for dir in &config.additional_dirs {
            let expanded = expand_tilde(dir.to_string_lossy().as_ref());
            let path = tokio::fs::canonicalize(&expanded).await.unwrap_or(expanded);
            args.push("--add-dir".to_string());
            args.push(path.to_string_lossy().to_string());
        }
        for dir in &config.plugin_dirs {
            let expanded = expand_tilde(dir.to_string_lossy().as_ref());
            let path = tokio::fs::canonicalize(&expanded).await.unwrap_or(expanded);
            args.push("--plugin-dir".to_string());
            args.push(path.to_string_lossy().to_string());
        }
        if config.ide {
            args.push("--ide".to_string());
        }

        // Advanced
        if let Some(ref agents) = config.agents {
            args.push("--agents".to_string());
            args.push(agents.clone());
        }
        if config.debug {
            args.push("--debug".to_string());
            if let Some(ref filter) = config.debug_filter {
                args.push(filter.clone());
            }
        }

        // Session semantics
        if let Some(ref id) = config.resume_session_id {
            args.push("--resume".to_string());
            args.push(id.clone());
        }
        if let Some(ref id) = config.explicit_session_id {
            args.push("--session-id".to_string());
            args.push(id.clone());
        }
        if config.continue_last_session {
            args.push("--continue".to_string());
        }
        if config.fork_session {
            args.push("--fork-session".to_string());
        }

        // Auto-add verbose flag for streaming JSON or if explicitly requested
        if config.output_format == crate::types::OutputFormat::StreamingJson || config.verbose {
            args.push("--verbose".to_string());
        }

        // Always add -- separator before query to protect dash-prefixed queries
        args.push("--".to_string());
        args.push(config.query.clone());

        Ok((args, mcp_file))
    }

    async fn write_mcp_config(&self, config: &MCPConfig) -> Result<NamedTempFile> {
        let temp_file = NamedTempFile::new()?;
        let json = serde_json::to_string_pretty(config)?;
        fs::write(temp_file.path(), json).await?;
        Ok(temp_file)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::InputFormat;
    use crate::types::OutputFormat;
    use crate::types::PermissionMode;

    fn create_test_client() -> Client {
        Client {
            claude_path: PathBuf::from("/usr/bin/claude"),
        }
    }

    #[tokio::test]
    async fn test_build_args_inserts_separator_for_dash_query() {
        let client = create_test_client();
        let config = SessionConfig::builder("- list files")
            .output_format(OutputFormat::Text)
            .build()
            .unwrap();

        let (args, _) = client.build_args(&config).await.unwrap();

        // Find the -- separator
        let sep_pos = args.iter().position(|a| a == "--");
        assert!(sep_pos.is_some(), "Separator -- should be present");

        let sep_pos = sep_pos.unwrap();
        assert_eq!(args[sep_pos + 1], "- list files");
    }

    #[tokio::test]
    async fn test_build_args_basic() {
        let client = create_test_client();
        let config = SessionConfig::builder("test query")
            .output_format(OutputFormat::Text)
            .build()
            .unwrap();

        let (args, _) = client.build_args(&config).await.unwrap();

        assert!(args.contains(&"--print".to_string()));
        assert!(args.contains(&"--output-format".to_string()));
        assert!(args.contains(&"text".to_string()));
        assert!(args.contains(&"--".to_string()));
        assert!(args.contains(&"test query".to_string()));
    }

    #[tokio::test]
    async fn test_build_args_with_model() {
        let client = create_test_client();
        let config = SessionConfig::builder("test")
            .model(crate::types::Model::Sonnet)
            .fallback_model(crate::types::Model::Haiku)
            .output_format(OutputFormat::Text)
            .build()
            .unwrap();

        let (args, _) = client.build_args(&config).await.unwrap();

        let model_pos = args.iter().position(|a| a == "--model").unwrap();
        assert_eq!(args[model_pos + 1], "sonnet");

        let fallback_pos = args.iter().position(|a| a == "--fallback-model").unwrap();
        assert_eq!(args[fallback_pos + 1], "haiku");
    }

    #[tokio::test]
    async fn test_build_args_with_permissions() {
        let client = create_test_client();
        let config = SessionConfig::builder("test")
            .permission_mode(PermissionMode::AcceptEdits)
            .enable_dangerous_permissions()
            .output_format(OutputFormat::Text)
            .build()
            .unwrap();

        let (args, _) = client.build_args(&config).await.unwrap();

        assert!(args.contains(&"--permission-mode".to_string()));
        assert!(args.contains(&"acceptEdits".to_string()));
        assert!(args.contains(&"--allow-dangerously-skip-permissions".to_string()));
        assert!(args.contains(&"--dangerously-skip-permissions".to_string()));
    }

    #[tokio::test]
    async fn test_build_args_with_tools() {
        let client = create_test_client();
        let config = SessionConfig::builder("test")
            .tools(vec!["Read".to_string(), "Write".to_string()])
            .allowed_tools(vec!["Bash".to_string()])
            .disallowed_tools(vec!["WebSearch".to_string()])
            .output_format(OutputFormat::Text)
            .build()
            .unwrap();

        let (args, _) = client.build_args(&config).await.unwrap();

        let tools_pos = args.iter().position(|a| a == "--tools").unwrap();
        assert_eq!(args[tools_pos + 1], "Read,Write");

        let allowed_pos = args.iter().position(|a| a == "--allowedTools").unwrap();
        assert_eq!(args[allowed_pos + 1], "Bash");

        let disallowed_pos = args.iter().position(|a| a == "--disallowedTools").unwrap();
        assert_eq!(args[disallowed_pos + 1], "WebSearch");
    }

    #[tokio::test]
    async fn test_build_args_with_session_semantics() {
        let client = create_test_client();

        // Test resume
        let config = SessionConfig::builder("test")
            .resume_session_id("session-123")
            .output_format(OutputFormat::Text)
            .build()
            .unwrap();
        let (args, _) = client.build_args(&config).await.unwrap();
        let resume_pos = args.iter().position(|a| a == "--resume").unwrap();
        assert_eq!(args[resume_pos + 1], "session-123");

        // Test explicit session ID
        let config = SessionConfig::builder("test")
            .explicit_session_id("uuid-456")
            .output_format(OutputFormat::Text)
            .build()
            .unwrap();
        let (args, _) = client.build_args(&config).await.unwrap();
        let session_id_pos = args.iter().position(|a| a == "--session-id").unwrap();
        assert_eq!(args[session_id_pos + 1], "uuid-456");

        // Test continue
        let config = SessionConfig::builder("test")
            .continue_last_session(true)
            .output_format(OutputFormat::Text)
            .build()
            .unwrap();
        let (args, _) = client.build_args(&config).await.unwrap();
        assert!(args.contains(&"--continue".to_string()));

        // Test fork
        let config = SessionConfig::builder("test")
            .fork_session(true)
            .output_format(OutputFormat::Text)
            .build()
            .unwrap();
        let (args, _) = client.build_args(&config).await.unwrap();
        assert!(args.contains(&"--fork-session".to_string()));
    }

    #[tokio::test]
    async fn test_build_args_with_input_format() {
        let client = create_test_client();
        let config = SessionConfig::builder("test")
            .input_format(InputFormat::StreamJson)
            .output_format(OutputFormat::Text)
            .build()
            .unwrap();

        let (args, _) = client.build_args(&config).await.unwrap();

        let input_pos = args.iter().position(|a| a == "--input-format").unwrap();
        assert_eq!(args[input_pos + 1], "stream-json");
    }

    #[tokio::test]
    async fn test_build_args_with_output_shaping() {
        let client = create_test_client();
        let config = SessionConfig::builder("test")
            .json_schema(r#"{"type":"object"}"#)
            .include_partial_messages(true)
            .replay_user_messages(true)
            .output_format(OutputFormat::Text)
            .build()
            .unwrap();

        let (args, _) = client.build_args(&config).await.unwrap();

        let schema_pos = args.iter().position(|a| a == "--json-schema").unwrap();
        assert_eq!(args[schema_pos + 1], r#"{"type":"object"}"#);
        assert!(args.contains(&"--include-partial-messages".to_string()));
        assert!(args.contains(&"--replay-user-messages".to_string()));
    }

    #[tokio::test]
    async fn test_build_args_with_advanced_options() {
        let client = create_test_client();
        let config = SessionConfig::builder("test")
            .agents(r#"{"test":"config"}"#)
            .debug(true)
            .debug_filter("filter*")
            .ide(true)
            .output_format(OutputFormat::Text)
            .build()
            .unwrap();

        let (args, _) = client.build_args(&config).await.unwrap();

        let agents_pos = args.iter().position(|a| a == "--agents").unwrap();
        assert_eq!(args[agents_pos + 1], r#"{"test":"config"}"#);

        let debug_pos = args.iter().position(|a| a == "--debug").unwrap();
        assert_eq!(args[debug_pos + 1], "filter*");

        assert!(args.contains(&"--ide".to_string()));
    }

    #[tokio::test]
    async fn test_build_args_verbose_auto_added_for_streaming() {
        let client = create_test_client();

        // Streaming JSON should auto-add verbose
        let config = SessionConfig::builder("test")
            .output_format(OutputFormat::StreamingJson)
            .build()
            .unwrap();
        let (args, _) = client.build_args(&config).await.unwrap();
        assert!(args.contains(&"--verbose".to_string()));

        // Text format should not auto-add verbose
        let config = SessionConfig::builder("test")
            .output_format(OutputFormat::Text)
            .build()
            .unwrap();
        let (args, _) = client.build_args(&config).await.unwrap();
        assert!(!args.contains(&"--verbose".to_string()));

        // Explicit verbose flag should be added
        let config = SessionConfig::builder("test")
            .output_format(OutputFormat::Text)
            .verbose(true)
            .build()
            .unwrap();
        let (args, _) = client.build_args(&config).await.unwrap();
        assert!(args.contains(&"--verbose".to_string()));
    }
}