claude-cli-sdk 0.5.1

Rust SDK for programmatic interaction with the 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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
//! Client configuration — `ClientConfig` with typed builder pattern.
//!
//! [`ClientConfig`] carries every option needed to spawn and control a Claude
//! Code CLI session. It uses [`typed_builder`] so that required fields must be
//! supplied at compile time while optional fields have sensible defaults.
//!
//! # Example
//!
//! ```rust
//! use claude_cli_sdk::config::{ClientConfig, PermissionMode};
//!
//! let config = ClientConfig::builder()
//!     .prompt("List files in /tmp")
//!     .build();
//! ```

use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use serde::{Deserialize, Serialize};
use typed_builder::TypedBuilder;

use tokio_util::sync::CancellationToken;

use crate::callback::MessageCallback;
use crate::hooks::HookMatcher;
use crate::mcp::McpServers;
use crate::permissions::CanUseToolCallback;

// ── Constants ─────────────────────────────────────────────────────────────────

/// The `stream-json` input format value for [`ClientConfig::input_format`].
///
/// When set as the input format, the CLI reads all user messages from stdin
/// as NDJSON. `--print` is omitted and [`ClientConfig::init_stdin_message`]
/// must be provided to unblock the init handshake.
pub const INPUT_FORMAT_STREAM_JSON: &str = "stream-json";

/// The `stream-json` output format value for [`ClientConfig::output_format`].
///
/// Enables realtime NDJSON streaming — required for the SDK's init handshake
/// and multi-turn conversations. This is the default output format.
pub const OUTPUT_FORMAT_STREAM_JSON: &str = "stream-json";

// ── ClientConfig ─────────────────────────────────────────────────────────────

/// Configuration for a Claude Code SDK client session.
///
/// Use [`ClientConfig::builder()`] to construct.
#[derive(TypedBuilder)]
pub struct ClientConfig {
    // ── Required ─────────────────────────────────────────────────────────
    /// The prompt text to send to Claude.
    #[builder(setter(into))]
    pub prompt: String,

    // ── Session ──────────────────────────────────────────────────────────
    /// Path to the Claude CLI binary. If `None`, auto-discovered via
    /// [`find_cli()`](crate::discovery::find_cli).
    #[builder(default, setter(strip_option))]
    pub cli_path: Option<PathBuf>,

    /// Working directory for the Claude process.
    #[builder(default, setter(strip_option))]
    pub cwd: Option<PathBuf>,

    /// Model to use (e.g., `"claude-sonnet-4-5"`).
    #[builder(default, setter(strip_option, into))]
    pub model: Option<String>,

    /// Fallback model if the primary is unavailable.
    #[builder(default, setter(strip_option, into))]
    pub fallback_model: Option<String>,

    /// System prompt configuration.
    #[builder(default, setter(strip_option))]
    pub system_prompt: Option<SystemPrompt>,

    // ── Limits ───────────────────────────────────────────────────────────
    /// Maximum number of agentic turns before stopping.
    #[builder(default, setter(strip_option))]
    pub max_turns: Option<u32>,

    /// Maximum USD budget for the session.
    #[builder(default, setter(strip_option))]
    pub max_budget_usd: Option<f64>,

    /// Maximum thinking tokens per turn.
    #[builder(default, setter(strip_option))]
    pub max_thinking_tokens: Option<u32>,

    // ── Tools ────────────────────────────────────────────────────────────
    /// Explicitly allowed tool names.
    #[builder(default)]
    pub allowed_tools: Vec<String>,

    /// Explicitly disallowed tool names.
    #[builder(default)]
    pub disallowed_tools: Vec<String>,

    // ── Permissions ──────────────────────────────────────────────────────
    /// Permission mode for the session.
    #[builder(default)]
    pub permission_mode: PermissionMode,

    /// Callback invoked when the CLI requests tool use permission.
    #[builder(default, setter(strip_option))]
    pub can_use_tool: Option<CanUseToolCallback>,

