vtcode-config 0.142.1

Config loader components shared across VT Code and downstream adopters
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
use std::collections::BTreeMap;
use std::path::PathBuf;

use serde::{Deserialize, Serialize};

fn default_auth_timeout_ms() -> u64 {
    5_000
}

fn default_auth_refresh_interval_ms() -> u64 {
    300_000
}

fn skip_serializing_custom_provider_api_format(api_format: &CustomProviderApiFormat) -> bool {
    api_format.is_auto()
}

/// Typed API format used by custom providers.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
pub enum CustomProviderApiFormat {
    #[default]
    #[serde(rename = "auto")]
    Auto,
    #[serde(rename = "openai-chat")]
    OpenAIChat,
    #[serde(rename = "openai-responses")]
    OpenAIResponses,
    #[serde(rename = "anthropic-messages")]
    AnthropicMessages,
}

impl CustomProviderApiFormat {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::OpenAIChat => "openai-chat",
            Self::OpenAIResponses => "openai-responses",
            Self::AnthropicMessages => "anthropic-messages",
        }
    }

    pub const fn is_auto(self) -> bool {
        matches!(self, Self::Auto)
    }

    pub const fn resolved(self) -> Option<Self> {
        match self {
            Self::Auto => None,
            other => Some(other),
        }
    }
}

/// Sparse per-provider or per-model capability/profile settings.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct CustomProviderProfileConfig {
    /// Typed API format for this provider/profile.
    #[serde(default, skip_serializing_if = "skip_serializing_custom_provider_api_format")]
    pub api_format: CustomProviderApiFormat,

    /// Optional context window size in tokens.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context_window: Option<usize>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_tools: Option<bool>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_reasoning: Option<bool>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_reasoning_effort: Option<bool>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_vision: Option<bool>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_structured_output: Option<bool>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_parallel_tool_calls: Option<bool>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_context_caching: Option<bool>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_responses_compaction: Option<bool>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_context_edits: Option<bool>,
}

impl CustomProviderProfileConfig {
    fn validate(&self, provider_name: &str, profile_key: &str) -> Result<(), String> {
        if self.context_window == Some(0) {
            return Err(format!(
                "custom_providers[{provider_name}].profiles[{profile_key}]: `context_window` must be greater than 0"
            ));
        }

        Ok(())
    }
}

/// Resolved capability/profile settings after applying provider defaults and
/// exact model-specific overrides.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ResolvedCustomProviderProfile {
    pub api_format: Option<CustomProviderApiFormat>,
    pub context_window: Option<usize>,
    pub supports_tools: Option<bool>,
    pub supports_reasoning: Option<bool>,
    pub supports_reasoning_effort: Option<bool>,
    pub supports_vision: Option<bool>,
    pub supports_structured_output: Option<bool>,
    pub supports_parallel_tool_calls: Option<bool>,
    pub supports_context_caching: Option<bool>,
    pub supports_responses_compaction: Option<bool>,
    pub supports_context_edits: Option<bool>,
}

impl ResolvedCustomProviderProfile {
    fn from_layers(defaults: &CustomProviderProfileConfig, profile: Option<&CustomProviderProfileConfig>) -> Self {
        let fallback_profile;
        let profile = match profile {
            Some(profile) => profile,
            None => {
                fallback_profile = CustomProviderProfileConfig::default();
                &fallback_profile
            }
        };

        Self {
            api_format: profile.api_format.resolved().or(defaults.api_format.resolved()),
            context_window: profile.context_window.or(defaults.context_window),
            supports_tools: profile.supports_tools.or(defaults.supports_tools),
            supports_reasoning: profile.supports_reasoning.or(defaults.supports_reasoning),
            supports_reasoning_effort: profile.supports_reasoning_effort.or(defaults.supports_reasoning_effort),
            supports_vision: profile.supports_vision.or(defaults.supports_vision),
            supports_structured_output: profile.supports_structured_output.or(defaults.supports_structured_output),
            supports_parallel_tool_calls: profile
                .supports_parallel_tool_calls
                .or(defaults.supports_parallel_tool_calls),
            supports_context_caching: profile.supports_context_caching.or(defaults.supports_context_caching),
            supports_responses_compaction: profile
                .supports_responses_compaction
                .or(defaults.supports_responses_compaction),
            supports_context_edits: profile.supports_context_edits.or(defaults.supports_context_edits),
        }
    }
}

