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