Skip to main content

codex_helper_core/
config.rs

1use std::collections::{BTreeMap, BTreeSet, HashMap};
2use std::env;
3use std::fs as stdfs;
4use std::path::{Path, PathBuf};
5
6use crate::client_config::{codex_home, is_claude_absent_backup_sentinel};
7use anyhow::{Context, Result};
8use serde::{Deserialize, Serialize};
9use serde_json::Value as JsonValue;
10use tokio::fs;
11use toml::Value as TomlValue;
12use tracing::{info, warn};
13
14pub use crate::client_config::{
15    claude_settings_backup_path, claude_settings_path, codex_auth_path, codex_config_path,
16    codex_models_cache_path, codex_switch_state_path,
17};
18
19#[path = "config_storage.rs"]
20mod storage_impl;
21
22#[path = "config_bootstrap.rs"]
23mod bootstrap_impl;
24
25#[path = "config_auth_sync.rs"]
26mod auth_sync_impl;
27
28#[path = "config_retry.rs"]
29mod retry_impl;
30
31#[path = "config_profiles.rs"]
32mod profiles_impl;
33
34#[path = "config_routing.rs"]
35mod routing_impl;
36
37#[path = "config_v2.rs"]
38mod v2_impl;
39
40#[path = "config_v4.rs"]
41mod v4_impl;
42
43pub use auth_sync_impl::{
44    SyncCodexAuthFromCodexOptions, SyncCodexAuthFromCodexReport, sync_codex_auth_from_codex_cli,
45};
46pub(crate) use auth_sync_impl::{infer_env_key_from_auth_json, read_file_if_exists};
47pub use bootstrap_impl::{
48    import_codex_config_from_codex_cli, load_or_bootstrap_for_service,
49    load_or_bootstrap_for_service_with_v4_source, load_or_bootstrap_from_claude,
50    load_or_bootstrap_from_codex, overwrite_codex_config_from_codex_cli_in_place,
51    probe_codex_bootstrap_from_cli,
52};
53pub(crate) use profiles_impl::validate_service_profiles;
54pub use profiles_impl::{
55    ServiceControlProfile, resolve_service_profile, resolve_service_profile_from_catalog,
56    validate_profile_station_compatibility,
57};
58pub use retry_impl::{
59    ResolvedRetryConfig, ResolvedRetryLayerConfig, RetryConfig, RetryLayerConfig, RetryProfileName,
60    RetryStrategy,
61};
62pub use routing_impl::{RoutingCandidate, ServiceRoutingExplanation, explain_service_routing};
63pub use storage_impl::{
64    CodexClientPatchConfig, LoadedProxyConfig, codex_client_patch_config_from_config_file,
65    codex_client_patch_mode_from_config_file, codex_client_patch_preset_from_config_file,
66    config_file_path, init_config_toml, load_config, load_config_with_v4_source,
67    normalize_config_toml_authoring, normalize_config_toml_client_patch, save_config,
68    save_config_v2, save_config_v4,
69};
70pub use v2_impl::{
71    build_persisted_provider_catalog, build_persisted_station_catalog, compact_v2_config,
72    compile_v2_to_runtime, migrate_legacy_to_v2,
73};
74pub(crate) use v4_impl::compact_v4_config_for_write;
75pub use v4_impl::{
76    ConfigV4MigrationReport, collect_route_graph_affinity_migration_warnings,
77    compile_v4_to_runtime, compile_v4_to_v2, effective_v4_routing, migrate_legacy_to_v4,
78    migrate_legacy_to_v4_with_report, migrate_v2_to_v4, migrate_v2_to_v4_with_report,
79    resolved_v4_provider_order,
80};
81
82pub mod legacy {
83    pub use super::v4_impl::legacy::*;
84}
85
86#[cfg(test)]
87use bootstrap_impl::bootstrap_from_codex;
88
89pub mod storage {
90    pub use super::storage_impl::{
91        CodexClientPatchConfig, LoadedProxyConfig, codex_client_patch_config_from_config_file,
92        codex_client_patch_mode_from_config_file, codex_client_patch_preset_from_config_file,
93        config_file_path, init_config_toml, load_config, load_config_with_v4_source,
94        normalize_config_toml_authoring, normalize_config_toml_client_patch, save_config,
95        save_config_v2, save_config_v4,
96    };
97}
98
99pub mod bootstrap {
100    pub use super::bootstrap_impl::{
101        import_codex_config_from_codex_cli, load_or_bootstrap_for_service,
102        load_or_bootstrap_from_claude, load_or_bootstrap_from_codex,
103        overwrite_codex_config_from_codex_cli_in_place, probe_codex_bootstrap_from_cli,
104    };
105}
106
107pub mod auth_sync {
108    pub use super::auth_sync_impl::{
109        SyncCodexAuthFromCodexOptions, SyncCodexAuthFromCodexReport, sync_codex_auth_from_codex_cli,
110    };
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize, Default)]
114pub struct UpstreamAuth {
115    /// Bearer token, e.g. OpenAI style
116    #[serde(skip_serializing_if = "Option::is_none")]
117    pub auth_token: Option<String>,
118    /// Environment variable name for bearer token (preferred over storing secrets on disk)
119    #[serde(skip_serializing_if = "Option::is_none")]
120    pub auth_token_env: Option<String>,
121    /// Optional API key header for some providers
122    #[serde(skip_serializing_if = "Option::is_none")]
123    pub api_key: Option<String>,
124    /// Environment variable name for API key header value
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub api_key_env: Option<String>,
127}
128
129impl UpstreamAuth {
130    pub fn resolve_auth_token(&self) -> Option<String> {
131        if let Some(token) = self.auth_token.as_deref()
132            && !token.trim().is_empty()
133        {
134            return Some(token.to_string());
135        }
136        if let Some(env_name) = self.auth_token_env.as_deref()
137            && let Ok(v) = env::var(env_name)
138            && !v.trim().is_empty()
139        {
140            return Some(v);
141        }
142        None
143    }
144
145    pub fn resolve_api_key(&self) -> Option<String> {
146        if let Some(key) = self.api_key.as_deref()
147            && !key.trim().is_empty()
148        {
149            return Some(key.to_string());
150        }
151        if let Some(env_name) = self.api_key_env.as_deref()
152            && let Ok(v) = env::var(env_name)
153            && !v.trim().is_empty()
154        {
155            return Some(v);
156        }
157        None
158    }
159}
160
161#[derive(Debug, Clone, Serialize, Deserialize)]
162pub struct UpstreamConfig {
163    pub base_url: String,
164    #[serde(default)]
165    pub auth: UpstreamAuth,
166    /// Optional free-form metadata, e.g. region / label
167    #[serde(default)]
168    pub tags: HashMap<String, String>,
169    /// Optional model whitelist for this upstream (exact or wildcard patterns like `gpt-*`).
170    #[serde(
171        default,
172        skip_serializing_if = "HashMap::is_empty",
173        alias = "supportedModels"
174    )]
175    pub supported_models: HashMap<String, bool>,
176    /// Optional model mapping: external model name -> upstream-specific model name (supports wildcards).
177    #[serde(
178        default,
179        skip_serializing_if = "HashMap::is_empty",
180        alias = "modelMapping"
181    )]
182    pub model_mapping: HashMap<String, String>,
183}
184
185pub fn model_routing_warnings(cfg: &ProxyConfig, service_name: &str) -> Vec<String> {
186    use crate::model_routing::match_wildcard;
187
188    fn validate_upstream(name: &str, upstream: &UpstreamConfig) -> Vec<String> {
189        let mut out = Vec::new();
190
191        if upstream.supported_models.is_empty() && upstream.model_mapping.is_empty() {
192            out.push(format!(
193                "[{name}] 未配置 supported_models 或 model_mapping,将假设支持所有模型(可能导致降级失败)"
194            ));
195            return out;
196        }
197
198        if !upstream.model_mapping.is_empty() && upstream.supported_models.is_empty() {
199            out.push(format!(
200                "[{name}] 配置了 model_mapping 但未配置 supported_models,映射目标将不做校验,请确认目标模型在供应商处可用"
201            ));
202        }
203
204        if upstream.model_mapping.is_empty() || upstream.supported_models.is_empty() {
205            return out;
206        }
207
208        for (external_model, internal_model) in upstream.model_mapping.iter() {
209            if internal_model.contains('*') {
210                continue;
211            }
212            let supported = if upstream
213                .supported_models
214                .get(internal_model)
215                .copied()
216                .unwrap_or(false)
217            {
218                true
219            } else {
220                upstream
221                    .supported_models
222                    .keys()
223                    .any(|p| match_wildcard(p, internal_model))
224            };
225            if !supported {
226                out.push(format!(
227                    "[{name}] 模型映射无效:'{external_model}' -> '{internal_model}',目标模型不在 supported_models 中"
228                ));
229            }
230        }
231        out
232    }
233
234    let mgr = match service_name {
235        "claude" => &cfg.claude,
236        "codex" => &cfg.codex,
237        _ => &cfg.codex,
238    };
239
240    let mut warnings = Vec::new();
241    for (cfg_name, svc) in mgr.stations() {
242        for (idx, upstream) in svc.upstreams.iter().enumerate() {
243            let name = format!(
244                "{service_name}:{cfg_name} upstream[{idx}] ({})",
245                upstream.base_url
246            );
247            warnings.extend(validate_upstream(&name, upstream));
248        }
249    }
250    warnings
251}
252
253/// A logical config entry (roughly corresponds to cli_proxy 的一个配置名)
254#[derive(Debug, Clone, Serialize, Deserialize)]
255pub struct ServiceConfig {
256    /// 配置标识(map key),保持稳定
257    #[serde(default)]
258    pub name: String,
259    /// 可选别名,便于展示/记忆
260    #[serde(default)]
261    pub alias: Option<String>,
262    /// Whether this config is eligible for automatic routing (defaults to true).
263    #[serde(default = "default_service_config_enabled")]
264    pub enabled: bool,
265    /// Priority group (1..=10, lower is higher priority). Default: 1.
266    #[serde(default = "default_service_config_level")]
267    pub level: u8,
268    #[serde(default)]
269    pub upstreams: Vec<UpstreamConfig>,
270}
271
272fn default_service_config_enabled() -> bool {
273    true
274}
275
276fn is_default_service_config_enabled(value: &bool) -> bool {
277    *value == default_service_config_enabled()
278}
279
280fn default_service_config_level() -> u8 {
281    1
282}
283
284fn default_provider_endpoint_priority() -> u32 {
285    0
286}
287
288fn is_default_provider_endpoint_priority(value: &u32) -> bool {
289    *value == default_provider_endpoint_priority()
290}
291
292#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq, Hash)]
293pub struct ProviderConcurrencyLimits {
294    #[serde(default, skip_serializing_if = "Option::is_none")]
295    pub max_concurrent_requests: Option<u32>,
296    #[serde(default, skip_serializing_if = "Option::is_none")]
297    pub limit_group: Option<String>,
298}
299
300fn is_default_provider_concurrency_limits(value: &ProviderConcurrencyLimits) -> bool {
301    value == &ProviderConcurrencyLimits::default()
302}
303
304#[derive(Debug, Clone, Serialize, Deserialize, Default)]
305pub struct ServiceConfigManager {
306    /// 当前激活配置名
307    #[serde(default)]
308    pub active: Option<String>,
309    /// 新会话默认使用的控制模板名(Phase 1: 仅加载与展示,不自动绑定)。
310    #[serde(default)]
311    pub default_profile: Option<String>,
312    /// 可复用控制模板。
313    #[serde(default)]
314    pub profiles: BTreeMap<String, ServiceControlProfile>,
315    /// 站点集合。公共序列化使用 `stations`,仍兼容读取 legacy `configs`。
316    #[serde(default, rename = "stations", alias = "configs")]
317    pub configs: HashMap<String, ServiceConfig>,
318}
319
320impl ServiceConfigManager {
321    pub fn stations(&self) -> &HashMap<String, ServiceConfig> {
322        &self.configs
323    }
324
325    pub fn stations_mut(&mut self) -> &mut HashMap<String, ServiceConfig> {
326        &mut self.configs
327    }
328
329    pub fn station(&self, name: &str) -> Option<&ServiceConfig> {
330        self.stations().get(name)
331    }
332
333    pub fn station_mut(&mut self, name: &str) -> Option<&mut ServiceConfig> {
334        self.stations_mut().get_mut(name)
335    }
336
337    pub fn contains_station(&self, name: &str) -> bool {
338        self.station(name).is_some()
339    }
340
341    pub fn station_count(&self) -> usize {
342        self.stations().len()
343    }
344
345    pub fn has_stations(&self) -> bool {
346        !self.stations().is_empty()
347    }
348
349    pub fn active_station(&self) -> Option<&ServiceConfig> {
350        self.active
351            .as_ref()
352            .and_then(|name| self.station(name))
353            // HashMap 的 values().next() 是非确定性的;这里用 key 排序后的最小项作为稳定兜底。
354            .or_else(|| {
355                self.stations()
356                    .iter()
357                    .min_by_key(|(k, _)| *k)
358                    .map(|(_, v)| v)
359            })
360    }
361
362    pub fn profile(&self, name: &str) -> Option<&ServiceControlProfile> {
363        self.profiles.get(name)
364    }
365
366    pub fn default_profile_ref(&self) -> Option<(&str, &ServiceControlProfile)> {
367        let name = self.default_profile.as_deref()?;
368        self.profile(name).map(|profile| (name, profile))
369    }
370}
371
372#[derive(Debug, Clone, Serialize, Deserialize)]
373pub struct NotifyPolicyConfig {
374    /// Only notify when proxy duration_ms is >= this threshold.
375    pub min_duration_ms: u64,
376    /// At most one notification per global_cooldown_ms.
377    pub global_cooldown_ms: u64,
378    /// Events within this window will be merged into one notification.
379    pub merge_window_ms: u64,
380    /// Suppress notifications for the same thread-id within this cooldown.
381    pub per_thread_cooldown_ms: u64,
382    /// How far back to look in proxy recent-finished list when matching a thread-id.
383    pub recent_search_window_ms: u64,
384    /// Timeout for calling proxy `status/recent` endpoint.
385    pub recent_endpoint_timeout_ms: u64,
386}
387
388impl Default for NotifyPolicyConfig {
389    fn default() -> Self {
390        Self {
391            min_duration_ms: 60_000,
392            global_cooldown_ms: 60_000,
393            merge_window_ms: 10_000,
394            per_thread_cooldown_ms: 180_000,
395            recent_search_window_ms: 5 * 60_000,
396            recent_endpoint_timeout_ms: 500,
397        }
398    }
399}
400
401#[derive(Debug, Clone, Serialize, Deserialize, Default)]
402pub struct NotifySystemConfig {
403    /// Whether to show system notifications (toasts). Default: false.
404    pub enabled: bool,
405}
406
407#[derive(Debug, Clone, Serialize, Deserialize, Default)]
408pub struct NotifyExecConfig {
409    /// Enable executing an external command for each aggregated notification.
410    pub enabled: bool,
411    /// Command to execute; the aggregated JSON is written to stdin.
412    /// Example: ["python", "my_script.py"].
413    #[serde(default)]
414    pub command: Vec<String>,
415}
416
417#[derive(Debug, Clone, Serialize, Deserialize, Default)]
418pub struct NotifyConfig {
419    /// Whether notify processing is enabled at all (system toast and exec are both disabled by default).
420    pub enabled: bool,
421    #[serde(default)]
422    pub policy: NotifyPolicyConfig,
423    #[serde(default)]
424    pub system: NotifySystemConfig,
425    #[serde(default)]
426    pub exec: NotifyExecConfig,
427}
428
429fn default_usage_forecast_enabled() -> bool {
430    true
431}
432
433fn default_usage_forecast_rate_window_minutes() -> u64 {
434    60
435}
436
437fn default_usage_forecast_min_priced_requests() -> u64 {
438    2
439}
440
441fn default_usage_forecast_reset_time() -> String {
442    "00:00".to_string()
443}
444
445fn default_usage_forecast_reset_utc_offset() -> String {
446    "+08:00".to_string()
447}
448
449#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
450pub struct UsageForecastConfig {
451    /// Whether spend forecast rendering is enabled.
452    #[serde(
453        default = "default_usage_forecast_enabled",
454        skip_serializing_if = "is_default_usage_forecast_enabled"
455    )]
456    pub enabled: bool,
457    /// Rolling spend-rate window used for projection.
458    #[serde(
459        default = "default_usage_forecast_rate_window_minutes",
460        skip_serializing_if = "is_default_usage_forecast_rate_window_minutes"
461    )]
462    pub rate_window_minutes: u64,
463    /// Minimum priced requests before the forecast is treated as confident enough to show.
464    #[serde(
465        default = "default_usage_forecast_min_priced_requests",
466        skip_serializing_if = "is_default_usage_forecast_min_priced_requests"
467    )]
468    pub min_priced_requests: u64,
469    /// Daily quota reset clock time in the reset timezone, formatted as HH:MM.
470    #[serde(
471        default = "default_usage_forecast_reset_time",
472        skip_serializing_if = "is_default_usage_forecast_reset_time"
473    )]
474    pub reset_time: String,
475    /// Reset timezone as a fixed UTC offset, for example +08:00.
476    #[serde(
477        default = "default_usage_forecast_reset_utc_offset",
478        skip_serializing_if = "is_default_usage_forecast_reset_utc_offset"
479    )]
480    pub reset_utc_offset: String,
481}
482
483impl Default for UsageForecastConfig {
484    fn default() -> Self {
485        Self {
486            enabled: default_usage_forecast_enabled(),
487            rate_window_minutes: default_usage_forecast_rate_window_minutes(),
488            min_priced_requests: default_usage_forecast_min_priced_requests(),
489            reset_time: default_usage_forecast_reset_time(),
490            reset_utc_offset: default_usage_forecast_reset_utc_offset(),
491        }
492    }
493}
494
495fn is_default_usage_forecast_enabled(value: &bool) -> bool {
496    *value == default_usage_forecast_enabled()
497}
498
499fn is_default_usage_forecast_rate_window_minutes(value: &u64) -> bool {
500    *value == default_usage_forecast_rate_window_minutes()
501}
502
503fn is_default_usage_forecast_min_priced_requests(value: &u64) -> bool {
504    *value == default_usage_forecast_min_priced_requests()
505}
506
507fn is_default_usage_forecast_reset_time(value: &String) -> bool {
508    value == &default_usage_forecast_reset_time()
509}
510
511fn is_default_usage_forecast_reset_utc_offset(value: &String) -> bool {
512    value == &default_usage_forecast_reset_utc_offset()
513}
514
515fn is_default_usage_forecast_config(value: &UsageForecastConfig) -> bool {
516    value == &UsageForecastConfig::default()
517}
518
519#[derive(Debug, Clone, Serialize, Deserialize, Default)]
520pub struct ProxyConfig {
521    /// Optional config schema version for future migrations
522    #[serde(default)]
523    pub version: Option<u32>,
524    /// Codex 服务配置
525    #[serde(default)]
526    pub codex: ServiceConfigManager,
527    /// Claude Code 等其他服务配置,后续扩展
528    #[serde(default)]
529    pub claude: ServiceConfigManager,
530    /// Global retry policy (proxy-side).
531    #[serde(default)]
532    pub retry: RetryConfig,
533    /// Notify integration settings (used by `codex-helper notify ...`).
534    #[serde(default)]
535    pub notify: NotifyConfig,
536    /// 默认目标服务(用于 CLI 默认选择 codex/claude)
537    #[serde(default)]
538    pub default_service: Option<ServiceKind>,
539    /// UI settings (mainly for the built-in TUI).
540    #[serde(default)]
541    pub ui: UiConfig,
542}
543
544fn default_proxy_config_v2_version() -> u32 {
545    2
546}
547
548pub const LEGACY_ROUTE_GRAPH_CONFIG_VERSION: u32 = 4;
549pub const CURRENT_ROUTE_GRAPH_CONFIG_VERSION: u32 = 5;
550
551pub fn is_supported_route_graph_config_version(version: u32) -> bool {
552    matches!(
553        version,
554        LEGACY_ROUTE_GRAPH_CONFIG_VERSION | CURRENT_ROUTE_GRAPH_CONFIG_VERSION
555    )
556}
557
558fn default_proxy_config_v4_version() -> u32 {
559    CURRENT_ROUTE_GRAPH_CONFIG_VERSION
560}
561
562#[derive(Debug, Clone, Serialize, Deserialize)]
563pub struct ProxyConfigV2 {
564    #[serde(default = "default_proxy_config_v2_version")]
565    pub version: u32,
566    #[serde(default)]
567    pub codex: ServiceViewV2,
568    #[serde(default)]
569    pub claude: ServiceViewV2,
570    #[serde(default)]
571    pub retry: RetryConfig,
572    #[serde(default)]
573    pub notify: NotifyConfig,
574    #[serde(default)]
575    pub default_service: Option<ServiceKind>,
576    #[serde(default)]
577    pub ui: UiConfig,
578}
579
580impl Default for ProxyConfigV2 {
581    fn default() -> Self {
582        Self {
583            version: default_proxy_config_v2_version(),
584            codex: ServiceViewV2::default(),
585            claude: ServiceViewV2::default(),
586            retry: RetryConfig::default(),
587            notify: NotifyConfig::default(),
588            default_service: None,
589            ui: UiConfig::default(),
590        }
591    }
592}
593
594#[derive(Debug, Clone, Serialize, Deserialize)]
595pub struct ProxyConfigV4 {
596    #[serde(default = "default_proxy_config_v4_version")]
597    pub version: u32,
598    #[serde(default)]
599    pub codex: ServiceViewV4,
600    #[serde(default)]
601    pub claude: ServiceViewV4,
602    #[serde(default)]
603    pub retry: RetryConfig,
604    #[serde(default)]
605    pub notify: NotifyConfig,
606    #[serde(default)]
607    pub default_service: Option<ServiceKind>,
608    #[serde(default)]
609    pub ui: UiConfig,
610}
611
612impl Default for ProxyConfigV4 {
613    fn default() -> Self {
614        Self {
615            version: default_proxy_config_v4_version(),
616            codex: ServiceViewV4::default(),
617            claude: ServiceViewV4::default(),
618            retry: RetryConfig::default(),
619            notify: NotifyConfig::default(),
620            default_service: None,
621            ui: UiConfig::default(),
622        }
623    }
624}
625
626#[derive(Debug, Clone, Serialize, Deserialize, Default)]
627pub struct ServiceViewV4 {
628    #[serde(default, skip_serializing_if = "Option::is_none")]
629    pub default_profile: Option<String>,
630    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
631    pub profiles: BTreeMap<String, ServiceControlProfile>,
632    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
633    pub providers: BTreeMap<String, ProviderConfigV4>,
634    #[serde(default, skip_serializing_if = "Option::is_none")]
635    pub routing: Option<RoutingConfigV4>,
636}
637
638#[derive(Debug, Clone, Serialize, Deserialize)]
639pub struct ProviderConfigV4 {
640    #[serde(default, skip_serializing_if = "Option::is_none")]
641    pub alias: Option<String>,
642    #[serde(
643        default = "default_service_config_enabled",
644        skip_serializing_if = "is_default_service_config_enabled"
645    )]
646    pub enabled: bool,
647    #[serde(default, skip_serializing_if = "Option::is_none")]
648    pub base_url: Option<String>,
649    #[serde(default, skip_serializing_if = "Option::is_none")]
650    pub continuity_domain: Option<String>,
651    #[serde(default, skip_serializing_if = "is_default_upstream_auth")]
652    pub auth: UpstreamAuth,
653    #[serde(default, flatten)]
654    pub inline_auth: UpstreamAuth,
655    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
656    pub tags: BTreeMap<String, String>,
657    #[serde(
658        default,
659        skip_serializing_if = "BTreeMap::is_empty",
660        alias = "supportedModels"
661    )]
662    pub supported_models: BTreeMap<String, bool>,
663    #[serde(
664        default,
665        skip_serializing_if = "BTreeMap::is_empty",
666        alias = "modelMapping"
667    )]
668    pub model_mapping: BTreeMap<String, String>,
669    #[serde(
670        default,
671        skip_serializing_if = "is_default_provider_concurrency_limits"
672    )]
673    pub limits: ProviderConcurrencyLimits,
674    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
675    pub endpoints: BTreeMap<String, ProviderEndpointV4>,
676}
677
678impl Default for ProviderConfigV4 {
679    fn default() -> Self {
680        Self {
681            alias: None,
682            enabled: default_service_config_enabled(),
683            base_url: None,
684            continuity_domain: None,
685            auth: UpstreamAuth::default(),
686            inline_auth: UpstreamAuth::default(),
687            tags: BTreeMap::new(),
688            supported_models: BTreeMap::new(),
689            model_mapping: BTreeMap::new(),
690            limits: ProviderConcurrencyLimits::default(),
691            endpoints: BTreeMap::new(),
692        }
693    }
694}
695
696#[derive(Debug, Clone, Serialize, Deserialize)]
697pub struct ProviderEndpointV4 {
698    pub base_url: String,
699    #[serde(default, skip_serializing_if = "Option::is_none")]
700    pub continuity_domain: Option<String>,
701    #[serde(
702        default = "default_service_config_enabled",
703        skip_serializing_if = "is_default_service_config_enabled"
704    )]
705    pub enabled: bool,
706    #[serde(
707        default = "default_provider_endpoint_priority",
708        skip_serializing_if = "is_default_provider_endpoint_priority"
709    )]
710    pub priority: u32,
711    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
712    pub tags: BTreeMap<String, String>,
713    #[serde(
714        default,
715        skip_serializing_if = "BTreeMap::is_empty",
716        alias = "supportedModels"
717    )]
718    pub supported_models: BTreeMap<String, bool>,
719    #[serde(
720        default,
721        skip_serializing_if = "BTreeMap::is_empty",
722        alias = "modelMapping"
723    )]
724    pub model_mapping: BTreeMap<String, String>,
725    #[serde(
726        default,
727        skip_serializing_if = "is_default_provider_concurrency_limits"
728    )]
729    pub limits: ProviderConcurrencyLimits,
730}
731
732#[derive(Debug, Clone, Serialize, Deserialize)]
733pub struct RoutingConfigV4 {
734    #[serde(default = "default_routing_entry_v4")]
735    pub entry: String,
736    #[serde(default = "default_routing_affinity_policy_v5")]
737    pub affinity_policy: RoutingAffinityPolicyV5,
738    #[serde(default, skip_serializing_if = "Option::is_none")]
739    pub fallback_ttl_ms: Option<u64>,
740    #[serde(default, skip_serializing_if = "Option::is_none")]
741    pub reprobe_preferred_after_ms: Option<u64>,
742    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
743    pub routes: BTreeMap<String, RoutingNodeV4>,
744    #[serde(skip, default = "default_routing_policy_v4")]
745    pub policy: RoutingPolicyV4,
746    #[serde(skip)]
747    pub order: Vec<String>,
748    #[serde(skip)]
749    pub target: Option<String>,
750    #[serde(skip)]
751    pub prefer_tags: Vec<BTreeMap<String, String>>,
752    #[serde(skip)]
753    pub chain: Vec<String>,
754    #[serde(skip)]
755    pub pools: BTreeMap<String, RoutingPoolV4>,
756    #[serde(skip, default = "default_routing_on_exhausted_v4")]
757    pub on_exhausted: RoutingExhaustedActionV4,
758}
759
760impl Default for RoutingConfigV4 {
761    fn default() -> Self {
762        Self {
763            entry: default_routing_entry_v4(),
764            affinity_policy: default_routing_affinity_policy_v5(),
765            fallback_ttl_ms: None,
766            reprobe_preferred_after_ms: None,
767            routes: BTreeMap::new(),
768            policy: default_routing_policy_v4(),
769            order: Vec::new(),
770            target: None,
771            prefer_tags: Vec::new(),
772            chain: Vec::new(),
773            pools: BTreeMap::new(),
774            on_exhausted: default_routing_on_exhausted_v4(),
775        }
776    }
777}
778
779impl ProxyConfigV4 {
780    pub fn sync_routing_compat_from_graph(&mut self) {
781        if let Some(routing) = self.codex.routing.as_mut() {
782            routing.sync_compat_from_graph();
783        }
784        if let Some(routing) = self.claude.routing.as_mut() {
785            routing.sync_compat_from_graph();
786        }
787    }
788}
789
790impl RoutingConfigV4 {
791    pub fn ordered_failover(children: Vec<String>) -> Self {
792        Self::single_entry_node(RoutingNodeV4 {
793            strategy: RoutingPolicyV4::OrderedFailover,
794            children,
795            ..RoutingNodeV4::default()
796        })
797    }
798
799    pub fn manual_sticky(target: String, children: Vec<String>) -> Self {
800        Self::single_entry_node(RoutingNodeV4 {
801            strategy: RoutingPolicyV4::ManualSticky,
802            target: Some(target),
803            children,
804            ..RoutingNodeV4::default()
805        })
806    }
807
808    pub fn tag_preferred(
809        children: Vec<String>,
810        prefer_tags: Vec<BTreeMap<String, String>>,
811        on_exhausted: RoutingExhaustedActionV4,
812    ) -> Self {
813        Self::single_entry_node(RoutingNodeV4 {
814            strategy: RoutingPolicyV4::TagPreferred,
815            children,
816            prefer_tags,
817            on_exhausted,
818            ..RoutingNodeV4::default()
819        })
820    }
821
822    pub fn single_entry_node(node: RoutingNodeV4) -> Self {
823        let entry = non_conflicting_default_route_entry(&node);
824        let mut out = Self {
825            routes: BTreeMap::from([(entry.clone(), node)]),
826            entry,
827            affinity_policy: default_routing_affinity_policy_v5(),
828            fallback_ttl_ms: None,
829            reprobe_preferred_after_ms: None,
830            policy: default_routing_policy_v4(),
831            order: Vec::new(),
832            target: None,
833            prefer_tags: Vec::new(),
834            chain: Vec::new(),
835            pools: BTreeMap::new(),
836            on_exhausted: default_routing_on_exhausted_v4(),
837        };
838        out.sync_compat_from_graph();
839        out
840    }
841
842    pub fn has_compat_authoring_fields(&self) -> bool {
843        self.policy != default_routing_policy_v4()
844            || !self.order.is_empty()
845            || self.target.is_some()
846            || !self.prefer_tags.is_empty()
847            || !self.chain.is_empty()
848            || !self.pools.is_empty()
849            || self.on_exhausted != default_routing_on_exhausted_v4()
850    }
851
852    pub fn entry_node(&self) -> Option<&RoutingNodeV4> {
853        self.routes.get(self.entry.as_str())
854    }
855
856    pub fn entry_node_mut(&mut self) -> Option<&mut RoutingNodeV4> {
857        self.routes.get_mut(self.entry.as_str())
858    }
859
860    pub fn sync_compat_from_graph(&mut self) {
861        let Some(node) = self.entry_node().cloned() else {
862            self.policy = default_routing_policy_v4();
863            self.order.clear();
864            self.target = None;
865            self.prefer_tags.clear();
866            self.chain.clear();
867            self.pools.clear();
868            self.on_exhausted = default_routing_on_exhausted_v4();
869            return;
870        };
871
872        self.policy = node.strategy;
873        self.target = node.target.clone();
874        self.prefer_tags = node.prefer_tags.clone();
875        self.on_exhausted = node.on_exhausted;
876        self.order = node.children.clone();
877    }
878
879    pub fn sync_graph_from_compat(&mut self) {
880        if !self.has_compat_authoring_fields() {
881            return;
882        }
883
884        if self.routes.is_empty() {
885            self.entry =
886                non_conflicting_default_route_entry_from_refs(&self.order, self.target.as_deref());
887            self.routes
888                .insert(self.entry.clone(), RoutingNodeV4::default());
889        }
890
891        let entry = self.entry.clone();
892        let node = self.routes.entry(entry).or_default();
893        node.strategy = self.policy;
894        node.target = self.target.clone();
895        node.prefer_tags = self.prefer_tags.clone();
896        node.on_exhausted = self.on_exhausted;
897        if !self.order.is_empty() {
898            node.children = self.order.clone();
899        }
900    }
901
902    pub fn route_node_names(&self) -> Vec<String> {
903        self.routes.keys().cloned().collect()
904    }
905
906    pub fn route_node_references(&self, target: &str) -> Vec<String> {
907        self.routes
908            .iter()
909            .filter_map(|(route_name, node)| {
910                if node.children.iter().any(|child| child == target)
911                    || node.target.as_deref() == Some(target)
912                    || node.then.as_deref() == Some(target)
913                    || node.default_route.as_deref() == Some(target)
914                {
915                    Some(route_name.clone())
916                } else {
917                    None
918                }
919            })
920            .collect()
921    }
922
923    pub fn rename_route_node(&mut self, old: &str, new: String) -> Result<()> {
924        if old == new {
925            return Ok(());
926        }
927        if !self.routes.contains_key(old) {
928            anyhow::bail!("route node '{old}' does not exist");
929        }
930        if self.routes.contains_key(new.as_str()) {
931            anyhow::bail!("route node '{new}' already exists");
932        }
933
934        let Some(node) = self.routes.remove(old) else {
935            anyhow::bail!("route node '{old}' does not exist");
936        };
937        self.routes.insert(new.clone(), node);
938        if self.entry == old {
939            self.entry = new.clone();
940        }
941        for node in self.routes.values_mut() {
942            rewrite_route_node_refs(node, old, new.as_str());
943        }
944        self.sync_compat_from_graph();
945        Ok(())
946    }
947
948    pub fn delete_route_node(&mut self, name: &str) -> Result<()> {
949        if self.entry == name {
950            anyhow::bail!("entry route node '{name}' cannot be deleted");
951        }
952        if !self.routes.contains_key(name) {
953            anyhow::bail!("route node '{name}' does not exist");
954        }
955        let refs = self.route_node_references(name);
956        if !refs.is_empty() {
957            anyhow::bail!(
958                "route node '{name}' is still referenced by: {}",
959                refs.join(", ")
960            );
961        }
962        self.routes.remove(name);
963        self.sync_compat_from_graph();
964        Ok(())
965    }
966}
967
968fn default_routing_entry_v4() -> String {
969    "main".to_string()
970}
971
972fn non_conflicting_default_route_entry(node: &RoutingNodeV4) -> String {
973    non_conflicting_default_route_entry_from_refs(&node.children, node.target.as_deref())
974}
975
976fn non_conflicting_default_route_entry_from_refs(
977    children: &[String],
978    target: Option<&str>,
979) -> String {
980    let occupied = children
981        .iter()
982        .map(String::as_str)
983        .chain(target)
984        .collect::<BTreeSet<_>>();
985    let base = default_routing_entry_v4();
986    if !occupied.contains(base.as_str()) {
987        return base;
988    }
989
990    let mut candidate = format!("{base}_route");
991    let mut idx = 2usize;
992    while occupied.contains(candidate.as_str()) {
993        candidate = format!("{base}_route_{idx}");
994        idx += 1;
995    }
996    candidate
997}
998
999fn rewrite_route_node_refs(node: &mut RoutingNodeV4, old: &str, new: &str) {
1000    for child in &mut node.children {
1001        if child == old {
1002            *child = new.to_string();
1003        }
1004    }
1005    if node.target.as_deref() == Some(old) {
1006        node.target = Some(new.to_string());
1007    }
1008    if node.then.as_deref() == Some(old) {
1009        node.then = Some(new.to_string());
1010    }
1011    if node.default_route.as_deref() == Some(old) {
1012        node.default_route = Some(new.to_string());
1013    }
1014}
1015
1016#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1017pub struct RoutingNodeV4 {
1018    #[serde(default = "default_routing_policy_v4")]
1019    pub strategy: RoutingPolicyV4,
1020    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1021    pub children: Vec<String>,
1022    #[serde(default, skip_serializing_if = "Option::is_none")]
1023    pub target: Option<String>,
1024    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1025    pub prefer_tags: Vec<BTreeMap<String, String>>,
1026    #[serde(default = "default_routing_on_exhausted_v4")]
1027    pub on_exhausted: RoutingExhaustedActionV4,
1028    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1029    pub metadata: BTreeMap<String, String>,
1030    #[serde(default, skip_serializing_if = "Option::is_none")]
1031    pub when: Option<RoutingConditionV4>,
1032    #[serde(default, skip_serializing_if = "Option::is_none")]
1033    pub then: Option<String>,
1034    #[serde(default, rename = "default", skip_serializing_if = "Option::is_none")]
1035    pub default_route: Option<String>,
1036}
1037
1038impl Default for RoutingNodeV4 {
1039    fn default() -> Self {
1040        Self {
1041            strategy: default_routing_policy_v4(),
1042            children: Vec::new(),
1043            target: None,
1044            prefer_tags: Vec::new(),
1045            on_exhausted: default_routing_on_exhausted_v4(),
1046            metadata: BTreeMap::new(),
1047            when: None,
1048            then: None,
1049            default_route: None,
1050        }
1051    }
1052}
1053
1054#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq, Hash)]
1055pub struct RoutingConditionV4 {
1056    #[serde(default, skip_serializing_if = "Option::is_none")]
1057    pub model: Option<String>,
1058    #[serde(default, skip_serializing_if = "Option::is_none")]
1059    pub service_tier: Option<String>,
1060    #[serde(default, skip_serializing_if = "Option::is_none")]
1061    pub reasoning_effort: Option<String>,
1062    #[serde(default, skip_serializing_if = "Option::is_none")]
1063    pub path: Option<String>,
1064    #[serde(default, skip_serializing_if = "Option::is_none")]
1065    pub method: Option<String>,
1066    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1067    pub headers: BTreeMap<String, String>,
1068}
1069
1070impl RoutingConditionV4 {
1071    pub fn is_empty(&self) -> bool {
1072        self.model.is_none()
1073            && self.service_tier.is_none()
1074            && self.reasoning_effort.is_none()
1075            && self.path.is_none()
1076            && self.method.is_none()
1077            && self.headers.is_empty()
1078    }
1079}
1080
1081#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
1082#[serde(rename_all = "kebab-case")]
1083pub enum RoutingPolicyV4 {
1084    ManualSticky,
1085    OrderedFailover,
1086    TagPreferred,
1087    Conditional,
1088}
1089
1090fn default_routing_policy_v4() -> RoutingPolicyV4 {
1091    RoutingPolicyV4::OrderedFailover
1092}
1093
1094#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
1095#[serde(rename_all = "kebab-case")]
1096pub enum RoutingExhaustedActionV4 {
1097    Continue,
1098    Stop,
1099}
1100
1101fn default_routing_on_exhausted_v4() -> RoutingExhaustedActionV4 {
1102    RoutingExhaustedActionV4::Continue
1103}
1104
1105#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
1106#[serde(rename_all = "kebab-case")]
1107pub enum RoutingAffinityPolicyV5 {
1108    Off,
1109    PreferredGroup,
1110    FallbackSticky,
1111    Hard,
1112}
1113
1114fn default_routing_affinity_policy_v5() -> RoutingAffinityPolicyV5 {
1115    RoutingAffinityPolicyV5::FallbackSticky
1116}
1117
1118#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1119pub struct RoutingPoolV4 {
1120    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1121    pub providers: Vec<String>,
1122}
1123
1124#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1125pub struct PersistedRoutingProviderRef {
1126    pub name: String,
1127    #[serde(default, skip_serializing_if = "Option::is_none")]
1128    pub alias: Option<String>,
1129    #[serde(default = "default_service_config_enabled")]
1130    pub enabled: bool,
1131    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1132    pub tags: BTreeMap<String, String>,
1133}
1134
1135#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1136pub struct PersistedRoutingSpec {
1137    pub entry: String,
1138    #[serde(default = "default_routing_affinity_policy_v5")]
1139    pub affinity_policy: RoutingAffinityPolicyV5,
1140    #[serde(default, skip_serializing_if = "Option::is_none")]
1141    pub fallback_ttl_ms: Option<u64>,
1142    #[serde(default, skip_serializing_if = "Option::is_none")]
1143    pub reprobe_preferred_after_ms: Option<u64>,
1144    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1145    pub routes: BTreeMap<String, RoutingNodeV4>,
1146    #[serde(default = "default_routing_policy_v4")]
1147    pub policy: RoutingPolicyV4,
1148    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1149    pub order: Vec<String>,
1150    #[serde(default, skip_serializing_if = "Option::is_none")]
1151    pub target: Option<String>,
1152    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1153    pub prefer_tags: Vec<BTreeMap<String, String>>,
1154    #[serde(default = "default_routing_on_exhausted_v4")]
1155    pub on_exhausted: RoutingExhaustedActionV4,
1156    #[serde(default = "default_routing_policy_v4")]
1157    pub entry_strategy: RoutingPolicyV4,
1158    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1159    pub expanded_order: Vec<String>,
1160    #[serde(default, skip_serializing_if = "Option::is_none")]
1161    pub entry_target: Option<String>,
1162    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1163    pub providers: Vec<PersistedRoutingProviderRef>,
1164}
1165
1166fn is_default_upstream_auth(auth: &UpstreamAuth) -> bool {
1167    auth.auth_token.is_none()
1168        && auth.auth_token_env.is_none()
1169        && auth.api_key.is_none()
1170        && auth.api_key_env.is_none()
1171}
1172
1173#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1174pub struct ServiceViewV2 {
1175    #[serde(
1176        default,
1177        skip_serializing_if = "Option::is_none",
1178        rename = "active_station",
1179        alias = "active_group"
1180    )]
1181    pub active_group: Option<String>,
1182    #[serde(default, skip_serializing_if = "Option::is_none")]
1183    pub default_profile: Option<String>,
1184    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1185    pub profiles: BTreeMap<String, ServiceControlProfile>,
1186    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1187    pub providers: BTreeMap<String, ProviderConfigV2>,
1188    #[serde(
1189        default,
1190        skip_serializing_if = "BTreeMap::is_empty",
1191        rename = "stations",
1192        alias = "groups"
1193    )]
1194    pub groups: BTreeMap<String, GroupConfigV2>,
1195}
1196
1197#[derive(Debug, Clone, Serialize, Deserialize)]
1198pub struct ProviderConfigV2 {
1199    #[serde(default, skip_serializing_if = "Option::is_none")]
1200    pub alias: Option<String>,
1201    #[serde(default = "default_service_config_enabled")]
1202    pub enabled: bool,
1203    #[serde(default)]
1204    pub auth: UpstreamAuth,
1205    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1206    pub tags: BTreeMap<String, String>,
1207    #[serde(
1208        default,
1209        skip_serializing_if = "BTreeMap::is_empty",
1210        alias = "supportedModels"
1211    )]
1212    pub supported_models: BTreeMap<String, bool>,
1213    #[serde(
1214        default,
1215        skip_serializing_if = "BTreeMap::is_empty",
1216        alias = "modelMapping"
1217    )]
1218    pub model_mapping: BTreeMap<String, String>,
1219    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1220    pub endpoints: BTreeMap<String, ProviderEndpointV2>,
1221}
1222
1223impl Default for ProviderConfigV2 {
1224    fn default() -> Self {
1225        Self {
1226            alias: None,
1227            enabled: default_service_config_enabled(),
1228            auth: UpstreamAuth::default(),
1229            tags: BTreeMap::new(),
1230            supported_models: BTreeMap::new(),
1231            model_mapping: BTreeMap::new(),
1232            endpoints: BTreeMap::new(),
1233        }
1234    }
1235}
1236
1237#[derive(Debug, Clone, Serialize, Deserialize)]
1238pub struct ProviderEndpointV2 {
1239    pub base_url: String,
1240    #[serde(default = "default_service_config_enabled")]
1241    pub enabled: bool,
1242    #[serde(
1243        default = "default_provider_endpoint_priority",
1244        skip_serializing_if = "is_default_provider_endpoint_priority"
1245    )]
1246    pub priority: u32,
1247    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1248    pub tags: BTreeMap<String, String>,
1249    #[serde(
1250        default,
1251        skip_serializing_if = "BTreeMap::is_empty",
1252        alias = "supportedModels"
1253    )]
1254    pub supported_models: BTreeMap<String, bool>,
1255    #[serde(
1256        default,
1257        skip_serializing_if = "BTreeMap::is_empty",
1258        alias = "modelMapping"
1259    )]
1260    pub model_mapping: BTreeMap<String, String>,
1261}
1262
1263#[derive(Debug, Clone, Serialize, Deserialize)]
1264pub struct GroupConfigV2 {
1265    #[serde(default, skip_serializing_if = "Option::is_none")]
1266    pub alias: Option<String>,
1267    #[serde(default = "default_service_config_enabled")]
1268    pub enabled: bool,
1269    #[serde(default = "default_service_config_level")]
1270    pub level: u8,
1271    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1272    pub members: Vec<GroupMemberRefV2>,
1273}
1274
1275impl Default for GroupConfigV2 {
1276    fn default() -> Self {
1277        Self {
1278            alias: None,
1279            enabled: default_service_config_enabled(),
1280            level: default_service_config_level(),
1281            members: Vec::new(),
1282        }
1283    }
1284}
1285
1286#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1287pub struct GroupMemberRefV2 {
1288    pub provider: String,
1289    #[serde(default, skip_serializing_if = "Vec::is_empty", alias = "endpoints")]
1290    pub endpoint_names: Vec<String>,
1291    #[serde(default)]
1292    pub preferred: bool,
1293}
1294
1295#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1296pub struct PersistedStationProviderEndpointRef {
1297    pub name: String,
1298    pub base_url: String,
1299    #[serde(default = "default_service_config_enabled")]
1300    pub enabled: bool,
1301}
1302
1303#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1304pub struct PersistedStationProviderRef {
1305    pub name: String,
1306    #[serde(default, skip_serializing_if = "Option::is_none")]
1307    pub alias: Option<String>,
1308    #[serde(default = "default_service_config_enabled")]
1309    pub enabled: bool,
1310    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1311    pub endpoints: Vec<PersistedStationProviderEndpointRef>,
1312}
1313
1314#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1315pub struct PersistedStationSpec {
1316    pub name: String,
1317    #[serde(default, skip_serializing_if = "Option::is_none")]
1318    pub alias: Option<String>,
1319    #[serde(default = "default_service_config_enabled")]
1320    pub enabled: bool,
1321    #[serde(default = "default_service_config_level")]
1322    pub level: u8,
1323    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1324    pub members: Vec<GroupMemberRefV2>,
1325}
1326
1327#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1328pub struct PersistedStationsCatalog {
1329    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1330    pub stations: Vec<PersistedStationSpec>,
1331    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1332    pub providers: Vec<PersistedStationProviderRef>,
1333}
1334
1335#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1336pub struct PersistedProviderEndpointSpec {
1337    pub name: String,
1338    pub base_url: String,
1339    #[serde(default = "default_service_config_enabled")]
1340    pub enabled: bool,
1341    #[serde(
1342        default = "default_provider_endpoint_priority",
1343        skip_serializing_if = "is_default_provider_endpoint_priority"
1344    )]
1345    pub priority: u32,
1346    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1347    pub tags: BTreeMap<String, String>,
1348    #[serde(
1349        default,
1350        skip_serializing_if = "is_default_provider_concurrency_limits"
1351    )]
1352    pub limits: ProviderConcurrencyLimits,
1353}
1354
1355#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1356pub struct PersistedProviderSpec {
1357    pub name: String,
1358    #[serde(default, skip_serializing_if = "Option::is_none")]
1359    pub alias: Option<String>,
1360    #[serde(default = "default_service_config_enabled")]
1361    pub enabled: bool,
1362    #[serde(default, skip_serializing_if = "Option::is_none")]
1363    pub auth_token_env: Option<String>,
1364    #[serde(default, skip_serializing_if = "Option::is_none")]
1365    pub api_key_env: Option<String>,
1366    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1367    pub tags: BTreeMap<String, String>,
1368    #[serde(
1369        default,
1370        skip_serializing_if = "is_default_provider_concurrency_limits"
1371    )]
1372    pub limits: ProviderConcurrencyLimits,
1373    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1374    pub endpoints: Vec<PersistedProviderEndpointSpec>,
1375}
1376
1377#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1378pub struct PersistedProvidersCatalog {
1379    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1380    pub providers: Vec<PersistedProviderSpec>,
1381}
1382
1383#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1384pub struct UiConfig {
1385    /// UI language: `en`, `zh`, or `auto` (default: unset).
1386    ///
1387    /// When unset, codex-helper will pick a default language based on system locale for the first run.
1388    #[serde(default)]
1389    pub language: Option<String>,
1390    /// Spend-rate projection shown in operator UIs.
1391    #[serde(default, skip_serializing_if = "is_default_usage_forecast_config")]
1392    pub usage_forecast: UsageForecastConfig,
1393}
1394
1395/// 获取 codex-helper 的主目录(用于配置、日志等)
1396pub fn proxy_home_dir() -> PathBuf {
1397    if let Ok(dir) = env::var("CODEX_HELPER_HOME") {
1398        let trimmed = dir.trim();
1399        if !trimmed.is_empty() {
1400            return PathBuf::from(trimmed);
1401        }
1402    }
1403
1404    #[cfg(test)]
1405    {
1406        static TEST_HOME: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
1407        TEST_HOME
1408            .get_or_init(|| {
1409                let mut dir = std::env::temp_dir();
1410                let unique = format!(
1411                    "codex-helper-test-{}-{}",
1412                    std::process::id(),
1413                    std::time::SystemTime::now()
1414                        .duration_since(std::time::UNIX_EPOCH)
1415                        .map(|d| d.as_nanos())
1416                        .unwrap_or(0)
1417                );
1418                dir.push(unique);
1419                dir.push(".codex-helper");
1420                let _ = std::fs::create_dir_all(&dir);
1421                dir
1422            })
1423            .clone()
1424    }
1425
1426    #[cfg(not(test))]
1427    {
1428        dirs::home_dir()
1429            .unwrap_or_else(|| PathBuf::from("."))
1430            .join(".codex-helper")
1431    }
1432}
1433
1434/// Directory where Codex stores conversation sessions: `~/.codex/sessions` (or `$CODEX_HOME/sessions`).
1435pub fn codex_sessions_dir() -> PathBuf {
1436    codex_home().join("sessions")
1437}
1438
1439/// 支持的上游服务类型:Codex / Claude。
1440#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1441#[serde(rename_all = "lowercase")]
1442pub enum ServiceKind {
1443    Codex,
1444    Claude,
1445}
1446
1447#[cfg(test)]
1448mod tests;