cc-switch 0.1.8

A CLI tool for managing multiple Claude API configurations and automatically switching between them
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
use crate::cli::completion::{generate_completion, list_aliases_for_completion};
use crate::cli::{Cli, Commands};
use crate::config::types::{AddCommandParams, ClaudeSettings, StorageMode};
use crate::config::{ConfigStorage, Configuration, EnvironmentConfig, validate_alias_name};
use crate::interactive::{
    handle_interactive_selection, launch_claude_with_env, read_input, read_sensitive_input,
};
use anyhow::{Result, anyhow};
use clap::Parser;
use std::fs;
use std::path::Path;

/// Parse storage mode string to StorageMode enum
///
/// # Arguments
/// * `store_str` - String representation of storage mode ("env" or "config")
///
/// # Returns
/// Result containing StorageMode or error if invalid
fn parse_storage_mode(store_str: &str) -> Result<StorageMode> {
    match store_str.to_lowercase().as_str() {
        "env" => Ok(StorageMode::Env),
        "config" => Ok(StorageMode::Config),
        _ => Err(anyhow!(
            "Invalid storage mode '{}'. Use 'env' or 'config'",
            store_str
        )),
    }
}

/// Parse a configuration from a JSON file
///
/// # Arguments
/// * `file_path` - Path to the JSON configuration file
///
/// # Returns
/// Result containing a tuple of (alias_name, token, url, model, small_fast_model, max_thinking_tokens, api_timeout_ms, claude_code_disable_nonessential_traffic, anthropic_default_sonnet_model, anthropic_default_opus_model, anthropic_default_haiku_model)
///
/// # Errors
/// Returns error if file cannot be read or parsed
#[allow(clippy::type_complexity)]
fn parse_config_from_file(
    file_path: &str,
) -> Result<(
    String,
    String,
    String,
    Option<String>,
    Option<String>,
    Option<u32>,
    Option<u32>,
    Option<u32>,
    Option<String>,
    Option<String>,
    Option<String>,
)> {
    // Read the file
    let file_content = fs::read_to_string(file_path)
        .map_err(|e| anyhow!("Failed to read file '{}': {}", file_path, e))?;

    // Parse JSON
    let json: serde_json::Value = serde_json::from_str(&file_content)
        .map_err(|e| anyhow!("Failed to parse JSON from file '{}': {}", file_path, e))?;

    // Extract env section
    let env = json.get("env").and_then(|v| v.as_object()).ok_or_else(|| {
        anyhow!(
            "File '{}' does not contain a valid 'env' section",
            file_path
        )
    })?;

    // Extract alias name from filename (without extension)
    let path = Path::new(file_path);
    let alias_name = path
        .file_stem()
        .and_then(|s| s.to_str())
        .ok_or_else(|| anyhow!("Invalid file path: {}", file_path))?
        .to_string();

    // Extract and map environment variables
    let token = env
        .get("ANTHROPIC_AUTH_TOKEN")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow!("Missing ANTHROPIC_AUTH_TOKEN in file '{}'", file_path))?
        .to_string();

    let url = env
        .get("ANTHROPIC_BASE_URL")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow!("Missing ANTHROPIC_BASE_URL in file '{}'", file_path))?
        .to_string();

    let model = env
        .get("ANTHROPIC_MODEL")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let small_fast_model = env
        .get("ANTHROPIC_SMALL_FAST_MODEL")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let max_thinking_tokens = env
        .get("ANTHROPIC_MAX_THINKING_TOKENS")
        .and_then(|v| v.as_u64())
        .map(|u| u as u32);

    let api_timeout_ms = env
        .get("API_TIMEOUT_MS")
        .and_then(|v| v.as_u64())
        .map(|u| u as u32);

    let claude_code_disable_nonessential_traffic = env
        .get("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC")
        .and_then(|v| v.as_u64())
        .map(|u| u as u32);

    let anthropic_default_sonnet_model = env
        .get("ANTHROPIC_DEFAULT_SONNET_MODEL")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let anthropic_default_opus_model = env
        .get("ANTHROPIC_DEFAULT_OPUS_MODEL")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let anthropic_default_haiku_model = env
        .get("ANTHROPIC_DEFAULT_HAIKU_MODEL")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    Ok((
        alias_name,
        token,
        url,
        model,
        small_fast_model,
        max_thinking_tokens,
        api_timeout_ms,
        claude_code_disable_nonessential_traffic,
        anthropic_default_sonnet_model,
        anthropic_default_opus_model,
        anthropic_default_haiku_model,
    ))
}

