1use crate::error::{Error, Result};
13use log::debug;
14use std::path::PathBuf;
15use std::process::Stdio;
16use uuid::Uuid;
17
18#[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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum InputFormat {
46 Text,
47 StreamJson,
48}
49
50impl InputFormat {
51 pub fn as_str(&self) -> &'static str {
53 match self {
54 InputFormat::Text => "text",
55 InputFormat::StreamJson => "stream-json",
56 }
57 }
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum OutputFormat {
63 Text,
64 Json,
65 StreamJson,
66}
67
68impl OutputFormat {
69 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#[derive(Debug, Clone)]
96pub enum CliFlag {
97 AddDir(Vec<PathBuf>),
99 Agent(String),
101 Agents(String),
103 AllowDangerouslySkipPermissions,
105 AllowedTools(Vec<String>),
107 AppendSystemPrompt(String),
109 Betas(Vec<String>),
111 Chrome,
113 Continue,
115 DangerouslySkipPermissions,
117 Debug(Option<String>),
119 DebugFile(PathBuf),
121 DisableSlashCommands,
123 DisallowedTools(Vec<String>),
125 FallbackModel(String),
127 File(Vec<String>),
129 ForkSession,
131 FromPr(Option<String>),
133 IncludePartialMessages,
135 InputFormat(InputFormat),
137 JsonSchema(String),
139 MaxBudgetUsd(f64),
141 MaxThinkingTokens(u32),
143 McpConfig(Vec<String>),
145 McpDebug,
147 Model(String),
149 NoChrome,
151 NoSessionPersistence,
153 OutputFormat(OutputFormat),
155 PermissionMode(PermissionMode),
157 PermissionPromptTool(String),
159 PluginDir(Vec<PathBuf>),
161 Print,
163 ReplayUserMessages,
165 Resume(Option<String>),
167 SessionId(String),
169 SettingSources(String),
171 Settings(String),
173 StrictMcpConfig,
175 SystemPrompt(String),
177 Tools(Vec<String>),
179 Verbose,
181}
182
183impl CliFlag {
184 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 pub fn to_args(&self) -> Vec<String> {
234 let flag = self.as_flag().to_string();
235 match self {
236 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 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 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 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 CliFlag::MaxBudgetUsd(amount) => vec![flag, amount.to_string()],
282 CliFlag::MaxThinkingTokens(tokens) => vec![flag, tokens.to_string()],
283
284 CliFlag::DebugFile(p) => vec![flag, p.to_string_lossy().to_string()],
286
287 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 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 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#[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 permission_prompt_tool: Option<String>,
407 allow_recursion: bool,
409 max_thinking_tokens: Option<u32>,
411}
412
413impl Default for ClaudeCliBuilder {
414 fn default() -> Self {
415 Self::new()
416 }
417}
418
419impl ClaudeCliBuilder {
420 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 pub fn command<P: Into<PathBuf>>(mut self, path: P) -> Self {
453 self.command = path.into();
454 self
455 }
456
457 pub fn working_directory<P: Into<PathBuf>>(mut self, path: P) -> Self {
459 self.working_directory = Some(path.into());
460 self
461 }
462
463 pub fn prompt<S: Into<String>>(mut self, prompt: S) -> Self {
465 self.prompt = Some(prompt.into());
466 self
467 }
468
469 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 pub fn verbose(mut self, verbose: bool) -> Self {
477 self.verbose = verbose;
478 self
479 }
480
481 pub fn dangerously_skip_permissions(mut self, skip: bool) -> Self {
483 self.dangerously_skip_permissions = skip;
484 self
485 }
486
487 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 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 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 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 pub fn permission_mode(mut self, mode: PermissionMode) -> Self {
528 self.permission_mode = Some(mode);
529 self
530 }
531
532 pub fn continue_conversation(mut self, continue_conv: bool) -> Self {
534 self.continue_conversation = continue_conv;
535 self
536 }
537
538 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 pub fn model<S: Into<String>>(mut self, model: S) -> Self {
546 self.model = Some(model.into());
547 self
548 }
549
550 pub fn fallback_model<S: Into<String>>(mut self, model: S) -> Self {
552 self.fallback_model = Some(model.into());
553 self
554 }
555
556 pub fn max_thinking_tokens(mut self, tokens: u32) -> Self {
558 self.max_thinking_tokens = Some(tokens);
559 self
560 }
561
562 pub fn settings<S: Into<String>>(mut self, settings: S) -> Self {
564 self.settings = Some(settings.into());
565 self
566 }
567
568 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 pub fn ide(mut self, ide: bool) -> Self {
580 self.ide = ide;
581 self
582 }
583
584 pub fn strict_mcp_config(mut self, strict: bool) -> Self {
586 self.strict_mcp_config = strict;
587 self
588 }
589
590 pub fn session_id(mut self, id: Uuid) -> Self {
592 self.session_id = Some(id);
593 self
594 }
595
596 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 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 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 #[cfg(feature = "integration-tests")]
638 pub fn allow_recursion(mut self) -> Self {
639 self.allow_recursion = true;
640 self
641 }
642
643 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 fn build_args(&self) -> Vec<String> {
655 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 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 if let Some(ref prompt) = self.prompt {
766 args.push(prompt.clone());
767 }
768
769 args
770 }
771
772 #[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 #[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 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 assert!(args.contains(&"--print".to_string()));
898 assert!(args.contains(&"--verbose".to_string())); 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 let args = builder.clone().build_args();
941 assert!(!args.contains(&valid_token.to_string()));
942
943 assert_eq!(builder.oauth_token, Some(valid_token.to_string()));
945 }
946
947 #[test]
948 fn test_oauth_token_validation() {
949 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 let args = builder.clone().build_args();
962 assert!(!args.contains(&valid_key.to_string()));
963
964 assert_eq!(builder.api_key, Some(valid_key.to_string()));
966 }
967
968 #[test]
969 fn test_api_key_validation() {
970 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 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 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}