claude-agents-sdk 0.1.5

Rust SDK for building agents with Claude Code CLI
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
//! Subprocess transport implementation for the Claude CLI.
//!
//! This module provides the concrete implementation of the Transport trait
//! that communicates with the Claude CLI via subprocess stdin/stdout.

use async_trait::async_trait;
use std::collections::HashMap;
use std::path::PathBuf;
use std::pin::Pin;
use std::process::Stdio;
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, Command};
use tokio::sync::Mutex;
use tokio_stream::Stream;
use tracing::{debug, error, trace, warn};

use super::Transport;
use crate::errors::{ClaudeSDKError, Result};
use crate::types::*;

/// Default maximum buffer size (1MB).
const DEFAULT_MAX_BUFFER_SIZE: usize = 1024 * 1024;

/// Default CLI command name.
const DEFAULT_CLI_PATH: &str = "claude";

/// Subprocess-based transport for communicating with the Claude CLI.
///
/// This transport spawns the Claude CLI as a subprocess and communicates
/// via JSON over stdin/stdout. It handles:
/// - Process lifecycle management
/// - Command-line argument construction from options
/// - Bidirectional JSON message passing
/// - Buffer size limits and error handling
pub struct SubprocessTransport {
    /// CLI path.
    cli_path: PathBuf,
    /// Command-line arguments.
    args: Vec<String>,
    /// Environment variables.
    env: HashMap<String, String>,
    /// Maximum buffer size.
    max_buffer_size: usize,
    /// Child process handle.
    process: Option<Child>,
    /// Stdin handle (wrapped in mutex for thread safety).
    /// Inner Option allows dropping stdin to send EOF to the child process.
    stdin: Option<Arc<Mutex<Option<tokio::process::ChildStdin>>>>,
    /// Stdout lines stream receiver.
    stdout_rx: Option<tokio::sync::mpsc::Receiver<Result<serde_json::Value>>>,
    /// Stderr callback.
    stderr_callback: Option<Arc<dyn Fn(String) + Send + Sync>>,
    /// Whether the transport is ready.
    ready: bool,
    /// Working directory.
    cwd: Option<PathBuf>,
}

impl SubprocessTransport {
    /// Create a new subprocess transport with the given options.
    pub fn new(options: &ClaudeAgentOptions) -> Result<Self> {
        let cli_path = options
            .cli_path
            .clone()
            .unwrap_or_else(|| PathBuf::from(DEFAULT_CLI_PATH));

        // Validate CLI exists
        if !cli_path.exists() {
            // Try to find in PATH
            if which::which(&cli_path).is_err() {
                return Err(ClaudeSDKError::cli_not_found(format!(
                    "Claude CLI not found at '{}'. Please ensure Claude Code is installed.",
                    cli_path.display()
                )));
            }
        }

        let args = Self::build_args(options)?;
        let env = Self::build_env(options);
        let max_buffer_size = options.max_buffer_size.unwrap_or(DEFAULT_MAX_BUFFER_SIZE);

        Ok(Self {
            cli_path,
            args,
            env,
            max_buffer_size,
            process: None,
            stdin: None,
            stdout_rx: None,
            stderr_callback: options.stderr.clone(),
            ready: false,
            cwd: options.cwd.clone(),
        })
    }

