1use codewhale_config::extension_host::{ExtensionHostConfig, PluginSettings};
4use codewhale_config::opencode_go_models;
5use codewhale_config::provider_preserves_custom_base_url_model;
6use codewhale_config::{
7 base_url_host, default_snapshots_enabled, resolve_xiaomi_mimo_base_url,
8 xiaomi_mimo_base_url_for_mode, xiaomi_mimo_mode_uses_standard_endpoint,
9};
10use std::borrow::Cow;
11use std::collections::{BTreeMap, HashMap};
12use std::fs;
13use std::path::{Path, PathBuf};
14use std::sync::Mutex;
15use std::time::SystemTime;
16
17use anyhow::{Context, Result};
18use codewhale_execpolicy::ExecPolicyEngine;
19use codewhale_localization::{Locale, MessageId, tr};
20use serde::{Deserialize, Serialize};
21use serde_json::json;
22#[cfg(unix)]
23use std::os::unix::fs::PermissionsExt;
24
25use crate::audit::log_sensitive_event;
26use crate::credentials::CredentialStore;
27use crate::features::{Feature, Features, FeaturesToml, is_known_feature_key};
28use codewhale_config::hooks::HooksConfig;
29
30mod credential_resolve;
39pub use credential_resolve::resolve_credential_source;
40mod subagent_limits;
41pub use subagent_limits::*;
42use subagent_limits::{resolve_subagent_api_timeout_secs, resolve_subagent_heartbeat_timeout_secs};
43
44pub const XIAOMI_MIMO_PAY_AS_YOU_GO_BASE_URL: &str = "https://api.xiaomimimo.com/v1";
45pub const XIAOMI_MIMO_TOKEN_PLAN_CN_BASE_URL: &str = "https://token-plan-cn.xiaomimimo.com/v1";
46pub const XIAOMI_MIMO_TOKEN_PLAN_SGP_BASE_URL: &str = DEFAULT_XIAOMI_MIMO_BASE_URL;
47pub const XIAOMI_MIMO_TOKEN_PLAN_AMS_BASE_URL: &str = "https://token-plan-ams.xiaomimimo.com/v1";
48pub const KIMI_CODE_MEMBERSHIP_PLAN_CONSOLE_URL: &str =
49 codewhale_config::provider::KIMI_CODE_MEMBERSHIP_PLAN_CONSOLE_URL;
50#[must_use]
52pub fn is_unresolved_local_ollama_model(model: &str) -> bool {
53 model.trim().eq_ignore_ascii_case(DEFAULT_OLLAMA_MODEL)
54}
55pub const OPENAI_CODEX_EFFECTIVE_CONTEXT_WINDOW_TOKENS: u32 = 128_000;
58
59#[cfg(test)]
60use codewhale_config::API_KEYRING_SENTINEL;
61use codewhale_config::{ConfigApiKeyValueKind, classify_config_api_key_value};
62
63pub const DEFAULT_ZAI_PROVIDER_MAX_CONCURRENCY: usize = 3;
64pub const MAX_PROVIDER_REQUEST_CONCURRENCY: usize = 64;
65
66pub const DEFAULT_REASONING_ONLY_REPROMPTS: u32 = 2;
69
70pub const DEFAULT_REASONING_ONLY_REPROMPT_MESSAGE: &str =
76 "Continue: give your answer, or make the next tool call.";
77
78pub fn default_stop_words() -> Vec<String> {
79 ["stop", "wait", "pause"]
80 .into_iter()
81 .map(str::to_string)
82 .collect()
83}
84
85use codewhale_config::ProviderKind;
86use codewhale_config::catalog::reviewed::constants::*;
87use codewhale_config::descriptors::defaults::*;
88use codewhale_config::descriptors::{compatibility_for_id, compatibility_for_selector};
89use codewhale_config::route::ProviderId;
90
91#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct ProviderIdentity {
98 pub provider: ProviderKind,
99 pub key: ProviderId,
100 pub(crate) exact_id: Option<ProviderId>,
105 pub(crate) migrated_legacy_ollama_cloud_route: bool,
110 pub(crate) legacy_root_custom_generation:
112 Option<codewhale_config::credentials::CredentialGeneration>,
113}
114
115impl ProviderIdentity {
116 pub fn migrated_legacy_ollama_cloud_route(&self) -> bool {
117 self.migrated_legacy_ollama_cloud_route
118 }
119
120 #[cfg(any(test, feature = "test-support"))]
121 pub fn test_exact_identity(provider: ProviderKind, key: impl Into<String>) -> Self {
122 let key = ProviderId::from(key.into());
123 Self {
124 provider,
125 exact_id: Some(key.clone()),
126 key,
127 migrated_legacy_ollama_cloud_route: false,
128 legacy_root_custom_generation: None,
129 }
130 }
131}
132
133impl std::hash::Hash for ProviderIdentity {
134 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
135 std::hash::Hash::hash(&self.key, state);
136 }
137}
138
139pub fn is_legacy_antigravity_identity(value: &str) -> bool {
140 codewhale_config::ProviderKind::parse_config_identity(value)
141 == Some(codewhale_config::ProviderKind::Antigravity)
142}
143
144impl ProviderIdentity {
145 #[must_use]
146 pub fn persisted_id(&self) -> Option<&str> {
147 self.exact_id.as_ref().map(ProviderId::as_str)
148 }
149
150 pub fn persisted_kind(&self) -> &str {
152 if self.provider == ProviderKind::Deepseek
153 && self.key.as_str() == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id
154 {
155 self.key.as_str()
156 } else {
157 self.provider.as_str()
158 }
159 }
160
161 pub fn config_table_key(&self) -> Result<&str> {
164 if self.provider == ProviderKind::Custom {
165 return Ok(self.key.as_str());
166 }
167 if self.migrated_legacy_ollama_cloud_route {
168 return Ok(ProviderKind::Ollama.as_str());
169 }
170 self.compatibility()
171 .map(|row| row.config_key)
172 .context("provider config metadata")
173 }
174
175 pub fn compatibility(
177 &self,
178 ) -> Option<&'static codewhale_config::descriptors::ProviderCompatibility> {
179 if self.provider == ProviderKind::Custom {
180 return None;
181 }
182 compatibility_for_id(self.key.as_str()).filter(|row| row.kind == self.provider)
183 }
184}
185
186fn normalize_subagent_provider_key(value: &str) -> String {
187 value
188 .trim()
189 .to_ascii_lowercase()
190 .chars()
191 .map(|ch| match ch {
192 '-' | '_' | '.' | ' ' => '_',
193 other => other,
194 })
195 .collect()
196}
197
198pub const DEEPSEEK_ALIAS_RETIREMENT_DATE: &str = "2026-07-24";
199pub const DEEPSEEK_ALIAS_RETIREMENT_UTC: &str = "2026-07-24T15:59:00Z";
200use codewhale_config::catalog::reviewed::constants::DEEPSEEK_ALIAS_REPLACEMENT;
201
202#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
204pub struct ModelAliasDeprecation {
205 pub alias: String,
206 pub replacement: String,
207 pub retirement_date: String,
208 pub retirement_utc: String,
209 pub notice: String,
210}
211
212pub fn configured_model_for_route<'a>(
213 config: &'a Config,
214 provider: ProviderKind,
215 identity: &str,
216 base_url: &str,
217 model: &str,
218) -> Option<&'a codewhale_config::catalog::configured::ConfiguredModel> {
219 if provider == ProviderKind::OpenaiCodex {
221 return None;
222 }
223 let models = config.custom_models.as_deref()?;
224 codewhale_config::catalog::configured::validate_configured_models(models).ok()?;
225 models
226 .iter()
227 .find(|row| row.id == model && row.matches_route(identity, base_url))
228}
229
230pub fn deepseek_alias_deprecation(model_lower: &str) -> Option<ModelAliasDeprecation> {
231 match model_lower {
232 "deepseek-chat" | "deepseek-reasoner" => Some(ModelAliasDeprecation {
233 alias: model_lower.to_string(),
234 replacement: DEEPSEEK_ALIAS_REPLACEMENT.to_string(),
235 retirement_date: DEEPSEEK_ALIAS_RETIREMENT_DATE.to_string(),
236 retirement_utc: DEEPSEEK_ALIAS_RETIREMENT_UTC.to_string(),
237 notice: format!(
238 "DeepSeek retired {model_lower} on {DEEPSEEK_ALIAS_RETIREMENT_DATE}; Codewhale sends {DEEPSEEK_ALIAS_REPLACEMENT} instead."
239 ),
240 }),
241 _ => None,
242 }
243}
244
245#[must_use]
246pub fn normalize_custom_model_id(model: &str) -> Option<String> {
247 let trimmed = model.trim();
248 if trimmed.is_empty() || trimmed.chars().any(char::is_control) {
249 None
250 } else {
251 Some(trimmed.to_string())
252 }
253}
254
255pub fn validate_route(provider: ProviderKind, model: &str) -> Result<(), String> {
256 let trimmed = model.trim();
257 if trimmed.is_empty() {
258 return Err(format!(
259 "No model selected for provider '{}'.",
260 provider.as_str()
261 ));
262 }
263 if trimmed.eq_ignore_ascii_case("auto") {
264 return Ok(());
265 }
266
267 if provider == ProviderKind::OpencodeGo {
268 return if opencode_go_model_id(trimmed).is_some() {
269 Ok(())
270 } else {
271 Err(format!(
272 "Model '{trimmed}' is not in OpenCode Go's documented protocol roster. \
273 Choose one of: {}.",
274 opencode_go_models().join(", ")
275 ))
276 };
277 }
278
279 if codewhale_config::descriptors::provider_passes_model_through(provider) {
280 return Ok(());
281 }
282
283 if matches!(provider, ProviderKind::Deepseek) {
284 if codewhale_config::route::resolve_model(ProviderKind::Deepseek, trimmed, None).is_ok() {
285 return Ok(());
286 }
287 return Err(format!(
288 "Model '{trimmed}' is not a DeepSeek model, but the active provider is '{}'. \
289 Use a DeepSeek model id (for example {}) or switch providers together with the model.",
290 provider.as_str(),
291 COMMON_DEEPSEEK_MODELS.join(", ")
292 ));
293 }
294
295 if root_deepseek_model_is_foreign_to_direct_provider(provider, trimmed) {
296 return Err(format!(
297 "Model '{trimmed}' is a DeepSeek model and is not compatible with provider '{}'. \
298 Switch the provider and model together, or pick a model this provider serves.",
299 provider.as_str()
300 ));
301 }
302
303 Ok(())
304}
305
306fn legacy_deepseek_alias_reasoning_effort(model: &str) -> Option<&'static str> {
307 codewhale_config::legacy_deepseek_alias_reasoning_effort(model)
308}
309
310pub fn opencode_go_model_id(model: &str) -> Option<&'static str> {
311 codewhale_config::opencode_go_model_id(model)
312}
313
314#[must_use]
328pub(crate) fn prefer_configured_model_spelling(configured: &str, remembered: String) -> String {
329 let configured = configured.trim();
330 if remembered != configured && remembered.eq_ignore_ascii_case(configured) {
331 return configured.to_string();
332 }
333 remembered
334}
335
336pub fn legacy_deepseek_alias_effort_for_route(
340 provider: ProviderKind,
341 base_url: &str,
342 model: &str,
343) -> Option<&'static str> {
344 if !matches!(
345 provider,
346 ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
347 ) {
348 return None;
349 }
350 let effort = legacy_deepseek_alias_reasoning_effort(model)?;
351 codewhale_config::route::resolve_model(provider, model, Some(base_url))
352 .is_ok_and(|resolved| resolved.wire_id != model.trim())
353 .then_some(effort)
354}
355
356#[must_use]
365pub fn model_completion_names_for_provider(provider: ProviderKind) -> Vec<&'static str> {
366 codewhale_config::catalog::reviewed::constants::completion_names(provider.as_str()).to_vec()
367}
368
369pub fn read_plugin_settings(
373 path: &Path,
374) -> std::result::Result<BTreeMap<String, PluginSettings>, String> {
375 let contents = match fs::read_to_string(path) {
376 Ok(contents) => contents,
377 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
378 Err(error) => return Err(format!("cannot read {}: {error}", path.display())),
379 };
380 parse_config_file(&contents)
383 .map(|file| file.base.plugins.unwrap_or_default())
384 .map_err(|_| format!("cannot parse {}", path.display()))
385}
386
387#[derive(Debug, Clone, serde::Serialize, Deserialize)]
389#[serde(try_from = "RawRateLimitRetryPolicy")]
390pub struct RateLimitRetryPolicy {
391 pub max_attempts: u32,
392 pub recovery_budget_secs: u64,
393 pub initial_delay_secs: u64,
394 pub max_delay_secs: u64,
395}
396
397impl Default for RateLimitRetryPolicy {
398 fn default() -> Self {
399 Self {
400 max_attempts: 20,
401 recovery_budget_secs: 600,
402 initial_delay_secs: 5,
403 max_delay_secs: 60,
404 }
405 }
406}
407
408#[derive(Deserialize)]
409#[serde(default)]
410struct RawRateLimitRetryPolicy {
411 max_attempts: u32,
412 recovery_budget_secs: u64,
413 initial_delay_secs: u64,
414 max_delay_secs: u64,
415}
416
417impl Default for RawRateLimitRetryPolicy {
418 fn default() -> Self {
419 let p = RateLimitRetryPolicy::default();
420 Self {
421 max_attempts: p.max_attempts,
422 recovery_budget_secs: p.recovery_budget_secs,
423 initial_delay_secs: p.initial_delay_secs,
424 max_delay_secs: p.max_delay_secs,
425 }
426 }
427}
428
429impl TryFrom<RawRateLimitRetryPolicy> for RateLimitRetryPolicy {
430 type Error = String;
431 fn try_from(p: RawRateLimitRetryPolicy) -> Result<Self, Self::Error> {
432 if !(1..=1000).contains(&p.max_attempts)
433 || !(1..=86400).contains(&p.recovery_budget_secs)
434 || p.initial_delay_secs == 0
435 || p.initial_delay_secs > p.max_delay_secs
436 || p.max_delay_secs > 86400
437 {
438 return Err("invalid retry.rate_limit policy: attempts 1..1000, budget 1..86400s, 1 <= initial <= max <= 86400s".into());
439 }
440 Ok(Self {
441 max_attempts: p.max_attempts,
442 recovery_budget_secs: p.recovery_budget_secs,
443 initial_delay_secs: p.initial_delay_secs,
444 max_delay_secs: p.max_delay_secs,
445 })
446 }
447}
448
449#[derive(Debug, Clone, Deserialize)]
451pub struct RetryConfig {
452 #[serde(default)]
453 pub rate_limit: RateLimitRetryPolicy,
454 pub enabled: Option<bool>,
455 pub max_retries: Option<u32>,
456 pub initial_delay: Option<f64>,
457 pub max_delay: Option<f64>,
458 pub exponential_base: Option<f64>,
459 #[serde(default)]
461 pub jitter: Option<bool>,
462 #[serde(default)]
466 pub jitter_factor: Option<f64>,
467 #[serde(default)]
470 pub respect_retry_after: Option<bool>,
471}
472
473fn deser_status_items<'de, D>(deserializer: D) -> Result<Option<Vec<StatusItem>>, D::Error>
478where
479 D: serde::Deserializer<'de>,
480{
481 let raw: Option<Vec<String>> = Option::deserialize(deserializer)?;
482 Ok(raw.map(|strings| {
483 strings
484 .into_iter()
485 .filter_map(|s| {
486 StatusItem::from_key(&s).or_else(|| {
487 tracing::warn!("ignoring unknown status item {s:?} in config");
488 None
489 })
490 })
491 .collect()
492 }))
493}
494
495#[derive(Debug, Clone, Default, Deserialize, Serialize)]
499#[serde(deny_unknown_fields)]
500pub struct StreamConfig {
501 pub open_timeout_secs: Option<u64>,
502 pub chunk_timeout_secs: Option<u64>,
503 pub force_http1: Option<bool>,
504 pub max_resumes: Option<u32>,
505 pub max_transparent_retries: Option<u32>,
506 pub max_stream_errors: Option<u32>,
507 pub max_duration_secs: Option<u64>,
508 pub max_content_mb: Option<u64>,
509 pub connect_timeout_secs: Option<u64>,
510 pub tcp_keepalive_secs: Option<u64>,
512 pub http2_keep_alive_interval_secs: Option<u64>,
514 pub http2_keep_alive_timeout_secs: Option<u64>,
516}
517
518#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
520pub struct RouteProvenance {
521 pub provider_from_saved_selection: bool,
522 pub model_from_saved_selection: bool,
523 pub provider_from_profile: bool,
524 pub model_from_profile: bool,
525 pub provider_from_env: bool,
526 pub provider_from_managed: bool,
527 pub model_from_managed: bool,
528}
529
530#[derive(Debug, Clone, Deserialize, Default)]
531pub struct TuiConfig {
532 pub alternate_screen: Option<String>,
533 pub mouse_capture: Option<bool>,
534 pub selection_copy_markdown: Option<bool>,
540 pub stream_chunk_timeout_secs: Option<u64>,
543 pub max_model_steps: Option<u32>,
547 pub turn_wall_clock_secs: Option<u64>,
551 pub stream_max_content_mb: Option<u64>,
555 pub stream_max_duration_secs: Option<u64>,
559 pub stream_max_resumes: Option<u32>,
562 pub stream_max_transparent_retries: Option<u32>,
565 pub stream_max_errors: Option<u32>,
568 pub stream_open_timeout_secs: Option<u64>,
572 pub connect_timeout_secs: Option<u64>,
575 pub force_http1: Option<bool>,
579 #[serde(default, deserialize_with = "deser_status_items")]
586 pub status_items: Option<Vec<StatusItem>>,
587 #[serde(default)]
595 pub posture_bar: Option<ChromeRowPreset>,
596 #[serde(default)]
600 pub metrics_line: Option<ChromeRowPreset>,
601 pub osc8_links: Option<bool>,
611 pub notification_condition: Option<NotificationCondition>,
626 #[serde(default)]
631 pub composer_arrows_scroll: Option<bool>,
632}
633
634#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq)]
643#[serde(rename_all = "snake_case")]
644pub enum ChromeRowPreset {
645 #[default]
647 Full,
648 Compact,
650 Hidden,
652}
653
654impl ChromeRowPreset {
655 pub const SETTINGS: [&'static str; 3] = ["full", "compact", "hidden"];
657
658 #[must_use]
660 pub const fn as_setting(self) -> &'static str {
661 match self {
662 Self::Full => "full",
663 Self::Compact => "compact",
664 Self::Hidden => "hidden",
665 }
666 }
667
668 #[must_use]
670 pub fn from_setting(value: &str) -> Option<Self> {
671 match value.trim().to_ascii_lowercase().as_str() {
672 "full" => Some(Self::Full),
673 "compact" => Some(Self::Compact),
674 "hidden" => Some(Self::Hidden),
675 _ => None,
676 }
677 }
678}
679
680#[cfg(test)]
681use codewhale_config::notifications::{EventSoundConfig, NotificationEventsConfig};
682
683#[cfg(test)]
684use codewhale_config::notifications::{
685 CompletionSound, NotificationConfigUpdate, NotificationMethod,
686};
687use codewhale_config::notifications::{NotificationCondition, NotificationsConfig};
688
689fn default_snapshot_max_age_days() -> u64 {
690 codewhale_config::DEFAULT_SNAPSHOT_MAX_AGE.as_secs() / (24 * 60 * 60)
691}
692
693fn default_snapshot_max_workspace_gb() -> u64 {
694 codewhale_config::DEFAULT_MAX_WORKSPACE_BYTES_FOR_SNAPSHOT / (1024 * 1024 * 1024)
695}
696
697#[derive(Debug, Clone, Deserialize)]
699pub struct SnapshotsConfig {
700 #[serde(default = "default_snapshots_enabled")]
702 pub enabled: bool,
703 #[serde(default = "default_snapshot_max_age_days")]
705 pub max_age_days: u64,
706 #[serde(default = "default_snapshot_max_workspace_gb")]
713 pub max_workspace_gb: u64,
714}
715
716impl Default for SnapshotsConfig {
717 fn default() -> Self {
718 Self {
719 enabled: default_snapshots_enabled(),
720 max_age_days: default_snapshot_max_age_days(),
721 max_workspace_gb: default_snapshot_max_workspace_gb(),
722 }
723 }
724}
725
726#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
732#[serde(rename_all = "lowercase")]
733pub enum MemoryBackend {
734 Native,
735 #[default]
736 Off,
737}
738
739#[derive(Debug, Clone, Default, Deserialize)]
740pub struct MemoryConfig {
741 #[serde(default)]
745 pub enabled: Option<bool>,
746 #[serde(default)]
749 pub backend: Option<MemoryBackend>,
750}
751
752#[derive(Debug, Clone, Default, Deserialize)]
754pub struct SpeechConfig {
755 #[serde(default)]
758 pub output_dir: Option<String>,
759}
760
761impl SnapshotsConfig {
762 #[must_use]
763 pub fn max_age(&self) -> std::time::Duration {
764 std::time::Duration::from_secs(self.max_age_days.saturating_mul(24 * 60 * 60))
765 }
766}
767
768mod search;
772pub use search::*;
773
774#[derive(Debug, Clone, Deserialize, Default)]
776pub struct ToolsConfig {
777 #[serde(default)]
780 pub always_load: Vec<String>,
781
782 #[serde(default)]
788 pub plugin_dir: Option<String>,
789
790 #[serde(default)]
796 pub overrides: Option<HashMap<String, ToolOverride>>,
797
798 #[serde(default)]
803 pub user_input_max_questions: Option<u32>,
804
805 #[serde(default)]
809 pub user_input_max_options: Option<u32>,
810
811 #[serde(default)]
817 pub user_input_timeout_seconds: Option<u64>,
818
819 #[serde(default)]
824 pub task_human_wait_cap_seconds: Option<u64>,
825
826 #[serde(default)]
827 pub max_parallel_shell_exec: Option<usize>,
828}
829
830#[derive(Debug, Clone, Copy, Deserialize, Default, PartialEq, Eq)]
832pub struct GoalConfig {
833 #[serde(default)]
841 pub max_continuations: Option<u32>,
842
843 #[serde(default)]
849 pub max_steps: Option<u32>,
850 #[serde(default)]
855 pub continuation_delay_seconds: Option<u64>,
856
857 #[serde(default)]
863 pub enforce_token_budget: Option<bool>,
864
865 #[serde(default)]
871 pub complete_judge: Option<bool>,
872
873 #[serde(default)]
878 pub blocked_judge: Option<bool>,
879}
880
881#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
885#[serde(default)]
886pub struct ReasoningOnlyConfig {
887 pub on_output_limit: bool,
888 pub max_reprompts: Option<u32>,
892 pub reprompt_message: Option<String>,
899}
900
901#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Hash)]
931#[serde(rename_all = "snake_case")]
932pub enum StatusItem {
933 Mode,
935 Model,
937 Cost,
939 Cache,
941 ContextPercent,
943 Tokens,
945 Balance,
947 SessionMetrics,
950 Ttft,
952 OutputRate,
954 Workspace,
957 GitBranch,
961}
962
963impl StatusItem {
964 #[must_use]
969 pub fn default_footer() -> Vec<StatusItem> {
970 vec![
971 StatusItem::Mode,
972 StatusItem::Model,
973 StatusItem::ContextPercent,
974 StatusItem::Cost,
975 StatusItem::Cache,
976 StatusItem::Tokens,
977 StatusItem::Ttft,
978 StatusItem::OutputRate,
979 ]
980 }
981
982 #[must_use]
984 pub fn key(self) -> &'static str {
985 match self {
986 StatusItem::Mode => "mode",
987 StatusItem::Model => "model",
988 StatusItem::Cost => "cost",
989 StatusItem::Cache => "cache",
990 StatusItem::ContextPercent => "context_percent",
991 StatusItem::Tokens => "tokens",
992 StatusItem::Balance => "balance",
993 StatusItem::SessionMetrics => "session_metrics",
994 StatusItem::Ttft => "ttft",
995 StatusItem::OutputRate => "output_rate",
996 StatusItem::Workspace => "workspace",
997 StatusItem::GitBranch => "git_branch",
998 }
999 }
1000
1001 #[must_use]
1005 pub fn from_key(key: &str) -> Option<Self> {
1006 match key {
1007 "mode" => Some(Self::Mode),
1008 "model" => Some(Self::Model),
1009 "cost" => Some(Self::Cost),
1010 "cache" => Some(Self::Cache),
1011 "context_percent" => Some(Self::ContextPercent),
1012 "tokens" => Some(Self::Tokens),
1013 "status" | "agents" | "reasoning_replay" | "prefix_stability" | "last_tool_elapsed"
1016 | "rate_limit" => None,
1017 "balance" => Some(Self::Balance),
1018 "session_metrics" => Some(Self::SessionMetrics),
1019 "ttft" => Some(Self::Ttft),
1020 "output_rate" => Some(Self::OutputRate),
1021 "workspace" => Some(Self::Workspace),
1022 "git_branch" => Some(Self::GitBranch),
1026 _ => None,
1027 }
1028 }
1029
1030 #[must_use]
1032 pub fn label(self) -> &'static str {
1033 match self {
1034 StatusItem::Mode => "Mode",
1035 StatusItem::Model => "Model",
1036 StatusItem::Cost => "Session cost",
1037 StatusItem::Cache => "Prompt cache hit rate",
1038 StatusItem::ContextPercent => "Context window %",
1039 StatusItem::Tokens => "Output tokens",
1040 StatusItem::Balance => "Account balance",
1041 StatusItem::SessionMetrics => "Session metrics",
1042 StatusItem::Ttft => "Time to first token",
1043 StatusItem::OutputRate => "Output rate",
1044 StatusItem::Workspace => "Workspace",
1045 StatusItem::GitBranch => "Git branch",
1046 }
1047 }
1048
1049 #[must_use]
1052 pub fn hint(self, locale: Locale) -> Cow<'static, str> {
1053 tr(
1054 locale,
1055 match self {
1056 StatusItem::Mode => MessageId::StatusPickerModeHint,
1057 StatusItem::Model => MessageId::StatusPickerModelHint,
1058 StatusItem::Cost => MessageId::StatusPickerCostHint,
1059 StatusItem::Cache => MessageId::StatusPickerCacheHint,
1060 StatusItem::ContextPercent => MessageId::StatusPickerContextPercentHint,
1061 StatusItem::Tokens => MessageId::StatusPickerTokensHint,
1062 StatusItem::Balance => MessageId::StatusPickerBalanceHint,
1063 StatusItem::SessionMetrics => MessageId::StatusPickerSessionMetricsHint,
1064 StatusItem::Ttft => MessageId::StatusPickerTtftHint,
1065 StatusItem::OutputRate => MessageId::StatusPickerOutputRateHint,
1066 StatusItem::Workspace => MessageId::StatusPickerWorkspaceHint,
1067 StatusItem::GitBranch => MessageId::StatusPickerGitBranchHint,
1068 },
1069 )
1070 }
1071
1072 #[must_use]
1075 pub fn all() -> &'static [StatusItem] {
1076 &[
1077 StatusItem::Mode,
1078 StatusItem::Model,
1079 StatusItem::ContextPercent,
1080 StatusItem::Cost,
1081 StatusItem::Balance,
1082 StatusItem::Cache,
1083 StatusItem::Tokens,
1084 StatusItem::Ttft,
1085 StatusItem::OutputRate,
1086 StatusItem::Workspace,
1087 StatusItem::GitBranch,
1088 ]
1089 }
1090
1091 #[must_use]
1095 pub fn is_available_for(self, provider: ProviderKind) -> bool {
1096 match self {
1097 StatusItem::Balance => provider_has_balance_api(provider),
1098 _ => true,
1099 }
1100 }
1101}
1102
1103#[must_use]
1106pub fn provider_has_balance_api(provider: ProviderKind) -> bool {
1107 matches!(
1108 provider,
1109 ProviderKind::Deepseek
1110 | ProviderKind::Openrouter
1111 | ProviderKind::Siliconflow
1112 | ProviderKind::SiliconflowCN
1113 )
1114}
1115
1116#[derive(Debug, Clone)]
1118pub struct RetryPolicy {
1119 pub rate_limit: RateLimitRetryPolicy,
1120 pub enabled: bool,
1121 pub max_retries: u32,
1122 pub initial_delay: f64,
1123 pub max_delay: f64,
1124 pub exponential_base: f64,
1125 pub jitter: bool,
1126 pub jitter_factor: f64,
1127 pub respect_retry_after: bool,
1128}
1129
1130#[derive(Debug, Clone, Deserialize, Default)]
1138pub struct ContextConfig {
1139 #[serde(default)]
1145 pub project_pack: Option<bool>,
1146}
1147
1148pub const COMPACTION_SUMMARY_INSTRUCTIONS_MAX_CHARS: usize = 4_000;
1153pub const DEFAULT_COMPACTION_RETAINED_USER_MESSAGE_TOKENS: usize = 20_000;
1156pub const MIN_COMPACTION_RETAINED_USER_MESSAGE_TOKENS: usize = 2_000;
1159pub const MAX_COMPACTION_RETAINED_USER_MESSAGE_TOKENS: usize = 200_000;
1162
1163#[derive(Debug, Clone, Deserialize, Default)]
1170pub struct CompactionSettings {
1171 #[serde(default)]
1178 pub summary_instructions: Option<String>,
1179 #[serde(default, alias = "retained_user_message_max_tokens")]
1185 pub retained_user_message_tokens: Option<usize>,
1186}
1187
1188#[derive(Debug, Clone, Deserialize, Default)]
1193pub struct SubagentsConfig {
1194 #[serde(default)]
1198 pub enabled: Option<bool>,
1199 #[serde(default)]
1200 pub default_model: Option<String>,
1201 #[serde(default)]
1202 pub worker_model: Option<String>,
1203 #[serde(default, rename = "scout_model", alias = "explorer_model")]
1204 pub explorer_model: Option<String>,
1205 #[serde(default, rename = "planner_model", alias = "awaiter_model")]
1206 pub awaiter_model: Option<String>,
1207 #[serde(default, rename = "reviewer_model", alias = "review_model")]
1208 pub review_model: Option<String>,
1209 #[serde(default)]
1210 pub custom_model: Option<String>,
1211 #[serde(default)]
1212 pub models: Option<HashMap<String, String>>,
1213 #[serde(default)]
1216 pub roles: Option<HashMap<String, SubagentRoleConfig>>,
1217 #[serde(default)]
1220 pub max_concurrent: Option<usize>,
1221 #[serde(default)]
1229 pub max_depth: Option<u32>,
1230 #[serde(default)]
1235 pub launch_concurrency: Option<usize>,
1236 #[serde(default, alias = "max_total", alias = "admission_limit")]
1240 pub max_admitted: Option<usize>,
1241 #[serde(default, rename = "interactive_max_launch")]
1244 pub interactive_max_launch_legacy: Option<usize>,
1245 #[serde(default)]
1252 pub api_timeout_secs: Option<u64>,
1253 #[serde(default)]
1258 pub heartbeat_timeout_secs: Option<u64>,
1259 #[serde(default)]
1262 pub default_max_steps: Option<u32>,
1263 #[serde(default)]
1266 pub default_wall_time_secs: Option<u64>,
1267 #[serde(default)]
1270 pub providers: Option<HashMap<String, SubagentProviderConfig>>,
1271}
1272
1273#[derive(Debug, Clone, Deserialize)]
1277#[serde(deny_unknown_fields)]
1278pub struct SubagentRoleConfig {
1279 pub model: String,
1280 #[serde(default)]
1286 pub replacements: Vec<String>,
1287}
1288
1289fn parse_subagent_role_pin(value: &str) -> SubagentModelOverride {
1290 let value = value.trim();
1291 match value.split_once('/') {
1292 Some((provider, model)) => SubagentModelOverride {
1293 provider: Some(provider.trim().to_string()),
1294 model: model.trim().to_string(),
1295 },
1296 None => value.into(),
1297 }
1298}
1299
1300#[derive(Debug, Clone, PartialEq, Eq)]
1303pub struct SubagentModelOverride {
1304 pub provider: Option<String>,
1305 pub model: String,
1306}
1307
1308impl From<String> for SubagentModelOverride {
1309 fn from(model: String) -> Self {
1310 Self {
1311 provider: None,
1312 model,
1313 }
1314 }
1315}
1316
1317impl From<&str> for SubagentModelOverride {
1318 fn from(model: &str) -> Self {
1319 model.to_string().into()
1320 }
1321}
1322
1323#[derive(Debug, Clone, Deserialize, Default)]
1328pub struct SubagentProviderConfig {
1329 #[serde(default)]
1330 pub enabled: Option<bool>,
1331 #[serde(default)]
1332 pub max_concurrent: Option<usize>,
1333 #[serde(default)]
1334 pub max_depth: Option<u32>,
1335 #[serde(default)]
1336 pub launch_concurrency: Option<usize>,
1337 #[serde(default, alias = "max_total", alias = "admission_limit")]
1338 pub max_admitted: Option<usize>,
1339 #[serde(default)]
1340 pub api_timeout_secs: Option<u64>,
1341 #[serde(default)]
1342 pub heartbeat_timeout_secs: Option<u64>,
1343}
1344
1345#[derive(Debug, Clone, Deserialize, Default)]
1358pub struct AutoConfig {
1359 #[serde(default)]
1360 pub cost_saving: Option<bool>,
1361 #[serde(default)]
1364 pub cross_provider: Option<bool>,
1365 #[serde(default)]
1367 pub router: Option<AutoRouterConfig>,
1368}
1369
1370pub(crate) const DEFAULT_AUTO_ROUTER_TIMEOUT_SECS: u64 = 4;
1372pub const MAX_AUTO_ROUTER_TIMEOUT_SECS: u64 = 300;
1375
1376#[derive(Debug, Clone, Default, Deserialize)]
1388pub struct AutoRouterConfig {
1389 #[serde(default)]
1391 pub provider: Option<String>,
1392 #[serde(default)]
1394 pub model: Option<String>,
1395 #[serde(default)]
1397 pub thinking: Option<String>,
1398 #[serde(default)]
1403 pub timeout_secs: Option<u64>,
1404 #[serde(default)]
1409 pub kind: Option<String>,
1410 #[serde(default)]
1414 pub min_confidence: Option<f64>,
1415 #[serde(default)]
1419 pub base_url: Option<String>,
1420}
1421
1422#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
1424#[serde(rename_all = "snake_case")]
1425pub enum AutoRouterKind {
1426 Chat,
1428 Decision,
1430}
1431
1432impl AutoRouterKind {
1433 #[must_use]
1436 pub fn parse(raw: Option<&str>) -> Option<Self> {
1437 match raw.map(str::trim).filter(|kind| !kind.is_empty()) {
1438 None => Some(Self::Chat),
1439 Some(kind) if kind.eq_ignore_ascii_case("chat") => Some(Self::Chat),
1440 Some(kind) if kind.eq_ignore_ascii_case("decision") => Some(Self::Decision),
1441 Some(_) => None,
1442 }
1443 }
1444}
1445
1446pub const DEFAULT_AUTO_ROUTER_MIN_CONFIDENCE: f64 = 0.5;
1450
1451fn default_update_check_for_updates() -> bool {
1452 true
1453}
1454
1455fn default_update_check_interval_hours() -> u64 {
1456 codewhale_release::check::DEFAULT_CHECK_INTERVAL_HOURS
1457}
1458
1459#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
1461pub struct UpdateConfig {
1462 #[serde(default = "default_update_check_for_updates")]
1464 pub check_for_updates: bool,
1465 #[serde(default = "default_update_check_interval_hours")]
1469 pub check_interval_hours: u64,
1470 #[serde(default)]
1472 pub update_uri: Option<String>,
1473 #[serde(default = "default_update_show_whats_new")]
1474 pub show_whats_new: bool,
1475 #[serde(default)]
1476 pub mode: Option<String>,
1477}
1478
1479fn default_update_show_whats_new() -> bool {
1480 true
1481}
1482
1483impl Default for UpdateConfig {
1484 fn default() -> Self {
1485 Self {
1486 check_for_updates: true,
1487 check_interval_hours: default_update_check_interval_hours(),
1488 update_uri: None,
1489 show_whats_new: true,
1490 mode: None,
1491 }
1492 }
1493}
1494
1495impl UpdateConfig {
1496 #[must_use]
1497 pub fn update_uri(&self) -> Option<&str> {
1498 self.update_uri
1499 .as_deref()
1500 .map(str::trim)
1501 .filter(|value| !value.is_empty())
1502 }
1503}
1504
1505fn default_cloud_facts_channel() -> String {
1506 "stable".to_string()
1507}
1508
1509fn default_cloud_facts_ttl_hours() -> u64 {
1510 codewhale_cloud_facts::DEFAULT_TTL_SECS / 3600
1511}
1512
1513#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
1517pub struct CloudFactsConfig {
1518 #[serde(default)]
1521 pub enabled: bool,
1522 #[serde(default = "default_cloud_facts_channel")]
1524 pub channel: String,
1525 #[serde(default)]
1527 pub url: Option<String>,
1528 #[serde(default = "default_cloud_facts_ttl_hours")]
1530 pub ttl_hours: u64,
1531}
1532
1533impl Default for CloudFactsConfig {
1534 fn default() -> Self {
1535 Self {
1536 enabled: false,
1537 channel: default_cloud_facts_channel(),
1538 url: None,
1539 ttl_hours: default_cloud_facts_ttl_hours(),
1540 }
1541 }
1542}
1543
1544impl CloudFactsConfig {
1545 #[must_use]
1547 pub fn settings(&self) -> codewhale_cloud_facts::Settings {
1548 let channel = self.channel.trim();
1549 codewhale_cloud_facts::Settings {
1550 enabled: self.enabled,
1551 channel: if codewhale_cloud_facts::valid_channel(channel) {
1552 channel.to_string()
1553 } else {
1554 default_cloud_facts_channel()
1555 },
1556 url: self
1557 .url
1558 .as_deref()
1559 .map(str::trim)
1560 .filter(|u| !u.is_empty())
1561 .map(str::to_string),
1562 ttl_secs: self.ttl_hours.max(1).saturating_mul(3600),
1563 ..codewhale_cloud_facts::Settings::default()
1564 }
1565 .resolve()
1566 }
1567}
1568
1569#[derive(Debug, Clone, Copy, Deserialize, Default, PartialEq, Eq)]
1571#[serde(rename_all = "snake_case")]
1572pub enum ApprovalDefaultSelection {
1573 #[default]
1575 Deny,
1576 AllowOnce,
1578}
1579
1580#[derive(Debug, Clone, Copy, Deserialize, Default, PartialEq, Eq)]
1584pub struct ApprovalConfig {
1585 #[serde(default)]
1588 pub default_selection: ApprovalDefaultSelection,
1589 #[serde(default)]
1595 pub timeout_seconds: Option<u64>,
1596}
1597
1598#[derive(Debug, Clone, Deserialize)]
1604#[serde(untagged)]
1605pub enum RawProseMeasure {
1606 Integer(i64),
1607 Float(f64),
1608 Boolean(bool),
1609 Text(String),
1610}
1611
1612impl RawProseMeasure {
1613 fn describe(&self) -> String {
1615 match self {
1616 Self::Integer(value) => value.to_string(),
1617 Self::Float(value) => value.to_string(),
1618 Self::Boolean(value) => value.to_string(),
1619 Self::Text(value) => format!("'{value}'"),
1620 }
1621 }
1622}
1623
1624#[derive(Debug, Clone, Default, Deserialize)]
1626#[serde(deny_unknown_fields)]
1627pub struct TranscriptConfig {
1628 #[serde(default)]
1636 pub prose_measure: Option<RawProseMeasure>,
1637}
1638
1639impl TranscriptConfig {
1640 fn prose_measure_columns(&self) -> Result<Option<u16>, String> {
1645 match &self.prose_measure {
1646 None | Some(RawProseMeasure::Integer(0)) => Ok(None),
1647 Some(RawProseMeasure::Integer(columns)) if *columns > 0 => {
1648 Ok(Some((*columns).min(i64::from(u16::MAX)) as u16))
1649 }
1650 Some(raw) => Err(format!(
1651 "expected a positive whole number of columns \
1652 (0 or absent = full width), got {}",
1653 raw.describe()
1654 )),
1655 }
1656 }
1657}
1658
1659#[derive(Debug, Clone)]
1664pub struct AccountModelAccess {
1665 pub session_id: String,
1666 pub credential: crate::credentials::Credential,
1667 pub expires_at: i64,
1668 pub profile: Option<String>,
1669}
1670
1671pub trait ModelHttpPolicy: std::fmt::Debug + Send + Sync {
1672 fn configure(
1673 &self,
1674 builder: reqwest::ClientBuilder,
1675 base_url: &str,
1676 ) -> Result<reqwest::ClientBuilder>;
1677}
1678
1679#[derive(Debug, Clone, Default, Deserialize)]
1681pub struct Config {
1682 #[serde(skip)]
1683 pub model_http_policy: Option<std::sync::Arc<dyn ModelHttpPolicy>>,
1684 #[serde(skip)]
1685 pub account_profile: Option<String>,
1686 #[serde(skip)]
1688 pub plugin_oauth_read_only: bool,
1689 #[serde(skip)]
1691 pub account_model_access: std::sync::Arc<parking_lot::RwLock<Option<AccountModelAccess>>>,
1692 #[serde(skip)]
1693 pub session_provider_keys_only: bool,
1694 #[serde(skip)]
1695 pub session_provider_keys: std::sync::Arc<
1696 parking_lot::RwLock<HashMap<ProviderIdentity, (String, crate::credentials::Credential)>>,
1697 >,
1698 #[serde(skip)]
1699 pub required_account_model_owner: Option<String>,
1700 #[serde(skip)]
1703 pub extra_trusted_paths: Vec<std::path::PathBuf>,
1704 #[serde(
1706 default,
1707 deserialize_with = "codewhale_config::catalog::configured::deserialize_configured_models"
1708 )]
1709 pub custom_models: Option<Vec<codewhale_config::catalog::configured::ConfiguredModel>>,
1710 #[serde(default)]
1712 pub stop_words: Option<Vec<String>>,
1713 pub provider: Option<String>,
1714 #[serde(alias = "httpHeaders")]
1719 pub http_headers: Option<HashMap<String, String>>,
1720 pub title: Option<String>,
1728 #[serde(alias = "defaultTextModel")]
1729 pub default_text_model: Option<String>,
1730 #[serde(rename = "model", skip_serializing)]
1733 pub legacy_model: Option<String>,
1734 #[serde(alias = "authMode")]
1735 pub auth_mode: Option<String>,
1736 pub reasoning_effort: Option<String>,
1739 #[serde(skip)]
1743 pub reasoning_effort_inferred_from_legacy_alias: bool,
1744 #[serde(skip)]
1749 pub fleet_operator_route_applied: bool,
1750 #[serde(skip)]
1754 pub fleet_operator_reasoning_applied: bool,
1755 #[serde(skip)]
1759 pub migrated_deepseek_model_alias: Option<String>,
1760 #[serde(skip)]
1768 pub(crate) migrated_legacy_ollama_cloud_route: bool,
1769 #[serde(skip)]
1776 pub runtime_chat_isolated: bool,
1777 #[serde(skip)]
1784 pub runtime_thread_inference_unrelated: bool,
1785 #[serde(default)]
1788 pub tools: Option<ToolsConfig>,
1789 pub skills_dir: Option<String>,
1790 pub mcp_config_path: Option<String>,
1791 pub mcp_oauth_callback_port: Option<u16>,
1792 pub mcp_oauth_callback_url: Option<String>,
1793 pub notes_path: Option<String>,
1794 pub memory_path: Option<String>,
1795 pub strict_tool_mode: Option<bool>,
1799 pub instructions: Option<Vec<String>>,
1807 pub allow_shell: Option<bool>,
1808 pub prompt_suggestion: Option<bool>,
1811 #[serde(alias = "approvalPolicy")]
1812 pub approval_policy: Option<String>,
1813 #[serde(alias = "sandboxMode")]
1814 pub sandbox_mode: Option<String>,
1815 #[serde(alias = "sandboxNetworkAccess")]
1822 pub sandbox_network_access: Option<bool>,
1823 #[serde(default, alias = "projectInstructionImports")]
1829 pub project_instruction_imports: Vec<String>,
1830 #[serde(default, alias = "instructionBudget")]
1836 pub instruction_budget: Option<codewhale_config::instruction_budget::InstructionBudgetConfig>,
1837 #[serde(default)]
1842 pub telemetry: Option<bool>,
1843 #[serde(default, alias = "fallbackProviders")]
1844 pub fallback_providers: Vec<codewhale_config::ProviderKind>,
1845 pub yolo: Option<bool>,
1846 pub verbosity: Option<String>,
1847 #[serde(alias = "sandboxBackend")]
1851 pub sandbox_backend: Option<String>,
1852 #[serde(alias = "sandboxUrl")]
1854 pub sandbox_url: Option<String>,
1855 #[serde(alias = "sandboxApiKey")]
1857 pub sandbox_api_key: Option<String>,
1858 #[serde(alias = "preferBwrap")]
1867 pub prefer_bwrap: Option<bool>,
1868 #[serde(skip)]
1869 pub tool_launcher: Option<Vec<String>>,
1870 #[serde(default, alias = "bwrapRoRoots")]
1875 pub bwrap_ro_roots: Vec<std::path::PathBuf>,
1876 #[serde(default, alias = "bwrapDevRoots")]
1883 pub bwrap_dev_roots: Vec<std::path::PathBuf>,
1884 #[serde(default, alias = "sandboxDeniedReadPaths")]
1892 pub sandbox_denied_read_paths: Vec<std::path::PathBuf>,
1893 #[serde(default, alias = "sandboxReadDenylistDefaults")]
1901 pub sandbox_read_denylist_defaults: Option<bool>,
1902 #[serde(default, alias = "sandboxReadDenylistExempt")]
1906 pub sandbox_read_denylist_exempt: Vec<std::path::PathBuf>,
1907 #[serde(alias = "managedConfigPath")]
1908 pub managed_config_path: Option<String>,
1909 #[serde(alias = "requirementsPath")]
1910 pub requirements_path: Option<String>,
1911 #[serde(alias = "maxSubagents")]
1912 pub max_subagents: Option<usize>,
1913 pub retry: Option<RetryConfig>,
1914 pub stream: Option<StreamConfig>,
1915 pub features: Option<FeaturesToml>,
1916 #[serde(default)]
1918 pub extension_host: Option<ExtensionHostConfig>,
1919 #[serde(default)]
1921 pub plugins: Option<BTreeMap<String, PluginSettings>>,
1922
1923 #[serde(default)]
1927 pub auto_review: Option<AutoReviewConfig>,
1928
1929 pub tui: Option<TuiConfig>,
1931
1932 #[serde(default)]
1935 pub transcript: Option<TranscriptConfig>,
1936
1937 #[serde(default)]
1939 pub hooks: Option<HooksConfig>,
1940
1941 #[serde(default)]
1945 pub lifecycle_outbox: Option<codewhale_config::LifecycleOutboxToml>,
1946
1947 #[serde(default)]
1952 pub control_socket: Option<codewhale_config::ControlSocketToml>,
1953
1954 #[serde(default)]
1956 pub providers: Option<ProvidersConfig>,
1957
1958 #[serde(default)]
1960 pub notifications: Option<NotificationsConfig>,
1961
1962 #[serde(default)]
1965 pub approval: Option<ApprovalConfig>,
1966
1967 #[serde(default)]
1970 pub network: Option<codewhale_config::NetworkPolicyToml>,
1971
1972 #[serde(default)]
1975 pub verifier: Option<codewhale_config::VerifierConfigToml>,
1976
1977 #[serde(default)]
1980 pub advisor: Option<codewhale_config::AdvisorConfigToml>,
1981
1982 #[serde(default)]
1987 pub skills: Option<SkillsConfig>,
1988
1989 #[serde(default)]
1992 pub snapshots: Option<SnapshotsConfig>,
1993
1994 #[serde(default)]
1998 pub search: Option<SearchConfig>,
1999
2000 #[serde(default)]
2004 pub goal: Option<GoalConfig>,
2005
2006 #[serde(default)]
2010 pub reasoning_only: Option<ReasoningOnlyConfig>,
2011
2012 #[serde(default)]
2017 pub memory: Option<MemoryConfig>,
2018
2019 #[serde(default)]
2021 pub speech: Option<SpeechConfig>,
2022
2023 #[serde(default)]
2026 pub auto: Option<AutoConfig>,
2027
2028 #[serde(default)]
2031 pub hotbar: Option<Vec<codewhale_config::HotbarBindingToml>>,
2032
2033 #[serde(default)]
2036 pub update: Option<UpdateConfig>,
2037
2038 #[serde(default)]
2040 pub cloud_facts: Option<CloudFactsConfig>,
2041
2042 #[serde(default)]
2045 pub lsp: Option<codewhale_config::LspConfigToml>,
2046
2047 #[serde(default)]
2050 pub context: ContextConfig,
2051
2052 #[serde(default)]
2055 pub compaction: Option<CompactionSettings>,
2056
2057 #[serde(default)]
2059 pub fleet: Option<codewhale_config::FleetConfigToml>,
2060
2061 #[serde(default)]
2066 pub workflow: Option<codewhale_config::WorkflowConfigToml>,
2067
2068 #[serde(default)]
2070 pub subagents: Option<SubagentsConfig>,
2071
2072 #[serde(default)]
2077 pub runtime_api: Option<RuntimeApiConfig>,
2078
2079 #[serde(default)]
2082 pub workshop: Option<codewhale_config::WorkshopConfig>,
2083
2084 #[serde(default)]
2086 pub vision_model: Option<VisionModelConfig>,
2087
2088 #[serde(default)]
2094 pub redaction: Option<codewhale_config::redaction::RedactionToml>,
2095
2096 #[serde(skip)]
2099 pub loaded_config_path: Option<PathBuf>,
2100
2101 #[serde(skip)]
2106 pub network_layer_is_managed: bool,
2107
2108 #[serde(skip)]
2111 pub remembered_selection_scope: Option<bool>,
2112
2113 #[serde(skip)]
2116 pub environment_model_applied: bool,
2117
2118 #[serde(skip)]
2119 pub route_provenance: RouteProvenance,
2120
2121 pub route_preferences_version: Option<u32>,
2124
2125 #[serde(skip)]
2130 pub exec_policy_engine: ExecPolicyEngine,
2131
2132 #[serde(skip)]
2142 pub base_url_env_receipt: BaseUrlEnvReceipt,
2143
2144 #[serde(skip)]
2147 pub legacy_root: codewhale_config::legacy_root::LegacyRootMigration,
2148
2149 #[serde(skip)]
2151 legacy_root_custom_generation: Option<codewhale_config::credentials::CredentialGeneration>,
2152
2153 #[serde(default)]
2158 pub mini_window: Option<MiniWindowConfig>,
2159}
2160
2161#[derive(Debug, Clone, PartialEq, Deserialize)]
2167pub struct MiniWindowConfig {
2168 #[serde(default = "mini_default_keep_input")]
2171 pub keep_input: bool,
2172 #[serde(default)]
2174 pub keep_todo: bool,
2175 #[serde(default)]
2178 pub keep_sidebar: bool,
2179 #[serde(default)]
2181 pub keep_footer: bool,
2182 #[serde(default)]
2185 pub keep_header: bool,
2186}
2187
2188impl Default for MiniWindowConfig {
2189 fn default() -> Self {
2190 Self {
2191 keep_input: true,
2192 keep_todo: false,
2193 keep_sidebar: false,
2194 keep_footer: false,
2195 keep_header: false,
2196 }
2197 }
2198}
2199
2200fn mini_default_keep_input() -> bool {
2201 true
2202}
2203
2204#[derive(Debug, Clone, Default, PartialEq, Eq)]
2213pub enum BaseUrlEnvReceipt {
2214 #[default]
2219 Unrecorded,
2220 NoOwner,
2225 Route(ProviderKind, String),
2229}
2230
2231impl BaseUrlEnvReceipt {
2232 fn owns(&self, provider: ProviderKind, identity: &str) -> bool {
2234 match self {
2235 Self::Route(owner, owner_identity) => *owner == provider && owner_identity == identity,
2236 Self::Unrecorded | Self::NoOwner => false,
2237 }
2238 }
2239}
2240
2241#[derive(Debug, Clone, Default, Deserialize)]
2242pub struct AutoReviewConfig {
2243 #[serde(default)]
2244 pub disabled: bool,
2245 #[serde(default)]
2246 pub review_all_shell: bool,
2247 #[serde(default)]
2248 pub reviewer_model: Option<String>,
2249 #[serde(default)]
2250 pub allow: Vec<AutoReviewRuleConfig>,
2251 #[serde(default)]
2252 pub block: Vec<AutoReviewRuleConfig>,
2253 #[serde(default)]
2254 pub environment: Vec<String>,
2255}
2256
2257#[derive(Debug, Clone, Default, Deserialize)]
2258pub struct AutoReviewRuleConfig {
2259 pub id: Option<String>,
2260 #[serde(default, alias = "toolName", alias = "tool_name")]
2261 pub tool: Option<String>,
2262 #[serde(default, alias = "actionKind", alias = "action_kind")]
2263 pub action_kind: Option<String>,
2264 #[serde(default, alias = "textContains")]
2265 pub(crate) text_contains: Option<String>,
2266 pub reason: Option<String>,
2267}
2268
2269impl AutoReviewConfig {
2270 fn validate(&self) -> Result<()> {
2271 if let Some(reviewer_model) = self.reviewer_model.as_deref() {
2272 validate_auto_review_reviewer_model(reviewer_model)?;
2273 }
2274 validate_auto_review_rules("allow", &self.allow)?;
2275 validate_auto_review_rules("block", &self.block)?;
2276 validate_auto_review_environment(&self.environment)?;
2277 Ok(())
2278 }
2279}
2280
2281pub fn validate_auto_review_environment(entries: &[String]) -> Result<()> {
2282 for (index, entry) in entries.iter().enumerate() {
2283 let trimmed = entry.trim();
2284 if trimmed.is_empty() || entry.chars().any(char::is_control) {
2285 anyhow::bail!(
2286 "Invalid auto_review.environment[{index}]: expected a non-empty entry without control characters."
2287 );
2288 }
2289 }
2290 Ok(())
2291}
2292
2293pub fn validate_auto_review_reviewer_model(raw: &str) -> Result<()> {
2294 let trimmed = raw.trim();
2295 if trimmed.is_empty()
2296 || raw != trimmed
2297 || trimmed
2298 .chars()
2299 .any(|ch| ch.is_whitespace() || ch.is_control())
2300 {
2301 anyhow::bail!(
2302 "Invalid auto_review.reviewer_model: expected a non-empty model identifier without whitespace or control characters."
2303 );
2304 }
2305 Ok(())
2306}
2307
2308impl AutoReviewRuleConfig {
2309 fn has_matcher(&self) -> bool {
2310 self.tool
2311 .as_deref()
2312 .is_some_and(|value| !value.trim().is_empty())
2313 || self
2314 .action_kind
2315 .as_deref()
2316 .is_some_and(|value| !value.trim().is_empty())
2317 }
2318}
2319
2320fn validate_auto_review_rules(kind: &str, rules: &[AutoReviewRuleConfig]) -> Result<()> {
2321 for (index, rule) in rules.iter().enumerate() {
2322 if rule
2323 .text_contains
2324 .as_deref()
2325 .is_some_and(|value| !value.trim().is_empty())
2326 {
2327 anyhow::bail!(
2328 "Invalid auto_review.{kind}[{index}].text_contains: user-intent matching was retired; scope the rule with tool and/or action_kind."
2329 );
2330 }
2331 if !rule.has_matcher() {
2332 anyhow::bail!(
2333 "Invalid auto_review.{kind}[{index}]: set at least one of tool or action_kind."
2334 );
2335 }
2336 if let Some(action_kind) = rule.action_kind.as_deref() {
2337 let normalized = action_kind.trim().to_ascii_lowercase().replace('-', "_");
2338 if auto_review_action_kind_name(&normalized).is_none() {
2339 anyhow::bail!(
2340 "Invalid auto_review.{kind}[{index}].action_kind '{action_kind}': expected read, write, shell, external, publish, or destructive."
2341 );
2342 }
2343 if kind == "allow"
2344 && !matches!(
2345 normalized.as_str(),
2346 "read" | "write" | "shell" | "external" | "publish" | "destructive"
2347 )
2348 {
2349 anyhow::bail!(
2350 "Invalid auto_review.allow[{index}].action_kind '{action_kind}': this retired narrow kind cannot safely widen to a v0.9.8 decision class; replace it with an exact tool rule or a current action_kind."
2351 );
2352 }
2353 }
2354 }
2355 Ok(())
2356}
2357
2358#[must_use]
2361pub fn auto_review_action_kind_name(raw: &str) -> Option<&'static str> {
2362 match raw.trim().to_ascii_lowercase().replace('-', "_").as_str() {
2363 "read" | "mcp_read" => Some("read"),
2364 "write" => Some("write"),
2365 "shell" => Some("shell"),
2366 "external" | "network" | "git" | "mcp_action" | "browser" | "unknown" => Some("external"),
2367 "publish" => Some("publish"),
2368 "destructive" | "secret" => Some("destructive"),
2369 _ => None,
2370 }
2371}
2372
2373#[derive(Debug, Clone, Deserialize)]
2376#[serde(tag = "type", rename_all = "snake_case")]
2377pub enum ToolOverride {
2378 Script {
2381 path: String,
2383 #[serde(default)]
2385 args: Option<Vec<String>>,
2386 },
2387 Command {
2390 command: String,
2392 #[serde(default)]
2394 args: Option<Vec<String>>,
2395 },
2396 Disabled,
2399}
2400
2401#[derive(Debug, Clone, Deserialize)]
2404pub struct VisionModelConfig {
2405 #[serde(skip)]
2406 pub model_http_policy: Option<std::sync::Arc<dyn ModelHttpPolicy>>,
2407 pub model: String,
2409 #[serde(default)]
2411 pub api_key: Option<String>,
2412 #[serde(default)]
2414 pub base_url: Option<String>,
2415}
2416
2417#[derive(Debug, Clone, Deserialize, Default)]
2419pub struct RuntimeApiConfig {
2420 #[serde(default)]
2427 pub cors_origins: Option<Vec<String>>,
2428}
2429
2430#[derive(Debug, Clone, Deserialize, Default)]
2432pub struct SkillsConfig {
2433 #[serde(default)]
2434 pub bundled: BundledSkillsConfig,
2435 #[serde(default)]
2436 pub listing_max_description_chars: Option<usize>,
2437 #[serde(default)]
2438 pub listing_budget_fraction: Option<f64>,
2439 #[serde(default)]
2442 pub registry_url: Option<String>,
2443 #[serde(default)]
2446 pub max_install_size_bytes: Option<u64>,
2447 #[serde(default, alias = "scanCodewhaleOnly")]
2451 pub scan_codewhale_only: Option<bool>,
2452 #[serde(default)]
2455 pub flat_workspace_root: Option<bool>,
2456 #[serde(skip)]
2457 pub creator_skills: bool,
2458}
2459
2460#[derive(Debug, Clone, Copy, Deserialize, Default, PartialEq, Eq, Hash, Serialize)]
2461#[serde(rename_all = "lowercase")]
2462pub enum BundledSkillsInstall {
2463 #[default]
2464 Auto,
2465 All,
2466 None,
2467}
2468
2469#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq, Hash, Serialize)]
2470pub struct BundledSkillsConfig {
2471 pub install: Option<BundledSkillsInstall>,
2472 pub selected: Option<Vec<String>>,
2473 pub disabled: Option<Vec<String>>,
2474 pub explicit_only: Option<Vec<String>>,
2475}
2476
2477impl SkillsConfig {
2478 #[must_use]
2479 pub fn flat_workspace_root(&self) -> bool {
2480 self.flat_workspace_root.unwrap_or(false)
2481 }
2482
2483 #[must_use]
2486 pub fn scan_codewhale_only(&self) -> bool {
2487 self.scan_codewhale_only.unwrap_or(false)
2488 }
2489}
2490
2491#[derive(Debug, Clone, Default, Deserialize, Serialize)]
2492pub struct ProviderConfig {
2493 pub vendor: Option<String>,
2495 #[serde(alias = "apiKey")]
2496 pub api_key: Option<String>,
2497 #[serde(alias = "baseUrl")]
2498 pub base_url: Option<String>,
2499 pub model: Option<String>,
2500 #[serde(
2501 default,
2502 alias = "contextWindow",
2503 alias = "context_window_tokens",
2504 alias = "contextWindowTokens",
2505 alias = "context_length",
2506 alias = "contextLength"
2507 )]
2508 pub context_window: Option<u32>,
2509 #[serde(default, alias = "modelContextWindows")]
2514 pub model_context_windows: Option<std::collections::BTreeMap<String, u32>>,
2515 pub mode: Option<String>,
2516 #[serde(
2520 default,
2521 alias = "apiStyle",
2522 alias = "api_style",
2523 alias = "protocol",
2524 alias = "wire_format",
2525 alias = "wireFormat",
2526 alias = "dialect"
2527 )]
2528 pub wire: Option<String>,
2529 #[serde(default, alias = "responsesProfile")]
2531 pub responses_profile: Option<String>,
2532 #[serde(alias = "authMode")]
2533 pub auth_mode: Option<String>,
2534 #[serde(default)]
2536 pub oauth: Option<crate::oauth::PluginOAuthConfig>,
2537 #[serde(default, alias = "oauthCredentialGeneration")]
2540 pub oauth_credential_generation: Option<String>,
2541 #[serde(alias = "insecureSkipTlsVerify")]
2542 pub insecure_skip_tls_verify: Option<bool>,
2543 #[serde(default, alias = "allowInsecureHttp")]
2546 pub allow_insecure_http: Option<bool>,
2547 #[serde(alias = "httpHeaders")]
2548 pub http_headers: Option<HashMap<String, String>>,
2549 #[serde(alias = "pathSuffix")]
2550 pub path_suffix: Option<String>,
2551 #[serde(alias = "reasoningStyle", alias = "reasoningStreamStyle")]
2552 pub reasoning_stream_style: Option<String>,
2553 #[serde(
2554 default,
2555 alias = "max-concurrency",
2556 alias = "maxConcurrency",
2557 alias = "concurrency"
2558 )]
2559 pub max_concurrency: Option<usize>,
2560 pub auth: Option<codewhale_config::ProviderAuthSourceToml>,
2561 #[serde(default, alias = "externalCredentials")]
2564 pub external_credentials: Option<codewhale_config::ExternalCredentialConsentToml>,
2565 #[serde(default)]
2571 pub kind: Option<String>,
2572 #[serde(skip)]
2574 pub plugin_authority: Option<codewhale_config::PluginAuthority>,
2575 #[serde(default, alias = "apiKeyEnv")]
2579 pub api_key_env: Option<String>,
2580}
2581
2582impl ProviderConfig {
2583 #[must_use]
2589 pub fn is_openai_compatible_custom(&self) -> bool {
2590 self.kind.as_deref().is_some_and(|kind| {
2591 let normalized = kind.trim().to_ascii_lowercase().replace('_', "-");
2592 normalized == "openai-compatible"
2593 })
2594 }
2595}
2596
2597#[derive(Debug, Clone, Default, Deserialize)]
2598pub struct ProvidersConfig {
2599 #[serde(default)]
2600 pub deepseek: ProviderConfig,
2601 #[serde(default, alias = "deepseekCn")]
2602 pub deepseek_cn: ProviderConfig,
2603 #[serde(
2604 default,
2605 alias = "deepseek-anthropic",
2606 alias = "deepseekAnthropic",
2607 alias = "deepseek-claude",
2608 alias = "deepseek_claude"
2609 )]
2610 pub deepseek_anthropic: ProviderConfig,
2611 #[serde(default, alias = "nvidiaNim")]
2612 pub nvidia_nim: ProviderConfig,
2613 #[serde(default)]
2614 pub openai: ProviderConfig,
2615 #[serde(default)]
2616 pub atlascloud: ProviderConfig,
2617 #[serde(default, alias = "wanjieArk")]
2618 pub wanjie_ark: ProviderConfig,
2619 #[serde(default)]
2620 pub volcengine: ProviderConfig,
2621 #[serde(default)]
2622 pub openrouter: ProviderConfig,
2623 #[serde(default, alias = "orca_router", alias = "orca")]
2624 pub orcarouter: ProviderConfig,
2625 #[serde(
2626 default,
2627 alias = "xiaomi",
2628 alias = "mimo",
2629 alias = "xiaomimimo",
2630 alias = "xiaomiMimo"
2631 )]
2632 pub xiaomi_mimo: ProviderConfig,
2633 #[serde(default)]
2634 pub novita: ProviderConfig,
2635 #[serde(default)]
2636 pub fireworks: ProviderConfig,
2637 #[serde(default)]
2638 pub siliconflow: ProviderConfig,
2639 #[serde(
2640 default,
2641 alias = "siliconflow-CN",
2642 alias = "siliconflow-cn",
2643 alias = "siliconflowCn"
2644 )]
2645 pub siliconflow_cn: ProviderConfig,
2646 #[serde(default)]
2647 pub arcee: ProviderConfig,
2648 #[serde(default)]
2649 pub moonshot: ProviderConfig,
2650 #[serde(default)]
2651 pub sglang: ProviderConfig,
2652 #[serde(default)]
2653 pub vllm: ProviderConfig,
2654 #[serde(default)]
2655 pub ollama: ProviderConfig,
2656 #[serde(default, alias = "ollama-cloud", alias = "ollamaCloud")]
2657 pub ollama_cloud: ProviderConfig,
2658 #[serde(default, alias = "hugging-face", alias = "hf")]
2659 pub huggingface: ProviderConfig,
2660 #[serde(default, alias = "model-scope", alias = "model_scope")]
2661 pub modelscope: ProviderConfig,
2662 #[serde(default, alias = "deep-infra", alias = "deep_infra")]
2663 pub deepinfra: ProviderConfig,
2664 #[serde(default, alias = "together-ai")]
2665 pub together: ProviderConfig,
2666 #[serde(
2667 default,
2668 alias = "baidu-qianfan",
2669 alias = "baidu_qianfan",
2670 alias = "baidu"
2671 )]
2672 pub qianfan: ProviderConfig,
2673 #[serde(
2674 default,
2675 alias = "openai-codex",
2676 alias = "openaiCodex",
2677 alias = "codex",
2678 alias = "chatgpt"
2679 )]
2680 pub openai_codex: ProviderConfig,
2681 #[serde(default, alias = "claude")]
2682 pub anthropic: ProviderConfig,
2683 #[serde(default, alias = "open-model", alias = "open_model")]
2684 pub openmodel: ProviderConfig,
2685 #[serde(
2686 default,
2687 alias = "zhipu",
2688 alias = "zhipuai",
2689 alias = "bigmodel",
2690 alias = "big-model"
2691 )]
2692 pub zai: ProviderConfig,
2693 #[serde(default)]
2694 pub stepfun: ProviderConfig,
2695 #[serde(default)]
2696 pub minimax: ProviderConfig,
2697 #[serde(
2698 default,
2699 alias = "minimax-anthropic",
2700 alias = "minimaxAnthropic",
2701 alias = "mini-max-anthropic",
2702 alias = "mini_max_anthropic"
2703 )]
2704 pub minimax_anthropic: ProviderConfig,
2705 #[serde(default, alias = "sakana-ai", alias = "sakana_ai", alias = "fugu")]
2706 pub sakana: ProviderConfig,
2707 #[serde(
2708 default,
2709 alias = "long-cat",
2710 alias = "meituan-longcat",
2711 alias = "meituan"
2712 )]
2713 pub longcat: ProviderConfig,
2714 #[serde(default, alias = "opencode-go", alias = "opencodego")]
2715 pub opencode_go: ProviderConfig,
2716 #[serde(
2717 default,
2718 alias = "opencode-zen",
2719 alias = "opencodezen",
2720 alias = "zen",
2721 alias = "opencode"
2722 )]
2723 pub opencode_zen: ProviderConfig,
2724 #[serde(
2725 default,
2726 alias = "meta-ai",
2727 alias = "meta_ai",
2728 alias = "meta-model-api",
2729 alias = "meta_model_api",
2730 alias = "muse",
2731 alias = "muse-spark"
2732 )]
2733 pub meta: ProviderConfig,
2734 #[serde(default, alias = "x-ai", alias = "x_ai", alias = "grok")]
2735 pub xai: ProviderConfig,
2736 #[serde(
2737 default,
2738 alias = "mistral-ai",
2739 alias = "mistral_ai",
2740 alias = "mistralai",
2741 alias = "la-plateforme",
2742 alias = "la_plateforme"
2743 )]
2744 pub mistral: ProviderConfig,
2745 #[serde(
2746 default,
2747 alias = "google-gemini",
2748 alias = "google_gemini",
2749 alias = "gemini"
2750 )]
2751 pub google: ProviderConfig,
2752 #[serde(default, alias = "agy")]
2753 pub antigravity: ProviderConfig,
2754 #[serde(
2755 default,
2756 alias = "telecom-js",
2757 alias = "telecom_js",
2758 alias = "telecomjs-cn",
2759 alias = "tokenhub"
2760 )]
2761 pub telecomjs: ProviderConfig,
2762 #[serde(default, alias = "eden-ai", alias = "eden_ai")]
2764 pub edenai: ProviderConfig,
2765 #[serde(default, alias = "zen-mux", alias = "zen_mux")]
2767 pub zenmux: ProviderConfig,
2768 #[serde(
2770 default,
2771 alias = "csdn-ai",
2772 alias = "csdn_ai",
2773 alias = "csdn-coding-plan",
2774 alias = "csdn_coding_plan",
2775 alias = "starmap"
2776 )]
2777 pub csdn: ProviderConfig,
2778 #[serde(
2780 default,
2781 alias = "concentrate-ai",
2782 alias = "concentrate_ai",
2783 alias = "concentrateai"
2784 )]
2785 pub concentrate: ProviderConfig,
2786 #[serde(
2788 default,
2789 alias = "codewhale-api",
2790 alias = "codewhale_api",
2791 alias = "cw-api",
2792 alias = "codewhale-cloud"
2793 )]
2794 pub codewhale: ProviderConfig,
2795 #[serde(default, alias = "modelstudio-token-plan")]
2797 pub modelstudio_token_plan: ProviderConfig,
2798 #[serde(default, alias = "modelstudio-token-plan-anthropic")]
2800 pub modelstudio_token_plan_anthropic: ProviderConfig,
2801 #[serde(default, alias = "modelstudio-coding-plan")]
2803 pub modelstudio_coding_plan: ProviderConfig,
2804 #[serde(default, alias = "modelstudio-coding-plan-anthropic")]
2806 pub modelstudio_coding_plan_anthropic: ProviderConfig,
2807 #[serde(flatten, default)]
2814 pub custom: HashMap<String, ProviderConfig>,
2815}
2816
2817impl ProvidersConfig {
2818 #[must_use]
2821 pub fn custom_provider_config(&self, name: &str) -> Option<&ProviderConfig> {
2822 self.custom.get(name)
2823 }
2824
2825 fn validate(&self) -> Result<()> {
2826 let builtins = [
2827 ("providers.deepseek", &self.deepseek),
2828 ("providers.deepseek_cn", &self.deepseek_cn),
2829 ("providers.deepseek_anthropic", &self.deepseek_anthropic),
2830 ("providers.nvidia_nim", &self.nvidia_nim),
2831 ("providers.openai", &self.openai),
2832 ("providers.atlascloud", &self.atlascloud),
2833 ("providers.wanjie_ark", &self.wanjie_ark),
2834 ("providers.volcengine", &self.volcengine),
2835 ("providers.openrouter", &self.openrouter),
2836 ("providers.xiaomi_mimo", &self.xiaomi_mimo),
2837 ("providers.novita", &self.novita),
2838 ("providers.fireworks", &self.fireworks),
2839 ("providers.siliconflow", &self.siliconflow),
2840 ("providers.siliconflow_cn", &self.siliconflow_cn),
2841 ("providers.arcee", &self.arcee),
2842 ("providers.moonshot", &self.moonshot),
2843 ("providers.sglang", &self.sglang),
2844 ("providers.vllm", &self.vllm),
2845 ("providers.ollama", &self.ollama),
2846 ("providers.ollama_cloud", &self.ollama_cloud),
2847 ("providers.huggingface", &self.huggingface),
2848 ("providers.deepinfra", &self.deepinfra),
2849 ("providers.together", &self.together),
2850 ("providers.qianfan", &self.qianfan),
2851 ("providers.openai_codex", &self.openai_codex),
2852 ("providers.anthropic", &self.anthropic),
2853 ("providers.openmodel", &self.openmodel),
2854 ("providers.zai", &self.zai),
2855 ("providers.stepfun", &self.stepfun),
2856 ("providers.minimax", &self.minimax),
2857 ("providers.minimax_anthropic", &self.minimax_anthropic),
2858 ("providers.sakana", &self.sakana),
2859 ("providers.opencode_go", &self.opencode_go),
2860 ("providers.opencode_zen", &self.opencode_zen),
2861 ("providers.meta", &self.meta),
2862 ("providers.xai", &self.xai),
2863 ];
2864 for (name, config) in builtins {
2865 validate_provider_context_window(name, config.context_window)?;
2866 validate_model_context_windows(name, config.model_context_windows.as_ref())?;
2867 }
2868 for (name, config) in &self.custom {
2869 let name = format!("providers.{name}");
2870 validate_provider_context_window(&name, config.context_window)?;
2871 validate_model_context_windows(&name, config.model_context_windows.as_ref())?;
2872 }
2873 Ok(())
2874 }
2875}
2876
2877fn validate_provider_context_window(name: &str, value: Option<u32>) -> Result<()> {
2878 if value == Some(0) {
2879 anyhow::bail!("{name}.context_window must be greater than 0");
2880 }
2881 Ok(())
2882}
2883
2884fn validate_model_context_windows(
2885 name: &str,
2886 table: Option<&std::collections::BTreeMap<String, u32>>,
2887) -> Result<()> {
2888 if let Some(table) = table {
2889 for (model, window) in table {
2890 if *window == 0 {
2891 anyhow::bail!("{name}.model_context_windows.{model} must be greater than 0");
2892 }
2893 }
2894 }
2895 Ok(())
2896}
2897
2898#[derive(Debug, Clone, Deserialize, Default)]
2899struct ConfigFile {
2900 #[serde(flatten)]
2905 base: Box<Config>,
2906 profiles: Option<HashMap<String, Config>>,
2907 #[serde(skip)]
2908 legacy_root: codewhale_config::legacy_root::LegacyRootMigration,
2909}
2910
2911#[derive(Debug, Clone, Deserialize, Default)]
2912struct RequirementsFile {
2913 #[serde(default)]
2914 allowed_approval_policies: Vec<String>,
2915 #[serde(default)]
2916 allowed_sandbox_modes: Vec<String>,
2917}
2918
2919#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2927pub enum ApprovalPolicyControl {
2928 Unset,
2929 RootConfig,
2930 Profile,
2931 Environment,
2932 ManagedConfig,
2933 ProjectConfig,
2934 Requirements,
2935 Ambiguous,
2936}
2937
2938impl ApprovalPolicyControl {
2939 #[must_use]
2940 pub fn editable_root(self) -> bool {
2941 matches!(self, Self::Unset | Self::RootConfig)
2942 }
2943
2944 #[must_use]
2945 pub fn label(self) -> &'static str {
2946 match self {
2947 Self::Unset => "saved TUI posture",
2948 Self::RootConfig => "the root config.toml approval_policy",
2949 Self::Profile => "the active config profile",
2950 Self::Environment => {
2951 set_env_var_name(APPROVAL_POLICY_ENV).unwrap_or(APPROVAL_POLICY_ENV[0])
2952 }
2953 Self::ManagedConfig => "managed configuration",
2954 Self::ProjectConfig => "project configuration",
2955 Self::Requirements => "managed approval requirements",
2956 Self::Ambiguous => "an unresolved configuration source",
2957 }
2958 }
2959}
2960
2961#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2965pub enum ShellAccessControl {
2966 Unset,
2967 RootConfig,
2968 Profile,
2969 Environment,
2970 ManagedConfig,
2971 ProjectConfig,
2972 Ambiguous,
2973}
2974
2975impl ShellAccessControl {
2976 #[must_use]
2977 pub fn editable_root(self) -> bool {
2978 matches!(self, Self::Unset | Self::RootConfig)
2979 }
2980
2981 #[must_use]
2982 pub fn label(self) -> &'static str {
2983 match self {
2984 Self::Unset => "the session default",
2985 Self::RootConfig => "the root config.toml allow_shell",
2986 Self::Profile => "the active config profile",
2987 Self::Environment => set_env_var_name(ALLOW_SHELL_ENV).unwrap_or(ALLOW_SHELL_ENV[0]),
2988 Self::ManagedConfig => "managed configuration",
2989 Self::ProjectConfig => "project configuration",
2990 Self::Ambiguous => "an unresolved configuration source",
2991 }
2992 }
2993}
2994
2995const APPROVAL_POLICY_ENV: [&str; 2] = ["CODEWHALE_APPROVAL_POLICY", "DEEPSEEK_APPROVAL_POLICY"];
2996const ALLOW_SHELL_ENV: [&str; 2] = ["CODEWHALE_ALLOW_SHELL", "DEEPSEEK_ALLOW_SHELL"];
2997
2998fn set_env_var_name(names: [&'static str; 2]) -> Option<&'static str> {
3004 let read = || {
3005 names
3006 .into_iter()
3007 .find(|name| std::env::var_os(name).is_some())
3008 };
3009 #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
3010 {
3011 crate::test_support::with_test_env_lock(read)
3012 }
3013 #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
3014 {
3015 read()
3016 }
3017}
3018
3019fn approval_policy_env_is_set() -> bool {
3020 set_env_var_name(APPROVAL_POLICY_ENV).is_some()
3021}
3022
3023fn allow_shell_env_is_set() -> bool {
3024 set_env_var_name(ALLOW_SHELL_ENV).is_some()
3025}
3026
3027fn project_config_root_bool(workspace: &Path, key: &str) -> Option<bool> {
3028 [
3029 workspace
3030 .join(codewhale_config::CODEWHALE_APP_DIR)
3031 .join("config.toml"),
3032 workspace
3033 .join(codewhale_config::LEGACY_APP_DIR)
3034 .join("config.toml"),
3035 ]
3036 .into_iter()
3037 .find(|path| path.exists())
3038 .and_then(|path| std::fs::read_to_string(path).ok())
3039 .and_then(|raw| toml::from_str::<toml::Value>(&raw).ok())
3040 .and_then(|document| document.get(key).and_then(toml::Value::as_bool))
3041}
3042
3043#[must_use]
3047pub fn approval_policy_baseline_from_permission_posture(
3048 posture: Option<&str>,
3049) -> Option<&'static str> {
3050 posture.and_then(
3051 |posture| match posture.trim().to_ascii_lowercase().as_str() {
3052 "ask" | "suggest" | "on-request" | "untrusted" => Some("on-request"),
3053 "accept-edits" | "accept_edits" | "acceptedits" | "edits" => Some("accept-edits"),
3054 "auto" | "auto-review" | "auto_review" => Some("auto"),
3055 "full" | "full-access" | "full_access" | "bypass" => Some("auto"),
3056 _ => None,
3057 },
3058 )
3059}
3060
3061impl Config {
3064 #[must_use]
3071 pub fn prefers_bwrap(&self) -> bool {
3072 self.prefer_bwrap.unwrap_or(true)
3073 }
3074
3075 #[must_use]
3076 pub fn stop_words(&self) -> Vec<String> {
3077 self.stop_words.clone().unwrap_or_else(default_stop_words)
3078 }
3079
3080 pub fn external_credential_consent_status(
3084 &self,
3085 identity: &ProviderIdentity,
3086 ) -> Option<codewhale_config::ExternalCredentialConsentStatus> {
3087 if identity.key.as_str() == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id {
3088 return None;
3089 }
3090 let provider = identity.provider;
3091 let (kind, source, path) = match provider {
3092 ProviderKind::OpenaiCodex => (
3093 codewhale_config::ProviderKind::OpenaiCodex,
3094 codewhale_config::ExternalCredentialSource::CodexCli,
3095 crate::oauth::auth_file_path(),
3096 ),
3097 ProviderKind::Xai => (
3098 codewhale_config::ProviderKind::Xai,
3099 codewhale_config::ExternalCredentialSource::GrokCli,
3100 crate::oauth::grok_auth_file_path(),
3101 ),
3102 ProviderKind::Deepseek => (
3103 codewhale_config::ProviderKind::Deepseek,
3104 codewhale_config::ExternalCredentialSource::DshCli,
3105 codewhale_config::default_dsh_credentials_path(),
3106 ),
3107 ProviderKind::DeepseekAnthropic => (
3108 codewhale_config::ProviderKind::DeepseekAnthropic,
3109 codewhale_config::ExternalCredentialSource::DshCli,
3110 codewhale_config::default_dsh_credentials_path(),
3111 ),
3112 _ => return None,
3113 };
3114 self.verify_provider_identity(identity).ok()?;
3115 let active = self.active_provider_identity().ok()?;
3116 let consent = self
3117 .provider_config_for(identity)
3118 .and_then(|entry| entry.external_credentials.as_ref());
3119 let mut status = codewhale_config::external_credential_consent_status(
3120 consent,
3121 kind,
3122 source,
3123 &path,
3124 active.provider,
3125 );
3126 if active != *identity {
3127 status.route_state = "dormant";
3128 }
3129 Some(status)
3130 }
3131
3132 #[must_use]
3137 pub fn runtime_preset_blocker(
3138 &self,
3139 config_path: Option<&Path>,
3140 profile: Option<&str>,
3141 workspace: &Path,
3142 ) -> Option<&'static str> {
3143 let requirements_path = self
3144 .requirements_path
3145 .as_deref()
3146 .map(expand_path)
3147 .or_else(default_requirements_path);
3148 if let Some(path) = requirements_path
3149 && path.exists()
3150 {
3151 let controlled = std::fs::read_to_string(path)
3152 .ok()
3153 .and_then(|raw| toml::from_str::<RequirementsFile>(&raw).ok())
3154 .is_none_or(|requirements| {
3155 !requirements.allowed_approval_policies.is_empty()
3156 || !requirements.allowed_sandbox_modes.is_empty()
3157 });
3158 if controlled {
3159 return Some("managed runtime requirements");
3160 }
3161 }
3162
3163 let workspace_is_home = codewhale_paths::user_home().is_some_and(|home| {
3164 let workspace = workspace
3165 .canonicalize()
3166 .unwrap_or_else(|_| workspace.to_path_buf());
3167 let home = home.canonicalize().unwrap_or(home);
3168 workspace == home
3169 });
3170 let project_controls_runtime = || {
3171 let saved_approval_baseline = crate::settings::Settings::load_persisted()
3172 .ok()
3173 .and_then(|settings| settings.permission_posture)
3174 .and_then(|posture| {
3175 approval_policy_baseline_from_permission_posture(Some(&posture))
3176 });
3177 let approval_baseline = self.approval_policy.as_deref().or(saved_approval_baseline);
3178 let parsed_controls =
3179 codewhale_config::load_project_config(workspace).is_some_and(|project| {
3180 project.approval_policy.as_deref().is_some_and(|policy| {
3181 codewhale_config::project_approval_policy_is_allowed(
3182 approval_baseline,
3183 policy,
3184 )
3185 }) || project.sandbox_mode.as_deref().is_some_and(|sandbox| {
3186 codewhale_config::project_sandbox_mode_is_allowed(
3187 self.sandbox_mode.as_deref(),
3188 sandbox,
3189 )
3190 })
3191 });
3192 parsed_controls || project_config_root_bool(workspace, "allow_shell") == Some(false)
3193 };
3194 if !workspace_is_home && project_controls_runtime() {
3195 return Some("project runtime configuration");
3196 }
3197
3198 match managed_config_file(self.managed_config_path.as_deref()) {
3199 Err(_) => return Some("an unreadable managed runtime configuration"),
3200 Ok(None) => {}
3201 Ok(Some(path)) => match load_single_config_file(&path) {
3202 Ok(managed)
3203 if managed.approval_policy.is_some()
3204 || managed.sandbox_mode.is_some()
3205 || managed.allow_shell.is_some() =>
3206 {
3207 return Some("managed runtime configuration");
3208 }
3209 Err(_) => return Some("an unreadable managed runtime configuration"),
3210 Ok(_) => {}
3211 },
3212 }
3213
3214 let env_controls_runtime = || {
3215 approval_policy_env_is_set()
3216 || allow_shell_env_is_set()
3217 || std::env::var_os("CODEWHALE_SANDBOX_MODE").is_some()
3218 || std::env::var_os("DEEPSEEK_SANDBOX_MODE").is_some()
3219 };
3220 #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
3221 let env_controls_runtime = crate::test_support::with_test_env_lock(env_controls_runtime);
3222 #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
3223 let env_controls_runtime = env_controls_runtime();
3224 if env_controls_runtime {
3225 return Some("environment-controlled runtime posture");
3226 }
3227
3228 if let Some(profile) = profile {
3229 let path = match resolve_load_config_path(config_path.map(Path::to_path_buf)) {
3230 Ok(Some(path)) => path,
3231 Ok(None) => return Some("an unresolved active config profile"),
3232 Err(_) => return Some("an invalid active config path override"),
3233 };
3234 let Some(parsed) = std::fs::read_to_string(path)
3235 .ok()
3236 .and_then(|raw| parse_config_file(&raw).ok())
3237 else {
3238 return Some("an unreadable active config profile");
3239 };
3240 if parsed
3241 .profiles
3242 .as_ref()
3243 .and_then(|profiles| profiles.get(profile))
3244 .is_some_and(|profile| {
3245 profile.approval_policy.is_some()
3246 || profile.sandbox_mode.is_some()
3247 || profile.allow_shell.is_some()
3248 })
3249 {
3250 return Some("the active config profile");
3251 }
3252 }
3253
3254 None
3255 }
3256
3257 #[must_use]
3262 pub fn approval_policy_control(
3263 &self,
3264 config_path: Option<&Path>,
3265 profile: Option<&str>,
3266 workspace: &Path,
3267 ) -> ApprovalPolicyControl {
3268 if self.approval_policy_is_requirements_managed() {
3269 return ApprovalPolicyControl::Requirements;
3270 }
3271
3272 let workspace_is_home = codewhale_paths::user_home().is_some_and(|home| {
3273 let workspace = workspace
3274 .canonicalize()
3275 .unwrap_or_else(|_| workspace.to_path_buf());
3276 let home = home.canonicalize().unwrap_or(home);
3277 workspace == home
3278 });
3279 if !workspace_is_home {
3280 let saved_approval_baseline = crate::settings::Settings::load_persisted()
3281 .ok()
3282 .and_then(|settings| settings.permission_posture)
3283 .and_then(|posture| {
3284 approval_policy_baseline_from_permission_posture(Some(&posture))
3285 });
3286 let approval_baseline = self.approval_policy.as_deref().or(saved_approval_baseline);
3287 if codewhale_config::load_project_config(workspace)
3288 .and_then(|project| project.approval_policy)
3289 .is_some_and(|policy| {
3290 codewhale_config::project_approval_policy_is_allowed(approval_baseline, &policy)
3291 })
3292 {
3293 return ApprovalPolicyControl::ProjectConfig;
3294 }
3295 }
3296
3297 match managed_config_file(self.managed_config_path.as_deref()) {
3298 Err(_) => return ApprovalPolicyControl::Ambiguous,
3299 Ok(None) => {}
3300 Ok(Some(path)) => match load_single_config_file(&path) {
3301 Ok(managed) if managed.approval_policy.is_some() => {
3302 return ApprovalPolicyControl::ManagedConfig;
3303 }
3304 Err(_) => return ApprovalPolicyControl::Ambiguous,
3305 Ok(_) => {}
3306 },
3307 }
3308
3309 if approval_policy_env_is_set() {
3310 return ApprovalPolicyControl::Environment;
3311 }
3312
3313 let path = match resolve_load_config_path(config_path.map(Path::to_path_buf)) {
3314 Ok(Some(path)) => path,
3315 Ok(None) | Err(_) => {
3316 return if self.approval_policy.is_some() {
3317 ApprovalPolicyControl::Ambiguous
3318 } else {
3319 ApprovalPolicyControl::Unset
3320 };
3321 }
3322 };
3323 let parsed = std::fs::read_to_string(path)
3324 .ok()
3325 .and_then(|raw| parse_config_file(&raw).ok());
3326 let Some(parsed) = parsed else {
3327 return if self.approval_policy.is_some() {
3328 ApprovalPolicyControl::Ambiguous
3329 } else {
3330 ApprovalPolicyControl::Unset
3331 };
3332 };
3333 if let Some(profile) = profile
3334 && parsed
3335 .profiles
3336 .as_ref()
3337 .and_then(|profiles| profiles.get(profile))
3338 .is_some_and(|profile| profile.approval_policy.is_some())
3339 {
3340 return ApprovalPolicyControl::Profile;
3341 }
3342 if parsed.base.approval_policy.is_some() {
3343 ApprovalPolicyControl::RootConfig
3344 } else if self.approval_policy.is_some() {
3345 ApprovalPolicyControl::Ambiguous
3346 } else {
3347 ApprovalPolicyControl::Unset
3348 }
3349 }
3350
3351 #[must_use]
3355 pub fn allow_shell_control(
3356 &self,
3357 config_path: Option<&Path>,
3358 profile: Option<&str>,
3359 workspace: &Path,
3360 ) -> ShellAccessControl {
3361 let workspace_is_home = codewhale_paths::user_home().is_some_and(|home| {
3362 let workspace = workspace
3363 .canonicalize()
3364 .unwrap_or_else(|_| workspace.to_path_buf());
3365 let home = home.canonicalize().unwrap_or(home);
3366 workspace == home
3367 });
3368 if !workspace_is_home && project_config_root_bool(workspace, "allow_shell") == Some(false) {
3369 return ShellAccessControl::ProjectConfig;
3370 }
3371
3372 match managed_config_file(self.managed_config_path.as_deref()) {
3373 Err(_) => return ShellAccessControl::Ambiguous,
3374 Ok(None) => {}
3375 Ok(Some(path)) => match load_single_config_file(&path) {
3376 Ok(managed) if managed.allow_shell.is_some() => {
3377 return ShellAccessControl::ManagedConfig;
3378 }
3379 Err(_) => return ShellAccessControl::Ambiguous,
3380 Ok(_) => {}
3381 },
3382 }
3383
3384 if allow_shell_env_is_set() {
3385 return ShellAccessControl::Environment;
3386 }
3387
3388 let path = match resolve_load_config_path(config_path.map(Path::to_path_buf)) {
3389 Ok(Some(path)) => path,
3390 Ok(None) | Err(_) => {
3391 return if self.allow_shell.is_some() {
3392 ShellAccessControl::Ambiguous
3393 } else {
3394 ShellAccessControl::Unset
3395 };
3396 }
3397 };
3398 let parsed = std::fs::read_to_string(path)
3399 .ok()
3400 .and_then(|raw| parse_config_file(&raw).ok());
3401 let Some(parsed) = parsed else {
3402 return if self.allow_shell.is_some() {
3403 ShellAccessControl::Ambiguous
3404 } else {
3405 ShellAccessControl::Unset
3406 };
3407 };
3408 if let Some(profile) = profile
3409 && parsed
3410 .profiles
3411 .as_ref()
3412 .and_then(|profiles| profiles.get(profile))
3413 .is_some_and(|profile| profile.allow_shell.is_some())
3414 {
3415 return ShellAccessControl::Profile;
3416 }
3417 if parsed.base.allow_shell.is_some() {
3418 ShellAccessControl::RootConfig
3419 } else if self.allow_shell.is_some() {
3420 ShellAccessControl::Ambiguous
3421 } else {
3422 ShellAccessControl::Unset
3423 }
3424 }
3425
3426 #[must_use]
3432 pub fn approval_policy_is_requirements_managed(&self) -> bool {
3433 let path = self
3434 .requirements_path
3435 .as_deref()
3436 .map(expand_path)
3437 .or_else(default_requirements_path);
3438 let Some(path) = path else {
3439 return false;
3440 };
3441 if !path.exists() {
3442 return false;
3443 }
3444 std::fs::read_to_string(path)
3447 .ok()
3448 .and_then(|contents| toml::from_str::<RequirementsFile>(&contents).ok())
3449 .is_none_or(|requirements| {
3450 !requirements.allowed_approval_policies.is_empty()
3451 || !requirements.allowed_sandbox_modes.is_empty()
3452 })
3453 }
3454
3455 #[must_use]
3456 pub fn search_provider_resolution(&self) -> SearchProviderResolution {
3457 if let Ok(raw) = std::env::var("CODEWHALE_SEARCH_PROVIDER")
3458 .or_else(|_| std::env::var("DEEPSEEK_SEARCH_PROVIDER"))
3459 && let Some(provider) = SearchProvider::parse(&raw)
3460 {
3461 return SearchProviderResolution {
3462 provider,
3463 source: SearchProviderSource::EnvOverride,
3464 };
3465 }
3466
3467 if let Some(provider) = self.search.as_ref().and_then(|search| search.provider) {
3468 return SearchProviderResolution {
3469 provider,
3470 source: SearchProviderSource::Config,
3471 };
3472 }
3473
3474 let generic_key = self
3479 .search
3480 .as_ref()
3481 .and_then(|search| search.api_key.as_deref());
3482 if tavily_key_from(generic_key).is_some() {
3483 return SearchProviderResolution {
3484 provider: SearchProvider::Tavily,
3485 source: SearchProviderSource::TavilyKey,
3486 };
3487 }
3488
3489 SearchProviderResolution {
3490 provider: SearchProvider::default(),
3491 source: SearchProviderSource::Default,
3492 }
3493 }
3494
3495 #[must_use]
3496 pub fn search_provider(&self) -> SearchProvider {
3497 self.search_provider_resolution().provider
3498 }
3499
3500 #[must_use]
3507 pub fn search_native(&self) -> Option<bool> {
3508 self.search
3509 .as_ref()
3510 .and_then(|search| search.native)
3511 .or_else(|| {
3512 (self.search_provider_resolution().source != SearchProviderSource::Default)
3513 .then_some(false)
3514 })
3515 }
3516
3517 pub fn set_search_provider(&mut self, provider: SearchProvider) -> SearchProvider {
3520 self.search
3521 .get_or_insert_with(SearchConfig::default)
3522 .provider = Some(provider);
3523 self.search_provider()
3524 }
3525
3526 #[must_use]
3532 pub fn auto_cost_saving(&self) -> bool {
3533 self.auto
3534 .as_ref()
3535 .and_then(|a| a.cost_saving)
3536 .unwrap_or(false)
3537 }
3538
3539 #[must_use]
3545 pub fn auto_cross_provider(&self) -> bool {
3546 self.auto
3547 .as_ref()
3548 .and_then(|a| a.cross_provider)
3549 .unwrap_or(false)
3550 }
3551
3552 #[must_use]
3557 pub fn auto_router_timeout_secs(&self) -> u64 {
3558 self.auto
3559 .as_ref()
3560 .and_then(|a| a.router.as_ref())
3561 .and_then(|r| r.timeout_secs)
3562 .filter(|secs| *secs > 0)
3563 .unwrap_or(DEFAULT_AUTO_ROUTER_TIMEOUT_SECS)
3564 .min(MAX_AUTO_ROUTER_TIMEOUT_SECS)
3565 }
3566
3567 #[must_use]
3570 pub fn auto_router_min_confidence(&self) -> f64 {
3571 self.auto
3572 .as_ref()
3573 .and_then(|a| a.router.as_ref())
3574 .and_then(|r| r.min_confidence)
3575 .filter(|value| value.is_finite())
3576 .unwrap_or(DEFAULT_AUTO_ROUTER_MIN_CONFIDENCE)
3577 .clamp(0.0, 1.0)
3578 }
3579
3580 #[must_use]
3581 pub fn tools_always_load(&self) -> std::collections::HashSet<String> {
3582 self.tools
3583 .as_ref()
3584 .map(|tools| {
3585 tools
3586 .always_load
3587 .iter()
3588 .map(|name| name.trim())
3589 .filter(|name| !name.is_empty())
3590 .map(ToOwned::to_owned)
3591 .collect()
3592 })
3593 .unwrap_or_default()
3594 }
3595
3596 #[must_use]
3600 pub fn user_input_timeout(&self) -> Option<std::time::Duration> {
3601 const MAX_SECONDS: u64 = 86_400;
3602 let seconds = self
3603 .tools
3604 .as_ref()
3605 .and_then(|tools| tools.user_input_timeout_seconds)?;
3606 if seconds > MAX_SECONDS {
3607 tracing::warn!(
3608 "[tools] user_input_timeout_seconds={seconds} exceeds 24h; clamping to {MAX_SECONDS}"
3609 );
3610 }
3611 Some(std::time::Duration::from_secs(seconds.min(MAX_SECONDS)))
3612 }
3613
3614 #[must_use]
3618 pub fn task_human_wait_cap(&self) -> std::time::Duration {
3619 const DEFAULT_SECONDS: u64 = 30 * 60;
3620 const MAX_SECONDS: u64 = 86_400;
3621 let seconds = self
3622 .tools
3623 .as_ref()
3624 .and_then(|tools| tools.task_human_wait_cap_seconds)
3625 .filter(|seconds| *seconds > 0)
3626 .unwrap_or(DEFAULT_SECONDS);
3627 if seconds > MAX_SECONDS {
3628 tracing::warn!(
3629 "[tools] task_human_wait_cap_seconds={seconds} exceeds 24h; clamping to {MAX_SECONDS}"
3630 );
3631 }
3632 std::time::Duration::from_secs(seconds.min(MAX_SECONDS))
3633 }
3634
3635 #[cfg(any(test, feature = "test-support"))]
3645 pub fn load(path: Option<PathBuf>, profile: Option<&str>) -> Result<Self> {
3646 Self::load_with(path, profile, ConfigEnvironmentPolicy::Runtime, &mut |_| {
3647 Ok(())
3648 })
3649 }
3650
3651 #[cfg(any(test, feature = "test-support"))]
3658 pub fn load_structural(path: Option<PathBuf>, profile: Option<&str>) -> Result<Self> {
3659 Self::load_with(
3660 path,
3661 profile,
3662 ConfigEnvironmentPolicy::StructuralDiagnostic,
3663 &mut |_| Ok(()),
3664 )
3665 }
3666
3667 pub fn from_saved_document(contents: &str, profile: Option<&str>) -> Result<Self> {
3670 let parsed = parse_config_file(contents).map_err(|_| {
3671 anyhow::anyhow!("Failed to parse configuration; file contents were omitted")
3672 })?;
3673 let legacy_root = parsed.legacy_root.clone();
3674 let mut config = apply_profile(parsed, profile)?;
3675 config.account_profile = profile.map(str::to_owned);
3676 config.legacy_root = legacy_root;
3677 Ok(config)
3678 }
3679
3680 pub fn migrated_legacy_ollama_cloud_route(&self) -> bool {
3681 self.migrated_legacy_ollama_cloud_route
3682 }
3683
3684 pub fn load_with(
3685 path: Option<PathBuf>,
3686 profile: Option<&str>,
3687 environment_policy: ConfigEnvironmentPolicy,
3688 extend: &mut dyn FnMut(&mut Config) -> Result<()>,
3689 ) -> Result<Self> {
3690 let path = resolve_load_config_path(path)?;
3691 let mut config = if let Some(path) = path.as_ref() {
3692 if path.exists() {
3693 let contents = fs::read_to_string(path)
3694 .with_context(|| format!("Failed to read config file: {}", path.display()))?;
3695 let parsed = Self::from_saved_document(&contents, profile).with_context(|| {
3696 format!(
3697 "Failed to load config file {}",
3698 codewhale_config::quote_os_path(path)
3699 )
3700 })?;
3701 if let Some(msg) = warn_on_misplaced_top_level_keys(&contents) {
3702 tracing::warn!("{msg}");
3703 }
3704 if let Ok(document) = toml::from_str::<toml::Value>(&contents) {
3705 codewhale_config::reject_unmanaged_tool_launcher(&document, path)?;
3706 }
3707 parsed
3708 } else {
3709 apply_profile(ConfigFile::default(), profile)?;
3710 Config::default()
3711 }
3712 } else {
3713 apply_profile(ConfigFile::default(), profile)?;
3714 Config::default()
3715 };
3716
3717 config.account_profile = profile.map(str::to_owned);
3719 if profile.is_none() && path.as_deref().is_some_and(is_home_config_path) {
3721 if let Ok(settings) =
3722 crate::settings::Settings::load_legacy_route_preferences_read_only()
3723 {
3724 config.apply_saved_selection(&settings);
3725 }
3726 config.remembered_selection_scope = Some(true);
3727 } else {
3728 config.remembered_selection_scope = Some(false);
3729 }
3730 apply_env_overrides(&mut config, environment_policy);
3731 apply_managed_overrides(&mut config)?;
3732 apply_requirements(&mut config)?;
3733 extend(&mut config)?;
3734 normalize_model_config(&mut config);
3735 config.exec_policy_engine = load_sibling_exec_policy_engine(path.as_deref())?;
3736 config.loaded_config_path = path.as_deref().map(std::path::absolute).transpose()?;
3737 config.validate()?;
3738 Ok(config)
3739 }
3740
3741 #[cfg(any(test, feature = "test-support"))]
3742 pub fn remembered_selection_is_applicable(&self) -> bool {
3743 self.remembered_selection_scope.unwrap_or(true)
3744 }
3745
3746 pub fn legacy_selection_identity(
3749 &self,
3750 key: &str,
3751 ) -> std::result::Result<ProviderIdentity, String> {
3752 if let Ok(active) = self.active_provider_identity()
3753 && active.key.as_str() == key
3754 {
3755 Ok(active)
3756 } else {
3757 self.resolve_provider_pin_identity(key)
3758 }
3759 }
3760
3761 pub fn apply_saved_selection(&mut self, settings: &crate::settings::Settings) -> bool {
3765 if self.remembered_selection_scope.is_some() {
3766 return false;
3767 }
3768 self.remembered_selection_scope = Some(true);
3769 if self.default_text_model.is_none() {
3770 self.default_text_model.clone_from(&self.legacy_model);
3771 }
3772 if self.fleet_operator_route_applied || self.route_preferences_version.is_some() {
3773 return false;
3774 }
3775 let mut active_changed = false;
3776 if let Some(provider) = settings.default_provider.as_deref()
3777 && let Ok(identity) = self.resolve_provider_identity(provider)
3778 {
3779 active_changed = self
3780 .active_provider_identity()
3781 .is_ok_and(|active| active != identity);
3782 if self.scope_to_provider_identity(&identity).is_err() {
3783 return false;
3784 }
3785 self.route_provenance.provider_from_saved_selection = true;
3786 }
3787 let mut choices = settings.provider_models.clone().unwrap_or_default();
3788 if let Some(model) = settings.default_model.as_ref() {
3789 for key in [
3790 ProviderKind::Deepseek.as_str(),
3791 codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id,
3792 ] {
3793 choices.entry(key.into()).or_insert_with(|| model.clone());
3794 }
3795 }
3796 let mut choices: Vec<_> = choices.into_iter().collect();
3797 choices.sort_by_key(|(key, _)| {
3800 (
3801 self.legacy_selection_identity(key)
3802 .is_ok_and(|identity| identity.key.as_str() == key),
3803 key.clone(),
3804 )
3805 });
3806 for (key, remembered) in choices {
3807 let remembered = remembered.trim();
3808 if remembered.is_empty() || remembered.chars().any(char::is_control) {
3809 continue;
3810 }
3811 let Ok(identity) = self.legacy_selection_identity(&key) else {
3812 continue;
3813 };
3814 let provider = identity.provider;
3815 let mut scoped = self.clone();
3816 if scoped.scope_to_provider_identity(&identity).is_err() {
3817 continue;
3818 }
3819 let configured = scoped
3820 .provider_config_for(&identity)
3821 .and_then(|entry| entry.model.as_deref())
3822 .or_else(|| {
3823 self.active_provider_identity()
3824 .is_ok_and(|active| active == identity)
3825 .then_some(self.default_text_model.as_deref())
3826 .flatten()
3827 })
3828 .unwrap_or_default();
3829 let declared = configured_model_for_route(
3830 &scoped,
3831 provider,
3832 identity.key.as_str(),
3833 &scoped.base_url_for_route(&identity),
3834 remembered,
3835 )
3836 .is_some();
3837 let model = if declared {
3838 remembered.to_string()
3839 } else {
3840 prefer_configured_model_spelling(configured, remembered.to_string())
3841 };
3842 if provider == ProviderKind::Custom && identity.persisted_id().is_some() {
3843 if let Some(entry) = self
3844 .providers
3845 .as_mut()
3846 .and_then(|providers| providers.custom.get_mut(identity.key.as_str()))
3847 {
3848 entry.model = Some(model);
3849 }
3850 } else if identity.migrated_legacy_ollama_cloud_route {
3851 self.providers
3852 .get_or_insert_with(ProvidersConfig::default)
3853 .ollama
3854 .model = Some(model);
3855 } else {
3856 self.set_provider_model_override(&identity, Some(model))
3857 .unwrap();
3858 }
3859 let is_active = self
3860 .active_provider_identity()
3861 .is_ok_and(|active| active == identity);
3862 if is_active {
3863 self.route_provenance.model_from_saved_selection = true;
3864 }
3865 active_changed |= is_active;
3866 }
3867 active_changed
3868 }
3869
3870 pub fn validate(&self) -> Result<()> {
3872 if let Some(skills) = &self.skills {
3873 if skills
3874 .listing_max_description_chars
3875 .is_some_and(|value| !(1..=40_000).contains(&value))
3876 {
3877 anyhow::bail!("[skills] listing_max_description_chars must be between 1 and 40000");
3878 }
3879 if skills
3880 .listing_budget_fraction
3881 .is_some_and(|value| !value.is_finite() || value <= 0.0 || value > 1.0)
3882 {
3883 anyhow::bail!(
3884 "[skills] listing_budget_fraction must be finite and greater than 0 and at most 1"
3885 );
3886 }
3887 }
3888 if let Some(retry) = &self.retry {
3889 for (key, value) in [
3890 ("initial_delay", retry.initial_delay),
3891 ("max_delay", retry.max_delay),
3892 ("exponential_base", retry.exponential_base),
3893 ] {
3894 if value.is_some_and(|value| !value.is_finite() || value < 0.0) {
3895 anyhow::bail!("[retry] {key} must be a finite number of at least 0");
3896 }
3897 }
3898 }
3899 if let Some(budget) = self.instruction_budget.as_ref() {
3900 budget
3901 .validate()
3902 .map_err(|error| anyhow::anyhow!("invalid [instruction_budget]: {error}"))?;
3903 }
3904 if let Some(provider) = self.provider.as_deref()
3905 && !is_legacy_antigravity_identity(provider)
3906 && compatibility_for_selector(provider).is_none()
3907 && self
3908 .providers
3909 .as_ref()
3910 .and_then(|providers| providers.custom_provider_config(provider))
3911 .is_none()
3912 {
3913 return Err(invalid_provider_diagnostic(provider).into());
3914 }
3915 let identity = self
3916 .active_provider_identity()
3917 .map_err(anyhow::Error::msg)?;
3918 let active_provider = identity.provider;
3919 codewhale_config::catalog::configured::validate_configured_models(
3920 self.custom_models.as_deref().unwrap_or_default(),
3921 )?;
3922 self.openrouter_vendor()?;
3923 if self
3924 .provider
3925 .as_deref()
3926 .is_some_and(is_legacy_antigravity_identity)
3927 {
3928 anyhow::bail!(codewhale_config::LEGACY_ANTIGRAVITY_TOMBSTONE_MESSAGE);
3929 }
3930 match validate_kimi_code_api_model_id(
3931 active_provider,
3932 &self.active_route_base_url(),
3933 &self.default_model(),
3934 ) {
3935 Err(error) if error == KIMI_CODE_CLAUDE_ALIAS_GUIDANCE => {
3936 return Err(SafeConfigDiagnostic::KimiCodeClaudeAlias.into());
3937 }
3938 result => result.map_err(anyhow::Error::msg)?,
3939 }
3940 if let Some(features) = &self.features {
3941 for key in features.entries.keys() {
3942 if !is_known_feature_key(key) {
3943 anyhow::bail!("Unknown feature flag: {key}");
3944 }
3945 }
3946 }
3947 let configured_model = self
3948 .provider_config_string_with_runtime_fallback(&identity, |entry| entry.model.clone())
3949 .or_else(|| self.default_text_model.clone());
3950 if let Some(model) = configured_model.as_deref()
3951 && !model.trim().eq_ignore_ascii_case("auto")
3952 && !codewhale_config::descriptors::provider_passes_model_through(active_provider)
3953 && !self.active_provider_preserves_custom_base_url_model()
3954 && configured_model_for_route(
3955 self,
3956 active_provider,
3957 identity.key.as_str(),
3958 &self.base_url_for_route(&identity),
3959 model,
3960 )
3961 .is_none()
3962 && codewhale_config::route::resolve_model(active_provider, model, None).is_err()
3963 {
3964 let provider = active_provider;
3965 let known = model_completion_names_for_provider(provider);
3966 let hint = if known.is_empty() {
3967 String::new()
3968 } else {
3969 format!(" (for example: {})", known.join(", "))
3970 };
3971 return Err(SafeConfigDiagnostic::invalid_value(
3972 "model",
3973 model,
3974 &format!(
3975 "auto or a model ID provider '{}' serves{hint}",
3976 provider.as_str()
3977 ),
3978 user_config_fix("model", "auto", Some("a *_MODEL environment variable")),
3979 )
3980 .into());
3981 }
3982 for (key, value, replacement, env_var) in [
3985 (
3986 "approval_policy",
3987 self.approval_policy.as_deref(),
3988 "on-request",
3989 Some("CODEWHALE_APPROVAL_POLICY"),
3990 ),
3991 ("verbosity", self.verbosity.as_deref(), "normal", None),
3992 (
3993 "sandbox_mode",
3994 self.sandbox_mode.as_deref(),
3995 "workspace-write",
3996 Some("CODEWHALE_SANDBOX_MODE"),
3997 ),
3998 ] {
3999 let (Some(value), Some(choices)) = (value, codewhale_config::config_toml_choices(key))
4000 else {
4001 continue;
4002 };
4003 if !choices.contains(&value.trim().to_ascii_lowercase().as_str()) {
4004 let expected = match choices.split_last() {
4005 Some((last, [])) => (*last).to_string(),
4006 Some((last, [only])) => format!("{only} or {last}"),
4007 Some((last, rest)) => format!("{}, or {last}", rest.join(", ")),
4008 None => String::new(),
4009 };
4010 let displayed_value = codewhale_sanitize::redact::redact_secrets(value);
4011 return Err(SafeConfigDiagnostic::invalid_value(
4012 key,
4013 &displayed_value,
4014 &expected,
4015 user_config_fix(key, replacement, env_var),
4016 )
4017 .into());
4018 }
4019 }
4020 if let Some(tui) = &self.tui
4021 && let Some(mode) = tui.alternate_screen.as_deref()
4022 {
4023 let mode = mode.to_ascii_lowercase();
4024 if !matches!(mode.as_str(), "auto" | "always" | "never") {
4025 return Err(SafeConfigDiagnostic::invalid_value(
4026 "tui.alternate_screen",
4027 &mode,
4028 "auto, always, or never",
4029 user_config_fix("tui.alternate_screen", "auto", None),
4030 )
4031 .into());
4032 }
4033 }
4034 if let Some(transcript) = &self.transcript
4035 && let Err(detail) = transcript.prose_measure_columns()
4036 {
4037 anyhow::bail!("Invalid transcript.prose_measure: {detail}.");
4038 }
4039 if let Some(auto_review) = &self.auto_review {
4040 auto_review.validate()?;
4041 if auto_review.disabled
4042 && self
4043 .approval_policy
4044 .as_deref()
4045 .and_then(codewhale_execpolicy::ApprovalMode::from_config_value)
4046 == Some(codewhale_execpolicy::ApprovalMode::Auto)
4047 {
4048 anyhow::bail!(
4049 "approval_policy = \"auto\" is disabled by managed configuration (`auto_review.disabled = true`)"
4050 );
4051 }
4052 }
4053 if let Some(providers) = &self.providers {
4054 providers.validate()?;
4055 }
4056 Ok(())
4057 }
4058
4059 #[must_use]
4066 pub fn prose_measure(&self) -> Option<u16> {
4067 self.transcript
4068 .as_ref()
4069 .and_then(|transcript| transcript.prose_measure_columns().ok().flatten())
4070 }
4071
4072 #[must_use]
4073 fn selects_legacy_ollama_cloud_route(&self) -> bool {
4078 if self.migrated_legacy_ollama_cloud_route {
4079 return true;
4080 }
4081 if self.provider.as_deref().and_then(ProviderKind::parse) != Some(ProviderKind::Ollama) {
4082 return false;
4083 }
4084 self.legacy_ollama_cloud_route_configured()
4085 }
4086
4087 fn legacy_ollama_cloud_route_configured(&self) -> bool {
4091 let base_url = self
4092 .providers
4093 .as_ref()
4094 .and_then(|providers| providers.ollama.base_url.as_deref())
4095 .map(str::to_string)
4096 .or_else(|| first_nonempty_env(&["OLLAMA_BASE_URL"]));
4097 base_url.is_some_and(|base_url| {
4098 codewhale_config::provider::migrates_legacy_ollama_cloud_route(
4099 codewhale_config::ProviderKind::Ollama,
4100 &base_url,
4101 )
4102 })
4103 }
4104
4105 pub fn active_provider_identity(&self) -> std::result::Result<ProviderIdentity, String> {
4107 let selected = self
4108 .provider
4109 .as_deref()
4110 .unwrap_or(ProviderKind::Deepseek.as_str());
4111 if self.migrated_legacy_ollama_cloud_route && selected == ProviderKind::OllamaCloud.as_str()
4112 {
4113 return self.resolve_persisted_provider_identity(
4114 Some(ProviderKind::OllamaCloud.as_str()),
4115 Some(ProviderKind::Ollama.as_str()),
4116 );
4117 }
4118 if is_legacy_antigravity_identity(selected) {
4121 return Ok(ProviderIdentity {
4122 provider: ProviderKind::Antigravity,
4123 key: ProviderId::from(ProviderKind::Antigravity.as_str()),
4124 exact_id: Some(ProviderId::from(ProviderKind::Antigravity.as_str())),
4125 migrated_legacy_ollama_cloud_route: false,
4126 legacy_root_custom_generation: None,
4127 });
4128 }
4129 if self.selects_literal_custom_provider()
4130 && self.current_legacy_root_custom_generation().is_some()
4131 {
4132 return self.resolve_persisted_provider_identity(Some("custom"), None);
4133 }
4134 self.resolve_provider_identity(selected)
4135 }
4136
4137 #[cfg(any(test, feature = "test-support"))]
4140 pub fn test_identity_for_kind(&self, kind: ProviderKind) -> ProviderIdentity {
4141 if let Ok(active) = self.active_provider_identity()
4142 && active.provider == kind
4143 {
4144 return active;
4145 }
4146 self.builtin_provider_identity(kind)
4147 .expect("test fixture must declare an admitted provider identity")
4148 }
4149
4150 pub fn provider_identities(&self) -> Vec<ProviderIdentity> {
4154 let active = self.active_provider_identity().ok();
4155 let mut identities = Vec::new();
4156 for row in codewhale_config::descriptors::provider_compatibility() {
4157 if row.kind == ProviderKind::Custom {
4158 continue;
4159 }
4160 let identity = active
4161 .as_ref()
4162 .filter(|identity| identity.key.as_str() == row.id)
4163 .cloned()
4164 .or_else(|| self.resolve_provider_pin_identity(row.id).ok());
4165 if let Some(identity) = identity
4166 && identity.provider == row.kind
4167 && !identities
4168 .iter()
4169 .any(|existing: &ProviderIdentity| existing == &identity)
4170 {
4171 identities.push(identity);
4172 }
4173 }
4174 if let Some(active) = active
4175 && !identities.contains(&active)
4176 {
4177 identities.push(active);
4178 }
4179 if let Some(providers) = &self.providers {
4180 for key in providers.custom.keys() {
4181 if let Ok(identity) = self.resolve_provider_pin_identity(key)
4182 && !identities
4183 .iter()
4184 .any(|existing| existing.key == identity.key)
4185 {
4186 identities.push(identity);
4187 }
4188 }
4189 }
4190 identities
4191 }
4192
4193 pub fn unadmitted_provider_keys(&self) -> Vec<&str> {
4195 let admitted = self.provider_identities();
4196 let mut keys = Vec::new();
4197 if let Some(providers) = &self.providers {
4198 keys.extend(providers.custom.keys().map(String::as_str).filter(|key| {
4199 !admitted
4200 .iter()
4201 .any(|identity| identity.key.as_str() == *key)
4202 }));
4203 }
4204 if let Some(key) = self.provider.as_deref()
4205 && self.active_provider_identity().is_err()
4206 && !keys.contains(&key)
4207 {
4208 keys.push(key);
4209 }
4210 keys.sort_unstable();
4211 keys
4212 }
4213
4214 pub fn builtin_provider_identity(
4215 &self,
4216 kind: ProviderKind,
4217 ) -> std::result::Result<ProviderIdentity, String> {
4218 self.resolve_persisted_provider_identity(Some(kind.as_str()), Some(kind.as_str()))
4219 }
4220
4221 pub fn resolve_provider_identity(
4230 &self,
4231 persisted: &str,
4232 ) -> std::result::Result<ProviderIdentity, String> {
4233 let key = persisted.trim();
4234 if key.is_empty() {
4235 return Err(
4236 "saved session has an empty provider identity; choose a valid session or repair its `metadata.model_provider` field"
4237 .to_string(),
4238 );
4239 }
4240
4241 let has_exact_custom_table = self
4242 .providers
4243 .as_ref()
4244 .and_then(|providers| providers.custom_provider_config(key))
4245 .is_some();
4246
4247 if !has_exact_custom_table
4248 && let Some(row) = compatibility_for_selector(key)
4249 && row.kind != ProviderKind::Antigravity
4250 && row.kind != ProviderKind::Custom
4251 {
4252 let mut provider = row.kind;
4253 let migrated_legacy_ollama_cloud_route =
4254 provider == ProviderKind::Ollama && self.legacy_ollama_cloud_route_configured();
4255 if provider == ProviderKind::Ollama && migrated_legacy_ollama_cloud_route {
4256 provider = ProviderKind::OllamaCloud;
4257 }
4258 return Ok(ProviderIdentity {
4259 provider,
4260 key: ProviderId::from(if migrated_legacy_ollama_cloud_route {
4261 provider.as_str()
4262 } else {
4263 row.id
4264 }),
4265 exact_id: Some(if migrated_legacy_ollama_cloud_route {
4266 ProviderId::from(ProviderKind::Ollama.as_str())
4267 } else {
4268 ProviderId::from(row.id)
4269 }),
4270 migrated_legacy_ollama_cloud_route,
4271 legacy_root_custom_generation: None,
4272 });
4273 }
4274
4275 if !has_exact_custom_table && key.eq_ignore_ascii_case(ProviderKind::Custom.as_str()) {
4276 if self.selects_literal_custom_provider() {
4277 return Err(
4282 "`provider = \"custom\"` requires a `[providers.custom]` table with a `base_url`; Codewhale will not use the custom-provider placeholder or fall back"
4283 .to_string(),
4284 );
4285 }
4286
4287 if !self.selects_literal_custom_provider() {
4292 let selected = self.provider.as_deref().map(str::trim).unwrap_or_default();
4293 let valid_named = self
4294 .providers
4295 .as_ref()
4296 .map(|providers| {
4297 providers
4298 .custom
4299 .keys()
4300 .filter(|name| {
4301 !name.eq_ignore_ascii_case(ProviderKind::Custom.as_str())
4302 && ProviderKind::parse(name).is_none()
4303 && self.resolve_provider_identity(name).is_ok()
4304 })
4305 .cloned()
4306 .collect::<Vec<_>>()
4307 })
4308 .unwrap_or_default();
4309 if let [name] = valid_named.as_slice()
4310 && selected == name
4311 {
4312 return self.resolve_provider_identity(name);
4313 }
4314 return Err(format!(
4315 "legacy session records only the generic `custom` provider kind, but the live config does not select exactly one valid named custom route (selected '{}', valid named routes: {}). Restore the original single `[providers.<name>]` route or repair the saved provider identity; Codewhale will not guess or fall back",
4316 if selected.is_empty() {
4317 "<unset>"
4318 } else {
4319 selected
4320 },
4321 valid_named.len()
4322 ));
4323 }
4324 }
4325
4326 let exact_key = key;
4327
4328 let entry = self
4329 .providers
4330 .as_ref()
4331 .and_then(|providers| providers.custom_provider_config(exact_key))
4332 .ok_or_else(|| {
4333 format!(
4334 "saved session requires custom provider '{exact_key}', but `[providers.{exact_key}]` is missing from the live config. Restore that exact table and retry; Codewhale will not fall back"
4335 )
4336 })?;
4337 if !entry.is_openai_compatible_custom() {
4338 return Err(format!(
4339 "saved session requires custom provider '{exact_key}', but `[providers.{exact_key}]` must set `kind = \"openai-compatible\"`. Fix the live config and retry; Codewhale will not fall back"
4340 ));
4341 }
4342 let base_url = entry
4343 .base_url
4344 .as_deref()
4345 .map(str::trim)
4346 .filter(|base_url| !base_url.is_empty())
4347 .ok_or_else(|| {
4348 format!(
4349 "saved session requires custom provider '{exact_key}', but `[providers.{exact_key}]` has no `base_url`. Fix the live config and retry; Codewhale will not fall back"
4350 )
4351 })?;
4352 let parsed = reqwest::Url::parse(base_url).map_err(|err| {
4353 format!(
4354 "saved session requires custom provider '{exact_key}', but `[providers.{exact_key}].base_url` is invalid: {err}. Fix the live config and retry; Codewhale will not fall back"
4355 )
4356 })?;
4357 if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
4358 return Err(format!(
4359 "saved session requires custom provider '{exact_key}', but `[providers.{exact_key}].base_url` must be an http(s) URL with a host. Fix the live config and retry; Codewhale will not fall back"
4360 ));
4361 }
4362
4363 Ok(ProviderIdentity {
4364 provider: ProviderKind::Custom,
4365 key: ProviderId::from(exact_key),
4366 exact_id: Some(ProviderId::from(exact_key)),
4367 migrated_legacy_ollama_cloud_route: false,
4368 legacy_root_custom_generation: None,
4369 })
4370 }
4371
4372 pub fn resolve_provider_pin_identity(
4382 &self,
4383 provider_id: &str,
4384 ) -> std::result::Result<ProviderIdentity, String> {
4385 let mut identity = self.resolve_provider_identity(provider_id)?;
4386 if provider_id
4387 .trim()
4388 .eq_ignore_ascii_case(ProviderKind::Custom.as_str())
4389 && !identity
4390 .key
4391 .as_str()
4392 .eq_ignore_ascii_case(ProviderKind::Custom.as_str())
4393 {
4394 return Err(format!(
4395 "an explicit provider pin must name the configured provider '{}'; `custom` is not a wildcard for a named provider",
4396 identity.key
4397 ));
4398 }
4399 if identity.provider == ProviderKind::OllamaCloud
4400 && ProviderKind::parse(provider_id.trim()) == Some(ProviderKind::OllamaCloud)
4401 {
4402 identity.migrated_legacy_ollama_cloud_route = false;
4403 }
4404 Ok(identity)
4405 }
4406
4407 pub fn resolve_provider_selection_identity(
4412 &self,
4413 provider_id: &str,
4414 ) -> std::result::Result<ProviderIdentity, String> {
4415 let requested = provider_id.trim();
4416 if !requested.is_empty()
4417 && compatibility_for_selector(requested).is_none()
4418 && !requested.eq_ignore_ascii_case(ProviderKind::Custom.as_str())
4419 && self
4420 .providers
4421 .as_ref()
4422 .and_then(|providers| providers.custom_provider_config(requested))
4423 .is_none()
4424 {
4425 return Err(invalid_provider_message(requested));
4426 }
4427 if is_legacy_antigravity_identity(requested) {
4428 return Err("Antigravity is retired and cannot be selected".to_string());
4429 }
4430 self.resolve_provider_pin_identity(provider_id)
4431 }
4432
4433 fn resolve_exact_provider_identity(
4436 &self,
4437 persisted: &str,
4438 ) -> std::result::Result<ProviderIdentity, String> {
4439 let id = persisted.trim();
4440 if id.is_empty() {
4441 return Err(
4442 "persisted provider route has an empty exact provider id; Codewhale will not guess or fall back"
4443 .to_string(),
4444 );
4445 }
4446 let has_exact_custom_table = self
4447 .providers
4448 .as_ref()
4449 .and_then(|providers| providers.custom_provider_config(id))
4450 .is_some();
4451 if id.eq_ignore_ascii_case(ProviderKind::Custom.as_str()) && !has_exact_custom_table {
4452 return Err(format!(
4453 "persisted provider route requires exact custom provider '{id}', but `[providers.{id}]` is missing from the live config. Restore that exact table and retry; Codewhale will not fall back"
4454 ));
4455 }
4456
4457 let identity = self.resolve_provider_identity(id)?;
4458 if identity.provider == ProviderKind::Custom && identity.persisted_id() != Some(id) {
4459 return Err(format!(
4460 "persisted provider route requires exact custom provider '{id}', but the live config does not provide that exact table. Restore `[providers.{id}]` and retry; Codewhale will not fall back"
4461 ));
4462 }
4463 Ok(identity)
4464 }
4465
4466 pub fn resolve_persisted_provider_identity(
4477 &self,
4478 provider_kind: Option<&str>,
4479 provider_id: Option<&str>,
4480 ) -> std::result::Result<ProviderIdentity, String> {
4481 let kind = provider_kind
4482 .map(str::trim)
4483 .filter(|value| !value.is_empty());
4484 let id = provider_id.map(str::trim);
4489
4490 let Some(kind) = kind else {
4491 return id.map_or_else(
4492 || {
4493 Err(
4494 "persisted provider route has neither a provider kind nor an exact provider id; Codewhale will not guess or fall back"
4495 .to_string(),
4496 )
4497 },
4498 |id| self.resolve_exact_provider_identity(id),
4499 );
4500 };
4501
4502 let source =
4503 compatibility_for_selector(kind).filter(|row| row.kind != ProviderKind::Antigravity);
4504 let Some(mut provider) = source.map(|row| row.kind) else {
4505 if let Some(id) = id
4509 && id != kind
4510 {
4511 return Err(format!(
4512 "persisted provider route has legacy identity '{kind}' but exact provider id '{id}'; repair the mismatched fields because Codewhale will not guess or fall back"
4513 ));
4514 }
4515 return match id {
4516 Some(id) => self.resolve_exact_provider_identity(id),
4517 None => self.resolve_provider_identity(kind),
4518 };
4519 };
4520 let migrated_legacy_ollama_cloud = (provider == ProviderKind::Ollama
4521 && self.legacy_ollama_cloud_route_configured())
4522 || (provider == ProviderKind::OllamaCloud
4523 && id.and_then(ProviderKind::parse) == Some(ProviderKind::Ollama)
4524 && self.legacy_ollama_cloud_route_configured());
4525 if migrated_legacy_ollama_cloud {
4526 provider = ProviderKind::OllamaCloud;
4527 }
4528
4529 if provider == ProviderKind::Custom {
4530 if let Some(id) = id {
4531 let identity = self.resolve_exact_provider_identity(id)?;
4532 if identity.provider != ProviderKind::Custom {
4533 return Err(format!(
4534 "persisted provider route declares generic kind 'custom' but exact provider id '{id}' resolves as built-in '{}'; use the matching built-in kind or restore `[providers.{id}]`. Codewhale will not guess or fall back",
4535 identity.provider.as_str()
4536 ));
4537 }
4538 return Ok(identity);
4539 }
4540
4541 let generation = self.current_legacy_root_custom_generation().filter(|_| self.selects_literal_custom_provider()).ok_or_else(|| {
4544 "legacy id-less `custom` route requires the unchanged root-scope migrated `base_url`; a table-only, conflicting, changed, or profile-only route cannot supply that provenance. Repair the saved exact provider id; Codewhale will not guess or fall back".to_string()
4545 })?;
4546 let mut identity =
4547 self.resolve_exact_provider_identity(ProviderKind::Custom.as_str())?;
4548 identity.exact_id = None;
4549 identity.legacy_root_custom_generation = Some(generation);
4550 return Ok(identity);
4551 }
4552
4553 let exact = id.and_then(compatibility_for_selector);
4554 if let Some(id) = id
4555 && (exact.is_none_or(|row| row.kind != provider)
4556 || source.is_some_and(|row| {
4557 row.id != row.kind.as_str() && exact.is_some_and(|exact| exact.id != row.id)
4558 }))
4559 && !(migrated_legacy_ollama_cloud
4560 && ProviderKind::parse(id) == Some(ProviderKind::Ollama))
4561 {
4562 return Err(format!(
4563 "persisted provider route declares built-in kind '{}' but exact provider id '{id}' names a different route; repair the mismatched fields because Codewhale will not guess or fall back",
4564 provider.as_str()
4565 ));
4566 }
4567
4568 let key = if migrated_legacy_ollama_cloud {
4569 provider.as_str()
4570 } else {
4571 exact.or(source).expect("parsed built-in compatibility").id
4572 };
4573
4574 if self
4580 .providers
4581 .as_ref()
4582 .and_then(|providers| providers.custom_provider_config(key))
4583 .is_some()
4584 {
4585 return Err(format!(
4586 "persisted provider route requires built-in '{}', but an exact `[providers.{}]` custom route shadows the same selector. Rename the custom route or update the saved provider kind/id pair; Codewhale will not guess or fall back",
4587 provider.as_str(),
4588 provider.as_str()
4589 ));
4590 }
4591
4592 Ok(ProviderIdentity {
4593 provider,
4594 key: ProviderId::from(key),
4595 exact_id: Some(if migrated_legacy_ollama_cloud {
4596 ProviderId::from(ProviderKind::Ollama.as_str())
4597 } else {
4598 ProviderId::from(key)
4599 }),
4600 migrated_legacy_ollama_cloud_route: migrated_legacy_ollama_cloud,
4601 legacy_root_custom_generation: None,
4602 })
4603 }
4604
4605 pub fn scope_to_provider_identity(
4608 &mut self,
4609 identity: &ProviderIdentity,
4610 ) -> std::result::Result<(), String> {
4611 self.verify_provider_identity(identity)?;
4612 self.migrated_legacy_ollama_cloud_route = identity.migrated_legacy_ollama_cloud_route;
4613 self.provider = Some(identity.key.to_string());
4614 Ok(())
4615 }
4616
4617 fn legacy_root_custom_table_generation(
4618 &self,
4619 ) -> Option<codewhale_config::credentials::CredentialGeneration> {
4620 let entry = self.providers.as_ref()?.custom.get("custom")?;
4621 let value = serde_json::to_value(entry).ok()?;
4622 Some(codewhale_config::credentials::CredentialGeneration::derive(
4623 "codewhale/legacy-root-custom-table/v1",
4624 &crate::hashing::canonical_json(&value),
4625 ))
4626 }
4627
4628 fn bind_legacy_root_custom_generation(&mut self) {
4629 use codewhale_config::legacy_root::{LegacyRootField, LegacyRootNote};
4630 let moved = self.legacy_root.notes.iter().any(|note| {
4631 matches!(note,
4632 LegacyRootNote::Moved { scope: None, field: LegacyRootField::BaseUrl, to }
4633 | LegacyRootNote::Merged { scope: None, field: LegacyRootField::BaseUrl, to }
4634 if to == "providers.custom"
4635 )
4636 });
4637 let conflicting = self.legacy_root.notes.iter().any(|note| {
4638 matches!(
4639 note,
4640 LegacyRootNote::Conflict {
4641 scope: None,
4642 field: LegacyRootField::BaseUrl,
4643 ..
4644 } | LegacyRootNote::DroppedEmpty {
4645 scope: None,
4646 field: LegacyRootField::BaseUrl
4647 }
4648 )
4649 });
4650 self.legacy_root_custom_generation =
4651 (moved && !conflicting && self.selects_literal_custom_provider())
4652 .then(|| self.legacy_root_custom_table_generation())
4653 .flatten();
4654 }
4655
4656 fn current_legacy_root_custom_generation(
4657 &self,
4658 ) -> Option<codewhale_config::credentials::CredentialGeneration> {
4659 let captured = self.legacy_root_custom_generation.as_ref()?;
4660 let current = self.legacy_root_custom_table_generation()?;
4661 (captured == ¤t).then_some(current)
4662 }
4663
4664 pub fn selects_literal_custom_provider(&self) -> bool {
4665 self.provider
4666 .as_deref()
4667 .map(str::trim)
4668 .is_some_and(|name| name.eq_ignore_ascii_case(ProviderKind::Custom.as_str()))
4669 }
4670
4671 #[cfg(test)]
4681 pub(crate) fn custom_identity_is_resolvable(&self, identity: &str) -> bool {
4682 self.custom_provider_entry_for_identity(identity).is_some()
4683 }
4684
4685 pub fn provider_wire_dialect(&self, identity: &ProviderIdentity) -> Option<&str> {
4692 self.provider_config_for(identity)?
4693 .wire
4694 .as_deref()
4695 .map(str::trim)
4696 .filter(|value| !value.is_empty())
4697 }
4698
4699 pub fn provider_responses_profile(&self, identity: &ProviderIdentity) -> Option<&str> {
4700 self.provider_config_for(identity)?
4701 .responses_profile
4702 .as_deref()
4703 .map(str::trim)
4704 .filter(|value| !value.is_empty())
4705 }
4706
4707 pub fn verify_provider_identity(
4708 &self,
4709 identity: &ProviderIdentity,
4710 ) -> std::result::Result<(), String> {
4711 let admitted = self.resolve_persisted_provider_identity(
4712 Some(identity.persisted_kind()),
4713 identity.persisted_id(),
4714 )?;
4715 if admitted == *identity {
4716 Ok(())
4717 } else {
4718 Err("provider identity changed before projection".into())
4719 }
4720 }
4721
4722 pub fn provider_config_for(&self, identity: &ProviderIdentity) -> Option<&ProviderConfig> {
4723 let providers = self.providers.as_ref()?;
4724 self.verify_provider_identity(identity).ok()?;
4725 if identity.provider == ProviderKind::Custom {
4726 return providers.custom_provider_config(identity.key.as_str());
4727 }
4728 let table = if identity.migrated_legacy_ollama_cloud_route {
4729 ProviderKind::Ollama.as_str()
4730 } else {
4731 identity.key.as_str()
4732 };
4733 codewhale_config::provider_config_table!(@read providers, table)
4734 }
4735
4736 pub fn openrouter_vendor(&self) -> Result<Option<String>> {
4738 let identity = self
4739 .active_provider_identity()
4740 .map_err(anyhow::Error::msg)?;
4741 let provider = identity.provider;
4742
4743 let Some(vendor) = self
4744 .provider_config_for(&identity)
4745 .and_then(|entry| entry.vendor.as_deref())
4746 else {
4747 return Ok(None);
4748 };
4749 let vendor = codewhale_config::validate_openrouter_vendor(vendor)?;
4750 if vendor.is_some() && provider != ProviderKind::Openrouter {
4751 anyhow::bail!("vendor is only supported by providers.openrouter");
4752 }
4753 Ok(vendor.map(str::to_string))
4754 }
4755
4756 pub fn subagent_provider_config(
4757 &self,
4758 identity: &ProviderIdentity,
4759 ) -> Option<&SubagentProviderConfig> {
4760 let providers = self.subagents.as_ref()?.providers.as_ref()?;
4761 providers.iter().find_map(|(key, config)| {
4762 let matches = if identity.provider == ProviderKind::Custom {
4763 key == identity.key.as_str()
4764 } else if let Some(row) = identity.compatibility() {
4765 let normalized = normalize_subagent_provider_key(key);
4766 compatibility_for_selector(key).is_some_and(|candidate| candidate.id == row.id)
4767 || normalized == normalize_subagent_provider_key(row.id)
4768 || row.subagent_aliases.contains(&normalized.as_str())
4769 } else {
4770 false
4771 };
4772 matches.then_some(config)
4773 })
4774 }
4775
4776 pub fn provider_config_for_mut(
4777 &mut self,
4778 identity: &ProviderIdentity,
4779 ) -> Result<&mut ProviderConfig> {
4780 self.verify_provider_identity(identity)
4781 .map_err(anyhow::Error::msg)?;
4782 let providers = self.providers.get_or_insert_with(ProvidersConfig::default);
4783 if identity.provider == ProviderKind::Custom {
4784 return providers
4785 .custom
4786 .get_mut(identity.key.as_str())
4787 .context("exact custom provider table missing before mutation");
4788 }
4789 let table = if identity.migrated_legacy_ollama_cloud_route {
4790 ProviderKind::Ollama.as_str()
4791 } else {
4792 identity.key.as_str()
4793 };
4794 codewhale_config::provider_config_table!(@write providers, table)
4795 .context("provider has no generated typed config table")
4796 }
4797
4798 pub fn set_provider_model_override(
4800 &mut self,
4801 identity: &ProviderIdentity,
4802 model: Option<String>,
4803 ) -> Result<()> {
4804 self.provider_config_for_mut(identity)?.model = model;
4805 if identity.legacy_root_custom_generation.is_some() {
4809 self.legacy_root_custom_generation = self.legacy_root_custom_table_generation();
4810 }
4811 Ok(())
4812 }
4813
4814 pub fn set_provider_base_url_override(
4816 &mut self,
4817 identity: &ProviderIdentity,
4818 base_url: Option<String>,
4819 ) -> Result<()> {
4820 self.provider_config_for_mut(identity)?.base_url = base_url;
4821 Ok(())
4822 }
4823
4824 pub fn set_provider_api_key_override(
4826 &mut self,
4827 identity: &ProviderIdentity,
4828 api_key: Option<String>,
4829 ) -> Result<()> {
4830 self.provider_config_for_mut(identity)?.api_key = api_key;
4831 Ok(())
4832 }
4833
4834 pub(crate) fn mark_codewhale_owned_xai_oauth(&mut self, generation: String) -> Result<()> {
4837 let identity = self
4838 .builtin_provider_identity(ProviderKind::Xai)
4839 .map_err(anyhow::Error::msg)?;
4840 let entry = self.provider_config_for_mut(&identity)?;
4841 entry.auth_mode = Some("oauth".to_string());
4842 entry.oauth_credential_generation = Some(generation);
4843 entry.external_credentials = None;
4844 Ok(())
4845 }
4846
4847 pub(crate) fn mark_codewhale_owned_chatgpt_oauth(&mut self, generation: String) -> Result<()> {
4850 let identity = self
4851 .builtin_provider_identity(ProviderKind::OpenaiCodex)
4852 .map_err(anyhow::Error::msg)?;
4853 let entry = self.provider_config_for_mut(&identity)?;
4854 entry.auth_mode = Some("oauth".to_string());
4855 entry.oauth_credential_generation = Some(generation);
4856 entry.external_credentials = None;
4857 Ok(())
4858 }
4859
4860 pub fn clear_codewhale_owned_chatgpt_oauth(&mut self) -> Result<()> {
4861 let identity = self
4862 .builtin_provider_identity(ProviderKind::OpenaiCodex)
4863 .map_err(anyhow::Error::msg)?;
4864 let entry = self.provider_config_for_mut(&identity)?;
4865 if entry
4866 .oauth_credential_generation
4867 .as_deref()
4868 .is_some_and(codewhale_config::is_valid_chatgpt_oauth_generation)
4869 {
4870 entry.oauth_credential_generation = None;
4871 if entry.auth_mode.as_deref() == Some("oauth") {
4872 entry.auth_mode = None;
4873 }
4874 }
4875 Ok(())
4876 }
4877
4878 pub fn refresh_provider_routes_from(&mut self, fresh: &Self) {
4885 self.custom_models.clone_from(&fresh.custom_models);
4886 self.provider.clone_from(&fresh.provider);
4887 self.http_headers.clone_from(&fresh.http_headers);
4888 self.default_text_model
4889 .clone_from(&fresh.default_text_model);
4890 self.legacy_model.clone_from(&fresh.legacy_model);
4891 self.remembered_selection_scope = fresh.remembered_selection_scope;
4892 self.route_preferences_version = fresh.route_preferences_version;
4893 self.environment_model_applied = fresh.environment_model_applied;
4894 self.auth_mode.clone_from(&fresh.auth_mode);
4895 self.fallback_providers
4896 .clone_from(&fresh.fallback_providers);
4897 self.retry.clone_from(&fresh.retry);
4898 self.providers.clone_from(&fresh.providers);
4899 self.base_url_env_receipt
4900 .clone_from(&fresh.base_url_env_receipt);
4901 self.legacy_root.clone_from(&fresh.legacy_root);
4902 self.legacy_root_custom_generation
4903 .clone_from(&fresh.legacy_root_custom_generation);
4904 self.reasoning_effort_inferred_from_legacy_alias =
4905 fresh.reasoning_effort_inferred_from_legacy_alias;
4906 self.migrated_deepseek_model_alias
4907 .clone_from(&fresh.migrated_deepseek_model_alias);
4908 }
4909
4910 #[must_use]
4919 pub fn provider_max_concurrency(&self, identity: &ProviderIdentity) -> Option<usize> {
4920 let provider = identity.provider;
4921 let configured = self
4922 .provider_config_for(identity)
4923 .and_then(|entry| entry.max_concurrency);
4924 match configured {
4925 Some(0) => None,
4926 Some(limit) => Some(limit.clamp(1, MAX_PROVIDER_REQUEST_CONCURRENCY)),
4927 None if provider == ProviderKind::Zai => Some(DEFAULT_ZAI_PROVIDER_MAX_CONCURRENCY),
4928 None => None,
4929 }
4930 }
4931
4932 pub fn provider_config(&self) -> Option<&ProviderConfig> {
4933 let identity = self.active_provider_identity().ok()?;
4934 self.provider_config_for(&identity)
4935 }
4936
4937 fn provider_config_string_with_runtime_fallback<F>(
4938 &self,
4939 identity: &ProviderIdentity,
4940 get: F,
4941 ) -> Option<String>
4942 where
4943 F: Fn(&ProviderConfig) -> Option<String>,
4944 {
4945 let provider = identity.provider;
4946 if let Some(value) = self.provider_config_for(identity).and_then(&get) {
4947 return Some(value);
4948 }
4949 if provider == ProviderKind::SiliconflowCN {
4950 return self
4951 .builtin_provider_identity(ProviderKind::Siliconflow)
4952 .ok()
4953 .as_ref()
4954 .and_then(|sibling| self.provider_config_for(sibling))
4955 .and_then(get);
4956 }
4957 None
4958 }
4959
4960 pub(crate) fn provider_route_string_with_deepseek_fallback<F>(
4967 &self,
4968 identity: &ProviderIdentity,
4969 get: F,
4970 ) -> Option<String>
4971 where
4972 F: Fn(&ProviderConfig) -> Option<String>,
4973 {
4974 if let Some(value) = self.provider_config_string_with_runtime_fallback(identity, &get) {
4975 return Some(value);
4976 }
4977 if identity.key.as_str() == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id
4978 && !matches!(
4979 &self.base_url_env_receipt,
4980 BaseUrlEnvReceipt::Route(ProviderKind::Deepseek, key) if key == ProviderKind::Deepseek.as_str()
4981 )
4982 {
4983 return self
4984 .builtin_provider_identity(ProviderKind::Deepseek)
4985 .ok()
4986 .as_ref()
4987 .and_then(|sibling| self.provider_config_for(sibling))
4988 .and_then(get)
4989 .filter(|value| !value.trim().is_empty());
4990 }
4991 None
4992 }
4993
4994 #[must_use]
4995 pub fn insecure_skip_tls_verify(&self) -> bool {
4996 self.provider_config()
4997 .and_then(|provider| provider.insecure_skip_tls_verify)
4998 .unwrap_or(false)
4999 }
5000
5001 #[must_use]
5006 pub fn allow_insecure_http(&self) -> bool {
5007 self.provider_config()
5008 .and_then(|provider| provider.allow_insecure_http)
5009 .unwrap_or(false)
5010 }
5011
5012 #[must_use]
5013 pub fn context_window_for_provider_config(&self, identity: &ProviderIdentity) -> Option<u32> {
5014 let provider = identity.provider;
5015 if let Some(window) = self
5016 .provider_config_for(identity)
5017 .and_then(|entry| entry.context_window)
5018 .filter(|window| *window > 0)
5019 {
5020 return Some(window);
5021 }
5022 if provider == ProviderKind::SiliconflowCN {
5023 return self
5024 .builtin_provider_identity(ProviderKind::Siliconflow)
5025 .ok()
5026 .as_ref()
5027 .and_then(|sibling| self.provider_config_for(sibling))
5028 .and_then(|entry| entry.context_window)
5029 .filter(|window| *window > 0);
5030 }
5031 None
5032 }
5033
5034 #[must_use]
5038 pub fn model_context_windows_for(
5039 &self,
5040 identity: &ProviderIdentity,
5041 ) -> Option<&std::collections::BTreeMap<String, u32>> {
5042 let provider = identity.provider;
5043 let table = self
5044 .provider_config_for(identity)
5045 .and_then(|entry| entry.model_context_windows.as_ref())
5046 .filter(|table| !table.is_empty());
5047 if table.is_some() {
5048 return table;
5049 }
5050 if provider == ProviderKind::SiliconflowCN {
5051 return self
5052 .builtin_provider_identity(ProviderKind::Siliconflow)
5053 .ok()
5054 .as_ref()
5055 .and_then(|sibling| self.provider_config_for(sibling))
5056 .and_then(|entry| entry.model_context_windows.as_ref())
5057 .filter(|table| !table.is_empty());
5058 }
5059 None
5060 }
5061
5062 #[must_use]
5063 pub fn http_headers(&self) -> HashMap<String, String> {
5064 let Ok(identity) = self.active_provider_identity() else {
5065 return HashMap::new();
5066 };
5067 let mut headers = self.http_headers.clone().unwrap_or_default();
5068 if let Some(provider_headers) = self
5069 .provider_config_for(&identity)
5070 .and_then(|provider| provider.http_headers.as_ref())
5071 {
5072 headers.extend(provider_headers.clone());
5073 }
5074 headers.retain(|name, value| !name.trim().is_empty() && !value.trim().is_empty());
5075 if auth_mode_disables_api_key(self.auth_mode_for_provider(&identity).as_deref()) {
5076 headers.retain(|name, _| !codewhale_config::is_upstream_auth_header(name));
5077 }
5078 headers
5079 }
5080
5081 fn active_configured_model_id(&self) -> Option<&str> {
5082 let identity = self.active_provider_identity().ok()?;
5083 self.provider_config_for(&identity)
5084 .and_then(|entry| entry.model.as_deref())
5085 .map(str::trim)
5086 .filter(|model| !model.is_empty())
5087 .or_else(|| {
5088 self.default_text_model
5089 .as_deref()
5090 .map(str::trim)
5091 .filter(|model| !model.is_empty())
5092 })
5093 }
5094
5095 pub fn active_deepseek_alias_deprecation(&self) -> Option<ModelAliasDeprecation> {
5099 let identity = self.active_provider_identity().ok()?;
5100 let provider = identity.provider;
5101
5102 if !matches!(
5103 provider,
5104 ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
5105 ) {
5106 return None;
5107 }
5108
5109 let alias = self
5110 .migrated_deepseek_model_alias
5111 .as_deref()
5112 .or_else(|| self.active_configured_model_id())?
5113 .trim()
5114 .to_ascii_lowercase();
5115 let base_url = self.active_route_base_url();
5121 if base_url_is_custom_for_provider(provider, &base_url) {
5122 return None;
5123 }
5124
5125 deepseek_alias_deprecation(&alias)
5126 }
5127
5128 pub fn root_model_alias_owned_by_outgoing(
5140 &self,
5141 incoming: &ProviderIdentity,
5142 ) -> Option<(ProviderIdentity, String)> {
5143 let value = self
5146 .default_text_model
5147 .as_deref()
5148 .or(self.legacy_model.as_deref())?
5149 .trim();
5150 if value.is_empty()
5151 || value.eq_ignore_ascii_case("auto")
5152 || value.chars().any(char::is_control)
5153 {
5154 return None;
5155 }
5156 let outgoing = self.active_provider_identity().ok()?;
5157 if outgoing == *incoming
5159 || (outgoing.provider == ProviderKind::Custom && outgoing.persisted_id().is_none())
5160 {
5161 return None;
5162 }
5163 let mut scoped = self.clone();
5164 scoped.scope_to_provider_identity(&outgoing).ok()?;
5165 if scoped
5166 .provider_config_for(&outgoing)
5167 .and_then(|entry| entry.model.as_deref())
5168 .is_some()
5169 {
5170 return None;
5171 }
5172 (scoped.default_model() == value).then(|| (outgoing, value.to_string()))
5173 }
5174
5175 fn select_configured_model(
5176 &self,
5177 identity: &ProviderIdentity,
5178 ) -> codewhale_config::ConfiguredModelSelection {
5179 let provider = identity.provider;
5180 let base_url = self.base_url_for_route(identity);
5181 let auth_mode = self.auth_mode_for_provider(identity);
5182 let provider_model = self
5183 .provider_config_string_with_runtime_fallback(identity, |entry| entry.model.clone());
5184 let codex_preferred = || {
5185 crate::codex_model_roster::cached_roster_for(self)
5186 .preferred_model_id()
5187 .map(str::to_owned)
5188 };
5189 let descriptor_default = Some(identity.compatibility().map_or("", |row| row.default_model));
5190 codewhale_config::resolve_configured_model(&codewhale_config::ConfiguredModelInputs {
5191 provider,
5192 provider_identity: identity.key.as_str(),
5193 base_url: &base_url,
5194 auth_mode: auth_mode.as_deref(),
5195 cli_model: None,
5196 env_model: None,
5197 provider_model: provider_model.as_deref(),
5198 default_text_model: self.default_text_model.as_deref(),
5199 legacy_root_model: self.legacy_model.as_deref(),
5200 custom_models: self.custom_models.as_deref(),
5201 codex_preferred_model: (provider == ProviderKind::OpenaiCodex)
5202 .then_some(&codex_preferred as &dyn Fn() -> Option<String>),
5203 descriptor_default,
5204 })
5205 }
5206
5207 #[must_use]
5208 pub fn default_model(&self) -> String {
5209 let Ok(identity) = self.active_provider_identity() else {
5210 return String::new();
5211 };
5212 self.select_configured_model(&identity)
5213 .resolved
5214 .map_or_else(|_| String::new(), |resolved| resolved.wire_id)
5215 }
5216
5217 #[must_use]
5218 pub fn default_model_uses_root_default_text_model(&self) -> bool {
5219 let Ok(identity) = self.active_provider_identity() else {
5220 return false;
5221 };
5222 let selection = self.select_configured_model(&identity);
5223 selection.resolved.is_ok()
5224 && matches!(
5225 selection.source,
5226 codewhale_config::ModelSource::RootDefaultTextModel
5227 | codewhale_config::ModelSource::RootModel
5228 )
5229 }
5230
5231 #[must_use]
5232 pub fn configured_model_error(&self) -> Option<String> {
5233 let identity = self.active_provider_identity().ok()?;
5234 let selection = self.select_configured_model(&identity);
5235 match selection.resolved {
5236 Ok(_) => None,
5237 Err(_) if !selection.source.is_explicit() && selection.raw.is_empty() => None,
5238 Err(error) => Some(codewhale_config::format_configured_model_error(
5239 identity.key.as_str(),
5240 &selection.raw,
5241 &error,
5242 )),
5243 }
5244 }
5245
5246 #[must_use]
5248 pub fn active_route_base_url(&self) -> String {
5249 self.active_provider_identity()
5250 .map(|identity| self.base_url_for_route(&identity))
5251 .unwrap_or_default()
5252 }
5253
5254 pub fn base_url_for_route(&self, identity: &ProviderIdentity) -> String {
5278 if self.verify_provider_identity(identity).is_err() {
5279 return String::new();
5280 }
5281 let provider = identity.provider;
5282 let provider_base = if provider == ProviderKind::Custom {
5283 self.provider_config_for(identity)
5284 .and_then(|entry| entry.base_url.clone())
5285 } else {
5286 self.provider_route_string_with_deepseek_fallback(identity, |entry| {
5287 entry.base_url.clone()
5288 })
5289 };
5290 let configured_base_url =
5296 provider_base.or_else(|| provider_env_base_url_override(provider));
5297 let entry = self.provider_config_for(identity);
5298 let mode = entry.and_then(|e| e.mode.as_deref());
5299 let wire = entry.and_then(|e| e.wire.as_deref());
5300 let base = if provider == ProviderKind::XiaomiMimo {
5301 let config_api_key = entry.and_then(|e| e.api_key.as_deref()).filter(|value| {
5302 classify_config_api_key_value(value) == ConfigApiKeyValueKind::Literal
5303 });
5304 let env_api_key =
5305 xiaomi_mimo_env_api_key_for_runtime(mode, configured_base_url.as_deref());
5306 let api_key = config_api_key.or(env_api_key.as_deref());
5307 resolve_xiaomi_mimo_base_url(configured_base_url, api_key, mode)
5308 } else if matches!(
5309 provider,
5310 ProviderKind::ModelstudioTokenPlan
5311 | ProviderKind::ModelstudioTokenPlanAnthropic
5312 | ProviderKind::ModelstudioCodingPlan
5313 | ProviderKind::ModelstudioCodingPlanAnthropic
5314 ) {
5315 resolve_modelstudio_base_url_for_tui(configured_base_url, provider, mode, wire)
5316 } else if matches!(
5317 provider,
5318 ProviderKind::Minimax | ProviderKind::MinimaxAnthropic
5319 ) {
5320 resolve_minimax_base_url_for_tui(configured_base_url, provider, wire)
5321 } else if matches!(
5322 provider,
5323 ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
5324 ) {
5325 resolve_deepseek_base_url_for_tui(configured_base_url, provider, wire)
5326 } else {
5327 configured_base_url
5328 .or_else(|| self.route_owned_generic_env_base_url(identity))
5329 .unwrap_or_else(|| {
5330 if provider == ProviderKind::Moonshot
5334 && self
5335 .provider_config_for(identity)
5336 .is_some_and(provider_config_uses_kimi_imported_token)
5337 {
5338 DEFAULT_KIMI_CODE_BASE_URL
5339 } else {
5340 identity.compatibility().map_or("", |row| row.base_url)
5341 }
5342 .to_string()
5343 })
5344 };
5345 normalize_base_url(&base)
5346 }
5347
5348 fn route_owned_generic_env_base_url(&self, identity: &ProviderIdentity) -> Option<String> {
5357 match &self.base_url_env_receipt {
5358 BaseUrlEnvReceipt::Unrecorded => env_base_url_override(),
5359 BaseUrlEnvReceipt::NoOwner => None,
5360 BaseUrlEnvReceipt::Route(..) => self
5361 .base_url_env_receipt
5362 .owns(identity.provider, identity.key.as_str())
5363 .then(env_base_url_override)
5364 .flatten(),
5365 }
5366 }
5367
5368 #[cfg(test)]
5374 fn custom_provider_entry_for_identity(&self, identity: &str) -> Option<&ProviderConfig> {
5375 let key = identity.trim();
5376 if key.is_empty() {
5377 return None;
5378 }
5379 self.providers.as_ref()?.custom_provider_config(key)
5380 }
5381
5382 fn active_provider_preserves_custom_base_url_model(&self) -> bool {
5383 self.active_provider_identity()
5384 .is_ok_and(|identity| self.provider_uses_custom_endpoint(&identity))
5385 }
5386
5387 pub fn provider_uses_custom_endpoint(&self, identity: &ProviderIdentity) -> bool {
5392 let provider = identity.provider;
5393 provider_preserves_custom_base_url_model(provider, &self.base_url_for_route(identity))
5394 }
5395
5396 pub fn config_credentials_are_bound_to_provider_endpoint(
5406 &self,
5407 identity: &ProviderIdentity,
5408 ) -> bool {
5409 !self
5410 .active_provider_identity()
5411 .is_ok_and(|active| active == *identity)
5412 || !self.active_base_url_is_environment_owned(identity)
5413 || !self.provider_uses_custom_endpoint(identity)
5414 }
5415
5416 fn active_base_url_is_environment_owned(&self, identity: &ProviderIdentity) -> bool {
5417 let provider = identity.provider;
5418 if !self
5419 .active_provider_identity()
5420 .is_ok_and(|active| active == *identity)
5421 {
5422 return false;
5423 }
5424 let route_key = identity.key.as_str();
5425 if self.base_url_env_receipt.owns(provider, route_key) {
5426 return true;
5427 }
5428
5429 if self.configured_base_url_for_provider(identity).is_some() {
5437 return false;
5438 }
5439 provider_env_base_url_override(provider).is_some()
5440 || (matches!(self.base_url_env_receipt, BaseUrlEnvReceipt::Unrecorded)
5441 && env_base_url_override().is_some())
5442 }
5443
5444 pub fn active_route_endpoint_configured(&self) -> bool {
5449 self.active_provider_identity().is_ok_and(|identity| {
5450 self.configured_base_url_for_provider(&identity).is_some()
5451 || self.active_base_url_is_environment_owned(&identity)
5452 })
5453 }
5454
5455 fn configured_base_url_for_provider(&self, identity: &ProviderIdentity) -> Option<String> {
5460 self.provider_route_string_with_deepseek_fallback(identity, |entry| entry.base_url.clone())
5461 .filter(|base| !base.trim().is_empty())
5462 }
5463
5464 pub fn model_ids_pass_through_for_provider(&self, identity: &ProviderIdentity) -> bool {
5473 let provider = identity.provider;
5474 codewhale_config::descriptors::provider_passes_model_through(provider)
5475 || self.provider_uses_custom_endpoint(identity)
5476 }
5477
5478 pub fn model_ids_pass_through(&self) -> bool {
5479 self.active_provider_identity()
5480 .is_ok_and(|identity| self.model_ids_pass_through_for_provider(&identity))
5481 }
5482
5483 pub fn auth_mode_for_provider(&self, identity: &ProviderIdentity) -> Option<String> {
5484 self.provider_config_string_with_runtime_fallback(identity, |entry| entry.auth_mode.clone())
5485 .or_else(|| {
5486 (self
5487 .active_provider_identity()
5488 .is_ok_and(|active| active == *identity))
5489 .then(|| self.auth_mode.clone())
5490 .flatten()
5491 })
5492 }
5493
5494 pub(crate) fn external_credential_read_grant(
5503 &self,
5504 identity: &ProviderIdentity,
5505 source: codewhale_config::ExternalCredentialSource,
5506 suggested_path: &Path,
5507 ) -> Result<codewhale_config::ExternalCredentialReadGrant> {
5508 anyhow::ensure!(
5509 identity.key.as_str() != codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id,
5510 "external credentials are unsupported for the legacy DeepSeek China route"
5511 );
5512 let provider = identity.provider;
5513 if !self
5514 .active_provider_identity()
5515 .is_ok_and(|active| active == *identity)
5516 {
5517 anyhow::bail!(
5518 "external credential access for {} is dormant until that provider is explicitly selected",
5519 provider.provider().display_name()
5520 );
5521 }
5522 let kind = provider;
5523 let consent = self
5524 .provider_config_for(identity)
5525 .and_then(|entry| entry.external_credentials.as_ref())
5526 .with_context(|| {
5527 format!(
5528 "External credentials owned by {} are disabled for {}. To allow read-only access to this exact file, run:\n codewhale auth external-consent --provider {} --mode read-only --path {}",
5529 source.as_str(),
5530 provider.provider().display_name(),
5531 kind.as_str(),
5532 codewhale_config::quote_os_path(suggested_path)
5533 )
5534 })?;
5535 consent
5536 .read_grant(kind, source, &consent.path)
5537 .map_err(|error| {
5538 anyhow::anyhow!(
5539 "external credential consent for {}: {error}",
5540 provider.provider().display_name()
5541 )
5542 })
5543 }
5544
5545 pub fn external_credential_read_consent_configured(
5549 &self,
5550 identity: &ProviderIdentity,
5551 source: codewhale_config::ExternalCredentialSource,
5552 ) -> bool {
5553 if identity.key.as_str() == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id {
5554 return false;
5555 }
5556 let provider = identity.provider;
5557 let kind = provider;
5558 let Some(consent) = self
5559 .provider_config_for(identity)
5560 .and_then(|entry| entry.external_credentials.as_ref())
5561 else {
5562 return false;
5563 };
5564 consent
5565 .validate_read_scope(kind, source, &consent.path)
5566 .is_ok()
5567 }
5568
5569 pub fn should_skip_secret_store_for_provider(&self, identity: &ProviderIdentity) -> bool {
5570 if self.verify_provider_identity(identity).is_err() {
5571 return true;
5572 }
5573 let provider = identity.provider;
5574 if provider == ProviderKind::Custom
5582 && !identity
5583 .key
5584 .as_str()
5585 .eq_ignore_ascii_case(ProviderKind::Custom.as_str())
5586 {
5587 return true;
5588 }
5589
5590 let auth_mode = self.auth_mode_for_provider(identity);
5591 if auth_mode_disables_api_key(auth_mode.as_deref()) {
5592 return true;
5593 }
5594 if self.provider_uses_custom_endpoint(identity) {
5595 let explicitly_authenticated_loopback = self
5600 .active_provider_identity()
5601 .is_ok_and(|active| active == *identity)
5602 && auth_mode_requires_api_key(auth_mode.as_deref())
5603 && base_url_uses_local_host(&self.active_route_base_url());
5604 if !explicitly_authenticated_loopback {
5605 return true;
5606 }
5607 }
5608 if auth_mode_requires_api_key(auth_mode.as_deref()) {
5609 return false;
5610 }
5611
5612 if provider == ProviderKind::Codewhale {
5617 return false;
5618 }
5619
5620 provider_route_is_keyless_self_hosted(provider, &self.base_url_for_route(identity))
5621 || (self
5622 .active_provider_identity()
5623 .is_ok_and(|active| active == *identity)
5624 && base_url_uses_local_host(&self.active_route_base_url()))
5625 }
5626
5627 pub fn bind_account_model_owner(&mut self, owner: &str) -> Result<()> {
5628 anyhow::ensure!(
5629 !owner.is_empty()
5630 && owner.len() <= 240
5631 && !owner.chars().any(|c| c.is_control() || c.is_whitespace()),
5632 "Invalid account model owner"
5633 );
5634 let access = self
5635 .account_model_access
5636 .read()
5637 .clone()
5638 .context("Connect account model access before running the Codewhale agent")?;
5639 self.account_model_access = std::sync::Arc::new(parking_lot::RwLock::new(Some(access)));
5640 self.required_account_model_owner = Some(owner.to_string());
5641 let identity = self
5642 .resolve_persisted_provider_identity(Some("codewhale"), Some("codewhale"))
5643 .map_err(anyhow::Error::msg)?;
5644 anyhow::ensure!(
5645 self.account_model_api_key(&identity).is_some(),
5646 "Codewhale agent model access must belong to the signed-in account"
5647 );
5648 Ok(())
5649 }
5650
5651 pub fn session_provider_api_key(&self, identity: &ProviderIdentity) -> Option<String> {
5652 self.verify_provider_identity(identity).ok()?;
5653 if self.should_skip_secret_store_for_provider(identity) {
5654 return None;
5655 }
5656 let endpoint = self.base_url_for_route(identity);
5657 self.session_provider_keys
5658 .read()
5659 .get(identity)
5660 .filter(|(bound_endpoint, _)| bound_endpoint == &endpoint)
5661 .map(|(_, credential)| credential.expose_secret().to_string())
5662 }
5663
5664 pub fn preserve_runtime_credentials(&mut self, current: &Self) {
5665 self.account_model_access = current.account_model_access.clone();
5666 self.session_provider_keys = current.session_provider_keys.clone();
5667 self.session_provider_keys_only = current.session_provider_keys_only;
5668 }
5669
5670 pub fn retain_compatible_session_keys(&self) {
5671 self.session_provider_keys
5672 .write()
5673 .retain(|identity, (endpoint, _)| {
5674 self.verify_provider_identity(identity).is_ok()
5675 && !self.should_skip_secret_store_for_provider(identity)
5676 && self.base_url_for_route(identity) == *endpoint
5677 });
5678 }
5679
5680 pub fn session_policy_without_key(
5681 &self,
5682 identity: &ProviderIdentity,
5683 ) -> Option<crate::credentials::CredentialSource> {
5684 use crate::credentials::{CredentialProbe, CredentialSource};
5685 if !self.session_provider_keys_only {
5686 return None;
5687 }
5688 let mode = self.auth_mode_for_provider(identity);
5689 if auth_mode_disables_api_key(mode.as_deref()) {
5690 return Some(CredentialSource::AuthModeNone);
5691 }
5692 let endpoint = self.base_url_for_route(identity);
5693 if identity.provider != ProviderKind::Codewhale
5694 && !auth_mode_requires_api_key(mode.as_deref())
5695 && !provider_uses_oauth_credentials(self, identity)
5696 && !self
5697 .provider_config_for(identity)
5698 .is_some_and(|entry| entry.oauth.is_some())
5699 && (provider_route_is_keyless_self_hosted(identity.provider, &endpoint)
5700 || base_url_uses_local_host(&endpoint))
5701 {
5702 return Some(CredentialSource::KeylessRoute { base_url: endpoint });
5703 }
5704 Some(CredentialSource::Missing {
5705 probed: vec![CredentialProbe::with_fix(
5706 "session-only provider key",
5707 "connect a session key to this Engine; stored credentials are disabled",
5708 )],
5709 })
5710 }
5711
5712 pub fn account_model_api_key(&self, identity: &ProviderIdentity) -> Option<String> {
5713 self.account_model_key_and_owner(identity)
5714 .map(|(key, _)| key)
5715 }
5716
5717 fn account_model_key_and_owner(&self, identity: &ProviderIdentity) -> Option<(String, String)> {
5718 let provider = identity.provider;
5719 if provider != ProviderKind::Codewhale
5722 || self.base_url_for_route(identity).trim_end_matches('/') != DEFAULT_CODEWHALE_BASE_URL
5723 || auth_mode_disables_api_key(self.auth_mode_for_provider(identity).as_deref())
5724 || self
5725 .provider_config_for(identity)
5726 .is_some_and(|entry| entry.auth.is_some() || entry.api_key_env.is_some())
5727 {
5728 return None;
5729 }
5730 if std::env::var(codewhale_secrets::account::ACCOUNT_API_BASE_ENV)
5731 .ok()
5732 .filter(|base| !base.trim().is_empty())
5733 .is_some_and(|base| {
5734 base.trim().trim_end_matches('/')
5735 != codewhale_secrets::account::DEFAULT_ACCOUNT_API_BASE
5736 })
5737 {
5738 return None;
5739 }
5740 let access = self.account_model_access.read().clone();
5741 let profile = self.account_profile.as_deref();
5742 if access.as_ref().is_some_and(|access| {
5743 codewhale_secrets::account::normalize_account_profile(access.profile.as_deref())
5744 != codewhale_secrets::account::normalize_account_profile(profile)
5745 }) {
5746 return None;
5747 }
5748 let secrets = codewhale_secrets::account::secure_account_session_secrets().ok()?;
5751 let snapshot = codewhale_secrets::account::AccountSessionStore::new(
5752 secrets,
5753 profile,
5754 codewhale_secrets::account::DEFAULT_ACCOUNT_API_BASE,
5755 )
5756 .snapshot()
5757 .ok()?;
5758 let now = chrono::Utc::now();
5759 let account = snapshot.runtime_info_at(now).ok()?;
5760 if access
5761 .as_ref()
5762 .is_some_and(|access| account.session_id.as_deref() != Some(access.session_id.as_str()))
5763 {
5764 return None;
5765 }
5766 if self
5767 .required_account_model_owner
5768 .as_ref()
5769 .is_some_and(|owner| account.account_id.as_ref() != Some(owner))
5770 {
5771 return None;
5772 }
5773 if !self.session_provider_keys_only
5774 && matches!(
5775 account.state,
5776 codewhale_secrets::account::AccountSessionState::Authenticated
5777 | codewhale_secrets::account::AccountSessionState::OfflineCached
5778 )
5779 && let Some(cached) = snapshot.device_access().ok()?
5780 && cached.expires_at > now.timestamp()
5781 && account.account_id.as_deref() == Some(cached.account_id.as_str())
5782 && account.session_id.as_deref() == Some(cached.session_id.as_str())
5783 {
5784 return Some((cached.credential, cached.account_id));
5785 }
5786 let access = access.filter(|access| access.expires_at > now.timestamp())?;
5787 let owner = account.account_id?;
5788 (account.state == codewhale_secrets::account::AccountSessionState::Authenticated
5789 && account.session_id.as_deref() == Some(access.session_id.as_str()))
5790 .then(|| (access.credential.expose_secret().to_string(), owner))
5791 }
5792
5793 pub fn readonly_health_credential_generation(
5797 &self,
5798 identity: &ProviderIdentity,
5799 ) -> Option<codewhale_config::credentials::CredentialGeneration> {
5800 if self.required_account_model_owner.is_some() {
5801 return None;
5802 }
5803 self.verify_provider_identity(identity).ok()?;
5804 let mut scoped = self.clone();
5805 scoped.scope_to_provider_identity(identity).ok()?;
5806 let endpoint = scoped.base_url_for_route(identity);
5807 let mode = scoped.auth_mode_for_provider(identity);
5808 let generation = |value: &str| {
5809 codewhale_config::credentials::CredentialGeneration::derive(
5810 &endpoint,
5811 &codewhale_secrets::normalize_api_key(value),
5812 )
5813 };
5814 if let Some(key) = scoped.session_provider_api_key(identity) {
5815 return Some(generation(&key));
5816 }
5817 if let Some(source) = scoped.session_policy_without_key(identity) {
5818 return match source {
5819 crate::credentials::CredentialSource::AuthModeNone
5820 | crate::credentials::CredentialSource::KeylessRoute { .. } => Some(generation("")),
5821 _ => None,
5822 };
5823 }
5824 if auth_mode_disables_api_key(mode.as_deref()) {
5825 return Some(generation(""));
5826 }
5827 if provider_uses_oauth_credentials(&scoped, identity)
5828 || scoped
5829 .provider_config_for(identity)
5830 .is_some_and(|entry| entry.auth.is_some())
5831 {
5832 return None;
5833 }
5834 if let Some(key) = explicit_cli_api_key_override() {
5835 return Some(generation(&key));
5836 }
5837 if identity.provider == ProviderKind::Deepseek
5841 && cli_api_key_source().as_deref() == Some("cli")
5842 {
5843 return None;
5844 }
5845 if scoped.config_credentials_are_bound_to_provider_endpoint(identity)
5846 && let Some(key) = scoped
5847 .provider_route_string_with_deepseek_fallback(identity, |entry| {
5848 entry.api_key.clone()
5849 })
5850 && classify_config_api_key_value(&key) == ConfigApiKeyValueKind::Literal
5851 {
5852 return Some(generation(&key));
5853 }
5854 if let Some(key) = provider_config_env_api_key(&scoped, identity) {
5855 return Some(generation(&key));
5856 }
5857 if bound_provider_api_key_env_name(&scoped, identity).is_some() {
5859 return None;
5860 }
5861 if !auth_mode_requires_api_key(mode.as_deref())
5862 && scoped.should_skip_secret_store_for_provider(identity)
5863 && identity.provider != ProviderKind::Codewhale
5864 && scoped
5865 .provider_config_for(identity)
5866 .is_none_or(|entry| entry.external_credentials.is_none())
5867 && (provider_route_is_keyless_self_hosted(identity.provider, &endpoint)
5868 || base_url_uses_local_host(&endpoint))
5869 {
5870 return Some(generation(""));
5871 }
5872 None
5873 }
5874
5875 pub fn active_route_api_key(&self) -> Result<String> {
5885 self.active_route_api_key_with_source().map(|(key, _)| key)
5886 }
5887
5888 pub fn active_route_api_key_with_source(&self) -> Result<(String, String)> {
5893 self.active_route_api_key_with_secret_store_mode(false)
5894 }
5895
5896 pub fn active_route_api_key_with_owner(&self) -> Result<(ResolvedApiKey, Option<String>)> {
5897 let mut owner = None;
5898 let key = self.active_route_api_key_with_owner_and_mode(false, &mut owner)?;
5899 Ok((key, owner))
5900 }
5901
5902 pub fn xai_oauth_route_credentials(
5907 &self,
5908 ) -> Option<Result<crate::oauth::OwnedOAuthCredentials>> {
5909 let identity = self.active_provider_identity().ok()?;
5910 if self.required_account_model_owner.is_some()
5911 || self.session_provider_keys_only
5912 || self.session_provider_api_key(&identity).is_some()
5913 {
5914 return None;
5915 }
5916 let provider = identity.provider;
5917
5918 let selected = provider == ProviderKind::Xai
5919 && !self.provider_uses_custom_endpoint(&identity)
5920 && self
5921 .provider_config_for(&identity)
5922 .is_some_and(provider_config_uses_xai_oauth)
5923 && crate::oauth::credentials_present(crate::oauth::OAuthProvider::Xai, self);
5924 selected.then(|| crate::oauth::get_xai_credentials(self))
5925 }
5926
5927 pub fn active_route_api_key_read_only(&self) -> Result<String> {
5936 self.active_route_api_key_with_secret_store_mode(true)
5937 .map(|(key, _)| key)
5938 }
5939
5940 fn active_route_api_key_with_secret_store_mode(
5941 &self,
5942 read_only: bool,
5943 ) -> Result<(String, String)> {
5944 self.active_route_api_key_with_owner_and_mode(read_only, &mut None)
5945 }
5946
5947 fn active_route_api_key_with_owner_and_mode(
5948 &self,
5949 read_only: bool,
5950 account_owner: &mut Option<String>,
5951 ) -> Result<ResolvedApiKey> {
5952 self.resolve_active_route_api_key(read_only, account_owner)
5953 .map(|(key, source)| (codewhale_secrets::normalize_api_key(&key), source))
5954 }
5955
5956 pub fn with_read_only_api_key_for_diagnostic(&self) -> Result<Self> {
5965 let identity = self
5966 .active_provider_identity()
5967 .map_err(anyhow::Error::msg)?;
5968
5969 let mut diagnostic = self.clone();
5970 if self.session_provider_keys_only
5971 || (self.required_account_model_owner.is_none()
5972 && self.session_provider_api_key(&identity).is_some())
5973 {
5974 return Ok(diagnostic);
5975 }
5976 if identity.provider == ProviderKind::Anthropic
5977 && self.auth_mode_for_provider(&identity).as_deref() == Some("oauth")
5978 {
5979 diagnostic.plugin_oauth_read_only = true;
5980 return Ok(diagnostic);
5981 }
5982 if identity.provider == ProviderKind::Custom
5983 && self
5984 .provider_config_for(&identity)
5985 .is_some_and(|entry| entry.oauth.is_some())
5986 {
5987 diagnostic.plugin_oauth_read_only = true;
5988 return Ok(diagnostic);
5989 }
5990 let api_key = self.active_route_api_key_read_only()?;
5991 diagnostic.set_provider_api_key_override(&identity, Some(api_key))?;
5992 Ok(diagnostic)
5993 }
5994
5995 fn resolve_active_route_api_key(
5999 &self,
6000 read_only: bool,
6001 account_owner: &mut Option<String>,
6002 ) -> Result<ResolvedApiKey> {
6003 let identity = self
6004 .active_provider_identity()
6005 .map_err(anyhow::Error::msg)?;
6006 self.verify_provider_identity(&identity)
6007 .map_err(anyhow::Error::msg)?;
6008 if self.required_account_model_owner.is_some() {
6009 return self.account_model_key_and_owner(&identity)
6010 .map(|(key, owner)| {
6011 *account_owner = Some(owner);
6012 (key, "Codewhale account".to_string())
6013 })
6014 .context("The selected account model access is unavailable; no credential fallback is allowed");
6015 }
6016 if let Some(key) = self.session_provider_api_key(&identity) {
6017 return Ok((
6018 key,
6019 crate::credentials::CredentialSource::SessionKey
6020 .label()
6021 .into_owned(),
6022 ));
6023 }
6024 if let Some(source) = self.session_policy_without_key(&identity) {
6025 return match &source {
6026 crate::credentials::CredentialSource::AuthModeNone
6027 | crate::credentials::CredentialSource::KeylessRoute { .. } => {
6028 Ok((String::new(), source.label().into_owned()))
6029 }
6030 _ => anyhow::bail!(
6031 "This Engine requires a session provider key; stored credentials are disabled"
6032 ),
6033 };
6034 }
6035 let provider = identity.provider;
6036 let keyless = || (String::new(), "none (keyless route)".to_string());
6037
6038 if provider == ProviderKind::Antigravity {
6039 anyhow::bail!(codewhale_config::LEGACY_ANTIGRAVITY_TOMBSTONE_MESSAGE);
6040 }
6041 let auth_mode = self.auth_mode_for_provider(&identity);
6042 if provider == ProviderKind::Custom
6043 && let Some(entry) = self.provider_config_for(&identity)
6044 && let Some(oauth) = entry.oauth.as_ref()
6045 {
6046 entry
6047 .plugin_authority
6048 .as_ref()
6049 .context("Plugin OAuth route lacks an approved plugin authority")?;
6050 anyhow::ensure!(
6051 auth_mode.as_deref() == Some("oauth"),
6052 "Plugin OAuth route requires auth_mode = oauth"
6053 );
6054 self.provider
6055 .as_deref()
6056 .context("Plugin OAuth route has no provider name")?;
6057 oauth.validate()?;
6058 return Ok((String::new(), "host-managed plugin OAuth".to_string()));
6063 }
6064
6065 if codewhale_config::credentials::auth_mode_is_claude_org(auth_mode.as_deref()) {
6066 anyhow::ensure!(
6067 provider == ProviderKind::Anthropic
6068 && !self.provider_uses_custom_endpoint(&identity),
6069 "auth_mode = \"claude-org\" works only for the anthropic provider on its official endpoint; remove base_url or the auth_mode from [providers.{}]",
6070 identity.key.as_str()
6071 );
6072 return Ok((
6073 String::new(),
6074 codewhale_config::credentials::CLAUDE_ORG_KEY_SOURCE.to_string(),
6075 ));
6076 }
6077 if auth_mode_disables_api_key(auth_mode.as_deref()) {
6078 return Ok(keyless());
6079 }
6080 if provider == ProviderKind::Anthropic && auth_mode.as_deref() == Some("oauth") {
6081 anyhow::bail!(codewhale_config::credentials::CLAUDE_SIGN_IN_REMOVED);
6082 }
6083 let custom_endpoint = self.provider_uses_custom_endpoint(&identity);
6084 let explicit_cli_key = explicit_cli_api_key_override();
6085
6086 if matches!(provider, ProviderKind::Deepseek)
6093 && cli_api_key_source().as_deref() == Some("cli")
6094 && let Some((env_key, source)) = explicit_cli_key
6095 .as_ref()
6096 .cloned()
6097 .map(|key| (key, "--api-key (CLI)".to_string()))
6098 .or_else(|| {
6099 provider_env_api_key_named(provider)
6100 .map(|(name, key)| (key, format!("env var {name}")))
6101 })
6102 && !env_key.trim().is_empty()
6103 {
6104 return Ok((env_key, source));
6105 }
6106
6107 if provider == ProviderKind::Moonshot
6108 && !custom_endpoint
6109 && self
6110 .provider_config_for(&identity)
6111 .is_some_and(provider_config_uses_kimi_imported_token)
6112 {
6113 let credential_help =
6114 credential_help_for_provider_route(provider, &self.active_route_base_url());
6115 anyhow::bail!(
6116 "Kimi CLI credential import is unsupported. Codewhale does not impersonate or reuse Kimi OAuth clients; configure an API key from {} instead.",
6117 credential_help
6118 .credential_url
6119 .unwrap_or("the selected provider's API-key console")
6120 );
6121 }
6122
6123 if let Some(credentials) = self.xai_oauth_route_credentials() {
6128 return credentials
6129 .map(|credentials| (credentials.access_token, XAI_OAUTH_KEY_SOURCE.to_string()));
6130 }
6131
6132 if provider == ProviderKind::OpenaiCodex && !custom_endpoint {
6133 let access_token = if read_only {
6134 crate::oauth::get_owned_credentials_read_only(
6135 crate::oauth::OAuthProvider::Chatgpt,
6136 self,
6137 )?
6138 .access_token
6139 } else {
6140 self.codex_credentials()?.access_token
6141 };
6142 return Ok((access_token, "ChatGPT sign-in".to_string()));
6143 }
6144
6145 if let Some(value) = explicit_cli_key {
6150 return Ok((value, "--api-key (CLI)".to_string()));
6151 }
6152
6153 if self.config_credentials_are_bound_to_provider_endpoint(&identity)
6156 && let Some(configured) = self
6157 .provider_route_string_with_deepseek_fallback(&identity, |entry| {
6158 entry.api_key.clone()
6159 })
6160 && classify_config_api_key_value(&configured) == ConfigApiKeyValueKind::Literal
6161 {
6162 let config_source = match provider_config_table_name(&identity) {
6163 Ok(table) => format!("`{table}` api_key"),
6164 Err(_) => "the provider config-table api_key".to_string(),
6165 };
6166 warn_on_config_api_key_shadowing(self, &identity, &config_source);
6167 return Ok((configured, format!("config file ({config_source})")));
6168 }
6169
6170 if provider == ProviderKind::Custom
6183 && let Some(env_name) = bound_provider_api_key_env_name(self, &identity)
6184 {
6185 return match std::env::var(&env_name) {
6186 Ok(value) if !value.trim().is_empty() => {
6187 Ok((value, format!("env var {env_name} (api_key_env)")))
6188 }
6189 _ => {
6190 let route_name = self.provider.as_deref().unwrap_or("<name>");
6191 Err(anyhow::anyhow!(
6192 "Custom provider '{route_name}' API key not found: the route binds \
6193 api_key_env = \"{env_name}\" but that environment variable is not set. \
6194 Set {env_name} to your key, or remove api_key_env from \
6195 [providers.{route_name}] to run the endpoint without credentials."
6196 ))
6197 }
6198 };
6199 }
6200 if let Some(value) = provider_config_env_api_key(self, &identity) {
6201 let name = bound_provider_api_key_env_name(self, &identity).unwrap_or_default();
6202 return Ok((value, format!("env var {name} (api_key_env)")));
6203 }
6204
6205 if !self.should_skip_secret_store_for_provider(&identity)
6211 && let Some(value) = provider_secret_store_api_key_with_mode(self, &identity, read_only)
6212 {
6213 return Ok((
6214 value,
6215 format!(
6216 "secret store slot `{}`",
6217 provider_secret_store_slot(provider)
6218 ),
6219 ));
6220 }
6221
6222 if !self.should_skip_secret_store_for_provider(&identity)
6225 && provider == ProviderKind::XiaomiMimo
6226 {
6227 let mode = self
6228 .provider_config_for(&identity)
6229 .and_then(|provider| provider.mode.as_deref());
6230 if let Some(value) =
6231 xiaomi_mimo_env_api_key_for_runtime(mode, Some(&self.active_route_base_url()))
6232 && !value.trim().is_empty()
6233 {
6234 return Ok((
6235 value,
6236 format!("env var ({})", provider.provider().env_vars().join(" / ")),
6237 ));
6238 }
6239 }
6240 if !self.should_skip_secret_store_for_provider(&identity)
6241 && let Some((name, value)) = provider_env_api_key_named(provider)
6242 {
6243 return Ok((value, format!("env var {name}")));
6244 }
6245
6246 if matches!(
6249 provider,
6250 ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
6251 ) && identity.key.as_str() != codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id
6252 && !custom_endpoint
6253 {
6254 let path = codewhale_config::default_dsh_credentials_path();
6255 if let Ok(grant) = self.external_credential_read_grant(
6256 &identity,
6257 codewhale_config::ExternalCredentialSource::DshCli,
6258 &path,
6259 ) && let Some(value) = crate::dsh_credentials::deepseek_api_key_from_grant(&grant)?
6260 {
6261 return Ok((
6262 value,
6263 "DeepSeek Harness credentials (consented)".to_string(),
6264 ));
6265 }
6266 }
6267
6268 if let Some((key, owner)) = self.account_model_key_and_owner(&identity) {
6271 *account_owner = Some(owner);
6272 return Ok((key, "Codewhale account".to_string()));
6273 }
6274
6275 if provider != ProviderKind::Codewhale
6281 && !auth_mode_requires_api_key(auth_mode.as_deref())
6282 && (provider_route_is_keyless_self_hosted(provider, &self.active_route_base_url())
6283 || base_url_uses_local_host(&self.active_route_base_url()))
6284 {
6285 return Ok(keyless());
6286 }
6287
6288 if custom_endpoint {
6289 let route_name = self
6290 .provider
6291 .as_deref()
6292 .unwrap_or_else(|| provider.as_str());
6293 anyhow::bail!(
6294 "Custom endpoint credentials for {route_name} must be bound explicitly. Ambient provider credentials are not sent to {}. Add api_key or api_key_env to this provider route, or pass --api-key with --base-url.",
6295 self.active_route_base_url()
6296 );
6297 }
6298
6299 match provider {
6300 ProviderKind::Codewhale => anyhow::bail!(
6301 "Codewhale API key not found, so no request was sent.\n\
6302 \n\
6303 The Codewhale API authenticates every model with one account \
6304 API key carrying the `models:infer` scope.\n\
6305 \n\
6306 1. Create one and save it on this machine:\n\
6307 codewhale account api-keys create --name <name> --scope models:infer --use\n\
6308 2. Or export it for this shell:\n\
6309 export CODEWHALE_API_KEY=cwc_key_...\n\
6310 \n\
6311 You can also create a key at {} and put it in \
6312 [providers.codewhale] api_key (or api_key_env).",
6313 provider
6314 .provider()
6315 .credential_help()
6316 .credential_url
6317 .unwrap_or("https://app.codewhale.net/settings?section=api")
6318 ),
6319 ProviderKind::Deepseek => {
6320 anyhow::bail!(deepseek_missing_key_message())
6321 }
6322 ProviderKind::SiliconflowCN => anyhow::bail!(
6323 "SiliconFlow China API key not found. Get a key: {}. Run 'codewhale auth set --provider siliconflow-CN', \
6324 set {}, or add [{}] api_key in ~/.codewhale/config.toml. \
6325 [providers.siliconflow] remains a fallback when the CN table omits api_key.",
6326 provider
6327 .provider()
6328 .credential_help()
6329 .credential_url
6330 .unwrap_or("https://cloud.siliconflow.com/account/ak"),
6331 provider.provider().env_vars().join(" / "),
6332 provider_config_table_name(&identity)?
6333 ),
6334 ProviderKind::Moonshot => {
6335 let credential_help =
6336 credential_help_for_provider_route(provider, &self.active_route_base_url());
6337 if moonshot_base_url_is_exact_kimi_code(&self.active_route_base_url()) {
6338 anyhow::bail!(
6339 "Kimi Code membership-plan API key not found. Get a plan key: {}. This route uses api.kimi.com/coding/v1 and does not import Kimi CLI credentials. Run 'codewhale auth set --provider moonshot', set {}, or add [{}] api_key.",
6340 credential_help
6341 .credential_url
6342 .unwrap_or(KIMI_CODE_MEMBERSHIP_PLAN_CONSOLE_URL),
6343 provider.provider().env_vars().join(" / "),
6344 provider_config_table_name(&identity)?
6345 );
6346 }
6347 anyhow::bail!(
6348 "Moonshot/Kimi API key not found. Get a key: {}. Run 'codewhale auth set --provider moonshot', \
6349 set {}, or add [{}] api_key. \
6350 For a Kimi Code plan key, set [providers.moonshot] base_url = \
6351 \"https://api.kimi.com/coding/v1\" and model = \"kimi-for-coding\".",
6352 credential_help
6353 .credential_url
6354 .unwrap_or("https://platform.kimi.ai/console/api-keys"),
6355 provider.provider().env_vars().join(" / "),
6356 provider_config_table_name(&identity)?
6357 );
6358 }
6359 ProviderKind::Anthropic | ProviderKind::Openmodel => {
6360 anyhow::bail!("{}", missing_provider_api_key_message(&identity)?)
6361 }
6362 ProviderKind::OpencodeZen => {
6363 anyhow::bail!("{}", missing_provider_api_key_message(&identity)?)
6364 }
6365 ProviderKind::OpenaiCodex => anyhow::bail!(
6366 "{}",
6367 crate::oauth::missing_auth_message(crate::oauth::OAuthProvider::Chatgpt)
6368 ),
6369 ProviderKind::Xai => {
6370 if self
6373 .provider_config_for(&identity)
6374 .is_some_and(provider_config_uses_xai_oauth)
6375 || crate::oauth::credentials_present(crate::oauth::OAuthProvider::Xai, self)
6376 {
6377 anyhow::bail!(
6378 "{}",
6379 crate::oauth::missing_auth_message(crate::oauth::OAuthProvider::Xai)
6380 );
6381 }
6382 anyhow::bail!(
6383 "xAI API key not found. Get a key: https://console.x.ai/\n\
6384 Run 'codewhale auth set --provider xai', set XAI_API_KEY, or add \
6385 [providers.xai] api_key.\n\
6386 OAuth alternative: run `codewhale auth xai-device` for \
6387 Codewhale-owned storage and set [providers.xai] auth_mode = \"oauth\"."
6388 );
6389 }
6390 ProviderKind::Sglang | ProviderKind::Vllm => Ok(keyless()),
6393 ProviderKind::Ollama
6394 if provider_route_is_keyless_self_hosted(
6395 provider,
6396 &self.active_route_base_url(),
6397 ) =>
6398 {
6399 Ok(keyless())
6400 }
6401 ProviderKind::Ollama => {
6402 let help =
6403 credential_help_for_provider_route(provider, &self.active_route_base_url());
6404 anyhow::bail!(
6405 "Ollama Cloud API key not found. Get a key: {}. Run 'codewhale auth set --provider ollama', set OLLAMA_API_KEY, or add [providers.ollama] api_key in ~/.codewhale/config.toml.",
6406 help.credential_url
6407 .unwrap_or(codewhale_config::provider::OLLAMA_CLOUD_API_KEY_URL)
6408 )
6409 }
6410 ProviderKind::Custom => {
6414 let provider_name = self.provider.as_deref().unwrap_or("<name>");
6415 match self
6416 .provider_config_for(&identity)
6417 .and_then(|entry| entry.api_key_env.as_deref())
6418 .map(str::trim)
6419 .filter(|name| !name.is_empty())
6420 {
6421 Some(env_name) => anyhow::bail!(
6422 "Custom provider '{provider_name}' API key not found.\n\
6423 Set the environment variable {env_name} to your key, \
6424 or add api_key to [providers.{provider_name}]."
6425 ),
6426 None => anyhow::bail!(
6427 "Custom provider '{provider_name}' has no auth configured.\n\
6428 Add api_key_env = \"YOUR_ENV_VAR\" (or api_key) to \
6429 [providers.{provider_name}] in ~/.codewhale/config.toml."
6430 ),
6431 }
6432 }
6433 _ => anyhow::bail!("{}", missing_provider_api_key_message(&identity)?),
6434 }
6435 }
6436
6437 #[must_use]
6439 pub fn skills_dir(&self) -> PathBuf {
6440 self.skills_dir
6441 .as_deref()
6442 .map(expand_path)
6443 .or_else(default_skills_dir)
6444 .unwrap_or_else(|| PathBuf::from("./skills"))
6445 }
6446
6447 #[must_use]
6448 pub fn bundled_skills_install_dir(&self) -> Option<PathBuf> {
6449 match self.skills_config().bundled.install.unwrap_or_default() {
6450 BundledSkillsInstall::None => return None,
6451 BundledSkillsInstall::All => return owned_skills_dir(),
6452 BundledSkillsInstall::Auto if self.skills_dir.is_some() => return None,
6453 BundledSkillsInstall::Auto => {}
6454 }
6455 let directory = default_skills_dir()?;
6456 let owned = owned_skills_dir()?;
6457 (directory == owned).then_some(directory)
6458 }
6459
6460 #[must_use]
6462 pub fn mcp_config_path(&self) -> PathBuf {
6463 let configured = self.mcp_config_path.as_deref().map(expand_path);
6464 match configured {
6465 Some(path) if path.is_absolute() => path,
6466 Some(path) => {
6467 tracing::warn!(
6468 configured_path = %path.display(),
6469 "relative mcp_config_path is not stable across launch directories; using the user-global MCP config"
6470 );
6471 default_mcp_config_path().unwrap_or_else(|| PathBuf::from("./mcp.json"))
6472 }
6473 None => default_mcp_config_path().unwrap_or_else(|| PathBuf::from("./mcp.json")),
6474 }
6475 }
6476
6477 #[must_use]
6479 pub fn notes_path(&self) -> PathBuf {
6480 self.notes_path
6481 .as_deref()
6482 .map(expand_path)
6483 .or_else(default_notes_path)
6484 .unwrap_or_else(|| PathBuf::from("./notes.txt"))
6485 }
6486
6487 #[must_use]
6489 pub fn memory_path(&self) -> PathBuf {
6490 let legacy_path = self
6491 .memory_path
6492 .as_deref()
6493 .map(expand_path)
6494 .or_else(default_memory_path)
6495 .unwrap_or_else(|| PathBuf::from("./memory.md"));
6496 if self.memory_backend() == MemoryBackend::Native {
6497 if crate::native_memory::NativeMemoryStore::from_global_path(&legacy_path).is_some() {
6508 return legacy_path;
6509 }
6510 return legacy_path
6511 .parent()
6512 .unwrap_or_else(|| Path::new("."))
6513 .join("memory")
6514 .join("global")
6515 .join("MEMORY.md");
6516 }
6517 legacy_path
6518 }
6519
6520 #[must_use]
6522 pub fn speech_output_dir(&self) -> Option<PathBuf> {
6523 std::env::var("XIAOMI_MIMO_SPEECH_OUTPUT_DIR")
6524 .or_else(|_| std::env::var("MIMO_SPEECH_OUTPUT_DIR"))
6525 .or_else(|_| std::env::var("XIAOMIMIMO_SPEECH_OUTPUT_DIR"))
6526 .ok()
6527 .map(|value| value.trim().to_string())
6528 .filter(|value| !value.is_empty())
6529 .map(|value| expand_path(&value))
6530 .or_else(|| {
6531 self.speech
6532 .as_ref()
6533 .and_then(|speech| speech.output_dir.as_deref())
6534 .map(str::trim)
6535 .filter(|value| !value.is_empty())
6536 .map(expand_path)
6537 })
6538 }
6539
6540 #[must_use]
6545 pub fn instructions_paths(&self) -> Vec<PathBuf> {
6546 self.instructions
6547 .as_deref()
6548 .unwrap_or(&[])
6549 .iter()
6550 .map(String::as_str)
6551 .map(str::trim)
6552 .filter(|s| !s.is_empty())
6553 .map(expand_path)
6554 .collect()
6555 }
6556
6557 #[must_use]
6558 pub fn auto_review_disabled(&self) -> bool {
6559 self.auto_review.as_ref().is_some_and(|cfg| cfg.disabled)
6560 }
6561
6562 #[must_use]
6563 pub fn auto_review_review_all_shell(&self) -> bool {
6564 self.auto_review
6565 .as_ref()
6566 .is_some_and(|cfg| cfg.review_all_shell)
6567 }
6568
6569 pub fn auto_review_reviewer_model(&self) -> Option<&str> {
6570 self.auto_review
6571 .as_ref()
6572 .and_then(|cfg| cfg.reviewer_model.as_deref())
6573 .map(str::trim)
6574 .filter(|model| !model.is_empty())
6575 }
6576
6577 #[must_use]
6578 pub fn auto_review_environment(&self) -> &[String] {
6579 self.auto_review
6580 .as_ref()
6581 .map_or(&[], |cfg| cfg.environment.as_slice())
6582 }
6583
6584 #[must_use]
6589 pub fn memory_enabled(&self) -> bool {
6590 if let Some(backend) = self.memory.as_ref().and_then(|memory| memory.backend) {
6591 return backend != MemoryBackend::Off;
6592 }
6593 self.memory
6594 .as_ref()
6595 .and_then(|m| m.enabled)
6596 .unwrap_or(false)
6597 }
6598
6599 #[must_use]
6604 pub fn goal_max_continuations(&self) -> u32 {
6605 self.goal
6606 .as_ref()
6607 .and_then(|goal| goal.max_continuations)
6608 .unwrap_or(crate::goal_loop::DEFAULT_MAX_GOAL_CONTINUATIONS)
6609 }
6610
6611 #[must_use]
6615 pub fn goal_max_steps(&self) -> u32 {
6616 let configured = self.goal.as_ref().and_then(|goal| goal.max_steps);
6617 let resolved = crate::turn_budget::resolve_max_model_steps(configured);
6618 if let Some(steps) = configured
6619 && steps > 0
6620 && resolved != steps
6621 {
6622 tracing::warn!("[goal] max_steps={steps} out of range; clamping to {resolved}");
6623 }
6624 resolved
6625 }
6626
6627 #[must_use]
6630 pub fn goal_enforce_token_budget(&self) -> bool {
6631 self.goal
6632 .as_ref()
6633 .and_then(|goal| goal.enforce_token_budget)
6634 .unwrap_or(false)
6635 }
6636
6637 #[must_use]
6639 pub fn goal_complete_judge(&self) -> bool {
6640 self.goal
6641 .as_ref()
6642 .and_then(|goal| goal.complete_judge)
6643 .unwrap_or(false)
6644 }
6645
6646 #[must_use]
6648 pub fn goal_blocked_judge(&self) -> bool {
6649 self.goal
6650 .as_ref()
6651 .and_then(|goal| goal.blocked_judge)
6652 .unwrap_or(false)
6653 }
6654
6655 #[must_use]
6658 pub fn goal_continuation_delay_seconds(&self) -> u64 {
6659 self.goal
6660 .as_ref()
6661 .and_then(|goal| goal.continuation_delay_seconds)
6662 .unwrap_or(0)
6663 .min(crate::goal_loop::MAX_GOAL_CONTINUATION_DELAY_SECONDS)
6664 }
6665
6666 #[must_use]
6667 pub fn reasoning_only_on_output_limit(&self) -> bool {
6668 self.reasoning_only
6669 .as_ref()
6670 .is_some_and(|cfg| cfg.on_output_limit)
6671 }
6672
6673 #[must_use]
6677 pub fn reasoning_only_max_reprompts(&self) -> u32 {
6678 self.reasoning_only
6679 .as_ref()
6680 .and_then(|cfg| cfg.max_reprompts)
6681 .unwrap_or(DEFAULT_REASONING_ONLY_REPROMPTS)
6682 }
6683
6684 #[must_use]
6689 pub fn reasoning_only_reprompt_message(&self) -> &str {
6690 self.reasoning_only
6691 .as_ref()
6692 .and_then(|cfg| cfg.reprompt_message.as_deref())
6693 .unwrap_or(DEFAULT_REASONING_ONLY_REPROMPT_MESSAGE)
6694 }
6695
6696 #[must_use]
6698 pub fn memory_backend(&self) -> MemoryBackend {
6699 self.memory
6700 .as_ref()
6701 .and_then(|memory| memory.backend)
6702 .unwrap_or_else(|| {
6703 let Some(memory) = self.memory.as_ref() else {
6704 return MemoryBackend::Off;
6705 };
6706 if memory.enabled.unwrap_or(false) {
6707 MemoryBackend::Native
6708 } else {
6709 MemoryBackend::Off
6710 }
6711 })
6712 }
6713
6714 #[must_use]
6720 pub fn vision_model_config(&self) -> Option<VisionModelConfig> {
6721 let mut config = self.vision_model.clone()?;
6722 if config.model_http_policy.is_none() {
6723 config.model_http_policy = self.model_http_policy.clone();
6724 }
6725 Some(config)
6726 }
6727
6728 #[must_use]
6729 pub fn project_context_pack_enabled(&self) -> bool {
6730 self.context.project_pack.unwrap_or(false)
6731 }
6732
6733 #[must_use]
6738 pub fn allow_shell(&self) -> bool {
6739 self.allow_shell.unwrap_or(false)
6740 }
6741
6742 #[must_use]
6751 pub fn interactive_allow_shell(&self) -> bool {
6752 self.allow_shell.unwrap_or(true)
6753 }
6754
6755 pub fn prompt_suggestion_enabled(&self) -> bool {
6757 self.prompt_suggestion.unwrap_or(false)
6758 }
6759
6760 #[must_use]
6768 pub fn compaction_summary_instructions(&self) -> Option<String> {
6769 self.compaction
6770 .as_ref()
6771 .and_then(|compaction| compaction.summary_instructions.as_deref())
6772 .map(str::trim)
6773 .filter(|text| !text.is_empty())
6774 .map(str::to_string)
6775 }
6776
6777 #[must_use]
6787 pub fn compaction_retained_user_message_tokens(&self) -> usize {
6788 let Some(requested) = self
6789 .compaction
6790 .as_ref()
6791 .and_then(|compaction| compaction.retained_user_message_tokens)
6792 else {
6793 return DEFAULT_COMPACTION_RETAINED_USER_MESSAGE_TOKENS;
6794 };
6795 let clamped = requested.clamp(
6796 MIN_COMPACTION_RETAINED_USER_MESSAGE_TOKENS,
6797 MAX_COMPACTION_RETAINED_USER_MESSAGE_TOKENS,
6798 );
6799 if clamped != requested {
6800 tracing::warn!(
6801 "[compaction] retained_user_message_tokens = {requested} is outside {}..={}; using {clamped}",
6802 MIN_COMPACTION_RETAINED_USER_MESSAGE_TOKENS,
6803 MAX_COMPACTION_RETAINED_USER_MESSAGE_TOKENS
6804 );
6805 }
6806 clamped
6807 }
6808
6809 #[must_use]
6813 pub fn max_subagents(&self) -> usize {
6814 if let Some(subagents_cfg) = self.subagents.as_ref()
6816 && let Some(max) = subagents_cfg.max_concurrent
6817 {
6818 return max.clamp(1, MAX_SUBAGENTS);
6819 }
6820 self.max_subagents
6822 .unwrap_or(DEFAULT_MAX_SUBAGENTS)
6823 .clamp(1, MAX_SUBAGENTS)
6824 }
6825
6826 #[must_use]
6830 pub fn max_subagents_for_provider(&self, identity: &ProviderIdentity) -> usize {
6831 self.subagent_provider_config(identity)
6832 .and_then(|cfg| cfg.max_concurrent)
6833 .map(|max| max.clamp(1, MAX_SUBAGENTS))
6834 .unwrap_or_else(|| self.max_subagents())
6835 }
6836
6837 #[must_use]
6841 pub fn subagents_enabled(&self) -> bool {
6842 self.subagents_disabled_reason().is_none()
6843 }
6844
6845 #[must_use]
6848 pub fn subagents_enabled_for_provider(&self, identity: &ProviderIdentity) -> bool {
6849 if !self.subagents_enabled() {
6850 return false;
6851 }
6852 let Some(provider_cfg) = self.subagent_provider_config(identity) else {
6853 return true;
6854 };
6855 provider_cfg.enabled != Some(false)
6856 && provider_cfg.max_concurrent != Some(0)
6857 && provider_cfg.max_depth != Some(0)
6858 }
6859
6860 #[must_use]
6862 pub fn subagents_disabled_reason(&self) -> Option<&'static str> {
6863 if !self.features().enabled(Feature::Subagents) {
6864 return Some("features.subagents=false");
6865 }
6866 let subagents_cfg = self.subagents.as_ref()?;
6867 if subagents_cfg.enabled == Some(false) {
6868 return Some("subagents.enabled=false");
6869 }
6870 if subagents_cfg.max_concurrent == Some(0) {
6871 return Some("subagents.max_concurrent=0");
6872 }
6873 if subagents_cfg.max_depth == Some(0) {
6874 return Some("subagents.max_depth=0");
6875 }
6876 None
6877 }
6878
6879 #[must_use]
6885 pub fn subagent_max_spawn_depth(&self) -> u32 {
6886 self.subagents
6887 .as_ref()
6888 .and_then(|cfg| cfg.max_depth)
6889 .unwrap_or(codewhale_protocol::fleet::DEFAULT_SPAWN_DEPTH)
6890 }
6891
6892 #[must_use]
6894 pub fn subagent_max_spawn_depth_for_provider(&self, identity: &ProviderIdentity) -> u32 {
6895 self.subagent_provider_config(identity)
6896 .and_then(|cfg| cfg.max_depth)
6897 .unwrap_or_else(|| self.subagent_max_spawn_depth())
6898 }
6899
6900 #[must_use]
6907 pub fn launch_concurrency(&self) -> usize {
6908 let max = self.max_subagents();
6909 self.subagents
6910 .as_ref()
6911 .and_then(|cfg| cfg.launch_concurrency.or(cfg.interactive_max_launch_legacy))
6912 .unwrap_or(max)
6913 .clamp(1, max)
6914 }
6915
6916 #[must_use]
6919 pub fn launch_concurrency_for_provider(&self, identity: &ProviderIdentity) -> usize {
6920 let max = self.max_subagents_for_provider(identity);
6921 self.subagent_provider_config(identity)
6922 .and_then(|cfg| cfg.launch_concurrency)
6923 .or_else(|| {
6924 self.subagents
6925 .as_ref()
6926 .and_then(|cfg| cfg.launch_concurrency.or(cfg.interactive_max_launch_legacy))
6927 })
6928 .unwrap_or(max)
6929 .clamp(1, max)
6930 }
6931
6932 #[must_use]
6939 pub fn max_admitted_subagents(&self) -> usize {
6940 let max_concurrent = self.max_subagents();
6941 self.subagents
6942 .as_ref()
6943 .and_then(|cfg| cfg.max_admitted)
6944 .unwrap_or(MAX_SUBAGENT_ADMISSION)
6945 .clamp(max_concurrent, MAX_SUBAGENT_ADMISSION)
6946 }
6947
6948 #[must_use]
6950 pub fn max_admitted_subagents_for_provider(&self, identity: &ProviderIdentity) -> usize {
6951 let max_concurrent = self.max_subagents_for_provider(identity);
6952 self.subagent_provider_config(identity)
6953 .and_then(|cfg| cfg.max_admitted)
6954 .or_else(|| self.subagents.as_ref().and_then(|cfg| cfg.max_admitted))
6955 .unwrap_or(MAX_SUBAGENT_ADMISSION)
6956 .clamp(max_concurrent, MAX_SUBAGENT_ADMISSION)
6957 }
6958
6959 #[must_use]
6963 pub fn subagent_default_max_steps(&self) -> Option<u32> {
6964 self.subagents
6965 .as_ref()
6966 .and_then(|cfg| cfg.default_max_steps)
6967 .filter(|steps| *steps > 0)
6968 }
6969
6970 #[must_use]
6974 pub fn subagent_default_wall_time_secs(&self) -> Option<u64> {
6975 self.subagents
6976 .as_ref()
6977 .and_then(|cfg| cfg.default_wall_time_secs)
6978 .filter(|secs| *secs > 0)
6979 }
6980
6981 #[must_use]
6989 pub fn subagent_api_timeout_secs(&self) -> u64 {
6990 resolve_subagent_api_timeout_secs(
6991 self.subagents.as_ref().and_then(|cfg| cfg.api_timeout_secs),
6992 )
6993 }
6994
6995 #[must_use]
6997 pub fn subagent_api_timeout_secs_for_provider(&self, identity: &ProviderIdentity) -> u64 {
6998 resolve_subagent_api_timeout_secs(
6999 self.subagent_provider_config(identity)
7000 .and_then(|cfg| cfg.api_timeout_secs)
7001 .or_else(|| self.subagents.as_ref().and_then(|cfg| cfg.api_timeout_secs)),
7002 )
7003 }
7004
7005 #[must_use]
7016 pub fn subagent_heartbeat_timeout_secs(&self) -> u64 {
7017 resolve_subagent_heartbeat_timeout_secs(
7018 self.subagents
7019 .as_ref()
7020 .and_then(|cfg| cfg.heartbeat_timeout_secs),
7021 self.subagent_api_timeout_secs(),
7022 DEFAULT_SUBAGENT_TOOL_TIMEOUT_SECS,
7023 )
7024 }
7025
7026 #[must_use]
7028 pub fn subagent_heartbeat_timeout_secs_for_provider(&self, identity: &ProviderIdentity) -> u64 {
7029 let api_timeout = self.subagent_api_timeout_secs_for_provider(identity);
7030 resolve_subagent_heartbeat_timeout_secs(
7031 self.subagent_provider_config(identity)
7032 .and_then(|cfg| cfg.heartbeat_timeout_secs)
7033 .or_else(|| {
7034 self.subagents
7035 .as_ref()
7036 .and_then(|cfg| cfg.heartbeat_timeout_secs)
7037 }),
7038 api_timeout,
7039 DEFAULT_SUBAGENT_TOOL_TIMEOUT_SECS,
7040 )
7041 }
7042
7043 #[must_use]
7051 pub fn stream_chunk_timeout_secs(&self) -> u64 {
7052 let raw = self
7053 .stream
7054 .as_ref()
7055 .and_then(|cfg| cfg.chunk_timeout_secs)
7056 .or_else(|| {
7057 self.tui
7058 .as_ref()
7059 .and_then(|cfg| cfg.stream_chunk_timeout_secs)
7060 })
7061 .or_else(|| {
7062 std::env::var(STREAM_CHUNK_TIMEOUT_ENV)
7063 .or_else(|_| std::env::var(LEGACY_STREAM_CHUNK_TIMEOUT_ENV))
7064 .ok()
7065 .and_then(|value| value.parse::<u64>().ok())
7066 })
7067 .unwrap_or(DEFAULT_STREAM_CHUNK_TIMEOUT_SECS);
7068 if raw == 0 {
7069 return DEFAULT_STREAM_CHUNK_TIMEOUT_SECS;
7070 }
7071 raw.clamp(MIN_STREAM_CHUNK_TIMEOUT_SECS, MAX_STREAM_CHUNK_TIMEOUT_SECS)
7072 }
7073
7074 #[must_use]
7080 pub fn max_model_steps(&self) -> u32 {
7081 let raw = self
7082 .tui
7083 .as_ref()
7084 .and_then(|cfg| cfg.max_model_steps)
7085 .or_else(|| {
7086 std::env::var(MAX_MODEL_STEPS_ENV)
7087 .ok()
7088 .and_then(|value| value.trim().parse::<u32>().ok())
7089 });
7090 crate::turn_budget::resolve_max_model_steps(raw)
7091 }
7092
7093 #[must_use]
7099 pub fn turn_wall_clock(&self) -> std::time::Duration {
7100 let raw = self
7101 .tui
7102 .as_ref()
7103 .and_then(|cfg| cfg.turn_wall_clock_secs)
7104 .or_else(|| {
7105 std::env::var(TURN_WALL_CLOCK_ENV)
7106 .ok()
7107 .and_then(|value| value.trim().parse::<u64>().ok())
7108 });
7109 crate::turn_budget::resolve_turn_wall_clock(raw)
7110 }
7111
7112 #[must_use]
7114 pub fn stream_max_content_bytes(&self) -> usize {
7115 crate::turn_budget::resolve_stream_max_content_bytes(
7116 self.stream
7117 .as_ref()
7118 .and_then(|cfg| cfg.max_content_mb)
7119 .or_else(|| self.tui.as_ref().and_then(|cfg| cfg.stream_max_content_mb)),
7120 )
7121 }
7122
7123 #[must_use]
7125 pub fn stream_max_duration(&self) -> std::time::Duration {
7126 std::time::Duration::from_secs(crate::turn_budget::resolve_stream_max_duration_secs(
7127 self.stream
7128 .as_ref()
7129 .and_then(|cfg| cfg.max_duration_secs)
7130 .or_else(|| {
7131 self.tui
7132 .as_ref()
7133 .and_then(|cfg| cfg.stream_max_duration_secs)
7134 }),
7135 ))
7136 }
7137
7138 #[must_use]
7140 pub fn stream_retry_limits(&self) -> crate::turn_budget::StreamRetryLimits {
7141 let tui = self.tui.as_ref();
7142 let stream = self.stream.as_ref();
7143 crate::turn_budget::resolve_stream_retry_limits(
7144 stream
7145 .and_then(|cfg| cfg.max_resumes)
7146 .or_else(|| tui.and_then(|cfg| cfg.stream_max_resumes)),
7147 stream
7148 .and_then(|cfg| cfg.max_transparent_retries)
7149 .or_else(|| tui.and_then(|cfg| cfg.stream_max_transparent_retries)),
7150 stream
7151 .and_then(|cfg| cfg.max_stream_errors)
7152 .or_else(|| tui.and_then(|cfg| cfg.stream_max_errors)),
7153 )
7154 }
7155
7156 #[must_use]
7158 pub fn stream_open_timeout(&self) -> std::time::Duration {
7159 codewhale_config::resolve_stream_open_timeout(
7160 self.stream
7161 .as_ref()
7162 .and_then(|cfg| cfg.open_timeout_secs)
7163 .or_else(|| {
7164 self.tui
7165 .as_ref()
7166 .and_then(|cfg| cfg.stream_open_timeout_secs)
7167 }),
7168 )
7169 }
7170
7171 #[must_use]
7174 pub fn force_http1(&self) -> bool {
7175 self.stream
7176 .as_ref()
7177 .and_then(|cfg| cfg.force_http1)
7178 .or_else(|| self.tui.as_ref().and_then(|cfg| cfg.force_http1))
7179 .unwrap_or(false)
7180 || codewhale_config::force_http1_from_env()
7181 }
7182
7183 #[must_use]
7185 pub fn connect_timeout(&self) -> std::time::Duration {
7186 let secs = match self
7187 .stream
7188 .as_ref()
7189 .and_then(|cfg| cfg.connect_timeout_secs)
7190 .or_else(|| self.tui.as_ref().and_then(|cfg| cfg.connect_timeout_secs))
7191 {
7192 None | Some(0) => DEFAULT_CONNECT_TIMEOUT_SECS,
7193 Some(secs) => secs.clamp(MIN_CONNECT_TIMEOUT_SECS, MAX_CONNECT_TIMEOUT_SECS),
7194 };
7195 std::time::Duration::from_secs(secs)
7196 }
7197
7198 pub fn tcp_keepalive(&self) -> Option<std::time::Duration> {
7200 let secs = self
7201 .stream
7202 .as_ref()
7203 .and_then(|cfg| cfg.tcp_keepalive_secs)
7204 .unwrap_or(30);
7205 (secs > 0).then(|| std::time::Duration::from_secs(secs.min(3600)))
7206 }
7207
7208 pub fn http2_keep_alive_interval(&self) -> Option<std::time::Duration> {
7210 let secs = self
7211 .stream
7212 .as_ref()
7213 .and_then(|cfg| cfg.http2_keep_alive_interval_secs)
7214 .unwrap_or(15);
7215 (secs > 0).then(|| std::time::Duration::from_secs(secs.min(3600)))
7216 }
7217
7218 pub fn http2_keep_alive_timeout(&self) -> std::time::Duration {
7219 let secs = match self
7220 .stream
7221 .as_ref()
7222 .and_then(|cfg| cfg.http2_keep_alive_timeout_secs)
7223 {
7224 None | Some(0) => 20,
7225 Some(secs) => secs.min(3600),
7226 };
7227 std::time::Duration::from_secs(secs)
7228 }
7229
7230 pub fn resolved_stream_settings(&self) -> StreamConfig {
7234 let limits = self.stream_retry_limits();
7235 StreamConfig {
7236 open_timeout_secs: Some(self.stream_open_timeout().as_secs()),
7237 chunk_timeout_secs: Some(self.stream_chunk_timeout_secs()),
7238 force_http1: Some(self.force_http1()),
7239 max_resumes: Some(limits.max_resumes),
7240 max_transparent_retries: Some(limits.max_transparent_retries),
7241 max_stream_errors: Some(limits.max_errors),
7242 max_duration_secs: Some(self.stream_max_duration().as_secs()),
7243 max_content_mb: Some((self.stream_max_content_bytes() / (1024 * 1024)) as u64),
7244 connect_timeout_secs: Some(self.connect_timeout().as_secs()),
7245 tcp_keepalive_secs: Some(self.tcp_keepalive().map_or(0, |value| value.as_secs())),
7246 http2_keep_alive_interval_secs: Some(
7247 self.http2_keep_alive_interval()
7248 .map_or(0, |value| value.as_secs()),
7249 ),
7250 http2_keep_alive_timeout_secs: Some(self.http2_keep_alive_timeout().as_secs()),
7251 }
7252 }
7253
7254 #[must_use]
7257 pub fn subagent_model_overrides(&self) -> HashMap<String, SubagentModelOverride> {
7258 let mut overrides = HashMap::new();
7259 let Some(cfg) = self.subagents.as_ref() else {
7260 return overrides;
7261 };
7262
7263 let mut insert = |key: &str, value: &Option<String>| {
7264 if let Some(model) = value.as_deref().map(str::trim).filter(|v| !v.is_empty()) {
7265 overrides.insert(key.to_string(), model.into());
7266 }
7267 };
7268 insert("default", &cfg.default_model);
7269 insert("worker", &cfg.worker_model);
7270 insert("general", &cfg.worker_model);
7271 insert("scout", &cfg.explorer_model);
7272 insert("explorer", &cfg.explorer_model);
7273 insert("explore", &cfg.explorer_model);
7274 insert("planner", &cfg.awaiter_model);
7275 insert("awaiter", &cfg.awaiter_model);
7276 insert("plan", &cfg.awaiter_model);
7277 insert("reviewer", &cfg.review_model);
7278 insert("review", &cfg.review_model);
7279 insert("custom", &cfg.custom_model);
7280
7281 if let Some(models) = cfg.models.as_ref() {
7282 for (key, model) in models {
7283 let key = key.trim();
7284 let model = model.trim();
7285 if !key.is_empty() && !model.is_empty() {
7286 overrides.insert(key.to_ascii_lowercase(), model.into());
7287 }
7288 }
7289 }
7290
7291 if let Some(roles) = cfg.roles.as_ref() {
7292 let mut entries: Vec<_> = roles.iter().collect();
7293 let canonical = |key: &str| {
7296 let key = key.trim().to_ascii_lowercase();
7297 if key == "default" {
7298 key
7299 } else {
7300 codewhale_protocol::fleet::migrate_legacy_role_token(&key)
7301 .unwrap_or(&key)
7302 .to_string()
7303 }
7304 };
7305 entries
7306 .sort_by_key(|(key, _)| (canonical(key) == key.trim().to_ascii_lowercase(), *key));
7307 for (key, pin) in entries {
7308 overrides.insert(canonical(key), parse_subagent_role_pin(&pin.model));
7311 }
7312 }
7313
7314 overrides
7315 }
7316
7317 pub fn subagent_route_replacements(&self, key: &str) -> Vec<SubagentModelOverride> {
7321 let Some(roles) = self.subagents.as_ref().and_then(|cfg| cfg.roles.as_ref()) else {
7322 return Vec::new();
7323 };
7324 let canonical = |raw: &str| {
7325 let raw = raw.trim().to_ascii_lowercase();
7326 if raw == "default" {
7327 raw
7328 } else {
7329 codewhale_protocol::fleet::migrate_legacy_role_token(&raw)
7330 .unwrap_or(&raw)
7331 .to_string()
7332 }
7333 };
7334 roles
7335 .iter()
7336 .filter(|(raw, _)| canonical(raw) == key)
7337 .max_by_key(|(raw, _)| (canonical(raw) == raw.trim().to_ascii_lowercase(), *raw))
7338 .map(|(_, pin)| {
7339 pin.replacements
7340 .iter()
7341 .map(|route| parse_subagent_role_pin(route))
7342 .collect()
7343 })
7344 .unwrap_or_default()
7345 }
7346
7347 #[must_use]
7350 pub fn fleet_config(&self) -> codewhale_config::FleetConfigToml {
7351 self.fleet.clone().unwrap_or_default()
7352 }
7353
7354 #[must_use]
7355 pub fn mcp_backend(&self) -> codewhale_config::McpBackend {
7356 self.extension_host
7357 .as_ref()
7358 .map_or(codewhale_config::McpBackend::default(), |host| {
7359 host.mcp_backend
7360 })
7361 }
7362
7363 #[must_use]
7368 pub fn workflow_config(&self) -> codewhale_config::WorkflowConfigToml {
7369 self.workflow.clone().unwrap_or_default()
7370 }
7371
7372 #[must_use]
7377 pub fn model_bound_redaction(&self) -> codewhale_config::redaction::ModelBoundMasking {
7378 self.redaction
7379 .as_ref()
7380 .map(codewhale_config::redaction::RedactionToml::model_bound_masking)
7381 .unwrap_or_default()
7382 }
7383
7384 pub fn redaction_confirmation_required(&self) -> bool {
7387 codewhale_config::redaction::confirmation_required(
7388 self.model_bound_redaction(),
7389 self.loaded_config_path.as_deref(),
7390 )
7391 }
7392
7393 pub fn record_redaction_confirmation(&self) -> anyhow::Result<std::path::PathBuf> {
7396 let path = self.loaded_config_path.as_deref().ok_or_else(|| {
7397 anyhow::anyhow!("No loaded config file can receive this confirmation")
7398 })?;
7399 codewhale_config::redaction::record_model_bound_disabled_confirmation(path)
7400 .map_err(anyhow::Error::from)
7401 }
7402
7403 #[must_use]
7405 pub fn reasoning_effort(&self) -> Option<&str> {
7406 self.reasoning_effort.as_deref()
7407 }
7408
7409 pub fn reasoning_effort_is_explicit(&self) -> bool {
7410 self.reasoning_effort.is_some() && !self.reasoning_effort_inferred_from_legacy_alias
7411 }
7412
7413 pub fn hooks_config(&self) -> HooksConfig {
7415 self.hooks.clone().unwrap_or_default()
7416 }
7417
7418 #[must_use]
7420 pub fn notifications_config(&self) -> NotificationsConfig {
7421 let mut notifications = self.notifications.clone().unwrap_or_default();
7422 notifications.condition = Some(
7423 notifications
7424 .condition
7425 .or_else(|| self.tui.as_ref().and_then(|tui| tui.notification_condition))
7426 .unwrap_or(NotificationCondition::Unfocused),
7427 );
7428 notifications
7429 }
7430
7431 #[must_use]
7433 pub fn approval_default_selection(&self) -> ApprovalDefaultSelection {
7434 self.approval.unwrap_or_default().default_selection
7435 }
7436
7437 #[must_use]
7442 pub fn approval_timeout(&self) -> Option<std::time::Duration> {
7443 const MAX_SECONDS: u64 = 86_400;
7444 let seconds = self.approval.unwrap_or_default().timeout_seconds?;
7445 if seconds == 0 {
7446 return None;
7447 }
7448 if seconds > MAX_SECONDS {
7449 tracing::warn!(
7450 "[approval] timeout_seconds={seconds} exceeds 24h; clamping to {MAX_SECONDS}"
7451 );
7452 }
7453 Some(std::time::Duration::from_secs(seconds.min(MAX_SECONDS)))
7454 }
7455
7456 #[must_use]
7458 pub fn snapshots_config(&self) -> SnapshotsConfig {
7459 self.snapshots.clone().unwrap_or_default()
7460 }
7461
7462 #[must_use]
7464 pub fn skills_config(&self) -> SkillsConfig {
7465 self.skills.clone().unwrap_or_default()
7466 }
7467
7468 #[must_use]
7470 pub fn update_config(&self) -> UpdateConfig {
7471 self.update.clone().unwrap_or_default()
7472 }
7473
7474 #[must_use]
7476 pub fn cloud_facts_config(&self) -> CloudFactsConfig {
7477 self.cloud_facts.clone().unwrap_or_default()
7478 }
7479
7480 #[must_use]
7482 pub fn resolve_hotbar_bindings(
7483 &self,
7484 known_action_ids: &[&str],
7485 ) -> codewhale_config::HotbarConfigResolution {
7486 codewhale_config::resolve_hotbar_bindings(self.hotbar.as_deref(), known_action_ids)
7487 }
7488
7489 #[must_use]
7491 pub fn features(&self) -> Features {
7492 let mut features = Features::with_defaults();
7493 if let Some(table) = &self.features {
7494 features.apply_map(&table.entries);
7495 }
7496 features
7497 }
7498
7499 pub fn set_feature(&mut self, key: &str, enabled: bool) -> Result<()> {
7501 if !is_known_feature_key(key) {
7502 anyhow::bail!("Unknown feature flag: {key}");
7503 }
7504 let table = self.features.get_or_insert_with(FeaturesToml::default);
7505 table.entries.insert(key.to_string(), enabled);
7506 Ok(())
7507 }
7508
7509 #[must_use]
7511 pub fn retry_policy(&self) -> RetryPolicy {
7512 let defaults = RetryPolicy {
7513 rate_limit: RateLimitRetryPolicy::default(),
7514 enabled: true,
7515 max_retries: 3,
7516 initial_delay: 1.0,
7517 max_delay: 60.0,
7518 exponential_base: 2.0,
7519 jitter: true,
7520 jitter_factor: 0.1,
7521 respect_retry_after: true,
7522 };
7523
7524 let Some(cfg) = &self.retry else {
7525 return defaults;
7526 };
7527
7528 RetryPolicy {
7529 rate_limit: cfg.rate_limit.clone(),
7530 enabled: cfg.enabled.unwrap_or(defaults.enabled),
7531 max_retries: cfg.max_retries.unwrap_or(defaults.max_retries),
7532 initial_delay: cfg.initial_delay.unwrap_or(defaults.initial_delay),
7533 max_delay: cfg.max_delay.unwrap_or(defaults.max_delay),
7534 exponential_base: cfg.exponential_base.unwrap_or(defaults.exponential_base),
7535 jitter: cfg.jitter.unwrap_or(defaults.jitter),
7536 jitter_factor: cfg
7537 .jitter_factor
7538 .filter(|factor| factor.is_finite())
7539 .map_or(defaults.jitter_factor, |factor| factor.clamp(0.0, 1.0)),
7540 respect_retry_after: cfg
7541 .respect_retry_after
7542 .unwrap_or(defaults.respect_retry_after),
7543 }
7544 }
7545}
7546
7547#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7554pub enum ConfigEnvironmentPolicy {
7555 Runtime,
7556 StructuralDiagnostic,
7557}
7558
7559impl ConfigEnvironmentPolicy {
7560 const fn permits_secret_bearing_values(self) -> bool {
7561 matches!(self, Self::Runtime)
7562 }
7563}
7564
7565fn root_deepseek_model_is_foreign_to_direct_provider(provider: ProviderKind, model: &str) -> bool {
7566 if matches!(
7567 provider,
7568 ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
7569 ) || codewhale_config::descriptors::provider_passes_model_through(provider)
7570 {
7571 return false;
7572 }
7573 if matches!(
7574 provider,
7575 ProviderKind::NvidiaNim
7576 | ProviderKind::Openrouter
7577 | ProviderKind::Orcarouter
7578 | ProviderKind::Novita
7579 | ProviderKind::Fireworks
7580 | ProviderKind::Siliconflow
7581 | ProviderKind::SiliconflowCN
7582 | ProviderKind::Deepinfra
7583 | ProviderKind::Together
7584 | ProviderKind::Sglang
7585 | ProviderKind::Vllm
7586 | ProviderKind::Volcengine
7587 | ProviderKind::Atlascloud
7588 | ProviderKind::OpencodeGo
7589 | ProviderKind::WanjieArk
7590 | ProviderKind::Huggingface
7591 | ProviderKind::XiaomiMimo
7592 | ProviderKind::Moonshot
7593 ) {
7594 return false;
7595 }
7596 codewhale_config::route::resolve_model(ProviderKind::Deepseek, model, None)
7597 .is_ok_and(|resolved| !resolved.is_auto)
7598}
7599
7600mod paths;
7607#[cfg(any(test, feature = "test-support"))]
7608pub use paths::clipboard_images_dir_for_home;
7609use paths::{
7610 canonicalize_or_keep, codewhale_home_dir, default_config_path, default_managed_config_path,
7611 default_mcp_config_path, default_memory_path, default_notes_path, default_requirements_path,
7612 default_skills_dir, env_config_path, expand_pathbuf, try_default_config_path,
7613 workspace_config_key,
7614};
7615pub use paths::{
7616 clipboard_images_dir, expand_path, home_config_path, is_home_config_path, owned_skills_dir,
7617};
7618
7619pub fn initialize_cloud_facts(config: &Config) {
7622 let settings = config.cloud_facts_config().settings();
7623 codewhale_cloud_facts::configure(&settings);
7624 codewhale_cloud_facts::maybe_load_persisted_cache(&settings);
7625 if tokio::runtime::Handle::try_current().is_ok() {
7626 codewhale_cloud_facts::spawn_background_refresh(settings, None);
7627 }
7628}
7629
7630pub fn workspace_trust_config_candidate_paths() -> Vec<PathBuf> {
7631 #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
7632 {
7633 if !crate::test_support::guarded_environment_provides_state_paths() {
7634 return vec![
7635 crate::test_support::unsealed_test_state_root()
7636 .join(codewhale_config::CONFIG_FILE_NAME),
7637 ];
7638 }
7639 }
7640
7641 match env_config_path() {
7642 Ok(Some(path)) => return vec![path],
7643 Ok(None) => {}
7644 Err(error) => {
7645 tracing::error!(
7646 error = %error,
7647 "invalid config path override; refusing workspace-trust fallback"
7648 );
7649 return Vec::new();
7650 }
7651 }
7652
7653 match codewhale_home_dir() {
7654 Ok(Some(codewhale_home)) => return vec![codewhale_home.join("config.toml")],
7655 Ok(None) => {}
7656 Err(error) => {
7657 tracing::error!(
7658 error = %error,
7659 "invalid Codewhale home override; refusing workspace-trust fallback"
7660 );
7661 return Vec::new();
7662 }
7663 }
7664
7665 let Some(home) = codewhale_paths::user_home() else {
7666 return Vec::new();
7667 };
7668 vec![
7669 home.join(".codewhale").join("config.toml"),
7670 home.join(".deepseek").join("config.toml"),
7671 ]
7672}
7673
7674pub fn needs_trust(workspace: &Path) -> bool {
7675 if is_workspace_trusted(workspace) {
7676 return false;
7677 }
7678
7679 let markers = [
7680 workspace.join(".deepseek").join("trusted"),
7681 workspace.join(".deepseek").join("trust.json"),
7682 ];
7683 !markers.iter().any(|path| path.exists())
7684}
7685
7686#[must_use]
7687pub fn is_workspace_trusted(workspace: &Path) -> bool {
7688 let config_path = match default_config_path() {
7689 Ok(path) => path,
7690 Err(error) => {
7691 tracing::error!(
7692 error = %error,
7693 "failed to resolve workspace-trust config; treating workspace as untrusted"
7694 );
7695 return false;
7696 }
7697 };
7698 let Ok(raw) = fs::read_to_string(config_path) else {
7699 return false;
7700 };
7701 let Ok(doc) = toml::from_str::<toml::Value>(&raw) else {
7702 return false;
7703 };
7704 workspace_trust_level_from_doc(&doc, workspace).is_some_and(is_trusted_level)
7705}
7706
7707pub fn save_workspace_trust(workspace: &Path) -> Result<PathBuf> {
7708 set_workspace_trust(workspace, true)
7709}
7710
7711pub fn set_workspace_trust(workspace: &Path, trusted: bool) -> Result<PathBuf> {
7712 let config_path =
7713 try_default_config_path().context("Failed to resolve config path for workspace trust.")?;
7714 ensure_parent_dir(&config_path)?;
7715
7716 let project_key = workspace_config_key(workspace);
7717 crate::config_persistence::mutate_config_document(&config_path, |doc| {
7718 crate::config_persistence::set_document_value(
7719 doc,
7720 &["projects", project_key.as_str(), "trust_level"],
7721 if trusted { "trusted" } else { "untrusted" },
7722 )
7723 })
7724 .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
7725 Ok(config_path)
7726}
7727
7728pub const HOOKS_RECEIPT_KEY: &str = "hooks_sha256";
7730pub const MCP_RECEIPT_KEY: &str = "mcp_sha256";
7731
7732pub fn project_receipt_for_workspace(workspace: &Path, key: &str) -> Option<String> {
7733 let raw = fs::read_to_string(default_config_path().ok()?).ok()?;
7734 let doc = toml::from_str::<toml::Value>(&raw).ok()?;
7735 doc.get("projects")?
7736 .get(workspace_config_key(workspace))?
7737 .get(key)?
7738 .as_str()
7739 .map(str::to_owned)
7740}
7741
7742pub fn save_workspace_project_receipt(
7743 workspace: &Path,
7744 key: &str,
7745 digest: &str,
7746) -> Result<PathBuf> {
7747 let config_path = try_default_config_path()?;
7748 ensure_parent_dir(&config_path)?;
7749 let project_key = workspace_config_key(workspace);
7750 crate::config_persistence::mutate_config_document(&config_path, |doc| {
7751 crate::config_persistence::set_document_value(
7752 doc,
7753 &["projects", project_key.as_str(), key],
7754 digest,
7755 )
7756 })?;
7757 Ok(config_path)
7758}
7759
7760pub fn hook_receipt_for_workspace(workspace: &Path) -> Option<String> {
7761 project_receipt_for_workspace(workspace, HOOKS_RECEIPT_KEY)
7762}
7763
7764pub fn save_workspace_hook_receipt(workspace: &Path, digest: &str) -> Result<PathBuf> {
7765 save_workspace_project_receipt(workspace, HOOKS_RECEIPT_KEY, digest)
7766}
7767
7768fn workspace_trust_level_from_doc<'a>(doc: &'a toml::Value, workspace: &Path) -> Option<&'a str> {
7769 let workspace = canonicalize_or_keep(workspace);
7770 let mut scope = Some(doc);
7775 while let Some(current) = scope {
7776 if let Some(projects) = current.get("projects").and_then(toml::Value::as_table) {
7777 for (raw_path, project) in projects {
7778 let project_path = canonicalize_or_keep(&expand_path(raw_path));
7779 if project_path == workspace {
7780 return project.get("trust_level").and_then(toml::Value::as_str);
7781 }
7782 }
7783 }
7784 scope = current.get("extras");
7785 }
7786 None
7787}
7788
7789fn is_trusted_level(level: &str) -> bool {
7790 level.trim().eq_ignore_ascii_case("trusted")
7791}
7792
7793pub fn resolve_load_config_path(path: Option<PathBuf>) -> Result<Option<PathBuf>> {
7794 if let Some(path) = path {
7795 return Ok(Some(expand_pathbuf(path)));
7796 }
7797
7798 try_default_config_path().map(Some)
7799}
7800
7801pub fn ensure_config_file_exists(path: Option<PathBuf>) -> Result<Option<PathBuf>> {
7806 let config_path = match path {
7807 Some(path) => expand_pathbuf(path),
7808 None => default_config_path().context("Failed to resolve config path.")?,
7809 };
7810 if config_path.exists() {
7811 return Ok(None);
7812 }
7813
7814 ensure_parent_dir(&config_path)?;
7815 let content = format!(
7816 r#"# codewhale Configuration
7817# Get your API key from https://platform.deepseek.com
7818# Save it with: codewhale auth set --provider deepseek
7819
7820# Base URL (default: https://api.deepseek.com/beta)
7821# Set https://api.deepseek.com to opt out of beta features.
7822# base_url = "https://api.deepseek.com/beta"
7823
7824# Default model
7825default_text_model = "{DEFAULT_TEXT_MODEL}"
7826
7827# Thinking mode (DeepSeek V4 reasoning effort):
7828# "auto" | "off" | "low" | "medium" | "high" | "max"
7829# Ctrl+T in the TUI (or /effort) cycles the active model's effort levels.
7830reasoning_effort = "auto"
7831
7832# Startup update check
7833[update]
7834check_for_updates = true
7835# check_interval_hours = 1
7836# update_uri = "https://internal.mirror.example/codewhale/releases/latest"
7837"#
7838 );
7839 write_config_file_secure(&config_path, &content)
7840 .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
7841 Ok(Some(config_path))
7842}
7843
7844fn env_base_url_override() -> Option<String> {
7850 codewhale_env_var("CODEWHALE_BASE_URL", "DEEPSEEK_BASE_URL")
7851 .ok()
7852 .filter(|v| !v.trim().is_empty())
7853}
7854
7855fn first_nonempty_env(names: &[&str]) -> Option<String> {
7856 let read = || {
7857 names.iter().find_map(|name| {
7858 std::env::var(name)
7859 .ok()
7860 .filter(|value| !value.trim().is_empty())
7861 })
7862 };
7863 #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
7864 {
7865 crate::test_support::with_test_env_lock(read)
7866 }
7867 #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
7868 {
7869 read()
7870 }
7871}
7872
7873fn provider_env_base_url_override(provider: ProviderKind) -> Option<String> {
7879 let names: &[&str] = match provider {
7880 ProviderKind::NvidiaNim => &["NVIDIA_NIM_BASE_URL", "NIM_BASE_URL", "NVIDIA_BASE_URL"],
7881 ProviderKind::Openai => &["OPENAI_BASE_URL"],
7882 ProviderKind::Atlascloud => &["ATLASCLOUD_BASE_URL"],
7883 ProviderKind::Openrouter => &["OPENROUTER_BASE_URL"],
7884 ProviderKind::Orcarouter => &["ORCA_API_BASE_URL", "ORCA_BASE_URL", "ORCAROUTER_BASE_URL"],
7889 ProviderKind::XiaomiMimo => &["XIAOMI_MIMO_BASE_URL", "MIMO_BASE_URL"],
7890 ProviderKind::WanjieArk => &[
7891 "WANJIE_ARK_BASE_URL",
7892 "WANJIE_BASE_URL",
7893 "WANJIE_MAAS_BASE_URL",
7894 ],
7895 ProviderKind::Volcengine => &[
7896 "VOLCENGINE_BASE_URL",
7897 "VOLCENGINE_ARK_BASE_URL",
7898 "ARK_BASE_URL",
7899 ],
7900 ProviderKind::Novita => &["NOVITA_BASE_URL"],
7901 ProviderKind::Fireworks => &["FIREWORKS_BASE_URL"],
7902 ProviderKind::Siliconflow | ProviderKind::SiliconflowCN => &["SILICONFLOW_BASE_URL"],
7903 ProviderKind::Arcee => &["ARCEE_BASE_URL"],
7904 ProviderKind::Moonshot => &["MOONSHOT_BASE_URL", "KIMI_BASE_URL"],
7905 ProviderKind::Sglang => &["SGLANG_BASE_URL"],
7906 ProviderKind::Vllm => &["VLLM_BASE_URL"],
7907 ProviderKind::Ollama => &["OLLAMA_BASE_URL"],
7908 ProviderKind::OllamaCloud => &["OLLAMA_CLOUD_BASE_URL"],
7909 ProviderKind::Huggingface => &["HUGGINGFACE_BASE_URL", "HF_BASE_URL"],
7910 ProviderKind::Modelscope => &["MODELSCOPE_BASE_URL"],
7911 ProviderKind::Meta => &["META_MODEL_API_BASE_URL", "MODEL_API_BASE_URL"],
7912 ProviderKind::Xai => &["XAI_BASE_URL"],
7913 ProviderKind::Mistral => &["MISTRAL_BASE_URL"],
7914 ProviderKind::Google => &["GOOGLE_BASE_URL", "GEMINI_BASE_URL"],
7915 ProviderKind::Antigravity => &[],
7916 ProviderKind::Telecomjs => &["TELECOMJS_BASE_URL"],
7917 ProviderKind::Edenai => &["EDENAI_BASE_URL"],
7918 ProviderKind::Zenmux => &["ZENMUX_BASE_URL"],
7919 ProviderKind::Csdn => &["CSDN_BASE_URL"],
7920 ProviderKind::Concentrate => &["CONCENTRATE_BASE_URL"],
7921 ProviderKind::Codewhale => &["CODEWHALE_API_BASE"],
7922 ProviderKind::ModelstudioTokenPlan | ProviderKind::ModelstudioTokenPlanAnthropic => {
7923 &["MODELSTUDIO_TOKEN_PLAN_BASE_URL"]
7924 }
7925 ProviderKind::ModelstudioCodingPlan | ProviderKind::ModelstudioCodingPlanAnthropic => {
7926 &["MODELSTUDIO_CODING_PLAN_BASE_URL"]
7927 }
7928 ProviderKind::OpencodeGo => &["OPENCODE_GO_BASE_URL"],
7929 ProviderKind::OpencodeZen => &["OPENCODE_ZEN_BASE_URL"],
7930 ProviderKind::Deepseek
7931 | ProviderKind::DeepseekAnthropic
7932 | ProviderKind::Anthropic
7933 | ProviderKind::Openmodel
7934 | ProviderKind::Deepinfra
7935 | ProviderKind::Together
7936 | ProviderKind::Qianfan
7937 | ProviderKind::OpenaiCodex
7938 | ProviderKind::Zai
7939 | ProviderKind::Stepfun
7940 | ProviderKind::Minimax
7941 | ProviderKind::MinimaxAnthropic
7942 | ProviderKind::Sakana
7943 | ProviderKind::LongCat
7944 | ProviderKind::Custom => &[],
7945 };
7946 if provider == ProviderKind::Codewhale {
7952 return first_nonempty_env(names)
7953 .as_deref()
7954 .and_then(codewhale_config::provider::codewhale_api_base);
7955 }
7956 first_nonempty_env(names)
7957}
7958
7959fn codewhale_env_var(
7963 codewhale_name: &str,
7964 legacy_name: &str,
7965) -> Result<String, std::env::VarError> {
7966 let read = || {
7967 std::env::var(codewhale_name)
7968 .ok()
7969 .filter(|value| !value.trim().is_empty())
7970 .or_else(|| {
7971 std::env::var(legacy_name)
7972 .ok()
7973 .filter(|value| !value.trim().is_empty())
7974 })
7975 .ok_or(std::env::VarError::NotPresent)
7976 };
7977 #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
7978 {
7979 crate::test_support::with_test_env_lock(read)
7980 }
7981 #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
7982 {
7983 read()
7984 }
7985}
7986
7987fn apply_env_overrides(config: &mut Config, policy: ConfigEnvironmentPolicy) {
7988 #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
7989 {
7990 crate::test_support::with_test_env_lock(|| {
7991 apply_env_overrides_unlocked(config, policy);
7992 })
7993 }
7994 #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
7995 {
7996 apply_env_overrides_unlocked(config, policy);
7997 }
7998}
7999
8000fn apply_env_overrides_unlocked(config: &mut Config, policy: ConfigEnvironmentPolicy) {
8001 if let Ok(value) = codewhale_env_var("CODEWHALE_PROVIDER", "DEEPSEEK_PROVIDER") {
8002 config.provider = Some(value);
8003 config.route_provenance.provider_from_env = true;
8004 config.route_provenance.provider_from_saved_selection = false;
8005 config.route_provenance.provider_from_profile = false;
8006 }
8007 let Ok(identity) = config.active_provider_identity() else {
8008 return;
8009 };
8010 let active_provider = identity.provider;
8011 let active_base_url_from_env = env_base_url_override().is_some()
8012 || provider_env_base_url_override(active_provider).is_some()
8013 || (config.selects_legacy_ollama_cloud_route()
8014 && first_nonempty_env(&["OLLAMA_BASE_URL"]).is_some());
8015 let changes_root_authority = active_base_url_from_env
8016 || (policy.permits_secret_bearing_values()
8017 && std::env::var("CODEWHALE_HTTP_HEADERS")
8018 .or_else(|_| std::env::var("DEEPSEEK_HTTP_HEADERS"))
8019 .is_ok());
8020 let identity = if identity.legacy_root_custom_generation.is_some() && changes_root_authority {
8021 let Ok(exact) = config.resolve_exact_provider_identity(identity.key.as_str()) else {
8022 return;
8023 };
8024 config.legacy_root_custom_generation = None;
8025 exact
8026 } else {
8027 identity
8028 };
8029 if let Ok(value) = codewhale_env_var("CODEWHALE_BASE_URL", "DEEPSEEK_BASE_URL")
8030 && let Ok(entry) = config.provider_config_for_mut(&identity)
8031 {
8032 entry.base_url = Some(value);
8033 }
8034 if matches!(active_provider, ProviderKind::NvidiaNim)
8035 && let Ok(value) = std::env::var("NVIDIA_NIM_BASE_URL")
8036 .or_else(|_| std::env::var("NIM_BASE_URL"))
8037 .or_else(|_| std::env::var("NVIDIA_BASE_URL"))
8038 && let Ok(entry) = config.provider_config_for_mut(&identity)
8039 {
8040 entry.base_url = Some(value);
8041 }
8042 if matches!(active_provider, ProviderKind::Openai)
8045 && let Ok(value) = std::env::var("OPENAI_BASE_URL")
8046 && !value.trim().is_empty()
8047 && let Ok(entry) = config.provider_config_for_mut(&identity)
8048 {
8049 entry.base_url = Some(value);
8050 }
8051 if matches!(active_provider, ProviderKind::Atlascloud)
8052 && let Ok(value) = std::env::var("ATLASCLOUD_BASE_URL")
8053 && !value.trim().is_empty()
8054 && let Ok(entry) = config.provider_config_for_mut(&identity)
8055 {
8056 entry.base_url = Some(value);
8057 }
8058 if matches!(active_provider, ProviderKind::Openrouter)
8059 && let Ok(value) = std::env::var("OPENROUTER_BASE_URL")
8060 && !value.trim().is_empty()
8061 && let Ok(entry) = config.provider_config_for_mut(&identity)
8062 {
8063 entry.base_url = Some(value);
8064 }
8065 if matches!(active_provider, ProviderKind::XiaomiMimo)
8066 && let Ok(value) =
8067 std::env::var("XIAOMI_MIMO_BASE_URL").or_else(|_| std::env::var("MIMO_BASE_URL"))
8068 && !value.trim().is_empty()
8069 && let Ok(entry) = config.provider_config_for_mut(&identity)
8070 {
8071 entry.base_url = Some(value);
8072 }
8073 if matches!(active_provider, ProviderKind::XiaomiMimo)
8074 && let Ok(value) = std::env::var("XIAOMI_MIMO_MODE").or_else(|_| std::env::var("MIMO_MODE"))
8075 && !value.trim().is_empty()
8076 && let Ok(entry) = config.provider_config_for_mut(&identity)
8077 {
8078 entry.mode = Some(value);
8079 }
8080 if matches!(active_provider, ProviderKind::WanjieArk)
8081 && let Ok(value) = std::env::var("WANJIE_ARK_BASE_URL")
8082 .or_else(|_| std::env::var("WANJIE_BASE_URL"))
8083 .or_else(|_| std::env::var("WANJIE_MAAS_BASE_URL"))
8084 && !value.trim().is_empty()
8085 && let Ok(entry) = config.provider_config_for_mut(&identity)
8086 {
8087 entry.base_url = Some(value);
8088 }
8089 if matches!(active_provider, ProviderKind::Volcengine)
8090 && let Ok(value) = std::env::var("VOLCENGINE_BASE_URL")
8091 .or_else(|_| std::env::var("VOLCENGINE_ARK_BASE_URL"))
8092 .or_else(|_| std::env::var("ARK_BASE_URL"))
8093 && !value.trim().is_empty()
8094 && let Ok(entry) = config.provider_config_for_mut(&identity)
8095 {
8096 entry.base_url = Some(value);
8097 }
8098 if matches!(active_provider, ProviderKind::Novita)
8099 && let Ok(value) = std::env::var("NOVITA_BASE_URL")
8100 && !value.trim().is_empty()
8101 && let Ok(entry) = config.provider_config_for_mut(&identity)
8102 {
8103 entry.base_url = Some(value);
8104 }
8105 if matches!(active_provider, ProviderKind::Fireworks)
8106 && let Ok(value) = std::env::var("FIREWORKS_BASE_URL")
8107 && !value.trim().is_empty()
8108 && let Ok(entry) = config.provider_config_for_mut(&identity)
8109 {
8110 entry.base_url = Some(value);
8111 }
8112 if matches!(
8113 active_provider,
8114 ProviderKind::Siliconflow | ProviderKind::SiliconflowCN
8115 ) && let Ok(value) = std::env::var("SILICONFLOW_BASE_URL")
8116 && !value.trim().is_empty()
8117 && let Ok(entry) = config.provider_config_for_mut(&identity)
8118 {
8119 entry.base_url = Some(value);
8120 }
8121 if matches!(active_provider, ProviderKind::Arcee)
8122 && let Ok(value) = std::env::var("ARCEE_BASE_URL")
8123 && !value.trim().is_empty()
8124 && let Ok(entry) = config.provider_config_for_mut(&identity)
8125 {
8126 entry.base_url = Some(value);
8127 }
8128 if matches!(active_provider, ProviderKind::Huggingface)
8129 && let Ok(value) =
8130 std::env::var("HUGGINGFACE_BASE_URL").or_else(|_| std::env::var("HF_BASE_URL"))
8131 && !value.trim().is_empty()
8132 && let Ok(entry) = config.provider_config_for_mut(&identity)
8133 {
8134 entry.base_url = Some(value);
8135 }
8136 if matches!(active_provider, ProviderKind::Modelscope)
8137 && let Ok(value) = std::env::var("MODELSCOPE_BASE_URL")
8138 && !value.trim().is_empty()
8139 && let Ok(entry) = config.provider_config_for_mut(&identity)
8140 {
8141 entry.base_url = Some(value);
8142 }
8143 if matches!(active_provider, ProviderKind::Moonshot)
8144 && let Ok(value) =
8145 std::env::var("MOONSHOT_BASE_URL").or_else(|_| std::env::var("KIMI_BASE_URL"))
8146 && !value.trim().is_empty()
8147 && let Ok(entry) = config.provider_config_for_mut(&identity)
8148 {
8149 entry.base_url = Some(value);
8150 }
8151 if matches!(active_provider, ProviderKind::Sglang)
8152 && let Ok(value) = std::env::var("SGLANG_BASE_URL")
8153 && !value.trim().is_empty()
8154 && let Ok(entry) = config.provider_config_for_mut(&identity)
8155 {
8156 entry.base_url = Some(value);
8157 }
8158 if matches!(active_provider, ProviderKind::Vllm)
8159 && let Ok(value) = std::env::var("VLLM_BASE_URL")
8160 && !value.trim().is_empty()
8161 && let Ok(entry) = config.provider_config_for_mut(&identity)
8162 {
8163 entry.base_url = Some(value);
8164 }
8165 if matches!(active_provider, ProviderKind::Meta)
8166 && let Ok(value) = std::env::var("META_MODEL_API_BASE_URL")
8167 .or_else(|_| std::env::var("MODEL_API_BASE_URL"))
8168 && !value.trim().is_empty()
8169 && let Ok(entry) = config.provider_config_for_mut(&identity)
8170 {
8171 entry.base_url = Some(value);
8172 }
8173 if matches!(active_provider, ProviderKind::Xai)
8174 && let Ok(value) = std::env::var("XAI_BASE_URL")
8175 && !value.trim().is_empty()
8176 && let Ok(entry) = config.provider_config_for_mut(&identity)
8177 {
8178 entry.base_url = Some(value);
8179 }
8180 if matches!(active_provider, ProviderKind::Mistral)
8181 && let Ok(value) = std::env::var("MISTRAL_BASE_URL")
8182 && !value.trim().is_empty()
8183 && let Ok(entry) = config.provider_config_for_mut(&identity)
8184 {
8185 entry.base_url = Some(value);
8186 }
8187 if matches!(active_provider, ProviderKind::Telecomjs)
8188 && let Ok(value) = std::env::var("TELECOMJS_BASE_URL")
8189 && !value.trim().is_empty()
8190 && let Ok(entry) = config.provider_config_for_mut(&identity)
8191 {
8192 entry.base_url = Some(value);
8193 }
8194 if matches!(active_provider, ProviderKind::Edenai)
8195 && let Ok(value) = std::env::var("EDENAI_BASE_URL")
8196 && !value.trim().is_empty()
8197 && let Ok(entry) = config.provider_config_for_mut(&identity)
8198 {
8199 entry.base_url = Some(value);
8200 }
8201 if matches!(active_provider, ProviderKind::Zenmux)
8202 && let Ok(value) = std::env::var("ZENMUX_BASE_URL")
8203 && !value.trim().is_empty()
8204 && let Ok(entry) = config.provider_config_for_mut(&identity)
8205 {
8206 entry.base_url = Some(value);
8207 }
8208 if matches!(active_provider, ProviderKind::Csdn)
8209 && let Ok(value) = std::env::var("CSDN_BASE_URL")
8210 && !value.trim().is_empty()
8211 && let Ok(entry) = config.provider_config_for_mut(&identity)
8212 {
8213 entry.base_url = Some(value);
8214 }
8215 if matches!(
8219 active_provider,
8220 ProviderKind::ModelstudioTokenPlan | ProviderKind::ModelstudioTokenPlanAnthropic
8221 ) && let Ok(value) = std::env::var("MODELSTUDIO_TOKEN_PLAN_BASE_URL")
8222 && !value.trim().is_empty()
8223 && let Ok(entry) = config.provider_config_for_mut(&identity)
8224 {
8225 entry.base_url = Some(value);
8226 }
8227 if matches!(
8228 active_provider,
8229 ProviderKind::ModelstudioCodingPlan | ProviderKind::ModelstudioCodingPlanAnthropic
8230 ) && let Ok(value) = std::env::var("MODELSTUDIO_CODING_PLAN_BASE_URL")
8231 && !value.trim().is_empty()
8232 && let Ok(entry) = config.provider_config_for_mut(&identity)
8233 {
8234 entry.base_url = Some(value);
8235 }
8236 if policy.permits_secret_bearing_values()
8237 && let Ok(value) = std::env::var("CODEWHALE_HTTP_HEADERS")
8238 .or_else(|_| std::env::var("DEEPSEEK_HTTP_HEADERS"))
8239 && let Ok(headers) = parse_http_headers(&value)
8240 && !headers.is_empty()
8241 {
8242 let mut root_headers = config.http_headers.clone().unwrap_or_default();
8243 root_headers.extend(headers.clone());
8244 config.http_headers = Some(root_headers);
8245
8246 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8247 let mut provider_headers = entry.http_headers.clone().unwrap_or_default();
8248 provider_headers.extend(headers);
8249 entry.http_headers = Some(provider_headers);
8250 }
8251 }
8252 if config.provider.as_deref().and_then(ProviderKind::parse) == Some(ProviderKind::Ollama)
8253 && let Ok(value) = std::env::var("OLLAMA_BASE_URL")
8254 && !value.trim().is_empty()
8255 && let Ok(entry) = config.provider_config_for_mut(&identity)
8256 {
8257 entry.base_url = Some(value);
8258 }
8259 if matches!(active_provider, ProviderKind::OllamaCloud)
8260 && config.provider.as_deref().and_then(ProviderKind::parse)
8261 == Some(ProviderKind::OllamaCloud)
8262 && let Ok(value) = std::env::var("OLLAMA_CLOUD_BASE_URL")
8263 && !value.trim().is_empty()
8264 && let Ok(entry) = config.provider_config_for_mut(&identity)
8265 {
8266 entry.base_url = Some(value);
8267 }
8268 if matches!(active_provider, ProviderKind::Sglang)
8269 && let Ok(value) = std::env::var("SGLANG_MODEL")
8270 {
8271 config.default_text_model = Some(value.clone());
8272 config
8273 .set_provider_model_override(&identity, Some(value))
8274 .unwrap();
8275 config.environment_model_applied = true;
8276 }
8277 if matches!(active_provider, ProviderKind::Vllm)
8278 && let Ok(value) = std::env::var("VLLM_MODEL")
8279 {
8280 config.default_text_model = Some(value.clone());
8281 config
8282 .set_provider_model_override(&identity, Some(value))
8283 .unwrap();
8284 config.environment_model_applied = true;
8285 }
8286 if matches!(
8287 active_provider,
8288 ProviderKind::Ollama | ProviderKind::OllamaCloud
8289 ) && let Ok(value) = std::env::var("OLLAMA_MODEL")
8290 {
8291 config.default_text_model = Some(value.clone());
8292 config
8293 .set_provider_model_override(&identity, Some(value))
8294 .unwrap();
8295 config.environment_model_applied = true;
8296 }
8297 if matches!(active_provider, ProviderKind::OllamaCloud)
8298 && let Ok(value) = std::env::var("OLLAMA_CLOUD_MODEL")
8299 {
8300 config.default_text_model = Some(value.clone());
8301 config
8302 .set_provider_model_override(&identity, Some(value))
8303 .unwrap();
8304 config.environment_model_applied = true;
8305 }
8306 if matches!(active_provider, ProviderKind::Openai)
8307 && let Ok(value) = std::env::var("OPENAI_MODEL")
8308 {
8309 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8310 entry.model = Some(value);
8311 }
8312 config.environment_model_applied = true;
8313 }
8314 if matches!(active_provider, ProviderKind::XiaomiMimo)
8315 && let Ok(value) =
8316 std::env::var("XIAOMI_MIMO_MODEL").or_else(|_| std::env::var("MIMO_MODEL"))
8317 {
8318 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8319 entry.model = Some(value);
8320 }
8321 config.environment_model_applied = true;
8322 }
8323 if matches!(active_provider, ProviderKind::Atlascloud)
8324 && let Ok(value) = std::env::var("ATLASCLOUD_MODEL")
8325 {
8326 config.default_text_model = Some(value.clone());
8327 config
8328 .set_provider_model_override(&identity, Some(value))
8329 .unwrap();
8330 config.environment_model_applied = true;
8331 }
8332 if matches!(active_provider, ProviderKind::WanjieArk)
8333 && let Ok(value) = std::env::var("WANJIE_ARK_MODEL")
8334 .or_else(|_| std::env::var("WANJIE_MODEL"))
8335 .or_else(|_| std::env::var("WANJIE_MAAS_MODEL"))
8336 && !value.trim().is_empty()
8337 {
8338 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8339 entry.model = Some(value);
8340 }
8341 config.environment_model_applied = true;
8342 }
8343 if matches!(active_provider, ProviderKind::Openrouter)
8344 && let Ok(value) = std::env::var("OPENROUTER_MODEL")
8345 && !value.trim().is_empty()
8346 {
8347 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8348 entry.model = Some(value);
8349 }
8350 config.environment_model_applied = true;
8351 }
8352 if matches!(active_provider, ProviderKind::Volcengine)
8353 && let Ok(value) =
8354 std::env::var("VOLCENGINE_MODEL").or_else(|_| std::env::var("VOLCENGINE_ARK_MODEL"))
8355 && !value.trim().is_empty()
8356 {
8357 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8358 entry.model = Some(value);
8359 }
8360 config.environment_model_applied = true;
8361 }
8362 if matches!(active_provider, ProviderKind::Novita)
8363 && let Ok(value) = std::env::var("NOVITA_MODEL")
8364 && !value.trim().is_empty()
8365 {
8366 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8367 entry.model = Some(value);
8368 }
8369 config.environment_model_applied = true;
8370 }
8371 if matches!(active_provider, ProviderKind::Fireworks)
8372 && let Ok(value) = std::env::var("FIREWORKS_MODEL")
8373 && !value.trim().is_empty()
8374 {
8375 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8376 entry.model = Some(value);
8377 }
8378 config.environment_model_applied = true;
8379 }
8380 if matches!(active_provider, ProviderKind::Moonshot)
8381 && let Ok(value) = std::env::var("MOONSHOT_MODEL")
8382 .or_else(|_| std::env::var("KIMI_MODEL_NAME"))
8383 .or_else(|_| std::env::var("KIMI_MODEL"))
8384 && !value.trim().is_empty()
8385 {
8386 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8387 entry.model = Some(value);
8388 }
8389 config.environment_model_applied = true;
8390 }
8391 if matches!(
8392 active_provider,
8393 ProviderKind::Siliconflow | ProviderKind::SiliconflowCN
8394 ) && let Ok(value) = std::env::var("SILICONFLOW_MODEL")
8395 && !value.trim().is_empty()
8396 {
8397 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8398 entry.model = Some(value);
8399 }
8400 config.environment_model_applied = true;
8401 }
8402 if matches!(active_provider, ProviderKind::Arcee)
8403 && let Ok(value) = std::env::var("ARCEE_MODEL")
8404 && !value.trim().is_empty()
8405 {
8406 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8407 entry.model = Some(value);
8408 }
8409 config.environment_model_applied = true;
8410 }
8411 if matches!(active_provider, ProviderKind::Huggingface)
8412 && let Ok(value) = std::env::var("HUGGINGFACE_MODEL").or_else(|_| std::env::var("HF_MODEL"))
8413 && !value.trim().is_empty()
8414 {
8415 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8416 entry.model = Some(value);
8417 }
8418 config.environment_model_applied = true;
8419 }
8420 if matches!(active_provider, ProviderKind::Modelscope)
8421 && let Ok(value) = std::env::var("MODELSCOPE_MODEL")
8422 && !value.trim().is_empty()
8423 {
8424 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8425 entry.model = Some(value);
8426 }
8427 config.environment_model_applied = true;
8428 }
8429 if matches!(active_provider, ProviderKind::Meta)
8430 && let Ok(value) =
8431 std::env::var("META_MODEL_API_MODEL").or_else(|_| std::env::var("MODEL_API_MODEL"))
8432 && !value.trim().is_empty()
8433 {
8434 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8435 entry.model = Some(value);
8436 }
8437 config.environment_model_applied = true;
8438 }
8439 if matches!(active_provider, ProviderKind::Xai)
8440 && let Ok(value) = std::env::var("XAI_MODEL")
8441 && !value.trim().is_empty()
8442 {
8443 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8444 entry.model = Some(value);
8445 }
8446 config.environment_model_applied = true;
8447 }
8448 if matches!(active_provider, ProviderKind::Mistral)
8449 && let Ok(value) = std::env::var("MISTRAL_MODEL")
8450 && !value.trim().is_empty()
8451 {
8452 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8453 entry.model = Some(value);
8454 }
8455 config.environment_model_applied = true;
8456 }
8457 if matches!(active_provider, ProviderKind::OpencodeGo)
8458 && let Ok(value) = std::env::var("OPENCODE_GO_MODEL")
8459 && !value.trim().is_empty()
8460 {
8461 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8462 entry.model = Some(value);
8463 }
8464 config.environment_model_applied = true;
8465 }
8466 if matches!(active_provider, ProviderKind::Telecomjs)
8467 && let Ok(value) = std::env::var("TELECOMJS_MODEL")
8468 && !value.trim().is_empty()
8469 {
8470 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8471 entry.model = Some(value);
8472 }
8473 config.environment_model_applied = true;
8474 }
8475 if matches!(active_provider, ProviderKind::Concentrate)
8476 && let Ok(value) = std::env::var("CONCENTRATE_MODEL")
8477 && !value.trim().is_empty()
8478 {
8479 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8480 entry.model = Some(value);
8481 }
8482 config.environment_model_applied = true;
8483 }
8484 if matches!(active_provider, ProviderKind::Edenai)
8485 && let Ok(value) = std::env::var("EDENAI_MODEL")
8486 && !value.trim().is_empty()
8487 {
8488 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8489 entry.model = Some(value);
8490 }
8491 config.environment_model_applied = true;
8492 }
8493 if matches!(active_provider, ProviderKind::Zenmux)
8494 && let Ok(value) = std::env::var("ZENMUX_MODEL")
8495 && !value.trim().is_empty()
8496 {
8497 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8498 entry.model = Some(value);
8499 }
8500 config.environment_model_applied = true;
8501 }
8502 if matches!(active_provider, ProviderKind::Csdn)
8503 && let Ok(value) = std::env::var("CSDN_MODEL")
8504 && !value.trim().is_empty()
8505 {
8506 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8507 entry.model = Some(value);
8508 }
8509 config.environment_model_applied = true;
8510 }
8511 if matches!(
8512 active_provider,
8513 ProviderKind::ModelstudioTokenPlan | ProviderKind::ModelstudioTokenPlanAnthropic
8514 ) && let Ok(value) = std::env::var("MODELSTUDIO_TOKEN_PLAN_MODEL")
8515 && !value.trim().is_empty()
8516 {
8517 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8518 entry.model = Some(value);
8519 }
8520 config.environment_model_applied = true;
8521 }
8522 if matches!(
8523 active_provider,
8524 ProviderKind::ModelstudioCodingPlan | ProviderKind::ModelstudioCodingPlanAnthropic
8525 ) && let Ok(value) = std::env::var("MODELSTUDIO_CODING_PLAN_MODEL")
8526 && !value.trim().is_empty()
8527 {
8528 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8529 entry.model = Some(value);
8530 }
8531 config.environment_model_applied = true;
8532 }
8533 if matches!(active_provider, ProviderKind::OpencodeZen)
8534 && let Ok(value) = std::env::var("OPENCODE_ZEN_MODEL")
8535 && !value.trim().is_empty()
8536 {
8537 if let Ok(entry) = config.provider_config_for_mut(&identity) {
8538 entry.model = Some(value);
8539 }
8540 config.environment_model_applied = true;
8541 }
8542 if matches!(active_provider, ProviderKind::NvidiaNim)
8543 && let Ok(value) = std::env::var("NVIDIA_NIM_MODEL")
8544 {
8545 config.default_text_model = Some(value.clone());
8546 config
8547 .set_provider_model_override(&identity, Some(value))
8548 .unwrap();
8549 config.environment_model_applied = true;
8550 }
8551 if let Some(value) = codewhale_env_var("CODEWHALE_MODEL", "DEEPSEEK_MODEL")
8552 .ok()
8553 .or_else(|| {
8554 std::env::var("DEEPSEEK_DEFAULT_TEXT_MODEL")
8555 .ok()
8556 .filter(|value| !value.trim().is_empty())
8557 })
8558 {
8559 if matches!(
8560 active_provider,
8561 ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
8562 ) {
8563 config.default_text_model = Some(value.clone());
8564 }
8565 config
8566 .set_provider_model_override(&identity, Some(value))
8567 .unwrap();
8568 config.environment_model_applied = true;
8569 }
8570 if let Ok(value) =
8571 std::env::var("CODEWHALE_SKILLS_DIR").or_else(|_| std::env::var("DEEPSEEK_SKILLS_DIR"))
8572 {
8573 config.skills_dir = Some(value);
8574 }
8575 if let Ok(value) =
8576 std::env::var("CODEWHALE_MCP_CONFIG").or_else(|_| std::env::var("DEEPSEEK_MCP_CONFIG"))
8577 {
8578 config.mcp_config_path = Some(value);
8579 }
8580 if let Ok(value) =
8581 std::env::var("CODEWHALE_NOTES_PATH").or_else(|_| std::env::var("DEEPSEEK_NOTES_PATH"))
8582 {
8583 config.notes_path = Some(value);
8584 }
8585 if let Ok(value) =
8586 std::env::var("CODEWHALE_MEMORY_PATH").or_else(|_| std::env::var("DEEPSEEK_MEMORY_PATH"))
8587 {
8588 config.memory_path = Some(value);
8589 }
8590 if let Ok(value) =
8591 std::env::var("CODEWHALE_MEMORY").or_else(|_| std::env::var("DEEPSEEK_MEMORY"))
8592 {
8593 let on = matches!(
8594 value.trim().to_ascii_lowercase().as_str(),
8595 "1" | "on" | "true" | "yes" | "y" | "enabled"
8596 );
8597 config
8598 .memory
8599 .get_or_insert_with(MemoryConfig::default)
8600 .enabled = Some(on);
8601 }
8602 if let Ok(value) =
8603 std::env::var("CODEWHALE_ALLOW_SHELL").or_else(|_| std::env::var("DEEPSEEK_ALLOW_SHELL"))
8604 {
8605 config.allow_shell = Some(value == "1" || value.eq_ignore_ascii_case("true"));
8606 }
8607 if let Ok(value) = std::env::var("CODEWHALE_APPROVAL_POLICY")
8608 .or_else(|_| std::env::var("DEEPSEEK_APPROVAL_POLICY"))
8609 {
8610 config.approval_policy = Some(value);
8611 }
8612 if let Ok(value) =
8613 std::env::var("CODEWHALE_SANDBOX_MODE").or_else(|_| std::env::var("DEEPSEEK_SANDBOX_MODE"))
8614 {
8615 config.sandbox_mode = Some(value);
8616 }
8617 if let Ok(value) = std::env::var("CODEWHALE_SANDBOX_NETWORK_ACCESS")
8618 .or_else(|_| std::env::var("DEEPSEEK_SANDBOX_NETWORK_ACCESS"))
8619 {
8620 config.sandbox_network_access = Some(value == "1" || value.eq_ignore_ascii_case("true"));
8621 }
8622 if let Ok(value) = std::env::var("CODEWHALE_PROJECT_INSTRUCTION_IMPORTS") {
8623 config.project_instruction_imports = value
8624 .split(',')
8625 .map(str::trim)
8626 .filter(|part| !part.is_empty())
8627 .map(str::to_string)
8628 .collect();
8629 }
8630 if let Ok(value) = std::env::var("CODEWHALE_YOLO").or_else(|_| std::env::var("DEEPSEEK_YOLO")) {
8634 config.yolo = Some(value == "1" || value.eq_ignore_ascii_case("true"));
8635 }
8636 if let Ok(value) =
8637 std::env::var("CODEWHALE_VERBOSITY").or_else(|_| std::env::var("DEEPSEEK_VERBOSITY"))
8638 {
8639 config.verbosity = Some(value);
8640 }
8641 if let Ok(value) = std::env::var("CODEWHALE_SANDBOX_BACKEND")
8642 .or_else(|_| std::env::var("DEEPSEEK_SANDBOX_BACKEND"))
8643 {
8644 config.sandbox_backend = Some(value);
8645 }
8646 if let Ok(value) = codewhale_env_var("CODEWHALE_PREFER_BWRAP", "DEEPSEEK_PREFER_BWRAP") {
8647 let primary_is_set = std::env::var("CODEWHALE_PREFER_BWRAP")
8648 .ok()
8649 .is_some_and(|value| !value.trim().is_empty());
8650 let legacy_is_set = std::env::var("DEEPSEEK_PREFER_BWRAP")
8651 .ok()
8652 .is_some_and(|value| !value.trim().is_empty());
8653 if !primary_is_set && legacy_is_set {
8654 tracing::warn!(
8655 "DEEPSEEK_PREFER_BWRAP is deprecated; use CODEWHALE_PREFER_BWRAP (the legacy alias is removed in 0.10.0)"
8656 );
8657 }
8658 config.prefer_bwrap = Some(value == "1" || value.eq_ignore_ascii_case("true"));
8659 }
8660 if let Ok(value) =
8661 std::env::var("CODEWHALE_SANDBOX_URL").or_else(|_| std::env::var("DEEPSEEK_SANDBOX_URL"))
8662 {
8663 config.sandbox_url = Some(value);
8664 }
8665 if policy.permits_secret_bearing_values()
8666 && let Ok(value) = std::env::var("CODEWHALE_SANDBOX_API_KEY")
8667 .or_else(|_| std::env::var("DEEPSEEK_SANDBOX_API_KEY"))
8668 {
8669 config.sandbox_api_key = Some(value);
8670 }
8671 if let Ok(value) = codewhale_env_var(
8672 "CODEWHALE_MANAGED_CONFIG_PATH",
8673 "DEEPSEEK_MANAGED_CONFIG_PATH",
8674 ) {
8675 config.managed_config_path = Some(value);
8676 }
8677 if policy.permits_secret_bearing_values()
8678 && let Ok(value) = std::env::var("CODEWHALE_SEARCH_API_KEY")
8679 .or_else(|_| std::env::var("DEEPSEEK_SEARCH_API_KEY"))
8680 && !value.trim().is_empty()
8681 {
8682 config
8683 .search
8684 .get_or_insert_with(SearchConfig::default)
8685 .api_key = Some(value);
8686 }
8687 if let Ok(value) = codewhale_env_var("CODEWHALE_SEARCH_BASE_URL", "DEEPSEEK_SEARCH_BASE_URL") {
8688 config
8689 .search
8690 .get_or_insert_with(SearchConfig::default)
8691 .base_url = Some(value);
8692 }
8693 if let Ok(value) = std::env::var("CODEWHALE_REQUIREMENTS_PATH")
8694 .or_else(|_| std::env::var("DEEPSEEK_REQUIREMENTS_PATH"))
8695 {
8696 config.requirements_path = Some(value);
8697 }
8698 if let Ok(value) = std::env::var("CODEWHALE_MAX_SUBAGENTS")
8699 .or_else(|_| std::env::var("DEEPSEEK_MAX_SUBAGENTS"))
8700 && let Ok(parsed) = value.parse::<usize>()
8701 {
8702 config.max_subagents = Some(parsed.clamp(1, MAX_SUBAGENTS));
8703 }
8704 config.base_url_env_receipt = if active_base_url_from_env {
8709 BaseUrlEnvReceipt::Route(active_provider, identity.key.to_string())
8710 } else {
8711 BaseUrlEnvReceipt::NoOwner
8712 };
8713}
8714
8715fn normalize_model_config(config: &mut Config) {
8716 if config.default_text_model.is_none() {
8717 config.default_text_model.clone_from(&config.legacy_model);
8718 }
8719 let Ok(identity) = config.active_provider_identity() else {
8720 return;
8721 };
8722 let provider = identity.provider;
8723 let base_url = config.active_route_base_url();
8724 let mut declared = Vec::new();
8725 for row in codewhale_config::descriptors::provider_compatibility() {
8726 let Ok(candidate) = config.resolve_persisted_provider_identity(Some(row.id), Some(row.id))
8727 else {
8728 continue;
8729 };
8730 for model in config.custom_models.as_deref().unwrap_or_default() {
8731 if configured_model_for_route(
8732 config,
8733 candidate.provider,
8734 candidate.key.as_str(),
8735 &config.base_url_for_route(&candidate),
8736 &model.id,
8737 )
8738 .is_some()
8739 {
8740 declared.push((candidate.key.clone(), model.id.clone()));
8741 }
8742 }
8743 }
8744 let is_declared = |key: &str, model: &str| {
8745 declared
8746 .iter()
8747 .any(|(id, value)| id.as_str() == key && value == model)
8748 };
8749 config.migrated_deepseek_model_alias = if matches!(
8750 provider,
8751 ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
8752 ) {
8753 config
8754 .active_configured_model_id()
8755 .filter(|model| !is_declared(identity.key.as_str(), model))
8756 .map(str::to_ascii_lowercase)
8757 .filter(|model| deepseek_alias_deprecation(model).is_some())
8758 .filter(|model| {
8759 codewhale_config::route::resolve_model(provider, model, Some(&base_url))
8760 .is_ok_and(|resolved| resolved.wire_id != model.as_str())
8761 })
8762 } else {
8763 None
8764 };
8765
8766 if config.reasoning_effort.is_none() {
8767 let alias_effort = config
8768 .migrated_deepseek_model_alias
8769 .as_deref()
8770 .and_then(legacy_deepseek_alias_reasoning_effort);
8771 if let Some(effort) = alias_effort {
8772 config.reasoning_effort = Some(effort.to_string());
8773 config.reasoning_effort_inferred_from_legacy_alias = true;
8774 }
8775 }
8776
8777 if let Some(model) = config.default_text_model.as_deref()
8778 && !is_declared(identity.key.as_str(), model)
8779 && !codewhale_config::descriptors::provider_passes_model_through(provider)
8780 && !config.active_provider_preserves_custom_base_url_model()
8781 && let Ok(resolved) = codewhale_config::route::resolve_model(provider, model, None)
8782 {
8783 config.default_text_model = Some(resolved.wire_id);
8784 }
8785
8786 if let Some(providers) = config.providers.as_mut() {
8787 if let Some(model) = providers.deepseek.model.as_deref()
8788 && !provider_entry_uses_custom_base_url(ProviderKind::Deepseek, &providers.deepseek)
8789 && !is_declared(ProviderKind::Deepseek.as_str(), model)
8790 && let Ok(resolved) =
8791 codewhale_config::route::resolve_model(ProviderKind::Deepseek, model, None)
8792 {
8793 providers.deepseek.model = Some(resolved.wire_id);
8794 }
8795 if let Some(model) = providers.deepseek_cn.model.as_deref()
8796 && !provider_entry_uses_custom_base_url(ProviderKind::Deepseek, &providers.deepseek_cn)
8797 && !is_declared(codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id, model)
8798 && let Ok(resolved) =
8799 codewhale_config::route::resolve_model(ProviderKind::Deepseek, model, None)
8800 {
8801 providers.deepseek_cn.model = Some(resolved.wire_id);
8802 }
8803 if let Some(model) = providers.deepseek_anthropic.model.as_deref()
8804 && !provider_entry_uses_custom_base_url(
8805 ProviderKind::DeepseekAnthropic,
8806 &providers.deepseek_anthropic,
8807 )
8808 && !is_declared(ProviderKind::DeepseekAnthropic.as_str(), model)
8809 && let Ok(resolved) =
8810 codewhale_config::route::resolve_model(ProviderKind::DeepseekAnthropic, model, None)
8811 {
8812 providers.deepseek_anthropic.model = Some(resolved.wire_id);
8813 }
8814 if let Some(model) = providers.nvidia_nim.model.as_deref()
8815 && !provider_entry_uses_custom_base_url(ProviderKind::NvidiaNim, &providers.nvidia_nim)
8816 && !is_declared(ProviderKind::NvidiaNim.as_str(), model)
8817 && let Ok(resolved) =
8818 codewhale_config::route::resolve_model(ProviderKind::NvidiaNim, model, None)
8819 {
8820 providers.nvidia_nim.model = Some(resolved.wire_id);
8821 }
8822 if let Some(model) = providers.openrouter.model.as_deref()
8823 && !provider_entry_uses_custom_base_url(ProviderKind::Openrouter, &providers.openrouter)
8824 && !is_declared(ProviderKind::Openrouter.as_str(), model)
8825 && let Ok(resolved) =
8826 codewhale_config::route::resolve_model(ProviderKind::Openrouter, model, None)
8827 {
8828 providers.openrouter.model = Some(resolved.wire_id);
8829 }
8830 if let Some(model) = providers.novita.model.as_deref()
8831 && !provider_entry_uses_custom_base_url(ProviderKind::Novita, &providers.novita)
8832 && !is_declared(ProviderKind::Novita.as_str(), model)
8833 && let Ok(resolved) =
8834 codewhale_config::route::resolve_model(ProviderKind::Novita, model, None)
8835 {
8836 providers.novita.model = Some(resolved.wire_id);
8837 }
8838 if let Some(model) = providers.fireworks.model.as_deref()
8839 && !provider_entry_uses_custom_base_url(ProviderKind::Fireworks, &providers.fireworks)
8840 && !is_declared(ProviderKind::Fireworks.as_str(), model)
8841 && let Ok(resolved) =
8842 codewhale_config::route::resolve_model(ProviderKind::Fireworks, model, None)
8843 {
8844 providers.fireworks.model = Some(resolved.wire_id);
8845 }
8846 if let Some(model) = providers.siliconflow.model.as_deref()
8847 && !provider_entry_uses_custom_base_url(
8848 ProviderKind::Siliconflow,
8849 &providers.siliconflow,
8850 )
8851 && !is_declared(ProviderKind::Siliconflow.as_str(), model)
8852 && let Ok(resolved) =
8853 codewhale_config::route::resolve_model(ProviderKind::Siliconflow, model, None)
8854 {
8855 providers.siliconflow.model = Some(resolved.wire_id);
8856 }
8857 if let Some(model) = providers.siliconflow_cn.model.as_deref()
8858 && !provider_entry_uses_custom_base_url(
8859 ProviderKind::SiliconflowCN,
8860 &providers.siliconflow_cn,
8861 )
8862 && !is_declared(ProviderKind::SiliconflowCN.as_str(), model)
8863 && let Ok(resolved) =
8864 codewhale_config::route::resolve_model(ProviderKind::SiliconflowCN, model, None)
8865 {
8866 providers.siliconflow_cn.model = Some(resolved.wire_id);
8867 }
8868 if let Some(model) = providers.moonshot.model.as_deref()
8869 && !provider_entry_uses_custom_base_url(ProviderKind::Moonshot, &providers.moonshot)
8870 && !is_declared(ProviderKind::Moonshot.as_str(), model)
8871 && let Ok(resolved) =
8872 codewhale_config::route::resolve_model(ProviderKind::Moonshot, model, None)
8873 {
8874 providers.moonshot.model = Some(resolved.wire_id);
8875 }
8876 if let Some(model) = providers.sglang.model.as_deref()
8877 && !provider_entry_uses_custom_base_url(ProviderKind::Sglang, &providers.sglang)
8878 && !is_declared(ProviderKind::Sglang.as_str(), model)
8879 && let Ok(resolved) =
8880 codewhale_config::route::resolve_model(ProviderKind::Sglang, model, None)
8881 {
8882 providers.sglang.model = Some(resolved.wire_id);
8883 }
8884 if let Some(model) = providers.vllm.model.as_deref()
8885 && !provider_entry_uses_custom_base_url(ProviderKind::Vllm, &providers.vllm)
8886 && !is_declared(ProviderKind::Vllm.as_str(), model)
8887 && let Ok(resolved) =
8888 codewhale_config::route::resolve_model(ProviderKind::Vllm, model, None)
8889 {
8890 providers.vllm.model = Some(resolved.wire_id);
8891 }
8892 if let Some(model) = providers.deepinfra.model.as_deref()
8893 && !provider_entry_uses_custom_base_url(ProviderKind::Deepinfra, &providers.deepinfra)
8894 && !is_declared(ProviderKind::Deepinfra.as_str(), model)
8895 && let Ok(resolved) =
8896 codewhale_config::route::resolve_model(ProviderKind::Deepinfra, model, None)
8897 {
8898 providers.deepinfra.model = Some(resolved.wire_id);
8899 }
8900 }
8901}
8902
8903#[cfg(any(test, feature = "test-support"))]
8904pub fn normalize_model_config_for_test(config: &mut Config) {
8905 normalize_model_config(config);
8906}
8907
8908fn provider_entry_uses_custom_base_url(provider: ProviderKind, entry: &ProviderConfig) -> bool {
8909 entry
8910 .base_url
8911 .as_deref()
8912 .is_some_and(|base_url| provider_preserves_custom_base_url_model(provider, base_url))
8913}
8914
8915fn xiaomi_mimo_base_url_uses_token_plan(base_url: &str) -> bool {
8916 let normalized = normalize_base_url(base_url).to_ascii_lowercase();
8917 normalized == XIAOMI_MIMO_TOKEN_PLAN_CN_BASE_URL
8918 || normalized == XIAOMI_MIMO_TOKEN_PLAN_SGP_BASE_URL
8919 || normalized == XIAOMI_MIMO_TOKEN_PLAN_AMS_BASE_URL
8920}
8921
8922fn xiaomi_mimo_env_var(candidates: &[&str]) -> Option<String> {
8923 candidates.iter().find_map(|name| {
8924 std::env::var(name)
8925 .ok()
8926 .filter(|value| !value.trim().is_empty())
8927 })
8928}
8929
8930fn xiaomi_mimo_env_api_key_for_runtime(
8931 mode: Option<&str>,
8932 base_url: Option<&str>,
8933) -> Option<String> {
8934 const TOKEN_PLAN_ENV_VARS: &[&str] =
8935 &["XIAOMI_MIMO_TOKEN_PLAN_API_KEY", "MIMO_TOKEN_PLAN_API_KEY"];
8936 const STANDARD_ENV_VARS: &[&str] = &["XIAOMI_MIMO_API_KEY", "XIAOMI_API_KEY", "MIMO_API_KEY"];
8937
8938 let normalized_mode =
8939 mode.map(|value| value.trim().to_ascii_lowercase().replace(['_', ' '], "-"));
8940 let standard_selected = normalized_mode
8941 .as_deref()
8942 .is_some_and(xiaomi_mimo_mode_uses_standard_endpoint)
8943 || base_url.is_some_and(xiaomi_mimo_base_url_is_pay_as_you_go);
8944 if standard_selected {
8945 return xiaomi_mimo_env_var(STANDARD_ENV_VARS);
8946 }
8947
8948 let token_plan_selected = normalized_mode
8949 .as_deref()
8950 .and_then(xiaomi_mimo_base_url_for_mode)
8951 .is_some()
8952 || base_url.is_some_and(xiaomi_mimo_base_url_uses_token_plan);
8953 if token_plan_selected {
8954 return xiaomi_mimo_env_var(TOKEN_PLAN_ENV_VARS);
8955 }
8956
8957 xiaomi_mimo_env_var(TOKEN_PLAN_ENV_VARS).or_else(|| xiaomi_mimo_env_var(STANDARD_ENV_VARS))
8958}
8959
8960fn wire_config_prefers_anthropic(wire: Option<&str>) -> bool {
8961 codewhale_config::provider::wire_dialect_prefers_anthropic(wire)
8962}
8963
8964fn modelstudio_mode_is_coding_plan(provider: ProviderKind, mode: Option<&str>) -> bool {
8965 if matches!(
8966 provider,
8967 ProviderKind::ModelstudioCodingPlan | ProviderKind::ModelstudioCodingPlanAnthropic
8968 ) {
8969 return true;
8970 }
8971 let Some(raw) = mode.map(str::trim).filter(|value| !value.is_empty()) else {
8972 return false;
8973 };
8974 let normalized = raw.to_ascii_lowercase().replace(['_', ' '], "-");
8975 matches!(
8976 normalized.as_str(),
8977 "coding-plan" | "coding" | "codingplan" | "dashscope-coding" | "code"
8978 )
8979}
8980
8981fn resolve_modelstudio_base_url_for_tui(
8982 configured: Option<String>,
8983 provider: ProviderKind,
8984 mode: Option<&str>,
8985 wire: Option<&str>,
8986) -> String {
8987 if let Some(url) = configured.filter(|value| !value.trim().is_empty()) {
8988 return url;
8989 }
8990 let coding = modelstudio_mode_is_coding_plan(provider, mode);
8991 let anthropic = matches!(
8992 provider,
8993 ProviderKind::ModelstudioTokenPlanAnthropic | ProviderKind::ModelstudioCodingPlanAnthropic
8994 ) || wire_config_prefers_anthropic(wire);
8995 match (coding, anthropic) {
8996 (true, true) => MODELSTUDIO_CODING_PLAN_ANTHROPIC_BASE_URL.to_string(),
8997 (true, false) => DEFAULT_MODELSTUDIO_CODING_PLAN_BASE_URL.to_string(),
8998 (false, true) => MODELSTUDIO_TOKEN_PLAN_ANTHROPIC_BASE_URL.to_string(),
8999 (false, false) => DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL.to_string(),
9000 }
9001}
9002
9003fn resolve_minimax_base_url_for_tui(
9004 configured: Option<String>,
9005 provider: ProviderKind,
9006 wire: Option<&str>,
9007) -> String {
9008 if let Some(url) = configured.filter(|value| !value.trim().is_empty()) {
9009 return url;
9010 }
9011 if matches!(provider, ProviderKind::MinimaxAnthropic) || wire_config_prefers_anthropic(wire) {
9012 DEFAULT_MINIMAX_ANTHROPIC_BASE_URL.to_string()
9013 } else {
9014 DEFAULT_MINIMAX_BASE_URL.to_string()
9015 }
9016}
9017
9018fn resolve_deepseek_base_url_for_tui(
9019 configured: Option<String>,
9020 provider: ProviderKind,
9021 wire: Option<&str>,
9022) -> String {
9023 if let Some(url) = configured.filter(|value| !value.trim().is_empty()) {
9024 return url;
9025 }
9026 if matches!(provider, ProviderKind::DeepseekAnthropic) || wire_config_prefers_anthropic(wire) {
9027 DEFAULT_DEEPSEEK_ANTHROPIC_BASE_URL.to_string()
9028 } else {
9029 DEFAULT_DEEPSEEK_BASE_URL.to_string()
9030 }
9031}
9032
9033fn xiaomi_mimo_base_url_is_pay_as_you_go(base_url: &str) -> bool {
9034 matches!(
9035 normalize_base_url(base_url).to_ascii_lowercase().as_str(),
9036 "https://api.xiaomimimo.com" | "https://api.xiaomimimo.com/v1"
9037 )
9038}
9039
9040fn base_url_is_custom_for_provider(provider: ProviderKind, base_url: &str) -> bool {
9041 codewhale_config::provider_preserves_custom_base_url_model(provider, base_url)
9042}
9043
9044pub fn provider_route_is_keyless_self_hosted(provider: ProviderKind, base_url: &str) -> bool {
9052 if provider == ProviderKind::Ollama {
9053 return base_url_uses_local_host(base_url);
9054 }
9055 matches!(
9056 provider,
9057 ProviderKind::Ollama | ProviderKind::Sglang | ProviderKind::Vllm
9058 )
9059}
9060
9061pub fn moonshot_base_url_is_exact_kimi_code(base_url: &str) -> bool {
9066 codewhale_config::provider::is_exact_kimi_code_route(
9067 codewhale_config::ProviderKind::Moonshot,
9068 base_url,
9069 )
9070}
9071
9072pub fn moonshot_base_url_is_exact_direct_platform(base_url: &str) -> bool {
9076 codewhale_config::provider::is_exact_moonshot_platform_route(
9077 codewhale_config::ProviderKind::Moonshot,
9078 base_url,
9079 )
9080}
9081
9082pub fn is_exact_direct_moonshot_k3_route(
9084 provider: ProviderKind,
9085 base_url: &str,
9086 model: &str,
9087) -> bool {
9088 provider == ProviderKind::Moonshot
9089 && moonshot_base_url_is_exact_direct_platform(base_url)
9090 && model.trim().eq_ignore_ascii_case(MOONSHOT_KIMI_K3_MODEL)
9091}
9092
9093pub fn is_exact_kimi_code_k3_route(provider: ProviderKind, base_url: &str, model: &str) -> bool {
9095 provider == ProviderKind::Moonshot
9096 && moonshot_base_url_is_exact_kimi_code(base_url)
9097 && [KIMI_CODE_K3_MODEL, KIMI_CODE_K3_256K_MODEL]
9098 .iter()
9099 .any(|id| model.trim().eq_ignore_ascii_case(id))
9100}
9101
9102#[must_use]
9106pub fn is_exact_kimi_code_bare_k3_route(
9107 provider: ProviderKind,
9108 base_url: &str,
9109 model: &str,
9110) -> bool {
9111 provider == ProviderKind::Moonshot
9112 && moonshot_base_url_is_exact_kimi_code(base_url)
9113 && model.trim().eq_ignore_ascii_case(KIMI_CODE_K3_MODEL)
9114}
9115
9116#[must_use]
9118pub fn is_exact_zai_chat_route(provider: ProviderKind, base_url: &str) -> bool {
9119 provider == ProviderKind::Zai
9120 && codewhale_config::provider::is_exact_zai_chat_route(
9121 codewhale_config::ProviderKind::Zai,
9122 base_url,
9123 )
9124}
9125
9126#[must_use]
9135pub fn is_exact_zai_tiered_effort_route(
9136 provider: ProviderKind,
9137 base_url: &str,
9138 model: &str,
9139) -> bool {
9140 is_exact_zai_chat_route(provider, base_url)
9141 && (model.trim().eq_ignore_ascii_case(ZAI_GLM_5_2_MODEL)
9142 || is_exact_zai_forced_thinking_route(provider, base_url, model))
9143}
9144
9145#[must_use]
9155pub fn is_exact_zai_forced_thinking_route(
9156 provider: ProviderKind,
9157 base_url: &str,
9158 model: &str,
9159) -> bool {
9160 is_exact_zai_chat_route(provider, base_url)
9161 && (model.trim().eq_ignore_ascii_case(ZAI_GLM_5_3_MODEL)
9162 || model.trim().eq_ignore_ascii_case(ZAI_GLM_5_3_FLASH_MODEL))
9163}
9164
9165#[must_use]
9167pub(crate) fn is_exact_zai_glm_5_turbo_route(
9168 provider: ProviderKind,
9169 base_url: &str,
9170 model: &str,
9171) -> bool {
9172 is_exact_zai_chat_route(provider, base_url)
9173 && model.trim().eq_ignore_ascii_case(ZAI_GLM_5_TURBO_MODEL)
9174}
9175
9176#[must_use]
9180pub fn is_exact_known_zai_reasoning_route(
9181 provider: ProviderKind,
9182 base_url: &str,
9183 model: &str,
9184) -> bool {
9185 is_exact_zai_tiered_effort_route(provider, base_url, model)
9186 || is_exact_zai_glm_5_turbo_route(provider, base_url, model)
9187 || (is_exact_zai_chat_route(provider, base_url)
9188 && model.trim().eq_ignore_ascii_case(ZAI_GLM_5_1_MODEL))
9189}
9190
9191#[must_use]
9198pub fn minimax_base_url_is_supported_direct(base_url: &str) -> bool {
9199 codewhale_config::provider::is_exact_minimax_chat_route(
9200 codewhale_config::ProviderKind::Minimax,
9201 base_url,
9202 ) || codewhale_config::provider::is_exact_minimax_anthropic_route(
9203 codewhale_config::ProviderKind::MinimaxAnthropic,
9204 base_url,
9205 )
9206}
9207
9208#[must_use]
9212pub fn is_exact_minimax_m3_route(provider: ProviderKind, base_url: &str, model: &str) -> bool {
9213 provider == ProviderKind::Minimax
9214 && codewhale_config::provider::is_exact_minimax_chat_route(
9215 codewhale_config::ProviderKind::Minimax,
9216 base_url,
9217 )
9218 && model.trim().eq_ignore_ascii_case(DEFAULT_MINIMAX_MODEL)
9219}
9220
9221#[must_use]
9225pub fn is_exact_minimax_anthropic_m3_route(
9226 provider: ProviderKind,
9227 base_url: &str,
9228 model: &str,
9229) -> bool {
9230 provider == ProviderKind::MinimaxAnthropic
9231 && codewhale_config::provider::is_exact_minimax_anthropic_route(
9232 codewhale_config::ProviderKind::MinimaxAnthropic,
9233 base_url,
9234 )
9235 && model.trim().eq_ignore_ascii_case(DEFAULT_MINIMAX_MODEL)
9236}
9237
9238#[must_use]
9239pub fn minimax_m3_route_uses_max_completion_tokens(
9240 provider: ProviderKind,
9241 base_url: &str,
9242 model: &str,
9243) -> bool {
9244 is_exact_minimax_m3_route(provider, base_url, model)
9245}
9246
9247pub const KIMI_CODE_MEMBERSHIP_MODELS: [&str; 4] = [
9255 KIMI_CODE_K3_MODEL,
9256 KIMI_CODE_K3_256K_MODEL,
9257 DEFAULT_KIMI_CODE_MODEL,
9258 KIMI_CODE_HIGHSPEED_MODEL,
9259];
9260
9261#[must_use]
9267pub fn is_kimi_code_membership_model(model: &str) -> bool {
9268 let model = model.trim();
9269 KIMI_CODE_MEMBERSHIP_MODELS
9270 .iter()
9271 .any(|id| model.eq_ignore_ascii_case(id))
9272}
9273
9274fn deepseek_missing_key_message() -> &'static str {
9278 concat!(
9279 "DeepSeek API key not found.\n",
9280 "Save a key for every folder:\n",
9281 " codewhale auth set --provider deepseek\n",
9282 "Get a key: https://platform.deepseek.com/api_keys\n",
9283 "Or export DEEPSEEK_API_KEY=<your-key> (this shell only).\n",
9284 "In zsh, ~/.zshrc is read only by interactive shells.\n",
9285 "Or set api_key in ~/.codewhale/config.toml.\n",
9286 "If you already use DeepSeek Harness, grant read-only access:\n",
9287 " codewhale auth external-consent --provider deepseek --mode read-only"
9288 )
9289}
9290
9291pub(crate) const MOONSHOT_DIRECT_PLATFORM_MODELS: [&str; 3] = [
9294 MOONSHOT_KIMI_K3_MODEL,
9295 DEFAULT_MOONSHOT_MODEL,
9296 MOONSHOT_KIMI_K2_6_MODEL,
9297];
9298
9299pub(crate) const KIMI_CODE_CLAUDE_ALIAS_GUIDANCE: &str = "Kimi Code model `k3[1m]` is a Claude Code environment convention, not an API model id. Use model = \"k3\". If your Kimi Code plan includes 1M context, also set context_window = 1048576; otherwise keep the 262144 safe default.";
9300
9301#[derive(Debug, thiserror::Error)]
9305pub enum SafeConfigDiagnostic {
9306 #[error("{}", KIMI_CODE_CLAUDE_ALIAS_GUIDANCE)]
9307 KimiCodeClaudeAlias,
9308 #[error("{message}")]
9312 InvalidValue {
9313 message: String,
9314 shareable: String,
9315 fix: Option<String>,
9317 },
9318}
9319
9320impl SafeConfigDiagnostic {
9321 fn invalid_value(key: &str, value: &str, expected: &str, fix: String) -> Self {
9322 Self::InvalidValue {
9323 message: format!("Invalid {key} '{value}': expected {expected}."),
9324 shareable: format!("Invalid {key} (value not shown): expected {expected}."),
9325 fix: Some(fix),
9326 }
9327 }
9328
9329 pub fn display_message(&self) -> String {
9332 let text = match self {
9333 Self::KimiCodeClaudeAlias => self.to_string(),
9334 Self::InvalidValue { shareable, .. } => shareable.clone(),
9335 };
9336 codewhale_sanitize::redact::redact_secrets(&text)
9337 }
9338
9339 pub fn fix(&self) -> Option<&str> {
9340 match self {
9341 Self::KimiCodeClaudeAlias => None,
9342 Self::InvalidValue { fix, .. } => fix.as_deref(),
9343 }
9344 }
9345
9346 pub fn find_in(error: &anyhow::Error) -> Option<&Self> {
9349 error.chain().find_map(|cause| cause.downcast_ref::<Self>())
9350 }
9351}
9352
9353fn user_config_fix(key: &str, valid: &str, env_var: Option<&str>) -> String {
9358 let edit = match key.split_once('.') {
9359 Some((table, field)) => {
9360 format!("set {field} = \"{valid}\" in the [{table}] table of config.toml")
9361 }
9362 None => format!("codewhale config set {key} {valid}"),
9363 };
9364 let layers = match env_var {
9365 Some(env_var) => format!("{env_var}, a profile, or managed config"),
9366 None => "a profile or managed config".to_string(),
9367 };
9368 format!("{edit} (if {layers} sets it, correct it there)")
9369}
9370
9371fn invalid_provider_diagnostic(provider: &str) -> SafeConfigDiagnostic {
9372 SafeConfigDiagnostic::invalid_value(
9373 "provider",
9374 provider,
9375 &ProviderKind::names_hint(),
9376 user_config_fix(
9377 "provider",
9378 ProviderKind::Deepseek.as_str(),
9379 Some("CODEWHALE_PROVIDER"),
9380 ),
9381 )
9382}
9383
9384pub(crate) fn invalid_provider_message(provider: &str) -> String {
9387 invalid_provider_diagnostic(provider).to_string()
9388}
9389
9390pub fn validate_kimi_code_api_model_id(
9395 provider: ProviderKind,
9396 base_url: &str,
9397 model: &str,
9398) -> std::result::Result<(), String> {
9399 if provider != ProviderKind::Moonshot {
9400 return Ok(());
9401 }
9402 let model = model.trim();
9403 if model.is_empty() {
9404 return Ok(());
9405 }
9406
9407 if moonshot_base_url_is_exact_kimi_code(base_url) {
9408 if model.eq_ignore_ascii_case("k3[1m]") {
9409 return Err(KIMI_CODE_CLAUDE_ALIAS_GUIDANCE.to_string());
9410 }
9411 for direct_id in MOONSHOT_DIRECT_PLATFORM_MODELS {
9412 if model.eq_ignore_ascii_case(direct_id) {
9413 return Err(format!(
9414 "Kimi Code membership route (api.kimi.com/coding/v1) does not accept model = \"{model}\": it is a direct Moonshot platform id. Use a Kimi Code membership model (\"k3\", \"k3-256k\", \"kimi-for-coding\", or \"kimi-for-coding-highspeed\") for this base_url. Direct Moonshot pay-as-you-go uses base_url = \"https://api.moonshot.ai/v1\" with model = \"{direct_id}\"."
9415 ));
9416 }
9417 }
9418 return Ok(());
9419 }
9420
9421 if moonshot_base_url_is_exact_direct_platform(base_url) {
9422 for membership_id in KIMI_CODE_MEMBERSHIP_MODELS {
9423 if model.eq_ignore_ascii_case(membership_id) {
9424 return Err(format!(
9425 "Moonshot direct route (api.moonshot.ai/v1) does not accept model = \"{model}\": it is a Kimi Code membership model id, not a direct-platform catalog model. Kimi Code membership uses base_url = \"https://api.kimi.com/coding/v1\" with model = \"{membership_id}\"; direct Moonshot pay-as-you-go K3 uses model = \"kimi-k3\"."
9426 ));
9427 }
9428 }
9429 }
9430
9431 Ok(())
9432}
9433
9434#[cfg(test)]
9435mod kimi_code_pairing_tests {
9436 use super::*;
9437
9438 #[test]
9439 fn membership_roster_passes_on_kimi_code_endpoint() {
9440 for model in [
9441 KIMI_CODE_K3_MODEL,
9442 KIMI_CODE_K3_256K_MODEL,
9443 DEFAULT_KIMI_CODE_MODEL,
9444 KIMI_CODE_HIGHSPEED_MODEL,
9445 ] {
9446 assert!(
9447 validate_kimi_code_api_model_id(
9448 ProviderKind::Moonshot,
9449 DEFAULT_KIMI_CODE_BASE_URL,
9450 model,
9451 )
9452 .is_ok(),
9453 "{model} must be accepted on the exact Kimi Code membership endpoint"
9454 );
9455 }
9456 }
9457
9458 #[test]
9459 fn direct_platform_ids_fail_on_kimi_code_endpoint() {
9460 for model in [
9461 MOONSHOT_KIMI_K3_MODEL,
9462 DEFAULT_MOONSHOT_MODEL,
9463 MOONSHOT_KIMI_K2_6_MODEL,
9464 ] {
9465 let err = validate_kimi_code_api_model_id(
9466 ProviderKind::Moonshot,
9467 DEFAULT_KIMI_CODE_BASE_URL,
9468 model,
9469 )
9470 .expect_err("direct-platform ids are not Kimi Code membership roster models");
9471 assert!(err.contains(model), "{err}");
9472 assert!(err.contains("api.moonshot.ai/v1"), "{err}");
9473 }
9474 }
9475
9476 #[test]
9477 fn membership_ids_fail_on_direct_moonshot_endpoint() {
9478 for model in [
9479 KIMI_CODE_K3_MODEL,
9480 KIMI_CODE_K3_256K_MODEL,
9481 DEFAULT_KIMI_CODE_MODEL,
9482 KIMI_CODE_HIGHSPEED_MODEL,
9483 ] {
9484 let err = validate_kimi_code_api_model_id(
9485 ProviderKind::Moonshot,
9486 DEFAULT_MOONSHOT_BASE_URL,
9487 model,
9488 )
9489 .expect_err("membership ids are not direct-platform catalog models");
9490 assert!(err.contains(model), "{err}");
9491 assert!(err.contains("api.kimi.com/coding/v1"), "{err}");
9492 }
9493 }
9494
9495 #[test]
9496 fn canonical_pairs_pass_and_custom_gateways_are_untouched() {
9497 for (base_url, model) in [
9499 (DEFAULT_KIMI_CODE_BASE_URL, KIMI_CODE_K3_MODEL),
9500 (DEFAULT_KIMI_CODE_BASE_URL, KIMI_CODE_K3_256K_MODEL),
9501 (DEFAULT_KIMI_CODE_BASE_URL, DEFAULT_KIMI_CODE_MODEL),
9502 (DEFAULT_KIMI_CODE_BASE_URL, KIMI_CODE_HIGHSPEED_MODEL),
9503 (DEFAULT_MOONSHOT_BASE_URL, MOONSHOT_KIMI_K3_MODEL),
9504 (DEFAULT_MOONSHOT_BASE_URL, DEFAULT_MOONSHOT_MODEL),
9505 (DEFAULT_MOONSHOT_BASE_URL, MOONSHOT_KIMI_K2_6_MODEL),
9506 ] {
9507 assert!(
9508 validate_kimi_code_api_model_id(ProviderKind::Moonshot, base_url, model).is_ok(),
9509 "{base_url} / {model}"
9510 );
9511 }
9512 assert!(
9514 validate_kimi_code_api_model_id(
9515 ProviderKind::Moonshot,
9516 DEFAULT_KIMI_CODE_BASE_URL,
9517 MOONSHOT_KIMI_K3_MODEL,
9518 )
9519 .is_err()
9520 );
9521 assert!(
9522 validate_kimi_code_api_model_id(
9523 ProviderKind::Moonshot,
9524 DEFAULT_MOONSHOT_BASE_URL,
9525 KIMI_CODE_K3_MODEL,
9526 )
9527 .is_err()
9528 );
9529 for model in [
9532 KIMI_CODE_K3_MODEL,
9533 KIMI_CODE_K3_256K_MODEL,
9534 DEFAULT_KIMI_CODE_MODEL,
9535 KIMI_CODE_HIGHSPEED_MODEL,
9536 MOONSHOT_KIMI_K3_MODEL,
9537 ] {
9538 assert!(
9539 validate_kimi_code_api_model_id(
9540 ProviderKind::Moonshot,
9541 "https://proxy.example/v1",
9542 model,
9543 )
9544 .is_ok(),
9545 "{model} on a custom gateway"
9546 );
9547 }
9548 }
9549}
9550
9551pub fn moonshot_k3_route_display_name(base_url: &str, model: &str) -> Option<&'static str> {
9553 if is_exact_kimi_code_bare_k3_route(ProviderKind::Moonshot, base_url, model) {
9554 return Some("Kimi Code membership / k3");
9555 }
9556 if is_exact_kimi_code_k3_route(ProviderKind::Moonshot, base_url, model) {
9557 return Some("Kimi Code membership / k3-256k");
9558 }
9559 if is_exact_direct_moonshot_k3_route(ProviderKind::Moonshot, base_url, model) {
9560 return Some("Moonshot direct / kimi-k3");
9561 }
9562 None
9563}
9564
9565pub fn credential_help_for_provider_route(
9573 provider: ProviderKind,
9574 base_url: &str,
9575) -> codewhale_config::provider::CredentialHelp {
9576 codewhale_config::provider::credential_help_for_route(provider, base_url)
9577}
9578
9579pub fn provider_config_uses_kimi_imported_token(config: &ProviderConfig) -> bool {
9580 config
9581 .auth_mode
9582 .as_deref()
9583 .is_some_and(auth_mode_uses_kimi_imported_token)
9584}
9585
9586use codewhale_config::{
9587 auth_mode_disables_api_key, auth_mode_requires_api_key, auth_mode_uses_kimi_imported_token,
9588};
9589
9590fn provider_config_uses_xai_oauth(config: &ProviderConfig) -> bool {
9591 config
9592 .auth_mode
9593 .as_deref()
9594 .is_some_and(crate::oauth::auth_mode_uses_xai_oauth)
9595}
9596
9597pub fn base_url_uses_local_host(base_url: &str) -> bool {
9602 let Some(host) = base_url_host(base_url) else {
9603 return false;
9604 };
9605 let host = host.trim_matches(['[', ']']).to_ascii_lowercase();
9606 if matches!(host.as_str(), "localhost" | "0.0.0.0") {
9607 return true;
9608 }
9609 host.parse::<std::net::IpAddr>()
9610 .is_ok_and(|addr| addr.is_loopback() || addr.is_unspecified())
9611}
9612
9613pub fn normalize_base_url(base: &str) -> String {
9614 let trimmed = base.trim_end_matches('/');
9615 let deepseek_domains = ["api.deepseek.com", "api.deepseeki.com"];
9616 if deepseek_domains
9617 .iter()
9618 .any(|domain| trimmed.contains(domain))
9619 {
9620 return trimmed.trim_end_matches("/v1").to_string();
9621 }
9622 trimmed.to_string()
9623}
9624
9625fn parse_http_headers(raw: &str) -> Result<HashMap<String, String>> {
9626 let mut headers = HashMap::new();
9627 for pair in raw.trim().split(',') {
9628 let pair = pair.trim();
9629 if pair.is_empty() {
9630 continue;
9631 }
9632 let Some((name, value)) = pair.split_once('=') else {
9633 anyhow::bail!("invalid header pair '{pair}', expected name=value");
9634 };
9635 let name = name.trim();
9636 let value = value.trim();
9637 if name.is_empty() {
9638 anyhow::bail!("header name cannot be empty");
9639 }
9640 if value.is_empty() {
9641 continue;
9642 }
9643 headers.insert(name.to_string(), value.to_string());
9644 }
9645 Ok(headers)
9646}
9647
9648fn apply_layer_root_model(config: &mut Config, layer: &Config) {
9652 if layer.default_text_model.is_none() && layer.legacy_model.is_none() {
9653 return;
9654 }
9655 let Ok(identity) = config.active_provider_identity() else {
9656 return;
9657 };
9658 let mut scoped = layer.clone();
9659 if scoped.scope_to_provider_identity(&identity).is_err() {
9660 return;
9661 }
9662 if scoped
9663 .provider_config_for(&identity)
9664 .and_then(|entry| entry.model.as_ref())
9665 .is_none()
9666 {
9667 config.set_provider_model_override(&identity, None).unwrap();
9668 }
9669}
9670
9671fn apply_profile(config: ConfigFile, profile: Option<&str>) -> Result<Config> {
9672 if let Some(profile_name) = profile {
9673 let profiles = config.profiles.as_ref();
9674 match profiles.and_then(|profiles| profiles.get(profile_name)) {
9675 Some(override_cfg) => {
9676 let mut merged = merge_config(*config.base, override_cfg.clone());
9677 apply_layer_root_model(&mut merged, override_cfg);
9678 merged.route_provenance.provider_from_profile = override_cfg.provider.is_some();
9679 let merged_identity = merged.active_provider_identity().ok();
9680 merged.route_provenance.model_from_profile =
9681 override_cfg.default_text_model.is_some()
9682 || override_cfg.legacy_model.is_some()
9683 || merged_identity.as_ref().is_some_and(|id| {
9684 override_cfg
9685 .provider_config_for(id)
9686 .and_then(|entry| entry.model.as_deref())
9687 .is_some()
9688 });
9689 Ok(merged)
9690 }
9691 None => {
9692 let available = profiles
9693 .map(|profiles| {
9694 let mut keys = profiles.keys().cloned().collect::<Vec<_>>();
9695 keys.sort();
9696 if keys.is_empty() {
9697 "none".to_string()
9698 } else {
9699 keys.join(", ")
9700 }
9701 })
9702 .unwrap_or_else(|| "none".to_string());
9703 Err(SafeConfigDiagnostic::InvalidValue {
9707 message: format!(
9708 "Profile '{profile_name}' not found. Available profiles: {available}"
9709 ),
9710 shareable: format!(
9711 "Profile not found (name not shown). Available profiles: {available}"
9712 ),
9713 fix: None,
9714 }
9715 .into())
9716 }
9717 }
9718 } else {
9719 Ok(*config.base)
9720 }
9721}
9722
9723fn merge_config(base: Config, override_cfg: Config) -> Config {
9724 Config {
9725 model_http_policy: override_cfg.model_http_policy.or(base.model_http_policy),
9726 custom_models: override_cfg.custom_models.or(base.custom_models),
9727 extra_trusted_paths: if override_cfg.extra_trusted_paths.is_empty() {
9728 base.extra_trusted_paths
9729 } else {
9730 override_cfg.extra_trusted_paths
9731 },
9732 provider: override_cfg.provider.or(base.provider),
9733 telemetry: override_cfg.telemetry.or(base.telemetry),
9734 http_headers: override_cfg.http_headers.or(base.http_headers),
9735 default_text_model: override_cfg
9736 .default_text_model
9737 .or_else(|| override_cfg.legacy_model.clone())
9738 .or(base.default_text_model)
9739 .or_else(|| base.legacy_model.clone()),
9740 legacy_model: override_cfg.legacy_model.or(base.legacy_model),
9741 redaction: override_cfg.redaction.or(base.redaction),
9742 loaded_config_path: override_cfg.loaded_config_path.or(base.loaded_config_path),
9743 remembered_selection_scope: override_cfg
9744 .remembered_selection_scope
9745 .or(base.remembered_selection_scope),
9746 route_preferences_version: override_cfg
9747 .route_preferences_version
9748 .or(base.route_preferences_version),
9749 environment_model_applied: override_cfg.environment_model_applied
9750 || base.environment_model_applied,
9751 route_provenance: base.route_provenance,
9752 auth_mode: override_cfg.auth_mode.or(base.auth_mode),
9753 reasoning_effort: override_cfg.reasoning_effort.or(base.reasoning_effort),
9754 reasoning_effort_inferred_from_legacy_alias: override_cfg
9755 .reasoning_effort_inferred_from_legacy_alias
9756 || base.reasoning_effort_inferred_from_legacy_alias,
9757 fleet_operator_route_applied: override_cfg.fleet_operator_route_applied
9758 || base.fleet_operator_route_applied,
9759 fleet_operator_reasoning_applied: override_cfg.fleet_operator_reasoning_applied
9760 || base.fleet_operator_reasoning_applied,
9761 migrated_legacy_ollama_cloud_route: override_cfg.migrated_legacy_ollama_cloud_route
9762 || base.migrated_legacy_ollama_cloud_route,
9763 migrated_deepseek_model_alias: override_cfg
9764 .migrated_deepseek_model_alias
9765 .or(base.migrated_deepseek_model_alias),
9766 tools: override_cfg.tools.or(base.tools),
9767 skills_dir: override_cfg.skills_dir.or(base.skills_dir),
9768 mcp_config_path: override_cfg.mcp_config_path.or(base.mcp_config_path),
9769 mcp_oauth_callback_port: override_cfg
9770 .mcp_oauth_callback_port
9771 .or(base.mcp_oauth_callback_port),
9772 mcp_oauth_callback_url: override_cfg
9773 .mcp_oauth_callback_url
9774 .or(base.mcp_oauth_callback_url),
9775 notes_path: override_cfg.notes_path.or(base.notes_path),
9776 memory_path: override_cfg.memory_path.or(base.memory_path),
9777 vision_model: override_cfg.vision_model.or(base.vision_model),
9778 instructions: override_cfg.instructions.or(base.instructions),
9782 instruction_budget: override_cfg.instruction_budget.or(base.instruction_budget),
9786 stop_words: override_cfg.stop_words.or(base.stop_words),
9787 allow_shell: override_cfg.allow_shell.or(base.allow_shell),
9788 prompt_suggestion: override_cfg.prompt_suggestion.or(base.prompt_suggestion),
9789 yolo: override_cfg.yolo.or(base.yolo),
9790 verbosity: override_cfg.verbosity.or(base.verbosity),
9791 approval_policy: override_cfg.approval_policy.or(base.approval_policy),
9792 sandbox_mode: override_cfg.sandbox_mode.or(base.sandbox_mode),
9793 sandbox_network_access: override_cfg
9794 .sandbox_network_access
9795 .or(base.sandbox_network_access),
9796 project_instruction_imports: if override_cfg.project_instruction_imports.is_empty() {
9797 base.project_instruction_imports
9798 } else {
9799 override_cfg.project_instruction_imports
9800 },
9801 fallback_providers: if override_cfg.fallback_providers.is_empty() {
9802 base.fallback_providers
9803 } else {
9804 override_cfg.fallback_providers
9805 },
9806 sandbox_backend: override_cfg.sandbox_backend.or(base.sandbox_backend),
9807 sandbox_url: override_cfg.sandbox_url.or(base.sandbox_url),
9808 sandbox_api_key: override_cfg.sandbox_api_key.or(base.sandbox_api_key),
9809 prefer_bwrap: override_cfg.prefer_bwrap.or(base.prefer_bwrap),
9810 tool_launcher: override_cfg.tool_launcher.or(base.tool_launcher),
9811 bwrap_ro_roots: if override_cfg.bwrap_ro_roots.is_empty() {
9812 base.bwrap_ro_roots
9813 } else {
9814 override_cfg.bwrap_ro_roots
9815 },
9816 bwrap_dev_roots: if override_cfg.bwrap_dev_roots.is_empty() {
9817 base.bwrap_dev_roots
9818 } else {
9819 override_cfg.bwrap_dev_roots
9820 },
9821 sandbox_denied_read_paths: if override_cfg.sandbox_denied_read_paths.is_empty() {
9822 base.sandbox_denied_read_paths
9823 } else {
9824 override_cfg.sandbox_denied_read_paths
9825 },
9826 sandbox_read_denylist_defaults: override_cfg
9827 .sandbox_read_denylist_defaults
9828 .or(base.sandbox_read_denylist_defaults),
9829 sandbox_read_denylist_exempt: if override_cfg.sandbox_read_denylist_exempt.is_empty() {
9830 base.sandbox_read_denylist_exempt
9831 } else {
9832 override_cfg.sandbox_read_denylist_exempt
9833 },
9834 managed_config_path: override_cfg
9835 .managed_config_path
9836 .or(base.managed_config_path),
9837 requirements_path: override_cfg.requirements_path.or(base.requirements_path),
9838 max_subagents: override_cfg.max_subagents.or(base.max_subagents),
9839 retry: override_cfg.retry.or(base.retry),
9840 stream: match (base.stream, override_cfg.stream) {
9841 (Some(base), Some(over)) => Some(StreamConfig {
9842 open_timeout_secs: over.open_timeout_secs.or(base.open_timeout_secs),
9843 chunk_timeout_secs: over.chunk_timeout_secs.or(base.chunk_timeout_secs),
9844 force_http1: over.force_http1.or(base.force_http1),
9845 max_resumes: over.max_resumes.or(base.max_resumes),
9846 max_transparent_retries: over
9847 .max_transparent_retries
9848 .or(base.max_transparent_retries),
9849 max_stream_errors: over.max_stream_errors.or(base.max_stream_errors),
9850 max_duration_secs: over.max_duration_secs.or(base.max_duration_secs),
9851 max_content_mb: over.max_content_mb.or(base.max_content_mb),
9852 connect_timeout_secs: over.connect_timeout_secs.or(base.connect_timeout_secs),
9853 tcp_keepalive_secs: over.tcp_keepalive_secs.or(base.tcp_keepalive_secs),
9854 http2_keep_alive_interval_secs: over
9855 .http2_keep_alive_interval_secs
9856 .or(base.http2_keep_alive_interval_secs),
9857 http2_keep_alive_timeout_secs: over
9858 .http2_keep_alive_timeout_secs
9859 .or(base.http2_keep_alive_timeout_secs),
9860 }),
9861 (base, over) => over.or(base),
9862 },
9863
9864 auto_review: override_cfg.auto_review.or(base.auto_review),
9865 tui: override_cfg.tui.or(base.tui),
9866 transcript: override_cfg.transcript.or(base.transcript),
9867 hooks: override_cfg.hooks.or(base.hooks),
9868 lifecycle_outbox: override_cfg.lifecycle_outbox.or(base.lifecycle_outbox),
9869 control_socket: override_cfg.control_socket.or(base.control_socket),
9870 providers: merge_providers(base.providers, override_cfg.providers),
9871 features: merge_features(base.features, override_cfg.features),
9872 extension_host: override_cfg.extension_host.or(base.extension_host),
9873 plugins: override_cfg.plugins.or(base.plugins),
9874 notifications: override_cfg.notifications.or(base.notifications),
9875 approval: override_cfg.approval.or(base.approval),
9876 network: override_cfg.network.or(base.network),
9877 network_layer_is_managed: override_cfg.network_layer_is_managed
9878 || base.network_layer_is_managed,
9879 verifier: override_cfg.verifier.or(base.verifier),
9880 advisor: override_cfg.advisor.or(base.advisor),
9881 skills: merge_skills_config(base.skills, override_cfg.skills),
9882 snapshots: override_cfg.snapshots.or(base.snapshots),
9883 search: override_cfg.search.or(base.search),
9884 goal: override_cfg.goal.or(base.goal),
9885 memory: override_cfg.memory.or(base.memory),
9886 speech: override_cfg.speech.or(base.speech),
9887 auto: override_cfg.auto.or(base.auto),
9888 hotbar: override_cfg.hotbar.or(base.hotbar),
9889 update: override_cfg.update.or(base.update),
9890 cloud_facts: override_cfg.cloud_facts.or(base.cloud_facts),
9891 lsp: override_cfg.lsp.or(base.lsp),
9892 context: ContextConfig {
9893 project_pack: override_cfg
9894 .context
9895 .project_pack
9896 .or(base.context.project_pack),
9897 },
9898 compaction: override_cfg.compaction.or(base.compaction),
9899 fleet: override_cfg.fleet.or(base.fleet),
9900 workflow: override_cfg.workflow.or(base.workflow),
9901 subagents: override_cfg.subagents.or(base.subagents),
9902 strict_tool_mode: override_cfg.strict_tool_mode.or(base.strict_tool_mode),
9903 runtime_api: override_cfg.runtime_api.or(base.runtime_api),
9904 workshop: override_cfg.workshop.or(base.workshop),
9905 exec_policy_engine: override_cfg.exec_policy_engine,
9906 base_url_env_receipt: match override_cfg.base_url_env_receipt {
9907 BaseUrlEnvReceipt::Unrecorded => base.base_url_env_receipt,
9908 recorded => recorded,
9909 },
9910 legacy_root: base.legacy_root,
9911 legacy_root_custom_generation: base.legacy_root_custom_generation,
9912 account_model_access: base.account_model_access,
9913 session_provider_keys: base.session_provider_keys,
9914 session_provider_keys_only: base.session_provider_keys_only,
9915 required_account_model_owner: base.required_account_model_owner,
9916 account_profile: override_cfg.account_profile.or(base.account_profile),
9917 plugin_oauth_read_only: base.plugin_oauth_read_only || override_cfg.plugin_oauth_read_only,
9918 runtime_chat_isolated: override_cfg.runtime_chat_isolated || base.runtime_chat_isolated,
9919 runtime_thread_inference_unrelated: override_cfg.runtime_thread_inference_unrelated
9920 || base.runtime_thread_inference_unrelated,
9921 mini_window: override_cfg.mini_window.or(base.mini_window),
9922 reasoning_only: override_cfg.reasoning_only.or(base.reasoning_only),
9923 title: override_cfg.title.or(base.title),
9924 }
9925}
9926
9927fn load_sibling_exec_policy_engine(config_path: Option<&Path>) -> Result<ExecPolicyEngine> {
9928 let Some(config_path) = config_path else {
9929 return Ok(ExecPolicyEngine::new(Vec::new(), Vec::new()));
9930 };
9931 let permissions_path = codewhale_config::permissions_path_for_config_path(config_path);
9932 if !permissions_path.exists() {
9933 return Ok(ExecPolicyEngine::new(Vec::new(), Vec::new()));
9934 }
9935
9936 let raw = fs::read_to_string(&permissions_path).with_context(|| {
9937 format!(
9938 "Failed to read permissions file: {}",
9939 permissions_path.display()
9940 )
9941 })?;
9942 let permissions: codewhale_config::PermissionsToml = toml::from_str(&raw).map_err(|_| {
9943 anyhow::anyhow!(
9944 "Failed to parse permissions file {}; file contents were omitted",
9945 codewhale_config::quote_os_path(&permissions_path)
9946 )
9947 })?;
9948 if permissions.is_empty() {
9949 Ok(ExecPolicyEngine::new(Vec::new(), Vec::new()))
9950 } else {
9951 Ok(ExecPolicyEngine::with_rulesets(vec![permissions.ruleset()]))
9952 }
9953}
9954
9955fn merge_skills_config(
9956 base: Option<SkillsConfig>,
9957 override_cfg: Option<SkillsConfig>,
9958) -> Option<SkillsConfig> {
9959 match (base, override_cfg) {
9960 (None, None) => None,
9961 (Some(base), None) => Some(base),
9962 (None, Some(override_cfg)) => Some(override_cfg),
9963 (Some(base), Some(override_cfg)) => Some(SkillsConfig {
9964 bundled: BundledSkillsConfig {
9965 install: override_cfg.bundled.install.or(base.bundled.install),
9966 selected: override_cfg.bundled.selected.or(base.bundled.selected),
9967 disabled: override_cfg.bundled.disabled.or(base.bundled.disabled),
9968 explicit_only: override_cfg
9969 .bundled
9970 .explicit_only
9971 .or(base.bundled.explicit_only),
9972 },
9973 listing_max_description_chars: override_cfg
9974 .listing_max_description_chars
9975 .or(base.listing_max_description_chars),
9976 listing_budget_fraction: override_cfg
9977 .listing_budget_fraction
9978 .or(base.listing_budget_fraction),
9979 registry_url: override_cfg.registry_url.or(base.registry_url),
9980 max_install_size_bytes: override_cfg
9981 .max_install_size_bytes
9982 .or(base.max_install_size_bytes),
9983 scan_codewhale_only: override_cfg
9984 .scan_codewhale_only
9985 .or(base.scan_codewhale_only),
9986 flat_workspace_root: override_cfg
9987 .flat_workspace_root
9988 .or(base.flat_workspace_root),
9989 creator_skills: false,
9990 }),
9991 }
9992}
9993
9994fn merge_provider_config(base: ProviderConfig, override_cfg: ProviderConfig) -> ProviderConfig {
9995 ProviderConfig {
9996 vendor: override_cfg.vendor.or(base.vendor),
9997 api_key: override_cfg.api_key.or(base.api_key),
9998 base_url: override_cfg.base_url.or(base.base_url),
9999 model: override_cfg.model.or(base.model),
10000 context_window: override_cfg.context_window.or(base.context_window),
10001 model_context_windows: override_cfg
10002 .model_context_windows
10003 .or(base.model_context_windows),
10004 mode: override_cfg.mode.or(base.mode),
10005 wire: override_cfg.wire.or(base.wire),
10006 responses_profile: override_cfg.responses_profile.or(base.responses_profile),
10007 auth_mode: override_cfg.auth_mode.or(base.auth_mode),
10008 oauth: override_cfg.oauth.or(base.oauth),
10009 plugin_authority: base.plugin_authority,
10010 oauth_credential_generation: override_cfg
10011 .oauth_credential_generation
10012 .or(base.oauth_credential_generation),
10013 insecure_skip_tls_verify: override_cfg
10014 .insecure_skip_tls_verify
10015 .or(base.insecure_skip_tls_verify),
10016 allow_insecure_http: override_cfg
10017 .allow_insecure_http
10018 .or(base.allow_insecure_http),
10019 http_headers: override_cfg.http_headers.or(base.http_headers),
10020 path_suffix: override_cfg.path_suffix.or(base.path_suffix),
10021 reasoning_stream_style: override_cfg
10022 .reasoning_stream_style
10023 .or(base.reasoning_stream_style),
10024 max_concurrency: override_cfg.max_concurrency.or(base.max_concurrency),
10025 auth: override_cfg.auth.or(base.auth),
10026 external_credentials: override_cfg
10027 .external_credentials
10028 .or(base.external_credentials),
10029 kind: override_cfg.kind.or(base.kind),
10030 api_key_env: override_cfg.api_key_env.or(base.api_key_env),
10031 }
10032}
10033
10034fn merge_custom_providers(
10038 mut base: HashMap<String, ProviderConfig>,
10039 override_cfg: HashMap<String, ProviderConfig>,
10040) -> HashMap<String, ProviderConfig> {
10041 for (name, entry) in override_cfg {
10042 let merged = match base.remove(&name) {
10043 Some(base_entry) => merge_provider_config(base_entry, entry),
10044 None => entry,
10045 };
10046 base.insert(name, merged);
10047 }
10048 base
10049}
10050
10051fn merge_providers(
10052 base: Option<ProvidersConfig>,
10053 override_cfg: Option<ProvidersConfig>,
10054) -> Option<ProvidersConfig> {
10055 match (base, override_cfg) {
10056 (None, None) => None,
10057 (Some(base), None) => Some(base),
10058 (None, Some(override_cfg)) => Some(override_cfg),
10059 (Some(base), Some(override_cfg)) => Some(ProvidersConfig {
10060 deepseek: merge_provider_config(base.deepseek, override_cfg.deepseek),
10061 deepseek_cn: merge_provider_config(base.deepseek_cn, override_cfg.deepseek_cn),
10062 deepseek_anthropic: merge_provider_config(
10063 base.deepseek_anthropic,
10064 override_cfg.deepseek_anthropic,
10065 ),
10066 nvidia_nim: merge_provider_config(base.nvidia_nim, override_cfg.nvidia_nim),
10067 openai: merge_provider_config(base.openai, override_cfg.openai),
10068 anthropic: merge_provider_config(base.anthropic, override_cfg.anthropic),
10069 openmodel: merge_provider_config(base.openmodel, override_cfg.openmodel),
10070 atlascloud: merge_provider_config(base.atlascloud, override_cfg.atlascloud),
10071 wanjie_ark: merge_provider_config(base.wanjie_ark, override_cfg.wanjie_ark),
10072 openrouter: merge_provider_config(base.openrouter, override_cfg.openrouter),
10073 orcarouter: merge_provider_config(base.orcarouter, override_cfg.orcarouter),
10074 xiaomi_mimo: merge_provider_config(base.xiaomi_mimo, override_cfg.xiaomi_mimo),
10075 novita: merge_provider_config(base.novita, override_cfg.novita),
10076 fireworks: merge_provider_config(base.fireworks, override_cfg.fireworks),
10077 siliconflow: merge_provider_config(base.siliconflow, override_cfg.siliconflow),
10078 siliconflow_cn: merge_provider_config(base.siliconflow_cn, override_cfg.siliconflow_cn),
10079 arcee: merge_provider_config(base.arcee, override_cfg.arcee),
10080 moonshot: merge_provider_config(base.moonshot, override_cfg.moonshot),
10081 sglang: merge_provider_config(base.sglang, override_cfg.sglang),
10082 vllm: merge_provider_config(base.vllm, override_cfg.vllm),
10083 ollama: merge_provider_config(base.ollama, override_cfg.ollama),
10084 ollama_cloud: merge_provider_config(base.ollama_cloud, override_cfg.ollama_cloud),
10085 volcengine: merge_provider_config(base.volcengine, override_cfg.volcengine),
10086 huggingface: merge_provider_config(base.huggingface, override_cfg.huggingface),
10087 modelscope: merge_provider_config(base.modelscope, override_cfg.modelscope),
10088 deepinfra: merge_provider_config(base.deepinfra, override_cfg.deepinfra),
10089 together: merge_provider_config(base.together, override_cfg.together),
10090 qianfan: merge_provider_config(base.qianfan, override_cfg.qianfan),
10091 openai_codex: merge_provider_config(base.openai_codex, override_cfg.openai_codex),
10092 zai: merge_provider_config(base.zai, override_cfg.zai),
10093 stepfun: merge_provider_config(base.stepfun, override_cfg.stepfun),
10094 minimax: merge_provider_config(base.minimax, override_cfg.minimax),
10095 minimax_anthropic: merge_provider_config(
10096 base.minimax_anthropic,
10097 override_cfg.minimax_anthropic,
10098 ),
10099 sakana: merge_provider_config(base.sakana, override_cfg.sakana),
10100 longcat: merge_provider_config(base.longcat, override_cfg.longcat),
10101 opencode_go: merge_provider_config(base.opencode_go, override_cfg.opencode_go),
10102 opencode_zen: merge_provider_config(base.opencode_zen, override_cfg.opencode_zen),
10103 meta: merge_provider_config(base.meta, override_cfg.meta),
10104 xai: merge_provider_config(base.xai, override_cfg.xai),
10105 mistral: merge_provider_config(base.mistral, override_cfg.mistral),
10106 google: merge_provider_config(base.google, override_cfg.google),
10107 antigravity: merge_provider_config(base.antigravity, override_cfg.antigravity),
10108 telecomjs: merge_provider_config(base.telecomjs, override_cfg.telecomjs),
10109 edenai: merge_provider_config(base.edenai, override_cfg.edenai),
10110 zenmux: merge_provider_config(base.zenmux, override_cfg.zenmux),
10111 csdn: merge_provider_config(base.csdn, override_cfg.csdn),
10112 concentrate: merge_provider_config(base.concentrate, override_cfg.concentrate),
10113 codewhale: merge_provider_config(base.codewhale, override_cfg.codewhale),
10114 modelstudio_token_plan: merge_provider_config(
10115 base.modelstudio_token_plan,
10116 override_cfg.modelstudio_token_plan,
10117 ),
10118 modelstudio_token_plan_anthropic: merge_provider_config(
10119 base.modelstudio_token_plan_anthropic,
10120 override_cfg.modelstudio_token_plan_anthropic,
10121 ),
10122 modelstudio_coding_plan: merge_provider_config(
10123 base.modelstudio_coding_plan,
10124 override_cfg.modelstudio_coding_plan,
10125 ),
10126 modelstudio_coding_plan_anthropic: merge_provider_config(
10127 base.modelstudio_coding_plan_anthropic,
10128 override_cfg.modelstudio_coding_plan_anthropic,
10129 ),
10130 custom: merge_custom_providers(base.custom, override_cfg.custom),
10131 }),
10132 }
10133}
10134
10135fn load_single_config_file(path: &Path) -> Result<Config> {
10136 let contents = fs::read_to_string(path)
10137 .with_context(|| format!("Failed to read config file: {}", path.display()))?;
10138 let parsed = parse_config_file(&contents).map_err(|_| {
10139 anyhow::anyhow!(
10140 "Failed to parse config file {}; file contents were omitted",
10141 codewhale_config::quote_os_path(path)
10142 )
10143 })?;
10144 Ok(*parsed.base)
10145}
10146
10147#[cfg(any(test, feature = "test-support"))]
10149impl Config {
10150 pub fn with_legacy_root(mut self, api_key: Option<String>, base_url: Option<String>) -> Self {
10154 self.set_legacy_root(api_key, base_url);
10155 self
10156 }
10157
10158 pub fn deepseek_table_api_key(&self) -> Option<&str> {
10160 self.providers.as_ref()?.deepseek.api_key.as_deref()
10161 }
10162
10163 pub fn deepseek_table_base_url(&self) -> Option<&str> {
10166 self.providers.as_ref()?.deepseek.base_url.as_deref()
10167 }
10168
10169 pub fn set_legacy_root(&mut self, api_key: Option<String>, base_url: Option<String>) {
10171 use toml::Value;
10172 let mut root = toml::Table::new();
10173 if let Some(provider) = &self.provider {
10174 root.insert("provider".into(), Value::String(provider.clone()));
10175 }
10176 if let Some(model) = self
10177 .default_text_model
10178 .clone()
10179 .or(self.legacy_model.clone())
10180 {
10181 root.insert("default_text_model".into(), Value::String(model));
10182 }
10183 if let Some(key) = api_key {
10184 root.insert("api_key".into(), Value::String(key));
10185 }
10186 if let Some(url) = base_url {
10187 root.insert("base_url".into(), Value::String(url));
10188 }
10189 let entry_table = |entry: &ProviderConfig| {
10190 let mut table = toml::Table::new();
10191 if let Some(key) = &entry.api_key {
10192 table.insert("api_key".into(), Value::String(key.clone()));
10193 }
10194 if let Some(url) = &entry.base_url {
10195 table.insert("base_url".into(), Value::String(url.clone()));
10196 }
10197 if let Some(model) = &entry.model {
10198 table.insert("model".into(), Value::String(model.clone()));
10199 }
10200 if let Some(kind) = &entry.kind {
10201 table.insert("kind".into(), Value::String(kind.clone()));
10202 }
10203 table
10204 };
10205 let mut providers = toml::Table::new();
10206 if let Some(configured) = self.providers.as_ref() {
10207 for row in codewhale_config::descriptors::provider_compatibility() {
10208 if let Some(entry) =
10209 codewhale_config::provider_config_table!(@read configured, row.id)
10210 {
10211 providers.insert(row.config_key.to_string(), Value::Table(entry_table(entry)));
10212 }
10213 }
10214 for (name, entry) in &configured.custom {
10215 providers.insert(name.clone(), Value::Table(entry_table(entry)));
10216 }
10217 }
10218 root.insert("providers".into(), Value::Table(providers));
10219 if let Some(vision) = &self.vision_model {
10220 let mut table = toml::Table::new();
10221 if let Some(key) = &vision.api_key {
10222 table.insert("api_key".into(), Value::String(key.clone()));
10223 }
10224 root.insert("vision_model".into(), Value::Table(table));
10225 }
10226
10227 self.legacy_root = codewhale_config::legacy_root::apply_to_table(&mut root);
10228
10229 if let Some(provider) = root.get("provider").and_then(Value::as_str) {
10230 self.provider = Some(provider.to_string());
10231 }
10232 if let (Some(vision), Some(key)) = (
10233 self.vision_model.as_mut(),
10234 root.get("vision_model")
10235 .and_then(|table| table.get("api_key"))
10236 .and_then(Value::as_str),
10237 ) {
10238 vision.api_key = Some(key.to_string());
10239 }
10240 let Some(providers) = root.get("providers").and_then(Value::as_table) else {
10241 return;
10242 };
10243 for (key, table) in providers {
10244 let Some(table) = table.as_table() else {
10245 continue;
10246 };
10247 let entry = if let Some(row) = codewhale_config::descriptors::provider_compatibility()
10248 .iter()
10249 .find(|row| row.config_key == key && row.kind != ProviderKind::Custom)
10250 {
10251 let configured = self.providers.get_or_insert_with(ProvidersConfig::default);
10252 let Some(entry) =
10253 codewhale_config::provider_config_table!(@write configured, row.id)
10254 else {
10255 continue;
10256 };
10257 entry
10258 } else {
10259 self.providers
10260 .get_or_insert_with(ProvidersConfig::default)
10261 .custom
10262 .entry(key.clone())
10263 .or_default()
10264 };
10265 let get = |field: &str| table.get(field).and_then(Value::as_str).map(str::to_string);
10266 entry.api_key = get("api_key");
10267 entry.base_url = get("base_url");
10268 entry.model = get("model");
10269 entry.kind = get("kind");
10270 }
10271 self.bind_legacy_root_custom_generation();
10272 }
10273}
10274
10275pub fn parse_config_base(contents: &str) -> std::result::Result<Config, toml::de::Error> {
10278 let parsed = parse_config_file(contents)?;
10279 let mut config = *parsed.base;
10280 config.legacy_root = parsed.legacy_root;
10281 Ok(config)
10282}
10283
10284pub fn parse_config_after_locked_migration(
10289 contents: &str,
10290 moved: &codewhale_config::legacy_root::LegacyRootMigration,
10291) -> std::result::Result<Config, toml::de::Error> {
10292 let mut config = parse_config_base(contents)?;
10293 config.legacy_root.notes.extend(moved.notes.iter().cloned());
10294 config.bind_legacy_root_custom_generation();
10295 Ok(config)
10296}
10297
10298fn parse_config_file(contents: &str) -> std::result::Result<ConfigFile, toml::de::Error> {
10302 let (text, legacy_root) = codewhale_config::legacy_root::canonicalize_text(contents)?;
10303 let mut parsed = toml::from_str::<ConfigFile>(&text)?;
10304 parsed.base.legacy_root = legacy_root.clone();
10305 parsed.base.bind_legacy_root_custom_generation();
10306 parsed.legacy_root = legacy_root;
10307 Ok(parsed)
10308}
10309
10310fn warn_on_misplaced_top_level_keys(raw: &str) -> Option<String> {
10319 let doc = toml::from_str::<toml::Value>(raw).ok()?;
10320 const UNKNOWN_SECTIONS: &[&str] = &["general", "sandbox"];
10322 const TOP_LEVEL_KEYS: &[&str] = &[
10324 "allow_shell",
10325 "sandbox_mode",
10326 "approval_policy",
10327 "verbosity",
10328 ];
10329
10330 let mut hits: Vec<String> = Vec::new();
10331 for section in UNKNOWN_SECTIONS {
10332 let Some(table) = doc.get(*section).and_then(toml::Value::as_table) else {
10333 continue;
10334 };
10335 for key in TOP_LEVEL_KEYS {
10336 if table.contains_key(*key) {
10337 hits.push(format!("`{section}.{key}`"));
10338 }
10339 }
10340 }
10341 if hits.is_empty() {
10342 return None;
10343 }
10344 Some(format!(
10345 "Ignoring {} — Codewhale has no `[general]` or `[sandbox]` section, so these \
10346 keys are silently dropped. Move them to the TOP of the config file (above any \
10347 `[section]` header), e.g. `allow_shell = true`. Until then, shell tools stay \
10348 disabled. (#2589)",
10349 hits.join(", ")
10350 ))
10351}
10352
10353fn apply_managed_overrides(config: &mut Config) -> Result<()> {
10354 let Some(path) = managed_config_file(config.managed_config_path.as_deref())? else {
10355 return Ok(());
10356 };
10357 let mut managed = load_single_config_file(&path).with_context(|| {
10358 format!(
10359 "the managed configuration {} cannot be loaded, and Codewhale does not start without a managed configuration it was told to use",
10360 codewhale_config::quote_os_path(&path)
10361 )
10362 })?;
10363 strip_external_credential_consent(&mut managed);
10364 managed.tool_launcher = managed_tool_launcher(&path)?;
10365 let prior_route = config
10366 .active_provider_identity()
10367 .map_err(|error| managed_route_error(config, &path, error))?;
10368 let mut merged = merge_config(config.clone(), managed.clone());
10369 apply_layer_root_model(&mut merged, &managed);
10370 let merged_route = merged
10371 .active_provider_identity()
10372 .map_err(|error| managed_route_error(&merged, &path, error))?;
10373 if managed.provider.is_some() {
10374 merged.route_provenance.provider_from_managed = true;
10375 merged.route_provenance.provider_from_env = false;
10376 merged.route_provenance.provider_from_saved_selection = false;
10377 merged.route_provenance.provider_from_profile = false;
10378 }
10379 if managed.default_text_model.is_some()
10380 || managed.legacy_model.is_some()
10381 || managed
10382 .provider_config_for(&merged_route)
10383 .and_then(|entry| entry.model.as_ref())
10384 .is_some()
10385 {
10386 merged.route_provenance.model_from_managed = true;
10387 merged.route_provenance.model_from_saved_selection = false;
10388 merged.route_provenance.model_from_profile = false;
10389 merged.remembered_selection_scope = Some(false);
10390 } else if managed.provider.is_some() {
10391 merged.remembered_selection_scope = Some(false);
10392 }
10393 if prior_route != merged_route || config_defines_base_url_for_effective_route(&managed, &merged)
10394 {
10395 if let BaseUrlEnvReceipt::Route(ProviderKind::Deepseek, key) = &config.base_url_env_receipt
10410 && let Ok(owner) = merged.resolve_persisted_provider_identity(
10411 Some(ProviderKind::Deepseek.as_str()),
10412 Some(key),
10413 )
10414 && managed
10415 .provider_config_for(&owner)
10416 .and_then(|entry| entry.base_url.as_ref())
10417 .is_none()
10418 && let Some(env_value) = env_base_url_override()
10419 && merged
10420 .provider_config_for(&owner)
10421 .and_then(|entry| entry.base_url.as_deref())
10422 == Some(env_value.as_str())
10423 {
10424 merged.provider_config_for_mut(&owner)?.base_url = None;
10425 }
10426 merged.base_url_env_receipt = BaseUrlEnvReceipt::NoOwner;
10427 }
10428 if managed.network.is_some() {
10432 merged.network_layer_is_managed = true;
10433 }
10434 if managed.tool_launcher.is_some()
10435 && !matches!(
10436 managed.sandbox_mode.as_deref(),
10437 Some("workspace-write" | "read-only")
10438 )
10439 {
10440 anyhow::bail!(
10441 "`tool_launcher` in the managed configuration {} needs `sandbox_mode = \"workspace-write\"` or `\"read-only\"` beside it: commands run through the launcher only inside the sandbox",
10442 codewhale_config::quote_os_path(&path)
10443 );
10444 }
10445 *config = merged;
10446 Ok(())
10447}
10448
10449fn managed_tool_launcher(path: &Path) -> Result<Option<Vec<String>>> {
10450 let raw = fs::read_to_string(path)
10451 .with_context(|| format!("Failed to read config file: {}", path.display()))?;
10452 let Ok(document) = toml::from_str::<toml::Value>(&raw) else {
10453 return Ok(None);
10454 };
10455 if codewhale_config::tool_launcher_in_profiles(&document) {
10456 anyhow::bail!(
10457 "`tool_launcher` in {} belongs at the top level of the managed configuration, not in a profile",
10458 codewhale_config::quote_os_path(path)
10459 );
10460 }
10461 let Some(value) = document.get("tool_launcher") else {
10462 return Ok(None);
10463 };
10464 if !cfg!(all(target_os = "linux", not(target_env = "ohos"))) {
10465 anyhow::bail!(
10466 "`tool_launcher` in {} is supported only on Linux",
10467 codewhale_config::quote_os_path(path)
10468 );
10469 }
10470 let argv = value
10471 .as_array()
10472 .and_then(|items| {
10473 items
10474 .iter()
10475 .map(|item| item.as_str().map(str::to_string))
10476 .collect::<Option<Vec<_>>>()
10477 })
10478 .filter(|argv| {
10479 argv.first()
10480 .is_some_and(|program| Path::new(program).is_absolute())
10481 && argv.iter().all(|arg| !arg.is_empty() && !arg.contains('\0'))
10482 })
10483 .ok_or_else(|| {
10484 anyhow::anyhow!(
10485 "`tool_launcher` in {} must be a list of strings whose first entry is an absolute program path",
10486 codewhale_config::quote_os_path(path)
10487 )
10488 })?;
10489 if !managed_path_is_named_by_host(path) {
10490 anyhow::bail!(
10491 "`tool_launcher` in {} is not accepted: that file is not CODEWHALE_MANAGED_CONFIG_PATH or the default managed path, and a launcher is read only from one of those",
10492 codewhale_config::quote_os_path(path)
10493 );
10494 }
10495 if managed_file_is_replaceable(path) {
10496 anyhow::bail!(
10497 "`tool_launcher` in {} is not accepted: the Engine's own user can change that file or its directory, so it is not a managed configuration",
10498 codewhale_config::quote_os_path(path)
10499 );
10500 }
10501 Ok(Some(argv))
10502}
10503
10504fn managed_path_from_env() -> Option<PathBuf> {
10505 codewhale_env_var(
10506 "CODEWHALE_MANAGED_CONFIG_PATH",
10507 "DEEPSEEK_MANAGED_CONFIG_PATH",
10508 )
10509 .ok()
10510 .map(|value| expand_path(&value))
10511}
10512
10513fn managed_config_file(configured: Option<&str>) -> Result<Option<PathBuf>> {
10514 if let Some(path) = managed_path_from_env() {
10515 return Ok(Some(path));
10516 }
10517 let default = default_managed_config_path().filter(|path| {
10518 fs::symlink_metadata(path).map_or_else(
10519 |error| error.kind() != std::io::ErrorKind::NotFound,
10520 |_| true,
10521 )
10522 });
10523 let Some(configured) = configured
10524 .filter(|value| !value.trim().is_empty())
10525 .map(expand_path)
10526 else {
10527 return Ok(default);
10528 };
10529 if let Some(default) = default
10530 && default != configured
10531 {
10532 anyhow::bail!(
10533 "`managed_config_path` names {}, but the default managed configuration {} exists, and a config file cannot replace it; name another managed file with CODEWHALE_MANAGED_CONFIG_PATH instead",
10534 codewhale_config::quote_os_path(&configured),
10535 codewhale_config::quote_os_path(&default)
10536 );
10537 }
10538 Ok(Some(configured))
10539}
10540
10541fn managed_route_error(config: &Config, path: &Path, error: String) -> anyhow::Error {
10542 let selected = config.provider.as_deref().unwrap_or_default();
10543 let undeclared = !selected.is_empty()
10544 && ProviderKind::parse(selected).is_none()
10545 && config
10546 .providers
10547 .as_ref()
10548 .and_then(|providers| providers.custom_provider_config(selected))
10549 .is_none();
10550 if undeclared {
10551 anyhow::anyhow!(
10552 "provider '{selected}' has no `[providers.{selected}]` table in the configuration, and the managed configuration {} applies: a provider that only a plugin declares cannot be used under a managed configuration. Declare `[providers.{selected}]` in the config file, or select a built-in provider",
10553 codewhale_config::quote_os_path(path)
10554 )
10555 } else {
10556 anyhow::anyhow!(
10557 "{error} (while applying the managed configuration {})",
10558 codewhale_config::quote_os_path(path)
10559 )
10560 }
10561}
10562
10563fn managed_path_is_named_by_host(path: &Path) -> bool {
10564 managed_path_from_env()
10565 .into_iter()
10566 .chain(default_managed_config_path())
10567 .any(|named| named == path)
10568}
10569
10570#[cfg(test)]
10571static TEST_TREAT_MANAGED_FILE_AS_SEALED: std::sync::atomic::AtomicBool =
10572 std::sync::atomic::AtomicBool::new(false);
10573
10574fn managed_file_is_replaceable(path: &Path) -> bool {
10575 #[cfg(test)]
10576 if TEST_TREAT_MANAGED_FILE_AS_SEALED.load(std::sync::atomic::Ordering::SeqCst) {
10577 return false;
10578 }
10579 engine_can_replace(path)
10580}
10581
10582#[cfg(unix)]
10583fn engine_can_replace(path: &Path) -> bool {
10584 use std::os::unix::ffi::OsStrExt as _;
10585 use std::os::unix::fs::MetadataExt as _;
10586 fn writable(path: &Path) -> bool {
10587 let Ok(spelled) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
10588 return true;
10589 };
10590 unsafe { libc::access(spelled.as_ptr(), libc::W_OK) == 0 }
10592 }
10593 let euid = unsafe { libc::geteuid() };
10595 let replaceable = |file: &Path| {
10596 if writable(file) {
10597 return true;
10598 }
10599 let mut child = file;
10600 while let Some(dir) = child.parent().filter(|dir| !dir.as_os_str().is_empty()) {
10601 if writable(dir) {
10602 let sticky = std::fs::metadata(dir).is_ok_and(|meta| meta.mode() & 0o1000 != 0);
10603 let child_is_ours =
10604 std::fs::symlink_metadata(child).map_or(true, |meta| meta.uid() == euid);
10605 if !sticky || child_is_ours {
10606 return true;
10607 }
10608 }
10609 child = dir;
10610 }
10611 false
10612 };
10613 let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
10614 let canonical = path.canonicalize().unwrap_or_else(|_| absolute.clone());
10615 replaceable(&absolute) || replaceable(&canonical)
10616}
10617
10618#[cfg(not(unix))]
10619fn engine_can_replace(_path: &Path) -> bool {
10620 true
10621}
10622
10623fn strip_external_credential_consent(config: &mut Config) {
10629 if config.providers.is_none() {
10630 return;
10631 }
10632 for row in codewhale_config::descriptors::provider_compatibility() {
10633 if row.kind == ProviderKind::Custom {
10634 continue;
10635 }
10636 let Ok(identity) = config.resolve_persisted_provider_identity(Some(row.id), Some(row.id))
10637 else {
10638 continue;
10639 };
10640 let Ok(entry) = config.provider_config_for_mut(&identity) else {
10641 continue;
10642 };
10643 if entry.external_credentials.as_ref().is_some_and(|consent| {
10644 consent.access != codewhale_config::ExternalCredentialAccess::Disabled
10645 }) {
10646 entry.external_credentials = None;
10647 }
10648 }
10649 if let Some(providers) = config.providers.as_mut() {
10650 for provider in providers.custom.values_mut() {
10651 if provider
10652 .external_credentials
10653 .as_ref()
10654 .is_some_and(|consent| {
10655 consent.access != codewhale_config::ExternalCredentialAccess::Disabled
10656 })
10657 {
10658 provider.external_credentials = None;
10659 }
10660 }
10661 }
10662}
10663
10664fn config_defines_base_url_for_effective_route(source: &Config, effective: &Config) -> bool {
10665 let Ok(identity) = effective.active_provider_identity() else {
10666 return false;
10667 };
10668 let mut source = source.clone();
10669 if source.scope_to_provider_identity(&identity).is_err() {
10670 return false;
10671 }
10672 source
10673 .provider_route_string_with_deepseek_fallback(&identity, |entry| entry.base_url.clone())
10674 .is_some_and(|base| !base.trim().is_empty())
10675}
10676
10677fn apply_requirements(config: &mut Config) -> Result<()> {
10678 let path = config
10679 .requirements_path
10680 .as_deref()
10681 .map(expand_path)
10682 .or_else(default_requirements_path);
10683 let Some(path) = path else {
10684 return Ok(());
10685 };
10686 if !path.exists() {
10687 return Ok(());
10688 }
10689 let contents = fs::read_to_string(&path)
10690 .with_context(|| format!("Failed to read requirements file: {}", path.display()))?;
10691 let requirements: RequirementsFile = toml::from_str(&contents).map_err(|_| {
10692 anyhow::anyhow!(
10693 "Failed to parse requirements file {}; file contents were omitted",
10694 codewhale_config::quote_os_path(&path)
10695 )
10696 })?;
10697
10698 if !requirements.allowed_approval_policies.is_empty() {
10699 use codewhale_execpolicy::ApprovalMode;
10700
10701 let policy = config
10702 .approval_policy
10703 .as_deref()
10704 .unwrap_or("on-request")
10705 .to_ascii_lowercase();
10706 if !requirements.allowed_approval_policies.iter().any(|p| {
10707 match (
10708 ApprovalMode::from_config_value(p),
10709 ApprovalMode::from_config_value(&policy),
10710 ) {
10711 (Some(allowed), Some(effective)) => allowed == effective,
10712 _ => p.eq_ignore_ascii_case(&policy),
10713 }
10714 }) {
10715 anyhow::bail!(
10716 "approval_policy '{policy}' is not allowed by requirements ({})",
10717 requirements.allowed_approval_policies.join(", ")
10718 );
10719 }
10720 }
10721 if !requirements.allowed_sandbox_modes.is_empty() {
10722 let mode = config
10727 .sandbox_mode
10728 .as_deref()
10729 .map(str::to_ascii_lowercase)
10730 .unwrap_or_else(|| {
10731 use codewhale_execpolicy::ApprovalMode;
10732
10733 let approval = config
10736 .approval_policy
10737 .as_deref()
10738 .and_then(ApprovalMode::from_config_value)
10739 .unwrap_or_default();
10740 approval.agent_baseline_sandbox_mode().to_string()
10741 });
10742 if !requirements
10743 .allowed_sandbox_modes
10744 .iter()
10745 .any(|m| m.eq_ignore_ascii_case(&mode))
10746 {
10747 anyhow::bail!(
10748 "sandbox_mode '{mode}' is not allowed by requirements ({})",
10749 requirements.allowed_sandbox_modes.join(", ")
10750 );
10751 }
10752 }
10753
10754 Ok(())
10755}
10756
10757fn merge_features(
10758 base: Option<FeaturesToml>,
10759 override_cfg: Option<FeaturesToml>,
10760) -> Option<FeaturesToml> {
10761 match (base, override_cfg) {
10762 (None, None) => None,
10763 (Some(mut base), Some(override_cfg)) => {
10764 for (key, value) in override_cfg.entries {
10765 base.entries.insert(key, value);
10766 }
10767 Some(base)
10768 }
10769 (Some(base), None) => Some(base),
10770 (None, Some(override_cfg)) => Some(override_cfg),
10771 }
10772}
10773
10774pub fn ensure_parent_dir(path: &Path) -> Result<()> {
10775 if let Some(parent) = path.parent() {
10776 fs::create_dir_all(parent)
10777 .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
10778 #[cfg(unix)]
10779 {
10780 if let Ok(meta) = fs::metadata(parent) {
10790 let mode = meta.permissions().mode();
10791 if mode & 0o077 != 0 {
10792 let mut perms = meta.permissions();
10793 perms.set_mode(mode & !0o077);
10794 if let Err(err) = fs::set_permissions(parent, perms) {
10795 tracing::warn!(
10796 target: "codewhale::config",
10797 path = %parent.display(),
10798 error = %err,
10799 "could not tighten parent dir permissions; \
10800 filesystem may not support Unix chmod \
10801 (Docker bind-mount, NTFS, network share). \
10802 Continuing — the file will still be written."
10803 );
10804 }
10805 }
10806 }
10807 }
10808 }
10809 Ok(())
10810}
10811
10812fn write_config_file_secure(path: &Path, content: &str) -> Result<()> {
10815 codewhale_config::create_config_document(path, content)
10816}
10817
10818#[derive(Debug, Clone, PartialEq, Eq)]
10821pub enum SavedCredential {
10822 KeyringAndConfigFile {
10829 backend: String,
10831 path: PathBuf,
10833 },
10834 ConfigFile(PathBuf),
10839}
10840
10841impl SavedCredential {
10842 #[must_use]
10845 pub fn describe(&self) -> String {
10846 match self {
10847 Self::KeyringAndConfigFile { backend, path } => {
10848 format!(
10849 "secret store ({backend}); credential-free config metadata in {}",
10850 path.display()
10851 )
10852 }
10853 Self::ConfigFile(path) => path.display().to_string(),
10854 }
10855 }
10856}
10857
10858pub fn credential_config_path() -> anyhow::Result<PathBuf> {
10871 let resolved = try_default_config_path()?;
10872 if !codewhale_config::config_path_is_workspace_scoped(&resolved) {
10873 return Ok(resolved);
10874 }
10875 let global = home_config_path()
10876 .context("Failed to resolve user-global config path: home directory not found.")?;
10877 tracing::info!(
10878 ambient = %resolved.display(),
10879 global = %global.display(),
10880 "rescoping credential write from workspace config to user-global config"
10881 );
10882 Ok(global)
10883}
10884
10885pub fn save_api_key(api_key: &str) -> Result<SavedCredential> {
10897 save_root_api_key_for_secret_slot(api_key, "deepseek", "deepseek")
10898}
10899
10900fn save_root_api_key_for_secret_slot(
10901 api_key: &str,
10902 secret_slot: &str,
10903 table: &str,
10904) -> Result<SavedCredential> {
10905 let normalized = codewhale_secrets::normalize_api_key(api_key);
10907 let trimmed = normalized.as_str();
10908 if trimmed.is_empty() {
10909 anyhow::bail!("Refusing to save an empty API key.");
10910 }
10911
10912 let path = credential_config_path().context("Failed to resolve config path for API key.")?;
10913
10914 if let Some(secrets) = credential_secret_store() {
10915 return crate::credentials::store::with_provider_write_lock(secret_slot, || {
10918 let prior_secret = secrets.get(secret_slot);
10919 match prior_secret.as_ref() {
10920 Ok(prior) => match secrets.set(secret_slot, trimmed) {
10921 Ok(()) => {
10922 if let Err(error) =
10923 save_root_api_key_metadata_without_plaintext(&path, table)
10924 {
10925 let current = secrets.get(secret_slot).map_err(|rollback| {
10926 anyhow::anyhow!(
10927 "{error}; additionally could not verify secret-store rollback for {secret_slot}: {rollback}"
10928 )
10929 })?;
10930 if current.as_deref() == Some(trimmed) {
10931 match prior {
10932 Some(previous) => secrets.set(secret_slot, previous),
10933 None => secrets.delete(secret_slot),
10934 }
10935 .map_err(|rollback| {
10936 anyhow::anyhow!(
10937 "{error}; additionally failed to restore prior secret-store state for {secret_slot}: {rollback}"
10938 )
10939 })?;
10940 }
10941 return Err(error);
10942 }
10943 codewhale_config::scrub_plaintext_api_keys_from_config_backup(&path)?;
10944 let backend = secrets.backend_name().to_string();
10945 log_sensitive_event(
10946 "credential.save",
10947 json!({
10948 "backend": backend.clone(),
10949 "config_path": path.display().to_string(),
10950 "plaintext_config_fallback": false,
10951 }),
10952 );
10953 Ok(SavedCredential::KeyringAndConfigFile { backend, path })
10954 }
10955 Err(err) => Err(plaintext_credential_fallback_refused("write", &path, &err)),
10956 },
10957 Err(error) => Err(plaintext_credential_fallback_refused(
10958 "snapshot", &path, &error,
10959 )),
10960 }
10961 });
10962 }
10963
10964 let path = save_api_key_to_config_file(trimmed, table)?;
10965 codewhale_config::scrub_plaintext_api_keys_from_config_backup(&path)?;
10966 Ok(SavedCredential::ConfigFile(path))
10967}
10968
10969fn plaintext_credential_fallback_refused(
10970 operation: &str,
10971 config_path: &Path,
10972 failure: &dyn std::fmt::Display,
10973) -> anyhow::Error {
10974 anyhow::anyhow!(
10975 "Secret storage {operation} failed: {failure}. Refusing to write the API key in plaintext to {}. Fix the configured secret backend and retry; Codewhale did not change that file.",
10976 codewhale_config::quote_os_path(config_path)
10977 )
10978}
10979
10980#[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
10986pub fn credential_secret_store() -> Option<codewhale_secrets::Secrets> {
10987 Some(codewhale_secrets::Secrets::auto_detect())
10988}
10989
10990#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
10991pub fn credential_secret_store() -> Option<codewhale_secrets::Secrets> {
10992 let isolated_home = codewhale_paths::codewhale_home_is_explicit();
10993 let explicit_backend = std::env::var_os("CODEWHALE_SECRET_BACKEND")
10994 .or_else(|| std::env::var_os("DEEPSEEK_SECRET_BACKEND"))
10995 .is_some_and(|value| !value.is_empty());
10996 (crate::test_support::state_from_environment() || (isolated_home && explicit_backend))
10997 .then(codewhale_secrets::Secrets::auto_detect)
10998}
10999
11000fn save_root_api_key_metadata_without_plaintext(config_path: &Path, table: &str) -> Result<()> {
11001 ensure_parent_dir(config_path)?;
11002 crate::config_persistence::mutate_config_document(config_path, |doc| {
11003 crate::config_persistence::set_document_value(doc, &["auth_mode"], "api_key")?;
11004 if !doc.contains_key("reasoning_effort") {
11007 crate::config_persistence::set_document_value(doc, &["reasoning_effort"], "auto")?;
11008 }
11009 crate::config_persistence::unset_document_value(doc, &["api_key"])?;
11010 crate::config_persistence::unset_document_value(doc, &["providers", table, "api_key"])?;
11011 crate::config_persistence::set_document_value(
11012 doc,
11013 &["providers", table, "auth_mode"],
11014 "api_key",
11015 )?;
11016 if table == "deepseek" {
11017 crate::config_persistence::unset_document_value(
11018 doc,
11019 &["providers", "deepseek-cn", "api_key"],
11020 )?;
11021 }
11022 Ok(())
11023 })
11024 .with_context(|| format!("Failed to write config to {}", config_path.display()))
11025}
11026
11027fn save_api_key_to_config_file(api_key: &str, table: &str) -> Result<PathBuf> {
11029 let config_path =
11030 credential_config_path().context("Failed to resolve config path for API key.")?;
11031
11032 ensure_parent_dir(&config_path)?;
11033
11034 if config_path.exists() {
11035 crate::config_persistence::mutate_config_document(&config_path, |doc| {
11040 crate::config_persistence::set_document_value(
11043 doc,
11044 &["providers", table, "api_key"],
11045 api_key,
11046 )?;
11047 crate::config_persistence::unset_document_value(doc, &["api_key"])?;
11048 crate::config_persistence::set_document_value(doc, &["auth_mode"], "api_key")
11049 })
11050 .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
11051 } else {
11052 let content = format!(
11054 r#"# codewhale Configuration
11055# Set provider credentials in this file or via environment variables.
11056# See /links in the TUI for provider-specific credential pages.
11057
11058auth_mode = "api_key"
11059
11060# Default model (unset follows the provider default)
11061# default_text_model = "{DEFAULT_TEXT_MODEL}"
11062
11063# Thinking mode (DeepSeek V4 reasoning effort):
11064# "auto" | "off" | "low" | "medium" | "high" | "max"
11065# Ctrl+T in the TUI (or /effort) cycles the active model's effort levels.
11066reasoning_effort = "auto"
11067
11068[providers.{table}]
11069api_key = "{api_key}"
11070# Base URL (default: https://api.deepseek.com/beta)
11071# Set https://api.deepseek.com to opt out of beta features.
11072# base_url = "https://api.deepseek.com/beta"
11073"#
11074 );
11075 crate::config_persistence::write_config_toml_atomic(&config_path, &content)
11076 .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
11077 }
11078
11079 log_sensitive_event(
11080 "credential.save",
11081 json!({
11082 "backend": "config_file",
11083 "config_path": config_path.display().to_string(),
11084 }),
11085 );
11086
11087 Ok(config_path)
11088}
11089
11090fn provider_uses_oauth_credentials(config: &Config, identity: &ProviderIdentity) -> bool {
11091 let provider = identity.provider;
11092 !auth_mode_disables_api_key(config.auth_mode_for_provider(identity).as_deref())
11093 && !config.provider_uses_custom_endpoint(identity)
11094 && (provider == ProviderKind::OpenaiCodex
11095 || (provider == ProviderKind::Anthropic
11096 && config.auth_mode_for_provider(identity).as_deref() == Some("oauth"))
11097 || (provider == ProviderKind::Moonshot
11098 && config
11099 .provider_config_for(identity)
11100 .is_some_and(provider_config_uses_kimi_imported_token))
11101 || (provider == ProviderKind::Xai
11102 && config
11103 .provider_config_for(identity)
11104 .is_some_and(provider_config_uses_xai_oauth)))
11105}
11106
11107fn bound_provider_api_key_env_name(config: &Config, identity: &ProviderIdentity) -> Option<String> {
11111 if !config.config_credentials_are_bound_to_provider_endpoint(identity) {
11112 return None;
11113 }
11114 config
11115 .provider_config_for(identity)
11116 .and_then(|entry| entry.api_key_env.as_deref())
11117 .map(str::trim)
11118 .filter(|name| !name.is_empty())
11119 .map(str::to_string)
11120}
11121
11122fn provider_config_env_api_key(config: &Config, identity: &ProviderIdentity) -> Option<String> {
11123 let env_name = bound_provider_api_key_env_name(config, identity)?;
11124 std::env::var(env_name)
11125 .ok()
11126 .filter(|value| !value.trim().is_empty())
11127}
11128
11129#[must_use]
11130pub fn active_provider_has_config_api_key(config: &Config) -> bool {
11131 let Ok(identity) = config.active_provider_identity() else {
11132 return false;
11133 };
11134 let provider = identity.provider;
11135 if auth_mode_disables_api_key(config.auth_mode_for_provider(&identity).as_deref()) {
11136 return false;
11137 }
11138 let custom_endpoint = config.provider_uses_custom_endpoint(&identity);
11139
11140 if provider == ProviderKind::Moonshot
11141 && !custom_endpoint
11142 && config
11143 .provider_config_for(&identity)
11144 .is_some_and(provider_config_uses_kimi_imported_token)
11145 {
11146 return false;
11147 }
11148 if provider == ProviderKind::OpenaiCodex && !custom_endpoint {
11149 return crate::oauth::credentials_valid(crate::oauth::OAuthProvider::Chatgpt, config);
11150 }
11151 if !custom_endpoint
11152 && matches!(provider, ProviderKind::Huggingface)
11153 && std::env::var("HUGGINGFACE_API_KEY")
11154 .or_else(|_| std::env::var("HF_TOKEN"))
11155 .is_ok_and(|k| !k.trim().is_empty())
11156 {
11157 return true;
11158 }
11159 if !custom_endpoint
11160 && matches!(provider, ProviderKind::Modelscope)
11161 && std::env::var("MODELSCOPE_API_KEY").is_ok_and(|k| !k.trim().is_empty())
11162 {
11163 return true;
11164 }
11165
11166 if config.config_credentials_are_bound_to_provider_endpoint(&identity)
11167 && config
11168 .provider_route_string_with_deepseek_fallback(&identity, |entry| entry.api_key.clone())
11169 .is_some_and(|key| {
11170 classify_config_api_key_value(&key) == ConfigApiKeyValueKind::Literal
11171 })
11172 {
11173 return true;
11174 }
11175 if !config.should_skip_secret_store_for_provider(&identity)
11176 && provider_secret_store_api_key(config, &identity).is_some()
11177 {
11178 return true;
11179 }
11180
11181 false
11182}
11183
11184#[must_use]
11185pub fn active_provider_has_env_api_key(config: &Config) -> bool {
11186 active_provider_env_api_key_source(config).is_some()
11187}
11188
11189#[must_use]
11194pub fn active_provider_env_api_key_source(config: &Config) -> Option<String> {
11195 let identity = config.active_provider_identity().ok()?;
11196 if config.required_account_model_owner.is_some()
11197 || config.session_provider_keys_only
11198 || config.session_provider_api_key(&identity).is_some()
11199 {
11200 return None;
11201 }
11202 let provider = identity.provider;
11203 if provider == ProviderKind::OpenaiCodex && !config.provider_uses_custom_endpoint(&identity) {
11204 return None;
11205 }
11206 if auth_mode_disables_api_key(config.auth_mode_for_provider(&identity).as_deref()) {
11207 return None;
11208 }
11209 if !provider_uses_oauth_credentials(config, &identity)
11210 && explicit_cli_api_key_override().is_some()
11211 {
11212 return Some("--api-key".to_string());
11213 }
11214 if provider_config_env_api_key(config, &identity).is_some() {
11215 return bound_provider_api_key_env_name(config, &identity);
11216 }
11217 if config.should_skip_secret_store_for_provider(&identity) {
11218 return None;
11219 }
11220 provider_env_api_key_named(provider).map(|(name, _)| name.to_string())
11221}
11222
11223#[must_use]
11224pub fn active_provider_uses_env_only_api_key(config: &Config) -> bool {
11225 active_provider_has_env_api_key(config) && !active_provider_has_config_api_key(config)
11226}
11227
11228struct UserGlobalConfigCache {
11238 path: PathBuf,
11239 modified: Option<SystemTime>,
11240 len: u64,
11241 json: serde_json::Value,
11242}
11243
11244fn user_global_config_json() -> Option<serde_json::Value> {
11245 static CACHE: Mutex<Option<UserGlobalConfigCache>> = Mutex::new(None);
11246 let path = codewhale_config::default_config_path().ok()?;
11247 let meta = fs::metadata(&path).ok()?;
11248 let modified = meta.modified().ok();
11249 let len = meta.len();
11250 let mut guard = CACHE.lock().ok()?;
11251 if let Some(cached) = guard.as_ref()
11252 && cached.path == path
11253 && cached.modified == modified
11254 && cached.len == len
11255 {
11256 return Some(cached.json.clone());
11257 }
11258 let text = fs::read_to_string(&path).ok()?;
11259 let doc = codewhale_config::parse_config_toml(&text).ok()?;
11260 let json = serde_json::to_value(&doc).ok()?;
11261 *guard = Some(UserGlobalConfigCache {
11262 path,
11263 modified,
11264 len,
11265 json: json.clone(),
11266 });
11267 Some(json)
11268}
11269
11270fn user_global_config_api_key(identity: &ProviderIdentity) -> Option<String> {
11271 let provider = identity.provider;
11272 if provider == ProviderKind::Custom {
11273 return None;
11276 }
11277 let json = user_global_config_json()?;
11278 let provider_config_key = identity.compatibility()?.config_key;
11279 let key = json
11280 .get("providers")?
11281 .get(provider_config_key)?
11282 .get("api_key")?
11283 .as_str()?;
11284 let key = key.trim();
11285 if key.is_empty() || classify_config_api_key_value(key) != ConfigApiKeyValueKind::Literal {
11286 return None;
11287 }
11288 Some(key.to_string())
11289}
11290
11291pub type ResolvedApiKey = (String, String);
11293
11294pub const XAI_OAUTH_KEY_SOURCE: &str = "xAI OAuth login";
11297
11298impl Config {
11299 pub fn codex_credentials(&self) -> Result<crate::oauth::OwnedOAuthCredentials> {
11302 anyhow::ensure!(
11303 !self.session_provider_keys_only,
11304 "Stored ChatGPT sign-in is unavailable under session-only provider key policy"
11305 );
11306 let identity = self
11307 .active_provider_identity()
11308 .map_err(anyhow::Error::msg)?;
11309 anyhow::ensure!(
11310 identity.provider == ProviderKind::OpenaiCodex
11311 && !self.provider_uses_custom_endpoint(&identity),
11312 "ChatGPT credentials are only available on the official public API route"
11313 );
11314 crate::oauth::official_chatgpt_registration(self)?;
11315 crate::oauth::get_owned_credentials(crate::oauth::OAuthProvider::Chatgpt, self)
11316 }
11317
11318 #[cfg(any(test, feature = "test-support"))]
11320 pub fn codex_account_id(&self) -> Option<String> {
11321 self.codex_credentials()
11322 .ok()
11323 .and_then(|credentials| credentials.account_id)
11324 }
11325}
11326
11327#[must_use]
11337pub fn provider_is_configured(
11338 provider: ProviderKind,
11339 is_active: bool,
11340 has_key: bool,
11341 configured: Option<&ProviderConfig>,
11342 is_named_custom_entry: bool,
11343) -> bool {
11344 if is_active || is_named_custom_entry {
11349 return true;
11350 }
11351 if configured.is_some_and(provider_config_is_explicit) {
11352 return true;
11353 }
11354 if matches!(
11355 provider,
11356 ProviderKind::Ollama | ProviderKind::Sglang | ProviderKind::Vllm
11357 ) {
11358 return false;
11359 }
11360 has_key
11361}
11362
11363fn provider_config_is_explicit(entry: &ProviderConfig) -> bool {
11370 let non_empty = |value: Option<&String>| value.is_some_and(|value| !value.trim().is_empty());
11371
11372 non_empty(entry.api_key.as_ref())
11373 || entry.vendor.is_some()
11374 || non_empty(entry.base_url.as_ref())
11375 || non_empty(entry.model.as_ref())
11376 || non_empty(entry.auth_mode.as_ref())
11377 || entry
11378 .auth
11379 .as_ref()
11380 .is_some_and(|auth| auth.validate().is_ok())
11381 || entry.context_window.is_some()
11382 || entry
11383 .model_context_windows
11384 .as_ref()
11385 .is_some_and(|table| !table.is_empty())
11386 || non_empty(entry.mode.as_ref())
11387 || entry.max_concurrency.is_some()
11388 || entry.http_headers.as_ref().is_some_and(|headers| {
11389 headers
11390 .iter()
11391 .any(|(name, value)| !name.trim().is_empty() && !value.trim().is_empty())
11392 })
11393 || non_empty(entry.path_suffix.as_ref())
11394 || non_empty(entry.reasoning_stream_style.as_ref())
11395 || entry.insecure_skip_tls_verify.is_some()
11396 || entry.allow_insecure_http.is_some()
11397 || non_empty(entry.kind.as_ref())
11398 || non_empty(entry.api_key_env.as_ref())
11399 || entry.external_credentials.is_some()
11400 || non_empty(entry.oauth_credential_generation.as_ref())
11401}
11402
11403#[cfg(any(test, feature = "test-support"))]
11408pub fn save_api_key_for(provider: ProviderKind, api_key: &str) -> Result<PathBuf> {
11409 match save_api_key_for_identity(
11410 &ProviderIdentity {
11411 provider,
11412 key: provider.as_str().into(),
11413 exact_id: Some(provider.as_str().into()),
11414 migrated_legacy_ollama_cloud_route: false,
11415 legacy_root_custom_generation: None,
11416 },
11417 &Config {
11418 provider: Some(provider.as_str().to_string()),
11419 ..Config::default()
11420 },
11421 api_key,
11422 )? {
11423 SavedCredential::KeyringAndConfigFile { path, .. } | SavedCredential::ConfigFile(path) => {
11424 Ok(path)
11425 }
11426 }
11427}
11428
11429pub fn save_api_key_for_identity(
11434 identity: &ProviderIdentity,
11435 route_config: &Config,
11436 api_key: &str,
11437) -> Result<SavedCredential> {
11438 route_config
11439 .verify_provider_identity(identity)
11440 .map_err(anyhow::Error::msg)?;
11441 if identity.provider == ProviderKind::Xai {
11442 return codewhale_config::with_xai_oauth_revocation_transaction(|| {
11443 save_api_key_for_identity_unlocked(identity, route_config, api_key)
11444 });
11445 }
11446 save_api_key_for_identity_unlocked(identity, route_config, api_key)
11447}
11448
11449fn save_api_key_for_identity_unlocked(
11450 identity: &ProviderIdentity,
11451 route_config: &Config,
11452 api_key: &str,
11453) -> Result<SavedCredential> {
11454 route_config
11455 .verify_provider_identity(identity)
11456 .map_err(anyhow::Error::msg)?;
11457 let provider = identity.provider;
11458 if provider == ProviderKind::OpenaiCodex {
11459 anyhow::bail!(codewhale_config::credentials::OPENAI_CODEX_API_KEY_REFUSAL);
11460 }
11461 let is_legacy_literal_custom = provider == ProviderKind::Custom
11462 && identity.key.as_str().trim() == ProviderKind::Custom.as_str()
11463 && identity.persisted_id().is_none();
11464 if matches!(provider, ProviderKind::Deepseek) {
11465 return save_api_key(api_key);
11466 }
11467 if is_legacy_literal_custom {
11468 return save_root_api_key_for_secret_slot(api_key, "custom", "custom");
11469 }
11470
11471 let normalized = codewhale_secrets::normalize_api_key(api_key);
11472 let api_key = normalized.as_str();
11473 anyhow::ensure!(!api_key.is_empty(), "Refusing to save an empty API key.");
11474
11475 let config_path =
11476 credential_config_path().context("Failed to resolve config path for provider API key.")?;
11477 ensure_parent_dir(&config_path)?;
11478
11479 let key_inside = if provider == ProviderKind::Custom {
11480 let key = identity.key.as_str().trim();
11481 anyhow::ensure!(!key.is_empty(), "custom provider id cannot be empty");
11482 key
11483 } else {
11484 provider_config_key(identity).context("provider api key table")?
11485 };
11486 let pin_kimi_code_base_url = provider == ProviderKind::Moonshot
11492 && route_config
11493 .provider_config_for(identity)
11494 .is_some_and(|entry| {
11495 provider_config_uses_kimi_imported_token(entry)
11496 && entry
11497 .base_url
11498 .as_deref()
11499 .is_none_or(|base_url| base_url.trim().is_empty())
11500 });
11501
11502 if !route_config.should_skip_secret_store_for_provider(identity)
11503 && let Some(secrets) = credential_secret_store()
11504 {
11505 let secret_slot = provider_secret_store_slot(provider);
11506 return crate::credentials::store::with_provider_write_lock(secret_slot, || {
11513 let prior_secret = secrets.get(secret_slot);
11514 match prior_secret.as_ref() {
11515 Ok(prior) => match secrets.set(secret_slot, api_key) {
11516 Ok(()) => {
11517 let config_result = crate::config_persistence::mutate_config_document(
11518 &config_path,
11519 |doc| {
11520 if pin_kimi_code_base_url {
11521 crate::config_persistence::set_document_value(
11522 doc,
11523 &["providers", key_inside, "base_url"],
11524 DEFAULT_KIMI_CODE_BASE_URL,
11525 )?;
11526 }
11527 crate::config_persistence::set_document_value(
11528 doc,
11529 &["providers", key_inside, "auth_mode"],
11530 "api_key",
11531 )?;
11532 crate::config_persistence::unset_document_value(
11533 doc,
11534 &["providers", key_inside, "external_credentials"],
11535 )?;
11536 if matches!(provider, ProviderKind::Xai | ProviderKind::Anthropic) {
11537 crate::config_persistence::unset_document_value(
11538 doc,
11539 &["providers", key_inside, "oauth_credential_generation"],
11540 )?;
11541 }
11542 crate::config_persistence::unset_document_value(
11543 doc,
11544 &["providers", key_inside, "api_key"],
11545 )?;
11546 Ok(())
11547 },
11548 )
11549 .with_context(|| {
11550 format!("Failed to write config to {}", config_path.display())
11551 });
11552 if let Err(error) = config_result {
11553 let current = secrets.get(secret_slot).map_err(|rollback| {
11554 anyhow::anyhow!(
11555 "{error}; additionally could not verify secret-store rollback for {secret_slot}: {rollback}"
11556 )
11557 })?;
11558 if current.as_deref() == Some(api_key) {
11559 match prior {
11560 Some(previous) => secrets.set(secret_slot, previous),
11561 None => secrets.delete(secret_slot),
11562 }
11563 .map_err(|rollback| {
11564 anyhow::anyhow!(
11565 "{error}; additionally failed to restore prior secret-store state for {secret_slot}: {rollback}"
11566 )
11567 })?;
11568 }
11569 return Err(error);
11570 }
11571 codewhale_config::scrub_plaintext_api_keys_from_config_backup(
11572 &config_path,
11573 )?;
11574 let backend = secrets.backend_name().to_string();
11575 log_sensitive_event(
11576 "credential.save",
11577 json!({
11578 "backend": backend.clone(),
11579 "provider": identity.key,
11580 "config_path": config_path.display().to_string(),
11581 "plaintext_config_fallback": false,
11582 }),
11583 );
11584 Ok(SavedCredential::KeyringAndConfigFile {
11585 backend,
11586 path: config_path,
11587 })
11588 }
11589 Err(err) => Err(plaintext_credential_fallback_refused(
11590 "write",
11591 &config_path,
11592 &err,
11593 )),
11594 },
11595 Err(error) => Err(plaintext_credential_fallback_refused(
11596 "snapshot",
11597 &config_path,
11598 &error,
11599 )),
11600 }
11601 });
11602 }
11603
11604 crate::config_persistence::mutate_config_document(&config_path, |doc| {
11607 if pin_kimi_code_base_url {
11608 crate::config_persistence::set_document_value(
11609 doc,
11610 &["providers", key_inside, "base_url"],
11611 DEFAULT_KIMI_CODE_BASE_URL,
11612 )?;
11613 }
11614 crate::config_persistence::set_document_value(
11615 doc,
11616 &["providers", key_inside, "auth_mode"],
11617 "api_key",
11618 )?;
11619 crate::config_persistence::unset_document_value(
11620 doc,
11621 &["providers", key_inside, "external_credentials"],
11622 )?;
11623 if matches!(provider, ProviderKind::Xai | ProviderKind::Anthropic) {
11624 crate::config_persistence::unset_document_value(
11625 doc,
11626 &["providers", key_inside, "oauth_credential_generation"],
11627 )?;
11628 }
11629 crate::config_persistence::set_document_value(
11630 doc,
11631 &["providers", key_inside, "api_key"],
11632 api_key,
11633 )
11634 })
11635 .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
11636 log_sensitive_event(
11637 "credential.save",
11638 json!({
11639 "backend": "config_file",
11640 "provider": identity.key,
11641 "config_path": config_path.display().to_string(),
11642 }),
11643 );
11644 codewhale_config::scrub_plaintext_api_keys_from_config_backup(&config_path)?;
11645
11646 Ok(SavedCredential::ConfigFile(config_path))
11647}
11648
11649pub fn save_provider_model_for_identity(
11652 identity: &ProviderIdentity,
11653 route_config: &Config,
11654 model: &str,
11655) -> Result<PathBuf> {
11656 route_config
11657 .verify_provider_identity(identity)
11658 .map_err(anyhow::Error::msg)?;
11659 let model = model.trim();
11660 anyhow::ensure!(!model.is_empty(), "model cannot be empty");
11661 let config_path =
11662 try_default_config_path().context("Failed to resolve config path for provider model.")?;
11663 crate::config_persistence::persist_provider_model_key(Some(&config_path), identity, model)
11664}
11665
11666pub fn save_provider_base_url_for_identity(
11673 identity: &ProviderIdentity,
11674 route_config: &Config,
11675 base_url: &str,
11676) -> Result<PathBuf> {
11677 route_config
11678 .verify_provider_identity(identity)
11679 .map_err(anyhow::Error::msg)?;
11680 let base_url = base_url.trim();
11681 anyhow::ensure!(!base_url.is_empty(), "base URL cannot be empty");
11682 let config_path = try_default_config_path()
11683 .context("Failed to resolve config path for provider base URL.")?;
11684 ensure_parent_dir(&config_path)?;
11685 let key_inside = if identity.provider == ProviderKind::Custom {
11686 let key = identity.key.as_str().trim();
11687 anyhow::ensure!(!key.is_empty(), "custom provider id cannot be empty");
11688 key
11689 } else {
11690 provider_config_key(identity).context("provider base URL table")?
11691 };
11692 crate::config_persistence::mutate_config_document(&config_path, |doc| {
11693 crate::config_persistence::set_document_value(
11694 doc,
11695 &["providers", key_inside, "base_url"],
11696 base_url,
11697 )
11698 })
11699 .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
11700 Ok(config_path)
11701}
11702
11703pub fn save_provider_context_window_for_identity(
11706 identity: &ProviderIdentity,
11707 route_config: &Config,
11708 context_window: u32,
11709) -> Result<PathBuf> {
11710 route_config
11711 .verify_provider_identity(identity)
11712 .map_err(anyhow::Error::msg)?;
11713 anyhow::ensure!(context_window > 0, "context window must be greater than 0");
11714 let config_path = try_default_config_path()
11715 .context("Failed to resolve config path for provider context window.")?;
11716 ensure_parent_dir(&config_path)?;
11717 let key_inside = if identity.provider == ProviderKind::Custom {
11718 let key = identity.key.as_str().trim();
11719 anyhow::ensure!(!key.is_empty(), "custom provider id cannot be empty");
11720 key
11721 } else {
11722 provider_config_key(identity).context("provider context window table")?
11723 };
11724 crate::config_persistence::mutate_config_document(&config_path, |doc| {
11725 crate::config_persistence::set_document_value(
11726 doc,
11727 &["providers", key_inside, "context_window"],
11728 i64::from(context_window),
11729 )
11730 })
11731 .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
11732 Ok(config_path)
11733}
11734
11735fn validate_external_credential_before_consent(
11746 consent_provider: codewhale_config::ProviderKind,
11747 source: codewhale_config::ExternalCredentialSource,
11748 path: &Path,
11749) -> Result<()> {
11750 let grant = codewhale_config::ExternalCredentialConsentToml::read_only(
11751 consent_provider,
11752 source,
11753 path.to_path_buf(),
11754 )
11755 .read_grant(consent_provider, source, path)?;
11756 match source {
11757 codewhale_config::ExternalCredentialSource::CodexCli => {
11758 crate::oauth::get_credentials(&grant).map(|_| ())
11759 }
11760 codewhale_config::ExternalCredentialSource::GrokCli => {
11761 crate::oauth::validate_grok_external_credentials(&grant)
11762 }
11763 codewhale_config::ExternalCredentialSource::DshCli => {
11764 crate::dsh_credentials::deepseek_api_key_from_grant(&grant)?
11765 .map(|_| ())
11766 .context("the DeepSeek Harness credentials file holds no DEEPSEEK_API_KEY")
11767 }
11768 codewhale_config::ExternalCredentialSource::AgyCli => {
11771 anyhow::bail!(codewhale_config::LEGACY_ANTIGRAVITY_TOMBSTONE_MESSAGE)
11772 }
11773 codewhale_config::ExternalCredentialSource::KimiCodeCli => anyhow::bail!(
11774 "Kimi CLI credentials are never imported; configure a Kimi API key instead"
11775 ),
11776 }
11777}
11778
11779pub fn persist_external_credential_consent_for_at(
11788 config_path: Option<&Path>,
11789 live_config: &mut Config,
11790 identity: &ProviderIdentity,
11791 consent_provider: codewhale_config::ProviderKind,
11792 source: codewhale_config::ExternalCredentialSource,
11793 path: &Path,
11794) -> Result<PathBuf> {
11795 live_config
11796 .verify_provider_identity(identity)
11797 .map_err(anyhow::Error::msg)?;
11798 let provider = identity.provider;
11799 let expected = match provider {
11800 ProviderKind::OpenaiCodex => (
11801 codewhale_config::ProviderKind::OpenaiCodex,
11802 codewhale_config::ExternalCredentialSource::CodexCli,
11803 ),
11804 ProviderKind::Xai => (
11805 codewhale_config::ProviderKind::Xai,
11806 codewhale_config::ExternalCredentialSource::GrokCli,
11807 ),
11808 _ => anyhow::bail!(
11809 "{} has no supported external credential owner",
11810 provider.as_str()
11811 ),
11812 };
11813 anyhow::ensure!(
11814 (consent_provider, source) == expected,
11815 "external credential owner does not match provider {}",
11816 provider.as_str()
11817 );
11818 let path = codewhale_config::resolve_external_credential_path(path)?;
11819 let path_value = path.to_str().context(
11820 "external credential path cannot be persisted losslessly because it is not valid UTF-8",
11821 )?;
11822 validate_external_credential_before_consent(consent_provider, source, &path).with_context(
11823 || {
11824 format!(
11825 "no usable {} credential was found, so read-only consent was not saved",
11826 source.owner_label()
11827 )
11828 },
11829 )?;
11830 let config_path = match config_path {
11831 Some(path) => path.to_path_buf(),
11832 None => credential_config_path()
11833 .context("Failed to resolve config path for external credential consent.")?,
11834 };
11835 ensure_parent_dir(&config_path)?;
11836 let key_inside = provider_config_key(identity).context("external credential provider key")?;
11837 crate::config_persistence::mutate_config_document(&config_path, |doc| {
11838 crate::config_persistence::set_document_value(
11839 doc,
11840 &["providers", key_inside, "auth_mode"],
11841 "oauth",
11842 )?;
11843 let prefix = &["providers", key_inside, "external_credentials"];
11844 crate::config_persistence::set_document_value(
11845 doc,
11846 &[prefix[0], prefix[1], prefix[2], "access"],
11847 "read_only",
11848 )?;
11849 crate::config_persistence::set_document_value(
11850 doc,
11851 &[prefix[0], prefix[1], prefix[2], "provider"],
11852 consent_provider.as_str(),
11853 )?;
11854 crate::config_persistence::set_document_value(
11855 doc,
11856 &[prefix[0], prefix[1], prefix[2], "source"],
11857 source.as_str(),
11858 )?;
11859 crate::config_persistence::set_document_value(
11860 doc,
11861 &[prefix[0], prefix[1], prefix[2], "path"],
11862 path_value,
11863 )?;
11864 crate::config_persistence::set_document_value(
11865 doc,
11866 &[prefix[0], prefix[1], prefix[2], "consent_version"],
11867 i64::from(codewhale_config::EXTERNAL_CREDENTIAL_CONSENT_VERSION),
11868 )
11869 })
11870 .with_context(|| {
11871 format!(
11872 "Failed to write config to {}",
11873 codewhale_config::quote_os_path(&config_path)
11874 )
11875 })?;
11876 live_config
11877 .providers
11878 .get_or_insert_with(ProvidersConfig::default);
11879 let entry = live_config.provider_config_for_mut(identity)?;
11880 entry.auth_mode = Some("oauth".to_string());
11881 entry.external_credentials = Some(codewhale_config::ExternalCredentialConsentToml::read_only(
11882 consent_provider,
11883 source,
11884 path,
11885 ));
11886 Ok(config_path)
11887}
11888
11889pub fn revoke_external_credential_consent_for_at(
11891 config_path: Option<&Path>,
11892 live_config: &mut Config,
11893 identity: &ProviderIdentity,
11894) -> Result<PathBuf> {
11895 live_config
11896 .verify_provider_identity(identity)
11897 .map_err(anyhow::Error::msg)?;
11898 let provider = identity.provider;
11899 anyhow::ensure!(
11900 matches!(provider, ProviderKind::OpenaiCodex | ProviderKind::Xai),
11901 "{} has no supported external credential owner",
11902 provider.as_str()
11903 );
11904 let config_path = match config_path {
11905 Some(path) => path.to_path_buf(),
11906 None => credential_config_path()
11907 .context("Failed to resolve config path for external credential consent.")?,
11908 };
11909 ensure_parent_dir(&config_path)?;
11910 let key_inside = provider_config_key(identity).context("external credential provider key")?;
11911 crate::config_persistence::mutate_config_document(&config_path, |doc| {
11912 crate::config_persistence::unset_document_value(
11913 doc,
11914 &["providers", key_inside, "external_credentials"],
11915 )?;
11916 Ok(())
11917 })
11918 .with_context(|| {
11919 format!(
11920 "Failed to write config to {}",
11921 codewhale_config::quote_os_path(&config_path)
11922 )
11923 })?;
11924 live_config
11925 .provider_config_for_mut(identity)?
11926 .external_credentials = None;
11927 Ok(config_path)
11928}
11929
11930pub fn provider_config_key(identity: &ProviderIdentity) -> Result<&str> {
11931 if identity.provider == ProviderKind::Deepseek
11932 && identity.key.as_str() == ProviderKind::Deepseek.as_str()
11933 {
11934 anyhow::bail!("DeepSeek stores auth at the root config level");
11935 }
11936 identity.config_table_key()
11937}
11938
11939fn provider_config_table_name(identity: &ProviderIdentity) -> Result<String> {
11940 Ok(format!("providers.{}", provider_config_key(identity)?))
11941}
11942
11943pub fn provider_env_api_key_var(provider: ProviderKind) -> Option<&'static str> {
11946 provider_env_api_key_named(provider).map(|(name, _)| name)
11947}
11948
11949fn provider_env_api_key_named(provider: ProviderKind) -> Option<(&'static str, String)> {
11952 let read = || {
11953 let names = provider.provider().env_vars();
11954 names.iter().find_map(|name| {
11955 std::env::var(name)
11956 .ok()
11957 .map(|value| codewhale_secrets::normalize_api_key(&value))
11958 .filter(|value| !value.is_empty())
11959 .map(|value| (*name, value))
11960 })
11961 };
11962 #[cfg(any(test, feature = "test-support"))]
11963 {
11964 codewhale_util::test_env_lock::with_test_env_lock(read)
11965 }
11966 #[cfg(not(any(test, feature = "test-support")))]
11967 {
11968 read()
11969 }
11970}
11971
11972pub fn provider_secret_store_slot(provider: ProviderKind) -> &'static str {
11974 provider.secret_store_slot()
11975}
11976
11977fn secret_slot_save_marker_on_shared_slot(config: &Config, identity: &ProviderIdentity) -> bool {
11985 let slot = provider_secret_store_slot(identity.provider);
11986 codewhale_config::descriptors::provider_compatibility()
11987 .iter()
11988 .filter(|row| provider_secret_store_slot(row.kind) == slot)
11989 .filter_map(|row| {
11990 config
11991 .resolve_persisted_provider_identity(Some(row.id), Some(row.id))
11992 .ok()
11993 })
11994 .any(|candidate| {
11995 config
11996 .provider_config_for(&candidate)
11997 .is_some_and(|entry| auth_mode_requires_api_key(entry.auth_mode.as_deref()))
11998 })
11999}
12000
12001pub fn provider_secret_store_api_key(
12006 config: &Config,
12007 identity: &ProviderIdentity,
12008) -> Option<String> {
12009 provider_secret_store_api_key_with_mode(config, identity, false)
12010}
12011
12012fn provider_secret_store_api_key_with_mode(
12013 config: &Config,
12014 identity: &ProviderIdentity,
12015 read_only: bool,
12016) -> Option<String> {
12017 let provider = identity.provider;
12018 if config.should_skip_secret_store_for_provider(identity) {
12023 return None;
12024 }
12025
12026 #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
12030 if !crate::test_support::state_from_environment()
12031 && (!codewhale_paths::codewhale_home_is_explicit()
12032 || std::env::var_os("CODEWHALE_SECRET_BACKEND").is_none())
12033 {
12034 return None;
12035 }
12036
12037 let secrets = if read_only {
12038 codewhale_secrets::Secrets::auto_detect_read_only()
12039 } else {
12040 codewhale_secrets::Secrets::auto_detect()
12041 };
12042 let store =
12047 crate::credentials::store::SecretStoreCredentials::new(secrets, known_secret_store_slots());
12048 let primary = store
12049 .read(provider_secret_store_slot(provider))
12050 .ok()
12051 .flatten()
12052 .map(|credential| credential.expose_secret().to_string());
12053 if primary.is_some() {
12054 return primary;
12055 }
12056
12057 (provider == ProviderKind::OllamaCloud && identity.migrated_legacy_ollama_cloud_route)
12062 .then(|| {
12063 store
12064 .read(ProviderKind::Ollama.as_str())
12065 .ok()
12066 .flatten()
12067 .map(|credential| credential.expose_secret().to_string())
12068 })
12069 .flatten()
12070}
12071
12072fn known_secret_store_slots() -> Vec<String> {
12079 let mut slots: Vec<String> = codewhale_config::descriptors::provider_compatibility()
12080 .iter()
12081 .map(|row| provider_secret_store_slot(row.kind).to_string())
12082 .collect();
12083 slots.sort();
12084 slots.dedup();
12085 slots
12086}
12087
12088fn config_api_key_shadow_warning(
12100 config: &Config,
12101 identity: &ProviderIdentity,
12102 config_source: &str,
12103) -> Option<String> {
12104 let provider = identity.provider;
12105 if config.should_skip_secret_store_for_provider(identity) {
12106 return None;
12107 }
12108 provider_secret_store_api_key_with_mode(config, identity, true).map(|_| {
12109 let slot = provider_secret_store_slot(provider);
12110 let id = provider.as_str();
12111 format!(
12112 "both {config_source} in the config file and secret-store slot \"{slot}\" \
12113 hold a credential for provider {id}; the config-file key won. Run \
12114 `codewhale auth set --provider {id}` to move the key into the secret store \
12115 and strip the plaintext copy, or remove the config-file api_key."
12116 )
12117 })
12118}
12119
12120fn warn_on_config_api_key_shadowing(
12124 config: &Config,
12125 identity: &ProviderIdentity,
12126 config_source: &str,
12127) {
12128 let provider = identity.provider;
12129 let Some(message) = config_api_key_shadow_warning(config, identity, config_source) else {
12130 return;
12131 };
12132 static WARNED_SLOTS: std::sync::OnceLock<
12133 std::sync::Mutex<std::collections::HashSet<&'static str>>,
12134 > = std::sync::OnceLock::new();
12135 let mut warned = WARNED_SLOTS
12136 .get_or_init(|| std::sync::Mutex::new(std::collections::HashSet::new()))
12137 .lock()
12138 .unwrap_or_else(|poisoned| poisoned.into_inner());
12139 if !warned.insert(provider_secret_store_slot(provider)) {
12140 return;
12141 }
12142 drop(warned);
12143 tracing::warn!("{message}");
12144}
12145
12146pub fn explicit_launch_model_override() -> Option<String> {
12156 codewhale_env_var("CODEWHALE_MODEL", "DEEPSEEK_MODEL")
12157 .ok()
12158 .map(|value| value.trim().to_string())
12159 .filter(|value| !value.is_empty())
12160}
12161
12162pub fn explicit_launch_provider_override() -> Option<String> {
12168 codewhale_env_var("CODEWHALE_PROVIDER", "DEEPSEEK_PROVIDER")
12169 .ok()
12170 .map(|value| value.trim().to_string())
12171 .filter(|value| !value.is_empty())
12172}
12173
12174pub fn explicit_cli_api_key_override() -> Option<String> {
12175 let read = || {
12176 (cli_api_key_source().as_deref() == Some("cli"))
12177 .then(|| {
12178 std::env::var(codewhale_config::CLI_API_KEY_ENV)
12179 .ok()
12180 .filter(|value| !value.trim().is_empty())
12181 })
12182 .flatten()
12183 };
12184 #[cfg(any(test, feature = "test-support"))]
12185 {
12186 codewhale_util::test_env_lock::with_test_env_lock(read)
12187 }
12188 #[cfg(not(any(test, feature = "test-support")))]
12189 {
12190 read()
12191 }
12192}
12193
12194pub fn cli_api_key_source() -> Option<String> {
12195 codewhale_env_var(
12196 codewhale_config::CLI_API_KEY_SOURCE_ENV,
12197 codewhale_config::LEGACY_CLI_API_KEY_SOURCE_ENV,
12198 )
12199 .ok()
12200}
12201
12202fn missing_provider_api_key_message(identity: &ProviderIdentity) -> Result<String> {
12203 let provider = identity.provider;
12204 let credential_hint = provider
12205 .provider()
12206 .credential_help()
12207 .credential_url
12208 .map(|url| format!(" Get a key: {url}."))
12209 .unwrap_or_default();
12210 let label = identity
12211 .compatibility()
12212 .map_or_else(|| provider.provider().display_name(), |row| row.label);
12213 Ok(format!(
12214 "{} API key not found.{} Run 'codewhale auth set --provider {}', set {}, or add [{}] api_key in ~/.codewhale/config.toml.",
12215 label,
12216 credential_hint,
12217 identity.key,
12218 provider.provider().env_vars().join(" / "),
12219 provider_config_table_name(identity)?
12220 ))
12221}
12222
12223pub fn clear_api_key() -> Result<()> {
12243 codewhale_config::with_xai_oauth_revocation_transaction(clear_api_key_unlocked)
12244}
12245
12246fn clear_api_key_unlocked() -> Result<()> {
12247 crate::credentials::store::with_provider_write_locks(
12251 known_secret_store_slots(),
12252 clear_api_key_under_slot_locks,
12253 )
12254}
12255
12256fn clear_api_key_under_slot_locks() -> Result<()> {
12257 let config_path = credential_config_path()
12262 .context("Failed to resolve config path while clearing API keys.")?;
12263
12264 if config_path.exists() {
12265 crate::config_persistence::mutate_config_document(&config_path, |doc| {
12266 crate::config_persistence::remove_document_key_recursive(doc.as_table_mut(), "api_key");
12267 crate::config_persistence::unset_document_value(
12268 doc,
12269 &["providers", "xai", "oauth_credential_generation"],
12270 )?;
12271 crate::config_persistence::unset_document_value(
12272 doc,
12273 &["providers", "xai", "auth_mode"],
12274 )?;
12275 crate::config_persistence::unset_document_value(
12276 doc,
12277 &["providers", "xai", "external_credentials"],
12278 )?;
12279 Ok(())
12280 })
12281 .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
12282 log_sensitive_event(
12283 "credential.clear",
12284 json!({
12285 "backend": "config_file",
12286 "config_path": config_path.display().to_string(),
12287 "scope": "root_and_provider_keys",
12288 }),
12289 );
12290 }
12291
12292 if let Some(secrets) = credential_secret_store() {
12299 let failures = clear_all_provider_api_keys_from_secret_store(secrets);
12300 if !failures.is_empty() {
12301 anyhow::bail!(
12302 "failed to delete stored credentials for: {}",
12303 failures.join(", ")
12304 );
12305 }
12306 }
12307
12308 Ok(())
12309}
12310
12311fn clear_all_provider_api_keys_from_secret_store(
12320 secrets: codewhale_secrets::Secrets,
12321) -> Vec<String> {
12322 let mut failures = Vec::new();
12323 let store = crate::credentials::store::SecretStoreCredentials::new(
12324 secrets.clone(),
12325 known_secret_store_slots(),
12326 );
12327 let stored: Vec<crate::credentials::CredentialInfo> = match store.list() {
12331 Ok(stored) => stored,
12332 Err(error) => {
12333 failures.push(format!("secret store enumeration: {error}"));
12334 return failures;
12335 }
12336 };
12337 for entry in stored {
12338 if let Err(error) = secrets.delete(&entry.provider_id) {
12342 failures.push(format!("{}: {error}", entry.provider_id));
12343 }
12344 }
12345 failures
12346}
12347
12348pub fn clear_active_provider_api_key(provider: &str) -> Result<()> {
12354 if provider == ProviderKind::Xai.as_str() {
12355 return codewhale_config::with_xai_oauth_revocation_transaction(|| {
12356 clear_active_provider_api_key_unlocked(provider)
12357 });
12358 }
12359 clear_active_provider_api_key_unlocked(provider)
12360}
12361
12362fn clear_active_provider_api_key_unlocked(provider: &str) -> Result<()> {
12363 let slot = compatibility_for_id(provider).map(|row| provider_secret_store_slot(row.kind));
12364 match slot {
12365 Some(slot) => crate::credentials::store::with_provider_write_lock(slot, || {
12366 clear_active_provider_api_key_under_lock(provider)
12367 }),
12368 None => clear_active_provider_api_key_under_lock(provider),
12369 }
12370}
12371
12372fn clear_active_provider_api_key_under_lock(provider: &str) -> Result<()> {
12373 let config_path = credential_config_path()
12374 .context("Failed to resolve config path while clearing API keys.")?;
12375
12376 if config_path.exists() {
12377 crate::config_persistence::mutate_config_document_with_migration(
12378 &config_path,
12379 |doc, moved| {
12380 let deepseek_family = provider == ProviderKind::Deepseek.as_str()
12383 || provider == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id;
12384 if deepseek_family || provider == ProviderKind::Custom.as_str() {
12385 crate::config_persistence::unset_document_value(doc, &["api_key"])?;
12386 }
12387 let table = compatibility_for_id(provider).map_or(provider, |row| row.config_key);
12388 let has_own_key = |doc: &toml_edit::DocumentMut| {
12389 [table, provider].iter().any(|key| {
12390 doc.get("providers")
12391 .and_then(|providers| providers.get(key))
12392 .and_then(|entry| entry.get("api_key"))
12393 .and_then(toml_edit::Item::as_str)
12394 .is_some_and(|value| !value.trim().is_empty())
12395 })
12396 };
12397 let clears_shared_deepseek_key = provider
12404 == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id
12405 && (!has_own_key(doc) || moved.moved_root_api_key_to("deepseek"));
12406 crate::config_persistence::unset_document_value(
12407 doc,
12408 &["providers", table, "api_key"],
12409 )?;
12410 if table != provider {
12411 crate::config_persistence::unset_document_value(
12413 doc,
12414 &["providers", provider, "api_key"],
12415 )?;
12416 }
12417 if clears_shared_deepseek_key {
12418 crate::config_persistence::unset_document_value(
12419 doc,
12420 &["providers", "deepseek", "api_key"],
12421 )?;
12422 }
12423 if provider == ProviderKind::Xai.as_str() {
12424 crate::config_persistence::unset_document_value(
12425 doc,
12426 &["providers", "xai", "oauth_credential_generation"],
12427 )?;
12428 crate::config_persistence::unset_document_value(
12429 doc,
12430 &["providers", "xai", "auth_mode"],
12431 )?;
12432 crate::config_persistence::unset_document_value(
12433 doc,
12434 &["providers", "xai", "external_credentials"],
12435 )?;
12436 }
12437 Ok(())
12438 },
12439 )
12440 .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
12441 log_sensitive_event(
12442 "credential.clear",
12443 json!({
12444 "backend": "config_file",
12445 "config_path": config_path.display().to_string(),
12446 "scope": provider,
12447 }),
12448 );
12449 }
12450
12451 if let Some(secrets) = credential_secret_store()
12457 && let Some(slot) = ProviderKind::all()
12458 .iter()
12459 .find(|candidate| candidate.as_str() == provider)
12460 .map(|candidate| provider_secret_store_slot(*candidate))
12461 {
12462 let has_value = secrets
12463 .get(slot)
12464 .ok()
12465 .flatten()
12466 .is_some_and(|value| !value.trim().is_empty());
12467 if has_value {
12468 secrets
12469 .delete(slot)
12470 .with_context(|| format!("failed to delete stored credential for {slot}"))?;
12471 }
12472 }
12473
12474 Ok(())
12475}
12476
12477#[cfg(test)]
12478mod tests;
12479
12480#[cfg(test)]
12481mod model_resolution_golden;
12482
12483#[cfg(test)]
12486mod credential_scope_tests {
12487 use super::*;
12488 use crate::test_support::{EnvVarGuard, lock_test_env};
12489
12490 #[test]
12497 fn api_key_save_rescopes_workspace_config_to_user_global() -> Result<()> {
12498 let _lock = lock_test_env();
12499 let temp = tempfile::tempdir()?;
12500 let workspace = temp.path().join("repo");
12501 fs::create_dir_all(workspace.join(".git"))?;
12502 let project_dir = workspace.join(".codewhale");
12503 fs::create_dir_all(&project_dir)?;
12504 let project_config = project_dir.join("config.toml");
12505 fs::write(&project_config, "approval_policy = \"never\"\n")?;
12506
12507 let user_home = temp.path().join("user-global-home");
12508 let _home = EnvVarGuard::set("CODEWHALE_HOME", user_home.as_os_str());
12509 let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", project_config.as_os_str());
12510 let _legacy_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
12511 let _backend = EnvVarGuard::remove("CODEWHALE_SECRET_BACKEND");
12515 let _legacy_backend = EnvVarGuard::remove("DEEPSEEK_SECRET_BACKEND");
12516
12517 let saved = save_api_key("workspace-rescope-test-key")?;
12518
12519 let global_config = user_home.join("config.toml");
12520 let saved_path = match saved {
12526 SavedCredential::ConfigFile(path) => path,
12527 other => panic!("expected a config-file save, got {}", other.describe()),
12528 };
12529 assert_eq!(
12530 canonicalize_or_keep(&saved_path),
12531 canonicalize_or_keep(&global_config),
12532 "credential save must surface the user-global destination"
12533 );
12534 let global = fs::read_to_string(&global_config)?;
12535 assert!(
12536 global.contains("workspace-rescope-test-key"),
12537 "user-global config must hold the saved key: {global}"
12538 );
12539 let project = fs::read_to_string(&project_config)?;
12540 assert!(
12541 !project.contains("workspace-rescope-test-key"),
12542 "credential leaked into workspace config: {project}"
12543 );
12544 assert!(
12545 !project.contains("api_key"),
12546 "workspace config must stay credential-free: {project}"
12547 );
12548 Ok(())
12549 }
12550
12551 #[test]
12555 fn provider_api_key_save_rescopes_workspace_config_to_user_global() -> Result<()> {
12556 let _lock = lock_test_env();
12557 let temp = tempfile::tempdir()?;
12558 let workspace = temp.path().join("repo");
12559 fs::create_dir_all(workspace.join(".git"))?;
12560 let project_dir = workspace.join(".codewhale");
12561 fs::create_dir_all(&project_dir)?;
12562 let project_config = project_dir.join("config.toml");
12563 fs::write(&project_config, "approval_policy = \"never\"\n")?;
12564
12565 let user_home = temp.path().join("user-global-home");
12566 let _home = EnvVarGuard::set("CODEWHALE_HOME", user_home.as_os_str());
12567 let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", project_config.as_os_str());
12568 let _legacy_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
12569 let _backend = EnvVarGuard::remove("CODEWHALE_SECRET_BACKEND");
12570 let _legacy_backend = EnvVarGuard::remove("DEEPSEEK_SECRET_BACKEND");
12571
12572 let path = save_api_key_for(ProviderKind::Openrouter, "workspace-rescope-openrouter-key")?;
12573
12574 assert_eq!(
12576 canonicalize_or_keep(&path),
12577 canonicalize_or_keep(&user_home.join("config.toml")),
12578 "provider save must report the user-global destination"
12579 );
12580 let global = fs::read_to_string(&path)?;
12581 assert!(global.contains("workspace-rescope-openrouter-key"));
12582 let project = fs::read_to_string(&project_config)?;
12583 assert!(
12584 !project.contains("workspace-rescope-openrouter-key"),
12585 "credential leaked into workspace config: {project}"
12586 );
12587 Ok(())
12588 }
12589
12590 #[test]
12591 fn managed_auto_review_disabled_replaces_user_table_and_refuses_auto_policy() -> Result<()> {
12592 let _lock = lock_test_env();
12593 let temp = tempfile::tempdir()?;
12594 let home = temp.path().join("home");
12595 fs::create_dir_all(&home)?;
12596 let _home = EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str());
12597 let user_config = home.join("config.toml");
12598 let managed_config = temp.path().join("managed.toml");
12599 let _managed =
12600 EnvVarGuard::set("CODEWHALE_MANAGED_CONFIG_PATH", managed_config.as_os_str());
12601 let _policy = EnvVarGuard::remove("CODEWHALE_APPROVAL_POLICY");
12602 let _legacy_policy = EnvVarGuard::remove("DEEPSEEK_APPROVAL_POLICY");
12603
12604 fs::write(
12605 &user_config,
12606 r#"
12607[[auto_review.allow]]
12608tool = "read"
12609reason = "user allow"
12610"#,
12611 )?;
12612 fs::write(
12613 &managed_config,
12614 r#"
12615[auto_review]
12616disabled = true
12617"#,
12618 )?;
12619
12620 let loaded = Config::load(Some(user_config.clone()), None)?;
12621 assert!(loaded.auto_review_disabled());
12622 assert!(
12623 loaded
12624 .auto_review
12625 .as_ref()
12626 .is_some_and(|cfg| cfg.allow.is_empty() && cfg.block.is_empty()),
12627 "managed [auto_review] table must replace the user table"
12628 );
12629
12630 fs::write(&user_config, "approval_policy = \"auto\"\n")?;
12631 let file_err = Config::load(Some(user_config.clone()), None)
12632 .expect_err("approval_policy = auto must fail when auto_review.disabled = true");
12633 assert!(
12634 file_err.to_string().contains("auto_review.disabled = true"),
12635 "unexpected error for config approval_policy: {file_err:#}"
12636 );
12637
12638 fs::write(&user_config, "")?;
12639 let _env_policy = EnvVarGuard::set("CODEWHALE_APPROVAL_POLICY", "auto");
12640 let env_err = Config::load(Some(user_config), None).expect_err(
12641 "CODEWHALE_APPROVAL_POLICY=auto must fail when auto_review.disabled = true",
12642 );
12643 assert!(
12644 env_err.to_string().contains("auto_review.disabled = true"),
12645 "unexpected error for CODEWHALE_APPROVAL_POLICY: {env_err:#}"
12646 );
12647 Ok(())
12648 }
12649
12650 #[test]
12651 fn auto_review_reviewer_model_parses_validates_merges_and_ignores_subagents() -> Result<()> {
12652 let _lock = lock_test_env();
12653 let temp = tempfile::tempdir()?;
12654 let home = temp.path().join("home");
12655 fs::create_dir_all(&home)?;
12656 let _home = EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str());
12657 let _managed = EnvVarGuard::remove("CODEWHALE_MANAGED_CONFIG_PATH");
12658 let user_config = home.join("config.toml");
12659
12660 fs::write(
12661 &user_config,
12662 r#"
12663[auto_review]
12664reviewer_model = "claude-sonnet-5-5"
12665
12666[subagents]
12667reviewer_model = "subagent-only-model"
12668"#,
12669 )?;
12670 let loaded = Config::load(Some(user_config.clone()), None)?;
12671 assert_eq!(
12672 loaded.auto_review_reviewer_model(),
12673 Some("claude-sonnet-5-5")
12674 );
12675
12676 fs::write(
12677 &user_config,
12678 r#"
12679[subagents]
12680reviewer_model = "subagent-only-model"
12681"#,
12682 )?;
12683 let without_ar_model = Config::load(Some(user_config.clone()), None)?;
12684 assert_eq!(without_ar_model.auto_review_reviewer_model(), None);
12685
12686 fs::write(
12687 &user_config,
12688 r#"
12689[auto_review]
12690reviewer_model = " "
12691"#,
12692 )?;
12693 let empty_err = Config::load(Some(user_config.clone()), None)
12694 .expect_err("blank auto_review.reviewer_model must fail validation");
12695 assert!(
12696 empty_err.to_string().contains("reviewer_model"),
12697 "{empty_err:#}"
12698 );
12699
12700 fs::write(
12701 &user_config,
12702 r#"
12703[auto_review]
12704reviewer_model = "bad model\nid"
12705"#,
12706 )?;
12707 let ws_err = Config::load(Some(user_config.clone()), None)
12708 .expect_err("whitespace in auto_review.reviewer_model must fail validation");
12709 assert!(ws_err.to_string().contains("reviewer_model"), "{ws_err:#}");
12710
12711 fs::write(
12712 &user_config,
12713 r#"
12714[auto_review]
12715reviewer_model = "gpt-5.5"
12716
12717[profiles.fast]
12718[profiles.fast.auto_review]
12719reviewer_model = "gpt-5.6"
12720"#,
12721 )?;
12722 let profiled = Config::load(Some(user_config.clone()), Some("fast"))?;
12723 assert_eq!(profiled.auto_review_reviewer_model(), Some("gpt-5.6"));
12724
12725 let managed_config = temp.path().join("managed.toml");
12726 let _managed_set =
12727 EnvVarGuard::set("CODEWHALE_MANAGED_CONFIG_PATH", managed_config.as_os_str());
12728 fs::write(
12729 &managed_config,
12730 r#"
12731[auto_review]
12732reviewer_model = "managed-reviewer"
12733"#,
12734 )?;
12735 let managed_loaded = Config::load(Some(user_config.clone()), Some("fast"))?;
12736 assert_eq!(
12737 managed_loaded.auto_review_reviewer_model(),
12738 Some("managed-reviewer")
12739 );
12740 drop(_managed_set);
12741 let _ = fs::remove_file(&managed_config);
12742
12743 fs::write(
12744 &user_config,
12745 r#"
12746[auto_review]
12747environment = [
12748 "trusted git remote: origin = https://github.com/org/repo",
12749 "trusted staging host: https://staging.example.internal",
12750]
12751"#,
12752 )?;
12753 let env_loaded = Config::load(Some(user_config.clone()), None)?;
12754 assert_eq!(
12755 env_loaded.auto_review_environment(),
12756 &[
12757 "trusted git remote: origin = https://github.com/org/repo".to_string(),
12758 "trusted staging host: https://staging.example.internal".to_string(),
12759 ]
12760 );
12761
12762 fs::write(
12763 &user_config,
12764 r#"
12765[auto_review]
12766environment = [" "]
12767"#,
12768 )?;
12769 let blank_env_err = Config::load(Some(user_config.clone()), None)
12770 .expect_err("blank auto_review.environment entry must fail validation");
12771 assert!(
12772 blank_env_err
12773 .to_string()
12774 .contains("auto_review.environment"),
12775 "{blank_env_err:#}"
12776 );
12777
12778 fs::write(
12779 &user_config,
12780 r#"
12781[auto_review]
12782environment = ["bad\nline"]
12783"#,
12784 )?;
12785 let control_env_err = Config::load(Some(user_config.clone()), None)
12786 .expect_err("control chars in auto_review.environment must fail validation");
12787 assert!(
12788 control_env_err
12789 .to_string()
12790 .contains("auto_review.environment"),
12791 "{control_env_err:#}"
12792 );
12793
12794 fs::write(
12795 &user_config,
12796 r#"
12797[auto_review]
12798environment = ["user remote: github.com/acme/repo"]
12799"#,
12800 )?;
12801 let _managed_env_set =
12802 EnvVarGuard::set("CODEWHALE_MANAGED_CONFIG_PATH", managed_config.as_os_str());
12803 fs::write(
12804 &managed_config,
12805 r#"
12806[auto_review]
12807environment = ["managed remote: github.internal/corp/repo"]
12808"#,
12809 )?;
12810 let managed_env = Config::load(Some(user_config), None)?;
12811 assert_eq!(
12812 managed_env.auto_review_environment(),
12813 &["managed remote: github.internal/corp/repo".to_string()]
12814 );
12815
12816 let review_shell_dir = tempfile::tempdir()?;
12817 let review_shell_user = review_shell_dir.path().join("config.toml");
12818 let review_shell_managed = review_shell_dir.path().join("managed.toml");
12819 let _managed_unset = EnvVarGuard::remove("CODEWHALE_MANAGED_CONFIG_PATH");
12820 fs::write(
12821 &review_shell_user,
12822 r#"
12823[auto_review]
12824review_all_shell = true
12825"#,
12826 )?;
12827 let default_cfg = Config::default();
12828 assert!(!default_cfg.auto_review_review_all_shell());
12829 let loaded_review_shell = Config::load(Some(review_shell_user.clone()), None)?;
12830 assert!(loaded_review_shell.auto_review_review_all_shell());
12831
12832 let _managed_override = EnvVarGuard::set(
12833 "CODEWHALE_MANAGED_CONFIG_PATH",
12834 review_shell_managed.as_os_str(),
12835 );
12836 fs::write(
12837 &review_shell_managed,
12838 r#"
12839[auto_review]
12840review_all_shell = false
12841"#,
12842 )?;
12843 let managed_override_cfg = Config::load(Some(review_shell_user), None)?;
12844 assert!(!managed_override_cfg.auto_review_review_all_shell());
12845 Ok(())
12846 }
12847}
12848
12849#[cfg(any(test, feature = "test-support"))]
12850pub mod test_support;