claus 0.2.2

An I/O less Anthropic API implementation
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
//! CLI wrapper for spawning the `claude` command.
//!
//! Provides a builder for constructing [`std::process::Command`] instances. The builder
//! configures command-line arguments for session management, permissions, MCP servers, and I/O
//! formats.

pub mod protocol;

use std::{collections::HashMap, path::PathBuf, process::Command};

/// Joins an iterator of string-like items with commas.
fn join_args<I, T>(args: I) -> String
where
    I: IntoIterator<Item = T>,
    T: AsRef<str>,
{
    args.into_iter()
        .map(|s| s.as_ref().to_owned())
        .collect::<Vec<_>>()
        .join(",")
}

/// Permission mode for tool execution.
///
/// The CLI also reads permission settings from `~/.claude/settings.json` and project-level
/// `.claude/settings.json` files.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum PermissionMode {
    /// Standard permission behavior with prompts.
    ///
    /// Unsuitable for non-interactive use since the CLI may hang waiting for user input.
    /// Use [`DontAsk`](Self::DontAsk) for headless/CI environments.
    #[default]
    Default,
    /// Auto-accept file edits, prompt for other tools.
    ///
    /// Auto-approves reads, file edits, and common filesystem Bash commands (`mkdir`, `touch`,
    /// `rm`, `rmdir`, `mv`, `cp`, `sed`). Other Bash commands and network requests still prompt.
    AcceptEdits,
    /// Allow all tools without prompts.
    ///
    /// Equivalent to `--dangerously-skip-permissions`. Only use in isolated environments
    /// (containers, VMs) without internet access.
    BypassPermissions,
    /// Delegate permission decisions to an MCP tool.
    ///
    /// Routes permission prompts to the MCP tool specified by
    /// [`CliBuilder::permission_prompt_tool`]. The tool receives permission requests and must
    /// return `{"behavior": "allow"}` or `{"behavior": "deny", "message": "..."}`. Useful for
    /// implementing custom approval logic or organizational security policies.
    Delegate,
    /// Deny tools unless pre-approved via allowed tools, settings, or hooks.
    ///
    /// Recommended for CI pipelines and non-interactive use. Auto-denies anything that would
    /// prompt; only pre-approved tools and read-only Bash commands execute.
    DontAsk,
    /// Exploration mode for research without edits.
    ///
    /// Claude can read files and run shell commands to explore, but cannot edit source files.
    /// Permission prompts still apply as in [`Default`](Self::Default) mode.
    Plan,
}

impl PermissionMode {
    /// Returns the CLI argument value.
    fn as_str(self) -> &'static str {
        match self {
            PermissionMode::Default => "default",
            PermissionMode::AcceptEdits => "acceptEdits",
            PermissionMode::BypassPermissions => "bypassPermissions",
            PermissionMode::Delegate => "delegate",
            PermissionMode::DontAsk => "dontAsk",
            PermissionMode::Plan => "plan",
        }
    }
}

/// Output format for the CLI.
///
/// Only applies when using [`CliBuilder::print`] mode.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum OutputFormat {
    /// Plain text output.
    ///
    /// Returns the final response as plain text. Best for simple scripting where you just need
    /// the result.
    #[default]
    Text,
    /// Single JSON result.
    ///
    /// Returns the final `result` message as a single JSON object - the same structure as the
    /// last message in [`StreamJson`](Self::StreamJson).
    Json,
    /// Newline-delimited JSON stream.
    ///
    /// Emits one JSON object per line as events occur. Required [`CliBuilder::verbose`]
    /// to be set.
    // TODO: Explain how to parse the format here!
    StreamJson,
}

impl OutputFormat {
    /// Returns the CLI argument value.
    fn as_str(self) -> &'static str {
        match self {
            OutputFormat::Text => "text",
            OutputFormat::Json => "json",
            OutputFormat::StreamJson => "stream-json",
        }
    }
}

/// Input format for the CLI.
///
/// Only applies when using [`CliBuilder::print`] mode.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum InputFormat {
    /// Plain text input via `-p` flag or stdin.
    #[default]
    Text,
    /// Newline-delimited JSON stream on stdin.
    ///
    /// Enables bidirectional communication for interactive sessions.
    // TODO: Explain how to use input format.
    StreamJson,
}