    /// Build command-line arguments from options.
    fn build_args(options: &ClaudeAgentOptions) -> Result<Vec<String>> {
        let mut args = vec![
            "--output-format".to_string(),
            "stream-json".to_string(),
            "--verbose".to_string(),
            "--input-format".to_string(),
            "stream-json".to_string(),
        ];

        // System prompt handling:
        // - None: Pass empty string to explicitly disable default system prompt
        // - Text: Pass the custom system prompt
        // - Preset without append: No flags (use CLI's default system prompt)
        // - Preset with append: Only --append-system-prompt (append to CLI default)
        match &options.system_prompt {
            None => {
                // Explicitly disable system prompt
                args.push("--system-prompt".to_string());
                args.push(String::new());
            }
            Some(SystemPromptConfig::Text(text)) => {
                args.push("--system-prompt".to_string());
                args.push(text.clone());
            }
            Some(SystemPromptConfig::Preset(preset)) => {
                // For preset, only add append flag if present
                // Otherwise, let CLI use its default system prompt
                if let Some(ref append) = preset.append {
                    args.push("--append-system-prompt".to_string());
                    args.push(append.clone());
                }
            }
        }

        // Permission mode
        if let Some(mode) = options.permission_mode {
            args.push("--permission-mode".to_string());
            args.push(
                match mode {
                    PermissionMode::Default => "default",
                    PermissionMode::AcceptEdits => "acceptEdits",
                    PermissionMode::Plan => "plan",
                    PermissionMode::BypassPermissions => "bypassPermissions",
                }
                .to_string(),
            );
        }

        // Model
        if let Some(ref model) = options.model {
            args.push("--model".to_string());
            args.push(model.clone());
        }

        // Fallback model
        if let Some(ref model) = options.fallback_model {
            args.push("--fallback-model".to_string());
            args.push(model.clone());
        }

        // Max turns
        if let Some(turns) = options.max_turns {
            args.push("--max-turns".to_string());
            args.push(turns.to_string());
        }

        // Max budget
        if let Some(budget) = options.max_budget_usd {
            args.push("--max-budget-usd".to_string());
            args.push(budget.to_string());
        }

        // Max thinking tokens
        if let Some(tokens) = options.max_thinking_tokens {
            args.push("--max-thinking-tokens".to_string());
            args.push(tokens.to_string());
        }

        // Continue conversation
        if options.continue_conversation {
            args.push("--continue".to_string());
        }

        // Resume session
        if let Some(ref session) = options.resume {
            args.push("--resume".to_string());
            args.push(session.clone());
        }

        // Fork session
        if options.fork_session {
            args.push("--fork-session".to_string());
        }

        // Allowed tools
        for tool in &options.allowed_tools {
            args.push("--allowed-tools".to_string());
            args.push(tool.clone());
        }

        // Disallowed tools
        for tool in &options.disallowed_tools {
            args.push("--disallowed-tools".to_string());
            args.push(tool.clone());
        }

        // Tools
        if let Some(ref tools) = options.tools {
            match tools {
                ToolsConfig::List(list) => {
                    for tool in list {
                        args.push("--tools".to_string());
                        args.push(tool.clone());
                    }
                }
                ToolsConfig::Preset(preset) => {
                    args.push("--tools-preset".to_string());
                    args.push(preset.preset.clone());
                }
            }
        }

        // MCP servers
        match &options.mcp_servers {
            McpServersConfig::Path(path) => {
                args.push("--mcp-config".to_string());
                args.push(path.to_string_lossy().to_string());
            }
            McpServersConfig::Map(servers) if !servers.is_empty() => {
                let json = serde_json::to_string(servers).map_err(|e| {
                    ClaudeSDKError::configuration(format!("Failed to serialize MCP servers: {}", e))
                })?;
                args.push("--mcp-servers".to_string());
                args.push(json);
            }
            _ => {}
        }

        // User
        if let Some(ref user) = options.user {
            args.push("--user".to_string());
            args.push(user.clone());
        }

        // Settings
        if let Some(ref settings) = options.settings {
            args.push("--settings".to_string());
            args.push(settings.clone());
        }

        // Setting sources
        if let Some(ref sources) = options.setting_sources {
            for source in sources {
                args.push("--setting-source".to_string());
                args.push(
                    match source {
                        SettingSource::User => "user",
                        SettingSource::Project => "project",
                        SettingSource::Local => "local",
                    }
                    .to_string(),
                );
            }
        }

        // Additional directories
        for dir in &options.add_dirs {
            args.push("--add-dir".to_string());
            args.push(dir.to_string_lossy().to_string());
        }

        // Include partial messages
        if options.include_partial_messages {
            args.push("--include-partial-messages".to_string());
        }

        // File checkpointing
        if options.enable_file_checkpointing {
            args.push("--enable-file-checkpointing".to_string());
        }

        // Sandbox settings
        if let Some(ref sandbox) = options.sandbox {
            let json = serde_json::to_string(sandbox).map_err(|e| {
                ClaudeSDKError::configuration(format!(
                    "Failed to serialize sandbox settings: {}",
                    e
                ))
            })?;
            args.push("--sandbox".to_string());
            args.push(json);
        }

        // Output format
        if let Some(ref format) = options.output_format {
            let json = serde_json::to_string(format).map_err(|e| {
                ClaudeSDKError::configuration(format!("Failed to serialize output format: {}", e))
            })?;
            args.push("--output-format-schema".to_string());
            args.push(json);
        }

        // Agents are sent via the initialize control request, not CLI args

        // Beta features
        for beta in &options.betas {
            args.push("--beta".to_string());
            args.push(
                serde_json::to_string(beta)
                    .unwrap_or_else(|_| format!("{:?}", beta))
                    .trim_matches('"')
                    .to_string(),
            );
        }

        // Extra args
        for (key, value) in &options.extra_args {
            args.push(format!("--{}", key));
            if let Some(v) = value {
                args.push(v.clone());
            }
        }

        Ok(args)
    }