    // ── Session management ───────────────────────────────────────────────
    /// Resume an existing session by ID.
    #[builder(default, setter(strip_option, into))]
    pub resume: Option<String>,

    // ── Hooks ────────────────────────────────────────────────────────────
    /// Lifecycle hooks to register for the session.
    #[builder(default)]
    pub hooks: Vec<HookMatcher>,

    // ── MCP ──────────────────────────────────────────────────────────────
    /// External MCP server configurations.
    #[builder(default)]
    pub mcp_servers: McpServers,

    // ── Callback ─────────────────────────────────────────────────────────
    /// Optional message callback for observe/filter.
    #[builder(default, setter(strip_option))]
    pub message_callback: Option<MessageCallback>,

    // ── Environment ──────────────────────────────────────────────────────
    /// Extra environment variables to pass to the CLI process.
    #[builder(default)]
    pub env: HashMap<String, String>,

    /// Enable verbose (debug) output from the CLI.
    #[builder(default)]
    pub verbose: bool,

    // ── Output ───────────────────────────────────────────────────────────
    /// Output format. Defaults to `"stream-json"` for SDK use.
    ///
    /// `"stream-json"` enables realtime streaming — the CLI outputs NDJSON
    /// lines as events happen. This is required for the SDK's init handshake
    /// and multi-turn conversations.
    ///
    /// Other options: `"json"` (single result blob), `"text"` (human-readable).
    #[builder(default_code = r#""stream-json".into()"#, setter(into))]
    pub output_format: String,

    // ── Extra CLI args ────────────────────────────────────────────────────
    /// Arbitrary extra CLI flags to pass through to the Claude process.
    ///
    /// Keys are flag names (without the `--` prefix). Values are optional:
    /// - `Some("value")` produces `--key value`
    /// - `None` produces `--key` (boolean-style flag)
    ///
    /// Uses [`BTreeMap`] to guarantee deterministic CLI arg ordering across
    /// invocations (important for reproducible test snapshots).
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::collections::BTreeMap;
    /// use claude_cli_sdk::ClientConfig;
    ///
    /// let config = ClientConfig::builder()
    ///     .prompt("hello")
    ///     .extra_args(BTreeMap::from([
    ///         ("replay-user-messages".into(), None),
    ///         ("context-window".into(), Some("200000".into())),
    ///     ]))
    ///     .build();
    /// ```
    #[builder(default)]
    pub extra_args: BTreeMap<String, Option<String>>,

    // ── Timeouts ──────────────────────────────────────────────────────────
    /// Deadline for process spawn + init message. `None` = wait forever.
    ///
    /// Default: `Some(30s)`.
    #[builder(default_code = "Some(Duration::from_secs(30))")]
    pub connect_timeout: Option<Duration>,

    /// Deadline for `child.wait()` during close. On expiry the process is
    /// killed. `None` = wait forever.
    ///
    /// Default: `Some(10s)`.
    #[builder(default_code = "Some(Duration::from_secs(10))")]
    pub close_timeout: Option<Duration>,

    /// If `true`, close stdin immediately after spawning the CLI process.
    ///
    /// This is required when using `--print` mode (the default) because
    /// the CLI expects stdin EOF before processing the prompt with
    /// `--output-format stream-json`.
    ///
    /// Default: `true`.
    #[builder(default_code = "true")]
    pub end_input_on_connect: bool,

    /// Per-message recv deadline. `None` = wait forever (default).
    ///
    /// This is for detecting hung/zombie processes, not for limiting turn
    /// time — Claude turns can legitimately take minutes.
    #[builder(default)]
    pub read_timeout: Option<Duration>,

    /// Fallback timeout for hook callbacks when [`HookMatcher::timeout`] is
    /// `None`.
    ///
    /// Default: 30 seconds.
    #[builder(default_code = "Duration::from_secs(30)")]
    pub default_hook_timeout: Duration,