impl InputFormat {
    /// Returns the CLI argument value.
    fn as_str(self) -> &'static str {
        match self {
            InputFormat::Text => "text",
            InputFormat::StreamJson => "stream-json",
        }
    }
}

/// MCP server definition.
#[derive(Clone, Debug)]
pub enum McpServer {
    /// Stdio-based MCP server (spawns a subprocess).
    Stdio(StdioMcpServer),
    /// HTTP-based MCP server.
    Http(HttpMcpServer),
}

impl McpServer {
    /// Returns the server name.
    pub fn name(&self) -> &str {
        match self {
            McpServer::Stdio(s) => &s.name,
            McpServer::Http(h) => &h.name,
        }
    }

    /// Returns the server definition as a JSON value for `--mcp-config`.
    fn to_value(&self) -> serde_json::Value {
        match self {
            McpServer::Stdio(s) => s.to_value(),
            McpServer::Http(h) => h.to_value(),
        }
    }
}

impl From<StdioMcpServer> for McpServer {
    fn from(server: StdioMcpServer) -> Self {
        McpServer::Stdio(server)
    }
}

impl From<HttpMcpServer> for McpServer {
    fn from(server: HttpMcpServer) -> Self {
        McpServer::Http(server)
    }
}

/// Stdio-based MCP server configuration.
#[derive(Clone, Debug)]
pub struct StdioMcpServer {
    /// Server name (key in `mcpServers` object).
    name: String,
    /// Command to execute.
    command: String,
    /// Command arguments.
    args: Vec<String>,
    /// Environment variables.
    env: HashMap<String, String>,
}

impl StdioMcpServer {
    /// Creates a new stdio MCP server with the given name and command.
    pub fn new(name: impl Into<String>, command: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            command: command.into(),
            args: Vec::new(),
            env: HashMap::new(),
        }
    }

    /// Sets all command arguments.
    pub fn args<I, T>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<String>,
    {
        self.args = args.into_iter().map(Into::into).collect();
        self
    }

    /// Adds a single command argument.
    pub fn arg(mut self, arg: impl Into<String>) -> Self {
        self.args.push(arg.into());
        self
    }

    /// Adds an environment variable.
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.env.insert(key.into(), value.into());
        self
    }

    /// Returns the server definition as a JSON value.
    fn to_value(&self) -> serde_json::Value {
        let mut obj = serde_json::json!({
            "command": self.command
        });
        if !self.args.is_empty() {
            obj["args"] = serde_json::json!(self.args);
        }
        if !self.env.is_empty() {
            obj["env"] = serde_json::json!(self.env);
        }
        obj
    }
}

/// HTTP-based MCP server configuration.
#[derive(Clone, Debug)]
pub struct HttpMcpServer {
    /// Server name (key in mcpServers object).
    name: String,
    /// Server URL.
    url: String,
    /// HTTP headers.
    headers: HashMap<String, String>,
}

impl HttpMcpServer {
    /// Creates a new HTTP MCP server with the given name and URL.
    pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            url: url.into(),
            headers: HashMap::new(),
        }
    }

    /// Adds an HTTP header.
    pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.insert(key.into(), value.into());
        self
    }

    /// Returns the server definition as a JSON value.
    fn to_value(&self) -> serde_json::Value {
        let mut obj = serde_json::json!({
            "type": "http",
            "url": self.url
        });
        if !self.headers.is_empty() {
            obj["headers"] = serde_json::json!(self.headers);
        }
        obj
    }
}