/// Command-backed bearer token configuration for a custom provider.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct CustomProviderCommandAuthConfig {
    /// Command to execute. Bare names are resolved via `PATH`.
    pub command: String,

    /// Optional command arguments.
    #[serde(default)]
    pub args: Vec<String>,

    /// Optional working directory for the token command.
    #[serde(default)]
    pub cwd: Option<PathBuf>,

    /// Maximum time to wait for the command to complete successfully.
    #[serde(default = "default_auth_timeout_ms")]
    pub timeout_ms: u64,

    /// Maximum age for the cached token before rerunning the command.
    #[serde(default = "default_auth_refresh_interval_ms")]
    pub refresh_interval_ms: u64,
}

impl Default for CustomProviderCommandAuthConfig {
    fn default() -> Self {
        Self {
            command: String::new(),
            args: Vec::new(),
            cwd: None,
            timeout_ms: default_auth_timeout_ms(),
            refresh_interval_ms: default_auth_refresh_interval_ms(),
        }
    }
}

impl CustomProviderCommandAuthConfig {
    fn validate(&self, provider_name: &str) -> Result<(), String> {
        if self.command.trim().is_empty() {
            return Err(format!("custom_providers[{provider_name}]: `auth.command` must not be empty"));
        }

        if self.timeout_ms == 0 {
            return Err(format!("custom_providers[{provider_name}]: `auth.timeout_ms` must be greater than 0"));
        }

        if self.refresh_interval_ms == 0 {
            return Err(format!(
                "custom_providers[{provider_name}]: `auth.refresh_interval_ms` must be greater than 0"
            ));
        }

        Ok(())
    }
}

/// Configuration for a user-defined OpenAI-compatible provider endpoint.
///
/// Allows users to define multiple named custom endpoints (e.g., corporate
/// proxies) with distinct display names, so they can toggle between them
/// and clearly see which endpoint is active.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct CustomProviderConfig {
    /// Stable provider key used for routing and persistence (e.g., "mycorp").
    /// Must be lowercase alphanumeric with optional hyphens/underscores.
    pub name: String,

    /// Human-friendly label shown in the TUI header, footer, and model picker
    /// (e.g., "MyCorporateName").
    pub display_name: String,

    /// Base URL of the OpenAI-compatible API endpoint
    /// (e.g., `<https://llm.corp.example/v1>`).
    pub base_url: String,

    /// Typed API format for the provider's default profile.
    #[serde(default, skip_serializing_if = "skip_serializing_custom_provider_api_format")]
    pub api_format: CustomProviderApiFormat,

    /// Optional context window size in tokens for models served by this endpoint.
    ///
    /// When omitted, the OpenAI-compatible provider uses its default context
    /// window size.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context_window: Option<usize>,

    /// Optional support for tool calling.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_tools: Option<bool>,

    /// Optional support for reasoning.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_reasoning: Option<bool>,

    /// Optional support for reasoning effort.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_reasoning_effort: Option<bool>,

    /// Optional support for vision inputs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_vision: Option<bool>,

    /// Optional support for structured output.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_structured_output: Option<bool>,

    /// Optional support for parallel tool calls.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_parallel_tool_calls: Option<bool>,

    /// Optional support for context caching.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_context_caching: Option<bool>,

    /// Optional support for responses compaction.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_responses_compaction: Option<bool>,

    /// Optional support for context edits.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_context_edits: Option<bool>,

    /// Environment variable name that holds the API key for this endpoint
    /// (e.g., "MYCORP_API_KEY").
    #[serde(default)]
    pub api_key_env: String,

    /// Optional command-backed bearer token configuration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auth: Option<CustomProviderCommandAuthConfig>,

    /// Default model to use with this endpoint (e.g., "gpt-5-mini").
    ///
    /// When [`models`](Self::models) is empty, this single model is what the
    /// `/model` picker offers for this provider. When [`models`](Self::models)
    /// is non-empty, this field is used as the default selection but the
    /// picker lists every entry in [`models`](Self::models).
    #[serde(default)]
    pub model: String,

    /// Optional list of additional model identifiers offered by the provider.
    ///
    /// Useful for OpenAI-compatible aggregators such as Atlas Cloud that
    /// expose many models behind a single endpoint. When set, the `/model`
    /// picker shows one entry per model. When empty, the picker falls back to
    /// the single [`model`](Self::model) field.
    #[serde(default)]
    pub models: Vec<String>,

    /// Exact model-keyed sparse capability profiles.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub profiles: BTreeMap<String, CustomProviderProfileConfig>,
}