    /// Deadline for the `--version` check in
    /// [`check_cli_version()`](crate::discovery::check_cli_version).
    /// `None` = wait forever.
    ///
    /// Default: `Some(5s)`.
    #[builder(default_code = "Some(Duration::from_secs(5))")]
    pub version_check_timeout: Option<Duration>,

    /// Deadline for control requests (e.g., `set_model`, `set_permission_mode`).
    /// If the CLI does not respond within this duration, the request fails with
    /// [`Error::Timeout`](crate::Error::Timeout).
    ///
    /// Default: `30s`.
    #[builder(default_code = "Duration::from_secs(30)")]
    pub control_request_timeout: Duration,

    // ── Cancellation ─────────────────────────────────────────────────────
    /// Optional cancellation token for cooperative cancellation.
    ///
    /// When cancelled, in-flight streams yield [`Error::Cancelled`](crate::Error::Cancelled)
    /// and the background reader task shuts down cleanly.
    #[builder(default, setter(strip_option))]
    pub cancellation_token: Option<CancellationToken>,

    // ── Stderr ───────────────────────────────────────────────────────────
    /// Optional callback for CLI stderr output.
    #[builder(default, setter(strip_option))]
    pub stderr_callback: Option<Arc<dyn Fn(String) + Send + Sync>>,

    /// Input format for the CLI session.
    ///
    /// Set to [`INPUT_FORMAT_STREAM_JSON`] for bidirectional multi-turn
    /// streaming (the CLI reads all messages from stdin as NDJSON). When set,
    /// `--print` is omitted and [`init_stdin_message`](Self::init_stdin_message)
    /// must provide the first message to unblock the init handshake.
    ///
    /// Default: `None` (standard `--print` mode).
    #[builder(default, setter(strip_option, into))]
    pub input_format: Option<String>,

    /// Optional message to write to stdin immediately after spawning the CLI,
    /// before waiting for the init message.
    ///
    /// This is needed when using `--input-format stream-json` (without `--print`),
    /// because the CLI waits for stdin input before emitting the `system/init`
    /// message. Writing a trigger message unblocks the init handshake.
    ///
    /// The message should be a valid JSON user message for `stream-json` mode.
    /// Note: the CLI will process this message and produce a response that
    /// flows through the normal message channel.
    ///
    /// Default: `None` (no trigger — suitable for `--print` mode).
    #[builder(default, setter(strip_option, into))]
    pub init_stdin_message: Option<String>,
}

impl std::fmt::Debug for ClientConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ClientConfig")
            .field("prompt", &self.prompt)
            .field("cli_path", &self.cli_path)
            .field("cwd", &self.cwd)
            .field("model", &self.model)
            .field("permission_mode", &self.permission_mode)
            .field("max_turns", &self.max_turns)
            .field("max_budget_usd", &self.max_budget_usd)
            .field("verbose", &self.verbose)
            .field("output_format", &self.output_format)
            .field("connect_timeout", &self.connect_timeout)
            .field("close_timeout", &self.close_timeout)
            .field("read_timeout", &self.read_timeout)
            .field("default_hook_timeout", &self.default_hook_timeout)
            .field("version_check_timeout", &self.version_check_timeout)
            .field("control_request_timeout", &self.control_request_timeout)
            .finish_non_exhaustive()
    }
}

// ── PermissionMode ───────────────────────────────────────────────────────────

/// Permission mode controlling how tool use requests are handled.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PermissionMode {
    /// Default: prompt the user for each tool use.
    #[default]
    Default,
    /// Automatically accept file edits (still prompt for other tools).
    AcceptEdits,
    /// Plan-only mode: suggest changes but don't execute.
    Plan,
    /// Bypass all permission prompts (dangerous — use in CI only).
    BypassPermissions,
}

impl PermissionMode {
    /// Convert to the CLI flag value.
    #[must_use]
    pub fn as_cli_flag(&self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::AcceptEdits => "acceptEdits",
            Self::Plan => "plan",
            Self::BypassPermissions => "bypassPermissions",
        }
    }
}