    /// Build environment variables.
    fn build_env(options: &ClaudeAgentOptions) -> HashMap<String, String> {
        let mut env = std::env::vars().collect::<HashMap<_, _>>();

        // Override with user-specified env vars
        for (key, value) in &options.env {
            env.insert(key.clone(), value.clone());
        }

        // Required SDK env vars
        env.insert("CLAUDE_SDK".to_string(), "true".to_string());

        env
    }

    /// Start reading stdout in background task.
    fn spawn_stdout_reader(
        stdout: tokio::process::ChildStdout,
        max_buffer_size: usize,
    ) -> tokio::sync::mpsc::Receiver<Result<serde_json::Value>> {
        let (tx, rx) = tokio::sync::mpsc::channel(256);

        tokio::spawn(async move {
            let reader = BufReader::with_capacity(max_buffer_size, stdout);
            let mut lines = reader.lines();

            loop {
                match lines.next_line().await {
                    Ok(Some(line)) => {
                        let display_len = line.len().min(200);
                        trace!("Received line from CLI: {}", &line[..display_len]);

                        let result = match serde_json::from_str(&line) {
                            Ok(value) => Ok(value),
                            Err(e) => Err(ClaudeSDKError::json_decode_with_context(
                                "Failed to parse JSON from CLI",
                                Some(line),
                                None,
                                e,
                            )),
                        };

                        if tx.send(result).await.is_err() {
                            debug!("Stdout reader: receiver dropped");
                            break;
                        }
                    }
                    Ok(None) => {
                        debug!("Stdout reader: EOF received");
                        break;
                    }
                    Err(e) => {
                        let _ = tx
                            .send(Err(ClaudeSDKError::cli_connection_with_source(
                                "Failed to read from CLI stdout",
                                e,
                            )))
                            .await;
                        break;
                    }
                }
            }

            debug!("Stdout reader task finished");
        });

        rx
    }

    /// Start reading stderr in background task.
    fn spawn_stderr_reader(
        stderr: tokio::process::ChildStderr,
        callback: Option<Arc<dyn Fn(String) + Send + Sync>>,
    ) {
        tokio::spawn(async move {
            let reader = BufReader::new(stderr);
            let mut lines = reader.lines();

            loop {
                match lines.next_line().await {
                    Ok(Some(line)) => {
                        trace!("CLI stderr: {}", line);
                        if let Some(ref cb) = callback {
                            cb(line);
                        }
                    }
                    Ok(None) => {
                        // EOF
                        break;
                    }
                    Err(e) => {
                        warn!("Error reading stderr: {}", e);
                        break;
                    }
                }
            }

            debug!("Stderr reader task finished");
        });
    }
}

#[async_trait]
impl Transport for SubprocessTransport {
    async fn connect(&mut self) -> Result<()> {
        debug!(
            "Starting CLI process: {} {:?}",
            self.cli_path.display(),
            self.args
        );

        let mut cmd = Command::new(&self.cli_path);
        cmd.args(&self.args)
            .envs(&self.env)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true);

        if let Some(ref cwd) = self.cwd {
            cmd.current_dir(cwd);
        }