impl CustomProviderConfig {
    /// Resolve the API key environment variable used for this provider.
    ///
    /// Falls back to a derived `NAME_API_KEY`-style variable when the config
    /// does not set `api_key_env`.
    pub fn resolved_api_key_env(&self) -> String {
        if !self.api_key_env.trim().is_empty() {
            return self.api_key_env.clone();
        }

        crate::api_keys::api_key_env_var(&self.name)
    }

    pub fn uses_command_auth(&self) -> bool {
        self.auth.is_some()
    }

    /// Return the list of models the `/model` picker should offer for this
    /// provider.
    ///
    /// If `models` is non-empty, every entry is returned (trimmed). Otherwise
    /// the single `model` field is returned as a one-element list. An empty
    /// `model` field with no `models` list yields an empty result.
    pub fn effective_models(&self) -> Vec<String> {
        if !self.models.is_empty() {
            return self
                .models
                .iter()
                .map(|m| m.trim().to_string())
                .filter(|m| !m.is_empty())
                .collect();
        }
        let trimmed = self.model.trim();
        if trimmed.is_empty() {
            Vec::new()
        } else {
            vec![trimmed.to_string()]
        }
    }

    pub fn profile(&self, model: &str) -> Option<&CustomProviderProfileConfig> {
        self.profiles.get(model)
    }

    pub fn resolved_profile(&self, model: &str) -> ResolvedCustomProviderProfile {
        let defaults = self.provider_defaults_profile();
        ResolvedCustomProviderProfile::from_layers(&defaults, self.profile(model))
    }

    pub fn provider_defaults_profile(&self) -> CustomProviderProfileConfig {
        CustomProviderProfileConfig {
            api_format: self.api_format,
            context_window: self.context_window,
            supports_tools: self.supports_tools,
            supports_reasoning: self.supports_reasoning,
            supports_reasoning_effort: self.supports_reasoning_effort,
            supports_vision: self.supports_vision,
            supports_structured_output: self.supports_structured_output,
            supports_parallel_tool_calls: self.supports_parallel_tool_calls,
            supports_context_caching: self.supports_context_caching,
            supports_responses_compaction: self.supports_responses_compaction,
            supports_context_edits: self.supports_context_edits,
        }
    }

    /// Validate that required fields are present and the name doesn't collide
    /// with built-in provider keys.
    pub fn validate(&self) -> Result<(), String> {
        if self.name.trim().is_empty() {
            return Err("custom_providers: `name` must not be empty".to_string());
        }

        if !is_valid_provider_name(&self.name) {
            return Err(format!(
                "custom_providers[{}]: `name` must use lowercase letters, digits, hyphens, or underscores",
                self.name
            ));
        }

        if self.display_name.trim().is_empty() {
            return Err(format!("custom_providers[{}]: `display_name` must not be empty", self.name));
        }

        if self.base_url.trim().is_empty() {
            return Err(format!("custom_providers[{}]: `base_url` must not be empty", self.name));
        }

        if self.context_window == Some(0) {
            return Err(format!("custom_providers[{}]: `context_window` must be greater than 0", self.name));
        }

        if let Some(auth) = &self.auth {
            auth.validate(&self.name)?;
            if !self.api_key_env.trim().is_empty() {
                return Err(format!("custom_providers[{}]: `auth` cannot be combined with `api_key_env`", self.name));
            }
        }

        if !self.api_key_env.trim().is_empty()
            && let Err(err) = crate::auth::CredentialIdentity::new(&self.name, &self.api_key_env)
        {
            return Err(format!("custom_providers[{}]: invalid `api_key_env`: {err}", self.name));
        }

        if self.models.iter().any(|m| m.trim().is_empty()) {
            return Err(format!("custom_providers[{}]: `models` entries must not be empty", self.name));
        }

        for (profile_key, profile) in &self.profiles {
            if profile_key.trim().is_empty() || profile_key.trim() != profile_key {
                return Err(format!(
                    "custom_providers[{}]: profile key `{profile_key}` must not be empty or contain surrounding whitespace",
                    self.name
                ));
            }

            profile.validate(&self.name, profile_key)?;
        }

        let reserved = [
            "openai",
            "anthropic",
            "gemini",
            "copilot",
            "deepseek",
            "openrouter",
            "ollama",
            "lmstudio",
            "llamacpp",
            "moonshot",
            "zai",
            "minimax",
            "huggingface",
            "openresponses",
        ];
        let lower = self.name.to_lowercase();
        if reserved.contains(&lower.as_str()) {
            return Err(format!("custom_providers[{}]: name collides with built-in provider", self.name));
        }

        Ok(())
    }
}