/// Handle adding a configuration with all the new features
///
/// # Arguments
/// * `params` - Parameters for the add command
/// * `storage` - Mutable reference to config storage
///
/// # Errors
/// Returns error if validation fails or user cancels interactive input
fn handle_add_command(mut params: AddCommandParams, storage: &mut ConfigStorage) -> Result<()> {
    // If from-file is provided, parse the file and use those values
    if let Some(file_path) = &params.from_file {
        println!("Importing configuration from file: {}", file_path);

        let (
            file_alias_name,
            file_token,
            file_url,
            file_model,
            file_small_fast_model,
            file_max_thinking_tokens,
            file_api_timeout_ms,
            file_claude_disable_nonessential_traffic,
            file_sonnet_model,
            file_opus_model,
            file_haiku_model,
        ) = parse_config_from_file(file_path)?;

        // Use the file's alias name (ignoring the one provided via command line)
        params.alias_name = file_alias_name;

        // Override params with file values
        params.token = Some(file_token);
        params.url = Some(file_url);
        params.model = file_model;
        params.small_fast_model = file_small_fast_model;
        params.max_thinking_tokens = file_max_thinking_tokens;
        params.api_timeout_ms = file_api_timeout_ms;
        params.claude_code_disable_nonessential_traffic = file_claude_disable_nonessential_traffic;
        params.anthropic_default_sonnet_model = file_sonnet_model;
        params.anthropic_default_opus_model = file_opus_model;
        params.anthropic_default_haiku_model = file_haiku_model;

        println!(
            "Configuration '{}' will be imported from file",
            params.alias_name
        );
    }

    // Validate alias name
    validate_alias_name(&params.alias_name)?;

    // Check if alias already exists
    if storage.get_configuration(&params.alias_name).is_some() && !params.force {
        eprintln!("Configuration '{}' already exists.", params.alias_name);
        eprintln!("Use --force to overwrite or choose a different alias name.");
        return Ok(());
    }

    // Cannot use interactive mode with --from-file
    if params.interactive && params.from_file.is_some() {
        anyhow::bail!("Cannot use --interactive mode with --from-file");
    }

    // Determine token value
    let final_token = if params.interactive {
        if params.token.is_some() || params.token_arg.is_some() {
            eprintln!(
                "Warning: Token provided via flags/arguments will be ignored in interactive mode"
            );
        }
        read_sensitive_input("Enter API token (sk-ant-xxx): ")?
    } else {
        match (&params.token, &params.token_arg) {
            (Some(t), _) => t.clone(),
            (None, Some(t)) => t.clone(),
            (None, None) => {
                anyhow::bail!(
                    "Token is required. Use -t flag, provide as argument, or use interactive mode with -i"
                );
            }
        }
    };

    // Determine URL value
    let final_url = if params.interactive {
        if params.url.is_some() || params.url_arg.is_some() {
            eprintln!(
                "Warning: URL provided via flags/arguments will be ignored in interactive mode"
            );
        }
        read_input("Enter API URL (default: https://api.anthropic.com): ")?
    } else {
        match (&params.url, &params.url_arg) {
            (Some(u), _) => u.clone(),
            (None, Some(u)) => u.clone(),
            (None, None) => "https://api.anthropic.com".to_string(),
        }
    };

    // Use default URL if empty
    let final_url = if final_url.is_empty() {
        "https://api.anthropic.com".to_string()
    } else {
        final_url
    };

    // Determine model value
    let final_model = if params.interactive {
        if params.model.is_some() {
            eprintln!("Warning: Model provided via flags will be ignored in interactive mode");
        }
        let model_input = read_input("Enter model name (optional, press enter to skip): ")?;
        if model_input.is_empty() {
            None
        } else {
            Some(model_input)
        }
    } else {
        params.model
    };

    // Determine small fast model value
    let final_small_fast_model = if params.interactive {
        if params.small_fast_model.is_some() {
            eprintln!(
                "Warning: Small fast model provided via flags will be ignored in interactive mode"
            );
        }
        let small_model_input =
            read_input("Enter small fast model name (optional, press enter to skip): ")?;
        if small_model_input.is_empty() {
            None
        } else {
            Some(small_model_input)
        }
    } else {
        params.small_fast_model
    };

    // Determine max thinking tokens value
    let final_max_thinking_tokens = if params.interactive {
        if params.max_thinking_tokens.is_some() {
            eprintln!(
                "Warning: Max thinking tokens provided via flags will be ignored in interactive mode"
            );
        }
        let tokens_input = read_input(
            "Enter maximum thinking tokens (optional, press enter to skip, enter 0 to clear): ",
        )?;
        if tokens_input.is_empty() {
            None
        } else if let Ok(tokens) = tokens_input.parse::<u32>() {
            if tokens == 0 { None } else { Some(tokens) }
        } else {
            eprintln!("Warning: Invalid max thinking tokens value, skipping");
            None
        }
    } else {
        params.max_thinking_tokens
    };

    // Determine API timeout value
    let final_api_timeout_ms = if params.interactive {
        if params.api_timeout_ms.is_some() {
            eprintln!(
                "Warning: API timeout provided via flags will be ignored in interactive mode"
            );
        }
        let timeout_input = read_input(
            "Enter API timeout in milliseconds (optional, press enter to skip, enter 0 to clear): ",
        )?;
        if timeout_input.is_empty() {
            None
        } else if let Ok(timeout) = timeout_input.parse::<u32>() {
            if timeout == 0 { None } else { Some(timeout) }
        } else {
            eprintln!("Warning: Invalid API timeout value, skipping");
            None
        }
    } else {
        params.api_timeout_ms
    };

    // Determine disable nonessential traffic flag value
    let final_claude_code_disable_nonessential_traffic = if params.interactive {
        if params.claude_code_disable_nonessential_traffic.is_some() {
            eprintln!(
                "Warning: Disable nonessential traffic flag provided via flags will be ignored in interactive mode"
            );
        }
        let flag_input = read_input(
            "Enter disable nonessential traffic flag (optional, press enter to skip, enter 0 to clear): ",
        )?;
        if flag_input.is_empty() {
            None
        } else if let Ok(flag) = flag_input.parse::<u32>() {
            if flag == 0 { None } else { Some(flag) }
        } else {
            eprintln!("Warning: Invalid disable nonessential traffic flag value, skipping");
            None
        }
    } else {
        params.claude_code_disable_nonessential_traffic
    };

    // Determine default Sonnet model value
    let final_anthropic_default_sonnet_model = if params.interactive {
        if params.anthropic_default_sonnet_model.is_some() {
            eprintln!(
                "Warning: Default Sonnet model provided via flags will be ignored in interactive mode"
            );
        }
        let model_input =
            read_input("Enter default Sonnet model name (optional, press enter to skip): ")?;
        if model_input.is_empty() {
            None
        } else {
            Some(model_input)
        }
    } else {
        params.anthropic_default_sonnet_model
    };

    // Determine default Opus model value
    let final_anthropic_default_opus_model = if params.interactive {
        if params.anthropic_default_opus_model.is_some() {
            eprintln!(
                "Warning: Default Opus model provided via flags will be ignored in interactive mode"
            );
        }
        let model_input =
            read_input("Enter default Opus model name (optional, press enter to skip): ")?;
        if model_input.is_empty() {
            None
        } else {
            Some(model_input)
        }
    } else {
        params.anthropic_default_opus_model
    };

    // Determine default Haiku model value
    let final_anthropic_default_haiku_model = if params.interactive {
        if params.anthropic_default_haiku_model.is_some() {
            eprintln!(
                "Warning: Default Haiku model provided via flags will be ignored in interactive mode"
            );
        }
        let model_input =
            read_input("Enter default Haiku model name (optional, press enter to skip): ")?;
        if model_input.is_empty() {
            None
        } else {
            Some(model_input)
        }
    } else {
        params.anthropic_default_haiku_model
    };

    // Validate token format with flexible API provider support
    let is_anthropic_official = final_url.contains("api.anthropic.com");
    if is_anthropic_official {
        if !final_token.starts_with("sk-ant-api03-") {
            eprintln!(
                "Warning: For official Anthropic API (api.anthropic.com), token should start with 'sk-ant-api03-'"
            );
        }
    } else {
        // For non-official APIs, provide general guidance
        if final_token.starts_with("sk-ant-api03-") {
            eprintln!("Warning: Using official Claude token format with non-official API endpoint");
        }
        // Don't validate format for third-party APIs as they may use different formats
    }

    // Create and add configuration
    let config = Configuration {
        alias_name: params.alias_name.clone(),
        token: final_token,
        url: final_url,
        model: final_model,
        small_fast_model: final_small_fast_model,
        max_thinking_tokens: final_max_thinking_tokens,
        api_timeout_ms: final_api_timeout_ms,
        claude_code_disable_nonessential_traffic: final_claude_code_disable_nonessential_traffic,
        anthropic_default_sonnet_model: final_anthropic_default_sonnet_model,
        anthropic_default_opus_model: final_anthropic_default_opus_model,
        anthropic_default_haiku_model: final_anthropic_default_haiku_model,
        claude_code_experimental_agent_teams: None,
        claude_code_disable_1m_context: None,
    };

    storage.add_configuration(config);
    storage.save()?;

    println!("Configuration '{}' added successfully", params.alias_name);
    if params.force {
        println!("(Overwrote existing configuration)");
    }

    Ok(())
}