        let mut child = cmd.spawn().map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                ClaudeSDKError::cli_not_found(format!(
                    "Failed to start Claude CLI at '{}': {}",
                    self.cli_path.display(),
                    e
                ))
            } else {
                ClaudeSDKError::cli_connection_with_source(
                    format!("Failed to start Claude CLI: {}", e),
                    e,
                )
            }
        })?;

        // Take stdin and wrap in mutex
        let stdin = child
            .stdin
            .take()
            .ok_or_else(|| ClaudeSDKError::cli_connection("Failed to open stdin to CLI process"))?;
        self.stdin = Some(Arc::new(Mutex::new(Some(stdin))));

        // Take stdout and start reader task
        let stdout = child.stdout.take().ok_or_else(|| {
            ClaudeSDKError::cli_connection("Failed to open stdout from CLI process")
        })?;
        self.stdout_rx = Some(Self::spawn_stdout_reader(stdout, self.max_buffer_size));

        // Take stderr and start reader task
        if let Some(stderr) = child.stderr.take() {
            Self::spawn_stderr_reader(stderr, self.stderr_callback.clone());
        }

        self.process = Some(child);
        self.ready = true;

        debug!("CLI process started successfully");
        Ok(())
    }

    async fn write(&self, data: &str) -> Result<()> {
        let stdin_arc = self
            .stdin
            .as_ref()
            .ok_or_else(|| ClaudeSDKError::cli_connection("Transport not connected"))?;

        let mut stdin_guard = stdin_arc.lock().await;
        let stdin = stdin_guard
            .as_mut()
            .ok_or_else(|| ClaudeSDKError::cli_connection("Stdin already closed"))?;

        trace!("Writing to CLI: {}", &data[..data.len().min(200)]);

        stdin.write_all(data.as_bytes()).await.map_err(|e| {
            ClaudeSDKError::cli_connection_with_source("Failed to write to CLI stdin", e)
        })?;

        stdin.write_all(b"\n").await.map_err(|e| {
            ClaudeSDKError::cli_connection_with_source("Failed to write newline to CLI stdin", e)
        })?;

        stdin.flush().await.map_err(|e| {
            ClaudeSDKError::cli_connection_with_source("Failed to flush CLI stdin", e)
        })?;

        Ok(())
    }

    fn message_stream(&self) -> Pin<Box<dyn Stream<Item = Result<serde_json::Value>> + Send + '_>> {
        // The message_stream method from the Transport trait cannot be properly
        // implemented with &self because we need to take ownership of the channel.
        // Users should use take_stdout_rx() instead which takes &mut self.
        //
        // This returns an empty stream - the actual message stream is obtained
        // via take_stdout_rx() on SubprocessTransport directly.
        //
        // Note: If custom transport support is re-added in the future, this trait
        // method should be redesigned to use &mut self or an Arc-wrapped receiver.
        warn!("message_stream() called on SubprocessTransport - use take_stdout_rx() instead");
        Box::pin(futures::stream::empty())
    }

    async fn close(&mut self) -> Result<()> {
        self.ready = false;

        // Close stdin first
        if let Some(stdin) = self.stdin.take() {
            drop(stdin);
        }

        // Wait for process to exit or kill it
        if let Some(mut process) = self.process.take() {
            // Give it a moment to exit gracefully
            match tokio::time::timeout(std::time::Duration::from_secs(2), process.wait()).await {
                Ok(Ok(status)) => {
                    debug!("CLI process exited with status: {:?}", status);
                }
                Ok(Err(e)) => {
                    error!("Error waiting for CLI process: {}", e);
                }
                Err(_) => {
                    warn!("CLI process did not exit in time, killing");
                    let _ = process.kill().await;
                }
            }
        }

        Ok(())
    }

    async fn end_input(&self) -> Result<()> {
        // Drop the ChildStdin handle to send EOF to the process
        if let Some(stdin_arc) = &self.stdin {
            let mut guard = stdin_arc.lock().await;
            if let Some(mut stdin) = guard.take() {
                // Flush before dropping
                let _ = stdin.flush().await;
            }
        }
        Ok(())
    }

    fn is_ready(&self) -> bool {
        self.ready
    }
}