fn is_valid_provider_name(name: &str) -> bool {
    let bytes = name.as_bytes();
    let Some(first) = bytes.first() else {
        return false;
    };
    let Some(last) = bytes.last() else {
        return false;
    };

    let is_valid_char = |ch: u8| matches!(ch, b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_');
    let is_alphanumeric = |ch: u8| matches!(ch, b'a'..=b'z' | b'0'..=b'9');

    is_alphanumeric(*first) && is_alphanumeric(*last) && bytes.iter().copied().all(is_valid_char)
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::path::PathBuf;

    use super::{
        CustomProviderApiFormat, CustomProviderCommandAuthConfig, CustomProviderConfig, CustomProviderProfileConfig,
        ResolvedCustomProviderProfile, default_auth_refresh_interval_ms, default_auth_timeout_ms,
    };

    #[test]
    fn validate_accepts_lowercase_provider_name() {
        let config = CustomProviderConfig {
            name: "mycorp".to_string(),
            display_name: "MyCorp".to_string(),
            base_url: "https://llm.example/v1".to_string(),
            api_format: CustomProviderApiFormat::Auto,
            context_window: None,
            supports_tools: None,
            supports_reasoning: None,
            supports_reasoning_effort: None,
            supports_vision: None,
            supports_structured_output: None,
            supports_parallel_tool_calls: None,
            supports_context_caching: None,
            supports_responses_compaction: None,
            supports_context_edits: None,
            api_key_env: String::new(),
            auth: None,
            model: "gpt-5-mini".to_string(),
            models: Vec::new(),
            profiles: BTreeMap::new(),
        };

        assert!(config.validate().is_ok());
        assert_eq!(config.resolved_api_key_env(), "MYCORP_API_KEY");
    }

    #[test]
    fn validate_rejects_invalid_provider_name() {
        let config = CustomProviderConfig {
            name: "My Corp".to_string(),
            display_name: "My Corp".to_string(),
            base_url: "https://llm.example/v1".to_string(),
            api_format: CustomProviderApiFormat::Auto,
            context_window: None,
            supports_tools: None,
            supports_reasoning: None,
            supports_reasoning_effort: None,
            supports_vision: None,
            supports_structured_output: None,
            supports_parallel_tool_calls: None,
            supports_context_caching: None,
            supports_responses_compaction: None,
            supports_context_edits: None,
            api_key_env: String::new(),
            auth: None,
            model: "gpt-5-mini".to_string(),
            models: Vec::new(),
            profiles: BTreeMap::new(),
        };

        let err = config.validate().expect_err("invalid name should fail");
        assert!(err.contains("must use lowercase letters, digits, hyphens, or underscores"));
    }

    #[test]
    fn validate_rejects_auth_and_api_key_env_together() {
        let config = CustomProviderConfig {
            name: "mycorp".to_string(),
            display_name: "MyCorp".to_string(),
            base_url: "https://llm.example/v1".to_string(),
            api_format: CustomProviderApiFormat::Auto,
            context_window: None,
            supports_tools: None,
            supports_reasoning: None,
            supports_reasoning_effort: None,
            supports_vision: None,
            supports_structured_output: None,
            supports_parallel_tool_calls: None,
            supports_context_caching: None,
            supports_responses_compaction: None,
            supports_context_edits: None,
            api_key_env: "MYCORP_API_KEY".to_string(),
            auth: Some(CustomProviderCommandAuthConfig {
                command: "print-token".to_string(),
                args: Vec::new(),
                cwd: None,
                timeout_ms: default_auth_timeout_ms(),
                refresh_interval_ms: default_auth_refresh_interval_ms(),
            }),
            model: "gpt-5-mini".to_string(),
            models: Vec::new(),
            profiles: BTreeMap::new(),
        };

        let err = config.validate().expect_err("conflicting auth should fail");
        assert!(err.contains("`auth` cannot be combined with `api_key_env`"));
    }

    #[test]
    fn validate_accepts_command_auth_without_static_env_key() {
        let config = CustomProviderConfig {
            name: "mycorp".to_string(),
            display_name: "MyCorp".to_string(),
            base_url: "https://llm.example/v1".to_string(),
            api_format: CustomProviderApiFormat::Auto,
            context_window: None,
            supports_tools: None,
            supports_reasoning: None,
            supports_reasoning_effort: None,
            supports_vision: None,
            supports_structured_output: None,
            supports_parallel_tool_calls: None,
            supports_context_caching: None,
            supports_responses_compaction: None,
            supports_context_edits: None,
            api_key_env: String::new(),
            auth: Some(CustomProviderCommandAuthConfig {
                command: "print-token".to_string(),
                args: vec!["--json".to_string()],
                cwd: Some(PathBuf::from("/tmp")),
                timeout_ms: 1_000,
                refresh_interval_ms: 60_000,
            }),
            model: "gpt-5-mini".to_string(),
            models: Vec::new(),
            profiles: BTreeMap::new(),
        };

        assert!(config.validate().is_ok());
        assert!(config.uses_command_auth());
    }

    #[test]
    fn validate_rejects_empty_model_entry_in_models_list() {
        let config = CustomProviderConfig {
            name: "mycorp".to_string(),
            display_name: "MyCorp".to_string(),
            base_url: "https://llm.example/v1".to_string(),
            api_format: CustomProviderApiFormat::Auto,
            context_window: None,
            supports_tools: None,
            supports_reasoning: None,
            supports_reasoning_effort: None,
            supports_vision: None,
            supports_structured_output: None,
            supports_parallel_tool_calls: None,
            supports_context_caching: None,
            supports_responses_compaction: None,
            supports_context_edits: None,
            api_key_env: "MYCORP_API_KEY".to_string(),
            auth: None,
            model: "gpt-5-mini".to_string(),
            models: vec!["valid-model".to_string(), "   ".to_string()],
            profiles: BTreeMap::new(),
        };

        let err = config.validate().expect_err("blank models entry should fail");
        assert!(err.contains("`models` entries must not be empty"));
    }

    #[test]
    fn validate_rejects_zero_context_window() {
        let config = CustomProviderConfig {
            name: "mycorp".to_string(),
            display_name: "MyCorp".to_string(),
            base_url: "https://llm.example/v1".to_string(),
            api_format: CustomProviderApiFormat::Auto,
            context_window: Some(0),
            supports_tools: None,
            supports_reasoning: None,
            supports_reasoning_effort: None,
            supports_vision: None,
            supports_structured_output: None,
            supports_parallel_tool_calls: None,
            supports_context_caching: None,
            supports_responses_compaction: None,
            supports_context_edits: None,
            api_key_env: String::new(),
            auth: None,
            model: "gpt-5-mini".to_string(),
            models: Vec::new(),
            profiles: BTreeMap::new(),
        };

        let err = config.validate().expect_err("zero context window should fail");
        assert!(err.contains("`context_window` must be greater than 0"));
    }

    #[test]
    fn validate_rejects_malformed_profile_key() {
        let mut profiles = BTreeMap::new();
        profiles.insert(
            " gpt-5-mini ".to_string(),
            CustomProviderProfileConfig {
                api_format: CustomProviderApiFormat::Auto,
                context_window: Some(128_000),
                supports_tools: None,
                supports_reasoning: None,
                supports_reasoning_effort: None,
                supports_vision: None,
                supports_structured_output: None,
                supports_parallel_tool_calls: None,
                supports_context_caching: None,
                supports_responses_compaction: None,
                supports_context_edits: None,
            },
        );

        let config = CustomProviderConfig {
            name: "mycorp".to_string(),
            display_name: "MyCorp".to_string(),
            base_url: "https://llm.example/v1".to_string(),
            api_format: CustomProviderApiFormat::Auto,
            context_window: None,
            supports_tools: None,
            supports_reasoning: None,
            supports_reasoning_effort: None,
            supports_vision: None,
            supports_structured_output: None,
            supports_parallel_tool_calls: None,
            supports_context_caching: None,
            supports_responses_compaction: None,
            supports_context_edits: None,
            api_key_env: String::new(),
            auth: None,
            model: "gpt-5-mini".to_string(),
            models: Vec::new(),
            profiles,
        };

        let err = config.validate().expect_err("profile key with whitespace should fail");
        assert!(err.contains("profile key"));
    }

    #[test]
    fn effective_models_uses_models_list_when_present() {
        let config = CustomProviderConfig {
            name: "atlascloud".to_string(),
            display_name: "Atlas Cloud".to_string(),
            base_url: "https://api.atlascloud.ai/v1".to_string(),
            api_format: CustomProviderApiFormat::Auto,
            context_window: None,
            supports_tools: None,
            supports_reasoning: None,
            supports_reasoning_effort: None,
            supports_vision: None,
            supports_structured_output: None,
            supports_parallel_tool_calls: None,
            supports_context_caching: None,
            supports_responses_compaction: None,
            supports_context_edits: None,
            api_key_env: "ATLASCLOUD_API_KEY".to_string(),
            auth: None,
            model: "deepseek-ai/deepseek-v4-flash".to_string(),
            models: vec![
                "deepseek-ai/deepseek-v4-flash".to_string(),
                "deepseek-ai/deepseek-v4-pro".to_string(),
                "deepseek-ai/DeepSeek-V3-0324".to_string(),
                "qwen/qwen3.6-35b-a3b".to_string(),
                "moonshotai/kimi-k2.7-code".to_string(),
                "moonshotai/kimi-k2.6".to_string(),
                "zai-org/glm-5.2".to_string(),
                "minimaxai/minimax-m3".to_string(),
            ],
            profiles: BTreeMap::new(),
        };

        assert_eq!(
            config.effective_models(),
            vec![
                "deepseek-ai/deepseek-v4-flash".to_string(),
                "deepseek-ai/deepseek-v4-pro".to_string(),
                "deepseek-ai/DeepSeek-V3-0324".to_string(),
                "qwen/qwen3.6-35b-a3b".to_string(),
                "moonshotai/kimi-k2.7-code".to_string(),
                "moonshotai/kimi-k2.6".to_string(),
                "zai-org/glm-5.2".to_string(),
                "minimaxai/minimax-m3".to_string(),
            ]
        );
    }

    #[test]
    fn effective_models_falls_back_to_single_model_field() {
        let config = CustomProviderConfig {
            model: "gpt-5-mini".to_string(),
            ..CustomProviderConfig::default()
        };

        assert_eq!(config.effective_models(), vec!["gpt-5-mini".to_string()]);
    }

    #[test]
    fn resolved_profile_prefers_exact_model_key() {
        let mut profiles = BTreeMap::new();
        profiles.insert(
            "gpt-5-mini".to_string(),
            CustomProviderProfileConfig {
                api_format: CustomProviderApiFormat::OpenAIResponses,
                context_window: Some(128_000),
                supports_tools: Some(true),
                supports_reasoning: None,
                supports_reasoning_effort: None,
                supports_vision: None,
                supports_structured_output: None,
                supports_parallel_tool_calls: None,
                supports_context_caching: None,
                supports_responses_compaction: None,
                supports_context_edits: None,
            },
        );

        let config = CustomProviderConfig {
            name: "mycorp".to_string(),
            display_name: "MyCorp".to_string(),
            base_url: "https://llm.example/v1".to_string(),
            api_format: CustomProviderApiFormat::OpenAIChat,
            context_window: Some(256_000),
            supports_tools: Some(true),
            supports_reasoning: Some(true),
            supports_reasoning_effort: None,
            supports_vision: None,
            supports_structured_output: None,
            supports_parallel_tool_calls: None,
            supports_context_caching: None,
            supports_responses_compaction: None,
            supports_context_edits: None,
            api_key_env: String::new(),
            auth: None,
            model: "gpt-5-mini".to_string(),
            models: Vec::new(),
            profiles,
        };

        let resolved = config.resolved_profile("gpt-5-mini");
        assert_eq!(
            resolved,
            ResolvedCustomProviderProfile {
                api_format: Some(CustomProviderApiFormat::OpenAIResponses),
                context_window: Some(128_000),
                supports_tools: Some(true),
                supports_reasoning: Some(true),
                supports_reasoning_effort: None,
                supports_vision: None,
                supports_structured_output: None,
                supports_parallel_tool_calls: None,
                supports_context_caching: None,
                supports_responses_compaction: None,
                supports_context_edits: None,
            }
        );
        assert!(config.profile("gpt-5").is_none());
    }

    #[test]
    fn sparse_inheritance_preserves_provider_defaults() {
        let mut profiles = BTreeMap::new();
        profiles.insert(
            "gpt-5-mini".to_string(),
            CustomProviderProfileConfig {
                api_format: CustomProviderApiFormat::Auto,
                context_window: None,
                supports_tools: Some(false),
                supports_reasoning: None,
                supports_reasoning_effort: Some(true),
                supports_vision: None,
                supports_structured_output: None,
                supports_parallel_tool_calls: None,
                supports_context_caching: None,
                supports_responses_compaction: None,
                supports_context_edits: None,
            },
        );

        let config = CustomProviderConfig {
            name: "mycorp".to_string(),
            display_name: "MyCorp".to_string(),
            base_url: "https://llm.example/v1".to_string(),
            api_format: CustomProviderApiFormat::OpenAIChat,
            context_window: Some(256_000),
            supports_tools: Some(true),
            supports_reasoning: Some(false),
            supports_reasoning_effort: None,
            supports_vision: Some(true),
            supports_structured_output: None,
            supports_parallel_tool_calls: Some(true),
            supports_context_caching: Some(false),
            supports_responses_compaction: None,
            supports_context_edits: None,
            api_key_env: String::new(),
            auth: None,
            model: "gpt-5-mini".to_string(),
            models: Vec::new(),
            profiles,
        };

        let resolved = config.resolved_profile("gpt-5-mini");
        assert_eq!(resolved.api_format, Some(CustomProviderApiFormat::OpenAIChat));
        assert_eq!(resolved.context_window, Some(256_000));
        assert_eq!(resolved.supports_tools, Some(false));
        assert_eq!(resolved.supports_reasoning, Some(false));
        assert_eq!(resolved.supports_reasoning_effort, Some(true));
        assert_eq!(resolved.supports_vision, Some(true));
        assert_eq!(resolved.supports_parallel_tool_calls, Some(true));
        assert_eq!(resolved.supports_context_caching, Some(false));
        assert_eq!(resolved.supports_responses_compaction, None);
        assert_eq!(resolved.supports_context_edits, None);
    }

    #[test]
    fn legacy_default_behavior_retains_auto_and_empty_profiles() {
        let parsed: CustomProviderConfig = toml::from_str(
            r#"
name = "mycorp"
display_name = "MyCorp"
base_url = "https://llm.example/v1"
model = "gpt-5-mini"
"#,
        )
        .expect("legacy custom provider config should parse");

        assert_eq!(parsed.api_format, CustomProviderApiFormat::Auto);
        assert!(parsed.profiles.is_empty());
        assert_eq!(parsed.resolved_profile("gpt-5-mini"), ResolvedCustomProviderProfile::default());
    }

    #[test]
    fn deserialize_rejects_invalid_api_format() {
        let err = toml::from_str::<CustomProviderConfig>(
            r#"
name = "mycorp"
display_name = "MyCorp"
base_url = "https://llm.example/v1"
api_format = "openai-chatty"
"#,
        )
        .expect_err("invalid api_format should fail");

        assert!(err.to_string().contains("openai-chatty"));
    }
}