/// Builder for constructing a `claude` CLI command.
#[derive(Clone, Debug, Default)]
pub struct CliBuilder {
    /// Session ID of a previous session to resume.
    #[cfg(feature = "uuid")]
    resume: Option<uuid::Uuid>,
    /// Session ID for a new conversation.
    #[cfg(feature = "uuid")]
    session_id: Option<uuid::Uuid>,
    /// MCP servers to configure.
    mcp_servers: Vec<McpServer>,
    /// Whether to ignore MCP servers from other sources.
    strict_mcp_config: bool,
    /// Permission mode for tool execution.
    permission_mode: PermissionMode,
    /// MCP tool name for permission prompts (used with delegate mode).
    permission_prompt_tool: Option<String>,
    /// Output format.
    output_format: OutputFormat,
    /// Input format.
    input_format: InputFormat,
    /// Whether to enable verbose output.
    verbose: bool,
    /// Initial prompt (for non-interactive mode).
    prompt: Option<String>,
    /// System prompt (replaces default).
    system_prompt: Option<String>,
    /// System prompt to append to default.
    append_system_prompt: Option<String>,
    /// Model to use.
    model: Option<String>,
    /// Fallback model when primary is overloaded.
    fallback_model: Option<String>,
    /// Maximum agentic turns.
    max_turns: Option<u32>,
    /// Maximum budget in USD.
    max_budget_usd: Option<f64>,
    /// Allowed tools (filter on top of available tools), comma-separated.
    allowed_tools: Option<String>,
    /// Available built-in tools, comma-separated.
    tools: Option<String>,
    /// Additional directories to allow tool access.
    add_dirs: Vec<PathBuf>,
    /// Print mode (non-interactive).
    print: bool,
    /// Include partial message chunks in streaming output.
    include_partial_messages: bool,
    /// Disable session persistence (ephemeral session).
    no_session_persistence: bool,
    /// Working directory for the process.
    current_dir: Option<PathBuf>,
}

impl CliBuilder {
    /// Creates a new builder with default settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Resumes a previous session by ID.
    ///
    /// Sessions are stored in `~/.claude/projects/<encoded-path>/<session-id>.jsonl`.
    #[cfg(feature = "uuid")]
    pub fn resume(mut self, session_id: impl Into<uuid::Uuid>) -> Self {
        self.resume = Some(session_id.into());
        self
    }

    /// Creates a builder configured for non-interactive use.
    ///
    /// Pre-configured with:
    /// - [`PermissionMode::DontAsk`] to avoid hanging on permission prompts
    /// - [`print`](Self::print) mode enabled for non-interactive output
    /// - [`OutputFormat::StreamJson`] for structured, parseable output
    /// - [`verbose`](Self::verbose) enabled (required for `StreamJson`)
    /// - [`strict_mcp_config`](Self::strict_mcp_config) to ignore external MCP servers
    /// - [`max_turns`](Self::max_turns) set to 1 (single response, no agentic loops)
    /// - [`no_session_persistence`](Self::no_session_persistence) to avoid writing session files
    /// - All built-in tools disabled (caller must explicitly enable via [`tools`](Self::tools))
    ///
    /// Suitable for CI pipelines, scripts, and automation. Caller must set
    /// [`prompt`](Self::prompt) before building.
    pub fn headless() -> Self {
        Self {
            permission_mode: PermissionMode::DontAsk,
            print: true,
            output_format: OutputFormat::StreamJson,
            verbose: true,
            strict_mcp_config: true,
            max_turns: Some(1),
            no_session_persistence: true,
            tools: Some(String::new()), // Empty string → --tools "" disables all built-in tools
            ..Self::default()
        }
    }

    /// Sets the session ID for a new conversation.
    ///
    /// Predetermines the session ID for new sessions. Useful for generating deterministic IDs
    /// (e.g., `Uuid::new_v5` from a room/channel identifier). Fails if a session with this ID
    /// already exists.
    ///
    /// Sessions are stored in `~/.claude/projects/<encoded-path>/<session-id>.jsonl`.
    #[cfg(feature = "uuid")]
    pub fn session_id(mut self, id: impl Into<uuid::Uuid>) -> Self {
        self.session_id = Some(id.into());
        self
    }

    /// Adds an MCP server to the configuration.
    pub fn mcp_server(mut self, server: impl Into<McpServer>) -> Self {
        self.mcp_servers.push(server.into());
        self
    }

    /// Sets whether to ignore MCP servers from other sources.
    pub fn strict_mcp_config(mut self, strict: bool) -> Self {
        self.strict_mcp_config = strict;
        self
    }