// ── SystemPrompt ─────────────────────────────────────────────────────────────

/// System prompt configuration for a Claude session.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum SystemPrompt {
    /// A raw text system prompt.
    Text {
        /// The system prompt text.
        text: String,
    },
    /// A named preset system prompt.
    Preset {
        /// The preset kind (e.g., `"custom"`).
        kind: String,
        /// The preset name.
        preset: String,
        /// Additional text to append after the preset.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        append: Option<String>,
    },
}

impl SystemPrompt {
    /// Create a text system prompt.
    #[must_use]
    pub fn text(s: impl Into<String>) -> Self {
        Self::Text { text: s.into() }
    }

    /// Create a preset system prompt.
    #[must_use]
    pub fn preset(kind: impl Into<String>, preset: impl Into<String>) -> Self {
        Self::Preset {
            kind: kind.into(),
            preset: preset.into(),
            append: None,
        }
    }
}

// ── CLI arg generation ───────────────────────────────────────────────────────

impl ClientConfig {
    /// Validate the configuration, returning an error for invalid settings.
    ///
    /// Checks:
    /// - If `cwd` is set, it must exist and be a directory.
    ///
    /// This is called automatically by [`Client::new()`](crate::Client::new).
    pub fn validate(&self) -> crate::errors::Result<()> {
        if let Some(ref cwd) = self.cwd {
            if !cwd.exists() {
                return Err(crate::errors::Error::Config(format!(
                    "working directory does not exist: {}",
                    cwd.display()
                )));
            }
            if !cwd.is_dir() {
                return Err(crate::errors::Error::Config(format!(
                    "working directory is not a directory: {}",
                    cwd.display()
                )));
            }
        }

        if let Some(ref msg) = self.init_stdin_message {
            serde_json::from_str::<serde_json::Value>(msg).map_err(|e| {
                crate::errors::Error::Config(format!("init_stdin_message is not valid JSON: {e}"))
            })?;
        }

        if self.init_stdin_message.is_some()
            && self.input_format.as_deref() != Some(INPUT_FORMAT_STREAM_JSON)
        {
            return Err(crate::errors::Error::Config(
                "init_stdin_message requires input_format = \"stream-json\"".into(),
            ));
        }

        if self.input_format.is_some() && self.extra_args.contains_key("input-format") {
            return Err(crate::errors::Error::Config(
                "input_format and extra_args[\"input-format\"] are mutually exclusive; use input_format".into(),
            ));
        }

        Ok(())
    }