/// Main entry point for the CLI application
///
/// Parses command-line arguments and executes the appropriate action:
/// - Switch configuration with `-c` flag
/// - Execute subcommands (add, remove, list)
/// - Show help if no arguments provided
///
/// # Errors
/// Returns error if any operation fails (file I/O, parsing, etc.)
pub fn run() -> Result<()> {
    let cli = Cli::parse();

    // Handle --migrate flag: migrate old path to new path and exit
    if cli.migrate {
        ConfigStorage::migrate_from_old_path()?;
        return Ok(());
    }

    // Handle --list-aliases flag for completion
    if cli.list_aliases {
        list_aliases_for_completion()?;
        return Ok(());
    }

    // Handle --store flag: set default storage mode and exit
    if let Some(ref store_str) = cli.store
        && cli.command.is_none()
    {
        // No command provided, so --store is a setter
        let mode = match parse_storage_mode(store_str) {
            Ok(mode) => mode,
            Err(e) => {
                eprintln!("Error: {}", e);
                std::process::exit(1);
            }
        };

        let mut storage = ConfigStorage::load()?;
        storage.default_storage_mode = Some(mode.clone());
        storage.save()?;

        let mode_str = match mode {
            StorageMode::Env => "env",
            StorageMode::Config => "config",
        };

        println!("Default storage mode set to: {}", mode_str);
        return Ok(());
    }

    // Handle subcommands
    if let Some(command) = cli.command {
        let mut storage = ConfigStorage::load()?;

        match command {
            Commands::Add {
                alias_name,
                token,
                url,
                model,
                small_fast_model,
                max_thinking_tokens,
                api_timeout_ms,
                claude_code_disable_nonessential_traffic,
                anthropic_default_sonnet_model,
                anthropic_default_opus_model,
                anthropic_default_haiku_model,
                force,
                interactive,
                token_arg,
                url_arg,
                from_file,
            } => {
                // When from_file is provided, alias_name will be extracted from the file
                // For other cases, use the provided alias_name or provide a default
                let final_alias_name = if from_file.is_some() {
                    // Will be set from file parsing, use a placeholder for now
                    "placeholder".to_string()
                } else {
                    alias_name.unwrap_or_else(|| {
                        eprintln!("Error: alias_name is required when not using --from-file");
                        std::process::exit(1);
                    })
                };

                let params = AddCommandParams {
                    alias_name: final_alias_name,
                    token,
                    url,
                    model,
                    small_fast_model,
                    max_thinking_tokens,
                    api_timeout_ms,
                    claude_code_disable_nonessential_traffic,
                    anthropic_default_sonnet_model,
                    anthropic_default_opus_model,
                    anthropic_default_haiku_model,
                    force,
                    interactive,
                    token_arg,
                    url_arg,
                    from_file,
                };
                handle_add_command(params, &mut storage)?;
            }
            Commands::Remove { alias_names } => {
                let mut removed_count = 0;
                let mut not_found_aliases = Vec::new();

                for alias_name in &alias_names {
                    if storage.remove_configuration(alias_name) {
                        removed_count += 1;
                        println!("Configuration '{alias_name}' removed successfully");
                    } else {
                        not_found_aliases.push(alias_name.clone());
                        println!("Configuration '{alias_name}' not found");
                    }
                }

                if removed_count > 0 {
                    storage.save()?;
                }

                if !not_found_aliases.is_empty() {
                    eprintln!(
                        "Warning: The following configurations were not found: {}",
                        not_found_aliases.join(", ")
                    );
                }

                if removed_count > 0 {
                    println!("Successfully removed {removed_count} configuration(s)");
                }
            }
            Commands::List { plain } => {
                if plain {
                    // Text output when -p flag is used
                    if storage.configurations.is_empty() {
                        println!("No configurations stored");
                    } else {
                        println!("Stored configurations:");
                        for (alias_name, config) in &storage.configurations {
                            let mut info = format!("token={}, url={}", config.token, config.url);
                            if let Some(model) = &config.model {
                                info.push_str(&format!(", model={model}"));
                            }
                            if let Some(small_fast_model) = &config.small_fast_model {
                                info.push_str(&format!(", small_fast_model={small_fast_model}"));
                            }
                            if let Some(max_thinking_tokens) = config.max_thinking_tokens {
                                info.push_str(&format!(
                                    ", max_thinking_tokens={max_thinking_tokens}"
                                ));
                            }
                            println!("  {alias_name}: {info}");
                        }
                    }
                } else {
                    // JSON output (default)
                    println!(
                        "{}",
                        serde_json::to_string_pretty(&storage.configurations)
                            .map_err(|e| anyhow!("Failed to serialize configurations: {}", e))?
                    );
                }
            }
            Commands::Completion { shell } => {
                generate_completion(&shell)?;
            }
            Commands::Use {
                alias_name,
                resume,
                r#continue,
                prompt,
            } => {
                // Handle special reset aliases
                if alias_name == "cc" || alias_name == "official" {
                    println!("Using official Claude configuration");

                    let mut settings =
                        ClaudeSettings::load(storage.get_claude_settings_dir().map(|s| s.as_str()))?;
                    settings.remove_anthropic_env();
                    settings.save(storage.get_claude_settings_dir().map(|s| s.as_str()))?;

                    launch_claude_with_env(
                        EnvironmentConfig::empty(),
                        None,
                        None,
                        r#continue,
                    )?;
                    return Ok(());
                }

                let config = storage
                    .configurations
                    .get(&alias_name)
                    .ok_or_else(|| anyhow!("Configuration '{}' not found", alias_name))?
                    .clone();

                let env_config = EnvironmentConfig::from_config(&config);
                let storage_mode = storage.default_storage_mode.clone().unwrap_or_default();

                // Update settings.json with the configuration
                let mut settings =
                    ClaudeSettings::load(storage.get_claude_settings_dir().map(|s| s.as_str()))?;
                settings.switch_to_config_with_mode(
                    &config,
                    storage_mode,
                    storage.get_claude_settings_dir().map(|s| s.as_str()),
                )?;

                println!("Switched to configuration '{}'", alias_name);
                println!("  URL:   {}", config.url);
                println!(
                    "  Token: {}",
                    crate::cli::display_utils::format_token_for_display(&config.token)
                );

                let prompt_str = if prompt.is_empty() {
                    None
                } else {
                    Some(prompt.join(" "))
                };

                launch_claude_with_env(
                    env_config,
                    prompt_str.as_deref(),
                    resume.as_deref(),
                    r#continue,
                )?;
            }
        }
    } else {
        // No command provided, show interactive configuration selection
        let storage = ConfigStorage::load()?;
        handle_interactive_selection(&storage)?;
    }

    Ok(())
}