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
use anyhow::{Context, Result};
use std::collections::BTreeMap;
use std::fs;

use crate::config::types::{ClaudeSettings, Configuration, StorageMode};
use crate::utils::get_claude_settings_path;

/// Remove trailing commas from JSON content to make it more lenient
///
/// Handles trailing commas before `}` and `]` characters, which are common
/// in hand-edited JSON files but not valid in standard JSON.
fn strip_trailing_commas(json: &str) -> String {
    // Simple approach: remove commas that appear before closing braces/brackets
    // This handles the most common case of trailing commas
    let mut result = String::with_capacity(json.len());
    let chars: Vec<char> = json.chars().collect();
    let mut i = 0;

    while i < chars.len() {
        let c = chars[i];

        // Check if this is a comma followed by optional whitespace and then } or ]
        if c == ',' {
            // Look ahead to see if the next non-whitespace char is } or ]
            let mut j = i + 1;
            while j < chars.len() && chars[j].is_whitespace() {
                j += 1;
            }

            if j < chars.len() && (chars[j] == '}' || chars[j] == ']') {
                // Skip this trailing comma
                i += 1;
                continue;
            }
        }

        result.push(c);
        i += 1;
    }

    result
}

impl ClaudeSettings {
    /// Load Claude settings from disk
    ///
    /// Reads the JSON file from the configured Claude settings directory
    /// Returns default empty settings if file doesn't exist
    /// Creates the file with default structure if it doesn't exist
    ///
    /// # Arguments
    /// * `custom_dir` - Optional custom directory for Claude settings
    ///
    /// # Errors
    /// Returns error if file exists but cannot be read or parsed
    pub fn load(custom_dir: Option<&str>) -> Result<Self> {
        let path = get_claude_settings_path(custom_dir)?;

        if !path.exists() {
            // Create default settings file if it doesn't exist
            let default_settings = ClaudeSettings::default();
            default_settings.save(custom_dir)?;
            return Ok(default_settings);
        }

        let content = fs::read_to_string(&path)
            .with_context(|| format!("Failed to read Claude settings from {}", path.display()))?;

        // Parse with better error handling for missing env field
        let mut settings: ClaudeSettings = if content.trim().is_empty() {
            ClaudeSettings::default()
        } else {
            // Strip trailing commas to handle lenient JSON
            let cleaned_content = strip_trailing_commas(&content);

            // Try to parse the cleaned content first
            match serde_json::from_str(&cleaned_content) {
                Ok(s) => s,
                Err(e) => {
                    // Provide helpful error message with the actual parse error
                    let error_msg = format!(
                        "Failed to parse Claude settings JSON at {}:\n  {}\n\n\
                         This usually means the JSON file has invalid syntax.\n\
                         Common issues:\n\
                         - Trailing commas (e.g., {{\"key\": \"value\",}})\n\
                         - Missing quotes around keys or values\n\
                         - Unescaped special characters in strings\n\n\
                         Please fix the JSON syntax in the file.",
                        path.display(),
                        e
                    );
                    return Err(anyhow::anyhow!("{}", error_msg));
                }
            }
        };

        // Ensure env field exists (handle case where it might be missing from JSON)
        if settings.env.is_empty() && !content.contains("\"env\"") {
            settings.env = BTreeMap::new();
        }

        Ok(settings)
    }