    /// Build the CLI argument list for spawning the Claude process.
    ///
    /// This does NOT include the binary path itself — just the arguments.
    #[must_use]
    pub fn to_cli_args(&self) -> Vec<String> {
        let mut args = vec!["--output-format".into(), self.output_format.clone()];

        // In --input-format stream-json mode the CLI reads all user messages
        // from stdin as NDJSON. --print must be omitted; passing it would waste
        // an API call on an empty prompt.
        let uses_stream_input = self.input_format.as_deref() == Some(INPUT_FORMAT_STREAM_JSON);

        if !uses_stream_input {
            args.push("--print".into());
            args.push(self.prompt.clone());
        }

        if let Some(ref fmt) = self.input_format {
            args.push("--input-format".into());
            args.push(fmt.clone());
        }

        // stream-json output requires --verbose.
        if self.output_format == OUTPUT_FORMAT_STREAM_JSON && !self.verbose {
            args.push("--verbose".into());
        }

        if let Some(model) = &self.model {
            args.push("--model".into());
            args.push(model.clone());
        }

        if let Some(fallback) = &self.fallback_model {
            args.push("--fallback-model".into());
            args.push(fallback.clone());
        }

        if let Some(turns) = self.max_turns {
            args.push("--max-turns".into());
            args.push(turns.to_string());
        }

        if let Some(budget) = self.max_budget_usd {
            args.push("--max-budget-usd".into());
            args.push(budget.to_string());
        }

        if let Some(thinking) = self.max_thinking_tokens {
            args.push("--max-thinking-tokens".into());
            args.push(thinking.to_string());
        }

        if self.permission_mode != PermissionMode::Default {
            args.push("--permission-mode".into());
            args.push(self.permission_mode.as_cli_flag().into());
        }

        // When a can_use_tool callback is configured, tell the CLI to route
        // permission requests through the stdio control protocol instead of
        // its built-in interactive terminal prompt. Without this flag the CLI
        // handles permissions internally and the callback never fires.
        if self.can_use_tool.is_some() {
            args.push("--permission-prompt-tool".into());
            args.push("stdio".into());
        }

        if let Some(resume) = &self.resume {
            args.push("--resume".into());
            args.push(resume.clone());
        }

        if self.verbose {
            args.push("--verbose".into());
        }

        for tool in &self.allowed_tools {
            args.push("--allowedTools".into());
            args.push(tool.clone());
        }

        for tool in &self.disallowed_tools {
            args.push("--disallowedTools".into());
            args.push(tool.clone());
        }

        if !self.mcp_servers.is_empty() {
            let json = serde_json::to_string(&self.mcp_servers)
                .expect("McpServers serialization is infallible");
            args.push("--mcp-servers".into());
            args.push(json);
        }

        if let Some(prompt) = &self.system_prompt {
            match prompt {
                SystemPrompt::Text { text } => {
                    args.push("--system-prompt".into());
                    args.push(text.clone());
                }
                SystemPrompt::Preset { preset, append, .. } => {
                    args.push("--system-prompt-preset".into());
                    args.push(preset.clone());
                    if let Some(append_text) = append {
                        args.push("--append-system-prompt".into());
                        args.push(append_text.clone());
                    }
                }
            }
        }

        // Extra args — appended last so they can override anything above.
        for (key, value) in &self.extra_args {
            args.push(format!("--{key}"));
            if let Some(v) = value {
                args.push(v.clone());
            }
        }

        args
    }

    /// Build the environment variable map for the CLI process.
    ///
    /// Merges SDK defaults with `self.env` (user-supplied env takes precedence)
    /// and any SDK-internal env vars.
    ///
    /// SDK defaults:
    /// - `CLAUDE_CODE_SDK_ORIGINATOR=claude_cli_sdk_rs` — telemetry originator
    /// - `TERM=dumb` — prevent ANSI escape sequences in output
    ///
    /// NOTE: `CI=true` is intentionally NOT set. Claude Code CLI v2.1+ treats
    /// `CI=true` as a signal to suppress ALL output (stdout + stderr), which
    /// breaks the NDJSON streaming protocol this SDK relies on.
    #[must_use]
    pub fn to_env(&self) -> HashMap<String, String> {
        let mut env = HashMap::new();

        // SDK defaults (overridable by self.env)
        env.insert(
            "CLAUDE_CODE_SDK_ORIGINATOR".into(),
            "claude_cli_sdk_rs".into(),
        );
        env.insert("TERM".into(), "dumb".into());

        // User-supplied env overrides defaults
        env.extend(self.env.clone());

        // Control protocol (always set if needed, cannot be overridden)
        if self.can_use_tool.is_some() || !self.hooks.is_empty() {
            env.insert("CLAUDE_CODE_SDK_CONTROL_PORT".into(), "stdin".into());
        }

        env
    }
}