    /// Sets the permission mode for tool execution.
    pub fn permission_mode(mut self, mode: PermissionMode) -> Self {
        self.permission_mode = mode;
        self
    }

    /// Sets the MCP tool name for permission prompts.
    ///
    /// Used with [`PermissionMode::Delegate`] to specify which MCP tool handles permission
    /// decisions. The tool name follows MCP convention: `mcp__<server>__<tool>`.
    pub fn permission_prompt_tool(mut self, tool_name: impl Into<String>) -> Self {
        self.permission_prompt_tool = Some(tool_name.into());
        self
    }

    /// Sets the output format.
    pub fn output_format(mut self, format: OutputFormat) -> Self {
        self.output_format = format;
        self
    }

    /// Sets the input format.
    pub fn input_format(mut self, format: InputFormat) -> Self {
        self.input_format = format;
        self
    }

    /// Enables or disables verbose output.
    pub fn verbose(mut self, enabled: bool) -> Self {
        self.verbose = enabled;
        self
    }

    /// Sets the initial prompt for non-interactive mode.
    pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
        self.prompt = Some(prompt.into());
        self
    }

    /// Sets the system prompt (replaces default).
    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.system_prompt = Some(prompt.into());
        self
    }

    /// Appends to the default system prompt.
    pub fn append_system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.append_system_prompt = Some(prompt.into());
        self
    }

    /// Sets the model to use.
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// Sets the fallback model when primary is overloaded.
    ///
    /// Only works with [`print`](Self::print) mode.
    pub fn fallback_model(mut self, model: impl Into<String>) -> Self {
        self.fallback_model = Some(model.into());
        self
    }

    /// Sets the maximum number of agentic turns.
    pub fn max_turns(mut self, turns: u32) -> Self {
        self.max_turns = Some(turns);
        self
    }

    /// Sets the maximum budget in USD.
    ///
    /// Only works with [`print`](Self::print) mode.
    pub fn max_budget_usd(mut self, amount: f64) -> Self {
        self.max_budget_usd = Some(amount);
        self
    }

    /// Sets allowed tools.
    ///
    /// Filters which tools are permitted from the available set. Use `"Bash(git:*) Edit"` syntax
    /// to allow specific patterns.
    ///
    /// - `Some([])` — no tools allowed
    /// - `Some(["Read", "Bash(git:*)"])` — only specified tools allowed
    /// - `None` — use default (all available tools allowed)
    pub fn allowed_tools<I, T>(mut self, tools: Option<I>) -> Self
    where
        I: IntoIterator<Item = T>,
        T: AsRef<str>,
    {
        self.allowed_tools = tools.map(|t| join_args(t));
        self
    }

    /// Sets the available built-in tools.
    ///
    /// - `Some([])` — disable all tools
    /// - `Some(["Read", "Bash"])` — only specified tools available
    /// - `None` — use default tool set
    ///
    /// Built-in tools include:
    /// - `Bash` — run shell commands
    /// - `Read` — read file contents
    /// - `Write` — create/overwrite files
    /// - `Edit` — edit existing files
    /// - `Glob` — find files by pattern
    /// - `Grep` — search file contents
    /// - `Task` — spawn subagents
    /// - `WebFetch` — fetch web content
    /// - `WebSearch` — search the web
    /// - `NotebookEdit` — edit Jupyter notebooks
    /// - `AskUserQuestion` — prompt the user for input
    ///
    /// Different from [`allowed_tools`](Self::allowed_tools) which filters on top of available
    /// tools.
    pub fn tools<I, T>(mut self, tools: Option<I>) -> Self
    where
        I: IntoIterator<Item = T>,
        T: AsRef<str>,
    {
        self.tools = tools.map(|t| join_args(t));
        self
    }

    /// Adds a directory for tool access.
    pub fn add_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.add_dirs.push(dir.into());
        self
    }

    /// Sets the working directory for the process.
    pub fn current_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.current_dir = Some(dir.into());
        self
    }

    /// Enables print mode (non-interactive, outputs result and exits).
    pub fn print(mut self, enabled: bool) -> Self {
        self.print = enabled;
        self
    }

    /// Includes partial message chunks in streaming output.
    ///
    /// Only works with [`print`](Self::print) and [`OutputFormat::StreamJson`].
    pub fn include_partial_messages(mut self, enabled: bool) -> Self {
        self.include_partial_messages = enabled;
        self
    }

    /// Disables session persistence (ephemeral session).
    ///
    /// Sessions will not be saved to disk and cannot be resumed.
    /// Only works with [`print`](Self::print) mode.
    pub fn no_session_persistence(mut self, enabled: bool) -> Self {
        self.no_session_persistence = enabled;
        self
    }

    /// Builds the configured command.
    ///
    /// Returns a [`Command`] with all arguments configured. The caller is responsible for setting
    /// up stdio and spawning.
    pub fn build(&self) -> Command {
        let mut cmd = Command::new("claude");

        if self.verbose {
            cmd.arg("--verbose");
        }

        if self.input_format != InputFormat::Text {
            cmd.arg("--input-format").arg(self.input_format.as_str());
        }

        if self.output_format != OutputFormat::Text {
            cmd.arg("--output-format").arg(self.output_format.as_str());
        }

        #[cfg(feature = "uuid")]
        if let Some(session_id) = &self.resume {
            cmd.arg("--resume").arg(session_id.to_string());
        }

        #[cfg(feature = "uuid")]
        if let Some(session_id) = &self.session_id {
            cmd.arg("--session-id").arg(session_id.to_string());
        }

        for server in &self.mcp_servers {
            let config = serde_json::json!({
                "mcpServers": {
                    server.name(): server.to_value()
                }
            });
            cmd.arg("--mcp-config").arg(config.to_string());
        }

        if self.strict_mcp_config {
            cmd.arg("--strict-mcp-config");
        }

        if self.permission_mode != PermissionMode::Default {
            cmd.arg("--permission-mode")
                .arg(self.permission_mode.as_str());
        }

        if let Some(tool_name) = &self.permission_prompt_tool {
            cmd.arg("--permission-prompt-tool").arg(tool_name);
        }

        if let Some(system_prompt) = &self.system_prompt {
            cmd.arg("--system-prompt").arg(system_prompt);
        }

        if let Some(append_system_prompt) = &self.append_system_prompt {
            cmd.arg("--append-system-prompt").arg(append_system_prompt);
        }

        if let Some(model) = &self.model {
            cmd.arg("--model").arg(model);
        }

        if let Some(fallback_model) = &self.fallback_model {
            cmd.arg("--fallback-model").arg(fallback_model);
        }

        if let Some(max_turns) = self.max_turns {
            cmd.arg("--max-turns").arg(max_turns.to_string());
        }

        if let Some(max_budget_usd) = self.max_budget_usd {
            cmd.arg("--max-budget-usd").arg(max_budget_usd.to_string());
        }

        if let Some(allowed_tools) = &self.allowed_tools {
            cmd.arg("--allowedTools").arg(allowed_tools);
        }

        if let Some(tools) = &self.tools {
            cmd.arg("--tools").arg(tools);
        }

        for dir in &self.add_dirs {
            cmd.arg("--add-dir").arg(dir);
        }

        if self.print {
            cmd.arg("-p");
        }

        if self.include_partial_messages {
            cmd.arg("--include-partial-messages");
        }

        if self.no_session_persistence {
            cmd.arg("--no-session-persistence");
        }

        // Prompt is a positional argument, must come last
        if let Some(prompt) = &self.prompt {
            cmd.arg(prompt);
        }

        if let Some(dir) = &self.current_dir {
            cmd.current_dir(dir);
        }

        cmd
    }
}