    /// Save Claude settings to disk
    ///
    /// Writes the current state to the configured Claude settings directory
    /// Creates the directory structure if it doesn't exist
    /// Ensures the env field is properly serialized
    ///
    /// # Arguments
    /// * `custom_dir` - Optional custom directory for Claude settings
    ///
    /// # Errors
    /// Returns error if directory cannot be created or file cannot be written
    pub fn save(&self, custom_dir: Option<&str>) -> Result<()> {
        let path = get_claude_settings_path(custom_dir)?;

        // Create directory if it doesn't exist
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)
                .with_context(|| format!("Failed to create directory {}", parent.display()))?;
        }

        // The custom Serialize implementation handles env field inclusion automatically
        let settings_to_save = self;

        let json = serde_json::to_string_pretty(&settings_to_save)
            .with_context(|| "Failed to serialize Claude settings")?;

        fs::write(&path, json).with_context(|| format!("Failed to write to {}", path.display()))?;

        Ok(())
    }

    /// Switch to a specific API configuration
    ///
    /// Updates the environment variables with the provided configuration
    /// Ensures env field exists before updating
    ///
    /// # Arguments
    /// * `config` - Configuration containing token, URL, and optional model settings to apply
    pub fn switch_to_config(&mut self, config: &Configuration) {
        // Ensure env field exists
        if self.env.is_empty() {
            self.env = BTreeMap::new();
        }

        // Remove all Anthropic environment variables to ensure clean state
        let env_fields = Configuration::get_env_field_names();
        for field in &env_fields {
            self.env.remove(*field);
        }

        // Set required environment variables
        self.env
            .insert("ANTHROPIC_AUTH_TOKEN".to_string(), config.token.clone());
        self.env
            .insert("ANTHROPIC_BASE_URL".to_string(), config.url.clone());

        // Set model configurations only if provided (don't set empty values)
        if let Some(model) = &config.model
            && !model.is_empty()
        {
            self.env
                .insert("ANTHROPIC_MODEL".to_string(), model.clone());
        }

        if let Some(small_fast_model) = &config.small_fast_model
            && !small_fast_model.is_empty()
        {
            self.env.insert(
                "ANTHROPIC_SMALL_FAST_MODEL".to_string(),
                small_fast_model.clone(),
            );
        }

        // Set additional configuration values that should not be removed
        if let Some(max_thinking_tokens) = config.max_thinking_tokens {
            self.env.insert(
                "ANTHROPIC_MAX_THINKING_TOKENS".to_string(),
                max_thinking_tokens.to_string(),
            );
        }

        if let Some(timeout) = config.api_timeout_ms {
            self.env
                .insert("API_TIMEOUT_MS".to_string(), timeout.to_string());
        }

        if let Some(flag) = config.claude_code_disable_nonessential_traffic {
            self.env.insert(
                "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC".to_string(),
                flag.to_string(),
            );
        }

        if let Some(model) = &config.anthropic_default_sonnet_model
            && !model.is_empty()
        {
            self.env
                .insert("ANTHROPIC_DEFAULT_SONNET_MODEL".to_string(), model.clone());
        }

        if let Some(model) = &config.anthropic_default_opus_model
            && !model.is_empty()
        {
            self.env
                .insert("ANTHROPIC_DEFAULT_OPUS_MODEL".to_string(), model.clone());
        }

        if let Some(model) = &config.anthropic_default_haiku_model
            && !model.is_empty()
        {
            self.env
                .insert("ANTHROPIC_DEFAULT_HAIKU_MODEL".to_string(), model.clone());
        }
    }

    /// Remove Anthropic environment variables
    ///
    /// Clears all Anthropic-related environment variables from settings
    /// Used to reset to default Claude behavior
    pub fn remove_anthropic_env(&mut self) {
        // Ensure env field exists
        if self.env.is_empty() {
            self.env = BTreeMap::new();
        }

        // Remove all environment variables that can be set by configurations
        let env_fields = Configuration::get_env_field_names();
        for field in &env_fields {
            self.env.remove(*field);
        }
    }

    /// Switch to a specific API configuration with specified storage mode
    ///
    /// Updates the settings.json file based on the storage mode:
    /// - Env mode: Launch Claude with environment variables (cleans settings.json)
    /// - Config mode: Write to env field in settings.json (settings file persistence)
    ///
    /// # Arguments
    /// * `config` - Configuration containing token, URL, and optional model settings to apply
    /// * `mode` - Storage mode to use (Env or Config)
    /// * `custom_dir` - Optional custom directory for Claude settings
    ///
    /// # Errors
    /// Returns error if settings cannot be saved
    pub fn switch_to_config_with_mode(
        &mut self,
        config: &Configuration,
        mode: StorageMode,
        custom_dir: Option<&str>,
    ) -> Result<()> {
        match mode {
            StorageMode::Env => {
                // Env mode: Check for conflicts with existing configurable fields
                // Automatically remove them from settings.json if found
                // Note: User preference fields are preserved (not cleared)

                // Get environment variable names that should be cleared
                // This excludes user preference fields like DISABLE_NONESSENTIAL_TRAFFIC
                let clearable_env_fields = Configuration::get_clearable_env_field_names();

                let mut removed_fields = Vec::new();

                // Check and remove Anthropic variables from env field
                for field in &clearable_env_fields {
                    if self.env.remove(*field).is_some() {
                        removed_fields.push(field.to_string());
                    }
                }

                // If fields were removed, report what was cleaned and save
                if !removed_fields.is_empty() {
                    eprintln!("🧹 Cleaning settings.json for env mode:");
                    eprintln!("   Removed configurable fields:");
                    for field in &removed_fields {
                        eprintln!("   - {}", field);
                    }
                    eprintln!();
                    eprintln!(
                        "   Settings.json cleaned. Environment variables will be used instead."
                    );

                    // Save the cleaned settings
                    self.save(custom_dir)?;
                }

                // Env mode: Environment variables will be set directly when launching Claude
            }
            StorageMode::Config => {
                // Config mode: Write Anthropic settings to env field with UPPERCASE names
                // Check for conflicts with system environment variables (not settings.json)
                // settings.json env field is managed by this tool, so it's expected to have values

                // Get all environment variable names that can be set by configurations
                let anthropic_env_fields = Configuration::get_env_field_names();

                let mut conflicts = Vec::new();

                // Check system environment variables for Anthropic variables
                // This is the real conflict - user may have set these in their shell
                for field in &anthropic_env_fields {
                    if std::env::var(field).is_ok() {
                        conflicts.push(format!("system env: {}", field));
                    }
                }

                // If conflicts found, report error and exit
                if !conflicts.is_empty() {
                    eprintln!("❌ Conflict detected in config mode:");
                    eprintln!("   Found existing Anthropic configuration in system environment:");
                    for conflict in &conflicts {
                        eprintln!("   - {}", conflict);
                    }
                    eprintln!();
                    eprintln!(
                        "   Config mode cannot work when Anthropic environment variables are set in system env."
                    );
                    eprintln!("   Please:");
                    eprintln!("   1. Unset system environment variables, or");
                    eprintln!("   2. Use 'env' mode instead");
                    return Err(anyhow::anyhow!(
                        "Config mode conflict: Anthropic environment variables exist in system env"
                    ));
                }

                // Apply the new configuration to env field (overwrite existing values)
                self.switch_to_config(config);

                // Add the additional fields that switch_to_config doesn't handle
                if let Some(max_thinking_tokens) = config.max_thinking_tokens {
                    self.env.insert(
                        "ANTHROPIC_MAX_THINKING_TOKENS".to_string(),
                        max_thinking_tokens.to_string(),
                    );
                }

                if let Some(timeout) = config.api_timeout_ms {
                    self.env
                        .insert("API_TIMEOUT_MS".to_string(), timeout.to_string());
                }

                if let Some(flag) = config.claude_code_disable_nonessential_traffic {
                    self.env.insert(
                        "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC".to_string(),
                        flag.to_string(),
                    );
                }

                if let Some(model) = &config.anthropic_default_sonnet_model
                    && !model.is_empty()
                {
                    self.env
                        .insert("ANTHROPIC_DEFAULT_SONNET_MODEL".to_string(), model.clone());
                }

                if let Some(model) = &config.anthropic_default_opus_model
                    && !model.is_empty()
                {
                    self.env
                        .insert("ANTHROPIC_DEFAULT_OPUS_MODEL".to_string(), model.clone());
                }

                if let Some(model) = &config.anthropic_default_haiku_model
                    && !model.is_empty()
                {
                    self.env
                        .insert("ANTHROPIC_DEFAULT_HAIKU_MODEL".to_string(), model.clone());
                }

                self.save(custom_dir)?;
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_strip_trailing_commas_simple() {
        let input = r#"{"a": 1,}"#;
        let expected = r#"{"a": 1}"#;
        assert_eq!(strip_trailing_commas(input), expected);
    }

    #[test]
    fn test_strip_trailing_commas_nested_object() {
        let input = r#"{"env": {"KEY": "value",},}"#;
        let expected = r#"{"env": {"KEY": "value"}}"#;
        assert_eq!(strip_trailing_commas(input), expected);
    }

    #[test]
    fn test_strip_trailing_commas_array() {
        let input = r#"{"items": [1, 2, 3,],}"#;
        let expected = r#"{"items": [1, 2, 3]}"#;
        assert_eq!(strip_trailing_commas(input), expected);
    }

    #[test]
    fn test_strip_trailing_commas_multiline() {
        let input = r#"{
  "env": {
    "KEY": "value",
  },
}"#;
        let expected = r#"{
  "env": {
    "KEY": "value"
  }
}"#;
        assert_eq!(strip_trailing_commas(input), expected);
    }

    #[test]
    fn test_strip_trailing_commas_no_trailing() {
        let input = r#"{"a": 1, "b": 2}"#;
        assert_eq!(strip_trailing_commas(input), input);
    }

    #[test]
    fn test_strip_trailing_commas_complex() {
        let input = r#"{
  "env": {
    "ANTHROPIC_AUTH_TOKEN": "token",
    "ANTHROPIC_BASE_URL": "https://api.example.com",
  },
  "model": "claude-3-opus",
}"#;
        let expected = r#"{
  "env": {
    "ANTHROPIC_AUTH_TOKEN": "token",
    "ANTHROPIC_BASE_URL": "https://api.example.com"
  },
  "model": "claude-3-opus"
}"#;
        assert_eq!(strip_trailing_commas(input), expected);
    }

    #[test]
    fn test_strip_trailing_commas_preserves_inner_commas() {
        let input = r#"{"a": 1, "b": 2, "c": 3,}"#;
        let expected = r#"{"a": 1, "b": 2, "c": 3}"#;
        assert_eq!(strip_trailing_commas(input), expected);
    }
}