Skip to main content

cc_switch/cli/
main.rs

1use crate::cli::completion::{
2    generate_completion, list_aliases_for_completion, list_codex_aliases_for_completion,
3    list_omp_aliases_for_completion,
4};
5use crate::cli::{Cli, Commands};
6use crate::codex::{
7    handle_codex_add, handle_codex_interactive, handle_codex_list, handle_codex_remove,
8    handle_codex_use,
9};
10use crate::config::types::{AddCommandParams, ClaudeSettings, StorageMode};
11use crate::config::{ConfigStorage, Configuration, EnvironmentConfig, validate_alias_name};
12use crate::interactive::{
13    handle_interactive_selection, launch_claude_with_env, read_input, read_sensitive_input,
14};
15use crate::omp::{
16    handle_omp_add, handle_omp_interactive, handle_omp_list, handle_omp_remove, handle_omp_use,
17};
18use anyhow::{Result, anyhow};
19use clap::Parser;
20use std::fs;
21
22/// Parse storage mode string to StorageMode enum
23///
24/// # Arguments
25/// * `store_str` - String representation of storage mode ("env" or "config")
26///
27/// # Returns
28/// Result containing StorageMode or error if invalid
29fn parse_storage_mode(store_str: &str) -> Result<StorageMode> {
30    match store_str.to_lowercase().as_str() {
31        "env" => Ok(StorageMode::Env),
32        "config" => Ok(StorageMode::Config),
33        _ => Err(anyhow!(
34            "Invalid storage mode '{}'. Use 'env' or 'config'",
35            store_str
36        )),
37    }
38}
39
40/// Parse a configuration from a JSON file
41///
42/// # Arguments
43/// * `file_path` - Path to the JSON configuration file
44///
45/// # Returns
46/// Result containing a tuple of configuration values (token, url, and optional fields)
47///
48/// # Errors
49/// Returns error if file cannot be read or parsed
50#[allow(clippy::type_complexity)]
51fn parse_config_from_file(
52    file_path: &str,
53) -> Result<(
54    String,
55    Option<String>,
56    String,
57    Option<String>,
58    Option<String>,
59    Option<u32>,
60    Option<u32>,
61    Option<u32>,
62    Option<String>,
63    Option<String>,
64    Option<String>,
65    Option<String>,
66    Option<u32>,
67    Option<String>,
68    Option<u32>,
69    Option<u32>,
70    Option<u32>,
71)> {
72    let file_content = fs::read_to_string(file_path)
73        .map_err(|e| anyhow!("Failed to read file '{}': {}", file_path, e))?;
74
75    let json: serde_json::Value = serde_json::from_str(&file_content)
76        .map_err(|e| anyhow!("Failed to parse JSON from file '{}': {}", file_path, e))?;
77
78    let env = json.get("env").and_then(|v| v.as_object()).ok_or_else(|| {
79        anyhow!(
80            "File '{}' does not contain a valid 'env' section",
81            file_path
82        )
83    })?;
84
85    let auth_token = env
86        .get("ANTHROPIC_AUTH_TOKEN")
87        .and_then(|v| v.as_str())
88        .map(|s| s.to_string());
89
90    let api_key = env
91        .get("ANTHROPIC_API_KEY")
92        .and_then(|v| v.as_str())
93        .map(|s| s.to_string());
94
95    if auth_token.is_some() && api_key.is_some() {
96        anyhow::bail!(
97            "File '{}' contains both ANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY — only one is allowed",
98            file_path
99        );
100    }
101
102    let token = match (&auth_token, &api_key) {
103        (Some(t), None) => t.clone(),
104        (None, Some(_)) => String::new(),
105        (None, None) => {
106            anyhow::bail!(
107                "Missing ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY in file '{}'",
108                file_path
109            );
110        }
111        _ => unreachable!(),
112    };
113
114    let url = env
115        .get("ANTHROPIC_BASE_URL")
116        .and_then(|v| v.as_str())
117        .ok_or_else(|| anyhow!("Missing ANTHROPIC_BASE_URL in file '{}'", file_path))?
118        .to_string();
119
120    let model = env
121        .get("ANTHROPIC_MODEL")
122        .and_then(|v| v.as_str())
123        .map(|s| s.to_string());
124
125    let small_fast_model = env
126        .get("ANTHROPIC_SMALL_FAST_MODEL")
127        .and_then(|v| v.as_str())
128        .map(|s| s.to_string());
129
130    let max_thinking_tokens = env
131        .get("ANTHROPIC_MAX_THINKING_TOKENS")
132        .and_then(|v| v.as_u64())
133        .map(|u| u as u32);
134
135    let api_timeout_ms = env
136        .get("API_TIMEOUT_MS")
137        .and_then(|v| v.as_u64())
138        .map(|u| u as u32);
139
140    let claude_code_disable_nonessential_traffic = env
141        .get("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC")
142        .and_then(|v| v.as_u64())
143        .map(|u| u as u32);
144
145    let anthropic_default_sonnet_model = env
146        .get("ANTHROPIC_DEFAULT_SONNET_MODEL")
147        .and_then(|v| v.as_str())
148        .map(|s| s.to_string());
149
150    let anthropic_default_opus_model = env
151        .get("ANTHROPIC_DEFAULT_OPUS_MODEL")
152        .and_then(|v| v.as_str())
153        .map(|s| s.to_string());
154
155    let anthropic_default_haiku_model = env
156        .get("ANTHROPIC_DEFAULT_HAIKU_MODEL")
157        .and_then(|v| v.as_str())
158        .map(|s| s.to_string());
159
160    let claude_code_subagent_model = env
161        .get("CLAUDE_CODE_SUBAGENT_MODEL")
162        .and_then(|v| v.as_str())
163        .map(|s| s.to_string());
164
165    let claude_code_disable_nonstreaming_fallback = env
166        .get("CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK")
167        .and_then(|v| v.as_u64())
168        .map(|u| u as u32);
169
170    let claude_code_effort_level = env
171        .get("CLAUDE_CODE_EFFORT_LEVEL")
172        .and_then(|v| v.as_str())
173        .map(|s| s.to_string());
174
175    let disable_prompt_caching = env
176        .get("DISABLE_PROMPT_CACHING")
177        .and_then(|v| v.as_u64())
178        .map(|u| u as u32);
179
180    let claude_code_disable_experimental_betas = env
181        .get("CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS")
182        .and_then(|v| v.as_u64())
183        .map(|u| u as u32);
184
185    let disable_autoupdater = env
186        .get("DISABLE_AUTOUPDATER")
187        .and_then(|v| v.as_u64())
188        .map(|u| u as u32);
189
190    Ok((
191        token,
192        api_key,
193        url,
194        model,
195        small_fast_model,
196        max_thinking_tokens,
197        api_timeout_ms,
198        claude_code_disable_nonessential_traffic,
199        anthropic_default_sonnet_model,
200        anthropic_default_opus_model,
201        anthropic_default_haiku_model,
202        claude_code_subagent_model,
203        claude_code_disable_nonstreaming_fallback,
204        claude_code_effort_level,
205        disable_prompt_caching,
206        claude_code_disable_experimental_betas,
207        disable_autoupdater,
208    ))
209}
210
211/// Handle adding a configuration with all the new features
212///
213/// # Arguments
214/// * `params` - Parameters for the add command
215/// * `storage` - Mutable reference to config storage
216///
217/// # Errors
218/// Returns error if validation fails or user cancels interactive input
219fn handle_add_command(mut params: AddCommandParams, storage: &mut ConfigStorage) -> Result<()> {
220    // If from-file is provided, parse the file and use those values
221    if let Some(file_path) = &params.from_file {
222        println!("Importing configuration from file: {}", file_path);
223
224        let (
225            file_token,
226            file_api_key,
227            file_url,
228            file_model,
229            file_small_fast_model,
230            file_max_thinking_tokens,
231            file_api_timeout_ms,
232            file_claude_disable_nonessential_traffic,
233            file_sonnet_model,
234            file_opus_model,
235            file_haiku_model,
236            file_subagent_model,
237            file_disable_nonstreaming_fallback,
238            file_effort_level,
239            file_disable_prompt_caching,
240            file_disable_experimental_betas,
241            file_disable_autoupdater,
242        ) = parse_config_from_file(file_path)?;
243
244        params.token = Some(file_token);
245        params.api_key = file_api_key;
246        params.url = Some(file_url);
247        params.model = file_model;
248        params.small_fast_model = file_small_fast_model;
249        params.max_thinking_tokens = file_max_thinking_tokens;
250        params.api_timeout_ms = file_api_timeout_ms;
251        params.claude_code_disable_nonessential_traffic = file_claude_disable_nonessential_traffic;
252        params.anthropic_default_sonnet_model = file_sonnet_model;
253        params.anthropic_default_opus_model = file_opus_model;
254        params.anthropic_default_haiku_model = file_haiku_model;
255        params.claude_code_subagent_model = file_subagent_model;
256        params.claude_code_disable_nonstreaming_fallback = file_disable_nonstreaming_fallback;
257        params.claude_code_effort_level = file_effort_level;
258        params.disable_prompt_caching = file_disable_prompt_caching;
259        params.claude_code_disable_experimental_betas = file_disable_experimental_betas;
260        params.disable_autoupdater = file_disable_autoupdater;
261
262        println!(
263            "Configuration '{}' will be imported from file",
264            params.alias_name
265        );
266    }
267
268    // Validate alias name
269    validate_alias_name(&params.alias_name)?;
270
271    // Check if alias already exists
272    if storage.get_configuration(&params.alias_name).is_some() && !params.force {
273        eprintln!("Configuration '{}' already exists.", params.alias_name);
274        eprintln!("Use --force to overwrite or choose a different alias name.");
275        return Ok(());
276    }
277
278    // Cannot use interactive mode with --from-file
279    if params.interactive && params.from_file.is_some() {
280        anyhow::bail!("Cannot use --interactive mode with --from-file");
281    }
282
283    // Enforce mutual exclusivity: --token and --api-key cannot both be provided
284    if params.token.is_some() && params.api_key.is_some() {
285        anyhow::bail!(
286            "Cannot use both --token and --api-key. Choose one:\n\
287             --token / -t  → sets ANTHROPIC_AUTH_TOKEN\n\
288             --api-key / -k → sets ANTHROPIC_API_KEY"
289        );
290    }
291
292    // Determine authentication value (token or api_key)
293    let (final_token, final_api_key): (String, Option<String>) = if params.interactive {
294        if params.token.is_some() || params.token_arg.is_some() || params.api_key.is_some() {
295            eprintln!(
296                "Warning: Token/API key provided via flags/arguments will be ignored in interactive mode"
297            );
298        }
299        let auth_type = read_input(
300            "Auth type — (1) ANTHROPIC_AUTH_TOKEN  (2) ANTHROPIC_API_KEY [default: 1]: ",
301        )?;
302        if auth_type == "2" {
303            let key = read_sensitive_input("Enter API key (ANTHROPIC_API_KEY): ")?;
304            (String::new(), Some(key))
305        } else {
306            let token = read_sensitive_input("Enter API token (sk-ant-xxx): ")?;
307            (token, None)
308        }
309    } else if let Some(key) = params.api_key {
310        (String::new(), Some(key))
311    } else {
312        match (&params.token, &params.token_arg) {
313            (Some(t), _) => (t.clone(), None),
314            (None, Some(t)) => (t.clone(), None),
315            (None, None) => {
316                anyhow::bail!(
317                    "Authentication is required. Use one of:\n\
318                     --token / -t  → sets ANTHROPIC_AUTH_TOKEN\n\
319                     --api-key / -k → sets ANTHROPIC_API_KEY\n\
320                     -i            → interactive mode"
321                );
322            }
323        }
324    };
325
326    // Determine URL value
327    let final_url = if params.interactive {
328        if params.url.is_some() || params.url_arg.is_some() {
329            eprintln!(
330                "Warning: URL provided via flags/arguments will be ignored in interactive mode"
331            );
332        }
333        read_input("Enter API URL (default: https://api.anthropic.com): ")?
334    } else {
335        match (&params.url, &params.url_arg) {
336            (Some(u), _) => u.clone(),
337            (None, Some(u)) => u.clone(),
338            (None, None) => "https://api.anthropic.com".to_string(),
339        }
340    };
341
342    // Use default URL if empty
343    let final_url = if final_url.is_empty() {
344        "https://api.anthropic.com".to_string()
345    } else {
346        final_url
347    };
348
349    // Determine model value
350    let final_model = if params.interactive {
351        if params.model.is_some() {
352            eprintln!("Warning: Model provided via flags will be ignored in interactive mode");
353        }
354        let model_input = read_input("Enter model name (optional, press enter to skip): ")?;
355        if model_input.is_empty() {
356            None
357        } else {
358            Some(model_input)
359        }
360    } else {
361        params.model
362    };
363
364    // Determine small fast model value
365    let final_small_fast_model = if params.interactive {
366        if params.small_fast_model.is_some() {
367            eprintln!(
368                "Warning: Small fast model provided via flags will be ignored in interactive mode"
369            );
370        }
371        let small_model_input =
372            read_input("Enter small fast model name (optional, press enter to skip): ")?;
373        if small_model_input.is_empty() {
374            None
375        } else {
376            Some(small_model_input)
377        }
378    } else {
379        params.small_fast_model
380    };
381
382    // Determine max thinking tokens value
383    let final_max_thinking_tokens = if params.interactive {
384        if params.max_thinking_tokens.is_some() {
385            eprintln!(
386                "Warning: Max thinking tokens provided via flags will be ignored in interactive mode"
387            );
388        }
389        let tokens_input = read_input(
390            "Enter maximum thinking tokens (optional, press enter to skip, enter 0 to clear): ",
391        )?;
392        if tokens_input.is_empty() {
393            None
394        } else if let Ok(tokens) = tokens_input.parse::<u32>() {
395            if tokens == 0 { None } else { Some(tokens) }
396        } else {
397            eprintln!("Warning: Invalid max thinking tokens value, skipping");
398            None
399        }
400    } else {
401        params.max_thinking_tokens
402    };
403
404    // Determine API timeout value
405    let final_api_timeout_ms = if params.interactive {
406        if params.api_timeout_ms.is_some() {
407            eprintln!(
408                "Warning: API timeout provided via flags will be ignored in interactive mode"
409            );
410        }
411        let timeout_input = read_input(
412            "Enter API timeout in milliseconds (optional, press enter to skip, enter 0 to clear): ",
413        )?;
414        if timeout_input.is_empty() {
415            None
416        } else if let Ok(timeout) = timeout_input.parse::<u32>() {
417            if timeout == 0 { None } else { Some(timeout) }
418        } else {
419            eprintln!("Warning: Invalid API timeout value, skipping");
420            None
421        }
422    } else {
423        params.api_timeout_ms
424    };
425
426    // Determine disable nonessential traffic flag value
427    let final_claude_code_disable_nonessential_traffic = if params.interactive {
428        if params.claude_code_disable_nonessential_traffic.is_some() {
429            eprintln!(
430                "Warning: Disable nonessential traffic flag provided via flags will be ignored in interactive mode"
431            );
432        }
433        let flag_input = read_input(
434            "Enter disable nonessential traffic flag (optional, press enter to skip, enter 0 to clear): ",
435        )?;
436        if flag_input.is_empty() {
437            None
438        } else if let Ok(flag) = flag_input.parse::<u32>() {
439            if flag == 0 { None } else { Some(flag) }
440        } else {
441            eprintln!("Warning: Invalid disable nonessential traffic flag value, skipping");
442            None
443        }
444    } else {
445        params.claude_code_disable_nonessential_traffic
446    };
447
448    // Determine default Sonnet model value
449    let final_anthropic_default_sonnet_model = if params.interactive {
450        if params.anthropic_default_sonnet_model.is_some() {
451            eprintln!(
452                "Warning: Default Sonnet model provided via flags will be ignored in interactive mode"
453            );
454        }
455        let model_input =
456            read_input("Enter default Sonnet model name (optional, press enter to skip): ")?;
457        if model_input.is_empty() {
458            None
459        } else {
460            Some(model_input)
461        }
462    } else {
463        params.anthropic_default_sonnet_model
464    };
465
466    // Determine default Opus model value
467    let final_anthropic_default_opus_model = if params.interactive {
468        if params.anthropic_default_opus_model.is_some() {
469            eprintln!(
470                "Warning: Default Opus model provided via flags will be ignored in interactive mode"
471            );
472        }
473        let model_input =
474            read_input("Enter default Opus model name (optional, press enter to skip): ")?;
475        if model_input.is_empty() {
476            None
477        } else {
478            Some(model_input)
479        }
480    } else {
481        params.anthropic_default_opus_model
482    };
483
484    // Determine default Haiku model value
485    let final_anthropic_default_haiku_model = if params.interactive {
486        if params.anthropic_default_haiku_model.is_some() {
487            eprintln!(
488                "Warning: Default Haiku model provided via flags will be ignored in interactive mode"
489            );
490        }
491        let model_input =
492            read_input("Enter default Haiku model name (optional, press enter to skip): ")?;
493        if model_input.is_empty() {
494            None
495        } else {
496            Some(model_input)
497        }
498    } else {
499        params.anthropic_default_haiku_model
500    };
501
502    // Determine subagent model value
503    let final_claude_code_subagent_model = if params.interactive {
504        if params.claude_code_subagent_model.is_some() {
505            eprintln!(
506                "Warning: Subagent model provided via flags will be ignored in interactive mode"
507            );
508        }
509        let model_input =
510            read_input("Enter subagent model name (optional, press enter to skip): ")?;
511        if model_input.is_empty() {
512            None
513        } else {
514            Some(model_input)
515        }
516    } else {
517        params.claude_code_subagent_model
518    };
519
520    // Determine disable non-streaming fallback flag value
521    let final_claude_code_disable_nonstreaming_fallback = if params.interactive {
522        if params.claude_code_disable_nonstreaming_fallback.is_some() {
523            eprintln!(
524                "Warning: Disable non-streaming fallback flag provided via flags will be ignored in interactive mode"
525            );
526        }
527        let flag_input = read_input(
528            "Enter disable non-streaming fallback flag (optional, press enter to skip, enter 0 to clear): ",
529        )?;
530        if flag_input.is_empty() {
531            None
532        } else if let Ok(flag) = flag_input.parse::<u32>() {
533            if flag == 0 { None } else { Some(flag) }
534        } else {
535            eprintln!("Warning: Invalid disable non-streaming fallback flag value, skipping");
536            None
537        }
538    } else {
539        params.claude_code_disable_nonstreaming_fallback
540    };
541
542    // Determine effort level value
543    let final_claude_code_effort_level = if params.interactive {
544        if params.claude_code_effort_level.is_some() {
545            eprintln!(
546                "Warning: Effort level provided via flags will be ignored in interactive mode"
547            );
548        }
549        let level_input = read_input("Enter effort level (optional, press enter to skip): ")?;
550        if level_input.is_empty() {
551            None
552        } else {
553            Some(level_input)
554        }
555    } else {
556        params.claude_code_effort_level
557    };
558
559    // Determine disable prompt caching flag value
560    let final_disable_prompt_caching = if params.interactive {
561        if params.disable_prompt_caching.is_some() {
562            eprintln!(
563                "Warning: Disable prompt caching flag provided via flags will be ignored in interactive mode"
564            );
565        }
566        let flag_input = read_input(
567            "Enter disable prompt caching flag (optional, press enter to skip, enter 0 to clear): ",
568        )?;
569        if flag_input.is_empty() {
570            None
571        } else if let Ok(flag) = flag_input.parse::<u32>() {
572            if flag == 0 { None } else { Some(flag) }
573        } else {
574            eprintln!("Warning: Invalid disable prompt caching flag value, skipping");
575            None
576        }
577    } else {
578        params.disable_prompt_caching
579    };
580
581    // Determine disable experimental betas flag value
582    let final_claude_code_disable_experimental_betas = if params.interactive {
583        if params.claude_code_disable_experimental_betas.is_some() {
584            eprintln!(
585                "Warning: Disable experimental betas flag provided via flags will be ignored in interactive mode"
586            );
587        }
588        let flag_input = read_input(
589            "Enter disable experimental betas flag (optional, press enter to skip, enter 0 to clear): ",
590        )?;
591        if flag_input.is_empty() {
592            None
593        } else if let Ok(flag) = flag_input.parse::<u32>() {
594            if flag == 0 { None } else { Some(flag) }
595        } else {
596            eprintln!("Warning: Invalid disable experimental betas flag value, skipping");
597            None
598        }
599    } else {
600        params.claude_code_disable_experimental_betas
601    };
602
603    // Determine disable auto-updater flag value
604    let final_disable_autoupdater = if params.interactive {
605        if params.disable_autoupdater.is_some() {
606            eprintln!(
607                "Warning: Disable auto-updater flag provided via flags will be ignored in interactive mode"
608            );
609        }
610        let flag_input = read_input(
611            "Enter disable auto-updater flag (optional, press enter to skip, enter 0 to clear): ",
612        )?;
613        if flag_input.is_empty() {
614            None
615        } else if let Ok(flag) = flag_input.parse::<u32>() {
616            if flag == 0 { None } else { Some(flag) }
617        } else {
618            eprintln!("Warning: Invalid disable auto-updater flag value, skipping");
619            None
620        }
621    } else {
622        params.disable_autoupdater
623    };
624
625    // Validate token format with flexible API provider support (only for AUTH_TOKEN)
626    if final_api_key.is_none() {
627        let is_anthropic_official = final_url.contains("api.anthropic.com");
628        if is_anthropic_official {
629            if !final_token.starts_with("sk-ant-api03-") {
630                eprintln!(
631                    "Warning: For official Anthropic API (api.anthropic.com), token should start with 'sk-ant-api03-'"
632                );
633            }
634        } else {
635            // For non-official APIs, provide general guidance
636            if final_token.starts_with("sk-ant-api03-") {
637                eprintln!(
638                    "Warning: Using official Claude token format with non-official API endpoint"
639                );
640            }
641        }
642    }
643
644    // Create and add configuration
645    let config = Configuration {
646        alias_name: params.alias_name.clone(),
647        token: final_token,
648        api_key: final_api_key,
649        url: final_url,
650        model: final_model,
651        small_fast_model: final_small_fast_model,
652        max_thinking_tokens: final_max_thinking_tokens,
653        api_timeout_ms: final_api_timeout_ms,
654        claude_code_disable_nonessential_traffic: final_claude_code_disable_nonessential_traffic,
655        anthropic_default_sonnet_model: final_anthropic_default_sonnet_model,
656        anthropic_default_opus_model: final_anthropic_default_opus_model,
657        anthropic_default_haiku_model: final_anthropic_default_haiku_model,
658        claude_code_subagent_model: final_claude_code_subagent_model,
659        claude_code_disable_nonstreaming_fallback: final_claude_code_disable_nonstreaming_fallback,
660        claude_code_effort_level: final_claude_code_effort_level,
661        disable_prompt_caching: final_disable_prompt_caching,
662        claude_code_disable_experimental_betas: final_claude_code_disable_experimental_betas,
663        disable_autoupdater: final_disable_autoupdater,
664        claude_code_experimental_agent_teams: None,
665        claude_code_disable_1m_context: None,
666    };
667
668    storage.add_configuration(config);
669    storage.save()?;
670
671    println!("Configuration '{}' added successfully", params.alias_name);
672    if params.force {
673        println!("(Overwrote existing configuration)");
674    }
675
676    Ok(())
677}
678
679/// Main entry point for the CLI application
680///
681/// Parses command-line arguments and executes the appropriate action:
682/// - Switch configuration with `-c` flag
683/// - Execute subcommands (add, remove, list)
684/// - Show help if no arguments provided
685///
686/// # Errors
687/// Returns error if any operation fails (file I/O, parsing, etc.)
688pub fn run() -> Result<()> {
689    let cli = Cli::parse();
690
691    // Handle --migrate flag: migrate old path to new path and exit
692    if cli.migrate {
693        ConfigStorage::migrate_from_old_path()?;
694        return Ok(());
695    }
696
697    // Handle --list-aliases flag for completion
698    if cli.list_aliases {
699        list_aliases_for_completion()?;
700        return Ok(());
701    }
702
703    // Handle --list-codex-aliases flag for completion
704    if cli.list_codex_aliases {
705        list_codex_aliases_for_completion()?;
706        return Ok(());
707    }
708    // Handle --list-omp-aliases flag for completion
709    if cli.list_omp_aliases {
710        list_omp_aliases_for_completion()?;
711        return Ok(());
712    }
713
714    // Reap per-PID alias files for terminated sessions on every invocation.
715    // Skipped for completion-only paths above to keep shell completion fast.
716    let _ = ClaudeSettings::cleanup_orphan_alias_files();
717
718    // Handle --store flag: set default storage mode and exit
719    if let Some(ref store_str) = cli.store
720        && cli.command.is_none()
721    {
722        // No command provided, so --store is a setter
723        let mode = match parse_storage_mode(store_str) {
724            Ok(mode) => mode,
725            Err(e) => {
726                eprintln!("Error: {}", e);
727                std::process::exit(1);
728            }
729        };
730
731        let mut storage = ConfigStorage::load()?;
732        storage.default_storage_mode = Some(mode.clone());
733        storage.save()?;
734
735        let mode_str = match mode {
736            StorageMode::Env => "env",
737            StorageMode::Config => "config",
738        };
739
740        println!("Default storage mode set to: {}", mode_str);
741        return Ok(());
742    }
743
744    // Handle subcommands
745    if let Some(command) = cli.command {
746        let mut storage = ConfigStorage::load()?;
747
748        match command {
749            Commands::Add {
750                alias_name,
751                token,
752                api_key,
753                url,
754                model,
755                small_fast_model,
756                max_thinking_tokens,
757                api_timeout_ms,
758                claude_code_disable_nonessential_traffic,
759                anthropic_default_sonnet_model,
760                anthropic_default_opus_model,
761                anthropic_default_haiku_model,
762                claude_code_subagent_model,
763                claude_code_disable_nonstreaming_fallback,
764                claude_code_effort_level,
765                disable_prompt_caching,
766                claude_code_disable_experimental_betas,
767                disable_autoupdater,
768                force,
769                interactive,
770                token_arg,
771                url_arg,
772                from_file,
773            } => {
774                let resolved_from_file: Option<String> = match from_file {
775                    Some(Some(path)) => {
776                        if !std::path::Path::new(&path).exists() {
777                            anyhow::bail!("Config file not found: {}", path);
778                        }
779                        Some(path)
780                    }
781                    Some(None) => {
782                        let custom_dir = storage.get_claude_settings_dir().map(|s| s.as_str());
783                        let default_path = crate::utils::get_claude_settings_path(custom_dir)
784                            .map(|p| p.to_string_lossy().into_owned())
785                            .map_err(|e| {
786                                anyhow!("Failed to resolve default Claude settings path: {}", e)
787                            })?;
788                        if !std::path::Path::new(&default_path).exists() {
789                            anyhow::bail!(
790                                "Default Claude config not found at: {}\n\
791                                 Run `claude` once to create it, or pass an explicit path: --from-file <path>",
792                                default_path
793                            );
794                        }
795                        Some(default_path)
796                    }
797                    None => None,
798                };
799
800                let params = AddCommandParams {
801                    alias_name,
802                    token,
803                    api_key,
804                    url,
805                    model,
806                    small_fast_model,
807                    max_thinking_tokens,
808                    api_timeout_ms,
809                    claude_code_disable_nonessential_traffic,
810                    anthropic_default_sonnet_model,
811                    anthropic_default_opus_model,
812                    anthropic_default_haiku_model,
813                    claude_code_subagent_model,
814                    claude_code_disable_nonstreaming_fallback,
815                    claude_code_effort_level,
816                    disable_prompt_caching,
817                    claude_code_disable_experimental_betas,
818                    disable_autoupdater,
819                    force,
820                    interactive,
821                    token_arg,
822                    url_arg,
823                    from_file: resolved_from_file,
824                };
825                handle_add_command(params, &mut storage)?;
826            }
827            Commands::Remove { alias_names } => {
828                let mut removed_count = 0;
829                let mut not_found_aliases = Vec::new();
830
831                for alias_name in &alias_names {
832                    if storage.remove_configuration(alias_name) {
833                        removed_count += 1;
834                        println!("Configuration '{alias_name}' removed successfully");
835                    } else {
836                        not_found_aliases.push(alias_name.clone());
837                        println!("Configuration '{alias_name}' not found");
838                    }
839                }
840
841                if removed_count > 0 {
842                    storage.save()?;
843                }
844
845                if !not_found_aliases.is_empty() {
846                    eprintln!(
847                        "Warning: The following configurations were not found: {}",
848                        not_found_aliases.join(", ")
849                    );
850                }
851
852                if removed_count > 0 {
853                    println!("Successfully removed {removed_count} configuration(s)");
854                }
855            }
856            Commands::List { plain, name } => {
857                if name {
858                    if storage.configurations.is_empty() {
859                        println!("No configurations stored");
860                    } else {
861                        for (alias_name, config) in &storage.configurations {
862                            println!("{}: {}", alias_name, config.url);
863                        }
864                    }
865                } else if plain {
866                    // Text output when -p flag is used
867                    if storage.configurations.is_empty() {
868                        println!("No configurations stored");
869                    } else {
870                        println!("Stored configurations:");
871                        for (alias_name, config) in &storage.configurations {
872                            let (auth_label, auth_value) = config.auth_env_pair();
873                            let mut info =
874                                format!("{}={}, url={}", auth_label, auth_value, config.url);
875                            if let Some(model) = &config.model {
876                                info.push_str(&format!(", model={model}"));
877                            }
878                            if let Some(small_fast_model) = &config.small_fast_model {
879                                info.push_str(&format!(", small_fast_model={small_fast_model}"));
880                            }
881                            if let Some(max_thinking_tokens) = config.max_thinking_tokens {
882                                info.push_str(&format!(
883                                    ", max_thinking_tokens={max_thinking_tokens}"
884                                ));
885                            }
886                            if let Some(subagent_model) = &config.claude_code_subagent_model {
887                                info.push_str(&format!(", subagent_model={subagent_model}"));
888                            }
889                            if let Some(flag) = config.claude_code_disable_nonstreaming_fallback {
890                                info.push_str(&format!(", disable_nonstreaming_fallback={flag}"));
891                            }
892                            if let Some(effort_level) = &config.claude_code_effort_level {
893                                info.push_str(&format!(", effort_level={effort_level}"));
894                            }
895                            if let Some(flag) = config.disable_prompt_caching {
896                                info.push_str(&format!(", disable_prompt_caching={flag}"));
897                            }
898                            if let Some(flag) = config.claude_code_disable_experimental_betas {
899                                info.push_str(&format!(", disable_experimental_betas={flag}"));
900                            }
901                            if let Some(flag) = config.disable_autoupdater {
902                                info.push_str(&format!(", disable_autoupdater={flag}"));
903                            }
904                            println!("  {alias_name}: {info}");
905                        }
906                    }
907                } else {
908                    // JSON output (default)
909                    println!(
910                        "{}",
911                        serde_json::to_string_pretty(&storage.configurations)
912                            .map_err(|e| anyhow!("Failed to serialize configurations: {}", e))?
913                    );
914                }
915            }
916            Commands::Completion { shell } => {
917                generate_completion(&shell)?;
918            }
919            Commands::Use {
920                alias_name,
921                resume,
922                r#continue,
923                prompt,
924            } => {
925                // Handle special reset aliases
926                if alias_name == "cc" || alias_name == "official" {
927                    use colored::Colorize;
928                    println!("{}", "Using official Claude configuration".blue());
929
930                    let mut settings = ClaudeSettings::load(
931                        storage.get_claude_settings_dir().map(|s| s.as_str()),
932                    )?;
933                    settings.remove_anthropic_env();
934                    settings.save(storage.get_claude_settings_dir().map(|s| s.as_str()))?;
935
936                    let env = EnvironmentConfig::empty().with_alias("official");
937                    launch_claude_with_env(env, None, None, r#continue)?;
938                    return Ok(());
939                }
940
941                let config = storage
942                    .configurations
943                    .get(&alias_name)
944                    .ok_or_else(|| anyhow!("Configuration '{}' not found", alias_name))?
945                    .clone();
946
947                let env_config = EnvironmentConfig::from_config(&config).with_alias(&alias_name);
948                let storage_mode = storage.default_storage_mode.clone().unwrap_or_default();
949
950                // Update settings.json with the configuration
951                let mut settings =
952                    ClaudeSettings::load(storage.get_claude_settings_dir().map(|s| s.as_str()))?;
953                settings.switch_to_config_with_mode(
954                    &config,
955                    storage_mode,
956                    storage.get_claude_settings_dir().map(|s| s.as_str()),
957                )?;
958
959                println!("Switched to configuration '{}'", alias_name);
960                println!("  URL:   {}", config.url);
961                let (auth_label, auth_value) = config.auth_env_pair();
962                println!(
963                    "  {}: {}",
964                    auth_label,
965                    crate::cli::display_utils::format_token_for_display(auth_value)
966                );
967
968                let prompt_str = if prompt.is_empty() {
969                    None
970                } else {
971                    Some(prompt.join(" "))
972                };
973
974                launch_claude_with_env(
975                    env_config,
976                    prompt_str.as_deref(),
977                    resume.as_deref(),
978                    r#continue,
979                )?;
980            }
981            Commands::Codex { command } => match command {
982                Some(crate::cli::CodexCommands::Add {
983                    alias_name,
984                    api_key,
985                    force,
986                    interactive,
987                    from_file,
988                }) => {
989                    let resolved_from_file: Option<String> = match from_file {
990                        Some(Some(path)) => {
991                            if !std::path::Path::new(&path).exists() {
992                                anyhow::bail!("Codex auth file not found: {}", path);
993                            }
994                            Some(path)
995                        }
996                        Some(None) => {
997                            let default_path = crate::codex::default_codex_auth_path()
998                                .map(|p| p.to_string_lossy().into_owned())
999                                .map_err(|e| {
1000                                    anyhow!("Failed to resolve default Codex auth path: {}", e)
1001                                })?;
1002                            if !std::path::Path::new(&default_path).exists() {
1003                                anyhow::bail!(
1004                                    "Default Codex auth file not found at: {}\n\
1005                                     Run `codex login` first, or pass an explicit path: --from-file <path>",
1006                                    default_path
1007                                );
1008                            }
1009                            Some(default_path)
1010                        }
1011                        None => None,
1012                    };
1013
1014                    handle_codex_add(
1015                        alias_name,
1016                        api_key,
1017                        force,
1018                        interactive,
1019                        resolved_from_file,
1020                        &mut storage,
1021                    )?;
1022                }
1023                Some(crate::cli::CodexCommands::List { plain, name }) => {
1024                    handle_codex_list(plain, name, &storage)?;
1025                }
1026                Some(crate::cli::CodexCommands::Use {
1027                    alias_name,
1028                    r#continue,
1029                    resume,
1030                    prompt,
1031                }) => {
1032                    handle_codex_use(alias_name, r#continue, resume, prompt, &mut storage)?;
1033                }
1034                Some(crate::cli::CodexCommands::Remove { alias_names }) => {
1035                    handle_codex_remove(alias_names, &mut storage)?;
1036                }
1037                None => {
1038                    // Enter interactive mode for Codex configurations
1039                    handle_codex_interactive(&storage)?;
1040                }
1041            },
1042            Commands::Omp { command } => match command {
1043                Some(crate::cli::OmpCommands::Add {
1044                    alias_name,
1045                    api_key,
1046                    force,
1047                    interactive,
1048                    from_file,
1049                    base_url,
1050                    slow_model,
1051                    smol_model,
1052                    plan_model,
1053                }) => {
1054                    let resolved_from_file: Option<String> = match from_file {
1055                        Some(Some(path)) => {
1056                            if !std::path::Path::new(&path).exists() {
1057                                anyhow::bail!("OMP env file not found: {}", path);
1058                            }
1059                            Some(path)
1060                        }
1061                        Some(None) => {
1062                            let default_path = crate::omp::default_omp_env_path()
1063                                .map(|p| p.to_string_lossy().into_owned())
1064                                .map_err(|e| {
1065                                    anyhow!("Failed to resolve default OMP env path: {}", e)
1066                                })?;
1067                            if !std::path::Path::new(&default_path).exists() {
1068                                anyhow::bail!(
1069                                    "Default OMP env file not found at: {}\n\
1070                                     Run `omp` once to create it, or pass an explicit path: --from-file <path>",
1071                                    default_path
1072                                );
1073                            }
1074                            Some(default_path)
1075                        }
1076                        None => None,
1077                    };
1078
1079                    handle_omp_add(
1080                        alias_name,
1081                        api_key,
1082                        force,
1083                        interactive,
1084                        resolved_from_file,
1085                        base_url,
1086                        slow_model,
1087                        smol_model,
1088                        plan_model,
1089                        &mut storage,
1090                    )?;
1091                }
1092                Some(crate::cli::OmpCommands::List { plain, name }) => {
1093                    handle_omp_list(plain, name, &storage)?;
1094                }
1095                Some(crate::cli::OmpCommands::Use {
1096                    alias_name,
1097                    r#continue,
1098                    resume,
1099                    prompt,
1100                }) => {
1101                    handle_omp_use(alias_name, r#continue, resume, prompt, &mut storage)?;
1102                }
1103                Some(crate::cli::OmpCommands::Remove { alias_names }) => {
1104                    handle_omp_remove(alias_names, &mut storage)?;
1105                }
1106                None => {
1107                    // Enter interactive mode for OMP configurations
1108                    handle_omp_interactive(&storage)?;
1109                }
1110            },
1111            Commands::Statusline { action } => {
1112                let custom_dir = storage.get_claude_settings_dir().map(|s| s.as_str());
1113                match action {
1114                    crate::cli::StatuslineAction::Install => {
1115                        crate::statusline::install(custom_dir)?;
1116                    }
1117                    crate::cli::StatuslineAction::Uninstall => {
1118                        crate::statusline::uninstall(custom_dir)?;
1119                    }
1120                }
1121            }
1122        }
1123    } else {
1124        // No command provided, show interactive configuration selection
1125        let storage = ConfigStorage::load()?;
1126        handle_interactive_selection(&storage)?;
1127    }
1128
1129    Ok(())
1130}