Skip to main content

claude_codes/
cli.rs

1//! Builder pattern for configuring and launching the Claude CLI process.
2//!
3//! This module provides [`ClaudeCliBuilder`] for constructing Claude CLI commands
4//! with the correct flags for JSON streaming mode. The builder automatically configures:
5//!
6//! - JSON streaming input/output formats
7//! - Non-interactive print mode
8//! - Verbose output for proper streaming
9//! - OAuth token and API key environment variables for authentication
10//!
11
12use crate::error::{Error, Result};
13use log::debug;
14use std::path::PathBuf;
15use std::process::Stdio;
16use uuid::Uuid;
17
18/// Permission mode for Claude CLI
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum PermissionMode {
21    AcceptEdits,
22    BypassPermissions,
23    Default,
24    Delegate,
25    DontAsk,
26    Plan,
27}
28
29impl PermissionMode {
30    /// Get the CLI string representation
31    pub fn as_str(&self) -> &'static str {
32        match self {
33            PermissionMode::AcceptEdits => "acceptEdits",
34            PermissionMode::BypassPermissions => "bypassPermissions",
35            PermissionMode::Default => "default",
36            PermissionMode::Delegate => "delegate",
37            PermissionMode::DontAsk => "dontAsk",
38            PermissionMode::Plan => "plan",
39        }
40    }
41}
42
43/// Input format for Claude CLI
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum InputFormat {
46    Text,
47    StreamJson,
48}
49
50impl InputFormat {
51    /// Get the CLI string representation
52    pub fn as_str(&self) -> &'static str {
53        match self {
54            InputFormat::Text => "text",
55            InputFormat::StreamJson => "stream-json",
56        }
57    }
58}
59
60/// Output format for Claude CLI
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum OutputFormat {
63    Text,
64    Json,
65    StreamJson,
66}
67
68impl OutputFormat {
69    /// Get the CLI string representation
70    pub fn as_str(&self) -> &'static str {
71        match self {
72            OutputFormat::Text => "text",
73            OutputFormat::Json => "json",
74            OutputFormat::StreamJson => "stream-json",
75        }
76    }
77}
78
79/// Comprehensive enum of all Claude CLI flags.
80///
81/// This enum represents every flag available in the Claude CLI (`claude --help`).
82/// Each variant carries the appropriate data type for its flag value.
83///
84/// Use `as_flag()` to get the CLI flag string (e.g., `"--model"`),
85/// or `to_args()` to get the complete flag + value as CLI arguments.
86///
87/// # Example
88/// ```
89/// use claude_codes::CliFlag;
90///
91/// let flag = CliFlag::Model("sonnet".to_string());
92/// assert_eq!(flag.as_flag(), "--model");
93/// assert_eq!(flag.to_args(), vec!["--model", "sonnet"]);
94/// ```
95#[derive(Debug, Clone)]
96pub enum CliFlag {
97    /// Additional directories to allow tool access to
98    AddDir(Vec<PathBuf>),
99    /// Agent for the current session
100    Agent(String),
101    /// JSON object defining custom agents
102    Agents(String),
103    /// Enable bypassing all permission checks as an option
104    AllowDangerouslySkipPermissions,
105    /// Tool names to allow (e.g. "Bash(git:*) Edit")
106    AllowedTools(Vec<String>),
107    /// Append to the default system prompt
108    AppendSystemPrompt(String),
109    /// Beta headers for API requests (API key users only)
110    Betas(Vec<String>),
111    /// Enable Claude in Chrome integration
112    Chrome,
113    /// Continue the most recent conversation
114    Continue,
115    /// Bypass all permission checks
116    DangerouslySkipPermissions,
117    /// Enable debug mode with optional category filter
118    Debug(Option<String>),
119    /// Write debug logs to a specific file path
120    DebugFile(PathBuf),
121    /// Disable all skills/slash commands
122    DisableSlashCommands,
123    /// Tool names to deny (e.g. "Bash(git:*) Edit")
124    DisallowedTools(Vec<String>),
125    /// Automatic fallback model when default is overloaded
126    FallbackModel(String),
127    /// File resources to download at startup (format: file_id:relative_path)
128    File(Vec<String>),
129    /// Create a new session ID when resuming instead of reusing original
130    ForkSession,
131    /// Resume a session linked to a PR
132    FromPr(Option<String>),
133    /// Include partial message chunks as they arrive
134    IncludePartialMessages,
135    /// Input format (text or stream-json)
136    InputFormat(InputFormat),
137    /// JSON Schema for structured output validation
138    JsonSchema(String),
139    /// Maximum dollar amount for API calls
140    MaxBudgetUsd(f64),
141    /// Maximum number of tokens for extended thinking
142    MaxThinkingTokens(u32),
143    /// Load MCP servers from JSON files or strings
144    McpConfig(Vec<String>),
145    /// Enable MCP debug mode (deprecated, use Debug instead)
146    McpDebug,
147    /// Model for the current session
148    Model(String),
149    /// Disable Claude in Chrome integration
150    NoChrome,
151    /// Disable session persistence
152    NoSessionPersistence,
153    /// Output format (text, json, or stream-json)
154    OutputFormat(OutputFormat),
155    /// Permission mode for the session
156    PermissionMode(PermissionMode),
157    /// Tool for handling permission prompts (e.g., "stdio")
158    PermissionPromptTool(String),
159    /// Load plugins from directories
160    PluginDir(Vec<PathBuf>),
161    /// Print response and exit
162    Print,
163    /// Re-emit user messages from stdin back on stdout
164    ReplayUserMessages,
165    /// Resume a conversation by session ID
166    Resume(Option<String>),
167    /// Use a specific session ID (UUID or tagged ID)
168    SessionId(String),
169    /// Comma-separated list of setting sources (user, project, local)
170    SettingSources(String),
171    /// Path to settings JSON file or JSON string
172    Settings(String),
173    /// Only use MCP servers from --mcp-config
174    StrictMcpConfig,
175    /// System prompt for the session
176    SystemPrompt(String),
177    /// Specify available tools from the built-in set
178    Tools(Vec<String>),
179    /// Override verbose mode setting
180    Verbose,
181}
182
183impl CliFlag {
184    /// Get the CLI flag string (e.g., `"--model"`)
185    pub fn as_flag(&self) -> &'static str {
186        match self {
187            CliFlag::AddDir(_) => "--add-dir",
188            CliFlag::Agent(_) => "--agent",
189            CliFlag::Agents(_) => "--agents",
190            CliFlag::AllowDangerouslySkipPermissions => "--allow-dangerously-skip-permissions",
191            CliFlag::AllowedTools(_) => "--allowed-tools",
192            CliFlag::AppendSystemPrompt(_) => "--append-system-prompt",
193            CliFlag::Betas(_) => "--betas",
194            CliFlag::Chrome => "--chrome",
195            CliFlag::Continue => "--continue",
196            CliFlag::DangerouslySkipPermissions => "--dangerously-skip-permissions",
197            CliFlag::Debug(_) => "--debug",
198            CliFlag::DebugFile(_) => "--debug-file",
199            CliFlag::DisableSlashCommands => "--disable-slash-commands",
200            CliFlag::DisallowedTools(_) => "--disallowed-tools",
201            CliFlag::FallbackModel(_) => "--fallback-model",
202            CliFlag::File(_) => "--file",
203            CliFlag::ForkSession => "--fork-session",
204            CliFlag::FromPr(_) => "--from-pr",
205            CliFlag::IncludePartialMessages => "--include-partial-messages",
206            CliFlag::InputFormat(_) => "--input-format",
207            CliFlag::JsonSchema(_) => "--json-schema",
208            CliFlag::MaxBudgetUsd(_) => "--max-budget-usd",
209            CliFlag::MaxThinkingTokens(_) => "--max-thinking-tokens",
210            CliFlag::McpConfig(_) => "--mcp-config",
211            CliFlag::McpDebug => "--mcp-debug",
212            CliFlag::Model(_) => "--model",
213            CliFlag::NoChrome => "--no-chrome",
214            CliFlag::NoSessionPersistence => "--no-session-persistence",
215            CliFlag::OutputFormat(_) => "--output-format",
216            CliFlag::PermissionMode(_) => "--permission-mode",
217            CliFlag::PermissionPromptTool(_) => "--permission-prompt-tool",
218            CliFlag::PluginDir(_) => "--plugin-dir",
219            CliFlag::Print => "--print",
220            CliFlag::ReplayUserMessages => "--replay-user-messages",
221            CliFlag::Resume(_) => "--resume",
222            CliFlag::SessionId(_) => "--session-id",
223            CliFlag::SettingSources(_) => "--setting-sources",
224            CliFlag::Settings(_) => "--settings",
225            CliFlag::StrictMcpConfig => "--strict-mcp-config",
226            CliFlag::SystemPrompt(_) => "--system-prompt",
227            CliFlag::Tools(_) => "--tools",
228            CliFlag::Verbose => "--verbose",
229        }
230    }
231
232    /// Convert this flag into CLI arguments (flag + value)
233    pub fn to_args(&self) -> Vec<String> {
234        let flag = self.as_flag().to_string();
235        match self {
236            // Boolean flags (no value)
237            CliFlag::AllowDangerouslySkipPermissions
238            | CliFlag::Chrome
239            | CliFlag::Continue
240            | CliFlag::DangerouslySkipPermissions
241            | CliFlag::DisableSlashCommands
242            | CliFlag::ForkSession
243            | CliFlag::IncludePartialMessages
244            | CliFlag::McpDebug
245            | CliFlag::NoChrome
246            | CliFlag::NoSessionPersistence
247            | CliFlag::Print
248            | CliFlag::ReplayUserMessages
249            | CliFlag::StrictMcpConfig
250            | CliFlag::Verbose => vec![flag],
251
252            // Optional value flags
253            CliFlag::Debug(filter) => match filter {
254                Some(f) => vec![flag, f.clone()],
255                None => vec![flag],
256            },
257            CliFlag::FromPr(value) | CliFlag::Resume(value) => match value {
258                Some(v) => vec![flag, v.clone()],
259                None => vec![flag],
260            },
261
262            // Single string value flags
263            CliFlag::Agent(v)
264            | CliFlag::Agents(v)
265            | CliFlag::AppendSystemPrompt(v)
266            | CliFlag::FallbackModel(v)
267            | CliFlag::JsonSchema(v)
268            | CliFlag::Model(v)
269            | CliFlag::PermissionPromptTool(v)
270            | CliFlag::SessionId(v)
271            | CliFlag::SettingSources(v)
272            | CliFlag::Settings(v)
273            | CliFlag::SystemPrompt(v) => vec![flag, v.clone()],
274
275            // Format flags
276            CliFlag::InputFormat(f) => vec![flag, f.as_str().to_string()],
277            CliFlag::OutputFormat(f) => vec![flag, f.as_str().to_string()],
278            CliFlag::PermissionMode(m) => vec![flag, m.as_str().to_string()],
279
280            // Numeric flags
281            CliFlag::MaxBudgetUsd(amount) => vec![flag, amount.to_string()],
282            CliFlag::MaxThinkingTokens(tokens) => vec![flag, tokens.to_string()],
283
284            // Path flags
285            CliFlag::DebugFile(p) => vec![flag, p.to_string_lossy().to_string()],
286
287            // Multi-value string flags
288            CliFlag::AllowedTools(items)
289            | CliFlag::Betas(items)
290            | CliFlag::DisallowedTools(items)
291            | CliFlag::File(items)
292            | CliFlag::McpConfig(items)
293            | CliFlag::Tools(items) => {
294                let mut args = vec![flag];
295                args.extend(items.clone());
296                args
297            }
298
299            // Multi-value path flags
300            CliFlag::AddDir(paths) | CliFlag::PluginDir(paths) => {
301                let mut args = vec![flag];
302                args.extend(paths.iter().map(|p| p.to_string_lossy().to_string()));
303                args
304            }
305        }
306    }
307
308    /// Returns all CLI flag names with their flag strings.
309    ///
310    /// Useful for enumerating available options in a UI or for validation.
311    ///
312    /// # Example
313    /// ```
314    /// use claude_codes::CliFlag;
315    ///
316    /// for (name, flag) in CliFlag::all_flags() {
317    ///     println!("{}: {}", name, flag);
318    /// }
319    /// ```
320    pub fn all_flags() -> Vec<(&'static str, &'static str)> {
321        vec![
322            ("AddDir", "--add-dir"),
323            ("Agent", "--agent"),
324            ("Agents", "--agents"),
325            (
326                "AllowDangerouslySkipPermissions",
327                "--allow-dangerously-skip-permissions",
328            ),
329            ("AllowedTools", "--allowed-tools"),
330            ("AppendSystemPrompt", "--append-system-prompt"),
331            ("Betas", "--betas"),
332            ("Chrome", "--chrome"),
333            ("Continue", "--continue"),
334            (
335                "DangerouslySkipPermissions",
336                "--dangerously-skip-permissions",
337            ),
338            ("Debug", "--debug"),
339            ("DebugFile", "--debug-file"),
340            ("DisableSlashCommands", "--disable-slash-commands"),
341            ("DisallowedTools", "--disallowed-tools"),
342            ("FallbackModel", "--fallback-model"),
343            ("File", "--file"),
344            ("ForkSession", "--fork-session"),
345            ("FromPr", "--from-pr"),
346            ("IncludePartialMessages", "--include-partial-messages"),
347            ("InputFormat", "--input-format"),
348            ("JsonSchema", "--json-schema"),
349            ("MaxBudgetUsd", "--max-budget-usd"),
350            ("MaxThinkingTokens", "--max-thinking-tokens"),
351            ("McpConfig", "--mcp-config"),
352            ("McpDebug", "--mcp-debug"),
353            ("Model", "--model"),
354            ("NoChrome", "--no-chrome"),
355            ("NoSessionPersistence", "--no-session-persistence"),
356            ("OutputFormat", "--output-format"),
357            ("PermissionMode", "--permission-mode"),
358            ("PermissionPromptTool", "--permission-prompt-tool"),
359            ("PluginDir", "--plugin-dir"),
360            ("Print", "--print"),
361            ("ReplayUserMessages", "--replay-user-messages"),
362            ("Resume", "--resume"),
363            ("SessionId", "--session-id"),
364            ("SettingSources", "--setting-sources"),
365            ("Settings", "--settings"),
366            ("StrictMcpConfig", "--strict-mcp-config"),
367            ("SystemPrompt", "--system-prompt"),
368            ("Tools", "--tools"),
369            ("Verbose", "--verbose"),
370        ]
371    }
372}
373
374/// Builder for creating Claude CLI commands in JSON streaming mode
375///
376/// This builder automatically configures Claude to use:
377/// - `--print` mode for non-interactive operation
378/// - `--output-format stream-json` for streaming JSON responses
379/// - `--input-format stream-json` for JSON input
380/// - `--replay-user-messages` to echo back user messages
381#[derive(Debug, Clone)]
382pub struct ClaudeCliBuilder {
383    command: PathBuf,
384    working_directory: Option<PathBuf>,
385    prompt: Option<String>,
386    debug: Option<String>,
387    verbose: bool,
388    dangerously_skip_permissions: bool,
389    allowed_tools: Vec<String>,
390    disallowed_tools: Vec<String>,
391    mcp_config: Vec<String>,
392    append_system_prompt: Option<String>,
393    permission_mode: Option<PermissionMode>,
394    continue_conversation: bool,
395    resume: Option<String>,
396    model: Option<String>,
397    fallback_model: Option<String>,
398    settings: Option<String>,
399    add_dir: Vec<PathBuf>,
400    ide: bool,
401    strict_mcp_config: bool,
402    session_id: Option<Uuid>,
403    oauth_token: Option<String>,
404    api_key: Option<String>,
405    /// Tool for handling permission prompts (e.g., "stdio" for bidirectional control)
406    permission_prompt_tool: Option<String>,
407    /// Allow spawning inside another Claude Code session by unsetting CLAUDECODE env var
408    allow_recursion: bool,
409    /// Maximum number of tokens for extended thinking
410    max_thinking_tokens: Option<u32>,
411}
412
413impl Default for ClaudeCliBuilder {
414    fn default() -> Self {
415        Self::new()
416    }
417}
418
419impl ClaudeCliBuilder {
420    /// Create a new Claude CLI builder with JSON streaming mode pre-configured
421    pub fn new() -> Self {
422        Self {
423            command: PathBuf::from("claude"),
424            working_directory: None,
425            prompt: None,
426            debug: None,
427            verbose: false,
428            dangerously_skip_permissions: false,
429            allowed_tools: Vec::new(),
430            disallowed_tools: Vec::new(),
431            mcp_config: Vec::new(),
432            append_system_prompt: None,
433            permission_mode: None,
434            continue_conversation: false,
435            resume: None,
436            model: None,
437            fallback_model: None,
438            settings: None,
439            add_dir: Vec::new(),
440            ide: false,
441            strict_mcp_config: false,
442            session_id: None,
443            oauth_token: None,
444            api_key: None,
445            permission_prompt_tool: None,
446            allow_recursion: false,
447            max_thinking_tokens: None,
448        }
449    }
450
451    /// Set custom path to Claude binary
452    pub fn command<P: Into<PathBuf>>(mut self, path: P) -> Self {
453        self.command = path.into();
454        self
455    }
456
457    /// Set the working directory for the Claude process.
458    pub fn working_directory<P: Into<PathBuf>>(mut self, path: P) -> Self {
459        self.working_directory = Some(path.into());
460        self
461    }
462
463    /// Set the prompt for Claude
464    pub fn prompt<S: Into<String>>(mut self, prompt: S) -> Self {
465        self.prompt = Some(prompt.into());
466        self
467    }
468
469    /// Enable debug mode with optional filter
470    pub fn debug<S: Into<String>>(mut self, filter: Option<S>) -> Self {
471        self.debug = filter.map(|s| s.into());
472        self
473    }
474
475    /// Enable verbose mode
476    pub fn verbose(mut self, verbose: bool) -> Self {
477        self.verbose = verbose;
478        self
479    }
480
481    /// Skip all permission checks (dangerous!)
482    pub fn dangerously_skip_permissions(mut self, skip: bool) -> Self {
483        self.dangerously_skip_permissions = skip;
484        self
485    }
486
487    /// Add allowed tools
488    pub fn allowed_tools<I, S>(mut self, tools: I) -> Self
489    where
490        I: IntoIterator<Item = S>,
491        S: Into<String>,
492    {
493        self.allowed_tools
494            .extend(tools.into_iter().map(|s| s.into()));
495        self
496    }
497
498    /// Add disallowed tools
499    pub fn disallowed_tools<I, S>(mut self, tools: I) -> Self
500    where
501        I: IntoIterator<Item = S>,
502        S: Into<String>,
503    {
504        self.disallowed_tools
505            .extend(tools.into_iter().map(|s| s.into()));
506        self
507    }
508
509    /// Add MCP configuration
510    pub fn mcp_config<I, S>(mut self, configs: I) -> Self
511    where
512        I: IntoIterator<Item = S>,
513        S: Into<String>,
514    {
515        self.mcp_config
516            .extend(configs.into_iter().map(|s| s.into()));
517        self
518    }
519
520    /// Append a system prompt
521    pub fn append_system_prompt<S: Into<String>>(mut self, prompt: S) -> Self {
522        self.append_system_prompt = Some(prompt.into());
523        self
524    }
525
526    /// Set permission mode
527    pub fn permission_mode(mut self, mode: PermissionMode) -> Self {
528        self.permission_mode = Some(mode);
529        self
530    }
531
532    /// Continue the most recent conversation
533    pub fn continue_conversation(mut self, continue_conv: bool) -> Self {
534        self.continue_conversation = continue_conv;
535        self
536    }
537
538    /// Resume a specific conversation
539    pub fn resume<S: Into<String>>(mut self, session_id: Option<S>) -> Self {
540        self.resume = session_id.map(|s| s.into());
541        self
542    }
543
544    /// Set the model to use
545    pub fn model<S: Into<String>>(mut self, model: S) -> Self {
546        self.model = Some(model.into());
547        self
548    }
549
550    /// Set fallback model for overload situations
551    pub fn fallback_model<S: Into<String>>(mut self, model: S) -> Self {
552        self.fallback_model = Some(model.into());
553        self
554    }
555
556    /// Set maximum number of tokens for extended thinking
557    pub fn max_thinking_tokens(mut self, tokens: u32) -> Self {
558        self.max_thinking_tokens = Some(tokens);
559        self
560    }
561
562    /// Load settings from file or JSON
563    pub fn settings<S: Into<String>>(mut self, settings: S) -> Self {
564        self.settings = Some(settings.into());
565        self
566    }
567
568    /// Add directories for tool access
569    pub fn add_directories<I, P>(mut self, dirs: I) -> Self
570    where
571        I: IntoIterator<Item = P>,
572        P: Into<PathBuf>,
573    {
574        self.add_dir.extend(dirs.into_iter().map(|p| p.into()));
575        self
576    }
577
578    /// Automatically connect to IDE
579    pub fn ide(mut self, ide: bool) -> Self {
580        self.ide = ide;
581        self
582    }
583
584    /// Use only MCP servers from config
585    pub fn strict_mcp_config(mut self, strict: bool) -> Self {
586        self.strict_mcp_config = strict;
587        self
588    }
589
590    /// Set a specific session ID (must be a UUID)
591    pub fn session_id(mut self, id: Uuid) -> Self {
592        self.session_id = Some(id);
593        self
594    }
595
596    /// Set OAuth token for authentication (must start with "sk-ant-oat")
597    pub fn oauth_token<S: Into<String>>(mut self, token: S) -> Self {
598        let token_str = token.into();
599        if !token_str.starts_with("sk-ant-oat") {
600            eprintln!("Warning: OAuth token should start with 'sk-ant-oat'");
601        }
602        self.oauth_token = Some(token_str);
603        self
604    }
605
606    /// Set API key for authentication (must start with "sk-ant-api")
607    pub fn api_key<S: Into<String>>(mut self, key: S) -> Self {
608        let key_str = key.into();
609        if !key_str.starts_with("sk-ant-api") {
610            eprintln!("Warning: API key should start with 'sk-ant-api'");
611        }
612        self.api_key = Some(key_str);
613        self
614    }
615
616    /// Enable bidirectional tool permission protocol via stdio
617    ///
618    /// When enabled, Claude CLI will send permission requests via stdout
619    /// and expect responses via stdin. Use "stdio" for standard I/O based
620    /// permission handling.
621    ///
622    /// # Example
623    /// ```
624    /// use claude_codes::ClaudeCliBuilder;
625    ///
626    /// let builder = ClaudeCliBuilder::new()
627    ///     .permission_prompt_tool("stdio")
628    ///     .model("sonnet");
629    /// ```
630    pub fn permission_prompt_tool<S: Into<String>>(mut self, tool: S) -> Self {
631        self.permission_prompt_tool = Some(tool.into());
632        self
633    }
634
635    /// Allow spawning inside another Claude Code session by unsetting the
636    /// `CLAUDECODE` environment variable in the child process.
637    #[cfg(feature = "integration-tests")]
638    pub fn allow_recursion(mut self) -> Self {
639        self.allow_recursion = true;
640        self
641    }
642
643    /// Resolve the command path, using `which` for non-absolute paths.
644    fn resolve_command(&self) -> Result<PathBuf> {
645        if self.command.is_absolute() {
646            return Ok(self.command.clone());
647        }
648        which::which(&self.command).map_err(|_| Error::BinaryNotFound {
649            name: self.command.display().to_string(),
650        })
651    }
652
653    /// Build the command arguments (always includes JSON streaming flags)
654    fn build_args(&self) -> Vec<String> {
655        // Always add JSON streaming mode flags
656        // Note: --print with stream-json requires --verbose
657        let mut args = vec![
658            "--print".to_string(),
659            "--verbose".to_string(),
660            "--output-format".to_string(),
661            "stream-json".to_string(),
662            "--input-format".to_string(),
663            "stream-json".to_string(),
664        ];
665
666        if let Some(ref debug) = self.debug {
667            args.push("--debug".to_string());
668            if !debug.is_empty() {
669                args.push(debug.clone());
670            }
671        }
672
673        if self.dangerously_skip_permissions {
674            args.push("--dangerously-skip-permissions".to_string());
675        }
676
677        if !self.allowed_tools.is_empty() {
678            args.push("--allowed-tools".to_string());
679            args.extend(self.allowed_tools.clone());
680        }
681
682        if !self.disallowed_tools.is_empty() {
683            args.push("--disallowed-tools".to_string());
684            args.extend(self.disallowed_tools.clone());
685        }
686
687        if !self.mcp_config.is_empty() {
688            args.push("--mcp-config".to_string());
689            args.extend(self.mcp_config.clone());
690        }
691
692        if let Some(ref prompt) = self.append_system_prompt {
693            args.push("--append-system-prompt".to_string());
694            args.push(prompt.clone());
695        }
696
697        if let Some(ref mode) = self.permission_mode {
698            args.push("--permission-mode".to_string());
699            args.push(mode.as_str().to_string());
700        }
701
702        if self.continue_conversation {
703            args.push("--continue".to_string());
704        }
705
706        if let Some(ref session) = self.resume {
707            args.push("--resume".to_string());
708            args.push(session.clone());
709        }
710
711        if let Some(ref model) = self.model {
712            args.push("--model".to_string());
713            args.push(model.clone());
714        }
715
716        if let Some(ref model) = self.fallback_model {
717            args.push("--fallback-model".to_string());
718            args.push(model.clone());
719        }
720
721        if let Some(tokens) = self.max_thinking_tokens {
722            args.push("--max-thinking-tokens".to_string());
723            args.push(tokens.to_string());
724        }
725
726        if let Some(ref settings) = self.settings {
727            args.push("--settings".to_string());
728            args.push(settings.clone());
729        }
730
731        if !self.add_dir.is_empty() {
732            args.push("--add-dir".to_string());
733            for dir in &self.add_dir {
734                args.push(dir.to_string_lossy().to_string());
735            }
736        }
737
738        if self.ide {
739            args.push("--ide".to_string());
740        }
741
742        if self.strict_mcp_config {
743            args.push("--strict-mcp-config".to_string());
744        }
745
746        if let Some(ref tool) = self.permission_prompt_tool {
747            args.push("--permission-prompt-tool".to_string());
748            args.push(tool.clone());
749        }
750
751        // Only add --session-id when NOT resuming/continuing an existing session
752        // (Claude CLI error: --session-id can only be used with --continue or --resume
753        // if --fork-session is also specified)
754        if self.resume.is_none() && !self.continue_conversation {
755            args.push("--session-id".to_string());
756            let session_uuid = self.session_id.unwrap_or_else(|| {
757                let uuid = Uuid::new_v4();
758                debug!("[CLI] Generated session UUID: {}", uuid);
759                uuid
760            });
761            args.push(session_uuid.to_string());
762        }
763
764        // Add prompt as the last argument if provided
765        if let Some(ref prompt) = self.prompt {
766            args.push(prompt.clone());
767        }
768
769        args
770    }
771
772    /// Spawn the Claude process
773    #[cfg(feature = "async-client")]
774    pub async fn spawn(self) -> Result<tokio::process::Child> {
775        let resolved = self.resolve_command()?;
776        let args = self.build_args();
777
778        debug!(
779            "[CLI] Executing command: {} {}",
780            resolved.display(),
781            args.join(" ")
782        );
783
784        let mut cmd = tokio::process::Command::new(&resolved);
785        cmd.args(&args)
786            .stdin(Stdio::piped())
787            .stdout(Stdio::piped())
788            .stderr(Stdio::piped());
789
790        if let Some(ref dir) = self.working_directory {
791            cmd.current_dir(dir);
792        }
793
794        if self.allow_recursion {
795            cmd.env_remove("CLAUDECODE");
796        }
797
798        if let Some(ref token) = self.oauth_token {
799            cmd.env("CLAUDE_CODE_OAUTH_TOKEN", token);
800        }
801
802        if let Some(ref key) = self.api_key {
803            cmd.env("ANTHROPIC_API_KEY", key);
804        }
805
806        crate::process::configure_no_window(cmd.as_std_mut());
807        let child = cmd.spawn().map_err(Error::Io)?;
808
809        Ok(child)
810    }
811
812    /// Build a Command without spawning (for testing or manual execution)
813    #[cfg(feature = "async-client")]
814    pub fn build_command(self) -> Result<tokio::process::Command> {
815        let resolved = self.resolve_command()?;
816        let args = self.build_args();
817        let mut cmd = tokio::process::Command::new(&resolved);
818        cmd.args(&args)
819            .stdin(Stdio::piped())
820            .stdout(Stdio::piped())
821            .stderr(Stdio::piped());
822
823        if let Some(ref dir) = self.working_directory {
824            cmd.current_dir(dir);
825        }
826
827        if self.allow_recursion {
828            cmd.env_remove("CLAUDECODE");
829        }
830
831        if let Some(ref token) = self.oauth_token {
832            cmd.env("CLAUDE_CODE_OAUTH_TOKEN", token);
833        }
834
835        if let Some(ref key) = self.api_key {
836            cmd.env("ANTHROPIC_API_KEY", key);
837        }
838
839        crate::process::configure_no_window(cmd.as_std_mut());
840        Ok(cmd)
841    }
842
843    /// Spawn the Claude process using synchronous std::process
844    pub fn spawn_sync(self) -> Result<std::process::Child> {
845        let resolved = self.resolve_command()?;
846        let args = self.build_args();
847
848        debug!(
849            "[CLI] Executing sync command: {} {}",
850            resolved.display(),
851            args.join(" ")
852        );
853
854        let mut cmd = std::process::Command::new(&resolved);
855        cmd.args(&args)
856            .stdin(Stdio::piped())
857            .stdout(Stdio::piped())
858            .stderr(Stdio::piped());
859
860        if let Some(ref dir) = self.working_directory {
861            cmd.current_dir(dir);
862        }
863
864        if self.allow_recursion {
865            cmd.env_remove("CLAUDECODE");
866        }
867
868        if let Some(ref token) = self.oauth_token {
869            cmd.env("CLAUDE_CODE_OAUTH_TOKEN", token);
870        }
871
872        if let Some(ref key) = self.api_key {
873            cmd.env("ANTHROPIC_API_KEY", key);
874        }
875
876        crate::process::configure_no_window(&mut cmd);
877        cmd.spawn().map_err(Error::Io)
878    }
879}
880
881#[cfg(test)]
882mod tests {
883    use super::*;
884
885    #[test]
886    fn test_working_directory() {
887        let builder = ClaudeCliBuilder::new().working_directory("workspace");
888        assert_eq!(builder.working_directory, Some(PathBuf::from("workspace")));
889    }
890
891    #[test]
892    fn test_streaming_flags_always_present() {
893        let builder = ClaudeCliBuilder::new();
894        let args = builder.build_args();
895
896        // Verify all streaming flags are present by default
897        assert!(args.contains(&"--print".to_string()));
898        assert!(args.contains(&"--verbose".to_string())); // Required for --print with stream-json
899        assert!(args.contains(&"--output-format".to_string()));
900        assert!(args.contains(&"stream-json".to_string()));
901        assert!(args.contains(&"--input-format".to_string()));
902    }
903
904    #[test]
905    fn test_with_prompt() {
906        let builder = ClaudeCliBuilder::new().prompt("Hello, Claude!");
907        let args = builder.build_args();
908
909        assert_eq!(args.last().unwrap(), "Hello, Claude!");
910    }
911
912    #[test]
913    fn test_with_model() {
914        let builder = ClaudeCliBuilder::new()
915            .model("sonnet")
916            .fallback_model("opus");
917        let args = builder.build_args();
918
919        assert!(args.contains(&"--model".to_string()));
920        assert!(args.contains(&"sonnet".to_string()));
921        assert!(args.contains(&"--fallback-model".to_string()));
922        assert!(args.contains(&"opus".to_string()));
923    }
924
925    #[test]
926    fn test_with_debug() {
927        let builder = ClaudeCliBuilder::new().debug(Some("api"));
928        let args = builder.build_args();
929
930        assert!(args.contains(&"--debug".to_string()));
931        assert!(args.contains(&"api".to_string()));
932    }
933
934    #[test]
935    fn test_with_oauth_token() {
936        let valid_token = "sk-ant-oat-123456789";
937        let builder = ClaudeCliBuilder::new().oauth_token(valid_token);
938
939        // OAuth token is set as env var, not in args
940        let args = builder.clone().build_args();
941        assert!(!args.contains(&valid_token.to_string()));
942
943        // Verify it's stored in the builder
944        assert_eq!(builder.oauth_token, Some(valid_token.to_string()));
945    }
946
947    #[test]
948    fn test_oauth_token_validation() {
949        // Test with invalid prefix (should print warning but still accept)
950        let invalid_token = "invalid-token-123";
951        let builder = ClaudeCliBuilder::new().oauth_token(invalid_token);
952        assert_eq!(builder.oauth_token, Some(invalid_token.to_string()));
953    }
954
955    #[test]
956    fn test_with_api_key() {
957        let valid_key = "sk-ant-api-987654321";
958        let builder = ClaudeCliBuilder::new().api_key(valid_key);
959
960        // API key is set as env var, not in args
961        let args = builder.clone().build_args();
962        assert!(!args.contains(&valid_key.to_string()));
963
964        // Verify it's stored in the builder
965        assert_eq!(builder.api_key, Some(valid_key.to_string()));
966    }
967
968    #[test]
969    fn test_api_key_validation() {
970        // Test with invalid prefix (should print warning but still accept)
971        let invalid_key = "invalid-api-key";
972        let builder = ClaudeCliBuilder::new().api_key(invalid_key);
973        assert_eq!(builder.api_key, Some(invalid_key.to_string()));
974    }
975
976    #[test]
977    fn test_both_auth_methods() {
978        let oauth = "sk-ant-oat-123";
979        let api_key = "sk-ant-api-456";
980        let builder = ClaudeCliBuilder::new().oauth_token(oauth).api_key(api_key);
981
982        assert_eq!(builder.oauth_token, Some(oauth.to_string()));
983        assert_eq!(builder.api_key, Some(api_key.to_string()));
984    }
985
986    #[test]
987    fn test_permission_prompt_tool() {
988        let builder = ClaudeCliBuilder::new().permission_prompt_tool("stdio");
989        let args = builder.build_args();
990
991        assert!(args.contains(&"--permission-prompt-tool".to_string()));
992        assert!(args.contains(&"stdio".to_string()));
993    }
994
995    #[test]
996    fn test_permission_prompt_tool_not_present_by_default() {
997        let builder = ClaudeCliBuilder::new();
998        let args = builder.build_args();
999
1000        assert!(!args.contains(&"--permission-prompt-tool".to_string()));
1001    }
1002
1003    #[test]
1004    fn test_session_id_present_for_new_session() {
1005        let builder = ClaudeCliBuilder::new();
1006        let args = builder.build_args();
1007
1008        assert!(
1009            args.contains(&"--session-id".to_string()),
1010            "New sessions should have --session-id"
1011        );
1012    }
1013
1014    #[test]
1015    fn test_session_id_not_present_with_resume() {
1016        // When resuming a session, --session-id should NOT be added
1017        // (Claude CLI rejects --session-id + --resume without --fork-session)
1018        let builder = ClaudeCliBuilder::new().resume(Some("existing-uuid".to_string()));
1019        let args = builder.build_args();
1020
1021        assert!(
1022            args.contains(&"--resume".to_string()),
1023            "Should have --resume flag"
1024        );
1025        assert!(
1026            !args.contains(&"--session-id".to_string()),
1027            "--session-id should NOT be present when resuming"
1028        );
1029    }
1030
1031    #[test]
1032    fn test_session_id_not_present_with_continue() {
1033        // When continuing a session, --session-id should NOT be added
1034        let builder = ClaudeCliBuilder::new().continue_conversation(true);
1035        let args = builder.build_args();
1036
1037        assert!(
1038            args.contains(&"--continue".to_string()),
1039            "Should have --continue flag"
1040        );
1041        assert!(
1042            !args.contains(&"--session-id".to_string()),
1043            "--session-id should NOT be present when continuing"
1044        );
1045    }
1046}