#[cfg(test)]
mod tests {
    use super::{CliBuilder, InputFormat, OutputFormat, PermissionMode, StdioMcpServer};

    #[test]
    fn minimal_command_has_no_args() {
        let cmd = CliBuilder::new().build();
        let args: Vec<_> = cmd.get_args().collect();
        assert!(args.is_empty());
    }

    #[test]
    fn headless_preset() {
        let cmd = CliBuilder::headless().build();
        let args: Vec<_> = cmd.get_args().map(|s| s.to_str().unwrap()).collect();
        assert!(args.contains(&"--permission-mode"));
        assert!(args.contains(&"dontAsk"));
        assert!(args.contains(&"-p"));
        assert!(args.contains(&"--output-format"));
        assert!(args.contains(&"stream-json"));
        assert!(args.contains(&"--verbose"));
        assert!(args.contains(&"--strict-mcp-config"));
        assert!(args.contains(&"--max-turns"));
        assert!(args.contains(&"1"));
        assert!(args.contains(&"--no-session-persistence"));
        // --tools "" disables all built-in tools
        assert!(args.contains(&"--tools"));
        assert!(args.contains(&""));
    }

    #[test]
    fn interactive_session_command() {
        let cmd = CliBuilder::new()
            .verbose(true)
            .input_format(InputFormat::StreamJson)
            .output_format(OutputFormat::StreamJson)
            .permission_mode(PermissionMode::DontAsk)
            .build();

        let args: Vec<_> = cmd.get_args().map(|s| s.to_str().unwrap()).collect();
        assert!(args.contains(&"--verbose"));
        assert!(args.contains(&"--input-format"));
        assert!(args.contains(&"stream-json"));
        assert!(args.contains(&"--permission-mode"));
        assert!(args.contains(&"dontAsk"));
    }