impl SubprocessTransport {
    /// Get the stdout receiver for message reading.
    pub fn take_stdout_rx(
        &mut self,
    ) -> Option<tokio::sync::mpsc::Receiver<Result<serde_json::Value>>> {
        self.stdout_rx.take()
    }
}

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

    #[test]
    fn test_build_args_basic() {
        let options = ClaudeAgentOptions::default();
        let args = SubprocessTransport::build_args(&options).unwrap();

        assert!(args.contains(&"--output-format".to_string()));
        assert!(args.contains(&"stream-json".to_string()));
        assert!(args.contains(&"--verbose".to_string()));
        assert!(args.contains(&"--input-format".to_string()));
    }

    #[test]
    fn test_build_args_with_model() {
        let options = ClaudeAgentOptions::new().with_model("claude-3-sonnet");
        let args = SubprocessTransport::build_args(&options).unwrap();

        assert!(args.contains(&"--model".to_string()));
        assert!(args.contains(&"claude-3-sonnet".to_string()));
    }

    #[test]
    fn test_build_args_always_streaming() {
        let options = ClaudeAgentOptions::default();
        let args = SubprocessTransport::build_args(&options).unwrap();

        assert!(args.contains(&"--input-format".to_string()));
        assert!(!args.contains(&"--print".to_string()));
        assert!(!args.contains(&"--agents".to_string()));
    }

    #[test]
    fn test_build_env() {
        let mut options = ClaudeAgentOptions::default();
        options
            .env
            .insert("CUSTOM_VAR".to_string(), "value".to_string());

        let env = SubprocessTransport::build_env(&options);

        assert_eq!(env.get("CLAUDE_SDK"), Some(&"true".to_string()));
        assert_eq!(env.get("CUSTOM_VAR"), Some(&"value".to_string()));
    }

    #[test]
    fn test_build_args_system_prompt_none() {
        let options = ClaudeAgentOptions::default();
        let args = SubprocessTransport::build_args(&options).unwrap();

        let sp_idx = args.iter().position(|a| a == "--system-prompt");
        assert!(sp_idx.is_some(), "Should have --system-prompt flag");
        assert_eq!(
            args[sp_idx.unwrap() + 1],
            "",
            "System prompt should be empty string"
        );
    }

    #[test]
    fn test_build_args_system_prompt_string() {
        let options = ClaudeAgentOptions::new().with_system_prompt("You are a pirate.");
        let args = SubprocessTransport::build_args(&options).unwrap();

        let sp_idx = args.iter().position(|a| a == "--system-prompt");
        assert!(sp_idx.is_some(), "Should have --system-prompt flag");
        assert_eq!(
            args[sp_idx.unwrap() + 1],
            "You are a pirate.",
            "System prompt should match"
        );
    }

    #[test]
    fn test_build_args_system_prompt_preset_no_append() {
        use crate::types::{SystemPromptConfig, SystemPromptPreset};

        let mut options = ClaudeAgentOptions::new();
        options.system_prompt = Some(SystemPromptConfig::Preset(SystemPromptPreset {
            preset_type: "preset".to_string(),
            preset: "claude_code".to_string(),
            append: None,
        }));
        let args = SubprocessTransport::build_args(&options).unwrap();

        assert!(!args.contains(&"--system-prompt".to_string()));
        assert!(!args.contains(&"--append-system-prompt".to_string()));
    }

    #[test]
    fn test_build_args_system_prompt_preset_with_append() {
        use crate::types::{SystemPromptConfig, SystemPromptPreset};

        let mut options = ClaudeAgentOptions::new();
        options.system_prompt = Some(SystemPromptConfig::Preset(SystemPromptPreset {
            preset_type: "preset".to_string(),
            preset: "claude_code".to_string(),
            append: Some("Be concise.".to_string()),
        }));
        let args = SubprocessTransport::build_args(&options).unwrap();

        assert!(!args.contains(&"--system-prompt".to_string()));

        let append_idx = args.iter().position(|a| a == "--append-system-prompt");
        assert!(append_idx.is_some());
        assert_eq!(args[append_idx.unwrap() + 1], "Be concise.");
    }

    #[test]
    fn test_build_args_agents_not_in_cli_args() {
        use crate::types::AgentDefinition;

        let mut options = ClaudeAgentOptions::new();
        options.agents = Some(std::collections::HashMap::from([(
            "test_agent".to_string(),
            AgentDefinition {
                description: "Test".to_string(),
                prompt: "Do stuff".to_string(),
                tools: None,
                model: None,
            },
        )]));
        let args = SubprocessTransport::build_args(&options).unwrap();

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