// ── Tests ────────────────────────────────────────────────────────────────────

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

    #[test]
    fn builder_minimal() {
        let config = ClientConfig::builder().prompt("hello").build();
        assert_eq!(config.prompt, "hello");
        assert_eq!(config.output_format, "stream-json");
        assert_eq!(config.permission_mode, PermissionMode::Default);
    }

    #[test]
    fn builder_full() {
        let config = ClientConfig::builder()
            .prompt("test prompt")
            .model("claude-opus-4-5")
            .max_turns(5_u32)
            .max_budget_usd(1.0_f64)
            .permission_mode(PermissionMode::AcceptEdits)
            .verbose(true)
            .build();

        assert_eq!(config.model.as_deref(), Some("claude-opus-4-5"));
        assert_eq!(config.max_turns, Some(5));
        assert_eq!(config.max_budget_usd, Some(1.0));
        assert_eq!(config.permission_mode, PermissionMode::AcceptEdits);
        assert!(config.verbose);
    }

    #[test]
    fn to_cli_args_minimal() {
        let config = ClientConfig::builder().prompt("hello").build();
        let args = config.to_cli_args();
        assert!(args.contains(&"--output-format".into()));
        assert!(args.contains(&"stream-json".into()));
        assert!(args.contains(&"--print".into()));
        assert!(args.contains(&"hello".into()));
    }

    #[test]
    fn to_cli_args_with_model_and_turns() {
        let config = ClientConfig::builder()
            .prompt("test")
            .model("claude-sonnet-4-5")
            .max_turns(10_u32)
            .build();
        let args = config.to_cli_args();
        assert!(args.contains(&"--model".into()));
        assert!(args.contains(&"claude-sonnet-4-5".into()));
        assert!(args.contains(&"--max-turns".into()));
        assert!(args.contains(&"10".into()));
    }

    #[test]
    fn to_cli_args_with_permission_mode() {
        let config = ClientConfig::builder()
            .prompt("test")
            .permission_mode(PermissionMode::BypassPermissions)
            .build();
        let args = config.to_cli_args();
        assert!(args.contains(&"--permission-mode".into()));
        assert!(args.contains(&"bypassPermissions".into()));
    }

    #[test]
    fn to_cli_args_default_permission_mode_not_included() {
        let config = ClientConfig::builder().prompt("test").build();
        let args = config.to_cli_args();
        assert!(!args.contains(&"--permission-mode".into()));
    }

    #[test]
    fn to_cli_args_with_system_prompt_text() {
        let config = ClientConfig::builder()
            .prompt("test")
            .system_prompt(SystemPrompt::text("You are a helpful assistant"))
            .build();
        let args = config.to_cli_args();
        assert!(args.contains(&"--system-prompt".into()));
        assert!(args.contains(&"You are a helpful assistant".into()));
    }

    #[test]
    fn to_cli_args_with_mcp_servers() {
        use crate::mcp::McpServerConfig;

        let mut servers = McpServers::new();
        servers.insert(
            "fs".into(),
            McpServerConfig::new("npx").with_args(["-y", "mcp-fs"]),
        );

        let config = ClientConfig::builder()
            .prompt("test")
            .mcp_servers(servers)
            .build();
        let args = config.to_cli_args();
        assert!(args.contains(&"--mcp-servers".into()));
    }

    #[test]
    fn to_env_without_callbacks() {
        let config = ClientConfig::builder().prompt("test").build();
        let env = config.to_env();
        assert!(!env.contains_key("CLAUDE_CODE_SDK_CONTROL_PORT"));
    }

    #[test]
    fn to_env_includes_originator_and_headless_defaults() {
        let config = ClientConfig::builder().prompt("test").build();
        let env = config.to_env();
        assert_eq!(
            env.get("CLAUDE_CODE_SDK_ORIGINATOR"),
            Some(&"claude_cli_sdk_rs".into())
        );
        assert!(!env.contains_key("CI"), "CI must not be set by default");
        assert_eq!(env.get("TERM"), Some(&"dumb".into()));
    }

    #[test]
    fn to_env_user_env_overrides_defaults() {
        let config = ClientConfig::builder()
            .prompt("test")
            .env(HashMap::from([("TERM".into(), "xterm-256color".into())]))
            .build();
        let env = config.to_env();
        // User-supplied value should override SDK default.
        assert_eq!(env.get("TERM"), Some(&"xterm-256color".into()));
        // Originator should still be present (not overridden).
        assert_eq!(
            env.get("CLAUDE_CODE_SDK_ORIGINATOR"),
            Some(&"claude_cli_sdk_rs".into())
        );
    }

    #[test]
    fn to_env_with_hooks_enables_control_port() {
        use crate::hooks::{HookCallback, HookEvent, HookMatcher, HookOutput};
        let cb: HookCallback = Arc::new(|_, _, _| Box::pin(async { HookOutput::allow() }));
        let config = ClientConfig::builder()
            .prompt("test")
            .hooks(vec![HookMatcher::new(HookEvent::PreToolUse, cb)])
            .build();
        let env = config.to_env();
        assert_eq!(
            env.get("CLAUDE_CODE_SDK_CONTROL_PORT"),
            Some(&"stdin".into())
        );
    }

    #[test]
    fn permission_mode_serde_round_trip() {
        let modes = [
            PermissionMode::Default,
            PermissionMode::AcceptEdits,
            PermissionMode::Plan,
            PermissionMode::BypassPermissions,
        ];
        for mode in modes {
            let json = serde_json::to_string(&mode).unwrap();
            let decoded: PermissionMode = serde_json::from_str(&json).unwrap();
            assert_eq!(mode, decoded);
        }
    }

    #[test]
    fn system_prompt_text_round_trip() {
        let sp = SystemPrompt::text("You are helpful");
        let json = serde_json::to_string(&sp).unwrap();
        let decoded: SystemPrompt = serde_json::from_str(&json).unwrap();
        assert_eq!(sp, decoded);
    }

    #[test]
    fn system_prompt_preset_round_trip() {
        let sp = SystemPrompt::Preset {
            kind: "custom".into(),
            preset: "coding".into(),
            append: Some("Also be concise.".into()),
        };
        let json = serde_json::to_string(&sp).unwrap();
        let decoded: SystemPrompt = serde_json::from_str(&json).unwrap();
        assert_eq!(sp, decoded);
    }

    #[test]
    fn debug_does_not_panic() {
        let config = ClientConfig::builder().prompt("test").build();
        let _ = format!("{config:?}");
    }

    #[test]
    fn to_cli_args_with_allowed_tools() {
        let config = ClientConfig::builder()
            .prompt("test")
            .allowed_tools(vec!["bash".into(), "read_file".into()])
            .build();
        let args = config.to_cli_args();
        let allowed_count = args.iter().filter(|a| *a == "--allowedTools").count();
        assert_eq!(allowed_count, 2);
    }

    #[test]
    fn to_cli_args_with_extra_args_boolean_flag() {
        let config = ClientConfig::builder()
            .prompt("test")
            .extra_args(BTreeMap::from([("replay-user-messages".into(), None)]))
            .build();
        let args = config.to_cli_args();
        assert!(args.contains(&"--replay-user-messages".into()));
    }

    #[test]
    fn to_cli_args_with_extra_args_valued_flag() {
        let config = ClientConfig::builder()
            .prompt("test")
            .extra_args(BTreeMap::from([(
                "context-window".into(),
                Some("200000".into()),
            )]))
            .build();
        let args = config.to_cli_args();
        let idx = args.iter().position(|a| a == "--context-window").unwrap();
        assert_eq!(args[idx + 1], "200000");
    }

    #[test]
    fn builder_timeout_defaults() {
        let config = ClientConfig::builder().prompt("test").build();
        assert_eq!(config.connect_timeout, Some(Duration::from_secs(30)));
        assert_eq!(config.close_timeout, Some(Duration::from_secs(10)));
        assert_eq!(config.read_timeout, None);
        assert_eq!(config.default_hook_timeout, Duration::from_secs(30));
        assert_eq!(config.version_check_timeout, Some(Duration::from_secs(5)));
    }

    #[test]
    fn builder_custom_timeouts() {
        let config = ClientConfig::builder()
            .prompt("test")
            .connect_timeout(Some(Duration::from_secs(60)))
            .close_timeout(Some(Duration::from_secs(20)))
            .read_timeout(Some(Duration::from_secs(120)))
            .default_hook_timeout(Duration::from_secs(10))
            .version_check_timeout(Some(Duration::from_secs(15)))
            .build();
        assert_eq!(config.connect_timeout, Some(Duration::from_secs(60)));
        assert_eq!(config.close_timeout, Some(Duration::from_secs(20)));
        assert_eq!(config.read_timeout, Some(Duration::from_secs(120)));
        assert_eq!(config.default_hook_timeout, Duration::from_secs(10));
        assert_eq!(config.version_check_timeout, Some(Duration::from_secs(15)));
    }

    #[test]
    fn builder_disable_connect_timeout() {
        let config = ClientConfig::builder()
            .prompt("test")
            .connect_timeout(None::<Duration>)
            .build();
        assert_eq!(config.connect_timeout, None);
    }

    #[test]
    fn builder_cancellation_token() {
        let token = CancellationToken::new();
        let config = ClientConfig::builder()
            .prompt("test")
            .cancellation_token(token.clone())
            .build();
        assert!(config.cancellation_token.is_some());
    }

    #[test]
    fn builder_cancellation_token_default_is_none() {
        let config = ClientConfig::builder().prompt("test").build();
        assert!(config.cancellation_token.is_none());
    }

    #[test]
    fn to_cli_args_with_resume() {
        let config = ClientConfig::builder()
            .prompt("test")
            .resume("session-123")
            .build();
        let args = config.to_cli_args();
        assert!(args.contains(&"--resume".into()));
        assert!(args.contains(&"session-123".into()));
    }

    #[test]
    fn to_cli_args_stream_input_format_omits_print() {
        let config = ClientConfig::builder()
            .prompt("ignored")
            .input_format(INPUT_FORMAT_STREAM_JSON)
            .build();
        let args = config.to_cli_args();
        assert!(
            !args.contains(&"--print".into()),
            "--print must be absent in stream-json input mode"
        );
        assert!(args.contains(&"--input-format".into()));
        let idx = args.iter().position(|a| a == "--input-format").unwrap();
        assert_eq!(args[idx + 1], INPUT_FORMAT_STREAM_JSON);
    }

    #[test]
    fn to_cli_args_input_format_emitted() {
        let config = ClientConfig::builder()
            .prompt("test")
            .input_format("custom-format")
            .build();
        let args = config.to_cli_args();
        assert!(args.contains(&"--input-format".into()));
        let idx = args.iter().position(|a| a == "--input-format").unwrap();
        assert_eq!(args[idx + 1], "custom-format");
    }

    #[test]
    fn validate_init_stdin_message_valid_json() {
        let config = ClientConfig::builder()
            .prompt("ignored")
            .input_format(INPUT_FORMAT_STREAM_JSON)
            .init_stdin_message(r#"{"type":"user","message":{"role":"user","content":"hello"}}"#)
            .build();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn validate_init_stdin_message_invalid_json() {
        let config = ClientConfig::builder()
            .prompt("ignored")
            .input_format(INPUT_FORMAT_STREAM_JSON)
            .init_stdin_message("not valid json {")
            .build();
        let err = config.validate().unwrap_err();
        assert!(
            matches!(err, crate::errors::Error::Config(ref msg) if msg.contains("not valid JSON")),
            "expected Config error about JSON validity, got: {err:?}"
        );
    }

    #[test]
    fn validate_init_stdin_message_without_input_format() {
        let config = ClientConfig::builder()
            .prompt("ignored")
            .init_stdin_message(r#"{"type":"user"}"#)
            .build();
        let err = config.validate().unwrap_err();
        assert!(
            matches!(err, crate::errors::Error::Config(ref msg) if msg.contains("input_format")),
            "expected Config error about missing input_format, got: {err:?}"
        );
    }
}