    #[test]
    #[cfg(feature = "uuid")]
    fn session_id_requires_uuid() {
        let session_id =
            uuid::Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").expect("valid uuid");
        let cmd = CliBuilder::new().session_id(session_id).build();

        let args: Vec<_> = cmd.get_args().map(|s| s.to_str().unwrap()).collect();
        assert!(args.contains(&"--session-id"));
        assert!(args.contains(&"550e8400-e29b-41d4-a716-446655440000"));
    }

    #[test]
    fn one_shot_command() {
        let cmd = CliBuilder::new()
            .prompt("Hello, world!")
            .print(true)
            .output_format(OutputFormat::StreamJson)
            .max_turns(5)
            .allowed_tools(Some(["Read"]))
            .build();

        let args: Vec<_> = cmd.get_args().map(|s| s.to_str().unwrap()).collect();
        assert!(args.contains(&"-p"));
        assert!(args.contains(&"Hello, world!")); // positional, at end
        assert!(args.contains(&"--max-turns"));
        assert!(args.contains(&"5"));
        assert!(args.contains(&"--allowedTools"));
        assert!(args.contains(&"Read"));
        // Prompt should be last argument
        assert_eq!(args.last(), Some(&"Hello, world!"));
    }

    #[test]
    fn mcp_server_config() {
        let cmd = CliBuilder::new()
            .mcp_server(
                StdioMcpServer::new("myserver", "mycmd")
                    .arg("--flag")
                    .env("KEY", "value"),
            )
            .strict_mcp_config(true)
            .build();

        let args: Vec<_> = cmd.get_args().map(|s| s.to_str().unwrap()).collect();
        assert!(args.contains(&"--mcp-config"));
        assert!(args.contains(&"--strict-mcp-config"));

        let config_idx = args
            .iter()
            .position(|&a| a == "--mcp-config")
            .expect("--mcp-config should be present");
        let config = args[config_idx + 1];
        assert!(config.contains("myserver"));
        assert!(config.contains("mycmd"));
    }

    /// Integration test that actually runs `claude` CLI.
    ///
    /// Run with: `cargo test --features uuid -- --ignored`
    #[test]
    #[ignore]
    fn integration_headless_run() {
        let output = CliBuilder::headless()
            .prompt("Reply with exactly: PONG")
            .build()
            .output()
            .expect("failed to execute claude");

        assert!(output.status.success(), "claude exited with error");

        let stdout = String::from_utf8_lossy(&output.stdout);

        // Parse the last line as JSON (the result message)
        let last_line = stdout.lines().last().expect("no output from claude");
        let result: serde_json::Value =
            serde_json::from_str(last_line).expect("failed to parse result JSON");

        assert_eq!(result["type"], "result");
        assert_eq!(result["subtype"], "success");
        assert!(
            result["result"]
                .as_str()
                .unwrap_or("")
                .to_uppercase()
                .contains("PONG"),
            "expected PONG in result, got: {}",
            result["result"]
        );
    }
}