use codewhale_config::extension_host::{ExtensionHostConfig, PluginSettings};
use codewhale_config::opencode_go_models;
use codewhale_config::provider_preserves_custom_base_url_model;
use codewhale_config::{
base_url_host, default_snapshots_enabled, resolve_xiaomi_mimo_base_url,
xiaomi_mimo_base_url_for_mode, xiaomi_mimo_mode_uses_standard_endpoint,
};
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::SystemTime;
use anyhow::{Context, Result};
use codewhale_execpolicy::ExecPolicyEngine;
use codewhale_localization::{Locale, MessageId, tr};
use serde::{Deserialize, Serialize};
use serde_json::json;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use crate::audit::log_sensitive_event;
use crate::credentials::CredentialStore;
use crate::features::{Feature, Features, FeaturesToml, is_known_feature_key};
use codewhale_config::hooks::HooksConfig;
mod credential_resolve;
pub use credential_resolve::resolve_credential_source;
mod subagent_limits;
pub use subagent_limits::*;
use subagent_limits::{resolve_subagent_api_timeout_secs, resolve_subagent_heartbeat_timeout_secs};
pub const XIAOMI_MIMO_PAY_AS_YOU_GO_BASE_URL: &str = "https://api.xiaomimimo.com/v1";
pub const XIAOMI_MIMO_TOKEN_PLAN_CN_BASE_URL: &str = "https://token-plan-cn.xiaomimimo.com/v1";
pub const XIAOMI_MIMO_TOKEN_PLAN_SGP_BASE_URL: &str = DEFAULT_XIAOMI_MIMO_BASE_URL;
pub const XIAOMI_MIMO_TOKEN_PLAN_AMS_BASE_URL: &str = "https://token-plan-ams.xiaomimimo.com/v1";
pub const KIMI_CODE_MEMBERSHIP_PLAN_CONSOLE_URL: &str =
codewhale_config::provider::KIMI_CODE_MEMBERSHIP_PLAN_CONSOLE_URL;
#[must_use]
pub fn is_unresolved_local_ollama_model(model: &str) -> bool {
model.trim().eq_ignore_ascii_case(DEFAULT_OLLAMA_MODEL)
}
pub const OPENAI_CODEX_EFFECTIVE_CONTEXT_WINDOW_TOKENS: u32 = 128_000;
#[cfg(test)]
use codewhale_config::API_KEYRING_SENTINEL;
use codewhale_config::{ConfigApiKeyValueKind, classify_config_api_key_value};
pub const DEFAULT_ZAI_PROVIDER_MAX_CONCURRENCY: usize = 3;
pub const MAX_PROVIDER_REQUEST_CONCURRENCY: usize = 64;
pub const DEFAULT_REASONING_ONLY_REPROMPTS: u32 = 2;
pub const DEFAULT_REASONING_ONLY_REPROMPT_MESSAGE: &str =
"Continue: give your answer, or make the next tool call.";
pub fn default_stop_words() -> Vec<String> {
["stop", "wait", "pause"]
.into_iter()
.map(str::to_string)
.collect()
}
use codewhale_config::ProviderKind;
use codewhale_config::catalog::reviewed::constants::*;
use codewhale_config::descriptors::defaults::*;
use codewhale_config::descriptors::{compatibility_for_id, compatibility_for_selector};
use codewhale_config::route::ProviderId;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProviderIdentity {
pub provider: ProviderKind,
pub key: ProviderId,
pub(crate) exact_id: Option<ProviderId>,
pub(crate) migrated_legacy_ollama_cloud_route: bool,
pub(crate) legacy_root_custom_generation:
Option<codewhale_config::credentials::CredentialGeneration>,
}
impl ProviderIdentity {
pub fn migrated_legacy_ollama_cloud_route(&self) -> bool {
self.migrated_legacy_ollama_cloud_route
}
#[cfg(any(test, feature = "test-support"))]
pub fn test_exact_identity(provider: ProviderKind, key: impl Into<String>) -> Self {
let key = ProviderId::from(key.into());
Self {
provider,
exact_id: Some(key.clone()),
key,
migrated_legacy_ollama_cloud_route: false,
legacy_root_custom_generation: None,
}
}
}
impl std::hash::Hash for ProviderIdentity {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::hash::Hash::hash(&self.key, state);
}
}
pub fn is_legacy_antigravity_identity(value: &str) -> bool {
codewhale_config::ProviderKind::parse_config_identity(value)
== Some(codewhale_config::ProviderKind::Antigravity)
}
impl ProviderIdentity {
#[must_use]
pub fn persisted_id(&self) -> Option<&str> {
self.exact_id.as_ref().map(ProviderId::as_str)
}
pub fn persisted_kind(&self) -> &str {
if self.provider == ProviderKind::Deepseek
&& self.key.as_str() == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id
{
self.key.as_str()
} else {
self.provider.as_str()
}
}
pub fn config_table_key(&self) -> Result<&str> {
if self.provider == ProviderKind::Custom {
return Ok(self.key.as_str());
}
if self.migrated_legacy_ollama_cloud_route {
return Ok(ProviderKind::Ollama.as_str());
}
self.compatibility()
.map(|row| row.config_key)
.context("provider config metadata")
}
pub fn compatibility(
&self,
) -> Option<&'static codewhale_config::descriptors::ProviderCompatibility> {
if self.provider == ProviderKind::Custom {
return None;
}
compatibility_for_id(self.key.as_str()).filter(|row| row.kind == self.provider)
}
}
fn normalize_subagent_provider_key(value: &str) -> String {
value
.trim()
.to_ascii_lowercase()
.chars()
.map(|ch| match ch {
'-' | '_' | '.' | ' ' => '_',
other => other,
})
.collect()
}
pub const DEEPSEEK_ALIAS_RETIREMENT_DATE: &str = "2026-07-24";
pub const DEEPSEEK_ALIAS_RETIREMENT_UTC: &str = "2026-07-24T15:59:00Z";
use codewhale_config::catalog::reviewed::constants::DEEPSEEK_ALIAS_REPLACEMENT;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct ModelAliasDeprecation {
pub alias: String,
pub replacement: String,
pub retirement_date: String,
pub retirement_utc: String,
pub notice: String,
}
pub fn configured_model_for_route<'a>(
config: &'a Config,
provider: ProviderKind,
identity: &str,
base_url: &str,
model: &str,
) -> Option<&'a codewhale_config::catalog::configured::ConfiguredModel> {
if provider == ProviderKind::OpenaiCodex {
return None;
}
let models = config.custom_models.as_deref()?;
codewhale_config::catalog::configured::validate_configured_models(models).ok()?;
models
.iter()
.find(|row| row.id == model && row.matches_route(identity, base_url))
}
pub fn deepseek_alias_deprecation(model_lower: &str) -> Option<ModelAliasDeprecation> {
match model_lower {
"deepseek-chat" | "deepseek-reasoner" => Some(ModelAliasDeprecation {
alias: model_lower.to_string(),
replacement: DEEPSEEK_ALIAS_REPLACEMENT.to_string(),
retirement_date: DEEPSEEK_ALIAS_RETIREMENT_DATE.to_string(),
retirement_utc: DEEPSEEK_ALIAS_RETIREMENT_UTC.to_string(),
notice: format!(
"DeepSeek retired {model_lower} on {DEEPSEEK_ALIAS_RETIREMENT_DATE}; Codewhale sends {DEEPSEEK_ALIAS_REPLACEMENT} instead."
),
}),
_ => None,
}
}
#[must_use]
pub fn normalize_custom_model_id(model: &str) -> Option<String> {
let trimmed = model.trim();
if trimmed.is_empty() || trimmed.chars().any(char::is_control) {
None
} else {
Some(trimmed.to_string())
}
}
pub fn validate_route(provider: ProviderKind, model: &str) -> Result<(), String> {
let trimmed = model.trim();
if trimmed.is_empty() {
return Err(format!(
"No model selected for provider '{}'.",
provider.as_str()
));
}
if trimmed.eq_ignore_ascii_case("auto") {
return Ok(());
}
if provider == ProviderKind::OpencodeGo {
return if opencode_go_model_id(trimmed).is_some() {
Ok(())
} else {
Err(format!(
"Model '{trimmed}' is not in OpenCode Go's documented protocol roster. \
Choose one of: {}.",
opencode_go_models().join(", ")
))
};
}
if codewhale_config::descriptors::provider_passes_model_through(provider) {
return Ok(());
}
if matches!(provider, ProviderKind::Deepseek) {
if codewhale_config::route::resolve_model(ProviderKind::Deepseek, trimmed, None).is_ok() {
return Ok(());
}
return Err(format!(
"Model '{trimmed}' is not a DeepSeek model, but the active provider is '{}'. \
Use a DeepSeek model id (for example {}) or switch providers together with the model.",
provider.as_str(),
COMMON_DEEPSEEK_MODELS.join(", ")
));
}
if root_deepseek_model_is_foreign_to_direct_provider(provider, trimmed) {
return Err(format!(
"Model '{trimmed}' is a DeepSeek model and is not compatible with provider '{}'. \
Switch the provider and model together, or pick a model this provider serves.",
provider.as_str()
));
}
Ok(())
}
fn legacy_deepseek_alias_reasoning_effort(model: &str) -> Option<&'static str> {
codewhale_config::legacy_deepseek_alias_reasoning_effort(model)
}
pub fn opencode_go_model_id(model: &str) -> Option<&'static str> {
codewhale_config::opencode_go_model_id(model)
}
#[must_use]
pub(crate) fn prefer_configured_model_spelling(configured: &str, remembered: String) -> String {
let configured = configured.trim();
if remembered != configured && remembered.eq_ignore_ascii_case(configured) {
return configured.to_string();
}
remembered
}
pub fn legacy_deepseek_alias_effort_for_route(
provider: ProviderKind,
base_url: &str,
model: &str,
) -> Option<&'static str> {
if !matches!(
provider,
ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
) {
return None;
}
let effort = legacy_deepseek_alias_reasoning_effort(model)?;
codewhale_config::route::resolve_model(provider, model, Some(base_url))
.is_ok_and(|resolved| resolved.wire_id != model.trim())
.then_some(effort)
}
#[must_use]
pub fn model_completion_names_for_provider(provider: ProviderKind) -> Vec<&'static str> {
codewhale_config::catalog::reviewed::constants::completion_names(provider.as_str()).to_vec()
}
pub fn read_plugin_settings(
path: &Path,
) -> std::result::Result<BTreeMap<String, PluginSettings>, String> {
let contents = match fs::read_to_string(path) {
Ok(contents) => contents,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
Err(error) => return Err(format!("cannot read {}: {error}", path.display())),
};
parse_config_file(&contents)
.map(|file| file.base.plugins.unwrap_or_default())
.map_err(|_| format!("cannot parse {}", path.display()))
}
#[derive(Debug, Clone, serde::Serialize, Deserialize)]
#[serde(try_from = "RawRateLimitRetryPolicy")]
pub struct RateLimitRetryPolicy {
pub max_attempts: u32,
pub recovery_budget_secs: u64,
pub initial_delay_secs: u64,
pub max_delay_secs: u64,
}
impl Default for RateLimitRetryPolicy {
fn default() -> Self {
Self {
max_attempts: 20,
recovery_budget_secs: 600,
initial_delay_secs: 5,
max_delay_secs: 60,
}
}
}
#[derive(Deserialize)]
#[serde(default)]
struct RawRateLimitRetryPolicy {
max_attempts: u32,
recovery_budget_secs: u64,
initial_delay_secs: u64,
max_delay_secs: u64,
}
impl Default for RawRateLimitRetryPolicy {
fn default() -> Self {
let p = RateLimitRetryPolicy::default();
Self {
max_attempts: p.max_attempts,
recovery_budget_secs: p.recovery_budget_secs,
initial_delay_secs: p.initial_delay_secs,
max_delay_secs: p.max_delay_secs,
}
}
}
impl TryFrom<RawRateLimitRetryPolicy> for RateLimitRetryPolicy {
type Error = String;
fn try_from(p: RawRateLimitRetryPolicy) -> Result<Self, Self::Error> {
if !(1..=1000).contains(&p.max_attempts)
|| !(1..=86400).contains(&p.recovery_budget_secs)
|| p.initial_delay_secs == 0
|| p.initial_delay_secs > p.max_delay_secs
|| p.max_delay_secs > 86400
{
return Err("invalid retry.rate_limit policy: attempts 1..1000, budget 1..86400s, 1 <= initial <= max <= 86400s".into());
}
Ok(Self {
max_attempts: p.max_attempts,
recovery_budget_secs: p.recovery_budget_secs,
initial_delay_secs: p.initial_delay_secs,
max_delay_secs: p.max_delay_secs,
})
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct RetryConfig {
#[serde(default)]
pub rate_limit: RateLimitRetryPolicy,
pub enabled: Option<bool>,
pub max_retries: Option<u32>,
pub initial_delay: Option<f64>,
pub max_delay: Option<f64>,
pub exponential_base: Option<f64>,
#[serde(default)]
pub jitter: Option<bool>,
#[serde(default)]
pub jitter_factor: Option<f64>,
#[serde(default)]
pub respect_retry_after: Option<bool>,
}
fn deser_status_items<'de, D>(deserializer: D) -> Result<Option<Vec<StatusItem>>, D::Error>
where
D: serde::Deserializer<'de>,
{
let raw: Option<Vec<String>> = Option::deserialize(deserializer)?;
Ok(raw.map(|strings| {
strings
.into_iter()
.filter_map(|s| {
StatusItem::from_key(&s).or_else(|| {
tracing::warn!("ignoring unknown status item {s:?} in config");
None
})
})
.collect()
}))
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct StreamConfig {
pub open_timeout_secs: Option<u64>,
pub chunk_timeout_secs: Option<u64>,
pub force_http1: Option<bool>,
pub max_resumes: Option<u32>,
pub max_transparent_retries: Option<u32>,
pub max_stream_errors: Option<u32>,
pub max_duration_secs: Option<u64>,
pub max_content_mb: Option<u64>,
pub connect_timeout_secs: Option<u64>,
pub tcp_keepalive_secs: Option<u64>,
pub http2_keep_alive_interval_secs: Option<u64>,
pub http2_keep_alive_timeout_secs: Option<u64>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RouteProvenance {
pub provider_from_saved_selection: bool,
pub model_from_saved_selection: bool,
pub provider_from_profile: bool,
pub model_from_profile: bool,
pub provider_from_env: bool,
pub provider_from_managed: bool,
pub model_from_managed: bool,
}
#[derive(Debug, Clone, Deserialize, Default)]
pub struct TuiConfig {
pub alternate_screen: Option<String>,
pub mouse_capture: Option<bool>,
pub selection_copy_markdown: Option<bool>,
pub stream_chunk_timeout_secs: Option<u64>,
pub max_model_steps: Option<u32>,
pub turn_wall_clock_secs: Option<u64>,
pub stream_max_content_mb: Option<u64>,
pub stream_max_duration_secs: Option<u64>,
pub stream_max_resumes: Option<u32>,
pub stream_max_transparent_retries: Option<u32>,
pub stream_max_errors: Option<u32>,
pub stream_open_timeout_secs: Option<u64>,
pub connect_timeout_secs: Option<u64>,
pub force_http1: Option<bool>,
#[serde(default, deserialize_with = "deser_status_items")]
pub status_items: Option<Vec<StatusItem>>,
#[serde(default)]
pub posture_bar: Option<ChromeRowPreset>,
#[serde(default)]
pub metrics_line: Option<ChromeRowPreset>,
pub osc8_links: Option<bool>,
pub notification_condition: Option<NotificationCondition>,
#[serde(default)]
pub composer_arrows_scroll: Option<bool>,
}
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ChromeRowPreset {
#[default]
Full,
Compact,
Hidden,
}
impl ChromeRowPreset {
pub const SETTINGS: [&'static str; 3] = ["full", "compact", "hidden"];
#[must_use]
pub const fn as_setting(self) -> &'static str {
match self {
Self::Full => "full",
Self::Compact => "compact",
Self::Hidden => "hidden",
}
}
#[must_use]
pub fn from_setting(value: &str) -> Option<Self> {
match value.trim().to_ascii_lowercase().as_str() {
"full" => Some(Self::Full),
"compact" => Some(Self::Compact),
"hidden" => Some(Self::Hidden),
_ => None,
}
}
}
#[cfg(test)]
use codewhale_config::notifications::{EventSoundConfig, NotificationEventsConfig};
#[cfg(test)]
use codewhale_config::notifications::{
CompletionSound, NotificationConfigUpdate, NotificationMethod,
};
use codewhale_config::notifications::{NotificationCondition, NotificationsConfig};
fn default_snapshot_max_age_days() -> u64 {
codewhale_config::DEFAULT_SNAPSHOT_MAX_AGE.as_secs() / (24 * 60 * 60)
}
fn default_snapshot_max_workspace_gb() -> u64 {
codewhale_config::DEFAULT_MAX_WORKSPACE_BYTES_FOR_SNAPSHOT / (1024 * 1024 * 1024)
}
#[derive(Debug, Clone, Deserialize)]
pub struct SnapshotsConfig {
#[serde(default = "default_snapshots_enabled")]
pub enabled: bool,
#[serde(default = "default_snapshot_max_age_days")]
pub max_age_days: u64,
#[serde(default = "default_snapshot_max_workspace_gb")]
pub max_workspace_gb: u64,
}
impl Default for SnapshotsConfig {
fn default() -> Self {
Self {
enabled: default_snapshots_enabled(),
max_age_days: default_snapshot_max_age_days(),
max_workspace_gb: default_snapshot_max_workspace_gb(),
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MemoryBackend {
Native,
#[default]
Off,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct MemoryConfig {
#[serde(default)]
pub enabled: Option<bool>,
#[serde(default)]
pub backend: Option<MemoryBackend>,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct SpeechConfig {
#[serde(default)]
pub output_dir: Option<String>,
}
impl SnapshotsConfig {
#[must_use]
pub fn max_age(&self) -> std::time::Duration {
std::time::Duration::from_secs(self.max_age_days.saturating_mul(24 * 60 * 60))
}
}
mod search;
pub use search::*;
#[derive(Debug, Clone, Deserialize, Default)]
pub struct ToolsConfig {
#[serde(default)]
pub always_load: Vec<String>,
#[serde(default)]
pub plugin_dir: Option<String>,
#[serde(default)]
pub overrides: Option<HashMap<String, ToolOverride>>,
#[serde(default)]
pub user_input_max_questions: Option<u32>,
#[serde(default)]
pub user_input_max_options: Option<u32>,
#[serde(default)]
pub user_input_timeout_seconds: Option<u64>,
#[serde(default)]
pub task_human_wait_cap_seconds: Option<u64>,
#[serde(default)]
pub max_parallel_shell_exec: Option<usize>,
}
#[derive(Debug, Clone, Copy, Deserialize, Default, PartialEq, Eq)]
pub struct GoalConfig {
#[serde(default)]
pub max_continuations: Option<u32>,
#[serde(default)]
pub max_steps: Option<u32>,
#[serde(default)]
pub continuation_delay_seconds: Option<u64>,
#[serde(default)]
pub enforce_token_budget: Option<bool>,
#[serde(default)]
pub complete_judge: Option<bool>,
#[serde(default)]
pub blocked_judge: Option<bool>,
}
#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
#[serde(default)]
pub struct ReasoningOnlyConfig {
pub on_output_limit: bool,
pub max_reprompts: Option<u32>,
pub reprompt_message: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Hash)]
#[serde(rename_all = "snake_case")]
pub enum StatusItem {
Mode,
Model,
Cost,
Cache,
ContextPercent,
Tokens,
Balance,
SessionMetrics,
Ttft,
OutputRate,
Workspace,
GitBranch,
}
impl StatusItem {
#[must_use]
pub fn default_footer() -> Vec<StatusItem> {
vec![
StatusItem::Mode,
StatusItem::Model,
StatusItem::ContextPercent,
StatusItem::Cost,
StatusItem::Cache,
StatusItem::Tokens,
StatusItem::Ttft,
StatusItem::OutputRate,
]
}
#[must_use]
pub fn key(self) -> &'static str {
match self {
StatusItem::Mode => "mode",
StatusItem::Model => "model",
StatusItem::Cost => "cost",
StatusItem::Cache => "cache",
StatusItem::ContextPercent => "context_percent",
StatusItem::Tokens => "tokens",
StatusItem::Balance => "balance",
StatusItem::SessionMetrics => "session_metrics",
StatusItem::Ttft => "ttft",
StatusItem::OutputRate => "output_rate",
StatusItem::Workspace => "workspace",
StatusItem::GitBranch => "git_branch",
}
}
#[must_use]
pub fn from_key(key: &str) -> Option<Self> {
match key {
"mode" => Some(Self::Mode),
"model" => Some(Self::Model),
"cost" => Some(Self::Cost),
"cache" => Some(Self::Cache),
"context_percent" => Some(Self::ContextPercent),
"tokens" => Some(Self::Tokens),
"status" | "agents" | "reasoning_replay" | "prefix_stability" | "last_tool_elapsed"
| "rate_limit" => None,
"balance" => Some(Self::Balance),
"session_metrics" => Some(Self::SessionMetrics),
"ttft" => Some(Self::Ttft),
"output_rate" => Some(Self::OutputRate),
"workspace" => Some(Self::Workspace),
"git_branch" => Some(Self::GitBranch),
_ => None,
}
}
#[must_use]
pub fn label(self) -> &'static str {
match self {
StatusItem::Mode => "Mode",
StatusItem::Model => "Model",
StatusItem::Cost => "Session cost",
StatusItem::Cache => "Prompt cache hit rate",
StatusItem::ContextPercent => "Context window %",
StatusItem::Tokens => "Output tokens",
StatusItem::Balance => "Account balance",
StatusItem::SessionMetrics => "Session metrics",
StatusItem::Ttft => "Time to first token",
StatusItem::OutputRate => "Output rate",
StatusItem::Workspace => "Workspace",
StatusItem::GitBranch => "Git branch",
}
}
#[must_use]
pub fn hint(self, locale: Locale) -> Cow<'static, str> {
tr(
locale,
match self {
StatusItem::Mode => MessageId::StatusPickerModeHint,
StatusItem::Model => MessageId::StatusPickerModelHint,
StatusItem::Cost => MessageId::StatusPickerCostHint,
StatusItem::Cache => MessageId::StatusPickerCacheHint,
StatusItem::ContextPercent => MessageId::StatusPickerContextPercentHint,
StatusItem::Tokens => MessageId::StatusPickerTokensHint,
StatusItem::Balance => MessageId::StatusPickerBalanceHint,
StatusItem::SessionMetrics => MessageId::StatusPickerSessionMetricsHint,
StatusItem::Ttft => MessageId::StatusPickerTtftHint,
StatusItem::OutputRate => MessageId::StatusPickerOutputRateHint,
StatusItem::Workspace => MessageId::StatusPickerWorkspaceHint,
StatusItem::GitBranch => MessageId::StatusPickerGitBranchHint,
},
)
}
#[must_use]
pub fn all() -> &'static [StatusItem] {
&[
StatusItem::Mode,
StatusItem::Model,
StatusItem::ContextPercent,
StatusItem::Cost,
StatusItem::Balance,
StatusItem::Cache,
StatusItem::Tokens,
StatusItem::Ttft,
StatusItem::OutputRate,
StatusItem::Workspace,
StatusItem::GitBranch,
]
}
#[must_use]
pub fn is_available_for(self, provider: ProviderKind) -> bool {
match self {
StatusItem::Balance => provider_has_balance_api(provider),
_ => true,
}
}
}
#[must_use]
pub fn provider_has_balance_api(provider: ProviderKind) -> bool {
matches!(
provider,
ProviderKind::Deepseek
| ProviderKind::Openrouter
| ProviderKind::Siliconflow
| ProviderKind::SiliconflowCN
)
}
#[derive(Debug, Clone)]
pub struct RetryPolicy {
pub rate_limit: RateLimitRetryPolicy,
pub enabled: bool,
pub max_retries: u32,
pub initial_delay: f64,
pub max_delay: f64,
pub exponential_base: f64,
pub jitter: bool,
pub jitter_factor: f64,
pub respect_retry_after: bool,
}
#[derive(Debug, Clone, Deserialize, Default)]
pub struct ContextConfig {
#[serde(default)]
pub project_pack: Option<bool>,
}
pub const COMPACTION_SUMMARY_INSTRUCTIONS_MAX_CHARS: usize = 4_000;
pub const DEFAULT_COMPACTION_RETAINED_USER_MESSAGE_TOKENS: usize = 20_000;
pub const MIN_COMPACTION_RETAINED_USER_MESSAGE_TOKENS: usize = 2_000;
pub const MAX_COMPACTION_RETAINED_USER_MESSAGE_TOKENS: usize = 200_000;
#[derive(Debug, Clone, Deserialize, Default)]
pub struct CompactionSettings {
#[serde(default)]
pub summary_instructions: Option<String>,
#[serde(default, alias = "retained_user_message_max_tokens")]
pub retained_user_message_tokens: Option<usize>,
}
#[derive(Debug, Clone, Deserialize, Default)]
pub struct SubagentsConfig {
#[serde(default)]
pub enabled: Option<bool>,
#[serde(default)]
pub default_model: Option<String>,
#[serde(default)]
pub worker_model: Option<String>,
#[serde(default, rename = "scout_model", alias = "explorer_model")]
pub explorer_model: Option<String>,
#[serde(default, rename = "planner_model", alias = "awaiter_model")]
pub awaiter_model: Option<String>,
#[serde(default, rename = "reviewer_model", alias = "review_model")]
pub review_model: Option<String>,
#[serde(default)]
pub custom_model: Option<String>,
#[serde(default)]
pub models: Option<HashMap<String, String>>,
#[serde(default)]
pub roles: Option<HashMap<String, SubagentRoleConfig>>,
#[serde(default)]
pub max_concurrent: Option<usize>,
#[serde(default)]
pub max_depth: Option<u32>,
#[serde(default)]
pub launch_concurrency: Option<usize>,
#[serde(default, alias = "max_total", alias = "admission_limit")]
pub max_admitted: Option<usize>,
#[serde(default, rename = "interactive_max_launch")]
pub interactive_max_launch_legacy: Option<usize>,
#[serde(default)]
pub api_timeout_secs: Option<u64>,
#[serde(default)]
pub heartbeat_timeout_secs: Option<u64>,
#[serde(default)]
pub default_max_steps: Option<u32>,
#[serde(default)]
pub default_wall_time_secs: Option<u64>,
#[serde(default)]
pub providers: Option<HashMap<String, SubagentProviderConfig>>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SubagentRoleConfig {
pub model: String,
#[serde(default)]
pub replacements: Vec<String>,
}
fn parse_subagent_role_pin(value: &str) -> SubagentModelOverride {
let value = value.trim();
match value.split_once('/') {
Some((provider, model)) => SubagentModelOverride {
provider: Some(provider.trim().to_string()),
model: model.trim().to_string(),
},
None => value.into(),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SubagentModelOverride {
pub provider: Option<String>,
pub model: String,
}
impl From<String> for SubagentModelOverride {
fn from(model: String) -> Self {
Self {
provider: None,
model,
}
}
}
impl From<&str> for SubagentModelOverride {
fn from(model: &str) -> Self {
model.to_string().into()
}
}
#[derive(Debug, Clone, Deserialize, Default)]
pub struct SubagentProviderConfig {
#[serde(default)]
pub enabled: Option<bool>,
#[serde(default)]
pub max_concurrent: Option<usize>,
#[serde(default)]
pub max_depth: Option<u32>,
#[serde(default)]
pub launch_concurrency: Option<usize>,
#[serde(default, alias = "max_total", alias = "admission_limit")]
pub max_admitted: Option<usize>,
#[serde(default)]
pub api_timeout_secs: Option<u64>,
#[serde(default)]
pub heartbeat_timeout_secs: Option<u64>,
}
#[derive(Debug, Clone, Deserialize, Default)]
pub struct AutoConfig {
#[serde(default)]
pub cost_saving: Option<bool>,
#[serde(default)]
pub cross_provider: Option<bool>,
#[serde(default)]
pub router: Option<AutoRouterConfig>,
}
pub(crate) const DEFAULT_AUTO_ROUTER_TIMEOUT_SECS: u64 = 4;
pub const MAX_AUTO_ROUTER_TIMEOUT_SECS: u64 = 300;
#[derive(Debug, Clone, Default, Deserialize)]
pub struct AutoRouterConfig {
#[serde(default)]
pub provider: Option<String>,
#[serde(default)]
pub model: Option<String>,
#[serde(default)]
pub thinking: Option<String>,
#[serde(default)]
pub timeout_secs: Option<u64>,
#[serde(default)]
pub kind: Option<String>,
#[serde(default)]
pub min_confidence: Option<f64>,
#[serde(default)]
pub base_url: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AutoRouterKind {
Chat,
Decision,
}
impl AutoRouterKind {
#[must_use]
pub fn parse(raw: Option<&str>) -> Option<Self> {
match raw.map(str::trim).filter(|kind| !kind.is_empty()) {
None => Some(Self::Chat),
Some(kind) if kind.eq_ignore_ascii_case("chat") => Some(Self::Chat),
Some(kind) if kind.eq_ignore_ascii_case("decision") => Some(Self::Decision),
Some(_) => None,
}
}
}
pub const DEFAULT_AUTO_ROUTER_MIN_CONFIDENCE: f64 = 0.5;
fn default_update_check_for_updates() -> bool {
true
}
fn default_update_check_interval_hours() -> u64 {
codewhale_release::check::DEFAULT_CHECK_INTERVAL_HOURS
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct UpdateConfig {
#[serde(default = "default_update_check_for_updates")]
pub check_for_updates: bool,
#[serde(default = "default_update_check_interval_hours")]
pub check_interval_hours: u64,
#[serde(default)]
pub update_uri: Option<String>,
#[serde(default = "default_update_show_whats_new")]
pub show_whats_new: bool,
#[serde(default)]
pub mode: Option<String>,
}
fn default_update_show_whats_new() -> bool {
true
}
impl Default for UpdateConfig {
fn default() -> Self {
Self {
check_for_updates: true,
check_interval_hours: default_update_check_interval_hours(),
update_uri: None,
show_whats_new: true,
mode: None,
}
}
}
impl UpdateConfig {
#[must_use]
pub fn update_uri(&self) -> Option<&str> {
self.update_uri
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
}
}
fn default_cloud_facts_channel() -> String {
"stable".to_string()
}
fn default_cloud_facts_ttl_hours() -> u64 {
codewhale_cloud_facts::DEFAULT_TTL_SECS / 3600
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct CloudFactsConfig {
#[serde(default)]
pub enabled: bool,
#[serde(default = "default_cloud_facts_channel")]
pub channel: String,
#[serde(default)]
pub url: Option<String>,
#[serde(default = "default_cloud_facts_ttl_hours")]
pub ttl_hours: u64,
}
impl Default for CloudFactsConfig {
fn default() -> Self {
Self {
enabled: false,
channel: default_cloud_facts_channel(),
url: None,
ttl_hours: default_cloud_facts_ttl_hours(),
}
}
}
impl CloudFactsConfig {
#[must_use]
pub fn settings(&self) -> codewhale_cloud_facts::Settings {
let channel = self.channel.trim();
codewhale_cloud_facts::Settings {
enabled: self.enabled,
channel: if codewhale_cloud_facts::valid_channel(channel) {
channel.to_string()
} else {
default_cloud_facts_channel()
},
url: self
.url
.as_deref()
.map(str::trim)
.filter(|u| !u.is_empty())
.map(str::to_string),
ttl_secs: self.ttl_hours.max(1).saturating_mul(3600),
..codewhale_cloud_facts::Settings::default()
}
.resolve()
}
}
#[derive(Debug, Clone, Copy, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalDefaultSelection {
#[default]
Deny,
AllowOnce,
}
#[derive(Debug, Clone, Copy, Deserialize, Default, PartialEq, Eq)]
pub struct ApprovalConfig {
#[serde(default)]
pub default_selection: ApprovalDefaultSelection,
#[serde(default)]
pub timeout_seconds: Option<u64>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum RawProseMeasure {
Integer(i64),
Float(f64),
Boolean(bool),
Text(String),
}
impl RawProseMeasure {
fn describe(&self) -> String {
match self {
Self::Integer(value) => value.to_string(),
Self::Float(value) => value.to_string(),
Self::Boolean(value) => value.to_string(),
Self::Text(value) => format!("'{value}'"),
}
}
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TranscriptConfig {
#[serde(default)]
pub prose_measure: Option<RawProseMeasure>,
}
impl TranscriptConfig {
fn prose_measure_columns(&self) -> Result<Option<u16>, String> {
match &self.prose_measure {
None | Some(RawProseMeasure::Integer(0)) => Ok(None),
Some(RawProseMeasure::Integer(columns)) if *columns > 0 => {
Ok(Some((*columns).min(i64::from(u16::MAX)) as u16))
}
Some(raw) => Err(format!(
"expected a positive whole number of columns \
(0 or absent = full width), got {}",
raw.describe()
)),
}
}
}
#[derive(Debug, Clone)]
pub struct AccountModelAccess {
pub session_id: String,
pub credential: crate::credentials::Credential,
pub expires_at: i64,
pub profile: Option<String>,
}
pub trait ModelHttpPolicy: std::fmt::Debug + Send + Sync {
fn configure(
&self,
builder: reqwest::ClientBuilder,
base_url: &str,
) -> Result<reqwest::ClientBuilder>;
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct Config {
#[serde(skip)]
pub model_http_policy: Option<std::sync::Arc<dyn ModelHttpPolicy>>,
#[serde(skip)]
pub account_profile: Option<String>,
#[serde(skip)]
pub plugin_oauth_read_only: bool,
#[serde(skip)]
pub account_model_access: std::sync::Arc<parking_lot::RwLock<Option<AccountModelAccess>>>,
#[serde(skip)]
pub session_provider_keys_only: bool,
#[serde(skip)]
pub session_provider_keys: std::sync::Arc<
parking_lot::RwLock<HashMap<ProviderIdentity, (String, crate::credentials::Credential)>>,
>,
#[serde(skip)]
pub required_account_model_owner: Option<String>,
#[serde(skip)]
pub extra_trusted_paths: Vec<std::path::PathBuf>,
#[serde(
default,
deserialize_with = "codewhale_config::catalog::configured::deserialize_configured_models"
)]
pub custom_models: Option<Vec<codewhale_config::catalog::configured::ConfiguredModel>>,
#[serde(default)]
pub stop_words: Option<Vec<String>>,
pub provider: Option<String>,
#[serde(alias = "httpHeaders")]
pub http_headers: Option<HashMap<String, String>>,
pub title: Option<String>,
#[serde(alias = "defaultTextModel")]
pub default_text_model: Option<String>,
#[serde(rename = "model", skip_serializing)]
pub legacy_model: Option<String>,
#[serde(alias = "authMode")]
pub auth_mode: Option<String>,
pub reasoning_effort: Option<String>,
#[serde(skip)]
pub reasoning_effort_inferred_from_legacy_alias: bool,
#[serde(skip)]
pub fleet_operator_route_applied: bool,
#[serde(skip)]
pub fleet_operator_reasoning_applied: bool,
#[serde(skip)]
pub migrated_deepseek_model_alias: Option<String>,
#[serde(skip)]
pub(crate) migrated_legacy_ollama_cloud_route: bool,
#[serde(skip)]
pub runtime_chat_isolated: bool,
#[serde(skip)]
pub runtime_thread_inference_unrelated: bool,
#[serde(default)]
pub tools: Option<ToolsConfig>,
pub skills_dir: Option<String>,
pub mcp_config_path: Option<String>,
pub mcp_oauth_callback_port: Option<u16>,
pub mcp_oauth_callback_url: Option<String>,
pub notes_path: Option<String>,
pub memory_path: Option<String>,
pub strict_tool_mode: Option<bool>,
pub instructions: Option<Vec<String>>,
pub allow_shell: Option<bool>,
pub prompt_suggestion: Option<bool>,
#[serde(alias = "approvalPolicy")]
pub approval_policy: Option<String>,
#[serde(alias = "sandboxMode")]
pub sandbox_mode: Option<String>,
#[serde(alias = "sandboxNetworkAccess")]
pub sandbox_network_access: Option<bool>,
#[serde(default, alias = "projectInstructionImports")]
pub project_instruction_imports: Vec<String>,
#[serde(default, alias = "instructionBudget")]
pub instruction_budget: Option<codewhale_config::instruction_budget::InstructionBudgetConfig>,
#[serde(default)]
pub telemetry: Option<bool>,
#[serde(default, alias = "fallbackProviders")]
pub fallback_providers: Vec<codewhale_config::ProviderKind>,
pub yolo: Option<bool>,
pub verbosity: Option<String>,
#[serde(alias = "sandboxBackend")]
pub sandbox_backend: Option<String>,
#[serde(alias = "sandboxUrl")]
pub sandbox_url: Option<String>,
#[serde(alias = "sandboxApiKey")]
pub sandbox_api_key: Option<String>,
#[serde(alias = "preferBwrap")]
pub prefer_bwrap: Option<bool>,
#[serde(skip)]
pub tool_launcher: Option<Vec<String>>,
#[serde(default, alias = "bwrapRoRoots")]
pub bwrap_ro_roots: Vec<std::path::PathBuf>,
#[serde(default, alias = "bwrapDevRoots")]
pub bwrap_dev_roots: Vec<std::path::PathBuf>,
#[serde(default, alias = "sandboxDeniedReadPaths")]
pub sandbox_denied_read_paths: Vec<std::path::PathBuf>,
#[serde(default, alias = "sandboxReadDenylistDefaults")]
pub sandbox_read_denylist_defaults: Option<bool>,
#[serde(default, alias = "sandboxReadDenylistExempt")]
pub sandbox_read_denylist_exempt: Vec<std::path::PathBuf>,
#[serde(alias = "managedConfigPath")]
pub managed_config_path: Option<String>,
#[serde(alias = "requirementsPath")]
pub requirements_path: Option<String>,
#[serde(alias = "maxSubagents")]
pub max_subagents: Option<usize>,
pub retry: Option<RetryConfig>,
pub stream: Option<StreamConfig>,
pub features: Option<FeaturesToml>,
#[serde(default)]
pub extension_host: Option<ExtensionHostConfig>,
#[serde(default)]
pub plugins: Option<BTreeMap<String, PluginSettings>>,
#[serde(default)]
pub auto_review: Option<AutoReviewConfig>,
pub tui: Option<TuiConfig>,
#[serde(default)]
pub transcript: Option<TranscriptConfig>,
#[serde(default)]
pub hooks: Option<HooksConfig>,
#[serde(default)]
pub lifecycle_outbox: Option<codewhale_config::LifecycleOutboxToml>,
#[serde(default)]
pub control_socket: Option<codewhale_config::ControlSocketToml>,
#[serde(default)]
pub providers: Option<ProvidersConfig>,
#[serde(default)]
pub notifications: Option<NotificationsConfig>,
#[serde(default)]
pub approval: Option<ApprovalConfig>,
#[serde(default)]
pub network: Option<codewhale_config::NetworkPolicyToml>,
#[serde(default)]
pub verifier: Option<codewhale_config::VerifierConfigToml>,
#[serde(default)]
pub advisor: Option<codewhale_config::AdvisorConfigToml>,
#[serde(default)]
pub skills: Option<SkillsConfig>,
#[serde(default)]
pub snapshots: Option<SnapshotsConfig>,
#[serde(default)]
pub search: Option<SearchConfig>,
#[serde(default)]
pub goal: Option<GoalConfig>,
#[serde(default)]
pub reasoning_only: Option<ReasoningOnlyConfig>,
#[serde(default)]
pub memory: Option<MemoryConfig>,
#[serde(default)]
pub speech: Option<SpeechConfig>,
#[serde(default)]
pub auto: Option<AutoConfig>,
#[serde(default)]
pub hotbar: Option<Vec<codewhale_config::HotbarBindingToml>>,
#[serde(default)]
pub update: Option<UpdateConfig>,
#[serde(default)]
pub cloud_facts: Option<CloudFactsConfig>,
#[serde(default)]
pub lsp: Option<codewhale_config::LspConfigToml>,
#[serde(default)]
pub context: ContextConfig,
#[serde(default)]
pub compaction: Option<CompactionSettings>,
#[serde(default)]
pub fleet: Option<codewhale_config::FleetConfigToml>,
#[serde(default)]
pub workflow: Option<codewhale_config::WorkflowConfigToml>,
#[serde(default)]
pub subagents: Option<SubagentsConfig>,
#[serde(default)]
pub runtime_api: Option<RuntimeApiConfig>,
#[serde(default)]
pub workshop: Option<codewhale_config::WorkshopConfig>,
#[serde(default)]
pub vision_model: Option<VisionModelConfig>,
#[serde(default)]
pub redaction: Option<codewhale_config::redaction::RedactionToml>,
#[serde(skip)]
pub loaded_config_path: Option<PathBuf>,
#[serde(skip)]
pub network_layer_is_managed: bool,
#[serde(skip)]
pub remembered_selection_scope: Option<bool>,
#[serde(skip)]
pub environment_model_applied: bool,
#[serde(skip)]
pub route_provenance: RouteProvenance,
pub route_preferences_version: Option<u32>,
#[serde(skip)]
pub exec_policy_engine: ExecPolicyEngine,
#[serde(skip)]
pub base_url_env_receipt: BaseUrlEnvReceipt,
#[serde(skip)]
pub legacy_root: codewhale_config::legacy_root::LegacyRootMigration,
#[serde(skip)]
legacy_root_custom_generation: Option<codewhale_config::credentials::CredentialGeneration>,
#[serde(default)]
pub mini_window: Option<MiniWindowConfig>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct MiniWindowConfig {
#[serde(default = "mini_default_keep_input")]
pub keep_input: bool,
#[serde(default)]
pub keep_todo: bool,
#[serde(default)]
pub keep_sidebar: bool,
#[serde(default)]
pub keep_footer: bool,
#[serde(default)]
pub keep_header: bool,
}
impl Default for MiniWindowConfig {
fn default() -> Self {
Self {
keep_input: true,
keep_todo: false,
keep_sidebar: false,
keep_footer: false,
keep_header: false,
}
}
}
fn mini_default_keep_input() -> bool {
true
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum BaseUrlEnvReceipt {
#[default]
Unrecorded,
NoOwner,
Route(ProviderKind, String),
}
impl BaseUrlEnvReceipt {
fn owns(&self, provider: ProviderKind, identity: &str) -> bool {
match self {
Self::Route(owner, owner_identity) => *owner == provider && owner_identity == identity,
Self::Unrecorded | Self::NoOwner => false,
}
}
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct AutoReviewConfig {
#[serde(default)]
pub disabled: bool,
#[serde(default)]
pub review_all_shell: bool,
#[serde(default)]
pub reviewer_model: Option<String>,
#[serde(default)]
pub allow: Vec<AutoReviewRuleConfig>,
#[serde(default)]
pub block: Vec<AutoReviewRuleConfig>,
#[serde(default)]
pub environment: Vec<String>,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct AutoReviewRuleConfig {
pub id: Option<String>,
#[serde(default, alias = "toolName", alias = "tool_name")]
pub tool: Option<String>,
#[serde(default, alias = "actionKind", alias = "action_kind")]
pub action_kind: Option<String>,
#[serde(default, alias = "textContains")]
pub(crate) text_contains: Option<String>,
pub reason: Option<String>,
}
impl AutoReviewConfig {
fn validate(&self) -> Result<()> {
if let Some(reviewer_model) = self.reviewer_model.as_deref() {
validate_auto_review_reviewer_model(reviewer_model)?;
}
validate_auto_review_rules("allow", &self.allow)?;
validate_auto_review_rules("block", &self.block)?;
validate_auto_review_environment(&self.environment)?;
Ok(())
}
}
pub fn validate_auto_review_environment(entries: &[String]) -> Result<()> {
for (index, entry) in entries.iter().enumerate() {
let trimmed = entry.trim();
if trimmed.is_empty() || entry.chars().any(char::is_control) {
anyhow::bail!(
"Invalid auto_review.environment[{index}]: expected a non-empty entry without control characters."
);
}
}
Ok(())
}
pub fn validate_auto_review_reviewer_model(raw: &str) -> Result<()> {
let trimmed = raw.trim();
if trimmed.is_empty()
|| raw != trimmed
|| trimmed
.chars()
.any(|ch| ch.is_whitespace() || ch.is_control())
{
anyhow::bail!(
"Invalid auto_review.reviewer_model: expected a non-empty model identifier without whitespace or control characters."
);
}
Ok(())
}
impl AutoReviewRuleConfig {
fn has_matcher(&self) -> bool {
self.tool
.as_deref()
.is_some_and(|value| !value.trim().is_empty())
|| self
.action_kind
.as_deref()
.is_some_and(|value| !value.trim().is_empty())
}
}
fn validate_auto_review_rules(kind: &str, rules: &[AutoReviewRuleConfig]) -> Result<()> {
for (index, rule) in rules.iter().enumerate() {
if rule
.text_contains
.as_deref()
.is_some_and(|value| !value.trim().is_empty())
{
anyhow::bail!(
"Invalid auto_review.{kind}[{index}].text_contains: user-intent matching was retired; scope the rule with tool and/or action_kind."
);
}
if !rule.has_matcher() {
anyhow::bail!(
"Invalid auto_review.{kind}[{index}]: set at least one of tool or action_kind."
);
}
if let Some(action_kind) = rule.action_kind.as_deref() {
let normalized = action_kind.trim().to_ascii_lowercase().replace('-', "_");
if auto_review_action_kind_name(&normalized).is_none() {
anyhow::bail!(
"Invalid auto_review.{kind}[{index}].action_kind '{action_kind}': expected read, write, shell, external, publish, or destructive."
);
}
if kind == "allow"
&& !matches!(
normalized.as_str(),
"read" | "write" | "shell" | "external" | "publish" | "destructive"
)
{
anyhow::bail!(
"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."
);
}
}
}
Ok(())
}
#[must_use]
pub fn auto_review_action_kind_name(raw: &str) -> Option<&'static str> {
match raw.trim().to_ascii_lowercase().replace('-', "_").as_str() {
"read" | "mcp_read" => Some("read"),
"write" => Some("write"),
"shell" => Some("shell"),
"external" | "network" | "git" | "mcp_action" | "browser" | "unknown" => Some("external"),
"publish" => Some("publish"),
"destructive" | "secret" => Some("destructive"),
_ => None,
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ToolOverride {
Script {
path: String,
#[serde(default)]
args: Option<Vec<String>>,
},
Command {
command: String,
#[serde(default)]
args: Option<Vec<String>>,
},
Disabled,
}
#[derive(Debug, Clone, Deserialize)]
pub struct VisionModelConfig {
#[serde(skip)]
pub model_http_policy: Option<std::sync::Arc<dyn ModelHttpPolicy>>,
pub model: String,
#[serde(default)]
pub api_key: Option<String>,
#[serde(default)]
pub base_url: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Default)]
pub struct RuntimeApiConfig {
#[serde(default)]
pub cors_origins: Option<Vec<String>>,
}
#[derive(Debug, Clone, Deserialize, Default)]
pub struct SkillsConfig {
#[serde(default)]
pub bundled: BundledSkillsConfig,
#[serde(default)]
pub listing_max_description_chars: Option<usize>,
#[serde(default)]
pub listing_budget_fraction: Option<f64>,
#[serde(default)]
pub registry_url: Option<String>,
#[serde(default)]
pub max_install_size_bytes: Option<u64>,
#[serde(default, alias = "scanCodewhaleOnly")]
pub scan_codewhale_only: Option<bool>,
#[serde(default)]
pub flat_workspace_root: Option<bool>,
#[serde(skip)]
pub creator_skills: bool,
}
#[derive(Debug, Clone, Copy, Deserialize, Default, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum BundledSkillsInstall {
#[default]
Auto,
All,
None,
}
#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq, Hash, Serialize)]
pub struct BundledSkillsConfig {
pub install: Option<BundledSkillsInstall>,
pub selected: Option<Vec<String>>,
pub disabled: Option<Vec<String>>,
pub explicit_only: Option<Vec<String>>,
}
impl SkillsConfig {
#[must_use]
pub fn flat_workspace_root(&self) -> bool {
self.flat_workspace_root.unwrap_or(false)
}
#[must_use]
pub fn scan_codewhale_only(&self) -> bool {
self.scan_codewhale_only.unwrap_or(false)
}
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ProviderConfig {
pub vendor: Option<String>,
#[serde(alias = "apiKey")]
pub api_key: Option<String>,
#[serde(alias = "baseUrl")]
pub base_url: Option<String>,
pub model: Option<String>,
#[serde(
default,
alias = "contextWindow",
alias = "context_window_tokens",
alias = "contextWindowTokens",
alias = "context_length",
alias = "contextLength"
)]
pub context_window: Option<u32>,
#[serde(default, alias = "modelContextWindows")]
pub model_context_windows: Option<std::collections::BTreeMap<String, u32>>,
pub mode: Option<String>,
#[serde(
default,
alias = "apiStyle",
alias = "api_style",
alias = "protocol",
alias = "wire_format",
alias = "wireFormat",
alias = "dialect"
)]
pub wire: Option<String>,
#[serde(default, alias = "responsesProfile")]
pub responses_profile: Option<String>,
#[serde(alias = "authMode")]
pub auth_mode: Option<String>,
#[serde(default)]
pub oauth: Option<crate::oauth::PluginOAuthConfig>,
#[serde(default, alias = "oauthCredentialGeneration")]
pub oauth_credential_generation: Option<String>,
#[serde(alias = "insecureSkipTlsVerify")]
pub insecure_skip_tls_verify: Option<bool>,
#[serde(default, alias = "allowInsecureHttp")]
pub allow_insecure_http: Option<bool>,
#[serde(alias = "httpHeaders")]
pub http_headers: Option<HashMap<String, String>>,
#[serde(alias = "pathSuffix")]
pub path_suffix: Option<String>,
#[serde(alias = "reasoningStyle", alias = "reasoningStreamStyle")]
pub reasoning_stream_style: Option<String>,
#[serde(
default,
alias = "max-concurrency",
alias = "maxConcurrency",
alias = "concurrency"
)]
pub max_concurrency: Option<usize>,
pub auth: Option<codewhale_config::ProviderAuthSourceToml>,
#[serde(default, alias = "externalCredentials")]
pub external_credentials: Option<codewhale_config::ExternalCredentialConsentToml>,
#[serde(default)]
pub kind: Option<String>,
#[serde(skip)]
pub plugin_authority: Option<codewhale_config::PluginAuthority>,
#[serde(default, alias = "apiKeyEnv")]
pub api_key_env: Option<String>,
}
impl ProviderConfig {
#[must_use]
pub fn is_openai_compatible_custom(&self) -> bool {
self.kind.as_deref().is_some_and(|kind| {
let normalized = kind.trim().to_ascii_lowercase().replace('_', "-");
normalized == "openai-compatible"
})
}
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct ProvidersConfig {
#[serde(default)]
pub deepseek: ProviderConfig,
#[serde(default, alias = "deepseekCn")]
pub deepseek_cn: ProviderConfig,
#[serde(
default,
alias = "deepseek-anthropic",
alias = "deepseekAnthropic",
alias = "deepseek-claude",
alias = "deepseek_claude"
)]
pub deepseek_anthropic: ProviderConfig,
#[serde(default, alias = "nvidiaNim")]
pub nvidia_nim: ProviderConfig,
#[serde(default)]
pub openai: ProviderConfig,
#[serde(default)]
pub atlascloud: ProviderConfig,
#[serde(default, alias = "wanjieArk")]
pub wanjie_ark: ProviderConfig,
#[serde(default)]
pub volcengine: ProviderConfig,
#[serde(default)]
pub openrouter: ProviderConfig,
#[serde(default, alias = "orca_router", alias = "orca")]
pub orcarouter: ProviderConfig,
#[serde(
default,
alias = "xiaomi",
alias = "mimo",
alias = "xiaomimimo",
alias = "xiaomiMimo"
)]
pub xiaomi_mimo: ProviderConfig,
#[serde(default)]
pub novita: ProviderConfig,
#[serde(default)]
pub fireworks: ProviderConfig,
#[serde(default)]
pub siliconflow: ProviderConfig,
#[serde(
default,
alias = "siliconflow-CN",
alias = "siliconflow-cn",
alias = "siliconflowCn"
)]
pub siliconflow_cn: ProviderConfig,
#[serde(default)]
pub arcee: ProviderConfig,
#[serde(default)]
pub moonshot: ProviderConfig,
#[serde(default)]
pub sglang: ProviderConfig,
#[serde(default)]
pub vllm: ProviderConfig,
#[serde(default)]
pub ollama: ProviderConfig,
#[serde(default, alias = "ollama-cloud", alias = "ollamaCloud")]
pub ollama_cloud: ProviderConfig,
#[serde(default, alias = "hugging-face", alias = "hf")]
pub huggingface: ProviderConfig,
#[serde(default, alias = "model-scope", alias = "model_scope")]
pub modelscope: ProviderConfig,
#[serde(default, alias = "deep-infra", alias = "deep_infra")]
pub deepinfra: ProviderConfig,
#[serde(default, alias = "together-ai")]
pub together: ProviderConfig,
#[serde(
default,
alias = "baidu-qianfan",
alias = "baidu_qianfan",
alias = "baidu"
)]
pub qianfan: ProviderConfig,
#[serde(
default,
alias = "openai-codex",
alias = "openaiCodex",
alias = "codex",
alias = "chatgpt"
)]
pub openai_codex: ProviderConfig,
#[serde(default, alias = "claude")]
pub anthropic: ProviderConfig,
#[serde(default, alias = "open-model", alias = "open_model")]
pub openmodel: ProviderConfig,
#[serde(
default,
alias = "zhipu",
alias = "zhipuai",
alias = "bigmodel",
alias = "big-model"
)]
pub zai: ProviderConfig,
#[serde(default)]
pub stepfun: ProviderConfig,
#[serde(default)]
pub minimax: ProviderConfig,
#[serde(
default,
alias = "minimax-anthropic",
alias = "minimaxAnthropic",
alias = "mini-max-anthropic",
alias = "mini_max_anthropic"
)]
pub minimax_anthropic: ProviderConfig,
#[serde(default, alias = "sakana-ai", alias = "sakana_ai", alias = "fugu")]
pub sakana: ProviderConfig,
#[serde(
default,
alias = "long-cat",
alias = "meituan-longcat",
alias = "meituan"
)]
pub longcat: ProviderConfig,
#[serde(default, alias = "opencode-go", alias = "opencodego")]
pub opencode_go: ProviderConfig,
#[serde(
default,
alias = "opencode-zen",
alias = "opencodezen",
alias = "zen",
alias = "opencode"
)]
pub opencode_zen: ProviderConfig,
#[serde(
default,
alias = "meta-ai",
alias = "meta_ai",
alias = "meta-model-api",
alias = "meta_model_api",
alias = "muse",
alias = "muse-spark"
)]
pub meta: ProviderConfig,
#[serde(default, alias = "x-ai", alias = "x_ai", alias = "grok")]
pub xai: ProviderConfig,
#[serde(
default,
alias = "mistral-ai",
alias = "mistral_ai",
alias = "mistralai",
alias = "la-plateforme",
alias = "la_plateforme"
)]
pub mistral: ProviderConfig,
#[serde(
default,
alias = "google-gemini",
alias = "google_gemini",
alias = "gemini"
)]
pub google: ProviderConfig,
#[serde(default, alias = "agy")]
pub antigravity: ProviderConfig,
#[serde(
default,
alias = "telecom-js",
alias = "telecom_js",
alias = "telecomjs-cn",
alias = "tokenhub"
)]
pub telecomjs: ProviderConfig,
#[serde(default, alias = "eden-ai", alias = "eden_ai")]
pub edenai: ProviderConfig,
#[serde(default, alias = "zen-mux", alias = "zen_mux")]
pub zenmux: ProviderConfig,
#[serde(
default,
alias = "csdn-ai",
alias = "csdn_ai",
alias = "csdn-coding-plan",
alias = "csdn_coding_plan",
alias = "starmap"
)]
pub csdn: ProviderConfig,
#[serde(
default,
alias = "concentrate-ai",
alias = "concentrate_ai",
alias = "concentrateai"
)]
pub concentrate: ProviderConfig,
#[serde(
default,
alias = "codewhale-api",
alias = "codewhale_api",
alias = "cw-api",
alias = "codewhale-cloud"
)]
pub codewhale: ProviderConfig,
#[serde(default, alias = "modelstudio-token-plan")]
pub modelstudio_token_plan: ProviderConfig,
#[serde(default, alias = "modelstudio-token-plan-anthropic")]
pub modelstudio_token_plan_anthropic: ProviderConfig,
#[serde(default, alias = "modelstudio-coding-plan")]
pub modelstudio_coding_plan: ProviderConfig,
#[serde(default, alias = "modelstudio-coding-plan-anthropic")]
pub modelstudio_coding_plan_anthropic: ProviderConfig,
#[serde(flatten, default)]
pub custom: HashMap<String, ProviderConfig>,
}
impl ProvidersConfig {
#[must_use]
pub fn custom_provider_config(&self, name: &str) -> Option<&ProviderConfig> {
self.custom.get(name)
}
fn validate(&self) -> Result<()> {
let builtins = [
("providers.deepseek", &self.deepseek),
("providers.deepseek_cn", &self.deepseek_cn),
("providers.deepseek_anthropic", &self.deepseek_anthropic),
("providers.nvidia_nim", &self.nvidia_nim),
("providers.openai", &self.openai),
("providers.atlascloud", &self.atlascloud),
("providers.wanjie_ark", &self.wanjie_ark),
("providers.volcengine", &self.volcengine),
("providers.openrouter", &self.openrouter),
("providers.xiaomi_mimo", &self.xiaomi_mimo),
("providers.novita", &self.novita),
("providers.fireworks", &self.fireworks),
("providers.siliconflow", &self.siliconflow),
("providers.siliconflow_cn", &self.siliconflow_cn),
("providers.arcee", &self.arcee),
("providers.moonshot", &self.moonshot),
("providers.sglang", &self.sglang),
("providers.vllm", &self.vllm),
("providers.ollama", &self.ollama),
("providers.ollama_cloud", &self.ollama_cloud),
("providers.huggingface", &self.huggingface),
("providers.deepinfra", &self.deepinfra),
("providers.together", &self.together),
("providers.qianfan", &self.qianfan),
("providers.openai_codex", &self.openai_codex),
("providers.anthropic", &self.anthropic),
("providers.openmodel", &self.openmodel),
("providers.zai", &self.zai),
("providers.stepfun", &self.stepfun),
("providers.minimax", &self.minimax),
("providers.minimax_anthropic", &self.minimax_anthropic),
("providers.sakana", &self.sakana),
("providers.opencode_go", &self.opencode_go),
("providers.opencode_zen", &self.opencode_zen),
("providers.meta", &self.meta),
("providers.xai", &self.xai),
];
for (name, config) in builtins {
validate_provider_context_window(name, config.context_window)?;
validate_model_context_windows(name, config.model_context_windows.as_ref())?;
}
for (name, config) in &self.custom {
let name = format!("providers.{name}");
validate_provider_context_window(&name, config.context_window)?;
validate_model_context_windows(&name, config.model_context_windows.as_ref())?;
}
Ok(())
}
}
fn validate_provider_context_window(name: &str, value: Option<u32>) -> Result<()> {
if value == Some(0) {
anyhow::bail!("{name}.context_window must be greater than 0");
}
Ok(())
}
fn validate_model_context_windows(
name: &str,
table: Option<&std::collections::BTreeMap<String, u32>>,
) -> Result<()> {
if let Some(table) = table {
for (model, window) in table {
if *window == 0 {
anyhow::bail!("{name}.model_context_windows.{model} must be greater than 0");
}
}
}
Ok(())
}
#[derive(Debug, Clone, Deserialize, Default)]
struct ConfigFile {
#[serde(flatten)]
base: Box<Config>,
profiles: Option<HashMap<String, Config>>,
#[serde(skip)]
legacy_root: codewhale_config::legacy_root::LegacyRootMigration,
}
#[derive(Debug, Clone, Deserialize, Default)]
struct RequirementsFile {
#[serde(default)]
allowed_approval_policies: Vec<String>,
#[serde(default)]
allowed_sandbox_modes: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApprovalPolicyControl {
Unset,
RootConfig,
Profile,
Environment,
ManagedConfig,
ProjectConfig,
Requirements,
Ambiguous,
}
impl ApprovalPolicyControl {
#[must_use]
pub fn editable_root(self) -> bool {
matches!(self, Self::Unset | Self::RootConfig)
}
#[must_use]
pub fn label(self) -> &'static str {
match self {
Self::Unset => "saved TUI posture",
Self::RootConfig => "the root config.toml approval_policy",
Self::Profile => "the active config profile",
Self::Environment => {
set_env_var_name(APPROVAL_POLICY_ENV).unwrap_or(APPROVAL_POLICY_ENV[0])
}
Self::ManagedConfig => "managed configuration",
Self::ProjectConfig => "project configuration",
Self::Requirements => "managed approval requirements",
Self::Ambiguous => "an unresolved configuration source",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShellAccessControl {
Unset,
RootConfig,
Profile,
Environment,
ManagedConfig,
ProjectConfig,
Ambiguous,
}
impl ShellAccessControl {
#[must_use]
pub fn editable_root(self) -> bool {
matches!(self, Self::Unset | Self::RootConfig)
}
#[must_use]
pub fn label(self) -> &'static str {
match self {
Self::Unset => "the session default",
Self::RootConfig => "the root config.toml allow_shell",
Self::Profile => "the active config profile",
Self::Environment => set_env_var_name(ALLOW_SHELL_ENV).unwrap_or(ALLOW_SHELL_ENV[0]),
Self::ManagedConfig => "managed configuration",
Self::ProjectConfig => "project configuration",
Self::Ambiguous => "an unresolved configuration source",
}
}
}
const APPROVAL_POLICY_ENV: [&str; 2] = ["CODEWHALE_APPROVAL_POLICY", "DEEPSEEK_APPROVAL_POLICY"];
const ALLOW_SHELL_ENV: [&str; 2] = ["CODEWHALE_ALLOW_SHELL", "DEEPSEEK_ALLOW_SHELL"];
fn set_env_var_name(names: [&'static str; 2]) -> Option<&'static str> {
let read = || {
names
.into_iter()
.find(|name| std::env::var_os(name).is_some())
};
#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
{
crate::test_support::with_test_env_lock(read)
}
#[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
{
read()
}
}
fn approval_policy_env_is_set() -> bool {
set_env_var_name(APPROVAL_POLICY_ENV).is_some()
}
fn allow_shell_env_is_set() -> bool {
set_env_var_name(ALLOW_SHELL_ENV).is_some()
}
fn project_config_root_bool(workspace: &Path, key: &str) -> Option<bool> {
[
workspace
.join(codewhale_config::CODEWHALE_APP_DIR)
.join("config.toml"),
workspace
.join(codewhale_config::LEGACY_APP_DIR)
.join("config.toml"),
]
.into_iter()
.find(|path| path.exists())
.and_then(|path| std::fs::read_to_string(path).ok())
.and_then(|raw| toml::from_str::<toml::Value>(&raw).ok())
.and_then(|document| document.get(key).and_then(toml::Value::as_bool))
}
#[must_use]
pub fn approval_policy_baseline_from_permission_posture(
posture: Option<&str>,
) -> Option<&'static str> {
posture.and_then(
|posture| match posture.trim().to_ascii_lowercase().as_str() {
"ask" | "suggest" | "on-request" | "untrusted" => Some("on-request"),
"accept-edits" | "accept_edits" | "acceptedits" | "edits" => Some("accept-edits"),
"auto" | "auto-review" | "auto_review" => Some("auto"),
"full" | "full-access" | "full_access" | "bypass" => Some("auto"),
_ => None,
},
)
}
impl Config {
#[must_use]
pub fn prefers_bwrap(&self) -> bool {
self.prefer_bwrap.unwrap_or(true)
}
#[must_use]
pub fn stop_words(&self) -> Vec<String> {
self.stop_words.clone().unwrap_or_else(default_stop_words)
}
pub fn external_credential_consent_status(
&self,
identity: &ProviderIdentity,
) -> Option<codewhale_config::ExternalCredentialConsentStatus> {
if identity.key.as_str() == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id {
return None;
}
let provider = identity.provider;
let (kind, source, path) = match provider {
ProviderKind::OpenaiCodex => (
codewhale_config::ProviderKind::OpenaiCodex,
codewhale_config::ExternalCredentialSource::CodexCli,
crate::oauth::auth_file_path(),
),
ProviderKind::Xai => (
codewhale_config::ProviderKind::Xai,
codewhale_config::ExternalCredentialSource::GrokCli,
crate::oauth::grok_auth_file_path(),
),
ProviderKind::Deepseek => (
codewhale_config::ProviderKind::Deepseek,
codewhale_config::ExternalCredentialSource::DshCli,
codewhale_config::default_dsh_credentials_path(),
),
ProviderKind::DeepseekAnthropic => (
codewhale_config::ProviderKind::DeepseekAnthropic,
codewhale_config::ExternalCredentialSource::DshCli,
codewhale_config::default_dsh_credentials_path(),
),
_ => return None,
};
self.verify_provider_identity(identity).ok()?;
let active = self.active_provider_identity().ok()?;
let consent = self
.provider_config_for(identity)
.and_then(|entry| entry.external_credentials.as_ref());
let mut status = codewhale_config::external_credential_consent_status(
consent,
kind,
source,
&path,
active.provider,
);
if active != *identity {
status.route_state = "dormant";
}
Some(status)
}
#[must_use]
pub fn runtime_preset_blocker(
&self,
config_path: Option<&Path>,
profile: Option<&str>,
workspace: &Path,
) -> Option<&'static str> {
let requirements_path = self
.requirements_path
.as_deref()
.map(expand_path)
.or_else(default_requirements_path);
if let Some(path) = requirements_path
&& path.exists()
{
let controlled = std::fs::read_to_string(path)
.ok()
.and_then(|raw| toml::from_str::<RequirementsFile>(&raw).ok())
.is_none_or(|requirements| {
!requirements.allowed_approval_policies.is_empty()
|| !requirements.allowed_sandbox_modes.is_empty()
});
if controlled {
return Some("managed runtime requirements");
}
}
let workspace_is_home = codewhale_paths::user_home().is_some_and(|home| {
let workspace = workspace
.canonicalize()
.unwrap_or_else(|_| workspace.to_path_buf());
let home = home.canonicalize().unwrap_or(home);
workspace == home
});
let project_controls_runtime = || {
let saved_approval_baseline = crate::settings::Settings::load_persisted()
.ok()
.and_then(|settings| settings.permission_posture)
.and_then(|posture| {
approval_policy_baseline_from_permission_posture(Some(&posture))
});
let approval_baseline = self.approval_policy.as_deref().or(saved_approval_baseline);
let parsed_controls =
codewhale_config::load_project_config(workspace).is_some_and(|project| {
project.approval_policy.as_deref().is_some_and(|policy| {
codewhale_config::project_approval_policy_is_allowed(
approval_baseline,
policy,
)
}) || project.sandbox_mode.as_deref().is_some_and(|sandbox| {
codewhale_config::project_sandbox_mode_is_allowed(
self.sandbox_mode.as_deref(),
sandbox,
)
})
});
parsed_controls || project_config_root_bool(workspace, "allow_shell") == Some(false)
};
if !workspace_is_home && project_controls_runtime() {
return Some("project runtime configuration");
}
match managed_config_file(self.managed_config_path.as_deref()) {
Err(_) => return Some("an unreadable managed runtime configuration"),
Ok(None) => {}
Ok(Some(path)) => match load_single_config_file(&path) {
Ok(managed)
if managed.approval_policy.is_some()
|| managed.sandbox_mode.is_some()
|| managed.allow_shell.is_some() =>
{
return Some("managed runtime configuration");
}
Err(_) => return Some("an unreadable managed runtime configuration"),
Ok(_) => {}
},
}
let env_controls_runtime = || {
approval_policy_env_is_set()
|| allow_shell_env_is_set()
|| std::env::var_os("CODEWHALE_SANDBOX_MODE").is_some()
|| std::env::var_os("DEEPSEEK_SANDBOX_MODE").is_some()
};
#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
let env_controls_runtime = crate::test_support::with_test_env_lock(env_controls_runtime);
#[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
let env_controls_runtime = env_controls_runtime();
if env_controls_runtime {
return Some("environment-controlled runtime posture");
}
if let Some(profile) = profile {
let path = match resolve_load_config_path(config_path.map(Path::to_path_buf)) {
Ok(Some(path)) => path,
Ok(None) => return Some("an unresolved active config profile"),
Err(_) => return Some("an invalid active config path override"),
};
let Some(parsed) = std::fs::read_to_string(path)
.ok()
.and_then(|raw| parse_config_file(&raw).ok())
else {
return Some("an unreadable active config profile");
};
if parsed
.profiles
.as_ref()
.and_then(|profiles| profiles.get(profile))
.is_some_and(|profile| {
profile.approval_policy.is_some()
|| profile.sandbox_mode.is_some()
|| profile.allow_shell.is_some()
})
{
return Some("the active config profile");
}
}
None
}
#[must_use]
pub fn approval_policy_control(
&self,
config_path: Option<&Path>,
profile: Option<&str>,
workspace: &Path,
) -> ApprovalPolicyControl {
if self.approval_policy_is_requirements_managed() {
return ApprovalPolicyControl::Requirements;
}
let workspace_is_home = codewhale_paths::user_home().is_some_and(|home| {
let workspace = workspace
.canonicalize()
.unwrap_or_else(|_| workspace.to_path_buf());
let home = home.canonicalize().unwrap_or(home);
workspace == home
});
if !workspace_is_home {
let saved_approval_baseline = crate::settings::Settings::load_persisted()
.ok()
.and_then(|settings| settings.permission_posture)
.and_then(|posture| {
approval_policy_baseline_from_permission_posture(Some(&posture))
});
let approval_baseline = self.approval_policy.as_deref().or(saved_approval_baseline);
if codewhale_config::load_project_config(workspace)
.and_then(|project| project.approval_policy)
.is_some_and(|policy| {
codewhale_config::project_approval_policy_is_allowed(approval_baseline, &policy)
})
{
return ApprovalPolicyControl::ProjectConfig;
}
}
match managed_config_file(self.managed_config_path.as_deref()) {
Err(_) => return ApprovalPolicyControl::Ambiguous,
Ok(None) => {}
Ok(Some(path)) => match load_single_config_file(&path) {
Ok(managed) if managed.approval_policy.is_some() => {
return ApprovalPolicyControl::ManagedConfig;
}
Err(_) => return ApprovalPolicyControl::Ambiguous,
Ok(_) => {}
},
}
if approval_policy_env_is_set() {
return ApprovalPolicyControl::Environment;
}
let path = match resolve_load_config_path(config_path.map(Path::to_path_buf)) {
Ok(Some(path)) => path,
Ok(None) | Err(_) => {
return if self.approval_policy.is_some() {
ApprovalPolicyControl::Ambiguous
} else {
ApprovalPolicyControl::Unset
};
}
};
let parsed = std::fs::read_to_string(path)
.ok()
.and_then(|raw| parse_config_file(&raw).ok());
let Some(parsed) = parsed else {
return if self.approval_policy.is_some() {
ApprovalPolicyControl::Ambiguous
} else {
ApprovalPolicyControl::Unset
};
};
if let Some(profile) = profile
&& parsed
.profiles
.as_ref()
.and_then(|profiles| profiles.get(profile))
.is_some_and(|profile| profile.approval_policy.is_some())
{
return ApprovalPolicyControl::Profile;
}
if parsed.base.approval_policy.is_some() {
ApprovalPolicyControl::RootConfig
} else if self.approval_policy.is_some() {
ApprovalPolicyControl::Ambiguous
} else {
ApprovalPolicyControl::Unset
}
}
#[must_use]
pub fn allow_shell_control(
&self,
config_path: Option<&Path>,
profile: Option<&str>,
workspace: &Path,
) -> ShellAccessControl {
let workspace_is_home = codewhale_paths::user_home().is_some_and(|home| {
let workspace = workspace
.canonicalize()
.unwrap_or_else(|_| workspace.to_path_buf());
let home = home.canonicalize().unwrap_or(home);
workspace == home
});
if !workspace_is_home && project_config_root_bool(workspace, "allow_shell") == Some(false) {
return ShellAccessControl::ProjectConfig;
}
match managed_config_file(self.managed_config_path.as_deref()) {
Err(_) => return ShellAccessControl::Ambiguous,
Ok(None) => {}
Ok(Some(path)) => match load_single_config_file(&path) {
Ok(managed) if managed.allow_shell.is_some() => {
return ShellAccessControl::ManagedConfig;
}
Err(_) => return ShellAccessControl::Ambiguous,
Ok(_) => {}
},
}
if allow_shell_env_is_set() {
return ShellAccessControl::Environment;
}
let path = match resolve_load_config_path(config_path.map(Path::to_path_buf)) {
Ok(Some(path)) => path,
Ok(None) | Err(_) => {
return if self.allow_shell.is_some() {
ShellAccessControl::Ambiguous
} else {
ShellAccessControl::Unset
};
}
};
let parsed = std::fs::read_to_string(path)
.ok()
.and_then(|raw| parse_config_file(&raw).ok());
let Some(parsed) = parsed else {
return if self.allow_shell.is_some() {
ShellAccessControl::Ambiguous
} else {
ShellAccessControl::Unset
};
};
if let Some(profile) = profile
&& parsed
.profiles
.as_ref()
.and_then(|profiles| profiles.get(profile))
.is_some_and(|profile| profile.allow_shell.is_some())
{
return ShellAccessControl::Profile;
}
if parsed.base.allow_shell.is_some() {
ShellAccessControl::RootConfig
} else if self.allow_shell.is_some() {
ShellAccessControl::Ambiguous
} else {
ShellAccessControl::Unset
}
}
#[must_use]
pub fn approval_policy_is_requirements_managed(&self) -> bool {
let path = self
.requirements_path
.as_deref()
.map(expand_path)
.or_else(default_requirements_path);
let Some(path) = path else {
return false;
};
if !path.exists() {
return false;
}
std::fs::read_to_string(path)
.ok()
.and_then(|contents| toml::from_str::<RequirementsFile>(&contents).ok())
.is_none_or(|requirements| {
!requirements.allowed_approval_policies.is_empty()
|| !requirements.allowed_sandbox_modes.is_empty()
})
}
#[must_use]
pub fn search_provider_resolution(&self) -> SearchProviderResolution {
if let Ok(raw) = std::env::var("CODEWHALE_SEARCH_PROVIDER")
.or_else(|_| std::env::var("DEEPSEEK_SEARCH_PROVIDER"))
&& let Some(provider) = SearchProvider::parse(&raw)
{
return SearchProviderResolution {
provider,
source: SearchProviderSource::EnvOverride,
};
}
if let Some(provider) = self.search.as_ref().and_then(|search| search.provider) {
return SearchProviderResolution {
provider,
source: SearchProviderSource::Config,
};
}
let generic_key = self
.search
.as_ref()
.and_then(|search| search.api_key.as_deref());
if tavily_key_from(generic_key).is_some() {
return SearchProviderResolution {
provider: SearchProvider::Tavily,
source: SearchProviderSource::TavilyKey,
};
}
SearchProviderResolution {
provider: SearchProvider::default(),
source: SearchProviderSource::Default,
}
}
#[must_use]
pub fn search_provider(&self) -> SearchProvider {
self.search_provider_resolution().provider
}
#[must_use]
pub fn search_native(&self) -> Option<bool> {
self.search
.as_ref()
.and_then(|search| search.native)
.or_else(|| {
(self.search_provider_resolution().source != SearchProviderSource::Default)
.then_some(false)
})
}
pub fn set_search_provider(&mut self, provider: SearchProvider) -> SearchProvider {
self.search
.get_or_insert_with(SearchConfig::default)
.provider = Some(provider);
self.search_provider()
}
#[must_use]
pub fn auto_cost_saving(&self) -> bool {
self.auto
.as_ref()
.and_then(|a| a.cost_saving)
.unwrap_or(false)
}
#[must_use]
pub fn auto_cross_provider(&self) -> bool {
self.auto
.as_ref()
.and_then(|a| a.cross_provider)
.unwrap_or(false)
}
#[must_use]
pub fn auto_router_timeout_secs(&self) -> u64 {
self.auto
.as_ref()
.and_then(|a| a.router.as_ref())
.and_then(|r| r.timeout_secs)
.filter(|secs| *secs > 0)
.unwrap_or(DEFAULT_AUTO_ROUTER_TIMEOUT_SECS)
.min(MAX_AUTO_ROUTER_TIMEOUT_SECS)
}
#[must_use]
pub fn auto_router_min_confidence(&self) -> f64 {
self.auto
.as_ref()
.and_then(|a| a.router.as_ref())
.and_then(|r| r.min_confidence)
.filter(|value| value.is_finite())
.unwrap_or(DEFAULT_AUTO_ROUTER_MIN_CONFIDENCE)
.clamp(0.0, 1.0)
}
#[must_use]
pub fn tools_always_load(&self) -> std::collections::HashSet<String> {
self.tools
.as_ref()
.map(|tools| {
tools
.always_load
.iter()
.map(|name| name.trim())
.filter(|name| !name.is_empty())
.map(ToOwned::to_owned)
.collect()
})
.unwrap_or_default()
}
#[must_use]
pub fn user_input_timeout(&self) -> Option<std::time::Duration> {
const MAX_SECONDS: u64 = 86_400;
let seconds = self
.tools
.as_ref()
.and_then(|tools| tools.user_input_timeout_seconds)?;
if seconds > MAX_SECONDS {
tracing::warn!(
"[tools] user_input_timeout_seconds={seconds} exceeds 24h; clamping to {MAX_SECONDS}"
);
}
Some(std::time::Duration::from_secs(seconds.min(MAX_SECONDS)))
}
#[must_use]
pub fn task_human_wait_cap(&self) -> std::time::Duration {
const DEFAULT_SECONDS: u64 = 30 * 60;
const MAX_SECONDS: u64 = 86_400;
let seconds = self
.tools
.as_ref()
.and_then(|tools| tools.task_human_wait_cap_seconds)
.filter(|seconds| *seconds > 0)
.unwrap_or(DEFAULT_SECONDS);
if seconds > MAX_SECONDS {
tracing::warn!(
"[tools] task_human_wait_cap_seconds={seconds} exceeds 24h; clamping to {MAX_SECONDS}"
);
}
std::time::Duration::from_secs(seconds.min(MAX_SECONDS))
}
#[cfg(any(test, feature = "test-support"))]
pub fn load(path: Option<PathBuf>, profile: Option<&str>) -> Result<Self> {
Self::load_with(path, profile, ConfigEnvironmentPolicy::Runtime, &mut |_| {
Ok(())
})
}
#[cfg(any(test, feature = "test-support"))]
pub fn load_structural(path: Option<PathBuf>, profile: Option<&str>) -> Result<Self> {
Self::load_with(
path,
profile,
ConfigEnvironmentPolicy::StructuralDiagnostic,
&mut |_| Ok(()),
)
}
pub fn from_saved_document(contents: &str, profile: Option<&str>) -> Result<Self> {
let parsed = parse_config_file(contents).map_err(|_| {
anyhow::anyhow!("Failed to parse configuration; file contents were omitted")
})?;
let legacy_root = parsed.legacy_root.clone();
let mut config = apply_profile(parsed, profile)?;
config.account_profile = profile.map(str::to_owned);
config.legacy_root = legacy_root;
Ok(config)
}
pub fn migrated_legacy_ollama_cloud_route(&self) -> bool {
self.migrated_legacy_ollama_cloud_route
}
pub fn load_with(
path: Option<PathBuf>,
profile: Option<&str>,
environment_policy: ConfigEnvironmentPolicy,
extend: &mut dyn FnMut(&mut Config) -> Result<()>,
) -> Result<Self> {
let path = resolve_load_config_path(path)?;
let mut config = if let Some(path) = path.as_ref() {
if path.exists() {
let contents = fs::read_to_string(path)
.with_context(|| format!("Failed to read config file: {}", path.display()))?;
let parsed = Self::from_saved_document(&contents, profile).with_context(|| {
format!(
"Failed to load config file {}",
codewhale_config::quote_os_path(path)
)
})?;
if let Some(msg) = warn_on_misplaced_top_level_keys(&contents) {
tracing::warn!("{msg}");
}
if let Ok(document) = toml::from_str::<toml::Value>(&contents) {
codewhale_config::reject_unmanaged_tool_launcher(&document, path)?;
}
parsed
} else {
apply_profile(ConfigFile::default(), profile)?;
Config::default()
}
} else {
apply_profile(ConfigFile::default(), profile)?;
Config::default()
};
config.account_profile = profile.map(str::to_owned);
if profile.is_none() && path.as_deref().is_some_and(is_home_config_path) {
if let Ok(settings) =
crate::settings::Settings::load_legacy_route_preferences_read_only()
{
config.apply_saved_selection(&settings);
}
config.remembered_selection_scope = Some(true);
} else {
config.remembered_selection_scope = Some(false);
}
apply_env_overrides(&mut config, environment_policy);
apply_managed_overrides(&mut config)?;
apply_requirements(&mut config)?;
extend(&mut config)?;
normalize_model_config(&mut config);
config.exec_policy_engine = load_sibling_exec_policy_engine(path.as_deref())?;
config.loaded_config_path = path.as_deref().map(std::path::absolute).transpose()?;
config.validate()?;
Ok(config)
}
#[cfg(any(test, feature = "test-support"))]
pub fn remembered_selection_is_applicable(&self) -> bool {
self.remembered_selection_scope.unwrap_or(true)
}
pub fn legacy_selection_identity(
&self,
key: &str,
) -> std::result::Result<ProviderIdentity, String> {
if let Ok(active) = self.active_provider_identity()
&& active.key.as_str() == key
{
Ok(active)
} else {
self.resolve_provider_pin_identity(key)
}
}
pub fn apply_saved_selection(&mut self, settings: &crate::settings::Settings) -> bool {
if self.remembered_selection_scope.is_some() {
return false;
}
self.remembered_selection_scope = Some(true);
if self.default_text_model.is_none() {
self.default_text_model.clone_from(&self.legacy_model);
}
if self.fleet_operator_route_applied || self.route_preferences_version.is_some() {
return false;
}
let mut active_changed = false;
if let Some(provider) = settings.default_provider.as_deref()
&& let Ok(identity) = self.resolve_provider_identity(provider)
{
active_changed = self
.active_provider_identity()
.is_ok_and(|active| active != identity);
if self.scope_to_provider_identity(&identity).is_err() {
return false;
}
self.route_provenance.provider_from_saved_selection = true;
}
let mut choices = settings.provider_models.clone().unwrap_or_default();
if let Some(model) = settings.default_model.as_ref() {
for key in [
ProviderKind::Deepseek.as_str(),
codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id,
] {
choices.entry(key.into()).or_insert_with(|| model.clone());
}
}
let mut choices: Vec<_> = choices.into_iter().collect();
choices.sort_by_key(|(key, _)| {
(
self.legacy_selection_identity(key)
.is_ok_and(|identity| identity.key.as_str() == key),
key.clone(),
)
});
for (key, remembered) in choices {
let remembered = remembered.trim();
if remembered.is_empty() || remembered.chars().any(char::is_control) {
continue;
}
let Ok(identity) = self.legacy_selection_identity(&key) else {
continue;
};
let provider = identity.provider;
let mut scoped = self.clone();
if scoped.scope_to_provider_identity(&identity).is_err() {
continue;
}
let configured = scoped
.provider_config_for(&identity)
.and_then(|entry| entry.model.as_deref())
.or_else(|| {
self.active_provider_identity()
.is_ok_and(|active| active == identity)
.then_some(self.default_text_model.as_deref())
.flatten()
})
.unwrap_or_default();
let declared = configured_model_for_route(
&scoped,
provider,
identity.key.as_str(),
&scoped.base_url_for_route(&identity),
remembered,
)
.is_some();
let model = if declared {
remembered.to_string()
} else {
prefer_configured_model_spelling(configured, remembered.to_string())
};
if provider == ProviderKind::Custom && identity.persisted_id().is_some() {
if let Some(entry) = self
.providers
.as_mut()
.and_then(|providers| providers.custom.get_mut(identity.key.as_str()))
{
entry.model = Some(model);
}
} else if identity.migrated_legacy_ollama_cloud_route {
self.providers
.get_or_insert_with(ProvidersConfig::default)
.ollama
.model = Some(model);
} else {
self.set_provider_model_override(&identity, Some(model))
.unwrap();
}
let is_active = self
.active_provider_identity()
.is_ok_and(|active| active == identity);
if is_active {
self.route_provenance.model_from_saved_selection = true;
}
active_changed |= is_active;
}
active_changed
}
pub fn validate(&self) -> Result<()> {
if let Some(skills) = &self.skills {
if skills
.listing_max_description_chars
.is_some_and(|value| !(1..=40_000).contains(&value))
{
anyhow::bail!("[skills] listing_max_description_chars must be between 1 and 40000");
}
if skills
.listing_budget_fraction
.is_some_and(|value| !value.is_finite() || value <= 0.0 || value > 1.0)
{
anyhow::bail!(
"[skills] listing_budget_fraction must be finite and greater than 0 and at most 1"
);
}
}
if let Some(retry) = &self.retry {
for (key, value) in [
("initial_delay", retry.initial_delay),
("max_delay", retry.max_delay),
("exponential_base", retry.exponential_base),
] {
if value.is_some_and(|value| !value.is_finite() || value < 0.0) {
anyhow::bail!("[retry] {key} must be a finite number of at least 0");
}
}
}
if let Some(budget) = self.instruction_budget.as_ref() {
budget
.validate()
.map_err(|error| anyhow::anyhow!("invalid [instruction_budget]: {error}"))?;
}
if let Some(provider) = self.provider.as_deref()
&& !is_legacy_antigravity_identity(provider)
&& compatibility_for_selector(provider).is_none()
&& self
.providers
.as_ref()
.and_then(|providers| providers.custom_provider_config(provider))
.is_none()
{
return Err(invalid_provider_diagnostic(provider).into());
}
let identity = self
.active_provider_identity()
.map_err(anyhow::Error::msg)?;
let active_provider = identity.provider;
codewhale_config::catalog::configured::validate_configured_models(
self.custom_models.as_deref().unwrap_or_default(),
)?;
self.openrouter_vendor()?;
if self
.provider
.as_deref()
.is_some_and(is_legacy_antigravity_identity)
{
anyhow::bail!(codewhale_config::LEGACY_ANTIGRAVITY_TOMBSTONE_MESSAGE);
}
match validate_kimi_code_api_model_id(
active_provider,
&self.active_route_base_url(),
&self.default_model(),
) {
Err(error) if error == KIMI_CODE_CLAUDE_ALIAS_GUIDANCE => {
return Err(SafeConfigDiagnostic::KimiCodeClaudeAlias.into());
}
result => result.map_err(anyhow::Error::msg)?,
}
if let Some(features) = &self.features {
for key in features.entries.keys() {
if !is_known_feature_key(key) {
anyhow::bail!("Unknown feature flag: {key}");
}
}
}
let configured_model = self
.provider_config_string_with_runtime_fallback(&identity, |entry| entry.model.clone())
.or_else(|| self.default_text_model.clone());
if let Some(model) = configured_model.as_deref()
&& !model.trim().eq_ignore_ascii_case("auto")
&& !codewhale_config::descriptors::provider_passes_model_through(active_provider)
&& !self.active_provider_preserves_custom_base_url_model()
&& configured_model_for_route(
self,
active_provider,
identity.key.as_str(),
&self.base_url_for_route(&identity),
model,
)
.is_none()
&& codewhale_config::route::resolve_model(active_provider, model, None).is_err()
{
let provider = active_provider;
let known = model_completion_names_for_provider(provider);
let hint = if known.is_empty() {
String::new()
} else {
format!(" (for example: {})", known.join(", "))
};
return Err(SafeConfigDiagnostic::invalid_value(
"model",
model,
&format!(
"auto or a model ID provider '{}' serves{hint}",
provider.as_str()
),
user_config_fix("model", "auto", Some("a *_MODEL environment variable")),
)
.into());
}
for (key, value, replacement, env_var) in [
(
"approval_policy",
self.approval_policy.as_deref(),
"on-request",
Some("CODEWHALE_APPROVAL_POLICY"),
),
("verbosity", self.verbosity.as_deref(), "normal", None),
(
"sandbox_mode",
self.sandbox_mode.as_deref(),
"workspace-write",
Some("CODEWHALE_SANDBOX_MODE"),
),
] {
let (Some(value), Some(choices)) = (value, codewhale_config::config_toml_choices(key))
else {
continue;
};
if !choices.contains(&value.trim().to_ascii_lowercase().as_str()) {
let expected = match choices.split_last() {
Some((last, [])) => (*last).to_string(),
Some((last, [only])) => format!("{only} or {last}"),
Some((last, rest)) => format!("{}, or {last}", rest.join(", ")),
None => String::new(),
};
let displayed_value = codewhale_sanitize::redact::redact_secrets(value);
return Err(SafeConfigDiagnostic::invalid_value(
key,
&displayed_value,
&expected,
user_config_fix(key, replacement, env_var),
)
.into());
}
}
if let Some(tui) = &self.tui
&& let Some(mode) = tui.alternate_screen.as_deref()
{
let mode = mode.to_ascii_lowercase();
if !matches!(mode.as_str(), "auto" | "always" | "never") {
return Err(SafeConfigDiagnostic::invalid_value(
"tui.alternate_screen",
&mode,
"auto, always, or never",
user_config_fix("tui.alternate_screen", "auto", None),
)
.into());
}
}
if let Some(transcript) = &self.transcript
&& let Err(detail) = transcript.prose_measure_columns()
{
anyhow::bail!("Invalid transcript.prose_measure: {detail}.");
}
if let Some(auto_review) = &self.auto_review {
auto_review.validate()?;
if auto_review.disabled
&& self
.approval_policy
.as_deref()
.and_then(codewhale_execpolicy::ApprovalMode::from_config_value)
== Some(codewhale_execpolicy::ApprovalMode::Auto)
{
anyhow::bail!(
"approval_policy = \"auto\" is disabled by managed configuration (`auto_review.disabled = true`)"
);
}
}
if let Some(providers) = &self.providers {
providers.validate()?;
}
Ok(())
}
#[must_use]
pub fn prose_measure(&self) -> Option<u16> {
self.transcript
.as_ref()
.and_then(|transcript| transcript.prose_measure_columns().ok().flatten())
}
#[must_use]
fn selects_legacy_ollama_cloud_route(&self) -> bool {
if self.migrated_legacy_ollama_cloud_route {
return true;
}
if self.provider.as_deref().and_then(ProviderKind::parse) != Some(ProviderKind::Ollama) {
return false;
}
self.legacy_ollama_cloud_route_configured()
}
fn legacy_ollama_cloud_route_configured(&self) -> bool {
let base_url = self
.providers
.as_ref()
.and_then(|providers| providers.ollama.base_url.as_deref())
.map(str::to_string)
.or_else(|| first_nonempty_env(&["OLLAMA_BASE_URL"]));
base_url.is_some_and(|base_url| {
codewhale_config::provider::migrates_legacy_ollama_cloud_route(
codewhale_config::ProviderKind::Ollama,
&base_url,
)
})
}
pub fn active_provider_identity(&self) -> std::result::Result<ProviderIdentity, String> {
let selected = self
.provider
.as_deref()
.unwrap_or(ProviderKind::Deepseek.as_str());
if self.migrated_legacy_ollama_cloud_route && selected == ProviderKind::OllamaCloud.as_str()
{
return self.resolve_persisted_provider_identity(
Some(ProviderKind::OllamaCloud.as_str()),
Some(ProviderKind::Ollama.as_str()),
);
}
if is_legacy_antigravity_identity(selected) {
return Ok(ProviderIdentity {
provider: ProviderKind::Antigravity,
key: ProviderId::from(ProviderKind::Antigravity.as_str()),
exact_id: Some(ProviderId::from(ProviderKind::Antigravity.as_str())),
migrated_legacy_ollama_cloud_route: false,
legacy_root_custom_generation: None,
});
}
if self.selects_literal_custom_provider()
&& self.current_legacy_root_custom_generation().is_some()
{
return self.resolve_persisted_provider_identity(Some("custom"), None);
}
self.resolve_provider_identity(selected)
}
#[cfg(any(test, feature = "test-support"))]
pub fn test_identity_for_kind(&self, kind: ProviderKind) -> ProviderIdentity {
if let Ok(active) = self.active_provider_identity()
&& active.provider == kind
{
return active;
}
self.builtin_provider_identity(kind)
.expect("test fixture must declare an admitted provider identity")
}
pub fn provider_identities(&self) -> Vec<ProviderIdentity> {
let active = self.active_provider_identity().ok();
let mut identities = Vec::new();
for row in codewhale_config::descriptors::provider_compatibility() {
if row.kind == ProviderKind::Custom {
continue;
}
let identity = active
.as_ref()
.filter(|identity| identity.key.as_str() == row.id)
.cloned()
.or_else(|| self.resolve_provider_pin_identity(row.id).ok());
if let Some(identity) = identity
&& identity.provider == row.kind
&& !identities
.iter()
.any(|existing: &ProviderIdentity| existing == &identity)
{
identities.push(identity);
}
}
if let Some(active) = active
&& !identities.contains(&active)
{
identities.push(active);
}
if let Some(providers) = &self.providers {
for key in providers.custom.keys() {
if let Ok(identity) = self.resolve_provider_pin_identity(key)
&& !identities
.iter()
.any(|existing| existing.key == identity.key)
{
identities.push(identity);
}
}
}
identities
}
pub fn unadmitted_provider_keys(&self) -> Vec<&str> {
let admitted = self.provider_identities();
let mut keys = Vec::new();
if let Some(providers) = &self.providers {
keys.extend(providers.custom.keys().map(String::as_str).filter(|key| {
!admitted
.iter()
.any(|identity| identity.key.as_str() == *key)
}));
}
if let Some(key) = self.provider.as_deref()
&& self.active_provider_identity().is_err()
&& !keys.contains(&key)
{
keys.push(key);
}
keys.sort_unstable();
keys
}
pub fn builtin_provider_identity(
&self,
kind: ProviderKind,
) -> std::result::Result<ProviderIdentity, String> {
self.resolve_persisted_provider_identity(Some(kind.as_str()), Some(kind.as_str()))
}
pub fn resolve_provider_identity(
&self,
persisted: &str,
) -> std::result::Result<ProviderIdentity, String> {
let key = persisted.trim();
if key.is_empty() {
return Err(
"saved session has an empty provider identity; choose a valid session or repair its `metadata.model_provider` field"
.to_string(),
);
}
let has_exact_custom_table = self
.providers
.as_ref()
.and_then(|providers| providers.custom_provider_config(key))
.is_some();
if !has_exact_custom_table
&& let Some(row) = compatibility_for_selector(key)
&& row.kind != ProviderKind::Antigravity
&& row.kind != ProviderKind::Custom
{
let mut provider = row.kind;
let migrated_legacy_ollama_cloud_route =
provider == ProviderKind::Ollama && self.legacy_ollama_cloud_route_configured();
if provider == ProviderKind::Ollama && migrated_legacy_ollama_cloud_route {
provider = ProviderKind::OllamaCloud;
}
return Ok(ProviderIdentity {
provider,
key: ProviderId::from(if migrated_legacy_ollama_cloud_route {
provider.as_str()
} else {
row.id
}),
exact_id: Some(if migrated_legacy_ollama_cloud_route {
ProviderId::from(ProviderKind::Ollama.as_str())
} else {
ProviderId::from(row.id)
}),
migrated_legacy_ollama_cloud_route,
legacy_root_custom_generation: None,
});
}
if !has_exact_custom_table && key.eq_ignore_ascii_case(ProviderKind::Custom.as_str()) {
if self.selects_literal_custom_provider() {
return Err(
"`provider = \"custom\"` requires a `[providers.custom]` table with a `base_url`; Codewhale will not use the custom-provider placeholder or fall back"
.to_string(),
);
}
if !self.selects_literal_custom_provider() {
let selected = self.provider.as_deref().map(str::trim).unwrap_or_default();
let valid_named = self
.providers
.as_ref()
.map(|providers| {
providers
.custom
.keys()
.filter(|name| {
!name.eq_ignore_ascii_case(ProviderKind::Custom.as_str())
&& ProviderKind::parse(name).is_none()
&& self.resolve_provider_identity(name).is_ok()
})
.cloned()
.collect::<Vec<_>>()
})
.unwrap_or_default();
if let [name] = valid_named.as_slice()
&& selected == name
{
return self.resolve_provider_identity(name);
}
return Err(format!(
"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",
if selected.is_empty() {
"<unset>"
} else {
selected
},
valid_named.len()
));
}
}
let exact_key = key;
let entry = self
.providers
.as_ref()
.and_then(|providers| providers.custom_provider_config(exact_key))
.ok_or_else(|| {
format!(
"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"
)
})?;
if !entry.is_openai_compatible_custom() {
return Err(format!(
"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"
));
}
let base_url = entry
.base_url
.as_deref()
.map(str::trim)
.filter(|base_url| !base_url.is_empty())
.ok_or_else(|| {
format!(
"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"
)
})?;
let parsed = reqwest::Url::parse(base_url).map_err(|err| {
format!(
"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"
)
})?;
if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
return Err(format!(
"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"
));
}
Ok(ProviderIdentity {
provider: ProviderKind::Custom,
key: ProviderId::from(exact_key),
exact_id: Some(ProviderId::from(exact_key)),
migrated_legacy_ollama_cloud_route: false,
legacy_root_custom_generation: None,
})
}
pub fn resolve_provider_pin_identity(
&self,
provider_id: &str,
) -> std::result::Result<ProviderIdentity, String> {
let mut identity = self.resolve_provider_identity(provider_id)?;
if provider_id
.trim()
.eq_ignore_ascii_case(ProviderKind::Custom.as_str())
&& !identity
.key
.as_str()
.eq_ignore_ascii_case(ProviderKind::Custom.as_str())
{
return Err(format!(
"an explicit provider pin must name the configured provider '{}'; `custom` is not a wildcard for a named provider",
identity.key
));
}
if identity.provider == ProviderKind::OllamaCloud
&& ProviderKind::parse(provider_id.trim()) == Some(ProviderKind::OllamaCloud)
{
identity.migrated_legacy_ollama_cloud_route = false;
}
Ok(identity)
}
pub fn resolve_provider_selection_identity(
&self,
provider_id: &str,
) -> std::result::Result<ProviderIdentity, String> {
let requested = provider_id.trim();
if !requested.is_empty()
&& compatibility_for_selector(requested).is_none()
&& !requested.eq_ignore_ascii_case(ProviderKind::Custom.as_str())
&& self
.providers
.as_ref()
.and_then(|providers| providers.custom_provider_config(requested))
.is_none()
{
return Err(invalid_provider_message(requested));
}
if is_legacy_antigravity_identity(requested) {
return Err("Antigravity is retired and cannot be selected".to_string());
}
self.resolve_provider_pin_identity(provider_id)
}
fn resolve_exact_provider_identity(
&self,
persisted: &str,
) -> std::result::Result<ProviderIdentity, String> {
let id = persisted.trim();
if id.is_empty() {
return Err(
"persisted provider route has an empty exact provider id; Codewhale will not guess or fall back"
.to_string(),
);
}
let has_exact_custom_table = self
.providers
.as_ref()
.and_then(|providers| providers.custom_provider_config(id))
.is_some();
if id.eq_ignore_ascii_case(ProviderKind::Custom.as_str()) && !has_exact_custom_table {
return Err(format!(
"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"
));
}
let identity = self.resolve_provider_identity(id)?;
if identity.provider == ProviderKind::Custom && identity.persisted_id() != Some(id) {
return Err(format!(
"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"
));
}
Ok(identity)
}
pub fn resolve_persisted_provider_identity(
&self,
provider_kind: Option<&str>,
provider_id: Option<&str>,
) -> std::result::Result<ProviderIdentity, String> {
let kind = provider_kind
.map(str::trim)
.filter(|value| !value.is_empty());
let id = provider_id.map(str::trim);
let Some(kind) = kind else {
return id.map_or_else(
|| {
Err(
"persisted provider route has neither a provider kind nor an exact provider id; Codewhale will not guess or fall back"
.to_string(),
)
},
|id| self.resolve_exact_provider_identity(id),
);
};
let source =
compatibility_for_selector(kind).filter(|row| row.kind != ProviderKind::Antigravity);
let Some(mut provider) = source.map(|row| row.kind) else {
if let Some(id) = id
&& id != kind
{
return Err(format!(
"persisted provider route has legacy identity '{kind}' but exact provider id '{id}'; repair the mismatched fields because Codewhale will not guess or fall back"
));
}
return match id {
Some(id) => self.resolve_exact_provider_identity(id),
None => self.resolve_provider_identity(kind),
};
};
let migrated_legacy_ollama_cloud = (provider == ProviderKind::Ollama
&& self.legacy_ollama_cloud_route_configured())
|| (provider == ProviderKind::OllamaCloud
&& id.and_then(ProviderKind::parse) == Some(ProviderKind::Ollama)
&& self.legacy_ollama_cloud_route_configured());
if migrated_legacy_ollama_cloud {
provider = ProviderKind::OllamaCloud;
}
if provider == ProviderKind::Custom {
if let Some(id) = id {
let identity = self.resolve_exact_provider_identity(id)?;
if identity.provider != ProviderKind::Custom {
return Err(format!(
"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",
identity.provider.as_str()
));
}
return Ok(identity);
}
let generation = self.current_legacy_root_custom_generation().filter(|_| self.selects_literal_custom_provider()).ok_or_else(|| {
"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()
})?;
let mut identity =
self.resolve_exact_provider_identity(ProviderKind::Custom.as_str())?;
identity.exact_id = None;
identity.legacy_root_custom_generation = Some(generation);
return Ok(identity);
}
let exact = id.and_then(compatibility_for_selector);
if let Some(id) = id
&& (exact.is_none_or(|row| row.kind != provider)
|| source.is_some_and(|row| {
row.id != row.kind.as_str() && exact.is_some_and(|exact| exact.id != row.id)
}))
&& !(migrated_legacy_ollama_cloud
&& ProviderKind::parse(id) == Some(ProviderKind::Ollama))
{
return Err(format!(
"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",
provider.as_str()
));
}
let key = if migrated_legacy_ollama_cloud {
provider.as_str()
} else {
exact.or(source).expect("parsed built-in compatibility").id
};
if self
.providers
.as_ref()
.and_then(|providers| providers.custom_provider_config(key))
.is_some()
{
return Err(format!(
"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",
provider.as_str(),
provider.as_str()
));
}
Ok(ProviderIdentity {
provider,
key: ProviderId::from(key),
exact_id: Some(if migrated_legacy_ollama_cloud {
ProviderId::from(ProviderKind::Ollama.as_str())
} else {
ProviderId::from(key)
}),
migrated_legacy_ollama_cloud_route: migrated_legacy_ollama_cloud,
legacy_root_custom_generation: None,
})
}
pub fn scope_to_provider_identity(
&mut self,
identity: &ProviderIdentity,
) -> std::result::Result<(), String> {
self.verify_provider_identity(identity)?;
self.migrated_legacy_ollama_cloud_route = identity.migrated_legacy_ollama_cloud_route;
self.provider = Some(identity.key.to_string());
Ok(())
}
fn legacy_root_custom_table_generation(
&self,
) -> Option<codewhale_config::credentials::CredentialGeneration> {
let entry = self.providers.as_ref()?.custom.get("custom")?;
let value = serde_json::to_value(entry).ok()?;
Some(codewhale_config::credentials::CredentialGeneration::derive(
"codewhale/legacy-root-custom-table/v1",
&crate::hashing::canonical_json(&value),
))
}
fn bind_legacy_root_custom_generation(&mut self) {
use codewhale_config::legacy_root::{LegacyRootField, LegacyRootNote};
let moved = self.legacy_root.notes.iter().any(|note| {
matches!(note,
LegacyRootNote::Moved { scope: None, field: LegacyRootField::BaseUrl, to }
| LegacyRootNote::Merged { scope: None, field: LegacyRootField::BaseUrl, to }
if to == "providers.custom"
)
});
let conflicting = self.legacy_root.notes.iter().any(|note| {
matches!(
note,
LegacyRootNote::Conflict {
scope: None,
field: LegacyRootField::BaseUrl,
..
} | LegacyRootNote::DroppedEmpty {
scope: None,
field: LegacyRootField::BaseUrl
}
)
});
self.legacy_root_custom_generation =
(moved && !conflicting && self.selects_literal_custom_provider())
.then(|| self.legacy_root_custom_table_generation())
.flatten();
}
fn current_legacy_root_custom_generation(
&self,
) -> Option<codewhale_config::credentials::CredentialGeneration> {
let captured = self.legacy_root_custom_generation.as_ref()?;
let current = self.legacy_root_custom_table_generation()?;
(captured == ¤t).then_some(current)
}
pub fn selects_literal_custom_provider(&self) -> bool {
self.provider
.as_deref()
.map(str::trim)
.is_some_and(|name| name.eq_ignore_ascii_case(ProviderKind::Custom.as_str()))
}
#[cfg(test)]
pub(crate) fn custom_identity_is_resolvable(&self, identity: &str) -> bool {
self.custom_provider_entry_for_identity(identity).is_some()
}
pub fn provider_wire_dialect(&self, identity: &ProviderIdentity) -> Option<&str> {
self.provider_config_for(identity)?
.wire
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
}
pub fn provider_responses_profile(&self, identity: &ProviderIdentity) -> Option<&str> {
self.provider_config_for(identity)?
.responses_profile
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
}
pub fn verify_provider_identity(
&self,
identity: &ProviderIdentity,
) -> std::result::Result<(), String> {
let admitted = self.resolve_persisted_provider_identity(
Some(identity.persisted_kind()),
identity.persisted_id(),
)?;
if admitted == *identity {
Ok(())
} else {
Err("provider identity changed before projection".into())
}
}
pub fn provider_config_for(&self, identity: &ProviderIdentity) -> Option<&ProviderConfig> {
let providers = self.providers.as_ref()?;
self.verify_provider_identity(identity).ok()?;
if identity.provider == ProviderKind::Custom {
return providers.custom_provider_config(identity.key.as_str());
}
let table = if identity.migrated_legacy_ollama_cloud_route {
ProviderKind::Ollama.as_str()
} else {
identity.key.as_str()
};
codewhale_config::provider_config_table!(@read providers, table)
}
pub fn openrouter_vendor(&self) -> Result<Option<String>> {
let identity = self
.active_provider_identity()
.map_err(anyhow::Error::msg)?;
let provider = identity.provider;
let Some(vendor) = self
.provider_config_for(&identity)
.and_then(|entry| entry.vendor.as_deref())
else {
return Ok(None);
};
let vendor = codewhale_config::validate_openrouter_vendor(vendor)?;
if vendor.is_some() && provider != ProviderKind::Openrouter {
anyhow::bail!("vendor is only supported by providers.openrouter");
}
Ok(vendor.map(str::to_string))
}
pub fn subagent_provider_config(
&self,
identity: &ProviderIdentity,
) -> Option<&SubagentProviderConfig> {
let providers = self.subagents.as_ref()?.providers.as_ref()?;
providers.iter().find_map(|(key, config)| {
let matches = if identity.provider == ProviderKind::Custom {
key == identity.key.as_str()
} else if let Some(row) = identity.compatibility() {
let normalized = normalize_subagent_provider_key(key);
compatibility_for_selector(key).is_some_and(|candidate| candidate.id == row.id)
|| normalized == normalize_subagent_provider_key(row.id)
|| row.subagent_aliases.contains(&normalized.as_str())
} else {
false
};
matches.then_some(config)
})
}
pub fn provider_config_for_mut(
&mut self,
identity: &ProviderIdentity,
) -> Result<&mut ProviderConfig> {
self.verify_provider_identity(identity)
.map_err(anyhow::Error::msg)?;
let providers = self.providers.get_or_insert_with(ProvidersConfig::default);
if identity.provider == ProviderKind::Custom {
return providers
.custom
.get_mut(identity.key.as_str())
.context("exact custom provider table missing before mutation");
}
let table = if identity.migrated_legacy_ollama_cloud_route {
ProviderKind::Ollama.as_str()
} else {
identity.key.as_str()
};
codewhale_config::provider_config_table!(@write providers, table)
.context("provider has no generated typed config table")
}
pub fn set_provider_model_override(
&mut self,
identity: &ProviderIdentity,
model: Option<String>,
) -> Result<()> {
self.provider_config_for_mut(identity)?.model = model;
if identity.legacy_root_custom_generation.is_some() {
self.legacy_root_custom_generation = self.legacy_root_custom_table_generation();
}
Ok(())
}
pub fn set_provider_base_url_override(
&mut self,
identity: &ProviderIdentity,
base_url: Option<String>,
) -> Result<()> {
self.provider_config_for_mut(identity)?.base_url = base_url;
Ok(())
}
pub fn set_provider_api_key_override(
&mut self,
identity: &ProviderIdentity,
api_key: Option<String>,
) -> Result<()> {
self.provider_config_for_mut(identity)?.api_key = api_key;
Ok(())
}
pub(crate) fn mark_codewhale_owned_xai_oauth(&mut self, generation: String) -> Result<()> {
let identity = self
.builtin_provider_identity(ProviderKind::Xai)
.map_err(anyhow::Error::msg)?;
let entry = self.provider_config_for_mut(&identity)?;
entry.auth_mode = Some("oauth".to_string());
entry.oauth_credential_generation = Some(generation);
entry.external_credentials = None;
Ok(())
}
pub(crate) fn mark_codewhale_owned_chatgpt_oauth(&mut self, generation: String) -> Result<()> {
let identity = self
.builtin_provider_identity(ProviderKind::OpenaiCodex)
.map_err(anyhow::Error::msg)?;
let entry = self.provider_config_for_mut(&identity)?;
entry.auth_mode = Some("oauth".to_string());
entry.oauth_credential_generation = Some(generation);
entry.external_credentials = None;
Ok(())
}
pub fn clear_codewhale_owned_chatgpt_oauth(&mut self) -> Result<()> {
let identity = self
.builtin_provider_identity(ProviderKind::OpenaiCodex)
.map_err(anyhow::Error::msg)?;
let entry = self.provider_config_for_mut(&identity)?;
if entry
.oauth_credential_generation
.as_deref()
.is_some_and(codewhale_config::is_valid_chatgpt_oauth_generation)
{
entry.oauth_credential_generation = None;
if entry.auth_mode.as_deref() == Some("oauth") {
entry.auth_mode = None;
}
}
Ok(())
}
pub fn refresh_provider_routes_from(&mut self, fresh: &Self) {
self.custom_models.clone_from(&fresh.custom_models);
self.provider.clone_from(&fresh.provider);
self.http_headers.clone_from(&fresh.http_headers);
self.default_text_model
.clone_from(&fresh.default_text_model);
self.legacy_model.clone_from(&fresh.legacy_model);
self.remembered_selection_scope = fresh.remembered_selection_scope;
self.route_preferences_version = fresh.route_preferences_version;
self.environment_model_applied = fresh.environment_model_applied;
self.auth_mode.clone_from(&fresh.auth_mode);
self.fallback_providers
.clone_from(&fresh.fallback_providers);
self.retry.clone_from(&fresh.retry);
self.providers.clone_from(&fresh.providers);
self.base_url_env_receipt
.clone_from(&fresh.base_url_env_receipt);
self.legacy_root.clone_from(&fresh.legacy_root);
self.legacy_root_custom_generation
.clone_from(&fresh.legacy_root_custom_generation);
self.reasoning_effort_inferred_from_legacy_alias =
fresh.reasoning_effort_inferred_from_legacy_alias;
self.migrated_deepseek_model_alias
.clone_from(&fresh.migrated_deepseek_model_alias);
}
#[must_use]
pub fn provider_max_concurrency(&self, identity: &ProviderIdentity) -> Option<usize> {
let provider = identity.provider;
let configured = self
.provider_config_for(identity)
.and_then(|entry| entry.max_concurrency);
match configured {
Some(0) => None,
Some(limit) => Some(limit.clamp(1, MAX_PROVIDER_REQUEST_CONCURRENCY)),
None if provider == ProviderKind::Zai => Some(DEFAULT_ZAI_PROVIDER_MAX_CONCURRENCY),
None => None,
}
}
pub fn provider_config(&self) -> Option<&ProviderConfig> {
let identity = self.active_provider_identity().ok()?;
self.provider_config_for(&identity)
}
fn provider_config_string_with_runtime_fallback<F>(
&self,
identity: &ProviderIdentity,
get: F,
) -> Option<String>
where
F: Fn(&ProviderConfig) -> Option<String>,
{
let provider = identity.provider;
if let Some(value) = self.provider_config_for(identity).and_then(&get) {
return Some(value);
}
if provider == ProviderKind::SiliconflowCN {
return self
.builtin_provider_identity(ProviderKind::Siliconflow)
.ok()
.as_ref()
.and_then(|sibling| self.provider_config_for(sibling))
.and_then(get);
}
None
}
pub(crate) fn provider_route_string_with_deepseek_fallback<F>(
&self,
identity: &ProviderIdentity,
get: F,
) -> Option<String>
where
F: Fn(&ProviderConfig) -> Option<String>,
{
if let Some(value) = self.provider_config_string_with_runtime_fallback(identity, &get) {
return Some(value);
}
if identity.key.as_str() == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id
&& !matches!(
&self.base_url_env_receipt,
BaseUrlEnvReceipt::Route(ProviderKind::Deepseek, key) if key == ProviderKind::Deepseek.as_str()
)
{
return self
.builtin_provider_identity(ProviderKind::Deepseek)
.ok()
.as_ref()
.and_then(|sibling| self.provider_config_for(sibling))
.and_then(get)
.filter(|value| !value.trim().is_empty());
}
None
}
#[must_use]
pub fn insecure_skip_tls_verify(&self) -> bool {
self.provider_config()
.and_then(|provider| provider.insecure_skip_tls_verify)
.unwrap_or(false)
}
#[must_use]
pub fn allow_insecure_http(&self) -> bool {
self.provider_config()
.and_then(|provider| provider.allow_insecure_http)
.unwrap_or(false)
}
#[must_use]
pub fn context_window_for_provider_config(&self, identity: &ProviderIdentity) -> Option<u32> {
let provider = identity.provider;
if let Some(window) = self
.provider_config_for(identity)
.and_then(|entry| entry.context_window)
.filter(|window| *window > 0)
{
return Some(window);
}
if provider == ProviderKind::SiliconflowCN {
return self
.builtin_provider_identity(ProviderKind::Siliconflow)
.ok()
.as_ref()
.and_then(|sibling| self.provider_config_for(sibling))
.and_then(|entry| entry.context_window)
.filter(|window| *window > 0);
}
None
}
#[must_use]
pub fn model_context_windows_for(
&self,
identity: &ProviderIdentity,
) -> Option<&std::collections::BTreeMap<String, u32>> {
let provider = identity.provider;
let table = self
.provider_config_for(identity)
.and_then(|entry| entry.model_context_windows.as_ref())
.filter(|table| !table.is_empty());
if table.is_some() {
return table;
}
if provider == ProviderKind::SiliconflowCN {
return self
.builtin_provider_identity(ProviderKind::Siliconflow)
.ok()
.as_ref()
.and_then(|sibling| self.provider_config_for(sibling))
.and_then(|entry| entry.model_context_windows.as_ref())
.filter(|table| !table.is_empty());
}
None
}
#[must_use]
pub fn http_headers(&self) -> HashMap<String, String> {
let Ok(identity) = self.active_provider_identity() else {
return HashMap::new();
};
let mut headers = self.http_headers.clone().unwrap_or_default();
if let Some(provider_headers) = self
.provider_config_for(&identity)
.and_then(|provider| provider.http_headers.as_ref())
{
headers.extend(provider_headers.clone());
}
headers.retain(|name, value| !name.trim().is_empty() && !value.trim().is_empty());
if auth_mode_disables_api_key(self.auth_mode_for_provider(&identity).as_deref()) {
headers.retain(|name, _| !codewhale_config::is_upstream_auth_header(name));
}
headers
}
fn active_configured_model_id(&self) -> Option<&str> {
let identity = self.active_provider_identity().ok()?;
self.provider_config_for(&identity)
.and_then(|entry| entry.model.as_deref())
.map(str::trim)
.filter(|model| !model.is_empty())
.or_else(|| {
self.default_text_model
.as_deref()
.map(str::trim)
.filter(|model| !model.is_empty())
})
}
pub fn active_deepseek_alias_deprecation(&self) -> Option<ModelAliasDeprecation> {
let identity = self.active_provider_identity().ok()?;
let provider = identity.provider;
if !matches!(
provider,
ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
) {
return None;
}
let alias = self
.migrated_deepseek_model_alias
.as_deref()
.or_else(|| self.active_configured_model_id())?
.trim()
.to_ascii_lowercase();
let base_url = self.active_route_base_url();
if base_url_is_custom_for_provider(provider, &base_url) {
return None;
}
deepseek_alias_deprecation(&alias)
}
pub fn root_model_alias_owned_by_outgoing(
&self,
incoming: &ProviderIdentity,
) -> Option<(ProviderIdentity, String)> {
let value = self
.default_text_model
.as_deref()
.or(self.legacy_model.as_deref())?
.trim();
if value.is_empty()
|| value.eq_ignore_ascii_case("auto")
|| value.chars().any(char::is_control)
{
return None;
}
let outgoing = self.active_provider_identity().ok()?;
if outgoing == *incoming
|| (outgoing.provider == ProviderKind::Custom && outgoing.persisted_id().is_none())
{
return None;
}
let mut scoped = self.clone();
scoped.scope_to_provider_identity(&outgoing).ok()?;
if scoped
.provider_config_for(&outgoing)
.and_then(|entry| entry.model.as_deref())
.is_some()
{
return None;
}
(scoped.default_model() == value).then(|| (outgoing, value.to_string()))
}
fn select_configured_model(
&self,
identity: &ProviderIdentity,
) -> codewhale_config::ConfiguredModelSelection {
let provider = identity.provider;
let base_url = self.base_url_for_route(identity);
let auth_mode = self.auth_mode_for_provider(identity);
let provider_model = self
.provider_config_string_with_runtime_fallback(identity, |entry| entry.model.clone());
let codex_preferred = || {
crate::codex_model_roster::cached_roster_for(self)
.preferred_model_id()
.map(str::to_owned)
};
let descriptor_default = Some(identity.compatibility().map_or("", |row| row.default_model));
codewhale_config::resolve_configured_model(&codewhale_config::ConfiguredModelInputs {
provider,
provider_identity: identity.key.as_str(),
base_url: &base_url,
auth_mode: auth_mode.as_deref(),
cli_model: None,
env_model: None,
provider_model: provider_model.as_deref(),
default_text_model: self.default_text_model.as_deref(),
legacy_root_model: self.legacy_model.as_deref(),
custom_models: self.custom_models.as_deref(),
codex_preferred_model: (provider == ProviderKind::OpenaiCodex)
.then_some(&codex_preferred as &dyn Fn() -> Option<String>),
descriptor_default,
})
}
#[must_use]
pub fn default_model(&self) -> String {
let Ok(identity) = self.active_provider_identity() else {
return String::new();
};
self.select_configured_model(&identity)
.resolved
.map_or_else(|_| String::new(), |resolved| resolved.wire_id)
}
#[must_use]
pub fn default_model_uses_root_default_text_model(&self) -> bool {
let Ok(identity) = self.active_provider_identity() else {
return false;
};
let selection = self.select_configured_model(&identity);
selection.resolved.is_ok()
&& matches!(
selection.source,
codewhale_config::ModelSource::RootDefaultTextModel
| codewhale_config::ModelSource::RootModel
)
}
#[must_use]
pub fn configured_model_error(&self) -> Option<String> {
let identity = self.active_provider_identity().ok()?;
let selection = self.select_configured_model(&identity);
match selection.resolved {
Ok(_) => None,
Err(_) if !selection.source.is_explicit() && selection.raw.is_empty() => None,
Err(error) => Some(codewhale_config::format_configured_model_error(
identity.key.as_str(),
&selection.raw,
&error,
)),
}
}
#[must_use]
pub fn active_route_base_url(&self) -> String {
self.active_provider_identity()
.map(|identity| self.base_url_for_route(&identity))
.unwrap_or_default()
}
pub fn base_url_for_route(&self, identity: &ProviderIdentity) -> String {
if self.verify_provider_identity(identity).is_err() {
return String::new();
}
let provider = identity.provider;
let provider_base = if provider == ProviderKind::Custom {
self.provider_config_for(identity)
.and_then(|entry| entry.base_url.clone())
} else {
self.provider_route_string_with_deepseek_fallback(identity, |entry| {
entry.base_url.clone()
})
};
let configured_base_url =
provider_base.or_else(|| provider_env_base_url_override(provider));
let entry = self.provider_config_for(identity);
let mode = entry.and_then(|e| e.mode.as_deref());
let wire = entry.and_then(|e| e.wire.as_deref());
let base = if provider == ProviderKind::XiaomiMimo {
let config_api_key = entry.and_then(|e| e.api_key.as_deref()).filter(|value| {
classify_config_api_key_value(value) == ConfigApiKeyValueKind::Literal
});
let env_api_key =
xiaomi_mimo_env_api_key_for_runtime(mode, configured_base_url.as_deref());
let api_key = config_api_key.or(env_api_key.as_deref());
resolve_xiaomi_mimo_base_url(configured_base_url, api_key, mode)
} else if matches!(
provider,
ProviderKind::ModelstudioTokenPlan
| ProviderKind::ModelstudioTokenPlanAnthropic
| ProviderKind::ModelstudioCodingPlan
| ProviderKind::ModelstudioCodingPlanAnthropic
) {
resolve_modelstudio_base_url_for_tui(configured_base_url, provider, mode, wire)
} else if matches!(
provider,
ProviderKind::Minimax | ProviderKind::MinimaxAnthropic
) {
resolve_minimax_base_url_for_tui(configured_base_url, provider, wire)
} else if matches!(
provider,
ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
) {
resolve_deepseek_base_url_for_tui(configured_base_url, provider, wire)
} else {
configured_base_url
.or_else(|| self.route_owned_generic_env_base_url(identity))
.unwrap_or_else(|| {
if provider == ProviderKind::Moonshot
&& self
.provider_config_for(identity)
.is_some_and(provider_config_uses_kimi_imported_token)
{
DEFAULT_KIMI_CODE_BASE_URL
} else {
identity.compatibility().map_or("", |row| row.base_url)
}
.to_string()
})
};
normalize_base_url(&base)
}
fn route_owned_generic_env_base_url(&self, identity: &ProviderIdentity) -> Option<String> {
match &self.base_url_env_receipt {
BaseUrlEnvReceipt::Unrecorded => env_base_url_override(),
BaseUrlEnvReceipt::NoOwner => None,
BaseUrlEnvReceipt::Route(..) => self
.base_url_env_receipt
.owns(identity.provider, identity.key.as_str())
.then(env_base_url_override)
.flatten(),
}
}
#[cfg(test)]
fn custom_provider_entry_for_identity(&self, identity: &str) -> Option<&ProviderConfig> {
let key = identity.trim();
if key.is_empty() {
return None;
}
self.providers.as_ref()?.custom_provider_config(key)
}
fn active_provider_preserves_custom_base_url_model(&self) -> bool {
self.active_provider_identity()
.is_ok_and(|identity| self.provider_uses_custom_endpoint(&identity))
}
pub fn provider_uses_custom_endpoint(&self, identity: &ProviderIdentity) -> bool {
let provider = identity.provider;
provider_preserves_custom_base_url_model(provider, &self.base_url_for_route(identity))
}
pub fn config_credentials_are_bound_to_provider_endpoint(
&self,
identity: &ProviderIdentity,
) -> bool {
!self
.active_provider_identity()
.is_ok_and(|active| active == *identity)
|| !self.active_base_url_is_environment_owned(identity)
|| !self.provider_uses_custom_endpoint(identity)
}
fn active_base_url_is_environment_owned(&self, identity: &ProviderIdentity) -> bool {
let provider = identity.provider;
if !self
.active_provider_identity()
.is_ok_and(|active| active == *identity)
{
return false;
}
let route_key = identity.key.as_str();
if self.base_url_env_receipt.owns(provider, route_key) {
return true;
}
if self.configured_base_url_for_provider(identity).is_some() {
return false;
}
provider_env_base_url_override(provider).is_some()
|| (matches!(self.base_url_env_receipt, BaseUrlEnvReceipt::Unrecorded)
&& env_base_url_override().is_some())
}
pub fn active_route_endpoint_configured(&self) -> bool {
self.active_provider_identity().is_ok_and(|identity| {
self.configured_base_url_for_provider(&identity).is_some()
|| self.active_base_url_is_environment_owned(&identity)
})
}
fn configured_base_url_for_provider(&self, identity: &ProviderIdentity) -> Option<String> {
self.provider_route_string_with_deepseek_fallback(identity, |entry| entry.base_url.clone())
.filter(|base| !base.trim().is_empty())
}
pub fn model_ids_pass_through_for_provider(&self, identity: &ProviderIdentity) -> bool {
let provider = identity.provider;
codewhale_config::descriptors::provider_passes_model_through(provider)
|| self.provider_uses_custom_endpoint(identity)
}
pub fn model_ids_pass_through(&self) -> bool {
self.active_provider_identity()
.is_ok_and(|identity| self.model_ids_pass_through_for_provider(&identity))
}
pub fn auth_mode_for_provider(&self, identity: &ProviderIdentity) -> Option<String> {
self.provider_config_string_with_runtime_fallback(identity, |entry| entry.auth_mode.clone())
.or_else(|| {
(self
.active_provider_identity()
.is_ok_and(|active| active == *identity))
.then(|| self.auth_mode.clone())
.flatten()
})
}
pub(crate) fn external_credential_read_grant(
&self,
identity: &ProviderIdentity,
source: codewhale_config::ExternalCredentialSource,
suggested_path: &Path,
) -> Result<codewhale_config::ExternalCredentialReadGrant> {
anyhow::ensure!(
identity.key.as_str() != codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id,
"external credentials are unsupported for the legacy DeepSeek China route"
);
let provider = identity.provider;
if !self
.active_provider_identity()
.is_ok_and(|active| active == *identity)
{
anyhow::bail!(
"external credential access for {} is dormant until that provider is explicitly selected",
provider.provider().display_name()
);
}
let kind = provider;
let consent = self
.provider_config_for(identity)
.and_then(|entry| entry.external_credentials.as_ref())
.with_context(|| {
format!(
"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 {}",
source.as_str(),
provider.provider().display_name(),
kind.as_str(),
codewhale_config::quote_os_path(suggested_path)
)
})?;
consent
.read_grant(kind, source, &consent.path)
.map_err(|error| {
anyhow::anyhow!(
"external credential consent for {}: {error}",
provider.provider().display_name()
)
})
}
pub fn external_credential_read_consent_configured(
&self,
identity: &ProviderIdentity,
source: codewhale_config::ExternalCredentialSource,
) -> bool {
if identity.key.as_str() == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id {
return false;
}
let provider = identity.provider;
let kind = provider;
let Some(consent) = self
.provider_config_for(identity)
.and_then(|entry| entry.external_credentials.as_ref())
else {
return false;
};
consent
.validate_read_scope(kind, source, &consent.path)
.is_ok()
}
pub fn should_skip_secret_store_for_provider(&self, identity: &ProviderIdentity) -> bool {
if self.verify_provider_identity(identity).is_err() {
return true;
}
let provider = identity.provider;
if provider == ProviderKind::Custom
&& !identity
.key
.as_str()
.eq_ignore_ascii_case(ProviderKind::Custom.as_str())
{
return true;
}
let auth_mode = self.auth_mode_for_provider(identity);
if auth_mode_disables_api_key(auth_mode.as_deref()) {
return true;
}
if self.provider_uses_custom_endpoint(identity) {
let explicitly_authenticated_loopback = self
.active_provider_identity()
.is_ok_and(|active| active == *identity)
&& auth_mode_requires_api_key(auth_mode.as_deref())
&& base_url_uses_local_host(&self.active_route_base_url());
if !explicitly_authenticated_loopback {
return true;
}
}
if auth_mode_requires_api_key(auth_mode.as_deref()) {
return false;
}
if provider == ProviderKind::Codewhale {
return false;
}
provider_route_is_keyless_self_hosted(provider, &self.base_url_for_route(identity))
|| (self
.active_provider_identity()
.is_ok_and(|active| active == *identity)
&& base_url_uses_local_host(&self.active_route_base_url()))
}
pub fn bind_account_model_owner(&mut self, owner: &str) -> Result<()> {
anyhow::ensure!(
!owner.is_empty()
&& owner.len() <= 240
&& !owner.chars().any(|c| c.is_control() || c.is_whitespace()),
"Invalid account model owner"
);
let access = self
.account_model_access
.read()
.clone()
.context("Connect account model access before running the Codewhale agent")?;
self.account_model_access = std::sync::Arc::new(parking_lot::RwLock::new(Some(access)));
self.required_account_model_owner = Some(owner.to_string());
let identity = self
.resolve_persisted_provider_identity(Some("codewhale"), Some("codewhale"))
.map_err(anyhow::Error::msg)?;
anyhow::ensure!(
self.account_model_api_key(&identity).is_some(),
"Codewhale agent model access must belong to the signed-in account"
);
Ok(())
}
pub fn session_provider_api_key(&self, identity: &ProviderIdentity) -> Option<String> {
self.verify_provider_identity(identity).ok()?;
if self.should_skip_secret_store_for_provider(identity) {
return None;
}
let endpoint = self.base_url_for_route(identity);
self.session_provider_keys
.read()
.get(identity)
.filter(|(bound_endpoint, _)| bound_endpoint == &endpoint)
.map(|(_, credential)| credential.expose_secret().to_string())
}
pub fn preserve_runtime_credentials(&mut self, current: &Self) {
self.account_model_access = current.account_model_access.clone();
self.session_provider_keys = current.session_provider_keys.clone();
self.session_provider_keys_only = current.session_provider_keys_only;
}
pub fn retain_compatible_session_keys(&self) {
self.session_provider_keys
.write()
.retain(|identity, (endpoint, _)| {
self.verify_provider_identity(identity).is_ok()
&& !self.should_skip_secret_store_for_provider(identity)
&& self.base_url_for_route(identity) == *endpoint
});
}
pub fn session_policy_without_key(
&self,
identity: &ProviderIdentity,
) -> Option<crate::credentials::CredentialSource> {
use crate::credentials::{CredentialProbe, CredentialSource};
if !self.session_provider_keys_only {
return None;
}
let mode = self.auth_mode_for_provider(identity);
if auth_mode_disables_api_key(mode.as_deref()) {
return Some(CredentialSource::AuthModeNone);
}
let endpoint = self.base_url_for_route(identity);
if identity.provider != ProviderKind::Codewhale
&& !auth_mode_requires_api_key(mode.as_deref())
&& !provider_uses_oauth_credentials(self, identity)
&& !self
.provider_config_for(identity)
.is_some_and(|entry| entry.oauth.is_some())
&& (provider_route_is_keyless_self_hosted(identity.provider, &endpoint)
|| base_url_uses_local_host(&endpoint))
{
return Some(CredentialSource::KeylessRoute { base_url: endpoint });
}
Some(CredentialSource::Missing {
probed: vec![CredentialProbe::with_fix(
"session-only provider key",
"connect a session key to this Engine; stored credentials are disabled",
)],
})
}
pub fn account_model_api_key(&self, identity: &ProviderIdentity) -> Option<String> {
self.account_model_key_and_owner(identity)
.map(|(key, _)| key)
}
fn account_model_key_and_owner(&self, identity: &ProviderIdentity) -> Option<(String, String)> {
let provider = identity.provider;
if provider != ProviderKind::Codewhale
|| self.base_url_for_route(identity).trim_end_matches('/') != DEFAULT_CODEWHALE_BASE_URL
|| auth_mode_disables_api_key(self.auth_mode_for_provider(identity).as_deref())
|| self
.provider_config_for(identity)
.is_some_and(|entry| entry.auth.is_some() || entry.api_key_env.is_some())
{
return None;
}
if std::env::var(codewhale_secrets::account::ACCOUNT_API_BASE_ENV)
.ok()
.filter(|base| !base.trim().is_empty())
.is_some_and(|base| {
base.trim().trim_end_matches('/')
!= codewhale_secrets::account::DEFAULT_ACCOUNT_API_BASE
})
{
return None;
}
let access = self.account_model_access.read().clone();
let profile = self.account_profile.as_deref();
if access.as_ref().is_some_and(|access| {
codewhale_secrets::account::normalize_account_profile(access.profile.as_deref())
!= codewhale_secrets::account::normalize_account_profile(profile)
}) {
return None;
}
let secrets = codewhale_secrets::account::secure_account_session_secrets().ok()?;
let snapshot = codewhale_secrets::account::AccountSessionStore::new(
secrets,
profile,
codewhale_secrets::account::DEFAULT_ACCOUNT_API_BASE,
)
.snapshot()
.ok()?;
let now = chrono::Utc::now();
let account = snapshot.runtime_info_at(now).ok()?;
if access
.as_ref()
.is_some_and(|access| account.session_id.as_deref() != Some(access.session_id.as_str()))
{
return None;
}
if self
.required_account_model_owner
.as_ref()
.is_some_and(|owner| account.account_id.as_ref() != Some(owner))
{
return None;
}
if !self.session_provider_keys_only
&& matches!(
account.state,
codewhale_secrets::account::AccountSessionState::Authenticated
| codewhale_secrets::account::AccountSessionState::OfflineCached
)
&& let Some(cached) = snapshot.device_access().ok()?
&& cached.expires_at > now.timestamp()
&& account.account_id.as_deref() == Some(cached.account_id.as_str())
&& account.session_id.as_deref() == Some(cached.session_id.as_str())
{
return Some((cached.credential, cached.account_id));
}
let access = access.filter(|access| access.expires_at > now.timestamp())?;
let owner = account.account_id?;
(account.state == codewhale_secrets::account::AccountSessionState::Authenticated
&& account.session_id.as_deref() == Some(access.session_id.as_str()))
.then(|| (access.credential.expose_secret().to_string(), owner))
}
pub fn readonly_health_credential_generation(
&self,
identity: &ProviderIdentity,
) -> Option<codewhale_config::credentials::CredentialGeneration> {
if self.required_account_model_owner.is_some() {
return None;
}
self.verify_provider_identity(identity).ok()?;
let mut scoped = self.clone();
scoped.scope_to_provider_identity(identity).ok()?;
let endpoint = scoped.base_url_for_route(identity);
let mode = scoped.auth_mode_for_provider(identity);
let generation = |value: &str| {
codewhale_config::credentials::CredentialGeneration::derive(
&endpoint,
&codewhale_secrets::normalize_api_key(value),
)
};
if let Some(key) = scoped.session_provider_api_key(identity) {
return Some(generation(&key));
}
if let Some(source) = scoped.session_policy_without_key(identity) {
return match source {
crate::credentials::CredentialSource::AuthModeNone
| crate::credentials::CredentialSource::KeylessRoute { .. } => Some(generation("")),
_ => None,
};
}
if auth_mode_disables_api_key(mode.as_deref()) {
return Some(generation(""));
}
if provider_uses_oauth_credentials(&scoped, identity)
|| scoped
.provider_config_for(identity)
.is_some_and(|entry| entry.auth.is_some())
{
return None;
}
if let Some(key) = explicit_cli_api_key_override() {
return Some(generation(&key));
}
if identity.provider == ProviderKind::Deepseek
&& cli_api_key_source().as_deref() == Some("cli")
{
return None;
}
if scoped.config_credentials_are_bound_to_provider_endpoint(identity)
&& let Some(key) = scoped
.provider_route_string_with_deepseek_fallback(identity, |entry| {
entry.api_key.clone()
})
&& classify_config_api_key_value(&key) == ConfigApiKeyValueKind::Literal
{
return Some(generation(&key));
}
if let Some(key) = provider_config_env_api_key(&scoped, identity) {
return Some(generation(&key));
}
if bound_provider_api_key_env_name(&scoped, identity).is_some() {
return None;
}
if !auth_mode_requires_api_key(mode.as_deref())
&& scoped.should_skip_secret_store_for_provider(identity)
&& identity.provider != ProviderKind::Codewhale
&& scoped
.provider_config_for(identity)
.is_none_or(|entry| entry.external_credentials.is_none())
&& (provider_route_is_keyless_self_hosted(identity.provider, &endpoint)
|| base_url_uses_local_host(&endpoint))
{
return Some(generation(""));
}
None
}
pub fn active_route_api_key(&self) -> Result<String> {
self.active_route_api_key_with_source().map(|(key, _)| key)
}
pub fn active_route_api_key_with_source(&self) -> Result<(String, String)> {
self.active_route_api_key_with_secret_store_mode(false)
}
pub fn active_route_api_key_with_owner(&self) -> Result<(ResolvedApiKey, Option<String>)> {
let mut owner = None;
let key = self.active_route_api_key_with_owner_and_mode(false, &mut owner)?;
Ok((key, owner))
}
pub fn xai_oauth_route_credentials(
&self,
) -> Option<Result<crate::oauth::OwnedOAuthCredentials>> {
let identity = self.active_provider_identity().ok()?;
if self.required_account_model_owner.is_some()
|| self.session_provider_keys_only
|| self.session_provider_api_key(&identity).is_some()
{
return None;
}
let provider = identity.provider;
let selected = provider == ProviderKind::Xai
&& !self.provider_uses_custom_endpoint(&identity)
&& self
.provider_config_for(&identity)
.is_some_and(provider_config_uses_xai_oauth)
&& crate::oauth::credentials_present(crate::oauth::OAuthProvider::Xai, self);
selected.then(|| crate::oauth::get_xai_credentials(self))
}
pub fn active_route_api_key_read_only(&self) -> Result<String> {
self.active_route_api_key_with_secret_store_mode(true)
.map(|(key, _)| key)
}
fn active_route_api_key_with_secret_store_mode(
&self,
read_only: bool,
) -> Result<(String, String)> {
self.active_route_api_key_with_owner_and_mode(read_only, &mut None)
}
fn active_route_api_key_with_owner_and_mode(
&self,
read_only: bool,
account_owner: &mut Option<String>,
) -> Result<ResolvedApiKey> {
self.resolve_active_route_api_key(read_only, account_owner)
.map(|(key, source)| (codewhale_secrets::normalize_api_key(&key), source))
}
pub fn with_read_only_api_key_for_diagnostic(&self) -> Result<Self> {
let identity = self
.active_provider_identity()
.map_err(anyhow::Error::msg)?;
let mut diagnostic = self.clone();
if self.session_provider_keys_only
|| (self.required_account_model_owner.is_none()
&& self.session_provider_api_key(&identity).is_some())
{
return Ok(diagnostic);
}
if identity.provider == ProviderKind::Anthropic
&& self.auth_mode_for_provider(&identity).as_deref() == Some("oauth")
{
diagnostic.plugin_oauth_read_only = true;
return Ok(diagnostic);
}
if identity.provider == ProviderKind::Custom
&& self
.provider_config_for(&identity)
.is_some_and(|entry| entry.oauth.is_some())
{
diagnostic.plugin_oauth_read_only = true;
return Ok(diagnostic);
}
let api_key = self.active_route_api_key_read_only()?;
diagnostic.set_provider_api_key_override(&identity, Some(api_key))?;
Ok(diagnostic)
}
fn resolve_active_route_api_key(
&self,
read_only: bool,
account_owner: &mut Option<String>,
) -> Result<ResolvedApiKey> {
let identity = self
.active_provider_identity()
.map_err(anyhow::Error::msg)?;
self.verify_provider_identity(&identity)
.map_err(anyhow::Error::msg)?;
if self.required_account_model_owner.is_some() {
return self.account_model_key_and_owner(&identity)
.map(|(key, owner)| {
*account_owner = Some(owner);
(key, "Codewhale account".to_string())
})
.context("The selected account model access is unavailable; no credential fallback is allowed");
}
if let Some(key) = self.session_provider_api_key(&identity) {
return Ok((
key,
crate::credentials::CredentialSource::SessionKey
.label()
.into_owned(),
));
}
if let Some(source) = self.session_policy_without_key(&identity) {
return match &source {
crate::credentials::CredentialSource::AuthModeNone
| crate::credentials::CredentialSource::KeylessRoute { .. } => {
Ok((String::new(), source.label().into_owned()))
}
_ => anyhow::bail!(
"This Engine requires a session provider key; stored credentials are disabled"
),
};
}
let provider = identity.provider;
let keyless = || (String::new(), "none (keyless route)".to_string());
if provider == ProviderKind::Antigravity {
anyhow::bail!(codewhale_config::LEGACY_ANTIGRAVITY_TOMBSTONE_MESSAGE);
}
let auth_mode = self.auth_mode_for_provider(&identity);
if provider == ProviderKind::Custom
&& let Some(entry) = self.provider_config_for(&identity)
&& let Some(oauth) = entry.oauth.as_ref()
{
entry
.plugin_authority
.as_ref()
.context("Plugin OAuth route lacks an approved plugin authority")?;
anyhow::ensure!(
auth_mode.as_deref() == Some("oauth"),
"Plugin OAuth route requires auth_mode = oauth"
);
self.provider
.as_deref()
.context("Plugin OAuth route has no provider name")?;
oauth.validate()?;
return Ok((String::new(), "host-managed plugin OAuth".to_string()));
}
if codewhale_config::credentials::auth_mode_is_claude_org(auth_mode.as_deref()) {
anyhow::ensure!(
provider == ProviderKind::Anthropic
&& !self.provider_uses_custom_endpoint(&identity),
"auth_mode = \"claude-org\" works only for the anthropic provider on its official endpoint; remove base_url or the auth_mode from [providers.{}]",
identity.key.as_str()
);
return Ok((
String::new(),
codewhale_config::credentials::CLAUDE_ORG_KEY_SOURCE.to_string(),
));
}
if auth_mode_disables_api_key(auth_mode.as_deref()) {
return Ok(keyless());
}
if provider == ProviderKind::Anthropic && auth_mode.as_deref() == Some("oauth") {
anyhow::bail!(codewhale_config::credentials::CLAUDE_SIGN_IN_REMOVED);
}
let custom_endpoint = self.provider_uses_custom_endpoint(&identity);
let explicit_cli_key = explicit_cli_api_key_override();
if matches!(provider, ProviderKind::Deepseek)
&& cli_api_key_source().as_deref() == Some("cli")
&& let Some((env_key, source)) = explicit_cli_key
.as_ref()
.cloned()
.map(|key| (key, "--api-key (CLI)".to_string()))
.or_else(|| {
provider_env_api_key_named(provider)
.map(|(name, key)| (key, format!("env var {name}")))
})
&& !env_key.trim().is_empty()
{
return Ok((env_key, source));
}
if provider == ProviderKind::Moonshot
&& !custom_endpoint
&& self
.provider_config_for(&identity)
.is_some_and(provider_config_uses_kimi_imported_token)
{
let credential_help =
credential_help_for_provider_route(provider, &self.active_route_base_url());
anyhow::bail!(
"Kimi CLI credential import is unsupported. Codewhale does not impersonate or reuse Kimi OAuth clients; configure an API key from {} instead.",
credential_help
.credential_url
.unwrap_or("the selected provider's API-key console")
);
}
if let Some(credentials) = self.xai_oauth_route_credentials() {
return credentials
.map(|credentials| (credentials.access_token, XAI_OAUTH_KEY_SOURCE.to_string()));
}
if provider == ProviderKind::OpenaiCodex && !custom_endpoint {
let access_token = if read_only {
crate::oauth::get_owned_credentials_read_only(
crate::oauth::OAuthProvider::Chatgpt,
self,
)?
.access_token
} else {
self.codex_credentials()?.access_token
};
return Ok((access_token, "ChatGPT sign-in".to_string()));
}
if let Some(value) = explicit_cli_key {
return Ok((value, "--api-key (CLI)".to_string()));
}
if self.config_credentials_are_bound_to_provider_endpoint(&identity)
&& let Some(configured) = self
.provider_route_string_with_deepseek_fallback(&identity, |entry| {
entry.api_key.clone()
})
&& classify_config_api_key_value(&configured) == ConfigApiKeyValueKind::Literal
{
let config_source = match provider_config_table_name(&identity) {
Ok(table) => format!("`{table}` api_key"),
Err(_) => "the provider config-table api_key".to_string(),
};
warn_on_config_api_key_shadowing(self, &identity, &config_source);
return Ok((configured, format!("config file ({config_source})")));
}
if provider == ProviderKind::Custom
&& let Some(env_name) = bound_provider_api_key_env_name(self, &identity)
{
return match std::env::var(&env_name) {
Ok(value) if !value.trim().is_empty() => {
Ok((value, format!("env var {env_name} (api_key_env)")))
}
_ => {
let route_name = self.provider.as_deref().unwrap_or("<name>");
Err(anyhow::anyhow!(
"Custom provider '{route_name}' API key not found: the route binds \
api_key_env = \"{env_name}\" but that environment variable is not set. \
Set {env_name} to your key, or remove api_key_env from \
[providers.{route_name}] to run the endpoint without credentials."
))
}
};
}
if let Some(value) = provider_config_env_api_key(self, &identity) {
let name = bound_provider_api_key_env_name(self, &identity).unwrap_or_default();
return Ok((value, format!("env var {name} (api_key_env)")));
}
if !self.should_skip_secret_store_for_provider(&identity)
&& let Some(value) = provider_secret_store_api_key_with_mode(self, &identity, read_only)
{
return Ok((
value,
format!(
"secret store slot `{}`",
provider_secret_store_slot(provider)
),
));
}
if !self.should_skip_secret_store_for_provider(&identity)
&& provider == ProviderKind::XiaomiMimo
{
let mode = self
.provider_config_for(&identity)
.and_then(|provider| provider.mode.as_deref());
if let Some(value) =
xiaomi_mimo_env_api_key_for_runtime(mode, Some(&self.active_route_base_url()))
&& !value.trim().is_empty()
{
return Ok((
value,
format!("env var ({})", provider.provider().env_vars().join(" / ")),
));
}
}
if !self.should_skip_secret_store_for_provider(&identity)
&& let Some((name, value)) = provider_env_api_key_named(provider)
{
return Ok((value, format!("env var {name}")));
}
if matches!(
provider,
ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
) && identity.key.as_str() != codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id
&& !custom_endpoint
{
let path = codewhale_config::default_dsh_credentials_path();
if let Ok(grant) = self.external_credential_read_grant(
&identity,
codewhale_config::ExternalCredentialSource::DshCli,
&path,
) && let Some(value) = crate::dsh_credentials::deepseek_api_key_from_grant(&grant)?
{
return Ok((
value,
"DeepSeek Harness credentials (consented)".to_string(),
));
}
}
if let Some((key, owner)) = self.account_model_key_and_owner(&identity) {
*account_owner = Some(owner);
return Ok((key, "Codewhale account".to_string()));
}
if provider != ProviderKind::Codewhale
&& !auth_mode_requires_api_key(auth_mode.as_deref())
&& (provider_route_is_keyless_self_hosted(provider, &self.active_route_base_url())
|| base_url_uses_local_host(&self.active_route_base_url()))
{
return Ok(keyless());
}
if custom_endpoint {
let route_name = self
.provider
.as_deref()
.unwrap_or_else(|| provider.as_str());
anyhow::bail!(
"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.",
self.active_route_base_url()
);
}
match provider {
ProviderKind::Codewhale => anyhow::bail!(
"Codewhale API key not found, so no request was sent.\n\
\n\
The Codewhale API authenticates every model with one account \
API key carrying the `models:infer` scope.\n\
\n\
1. Create one and save it on this machine:\n\
codewhale account api-keys create --name <name> --scope models:infer --use\n\
2. Or export it for this shell:\n\
export CODEWHALE_API_KEY=cwc_key_...\n\
\n\
You can also create a key at {} and put it in \
[providers.codewhale] api_key (or api_key_env).",
provider
.provider()
.credential_help()
.credential_url
.unwrap_or("https://app.codewhale.net/settings?section=api")
),
ProviderKind::Deepseek => {
anyhow::bail!(deepseek_missing_key_message())
}
ProviderKind::SiliconflowCN => anyhow::bail!(
"SiliconFlow China API key not found. Get a key: {}. Run 'codewhale auth set --provider siliconflow-CN', \
set {}, or add [{}] api_key in ~/.codewhale/config.toml. \
[providers.siliconflow] remains a fallback when the CN table omits api_key.",
provider
.provider()
.credential_help()
.credential_url
.unwrap_or("https://cloud.siliconflow.com/account/ak"),
provider.provider().env_vars().join(" / "),
provider_config_table_name(&identity)?
),
ProviderKind::Moonshot => {
let credential_help =
credential_help_for_provider_route(provider, &self.active_route_base_url());
if moonshot_base_url_is_exact_kimi_code(&self.active_route_base_url()) {
anyhow::bail!(
"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.",
credential_help
.credential_url
.unwrap_or(KIMI_CODE_MEMBERSHIP_PLAN_CONSOLE_URL),
provider.provider().env_vars().join(" / "),
provider_config_table_name(&identity)?
);
}
anyhow::bail!(
"Moonshot/Kimi API key not found. Get a key: {}. Run 'codewhale auth set --provider moonshot', \
set {}, or add [{}] api_key. \
For a Kimi Code plan key, set [providers.moonshot] base_url = \
\"https://api.kimi.com/coding/v1\" and model = \"kimi-for-coding\".",
credential_help
.credential_url
.unwrap_or("https://platform.kimi.ai/console/api-keys"),
provider.provider().env_vars().join(" / "),
provider_config_table_name(&identity)?
);
}
ProviderKind::Anthropic | ProviderKind::Openmodel => {
anyhow::bail!("{}", missing_provider_api_key_message(&identity)?)
}
ProviderKind::OpencodeZen => {
anyhow::bail!("{}", missing_provider_api_key_message(&identity)?)
}
ProviderKind::OpenaiCodex => anyhow::bail!(
"{}",
crate::oauth::missing_auth_message(crate::oauth::OAuthProvider::Chatgpt)
),
ProviderKind::Xai => {
if self
.provider_config_for(&identity)
.is_some_and(provider_config_uses_xai_oauth)
|| crate::oauth::credentials_present(crate::oauth::OAuthProvider::Xai, self)
{
anyhow::bail!(
"{}",
crate::oauth::missing_auth_message(crate::oauth::OAuthProvider::Xai)
);
}
anyhow::bail!(
"xAI API key not found. Get a key: https://console.x.ai/\n\
Run 'codewhale auth set --provider xai', set XAI_API_KEY, or add \
[providers.xai] api_key.\n\
OAuth alternative: run `codewhale auth xai-device` for \
Codewhale-owned storage and set [providers.xai] auth_mode = \"oauth\"."
);
}
ProviderKind::Sglang | ProviderKind::Vllm => Ok(keyless()),
ProviderKind::Ollama
if provider_route_is_keyless_self_hosted(
provider,
&self.active_route_base_url(),
) =>
{
Ok(keyless())
}
ProviderKind::Ollama => {
let help =
credential_help_for_provider_route(provider, &self.active_route_base_url());
anyhow::bail!(
"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.",
help.credential_url
.unwrap_or(codewhale_config::provider::OLLAMA_CLOUD_API_KEY_URL)
)
}
ProviderKind::Custom => {
let provider_name = self.provider.as_deref().unwrap_or("<name>");
match self
.provider_config_for(&identity)
.and_then(|entry| entry.api_key_env.as_deref())
.map(str::trim)
.filter(|name| !name.is_empty())
{
Some(env_name) => anyhow::bail!(
"Custom provider '{provider_name}' API key not found.\n\
Set the environment variable {env_name} to your key, \
or add api_key to [providers.{provider_name}]."
),
None => anyhow::bail!(
"Custom provider '{provider_name}' has no auth configured.\n\
Add api_key_env = \"YOUR_ENV_VAR\" (or api_key) to \
[providers.{provider_name}] in ~/.codewhale/config.toml."
),
}
}
_ => anyhow::bail!("{}", missing_provider_api_key_message(&identity)?),
}
}
#[must_use]
pub fn skills_dir(&self) -> PathBuf {
self.skills_dir
.as_deref()
.map(expand_path)
.or_else(default_skills_dir)
.unwrap_or_else(|| PathBuf::from("./skills"))
}
#[must_use]
pub fn bundled_skills_install_dir(&self) -> Option<PathBuf> {
match self.skills_config().bundled.install.unwrap_or_default() {
BundledSkillsInstall::None => return None,
BundledSkillsInstall::All => return owned_skills_dir(),
BundledSkillsInstall::Auto if self.skills_dir.is_some() => return None,
BundledSkillsInstall::Auto => {}
}
let directory = default_skills_dir()?;
let owned = owned_skills_dir()?;
(directory == owned).then_some(directory)
}
#[must_use]
pub fn mcp_config_path(&self) -> PathBuf {
let configured = self.mcp_config_path.as_deref().map(expand_path);
match configured {
Some(path) if path.is_absolute() => path,
Some(path) => {
tracing::warn!(
configured_path = %path.display(),
"relative mcp_config_path is not stable across launch directories; using the user-global MCP config"
);
default_mcp_config_path().unwrap_or_else(|| PathBuf::from("./mcp.json"))
}
None => default_mcp_config_path().unwrap_or_else(|| PathBuf::from("./mcp.json")),
}
}
#[must_use]
pub fn notes_path(&self) -> PathBuf {
self.notes_path
.as_deref()
.map(expand_path)
.or_else(default_notes_path)
.unwrap_or_else(|| PathBuf::from("./notes.txt"))
}
#[must_use]
pub fn memory_path(&self) -> PathBuf {
let legacy_path = self
.memory_path
.as_deref()
.map(expand_path)
.or_else(default_memory_path)
.unwrap_or_else(|| PathBuf::from("./memory.md"));
if self.memory_backend() == MemoryBackend::Native {
if crate::native_memory::NativeMemoryStore::from_global_path(&legacy_path).is_some() {
return legacy_path;
}
return legacy_path
.parent()
.unwrap_or_else(|| Path::new("."))
.join("memory")
.join("global")
.join("MEMORY.md");
}
legacy_path
}
#[must_use]
pub fn speech_output_dir(&self) -> Option<PathBuf> {
std::env::var("XIAOMI_MIMO_SPEECH_OUTPUT_DIR")
.or_else(|_| std::env::var("MIMO_SPEECH_OUTPUT_DIR"))
.or_else(|_| std::env::var("XIAOMIMIMO_SPEECH_OUTPUT_DIR"))
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
.map(|value| expand_path(&value))
.or_else(|| {
self.speech
.as_ref()
.and_then(|speech| speech.output_dir.as_deref())
.map(str::trim)
.filter(|value| !value.is_empty())
.map(expand_path)
})
}
#[must_use]
pub fn instructions_paths(&self) -> Vec<PathBuf> {
self.instructions
.as_deref()
.unwrap_or(&[])
.iter()
.map(String::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.map(expand_path)
.collect()
}
#[must_use]
pub fn auto_review_disabled(&self) -> bool {
self.auto_review.as_ref().is_some_and(|cfg| cfg.disabled)
}
#[must_use]
pub fn auto_review_review_all_shell(&self) -> bool {
self.auto_review
.as_ref()
.is_some_and(|cfg| cfg.review_all_shell)
}
pub fn auto_review_reviewer_model(&self) -> Option<&str> {
self.auto_review
.as_ref()
.and_then(|cfg| cfg.reviewer_model.as_deref())
.map(str::trim)
.filter(|model| !model.is_empty())
}
#[must_use]
pub fn auto_review_environment(&self) -> &[String] {
self.auto_review
.as_ref()
.map_or(&[], |cfg| cfg.environment.as_slice())
}
#[must_use]
pub fn memory_enabled(&self) -> bool {
if let Some(backend) = self.memory.as_ref().and_then(|memory| memory.backend) {
return backend != MemoryBackend::Off;
}
self.memory
.as_ref()
.and_then(|m| m.enabled)
.unwrap_or(false)
}
#[must_use]
pub fn goal_max_continuations(&self) -> u32 {
self.goal
.as_ref()
.and_then(|goal| goal.max_continuations)
.unwrap_or(crate::goal_loop::DEFAULT_MAX_GOAL_CONTINUATIONS)
}
#[must_use]
pub fn goal_max_steps(&self) -> u32 {
let configured = self.goal.as_ref().and_then(|goal| goal.max_steps);
let resolved = crate::turn_budget::resolve_max_model_steps(configured);
if let Some(steps) = configured
&& steps > 0
&& resolved != steps
{
tracing::warn!("[goal] max_steps={steps} out of range; clamping to {resolved}");
}
resolved
}
#[must_use]
pub fn goal_enforce_token_budget(&self) -> bool {
self.goal
.as_ref()
.and_then(|goal| goal.enforce_token_budget)
.unwrap_or(false)
}
#[must_use]
pub fn goal_complete_judge(&self) -> bool {
self.goal
.as_ref()
.and_then(|goal| goal.complete_judge)
.unwrap_or(false)
}
#[must_use]
pub fn goal_blocked_judge(&self) -> bool {
self.goal
.as_ref()
.and_then(|goal| goal.blocked_judge)
.unwrap_or(false)
}
#[must_use]
pub fn goal_continuation_delay_seconds(&self) -> u64 {
self.goal
.as_ref()
.and_then(|goal| goal.continuation_delay_seconds)
.unwrap_or(0)
.min(crate::goal_loop::MAX_GOAL_CONTINUATION_DELAY_SECONDS)
}
#[must_use]
pub fn reasoning_only_on_output_limit(&self) -> bool {
self.reasoning_only
.as_ref()
.is_some_and(|cfg| cfg.on_output_limit)
}
#[must_use]
pub fn reasoning_only_max_reprompts(&self) -> u32 {
self.reasoning_only
.as_ref()
.and_then(|cfg| cfg.max_reprompts)
.unwrap_or(DEFAULT_REASONING_ONLY_REPROMPTS)
}
#[must_use]
pub fn reasoning_only_reprompt_message(&self) -> &str {
self.reasoning_only
.as_ref()
.and_then(|cfg| cfg.reprompt_message.as_deref())
.unwrap_or(DEFAULT_REASONING_ONLY_REPROMPT_MESSAGE)
}
#[must_use]
pub fn memory_backend(&self) -> MemoryBackend {
self.memory
.as_ref()
.and_then(|memory| memory.backend)
.unwrap_or_else(|| {
let Some(memory) = self.memory.as_ref() else {
return MemoryBackend::Off;
};
if memory.enabled.unwrap_or(false) {
MemoryBackend::Native
} else {
MemoryBackend::Off
}
})
}
#[must_use]
pub fn vision_model_config(&self) -> Option<VisionModelConfig> {
let mut config = self.vision_model.clone()?;
if config.model_http_policy.is_none() {
config.model_http_policy = self.model_http_policy.clone();
}
Some(config)
}
#[must_use]
pub fn project_context_pack_enabled(&self) -> bool {
self.context.project_pack.unwrap_or(false)
}
#[must_use]
pub fn allow_shell(&self) -> bool {
self.allow_shell.unwrap_or(false)
}
#[must_use]
pub fn interactive_allow_shell(&self) -> bool {
self.allow_shell.unwrap_or(true)
}
pub fn prompt_suggestion_enabled(&self) -> bool {
self.prompt_suggestion.unwrap_or(false)
}
#[must_use]
pub fn compaction_summary_instructions(&self) -> Option<String> {
self.compaction
.as_ref()
.and_then(|compaction| compaction.summary_instructions.as_deref())
.map(str::trim)
.filter(|text| !text.is_empty())
.map(str::to_string)
}
#[must_use]
pub fn compaction_retained_user_message_tokens(&self) -> usize {
let Some(requested) = self
.compaction
.as_ref()
.and_then(|compaction| compaction.retained_user_message_tokens)
else {
return DEFAULT_COMPACTION_RETAINED_USER_MESSAGE_TOKENS;
};
let clamped = requested.clamp(
MIN_COMPACTION_RETAINED_USER_MESSAGE_TOKENS,
MAX_COMPACTION_RETAINED_USER_MESSAGE_TOKENS,
);
if clamped != requested {
tracing::warn!(
"[compaction] retained_user_message_tokens = {requested} is outside {}..={}; using {clamped}",
MIN_COMPACTION_RETAINED_USER_MESSAGE_TOKENS,
MAX_COMPACTION_RETAINED_USER_MESSAGE_TOKENS
);
}
clamped
}
#[must_use]
pub fn max_subagents(&self) -> usize {
if let Some(subagents_cfg) = self.subagents.as_ref()
&& let Some(max) = subagents_cfg.max_concurrent
{
return max.clamp(1, MAX_SUBAGENTS);
}
self.max_subagents
.unwrap_or(DEFAULT_MAX_SUBAGENTS)
.clamp(1, MAX_SUBAGENTS)
}
#[must_use]
pub fn max_subagents_for_provider(&self, identity: &ProviderIdentity) -> usize {
self.subagent_provider_config(identity)
.and_then(|cfg| cfg.max_concurrent)
.map(|max| max.clamp(1, MAX_SUBAGENTS))
.unwrap_or_else(|| self.max_subagents())
}
#[must_use]
pub fn subagents_enabled(&self) -> bool {
self.subagents_disabled_reason().is_none()
}
#[must_use]
pub fn subagents_enabled_for_provider(&self, identity: &ProviderIdentity) -> bool {
if !self.subagents_enabled() {
return false;
}
let Some(provider_cfg) = self.subagent_provider_config(identity) else {
return true;
};
provider_cfg.enabled != Some(false)
&& provider_cfg.max_concurrent != Some(0)
&& provider_cfg.max_depth != Some(0)
}
#[must_use]
pub fn subagents_disabled_reason(&self) -> Option<&'static str> {
if !self.features().enabled(Feature::Subagents) {
return Some("features.subagents=false");
}
let subagents_cfg = self.subagents.as_ref()?;
if subagents_cfg.enabled == Some(false) {
return Some("subagents.enabled=false");
}
if subagents_cfg.max_concurrent == Some(0) {
return Some("subagents.max_concurrent=0");
}
if subagents_cfg.max_depth == Some(0) {
return Some("subagents.max_depth=0");
}
None
}
#[must_use]
pub fn subagent_max_spawn_depth(&self) -> u32 {
self.subagents
.as_ref()
.and_then(|cfg| cfg.max_depth)
.unwrap_or(codewhale_protocol::fleet::DEFAULT_SPAWN_DEPTH)
}
#[must_use]
pub fn subagent_max_spawn_depth_for_provider(&self, identity: &ProviderIdentity) -> u32 {
self.subagent_provider_config(identity)
.and_then(|cfg| cfg.max_depth)
.unwrap_or_else(|| self.subagent_max_spawn_depth())
}
#[must_use]
pub fn launch_concurrency(&self) -> usize {
let max = self.max_subagents();
self.subagents
.as_ref()
.and_then(|cfg| cfg.launch_concurrency.or(cfg.interactive_max_launch_legacy))
.unwrap_or(max)
.clamp(1, max)
}
#[must_use]
pub fn launch_concurrency_for_provider(&self, identity: &ProviderIdentity) -> usize {
let max = self.max_subagents_for_provider(identity);
self.subagent_provider_config(identity)
.and_then(|cfg| cfg.launch_concurrency)
.or_else(|| {
self.subagents
.as_ref()
.and_then(|cfg| cfg.launch_concurrency.or(cfg.interactive_max_launch_legacy))
})
.unwrap_or(max)
.clamp(1, max)
}
#[must_use]
pub fn max_admitted_subagents(&self) -> usize {
let max_concurrent = self.max_subagents();
self.subagents
.as_ref()
.and_then(|cfg| cfg.max_admitted)
.unwrap_or(MAX_SUBAGENT_ADMISSION)
.clamp(max_concurrent, MAX_SUBAGENT_ADMISSION)
}
#[must_use]
pub fn max_admitted_subagents_for_provider(&self, identity: &ProviderIdentity) -> usize {
let max_concurrent = self.max_subagents_for_provider(identity);
self.subagent_provider_config(identity)
.and_then(|cfg| cfg.max_admitted)
.or_else(|| self.subagents.as_ref().and_then(|cfg| cfg.max_admitted))
.unwrap_or(MAX_SUBAGENT_ADMISSION)
.clamp(max_concurrent, MAX_SUBAGENT_ADMISSION)
}
#[must_use]
pub fn subagent_default_max_steps(&self) -> Option<u32> {
self.subagents
.as_ref()
.and_then(|cfg| cfg.default_max_steps)
.filter(|steps| *steps > 0)
}
#[must_use]
pub fn subagent_default_wall_time_secs(&self) -> Option<u64> {
self.subagents
.as_ref()
.and_then(|cfg| cfg.default_wall_time_secs)
.filter(|secs| *secs > 0)
}
#[must_use]
pub fn subagent_api_timeout_secs(&self) -> u64 {
resolve_subagent_api_timeout_secs(
self.subagents.as_ref().and_then(|cfg| cfg.api_timeout_secs),
)
}
#[must_use]
pub fn subagent_api_timeout_secs_for_provider(&self, identity: &ProviderIdentity) -> u64 {
resolve_subagent_api_timeout_secs(
self.subagent_provider_config(identity)
.and_then(|cfg| cfg.api_timeout_secs)
.or_else(|| self.subagents.as_ref().and_then(|cfg| cfg.api_timeout_secs)),
)
}
#[must_use]
pub fn subagent_heartbeat_timeout_secs(&self) -> u64 {
resolve_subagent_heartbeat_timeout_secs(
self.subagents
.as_ref()
.and_then(|cfg| cfg.heartbeat_timeout_secs),
self.subagent_api_timeout_secs(),
DEFAULT_SUBAGENT_TOOL_TIMEOUT_SECS,
)
}
#[must_use]
pub fn subagent_heartbeat_timeout_secs_for_provider(&self, identity: &ProviderIdentity) -> u64 {
let api_timeout = self.subagent_api_timeout_secs_for_provider(identity);
resolve_subagent_heartbeat_timeout_secs(
self.subagent_provider_config(identity)
.and_then(|cfg| cfg.heartbeat_timeout_secs)
.or_else(|| {
self.subagents
.as_ref()
.and_then(|cfg| cfg.heartbeat_timeout_secs)
}),
api_timeout,
DEFAULT_SUBAGENT_TOOL_TIMEOUT_SECS,
)
}
#[must_use]
pub fn stream_chunk_timeout_secs(&self) -> u64 {
let raw = self
.stream
.as_ref()
.and_then(|cfg| cfg.chunk_timeout_secs)
.or_else(|| {
self.tui
.as_ref()
.and_then(|cfg| cfg.stream_chunk_timeout_secs)
})
.or_else(|| {
std::env::var(STREAM_CHUNK_TIMEOUT_ENV)
.or_else(|_| std::env::var(LEGACY_STREAM_CHUNK_TIMEOUT_ENV))
.ok()
.and_then(|value| value.parse::<u64>().ok())
})
.unwrap_or(DEFAULT_STREAM_CHUNK_TIMEOUT_SECS);
if raw == 0 {
return DEFAULT_STREAM_CHUNK_TIMEOUT_SECS;
}
raw.clamp(MIN_STREAM_CHUNK_TIMEOUT_SECS, MAX_STREAM_CHUNK_TIMEOUT_SECS)
}
#[must_use]
pub fn max_model_steps(&self) -> u32 {
let raw = self
.tui
.as_ref()
.and_then(|cfg| cfg.max_model_steps)
.or_else(|| {
std::env::var(MAX_MODEL_STEPS_ENV)
.ok()
.and_then(|value| value.trim().parse::<u32>().ok())
});
crate::turn_budget::resolve_max_model_steps(raw)
}
#[must_use]
pub fn turn_wall_clock(&self) -> std::time::Duration {
let raw = self
.tui
.as_ref()
.and_then(|cfg| cfg.turn_wall_clock_secs)
.or_else(|| {
std::env::var(TURN_WALL_CLOCK_ENV)
.ok()
.and_then(|value| value.trim().parse::<u64>().ok())
});
crate::turn_budget::resolve_turn_wall_clock(raw)
}
#[must_use]
pub fn stream_max_content_bytes(&self) -> usize {
crate::turn_budget::resolve_stream_max_content_bytes(
self.stream
.as_ref()
.and_then(|cfg| cfg.max_content_mb)
.or_else(|| self.tui.as_ref().and_then(|cfg| cfg.stream_max_content_mb)),
)
}
#[must_use]
pub fn stream_max_duration(&self) -> std::time::Duration {
std::time::Duration::from_secs(crate::turn_budget::resolve_stream_max_duration_secs(
self.stream
.as_ref()
.and_then(|cfg| cfg.max_duration_secs)
.or_else(|| {
self.tui
.as_ref()
.and_then(|cfg| cfg.stream_max_duration_secs)
}),
))
}
#[must_use]
pub fn stream_retry_limits(&self) -> crate::turn_budget::StreamRetryLimits {
let tui = self.tui.as_ref();
let stream = self.stream.as_ref();
crate::turn_budget::resolve_stream_retry_limits(
stream
.and_then(|cfg| cfg.max_resumes)
.or_else(|| tui.and_then(|cfg| cfg.stream_max_resumes)),
stream
.and_then(|cfg| cfg.max_transparent_retries)
.or_else(|| tui.and_then(|cfg| cfg.stream_max_transparent_retries)),
stream
.and_then(|cfg| cfg.max_stream_errors)
.or_else(|| tui.and_then(|cfg| cfg.stream_max_errors)),
)
}
#[must_use]
pub fn stream_open_timeout(&self) -> std::time::Duration {
codewhale_config::resolve_stream_open_timeout(
self.stream
.as_ref()
.and_then(|cfg| cfg.open_timeout_secs)
.or_else(|| {
self.tui
.as_ref()
.and_then(|cfg| cfg.stream_open_timeout_secs)
}),
)
}
#[must_use]
pub fn force_http1(&self) -> bool {
self.stream
.as_ref()
.and_then(|cfg| cfg.force_http1)
.or_else(|| self.tui.as_ref().and_then(|cfg| cfg.force_http1))
.unwrap_or(false)
|| codewhale_config::force_http1_from_env()
}
#[must_use]
pub fn connect_timeout(&self) -> std::time::Duration {
let secs = match self
.stream
.as_ref()
.and_then(|cfg| cfg.connect_timeout_secs)
.or_else(|| self.tui.as_ref().and_then(|cfg| cfg.connect_timeout_secs))
{
None | Some(0) => DEFAULT_CONNECT_TIMEOUT_SECS,
Some(secs) => secs.clamp(MIN_CONNECT_TIMEOUT_SECS, MAX_CONNECT_TIMEOUT_SECS),
};
std::time::Duration::from_secs(secs)
}
pub fn tcp_keepalive(&self) -> Option<std::time::Duration> {
let secs = self
.stream
.as_ref()
.and_then(|cfg| cfg.tcp_keepalive_secs)
.unwrap_or(30);
(secs > 0).then(|| std::time::Duration::from_secs(secs.min(3600)))
}
pub fn http2_keep_alive_interval(&self) -> Option<std::time::Duration> {
let secs = self
.stream
.as_ref()
.and_then(|cfg| cfg.http2_keep_alive_interval_secs)
.unwrap_or(15);
(secs > 0).then(|| std::time::Duration::from_secs(secs.min(3600)))
}
pub fn http2_keep_alive_timeout(&self) -> std::time::Duration {
let secs = match self
.stream
.as_ref()
.and_then(|cfg| cfg.http2_keep_alive_timeout_secs)
{
None | Some(0) => 20,
Some(secs) => secs.min(3600),
};
std::time::Duration::from_secs(secs)
}
pub fn resolved_stream_settings(&self) -> StreamConfig {
let limits = self.stream_retry_limits();
StreamConfig {
open_timeout_secs: Some(self.stream_open_timeout().as_secs()),
chunk_timeout_secs: Some(self.stream_chunk_timeout_secs()),
force_http1: Some(self.force_http1()),
max_resumes: Some(limits.max_resumes),
max_transparent_retries: Some(limits.max_transparent_retries),
max_stream_errors: Some(limits.max_errors),
max_duration_secs: Some(self.stream_max_duration().as_secs()),
max_content_mb: Some((self.stream_max_content_bytes() / (1024 * 1024)) as u64),
connect_timeout_secs: Some(self.connect_timeout().as_secs()),
tcp_keepalive_secs: Some(self.tcp_keepalive().map_or(0, |value| value.as_secs())),
http2_keep_alive_interval_secs: Some(
self.http2_keep_alive_interval()
.map_or(0, |value| value.as_secs()),
),
http2_keep_alive_timeout_secs: Some(self.http2_keep_alive_timeout().as_secs()),
}
}
#[must_use]
pub fn subagent_model_overrides(&self) -> HashMap<String, SubagentModelOverride> {
let mut overrides = HashMap::new();
let Some(cfg) = self.subagents.as_ref() else {
return overrides;
};
let mut insert = |key: &str, value: &Option<String>| {
if let Some(model) = value.as_deref().map(str::trim).filter(|v| !v.is_empty()) {
overrides.insert(key.to_string(), model.into());
}
};
insert("default", &cfg.default_model);
insert("worker", &cfg.worker_model);
insert("general", &cfg.worker_model);
insert("scout", &cfg.explorer_model);
insert("explorer", &cfg.explorer_model);
insert("explore", &cfg.explorer_model);
insert("planner", &cfg.awaiter_model);
insert("awaiter", &cfg.awaiter_model);
insert("plan", &cfg.awaiter_model);
insert("reviewer", &cfg.review_model);
insert("review", &cfg.review_model);
insert("custom", &cfg.custom_model);
if let Some(models) = cfg.models.as_ref() {
for (key, model) in models {
let key = key.trim();
let model = model.trim();
if !key.is_empty() && !model.is_empty() {
overrides.insert(key.to_ascii_lowercase(), model.into());
}
}
}
if let Some(roles) = cfg.roles.as_ref() {
let mut entries: Vec<_> = roles.iter().collect();
let canonical = |key: &str| {
let key = key.trim().to_ascii_lowercase();
if key == "default" {
key
} else {
codewhale_protocol::fleet::migrate_legacy_role_token(&key)
.unwrap_or(&key)
.to_string()
}
};
entries
.sort_by_key(|(key, _)| (canonical(key) == key.trim().to_ascii_lowercase(), *key));
for (key, pin) in entries {
overrides.insert(canonical(key), parse_subagent_role_pin(&pin.model));
}
}
overrides
}
pub fn subagent_route_replacements(&self, key: &str) -> Vec<SubagentModelOverride> {
let Some(roles) = self.subagents.as_ref().and_then(|cfg| cfg.roles.as_ref()) else {
return Vec::new();
};
let canonical = |raw: &str| {
let raw = raw.trim().to_ascii_lowercase();
if raw == "default" {
raw
} else {
codewhale_protocol::fleet::migrate_legacy_role_token(&raw)
.unwrap_or(&raw)
.to_string()
}
};
roles
.iter()
.filter(|(raw, _)| canonical(raw) == key)
.max_by_key(|(raw, _)| (canonical(raw) == raw.trim().to_ascii_lowercase(), *raw))
.map(|(_, pin)| {
pin.replacements
.iter()
.map(|route| parse_subagent_role_pin(route))
.collect()
})
.unwrap_or_default()
}
#[must_use]
pub fn fleet_config(&self) -> codewhale_config::FleetConfigToml {
self.fleet.clone().unwrap_or_default()
}
#[must_use]
pub fn mcp_backend(&self) -> codewhale_config::McpBackend {
self.extension_host
.as_ref()
.map_or(codewhale_config::McpBackend::default(), |host| {
host.mcp_backend
})
}
#[must_use]
pub fn workflow_config(&self) -> codewhale_config::WorkflowConfigToml {
self.workflow.clone().unwrap_or_default()
}
#[must_use]
pub fn model_bound_redaction(&self) -> codewhale_config::redaction::ModelBoundMasking {
self.redaction
.as_ref()
.map(codewhale_config::redaction::RedactionToml::model_bound_masking)
.unwrap_or_default()
}
pub fn redaction_confirmation_required(&self) -> bool {
codewhale_config::redaction::confirmation_required(
self.model_bound_redaction(),
self.loaded_config_path.as_deref(),
)
}
pub fn record_redaction_confirmation(&self) -> anyhow::Result<std::path::PathBuf> {
let path = self.loaded_config_path.as_deref().ok_or_else(|| {
anyhow::anyhow!("No loaded config file can receive this confirmation")
})?;
codewhale_config::redaction::record_model_bound_disabled_confirmation(path)
.map_err(anyhow::Error::from)
}
#[must_use]
pub fn reasoning_effort(&self) -> Option<&str> {
self.reasoning_effort.as_deref()
}
pub fn reasoning_effort_is_explicit(&self) -> bool {
self.reasoning_effort.is_some() && !self.reasoning_effort_inferred_from_legacy_alias
}
pub fn hooks_config(&self) -> HooksConfig {
self.hooks.clone().unwrap_or_default()
}
#[must_use]
pub fn notifications_config(&self) -> NotificationsConfig {
let mut notifications = self.notifications.clone().unwrap_or_default();
notifications.condition = Some(
notifications
.condition
.or_else(|| self.tui.as_ref().and_then(|tui| tui.notification_condition))
.unwrap_or(NotificationCondition::Unfocused),
);
notifications
}
#[must_use]
pub fn approval_default_selection(&self) -> ApprovalDefaultSelection {
self.approval.unwrap_or_default().default_selection
}
#[must_use]
pub fn approval_timeout(&self) -> Option<std::time::Duration> {
const MAX_SECONDS: u64 = 86_400;
let seconds = self.approval.unwrap_or_default().timeout_seconds?;
if seconds == 0 {
return None;
}
if seconds > MAX_SECONDS {
tracing::warn!(
"[approval] timeout_seconds={seconds} exceeds 24h; clamping to {MAX_SECONDS}"
);
}
Some(std::time::Duration::from_secs(seconds.min(MAX_SECONDS)))
}
#[must_use]
pub fn snapshots_config(&self) -> SnapshotsConfig {
self.snapshots.clone().unwrap_or_default()
}
#[must_use]
pub fn skills_config(&self) -> SkillsConfig {
self.skills.clone().unwrap_or_default()
}
#[must_use]
pub fn update_config(&self) -> UpdateConfig {
self.update.clone().unwrap_or_default()
}
#[must_use]
pub fn cloud_facts_config(&self) -> CloudFactsConfig {
self.cloud_facts.clone().unwrap_or_default()
}
#[must_use]
pub fn resolve_hotbar_bindings(
&self,
known_action_ids: &[&str],
) -> codewhale_config::HotbarConfigResolution {
codewhale_config::resolve_hotbar_bindings(self.hotbar.as_deref(), known_action_ids)
}
#[must_use]
pub fn features(&self) -> Features {
let mut features = Features::with_defaults();
if let Some(table) = &self.features {
features.apply_map(&table.entries);
}
features
}
pub fn set_feature(&mut self, key: &str, enabled: bool) -> Result<()> {
if !is_known_feature_key(key) {
anyhow::bail!("Unknown feature flag: {key}");
}
let table = self.features.get_or_insert_with(FeaturesToml::default);
table.entries.insert(key.to_string(), enabled);
Ok(())
}
#[must_use]
pub fn retry_policy(&self) -> RetryPolicy {
let defaults = RetryPolicy {
rate_limit: RateLimitRetryPolicy::default(),
enabled: true,
max_retries: 3,
initial_delay: 1.0,
max_delay: 60.0,
exponential_base: 2.0,
jitter: true,
jitter_factor: 0.1,
respect_retry_after: true,
};
let Some(cfg) = &self.retry else {
return defaults;
};
RetryPolicy {
rate_limit: cfg.rate_limit.clone(),
enabled: cfg.enabled.unwrap_or(defaults.enabled),
max_retries: cfg.max_retries.unwrap_or(defaults.max_retries),
initial_delay: cfg.initial_delay.unwrap_or(defaults.initial_delay),
max_delay: cfg.max_delay.unwrap_or(defaults.max_delay),
exponential_base: cfg.exponential_base.unwrap_or(defaults.exponential_base),
jitter: cfg.jitter.unwrap_or(defaults.jitter),
jitter_factor: cfg
.jitter_factor
.filter(|factor| factor.is_finite())
.map_or(defaults.jitter_factor, |factor| factor.clamp(0.0, 1.0)),
respect_retry_after: cfg
.respect_retry_after
.unwrap_or(defaults.respect_retry_after),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigEnvironmentPolicy {
Runtime,
StructuralDiagnostic,
}
impl ConfigEnvironmentPolicy {
const fn permits_secret_bearing_values(self) -> bool {
matches!(self, Self::Runtime)
}
}
fn root_deepseek_model_is_foreign_to_direct_provider(provider: ProviderKind, model: &str) -> bool {
if matches!(
provider,
ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
) || codewhale_config::descriptors::provider_passes_model_through(provider)
{
return false;
}
if matches!(
provider,
ProviderKind::NvidiaNim
| ProviderKind::Openrouter
| ProviderKind::Orcarouter
| ProviderKind::Novita
| ProviderKind::Fireworks
| ProviderKind::Siliconflow
| ProviderKind::SiliconflowCN
| ProviderKind::Deepinfra
| ProviderKind::Together
| ProviderKind::Sglang
| ProviderKind::Vllm
| ProviderKind::Volcengine
| ProviderKind::Atlascloud
| ProviderKind::OpencodeGo
| ProviderKind::WanjieArk
| ProviderKind::Huggingface
| ProviderKind::XiaomiMimo
| ProviderKind::Moonshot
) {
return false;
}
codewhale_config::route::resolve_model(ProviderKind::Deepseek, model, None)
.is_ok_and(|resolved| !resolved.is_auto)
}
mod paths;
#[cfg(any(test, feature = "test-support"))]
pub use paths::clipboard_images_dir_for_home;
use paths::{
canonicalize_or_keep, codewhale_home_dir, default_config_path, default_managed_config_path,
default_mcp_config_path, default_memory_path, default_notes_path, default_requirements_path,
default_skills_dir, env_config_path, expand_pathbuf, try_default_config_path,
workspace_config_key,
};
pub use paths::{
clipboard_images_dir, expand_path, home_config_path, is_home_config_path, owned_skills_dir,
};
pub fn initialize_cloud_facts(config: &Config) {
let settings = config.cloud_facts_config().settings();
codewhale_cloud_facts::configure(&settings);
codewhale_cloud_facts::maybe_load_persisted_cache(&settings);
if tokio::runtime::Handle::try_current().is_ok() {
codewhale_cloud_facts::spawn_background_refresh(settings, None);
}
}
pub fn workspace_trust_config_candidate_paths() -> Vec<PathBuf> {
#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
{
if !crate::test_support::guarded_environment_provides_state_paths() {
return vec![
crate::test_support::unsealed_test_state_root()
.join(codewhale_config::CONFIG_FILE_NAME),
];
}
}
match env_config_path() {
Ok(Some(path)) => return vec![path],
Ok(None) => {}
Err(error) => {
tracing::error!(
error = %error,
"invalid config path override; refusing workspace-trust fallback"
);
return Vec::new();
}
}
match codewhale_home_dir() {
Ok(Some(codewhale_home)) => return vec![codewhale_home.join("config.toml")],
Ok(None) => {}
Err(error) => {
tracing::error!(
error = %error,
"invalid Codewhale home override; refusing workspace-trust fallback"
);
return Vec::new();
}
}
let Some(home) = codewhale_paths::user_home() else {
return Vec::new();
};
vec![
home.join(".codewhale").join("config.toml"),
home.join(".deepseek").join("config.toml"),
]
}
pub fn needs_trust(workspace: &Path) -> bool {
if is_workspace_trusted(workspace) {
return false;
}
let markers = [
workspace.join(".deepseek").join("trusted"),
workspace.join(".deepseek").join("trust.json"),
];
!markers.iter().any(|path| path.exists())
}
#[must_use]
pub fn is_workspace_trusted(workspace: &Path) -> bool {
let config_path = match default_config_path() {
Ok(path) => path,
Err(error) => {
tracing::error!(
error = %error,
"failed to resolve workspace-trust config; treating workspace as untrusted"
);
return false;
}
};
let Ok(raw) = fs::read_to_string(config_path) else {
return false;
};
let Ok(doc) = toml::from_str::<toml::Value>(&raw) else {
return false;
};
workspace_trust_level_from_doc(&doc, workspace).is_some_and(is_trusted_level)
}
pub fn save_workspace_trust(workspace: &Path) -> Result<PathBuf> {
set_workspace_trust(workspace, true)
}
pub fn set_workspace_trust(workspace: &Path, trusted: bool) -> Result<PathBuf> {
let config_path =
try_default_config_path().context("Failed to resolve config path for workspace trust.")?;
ensure_parent_dir(&config_path)?;
let project_key = workspace_config_key(workspace);
crate::config_persistence::mutate_config_document(&config_path, |doc| {
crate::config_persistence::set_document_value(
doc,
&["projects", project_key.as_str(), "trust_level"],
if trusted { "trusted" } else { "untrusted" },
)
})
.with_context(|| format!("Failed to write config to {}", config_path.display()))?;
Ok(config_path)
}
pub const HOOKS_RECEIPT_KEY: &str = "hooks_sha256";
pub const MCP_RECEIPT_KEY: &str = "mcp_sha256";
pub fn project_receipt_for_workspace(workspace: &Path, key: &str) -> Option<String> {
let raw = fs::read_to_string(default_config_path().ok()?).ok()?;
let doc = toml::from_str::<toml::Value>(&raw).ok()?;
doc.get("projects")?
.get(workspace_config_key(workspace))?
.get(key)?
.as_str()
.map(str::to_owned)
}
pub fn save_workspace_project_receipt(
workspace: &Path,
key: &str,
digest: &str,
) -> Result<PathBuf> {
let config_path = try_default_config_path()?;
ensure_parent_dir(&config_path)?;
let project_key = workspace_config_key(workspace);
crate::config_persistence::mutate_config_document(&config_path, |doc| {
crate::config_persistence::set_document_value(
doc,
&["projects", project_key.as_str(), key],
digest,
)
})?;
Ok(config_path)
}
pub fn hook_receipt_for_workspace(workspace: &Path) -> Option<String> {
project_receipt_for_workspace(workspace, HOOKS_RECEIPT_KEY)
}
pub fn save_workspace_hook_receipt(workspace: &Path, digest: &str) -> Result<PathBuf> {
save_workspace_project_receipt(workspace, HOOKS_RECEIPT_KEY, digest)
}
fn workspace_trust_level_from_doc<'a>(doc: &'a toml::Value, workspace: &Path) -> Option<&'a str> {
let workspace = canonicalize_or_keep(workspace);
let mut scope = Some(doc);
while let Some(current) = scope {
if let Some(projects) = current.get("projects").and_then(toml::Value::as_table) {
for (raw_path, project) in projects {
let project_path = canonicalize_or_keep(&expand_path(raw_path));
if project_path == workspace {
return project.get("trust_level").and_then(toml::Value::as_str);
}
}
}
scope = current.get("extras");
}
None
}
fn is_trusted_level(level: &str) -> bool {
level.trim().eq_ignore_ascii_case("trusted")
}
pub fn resolve_load_config_path(path: Option<PathBuf>) -> Result<Option<PathBuf>> {
if let Some(path) = path {
return Ok(Some(expand_pathbuf(path)));
}
try_default_config_path().map(Some)
}
pub fn ensure_config_file_exists(path: Option<PathBuf>) -> Result<Option<PathBuf>> {
let config_path = match path {
Some(path) => expand_pathbuf(path),
None => default_config_path().context("Failed to resolve config path.")?,
};
if config_path.exists() {
return Ok(None);
}
ensure_parent_dir(&config_path)?;
let content = format!(
r#"# codewhale Configuration
# Get your API key from https://platform.deepseek.com
# Save it with: codewhale auth set --provider deepseek
# Base URL (default: https://api.deepseek.com/beta)
# Set https://api.deepseek.com to opt out of beta features.
# base_url = "https://api.deepseek.com/beta"
# Default model
default_text_model = "{DEFAULT_TEXT_MODEL}"
# Thinking mode (DeepSeek V4 reasoning effort):
# "auto" | "off" | "low" | "medium" | "high" | "max"
# Ctrl+T in the TUI (or /effort) cycles the active model's effort levels.
reasoning_effort = "auto"
# Startup update check
[update]
check_for_updates = true
# check_interval_hours = 1
# update_uri = "https://internal.mirror.example/codewhale/releases/latest"
"#
);
write_config_file_secure(&config_path, &content)
.with_context(|| format!("Failed to write config to {}", config_path.display()))?;
Ok(Some(config_path))
}
fn env_base_url_override() -> Option<String> {
codewhale_env_var("CODEWHALE_BASE_URL", "DEEPSEEK_BASE_URL")
.ok()
.filter(|v| !v.trim().is_empty())
}
fn first_nonempty_env(names: &[&str]) -> Option<String> {
let read = || {
names.iter().find_map(|name| {
std::env::var(name)
.ok()
.filter(|value| !value.trim().is_empty())
})
};
#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
{
crate::test_support::with_test_env_lock(read)
}
#[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
{
read()
}
}
fn provider_env_base_url_override(provider: ProviderKind) -> Option<String> {
let names: &[&str] = match provider {
ProviderKind::NvidiaNim => &["NVIDIA_NIM_BASE_URL", "NIM_BASE_URL", "NVIDIA_BASE_URL"],
ProviderKind::Openai => &["OPENAI_BASE_URL"],
ProviderKind::Atlascloud => &["ATLASCLOUD_BASE_URL"],
ProviderKind::Openrouter => &["OPENROUTER_BASE_URL"],
ProviderKind::Orcarouter => &["ORCA_API_BASE_URL", "ORCA_BASE_URL", "ORCAROUTER_BASE_URL"],
ProviderKind::XiaomiMimo => &["XIAOMI_MIMO_BASE_URL", "MIMO_BASE_URL"],
ProviderKind::WanjieArk => &[
"WANJIE_ARK_BASE_URL",
"WANJIE_BASE_URL",
"WANJIE_MAAS_BASE_URL",
],
ProviderKind::Volcengine => &[
"VOLCENGINE_BASE_URL",
"VOLCENGINE_ARK_BASE_URL",
"ARK_BASE_URL",
],
ProviderKind::Novita => &["NOVITA_BASE_URL"],
ProviderKind::Fireworks => &["FIREWORKS_BASE_URL"],
ProviderKind::Siliconflow | ProviderKind::SiliconflowCN => &["SILICONFLOW_BASE_URL"],
ProviderKind::Arcee => &["ARCEE_BASE_URL"],
ProviderKind::Moonshot => &["MOONSHOT_BASE_URL", "KIMI_BASE_URL"],
ProviderKind::Sglang => &["SGLANG_BASE_URL"],
ProviderKind::Vllm => &["VLLM_BASE_URL"],
ProviderKind::Ollama => &["OLLAMA_BASE_URL"],
ProviderKind::OllamaCloud => &["OLLAMA_CLOUD_BASE_URL"],
ProviderKind::Huggingface => &["HUGGINGFACE_BASE_URL", "HF_BASE_URL"],
ProviderKind::Modelscope => &["MODELSCOPE_BASE_URL"],
ProviderKind::Meta => &["META_MODEL_API_BASE_URL", "MODEL_API_BASE_URL"],
ProviderKind::Xai => &["XAI_BASE_URL"],
ProviderKind::Mistral => &["MISTRAL_BASE_URL"],
ProviderKind::Google => &["GOOGLE_BASE_URL", "GEMINI_BASE_URL"],
ProviderKind::Antigravity => &[],
ProviderKind::Telecomjs => &["TELECOMJS_BASE_URL"],
ProviderKind::Edenai => &["EDENAI_BASE_URL"],
ProviderKind::Zenmux => &["ZENMUX_BASE_URL"],
ProviderKind::Csdn => &["CSDN_BASE_URL"],
ProviderKind::Concentrate => &["CONCENTRATE_BASE_URL"],
ProviderKind::Codewhale => &["CODEWHALE_API_BASE"],
ProviderKind::ModelstudioTokenPlan | ProviderKind::ModelstudioTokenPlanAnthropic => {
&["MODELSTUDIO_TOKEN_PLAN_BASE_URL"]
}
ProviderKind::ModelstudioCodingPlan | ProviderKind::ModelstudioCodingPlanAnthropic => {
&["MODELSTUDIO_CODING_PLAN_BASE_URL"]
}
ProviderKind::OpencodeGo => &["OPENCODE_GO_BASE_URL"],
ProviderKind::OpencodeZen => &["OPENCODE_ZEN_BASE_URL"],
ProviderKind::Deepseek
| ProviderKind::DeepseekAnthropic
| ProviderKind::Anthropic
| ProviderKind::Openmodel
| ProviderKind::Deepinfra
| ProviderKind::Together
| ProviderKind::Qianfan
| ProviderKind::OpenaiCodex
| ProviderKind::Zai
| ProviderKind::Stepfun
| ProviderKind::Minimax
| ProviderKind::MinimaxAnthropic
| ProviderKind::Sakana
| ProviderKind::LongCat
| ProviderKind::Custom => &[],
};
if provider == ProviderKind::Codewhale {
return first_nonempty_env(names)
.as_deref()
.and_then(codewhale_config::provider::codewhale_api_base);
}
first_nonempty_env(names)
}
fn codewhale_env_var(
codewhale_name: &str,
legacy_name: &str,
) -> Result<String, std::env::VarError> {
let read = || {
std::env::var(codewhale_name)
.ok()
.filter(|value| !value.trim().is_empty())
.or_else(|| {
std::env::var(legacy_name)
.ok()
.filter(|value| !value.trim().is_empty())
})
.ok_or(std::env::VarError::NotPresent)
};
#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
{
crate::test_support::with_test_env_lock(read)
}
#[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
{
read()
}
}
fn apply_env_overrides(config: &mut Config, policy: ConfigEnvironmentPolicy) {
#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
{
crate::test_support::with_test_env_lock(|| {
apply_env_overrides_unlocked(config, policy);
})
}
#[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
{
apply_env_overrides_unlocked(config, policy);
}
}
fn apply_env_overrides_unlocked(config: &mut Config, policy: ConfigEnvironmentPolicy) {
if let Ok(value) = codewhale_env_var("CODEWHALE_PROVIDER", "DEEPSEEK_PROVIDER") {
config.provider = Some(value);
config.route_provenance.provider_from_env = true;
config.route_provenance.provider_from_saved_selection = false;
config.route_provenance.provider_from_profile = false;
}
let Ok(identity) = config.active_provider_identity() else {
return;
};
let active_provider = identity.provider;
let active_base_url_from_env = env_base_url_override().is_some()
|| provider_env_base_url_override(active_provider).is_some()
|| (config.selects_legacy_ollama_cloud_route()
&& first_nonempty_env(&["OLLAMA_BASE_URL"]).is_some());
let changes_root_authority = active_base_url_from_env
|| (policy.permits_secret_bearing_values()
&& std::env::var("CODEWHALE_HTTP_HEADERS")
.or_else(|_| std::env::var("DEEPSEEK_HTTP_HEADERS"))
.is_ok());
let identity = if identity.legacy_root_custom_generation.is_some() && changes_root_authority {
let Ok(exact) = config.resolve_exact_provider_identity(identity.key.as_str()) else {
return;
};
config.legacy_root_custom_generation = None;
exact
} else {
identity
};
if let Ok(value) = codewhale_env_var("CODEWHALE_BASE_URL", "DEEPSEEK_BASE_URL")
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::NvidiaNim)
&& let Ok(value) = std::env::var("NVIDIA_NIM_BASE_URL")
.or_else(|_| std::env::var("NIM_BASE_URL"))
.or_else(|_| std::env::var("NVIDIA_BASE_URL"))
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Openai)
&& let Ok(value) = std::env::var("OPENAI_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Atlascloud)
&& let Ok(value) = std::env::var("ATLASCLOUD_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Openrouter)
&& let Ok(value) = std::env::var("OPENROUTER_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::XiaomiMimo)
&& let Ok(value) =
std::env::var("XIAOMI_MIMO_BASE_URL").or_else(|_| std::env::var("MIMO_BASE_URL"))
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::XiaomiMimo)
&& let Ok(value) = std::env::var("XIAOMI_MIMO_MODE").or_else(|_| std::env::var("MIMO_MODE"))
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.mode = Some(value);
}
if matches!(active_provider, ProviderKind::WanjieArk)
&& let Ok(value) = std::env::var("WANJIE_ARK_BASE_URL")
.or_else(|_| std::env::var("WANJIE_BASE_URL"))
.or_else(|_| std::env::var("WANJIE_MAAS_BASE_URL"))
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Volcengine)
&& let Ok(value) = std::env::var("VOLCENGINE_BASE_URL")
.or_else(|_| std::env::var("VOLCENGINE_ARK_BASE_URL"))
.or_else(|_| std::env::var("ARK_BASE_URL"))
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Novita)
&& let Ok(value) = std::env::var("NOVITA_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Fireworks)
&& let Ok(value) = std::env::var("FIREWORKS_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(
active_provider,
ProviderKind::Siliconflow | ProviderKind::SiliconflowCN
) && let Ok(value) = std::env::var("SILICONFLOW_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Arcee)
&& let Ok(value) = std::env::var("ARCEE_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Huggingface)
&& let Ok(value) =
std::env::var("HUGGINGFACE_BASE_URL").or_else(|_| std::env::var("HF_BASE_URL"))
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Modelscope)
&& let Ok(value) = std::env::var("MODELSCOPE_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Moonshot)
&& let Ok(value) =
std::env::var("MOONSHOT_BASE_URL").or_else(|_| std::env::var("KIMI_BASE_URL"))
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Sglang)
&& let Ok(value) = std::env::var("SGLANG_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Vllm)
&& let Ok(value) = std::env::var("VLLM_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Meta)
&& let Ok(value) = std::env::var("META_MODEL_API_BASE_URL")
.or_else(|_| std::env::var("MODEL_API_BASE_URL"))
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Xai)
&& let Ok(value) = std::env::var("XAI_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Mistral)
&& let Ok(value) = std::env::var("MISTRAL_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Telecomjs)
&& let Ok(value) = std::env::var("TELECOMJS_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Edenai)
&& let Ok(value) = std::env::var("EDENAI_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Zenmux)
&& let Ok(value) = std::env::var("ZENMUX_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Csdn)
&& let Ok(value) = std::env::var("CSDN_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(
active_provider,
ProviderKind::ModelstudioTokenPlan | ProviderKind::ModelstudioTokenPlanAnthropic
) && let Ok(value) = std::env::var("MODELSTUDIO_TOKEN_PLAN_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(
active_provider,
ProviderKind::ModelstudioCodingPlan | ProviderKind::ModelstudioCodingPlanAnthropic
) && let Ok(value) = std::env::var("MODELSTUDIO_CODING_PLAN_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if policy.permits_secret_bearing_values()
&& let Ok(value) = std::env::var("CODEWHALE_HTTP_HEADERS")
.or_else(|_| std::env::var("DEEPSEEK_HTTP_HEADERS"))
&& let Ok(headers) = parse_http_headers(&value)
&& !headers.is_empty()
{
let mut root_headers = config.http_headers.clone().unwrap_or_default();
root_headers.extend(headers.clone());
config.http_headers = Some(root_headers);
if let Ok(entry) = config.provider_config_for_mut(&identity) {
let mut provider_headers = entry.http_headers.clone().unwrap_or_default();
provider_headers.extend(headers);
entry.http_headers = Some(provider_headers);
}
}
if config.provider.as_deref().and_then(ProviderKind::parse) == Some(ProviderKind::Ollama)
&& let Ok(value) = std::env::var("OLLAMA_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::OllamaCloud)
&& config.provider.as_deref().and_then(ProviderKind::parse)
== Some(ProviderKind::OllamaCloud)
&& let Ok(value) = std::env::var("OLLAMA_CLOUD_BASE_URL")
&& !value.trim().is_empty()
&& let Ok(entry) = config.provider_config_for_mut(&identity)
{
entry.base_url = Some(value);
}
if matches!(active_provider, ProviderKind::Sglang)
&& let Ok(value) = std::env::var("SGLANG_MODEL")
{
config.default_text_model = Some(value.clone());
config
.set_provider_model_override(&identity, Some(value))
.unwrap();
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Vllm)
&& let Ok(value) = std::env::var("VLLM_MODEL")
{
config.default_text_model = Some(value.clone());
config
.set_provider_model_override(&identity, Some(value))
.unwrap();
config.environment_model_applied = true;
}
if matches!(
active_provider,
ProviderKind::Ollama | ProviderKind::OllamaCloud
) && let Ok(value) = std::env::var("OLLAMA_MODEL")
{
config.default_text_model = Some(value.clone());
config
.set_provider_model_override(&identity, Some(value))
.unwrap();
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::OllamaCloud)
&& let Ok(value) = std::env::var("OLLAMA_CLOUD_MODEL")
{
config.default_text_model = Some(value.clone());
config
.set_provider_model_override(&identity, Some(value))
.unwrap();
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Openai)
&& let Ok(value) = std::env::var("OPENAI_MODEL")
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::XiaomiMimo)
&& let Ok(value) =
std::env::var("XIAOMI_MIMO_MODEL").or_else(|_| std::env::var("MIMO_MODEL"))
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Atlascloud)
&& let Ok(value) = std::env::var("ATLASCLOUD_MODEL")
{
config.default_text_model = Some(value.clone());
config
.set_provider_model_override(&identity, Some(value))
.unwrap();
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::WanjieArk)
&& let Ok(value) = std::env::var("WANJIE_ARK_MODEL")
.or_else(|_| std::env::var("WANJIE_MODEL"))
.or_else(|_| std::env::var("WANJIE_MAAS_MODEL"))
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Openrouter)
&& let Ok(value) = std::env::var("OPENROUTER_MODEL")
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Volcengine)
&& let Ok(value) =
std::env::var("VOLCENGINE_MODEL").or_else(|_| std::env::var("VOLCENGINE_ARK_MODEL"))
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Novita)
&& let Ok(value) = std::env::var("NOVITA_MODEL")
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Fireworks)
&& let Ok(value) = std::env::var("FIREWORKS_MODEL")
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Moonshot)
&& let Ok(value) = std::env::var("MOONSHOT_MODEL")
.or_else(|_| std::env::var("KIMI_MODEL_NAME"))
.or_else(|_| std::env::var("KIMI_MODEL"))
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(
active_provider,
ProviderKind::Siliconflow | ProviderKind::SiliconflowCN
) && let Ok(value) = std::env::var("SILICONFLOW_MODEL")
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Arcee)
&& let Ok(value) = std::env::var("ARCEE_MODEL")
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Huggingface)
&& let Ok(value) = std::env::var("HUGGINGFACE_MODEL").or_else(|_| std::env::var("HF_MODEL"))
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Modelscope)
&& let Ok(value) = std::env::var("MODELSCOPE_MODEL")
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Meta)
&& let Ok(value) =
std::env::var("META_MODEL_API_MODEL").or_else(|_| std::env::var("MODEL_API_MODEL"))
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Xai)
&& let Ok(value) = std::env::var("XAI_MODEL")
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Mistral)
&& let Ok(value) = std::env::var("MISTRAL_MODEL")
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::OpencodeGo)
&& let Ok(value) = std::env::var("OPENCODE_GO_MODEL")
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Telecomjs)
&& let Ok(value) = std::env::var("TELECOMJS_MODEL")
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Concentrate)
&& let Ok(value) = std::env::var("CONCENTRATE_MODEL")
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Edenai)
&& let Ok(value) = std::env::var("EDENAI_MODEL")
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Zenmux)
&& let Ok(value) = std::env::var("ZENMUX_MODEL")
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::Csdn)
&& let Ok(value) = std::env::var("CSDN_MODEL")
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(
active_provider,
ProviderKind::ModelstudioTokenPlan | ProviderKind::ModelstudioTokenPlanAnthropic
) && let Ok(value) = std::env::var("MODELSTUDIO_TOKEN_PLAN_MODEL")
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(
active_provider,
ProviderKind::ModelstudioCodingPlan | ProviderKind::ModelstudioCodingPlanAnthropic
) && let Ok(value) = std::env::var("MODELSTUDIO_CODING_PLAN_MODEL")
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::OpencodeZen)
&& let Ok(value) = std::env::var("OPENCODE_ZEN_MODEL")
&& !value.trim().is_empty()
{
if let Ok(entry) = config.provider_config_for_mut(&identity) {
entry.model = Some(value);
}
config.environment_model_applied = true;
}
if matches!(active_provider, ProviderKind::NvidiaNim)
&& let Ok(value) = std::env::var("NVIDIA_NIM_MODEL")
{
config.default_text_model = Some(value.clone());
config
.set_provider_model_override(&identity, Some(value))
.unwrap();
config.environment_model_applied = true;
}
if let Some(value) = codewhale_env_var("CODEWHALE_MODEL", "DEEPSEEK_MODEL")
.ok()
.or_else(|| {
std::env::var("DEEPSEEK_DEFAULT_TEXT_MODEL")
.ok()
.filter(|value| !value.trim().is_empty())
})
{
if matches!(
active_provider,
ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
) {
config.default_text_model = Some(value.clone());
}
config
.set_provider_model_override(&identity, Some(value))
.unwrap();
config.environment_model_applied = true;
}
if let Ok(value) =
std::env::var("CODEWHALE_SKILLS_DIR").or_else(|_| std::env::var("DEEPSEEK_SKILLS_DIR"))
{
config.skills_dir = Some(value);
}
if let Ok(value) =
std::env::var("CODEWHALE_MCP_CONFIG").or_else(|_| std::env::var("DEEPSEEK_MCP_CONFIG"))
{
config.mcp_config_path = Some(value);
}
if let Ok(value) =
std::env::var("CODEWHALE_NOTES_PATH").or_else(|_| std::env::var("DEEPSEEK_NOTES_PATH"))
{
config.notes_path = Some(value);
}
if let Ok(value) =
std::env::var("CODEWHALE_MEMORY_PATH").or_else(|_| std::env::var("DEEPSEEK_MEMORY_PATH"))
{
config.memory_path = Some(value);
}
if let Ok(value) =
std::env::var("CODEWHALE_MEMORY").or_else(|_| std::env::var("DEEPSEEK_MEMORY"))
{
let on = matches!(
value.trim().to_ascii_lowercase().as_str(),
"1" | "on" | "true" | "yes" | "y" | "enabled"
);
config
.memory
.get_or_insert_with(MemoryConfig::default)
.enabled = Some(on);
}
if let Ok(value) =
std::env::var("CODEWHALE_ALLOW_SHELL").or_else(|_| std::env::var("DEEPSEEK_ALLOW_SHELL"))
{
config.allow_shell = Some(value == "1" || value.eq_ignore_ascii_case("true"));
}
if let Ok(value) = std::env::var("CODEWHALE_APPROVAL_POLICY")
.or_else(|_| std::env::var("DEEPSEEK_APPROVAL_POLICY"))
{
config.approval_policy = Some(value);
}
if let Ok(value) =
std::env::var("CODEWHALE_SANDBOX_MODE").or_else(|_| std::env::var("DEEPSEEK_SANDBOX_MODE"))
{
config.sandbox_mode = Some(value);
}
if let Ok(value) = std::env::var("CODEWHALE_SANDBOX_NETWORK_ACCESS")
.or_else(|_| std::env::var("DEEPSEEK_SANDBOX_NETWORK_ACCESS"))
{
config.sandbox_network_access = Some(value == "1" || value.eq_ignore_ascii_case("true"));
}
if let Ok(value) = std::env::var("CODEWHALE_PROJECT_INSTRUCTION_IMPORTS") {
config.project_instruction_imports = value
.split(',')
.map(str::trim)
.filter(|part| !part.is_empty())
.map(str::to_string)
.collect();
}
if let Ok(value) = std::env::var("CODEWHALE_YOLO").or_else(|_| std::env::var("DEEPSEEK_YOLO")) {
config.yolo = Some(value == "1" || value.eq_ignore_ascii_case("true"));
}
if let Ok(value) =
std::env::var("CODEWHALE_VERBOSITY").or_else(|_| std::env::var("DEEPSEEK_VERBOSITY"))
{
config.verbosity = Some(value);
}
if let Ok(value) = std::env::var("CODEWHALE_SANDBOX_BACKEND")
.or_else(|_| std::env::var("DEEPSEEK_SANDBOX_BACKEND"))
{
config.sandbox_backend = Some(value);
}
if let Ok(value) = codewhale_env_var("CODEWHALE_PREFER_BWRAP", "DEEPSEEK_PREFER_BWRAP") {
let primary_is_set = std::env::var("CODEWHALE_PREFER_BWRAP")
.ok()
.is_some_and(|value| !value.trim().is_empty());
let legacy_is_set = std::env::var("DEEPSEEK_PREFER_BWRAP")
.ok()
.is_some_and(|value| !value.trim().is_empty());
if !primary_is_set && legacy_is_set {
tracing::warn!(
"DEEPSEEK_PREFER_BWRAP is deprecated; use CODEWHALE_PREFER_BWRAP (the legacy alias is removed in 0.10.0)"
);
}
config.prefer_bwrap = Some(value == "1" || value.eq_ignore_ascii_case("true"));
}
if let Ok(value) =
std::env::var("CODEWHALE_SANDBOX_URL").or_else(|_| std::env::var("DEEPSEEK_SANDBOX_URL"))
{
config.sandbox_url = Some(value);
}
if policy.permits_secret_bearing_values()
&& let Ok(value) = std::env::var("CODEWHALE_SANDBOX_API_KEY")
.or_else(|_| std::env::var("DEEPSEEK_SANDBOX_API_KEY"))
{
config.sandbox_api_key = Some(value);
}
if let Ok(value) = codewhale_env_var(
"CODEWHALE_MANAGED_CONFIG_PATH",
"DEEPSEEK_MANAGED_CONFIG_PATH",
) {
config.managed_config_path = Some(value);
}
if policy.permits_secret_bearing_values()
&& let Ok(value) = std::env::var("CODEWHALE_SEARCH_API_KEY")
.or_else(|_| std::env::var("DEEPSEEK_SEARCH_API_KEY"))
&& !value.trim().is_empty()
{
config
.search
.get_or_insert_with(SearchConfig::default)
.api_key = Some(value);
}
if let Ok(value) = codewhale_env_var("CODEWHALE_SEARCH_BASE_URL", "DEEPSEEK_SEARCH_BASE_URL") {
config
.search
.get_or_insert_with(SearchConfig::default)
.base_url = Some(value);
}
if let Ok(value) = std::env::var("CODEWHALE_REQUIREMENTS_PATH")
.or_else(|_| std::env::var("DEEPSEEK_REQUIREMENTS_PATH"))
{
config.requirements_path = Some(value);
}
if let Ok(value) = std::env::var("CODEWHALE_MAX_SUBAGENTS")
.or_else(|_| std::env::var("DEEPSEEK_MAX_SUBAGENTS"))
&& let Ok(parsed) = value.parse::<usize>()
{
config.max_subagents = Some(parsed.clamp(1, MAX_SUBAGENTS));
}
config.base_url_env_receipt = if active_base_url_from_env {
BaseUrlEnvReceipt::Route(active_provider, identity.key.to_string())
} else {
BaseUrlEnvReceipt::NoOwner
};
}
fn normalize_model_config(config: &mut Config) {
if config.default_text_model.is_none() {
config.default_text_model.clone_from(&config.legacy_model);
}
let Ok(identity) = config.active_provider_identity() else {
return;
};
let provider = identity.provider;
let base_url = config.active_route_base_url();
let mut declared = Vec::new();
for row in codewhale_config::descriptors::provider_compatibility() {
let Ok(candidate) = config.resolve_persisted_provider_identity(Some(row.id), Some(row.id))
else {
continue;
};
for model in config.custom_models.as_deref().unwrap_or_default() {
if configured_model_for_route(
config,
candidate.provider,
candidate.key.as_str(),
&config.base_url_for_route(&candidate),
&model.id,
)
.is_some()
{
declared.push((candidate.key.clone(), model.id.clone()));
}
}
}
let is_declared = |key: &str, model: &str| {
declared
.iter()
.any(|(id, value)| id.as_str() == key && value == model)
};
config.migrated_deepseek_model_alias = if matches!(
provider,
ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
) {
config
.active_configured_model_id()
.filter(|model| !is_declared(identity.key.as_str(), model))
.map(str::to_ascii_lowercase)
.filter(|model| deepseek_alias_deprecation(model).is_some())
.filter(|model| {
codewhale_config::route::resolve_model(provider, model, Some(&base_url))
.is_ok_and(|resolved| resolved.wire_id != model.as_str())
})
} else {
None
};
if config.reasoning_effort.is_none() {
let alias_effort = config
.migrated_deepseek_model_alias
.as_deref()
.and_then(legacy_deepseek_alias_reasoning_effort);
if let Some(effort) = alias_effort {
config.reasoning_effort = Some(effort.to_string());
config.reasoning_effort_inferred_from_legacy_alias = true;
}
}
if let Some(model) = config.default_text_model.as_deref()
&& !is_declared(identity.key.as_str(), model)
&& !codewhale_config::descriptors::provider_passes_model_through(provider)
&& !config.active_provider_preserves_custom_base_url_model()
&& let Ok(resolved) = codewhale_config::route::resolve_model(provider, model, None)
{
config.default_text_model = Some(resolved.wire_id);
}
if let Some(providers) = config.providers.as_mut() {
if let Some(model) = providers.deepseek.model.as_deref()
&& !provider_entry_uses_custom_base_url(ProviderKind::Deepseek, &providers.deepseek)
&& !is_declared(ProviderKind::Deepseek.as_str(), model)
&& let Ok(resolved) =
codewhale_config::route::resolve_model(ProviderKind::Deepseek, model, None)
{
providers.deepseek.model = Some(resolved.wire_id);
}
if let Some(model) = providers.deepseek_cn.model.as_deref()
&& !provider_entry_uses_custom_base_url(ProviderKind::Deepseek, &providers.deepseek_cn)
&& !is_declared(codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id, model)
&& let Ok(resolved) =
codewhale_config::route::resolve_model(ProviderKind::Deepseek, model, None)
{
providers.deepseek_cn.model = Some(resolved.wire_id);
}
if let Some(model) = providers.deepseek_anthropic.model.as_deref()
&& !provider_entry_uses_custom_base_url(
ProviderKind::DeepseekAnthropic,
&providers.deepseek_anthropic,
)
&& !is_declared(ProviderKind::DeepseekAnthropic.as_str(), model)
&& let Ok(resolved) =
codewhale_config::route::resolve_model(ProviderKind::DeepseekAnthropic, model, None)
{
providers.deepseek_anthropic.model = Some(resolved.wire_id);
}
if let Some(model) = providers.nvidia_nim.model.as_deref()
&& !provider_entry_uses_custom_base_url(ProviderKind::NvidiaNim, &providers.nvidia_nim)
&& !is_declared(ProviderKind::NvidiaNim.as_str(), model)
&& let Ok(resolved) =
codewhale_config::route::resolve_model(ProviderKind::NvidiaNim, model, None)
{
providers.nvidia_nim.model = Some(resolved.wire_id);
}
if let Some(model) = providers.openrouter.model.as_deref()
&& !provider_entry_uses_custom_base_url(ProviderKind::Openrouter, &providers.openrouter)
&& !is_declared(ProviderKind::Openrouter.as_str(), model)
&& let Ok(resolved) =
codewhale_config::route::resolve_model(ProviderKind::Openrouter, model, None)
{
providers.openrouter.model = Some(resolved.wire_id);
}
if let Some(model) = providers.novita.model.as_deref()
&& !provider_entry_uses_custom_base_url(ProviderKind::Novita, &providers.novita)
&& !is_declared(ProviderKind::Novita.as_str(), model)
&& let Ok(resolved) =
codewhale_config::route::resolve_model(ProviderKind::Novita, model, None)
{
providers.novita.model = Some(resolved.wire_id);
}
if let Some(model) = providers.fireworks.model.as_deref()
&& !provider_entry_uses_custom_base_url(ProviderKind::Fireworks, &providers.fireworks)
&& !is_declared(ProviderKind::Fireworks.as_str(), model)
&& let Ok(resolved) =
codewhale_config::route::resolve_model(ProviderKind::Fireworks, model, None)
{
providers.fireworks.model = Some(resolved.wire_id);
}
if let Some(model) = providers.siliconflow.model.as_deref()
&& !provider_entry_uses_custom_base_url(
ProviderKind::Siliconflow,
&providers.siliconflow,
)
&& !is_declared(ProviderKind::Siliconflow.as_str(), model)
&& let Ok(resolved) =
codewhale_config::route::resolve_model(ProviderKind::Siliconflow, model, None)
{
providers.siliconflow.model = Some(resolved.wire_id);
}
if let Some(model) = providers.siliconflow_cn.model.as_deref()
&& !provider_entry_uses_custom_base_url(
ProviderKind::SiliconflowCN,
&providers.siliconflow_cn,
)
&& !is_declared(ProviderKind::SiliconflowCN.as_str(), model)
&& let Ok(resolved) =
codewhale_config::route::resolve_model(ProviderKind::SiliconflowCN, model, None)
{
providers.siliconflow_cn.model = Some(resolved.wire_id);
}
if let Some(model) = providers.moonshot.model.as_deref()
&& !provider_entry_uses_custom_base_url(ProviderKind::Moonshot, &providers.moonshot)
&& !is_declared(ProviderKind::Moonshot.as_str(), model)
&& let Ok(resolved) =
codewhale_config::route::resolve_model(ProviderKind::Moonshot, model, None)
{
providers.moonshot.model = Some(resolved.wire_id);
}
if let Some(model) = providers.sglang.model.as_deref()
&& !provider_entry_uses_custom_base_url(ProviderKind::Sglang, &providers.sglang)
&& !is_declared(ProviderKind::Sglang.as_str(), model)
&& let Ok(resolved) =
codewhale_config::route::resolve_model(ProviderKind::Sglang, model, None)
{
providers.sglang.model = Some(resolved.wire_id);
}
if let Some(model) = providers.vllm.model.as_deref()
&& !provider_entry_uses_custom_base_url(ProviderKind::Vllm, &providers.vllm)
&& !is_declared(ProviderKind::Vllm.as_str(), model)
&& let Ok(resolved) =
codewhale_config::route::resolve_model(ProviderKind::Vllm, model, None)
{
providers.vllm.model = Some(resolved.wire_id);
}
if let Some(model) = providers.deepinfra.model.as_deref()
&& !provider_entry_uses_custom_base_url(ProviderKind::Deepinfra, &providers.deepinfra)
&& !is_declared(ProviderKind::Deepinfra.as_str(), model)
&& let Ok(resolved) =
codewhale_config::route::resolve_model(ProviderKind::Deepinfra, model, None)
{
providers.deepinfra.model = Some(resolved.wire_id);
}
}
}
#[cfg(any(test, feature = "test-support"))]
pub fn normalize_model_config_for_test(config: &mut Config) {
normalize_model_config(config);
}
fn provider_entry_uses_custom_base_url(provider: ProviderKind, entry: &ProviderConfig) -> bool {
entry
.base_url
.as_deref()
.is_some_and(|base_url| provider_preserves_custom_base_url_model(provider, base_url))
}
fn xiaomi_mimo_base_url_uses_token_plan(base_url: &str) -> bool {
let normalized = normalize_base_url(base_url).to_ascii_lowercase();
normalized == XIAOMI_MIMO_TOKEN_PLAN_CN_BASE_URL
|| normalized == XIAOMI_MIMO_TOKEN_PLAN_SGP_BASE_URL
|| normalized == XIAOMI_MIMO_TOKEN_PLAN_AMS_BASE_URL
}
fn xiaomi_mimo_env_var(candidates: &[&str]) -> Option<String> {
candidates.iter().find_map(|name| {
std::env::var(name)
.ok()
.filter(|value| !value.trim().is_empty())
})
}
fn xiaomi_mimo_env_api_key_for_runtime(
mode: Option<&str>,
base_url: Option<&str>,
) -> Option<String> {
const TOKEN_PLAN_ENV_VARS: &[&str] =
&["XIAOMI_MIMO_TOKEN_PLAN_API_KEY", "MIMO_TOKEN_PLAN_API_KEY"];
const STANDARD_ENV_VARS: &[&str] = &["XIAOMI_MIMO_API_KEY", "XIAOMI_API_KEY", "MIMO_API_KEY"];
let normalized_mode =
mode.map(|value| value.trim().to_ascii_lowercase().replace(['_', ' '], "-"));
let standard_selected = normalized_mode
.as_deref()
.is_some_and(xiaomi_mimo_mode_uses_standard_endpoint)
|| base_url.is_some_and(xiaomi_mimo_base_url_is_pay_as_you_go);
if standard_selected {
return xiaomi_mimo_env_var(STANDARD_ENV_VARS);
}
let token_plan_selected = normalized_mode
.as_deref()
.and_then(xiaomi_mimo_base_url_for_mode)
.is_some()
|| base_url.is_some_and(xiaomi_mimo_base_url_uses_token_plan);
if token_plan_selected {
return xiaomi_mimo_env_var(TOKEN_PLAN_ENV_VARS);
}
xiaomi_mimo_env_var(TOKEN_PLAN_ENV_VARS).or_else(|| xiaomi_mimo_env_var(STANDARD_ENV_VARS))
}
fn wire_config_prefers_anthropic(wire: Option<&str>) -> bool {
codewhale_config::provider::wire_dialect_prefers_anthropic(wire)
}
fn modelstudio_mode_is_coding_plan(provider: ProviderKind, mode: Option<&str>) -> bool {
if matches!(
provider,
ProviderKind::ModelstudioCodingPlan | ProviderKind::ModelstudioCodingPlanAnthropic
) {
return true;
}
let Some(raw) = mode.map(str::trim).filter(|value| !value.is_empty()) else {
return false;
};
let normalized = raw.to_ascii_lowercase().replace(['_', ' '], "-");
matches!(
normalized.as_str(),
"coding-plan" | "coding" | "codingplan" | "dashscope-coding" | "code"
)
}
fn resolve_modelstudio_base_url_for_tui(
configured: Option<String>,
provider: ProviderKind,
mode: Option<&str>,
wire: Option<&str>,
) -> String {
if let Some(url) = configured.filter(|value| !value.trim().is_empty()) {
return url;
}
let coding = modelstudio_mode_is_coding_plan(provider, mode);
let anthropic = matches!(
provider,
ProviderKind::ModelstudioTokenPlanAnthropic | ProviderKind::ModelstudioCodingPlanAnthropic
) || wire_config_prefers_anthropic(wire);
match (coding, anthropic) {
(true, true) => MODELSTUDIO_CODING_PLAN_ANTHROPIC_BASE_URL.to_string(),
(true, false) => DEFAULT_MODELSTUDIO_CODING_PLAN_BASE_URL.to_string(),
(false, true) => MODELSTUDIO_TOKEN_PLAN_ANTHROPIC_BASE_URL.to_string(),
(false, false) => DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL.to_string(),
}
}
fn resolve_minimax_base_url_for_tui(
configured: Option<String>,
provider: ProviderKind,
wire: Option<&str>,
) -> String {
if let Some(url) = configured.filter(|value| !value.trim().is_empty()) {
return url;
}
if matches!(provider, ProviderKind::MinimaxAnthropic) || wire_config_prefers_anthropic(wire) {
DEFAULT_MINIMAX_ANTHROPIC_BASE_URL.to_string()
} else {
DEFAULT_MINIMAX_BASE_URL.to_string()
}
}
fn resolve_deepseek_base_url_for_tui(
configured: Option<String>,
provider: ProviderKind,
wire: Option<&str>,
) -> String {
if let Some(url) = configured.filter(|value| !value.trim().is_empty()) {
return url;
}
if matches!(provider, ProviderKind::DeepseekAnthropic) || wire_config_prefers_anthropic(wire) {
DEFAULT_DEEPSEEK_ANTHROPIC_BASE_URL.to_string()
} else {
DEFAULT_DEEPSEEK_BASE_URL.to_string()
}
}
fn xiaomi_mimo_base_url_is_pay_as_you_go(base_url: &str) -> bool {
matches!(
normalize_base_url(base_url).to_ascii_lowercase().as_str(),
"https://api.xiaomimimo.com" | "https://api.xiaomimimo.com/v1"
)
}
fn base_url_is_custom_for_provider(provider: ProviderKind, base_url: &str) -> bool {
codewhale_config::provider_preserves_custom_base_url_model(provider, base_url)
}
pub fn provider_route_is_keyless_self_hosted(provider: ProviderKind, base_url: &str) -> bool {
if provider == ProviderKind::Ollama {
return base_url_uses_local_host(base_url);
}
matches!(
provider,
ProviderKind::Ollama | ProviderKind::Sglang | ProviderKind::Vllm
)
}
pub fn moonshot_base_url_is_exact_kimi_code(base_url: &str) -> bool {
codewhale_config::provider::is_exact_kimi_code_route(
codewhale_config::ProviderKind::Moonshot,
base_url,
)
}
pub fn moonshot_base_url_is_exact_direct_platform(base_url: &str) -> bool {
codewhale_config::provider::is_exact_moonshot_platform_route(
codewhale_config::ProviderKind::Moonshot,
base_url,
)
}
pub fn is_exact_direct_moonshot_k3_route(
provider: ProviderKind,
base_url: &str,
model: &str,
) -> bool {
provider == ProviderKind::Moonshot
&& moonshot_base_url_is_exact_direct_platform(base_url)
&& model.trim().eq_ignore_ascii_case(MOONSHOT_KIMI_K3_MODEL)
}
pub fn is_exact_kimi_code_k3_route(provider: ProviderKind, base_url: &str, model: &str) -> bool {
provider == ProviderKind::Moonshot
&& moonshot_base_url_is_exact_kimi_code(base_url)
&& [KIMI_CODE_K3_MODEL, KIMI_CODE_K3_256K_MODEL]
.iter()
.any(|id| model.trim().eq_ignore_ascii_case(id))
}
#[must_use]
pub fn is_exact_kimi_code_bare_k3_route(
provider: ProviderKind,
base_url: &str,
model: &str,
) -> bool {
provider == ProviderKind::Moonshot
&& moonshot_base_url_is_exact_kimi_code(base_url)
&& model.trim().eq_ignore_ascii_case(KIMI_CODE_K3_MODEL)
}
#[must_use]
pub fn is_exact_zai_chat_route(provider: ProviderKind, base_url: &str) -> bool {
provider == ProviderKind::Zai
&& codewhale_config::provider::is_exact_zai_chat_route(
codewhale_config::ProviderKind::Zai,
base_url,
)
}
#[must_use]
pub fn is_exact_zai_tiered_effort_route(
provider: ProviderKind,
base_url: &str,
model: &str,
) -> bool {
is_exact_zai_chat_route(provider, base_url)
&& (model.trim().eq_ignore_ascii_case(ZAI_GLM_5_2_MODEL)
|| is_exact_zai_forced_thinking_route(provider, base_url, model))
}
#[must_use]
pub fn is_exact_zai_forced_thinking_route(
provider: ProviderKind,
base_url: &str,
model: &str,
) -> bool {
is_exact_zai_chat_route(provider, base_url)
&& (model.trim().eq_ignore_ascii_case(ZAI_GLM_5_3_MODEL)
|| model.trim().eq_ignore_ascii_case(ZAI_GLM_5_3_FLASH_MODEL))
}
#[must_use]
pub(crate) fn is_exact_zai_glm_5_turbo_route(
provider: ProviderKind,
base_url: &str,
model: &str,
) -> bool {
is_exact_zai_chat_route(provider, base_url)
&& model.trim().eq_ignore_ascii_case(ZAI_GLM_5_TURBO_MODEL)
}
#[must_use]
pub fn is_exact_known_zai_reasoning_route(
provider: ProviderKind,
base_url: &str,
model: &str,
) -> bool {
is_exact_zai_tiered_effort_route(provider, base_url, model)
|| is_exact_zai_glm_5_turbo_route(provider, base_url, model)
|| (is_exact_zai_chat_route(provider, base_url)
&& model.trim().eq_ignore_ascii_case(ZAI_GLM_5_1_MODEL))
}
#[must_use]
pub fn minimax_base_url_is_supported_direct(base_url: &str) -> bool {
codewhale_config::provider::is_exact_minimax_chat_route(
codewhale_config::ProviderKind::Minimax,
base_url,
) || codewhale_config::provider::is_exact_minimax_anthropic_route(
codewhale_config::ProviderKind::MinimaxAnthropic,
base_url,
)
}
#[must_use]
pub fn is_exact_minimax_m3_route(provider: ProviderKind, base_url: &str, model: &str) -> bool {
provider == ProviderKind::Minimax
&& codewhale_config::provider::is_exact_minimax_chat_route(
codewhale_config::ProviderKind::Minimax,
base_url,
)
&& model.trim().eq_ignore_ascii_case(DEFAULT_MINIMAX_MODEL)
}
#[must_use]
pub fn is_exact_minimax_anthropic_m3_route(
provider: ProviderKind,
base_url: &str,
model: &str,
) -> bool {
provider == ProviderKind::MinimaxAnthropic
&& codewhale_config::provider::is_exact_minimax_anthropic_route(
codewhale_config::ProviderKind::MinimaxAnthropic,
base_url,
)
&& model.trim().eq_ignore_ascii_case(DEFAULT_MINIMAX_MODEL)
}
#[must_use]
pub fn minimax_m3_route_uses_max_completion_tokens(
provider: ProviderKind,
base_url: &str,
model: &str,
) -> bool {
is_exact_minimax_m3_route(provider, base_url, model)
}
pub const KIMI_CODE_MEMBERSHIP_MODELS: [&str; 4] = [
KIMI_CODE_K3_MODEL,
KIMI_CODE_K3_256K_MODEL,
DEFAULT_KIMI_CODE_MODEL,
KIMI_CODE_HIGHSPEED_MODEL,
];
#[must_use]
pub fn is_kimi_code_membership_model(model: &str) -> bool {
let model = model.trim();
KIMI_CODE_MEMBERSHIP_MODELS
.iter()
.any(|id| model.eq_ignore_ascii_case(id))
}
fn deepseek_missing_key_message() -> &'static str {
concat!(
"DeepSeek API key not found.\n",
"Save a key for every folder:\n",
" codewhale auth set --provider deepseek\n",
"Get a key: https://platform.deepseek.com/api_keys\n",
"Or export DEEPSEEK_API_KEY=<your-key> (this shell only).\n",
"In zsh, ~/.zshrc is read only by interactive shells.\n",
"Or set api_key in ~/.codewhale/config.toml.\n",
"If you already use DeepSeek Harness, grant read-only access:\n",
" codewhale auth external-consent --provider deepseek --mode read-only"
)
}
pub(crate) const MOONSHOT_DIRECT_PLATFORM_MODELS: [&str; 3] = [
MOONSHOT_KIMI_K3_MODEL,
DEFAULT_MOONSHOT_MODEL,
MOONSHOT_KIMI_K2_6_MODEL,
];
pub(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.";
#[derive(Debug, thiserror::Error)]
pub enum SafeConfigDiagnostic {
#[error("{}", KIMI_CODE_CLAUDE_ALIAS_GUIDANCE)]
KimiCodeClaudeAlias,
#[error("{message}")]
InvalidValue {
message: String,
shareable: String,
fix: Option<String>,
},
}
impl SafeConfigDiagnostic {
fn invalid_value(key: &str, value: &str, expected: &str, fix: String) -> Self {
Self::InvalidValue {
message: format!("Invalid {key} '{value}': expected {expected}."),
shareable: format!("Invalid {key} (value not shown): expected {expected}."),
fix: Some(fix),
}
}
pub fn display_message(&self) -> String {
let text = match self {
Self::KimiCodeClaudeAlias => self.to_string(),
Self::InvalidValue { shareable, .. } => shareable.clone(),
};
codewhale_sanitize::redact::redact_secrets(&text)
}
pub fn fix(&self) -> Option<&str> {
match self {
Self::KimiCodeClaudeAlias => None,
Self::InvalidValue { fix, .. } => fix.as_deref(),
}
}
pub fn find_in(error: &anyhow::Error) -> Option<&Self> {
error.chain().find_map(|cause| cause.downcast_ref::<Self>())
}
}
fn user_config_fix(key: &str, valid: &str, env_var: Option<&str>) -> String {
let edit = match key.split_once('.') {
Some((table, field)) => {
format!("set {field} = \"{valid}\" in the [{table}] table of config.toml")
}
None => format!("codewhale config set {key} {valid}"),
};
let layers = match env_var {
Some(env_var) => format!("{env_var}, a profile, or managed config"),
None => "a profile or managed config".to_string(),
};
format!("{edit} (if {layers} sets it, correct it there)")
}
fn invalid_provider_diagnostic(provider: &str) -> SafeConfigDiagnostic {
SafeConfigDiagnostic::invalid_value(
"provider",
provider,
&ProviderKind::names_hint(),
user_config_fix(
"provider",
ProviderKind::Deepseek.as_str(),
Some("CODEWHALE_PROVIDER"),
),
)
}
pub(crate) fn invalid_provider_message(provider: &str) -> String {
invalid_provider_diagnostic(provider).to_string()
}
pub fn validate_kimi_code_api_model_id(
provider: ProviderKind,
base_url: &str,
model: &str,
) -> std::result::Result<(), String> {
if provider != ProviderKind::Moonshot {
return Ok(());
}
let model = model.trim();
if model.is_empty() {
return Ok(());
}
if moonshot_base_url_is_exact_kimi_code(base_url) {
if model.eq_ignore_ascii_case("k3[1m]") {
return Err(KIMI_CODE_CLAUDE_ALIAS_GUIDANCE.to_string());
}
for direct_id in MOONSHOT_DIRECT_PLATFORM_MODELS {
if model.eq_ignore_ascii_case(direct_id) {
return Err(format!(
"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}\"."
));
}
}
return Ok(());
}
if moonshot_base_url_is_exact_direct_platform(base_url) {
for membership_id in KIMI_CODE_MEMBERSHIP_MODELS {
if model.eq_ignore_ascii_case(membership_id) {
return Err(format!(
"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\"."
));
}
}
}
Ok(())
}
#[cfg(test)]
mod kimi_code_pairing_tests {
use super::*;
#[test]
fn membership_roster_passes_on_kimi_code_endpoint() {
for model in [
KIMI_CODE_K3_MODEL,
KIMI_CODE_K3_256K_MODEL,
DEFAULT_KIMI_CODE_MODEL,
KIMI_CODE_HIGHSPEED_MODEL,
] {
assert!(
validate_kimi_code_api_model_id(
ProviderKind::Moonshot,
DEFAULT_KIMI_CODE_BASE_URL,
model,
)
.is_ok(),
"{model} must be accepted on the exact Kimi Code membership endpoint"
);
}
}
#[test]
fn direct_platform_ids_fail_on_kimi_code_endpoint() {
for model in [
MOONSHOT_KIMI_K3_MODEL,
DEFAULT_MOONSHOT_MODEL,
MOONSHOT_KIMI_K2_6_MODEL,
] {
let err = validate_kimi_code_api_model_id(
ProviderKind::Moonshot,
DEFAULT_KIMI_CODE_BASE_URL,
model,
)
.expect_err("direct-platform ids are not Kimi Code membership roster models");
assert!(err.contains(model), "{err}");
assert!(err.contains("api.moonshot.ai/v1"), "{err}");
}
}
#[test]
fn membership_ids_fail_on_direct_moonshot_endpoint() {
for model in [
KIMI_CODE_K3_MODEL,
KIMI_CODE_K3_256K_MODEL,
DEFAULT_KIMI_CODE_MODEL,
KIMI_CODE_HIGHSPEED_MODEL,
] {
let err = validate_kimi_code_api_model_id(
ProviderKind::Moonshot,
DEFAULT_MOONSHOT_BASE_URL,
model,
)
.expect_err("membership ids are not direct-platform catalog models");
assert!(err.contains(model), "{err}");
assert!(err.contains("api.kimi.com/coding/v1"), "{err}");
}
}
#[test]
fn canonical_pairs_pass_and_custom_gateways_are_untouched() {
for (base_url, model) in [
(DEFAULT_KIMI_CODE_BASE_URL, KIMI_CODE_K3_MODEL),
(DEFAULT_KIMI_CODE_BASE_URL, KIMI_CODE_K3_256K_MODEL),
(DEFAULT_KIMI_CODE_BASE_URL, DEFAULT_KIMI_CODE_MODEL),
(DEFAULT_KIMI_CODE_BASE_URL, KIMI_CODE_HIGHSPEED_MODEL),
(DEFAULT_MOONSHOT_BASE_URL, MOONSHOT_KIMI_K3_MODEL),
(DEFAULT_MOONSHOT_BASE_URL, DEFAULT_MOONSHOT_MODEL),
(DEFAULT_MOONSHOT_BASE_URL, MOONSHOT_KIMI_K2_6_MODEL),
] {
assert!(
validate_kimi_code_api_model_id(ProviderKind::Moonshot, base_url, model).is_ok(),
"{base_url} / {model}"
);
}
assert!(
validate_kimi_code_api_model_id(
ProviderKind::Moonshot,
DEFAULT_KIMI_CODE_BASE_URL,
MOONSHOT_KIMI_K3_MODEL,
)
.is_err()
);
assert!(
validate_kimi_code_api_model_id(
ProviderKind::Moonshot,
DEFAULT_MOONSHOT_BASE_URL,
KIMI_CODE_K3_MODEL,
)
.is_err()
);
for model in [
KIMI_CODE_K3_MODEL,
KIMI_CODE_K3_256K_MODEL,
DEFAULT_KIMI_CODE_MODEL,
KIMI_CODE_HIGHSPEED_MODEL,
MOONSHOT_KIMI_K3_MODEL,
] {
assert!(
validate_kimi_code_api_model_id(
ProviderKind::Moonshot,
"https://proxy.example/v1",
model,
)
.is_ok(),
"{model} on a custom gateway"
);
}
}
}
pub fn moonshot_k3_route_display_name(base_url: &str, model: &str) -> Option<&'static str> {
if is_exact_kimi_code_bare_k3_route(ProviderKind::Moonshot, base_url, model) {
return Some("Kimi Code membership / k3");
}
if is_exact_kimi_code_k3_route(ProviderKind::Moonshot, base_url, model) {
return Some("Kimi Code membership / k3-256k");
}
if is_exact_direct_moonshot_k3_route(ProviderKind::Moonshot, base_url, model) {
return Some("Moonshot direct / kimi-k3");
}
None
}
pub fn credential_help_for_provider_route(
provider: ProviderKind,
base_url: &str,
) -> codewhale_config::provider::CredentialHelp {
codewhale_config::provider::credential_help_for_route(provider, base_url)
}
pub fn provider_config_uses_kimi_imported_token(config: &ProviderConfig) -> bool {
config
.auth_mode
.as_deref()
.is_some_and(auth_mode_uses_kimi_imported_token)
}
use codewhale_config::{
auth_mode_disables_api_key, auth_mode_requires_api_key, auth_mode_uses_kimi_imported_token,
};
fn provider_config_uses_xai_oauth(config: &ProviderConfig) -> bool {
config
.auth_mode
.as_deref()
.is_some_and(crate::oauth::auth_mode_uses_xai_oauth)
}
pub fn base_url_uses_local_host(base_url: &str) -> bool {
let Some(host) = base_url_host(base_url) else {
return false;
};
let host = host.trim_matches(['[', ']']).to_ascii_lowercase();
if matches!(host.as_str(), "localhost" | "0.0.0.0") {
return true;
}
host.parse::<std::net::IpAddr>()
.is_ok_and(|addr| addr.is_loopback() || addr.is_unspecified())
}
pub fn normalize_base_url(base: &str) -> String {
let trimmed = base.trim_end_matches('/');
let deepseek_domains = ["api.deepseek.com", "api.deepseeki.com"];
if deepseek_domains
.iter()
.any(|domain| trimmed.contains(domain))
{
return trimmed.trim_end_matches("/v1").to_string();
}
trimmed.to_string()
}
fn parse_http_headers(raw: &str) -> Result<HashMap<String, String>> {
let mut headers = HashMap::new();
for pair in raw.trim().split(',') {
let pair = pair.trim();
if pair.is_empty() {
continue;
}
let Some((name, value)) = pair.split_once('=') else {
anyhow::bail!("invalid header pair '{pair}', expected name=value");
};
let name = name.trim();
let value = value.trim();
if name.is_empty() {
anyhow::bail!("header name cannot be empty");
}
if value.is_empty() {
continue;
}
headers.insert(name.to_string(), value.to_string());
}
Ok(headers)
}
fn apply_layer_root_model(config: &mut Config, layer: &Config) {
if layer.default_text_model.is_none() && layer.legacy_model.is_none() {
return;
}
let Ok(identity) = config.active_provider_identity() else {
return;
};
let mut scoped = layer.clone();
if scoped.scope_to_provider_identity(&identity).is_err() {
return;
}
if scoped
.provider_config_for(&identity)
.and_then(|entry| entry.model.as_ref())
.is_none()
{
config.set_provider_model_override(&identity, None).unwrap();
}
}
fn apply_profile(config: ConfigFile, profile: Option<&str>) -> Result<Config> {
if let Some(profile_name) = profile {
let profiles = config.profiles.as_ref();
match profiles.and_then(|profiles| profiles.get(profile_name)) {
Some(override_cfg) => {
let mut merged = merge_config(*config.base, override_cfg.clone());
apply_layer_root_model(&mut merged, override_cfg);
merged.route_provenance.provider_from_profile = override_cfg.provider.is_some();
let merged_identity = merged.active_provider_identity().ok();
merged.route_provenance.model_from_profile =
override_cfg.default_text_model.is_some()
|| override_cfg.legacy_model.is_some()
|| merged_identity.as_ref().is_some_and(|id| {
override_cfg
.provider_config_for(id)
.and_then(|entry| entry.model.as_deref())
.is_some()
});
Ok(merged)
}
None => {
let available = profiles
.map(|profiles| {
let mut keys = profiles.keys().cloned().collect::<Vec<_>>();
keys.sort();
if keys.is_empty() {
"none".to_string()
} else {
keys.join(", ")
}
})
.unwrap_or_else(|| "none".to_string());
Err(SafeConfigDiagnostic::InvalidValue {
message: format!(
"Profile '{profile_name}' not found. Available profiles: {available}"
),
shareable: format!(
"Profile not found (name not shown). Available profiles: {available}"
),
fix: None,
}
.into())
}
}
} else {
Ok(*config.base)
}
}
fn merge_config(base: Config, override_cfg: Config) -> Config {
Config {
model_http_policy: override_cfg.model_http_policy.or(base.model_http_policy),
custom_models: override_cfg.custom_models.or(base.custom_models),
extra_trusted_paths: if override_cfg.extra_trusted_paths.is_empty() {
base.extra_trusted_paths
} else {
override_cfg.extra_trusted_paths
},
provider: override_cfg.provider.or(base.provider),
telemetry: override_cfg.telemetry.or(base.telemetry),
http_headers: override_cfg.http_headers.or(base.http_headers),
default_text_model: override_cfg
.default_text_model
.or_else(|| override_cfg.legacy_model.clone())
.or(base.default_text_model)
.or_else(|| base.legacy_model.clone()),
legacy_model: override_cfg.legacy_model.or(base.legacy_model),
redaction: override_cfg.redaction.or(base.redaction),
loaded_config_path: override_cfg.loaded_config_path.or(base.loaded_config_path),
remembered_selection_scope: override_cfg
.remembered_selection_scope
.or(base.remembered_selection_scope),
route_preferences_version: override_cfg
.route_preferences_version
.or(base.route_preferences_version),
environment_model_applied: override_cfg.environment_model_applied
|| base.environment_model_applied,
route_provenance: base.route_provenance,
auth_mode: override_cfg.auth_mode.or(base.auth_mode),
reasoning_effort: override_cfg.reasoning_effort.or(base.reasoning_effort),
reasoning_effort_inferred_from_legacy_alias: override_cfg
.reasoning_effort_inferred_from_legacy_alias
|| base.reasoning_effort_inferred_from_legacy_alias,
fleet_operator_route_applied: override_cfg.fleet_operator_route_applied
|| base.fleet_operator_route_applied,
fleet_operator_reasoning_applied: override_cfg.fleet_operator_reasoning_applied
|| base.fleet_operator_reasoning_applied,
migrated_legacy_ollama_cloud_route: override_cfg.migrated_legacy_ollama_cloud_route
|| base.migrated_legacy_ollama_cloud_route,
migrated_deepseek_model_alias: override_cfg
.migrated_deepseek_model_alias
.or(base.migrated_deepseek_model_alias),
tools: override_cfg.tools.or(base.tools),
skills_dir: override_cfg.skills_dir.or(base.skills_dir),
mcp_config_path: override_cfg.mcp_config_path.or(base.mcp_config_path),
mcp_oauth_callback_port: override_cfg
.mcp_oauth_callback_port
.or(base.mcp_oauth_callback_port),
mcp_oauth_callback_url: override_cfg
.mcp_oauth_callback_url
.or(base.mcp_oauth_callback_url),
notes_path: override_cfg.notes_path.or(base.notes_path),
memory_path: override_cfg.memory_path.or(base.memory_path),
vision_model: override_cfg.vision_model.or(base.vision_model),
instructions: override_cfg.instructions.or(base.instructions),
instruction_budget: override_cfg.instruction_budget.or(base.instruction_budget),
stop_words: override_cfg.stop_words.or(base.stop_words),
allow_shell: override_cfg.allow_shell.or(base.allow_shell),
prompt_suggestion: override_cfg.prompt_suggestion.or(base.prompt_suggestion),
yolo: override_cfg.yolo.or(base.yolo),
verbosity: override_cfg.verbosity.or(base.verbosity),
approval_policy: override_cfg.approval_policy.or(base.approval_policy),
sandbox_mode: override_cfg.sandbox_mode.or(base.sandbox_mode),
sandbox_network_access: override_cfg
.sandbox_network_access
.or(base.sandbox_network_access),
project_instruction_imports: if override_cfg.project_instruction_imports.is_empty() {
base.project_instruction_imports
} else {
override_cfg.project_instruction_imports
},
fallback_providers: if override_cfg.fallback_providers.is_empty() {
base.fallback_providers
} else {
override_cfg.fallback_providers
},
sandbox_backend: override_cfg.sandbox_backend.or(base.sandbox_backend),
sandbox_url: override_cfg.sandbox_url.or(base.sandbox_url),
sandbox_api_key: override_cfg.sandbox_api_key.or(base.sandbox_api_key),
prefer_bwrap: override_cfg.prefer_bwrap.or(base.prefer_bwrap),
tool_launcher: override_cfg.tool_launcher.or(base.tool_launcher),
bwrap_ro_roots: if override_cfg.bwrap_ro_roots.is_empty() {
base.bwrap_ro_roots
} else {
override_cfg.bwrap_ro_roots
},
bwrap_dev_roots: if override_cfg.bwrap_dev_roots.is_empty() {
base.bwrap_dev_roots
} else {
override_cfg.bwrap_dev_roots
},
sandbox_denied_read_paths: if override_cfg.sandbox_denied_read_paths.is_empty() {
base.sandbox_denied_read_paths
} else {
override_cfg.sandbox_denied_read_paths
},
sandbox_read_denylist_defaults: override_cfg
.sandbox_read_denylist_defaults
.or(base.sandbox_read_denylist_defaults),
sandbox_read_denylist_exempt: if override_cfg.sandbox_read_denylist_exempt.is_empty() {
base.sandbox_read_denylist_exempt
} else {
override_cfg.sandbox_read_denylist_exempt
},
managed_config_path: override_cfg
.managed_config_path
.or(base.managed_config_path),
requirements_path: override_cfg.requirements_path.or(base.requirements_path),
max_subagents: override_cfg.max_subagents.or(base.max_subagents),
retry: override_cfg.retry.or(base.retry),
stream: match (base.stream, override_cfg.stream) {
(Some(base), Some(over)) => Some(StreamConfig {
open_timeout_secs: over.open_timeout_secs.or(base.open_timeout_secs),
chunk_timeout_secs: over.chunk_timeout_secs.or(base.chunk_timeout_secs),
force_http1: over.force_http1.or(base.force_http1),
max_resumes: over.max_resumes.or(base.max_resumes),
max_transparent_retries: over
.max_transparent_retries
.or(base.max_transparent_retries),
max_stream_errors: over.max_stream_errors.or(base.max_stream_errors),
max_duration_secs: over.max_duration_secs.or(base.max_duration_secs),
max_content_mb: over.max_content_mb.or(base.max_content_mb),
connect_timeout_secs: over.connect_timeout_secs.or(base.connect_timeout_secs),
tcp_keepalive_secs: over.tcp_keepalive_secs.or(base.tcp_keepalive_secs),
http2_keep_alive_interval_secs: over
.http2_keep_alive_interval_secs
.or(base.http2_keep_alive_interval_secs),
http2_keep_alive_timeout_secs: over
.http2_keep_alive_timeout_secs
.or(base.http2_keep_alive_timeout_secs),
}),
(base, over) => over.or(base),
},
auto_review: override_cfg.auto_review.or(base.auto_review),
tui: override_cfg.tui.or(base.tui),
transcript: override_cfg.transcript.or(base.transcript),
hooks: override_cfg.hooks.or(base.hooks),
lifecycle_outbox: override_cfg.lifecycle_outbox.or(base.lifecycle_outbox),
control_socket: override_cfg.control_socket.or(base.control_socket),
providers: merge_providers(base.providers, override_cfg.providers),
features: merge_features(base.features, override_cfg.features),
extension_host: override_cfg.extension_host.or(base.extension_host),
plugins: override_cfg.plugins.or(base.plugins),
notifications: override_cfg.notifications.or(base.notifications),
approval: override_cfg.approval.or(base.approval),
network: override_cfg.network.or(base.network),
network_layer_is_managed: override_cfg.network_layer_is_managed
|| base.network_layer_is_managed,
verifier: override_cfg.verifier.or(base.verifier),
advisor: override_cfg.advisor.or(base.advisor),
skills: merge_skills_config(base.skills, override_cfg.skills),
snapshots: override_cfg.snapshots.or(base.snapshots),
search: override_cfg.search.or(base.search),
goal: override_cfg.goal.or(base.goal),
memory: override_cfg.memory.or(base.memory),
speech: override_cfg.speech.or(base.speech),
auto: override_cfg.auto.or(base.auto),
hotbar: override_cfg.hotbar.or(base.hotbar),
update: override_cfg.update.or(base.update),
cloud_facts: override_cfg.cloud_facts.or(base.cloud_facts),
lsp: override_cfg.lsp.or(base.lsp),
context: ContextConfig {
project_pack: override_cfg
.context
.project_pack
.or(base.context.project_pack),
},
compaction: override_cfg.compaction.or(base.compaction),
fleet: override_cfg.fleet.or(base.fleet),
workflow: override_cfg.workflow.or(base.workflow),
subagents: override_cfg.subagents.or(base.subagents),
strict_tool_mode: override_cfg.strict_tool_mode.or(base.strict_tool_mode),
runtime_api: override_cfg.runtime_api.or(base.runtime_api),
workshop: override_cfg.workshop.or(base.workshop),
exec_policy_engine: override_cfg.exec_policy_engine,
base_url_env_receipt: match override_cfg.base_url_env_receipt {
BaseUrlEnvReceipt::Unrecorded => base.base_url_env_receipt,
recorded => recorded,
},
legacy_root: base.legacy_root,
legacy_root_custom_generation: base.legacy_root_custom_generation,
account_model_access: base.account_model_access,
session_provider_keys: base.session_provider_keys,
session_provider_keys_only: base.session_provider_keys_only,
required_account_model_owner: base.required_account_model_owner,
account_profile: override_cfg.account_profile.or(base.account_profile),
plugin_oauth_read_only: base.plugin_oauth_read_only || override_cfg.plugin_oauth_read_only,
runtime_chat_isolated: override_cfg.runtime_chat_isolated || base.runtime_chat_isolated,
runtime_thread_inference_unrelated: override_cfg.runtime_thread_inference_unrelated
|| base.runtime_thread_inference_unrelated,
mini_window: override_cfg.mini_window.or(base.mini_window),
reasoning_only: override_cfg.reasoning_only.or(base.reasoning_only),
title: override_cfg.title.or(base.title),
}
}
fn load_sibling_exec_policy_engine(config_path: Option<&Path>) -> Result<ExecPolicyEngine> {
let Some(config_path) = config_path else {
return Ok(ExecPolicyEngine::new(Vec::new(), Vec::new()));
};
let permissions_path = codewhale_config::permissions_path_for_config_path(config_path);
if !permissions_path.exists() {
return Ok(ExecPolicyEngine::new(Vec::new(), Vec::new()));
}
let raw = fs::read_to_string(&permissions_path).with_context(|| {
format!(
"Failed to read permissions file: {}",
permissions_path.display()
)
})?;
let permissions: codewhale_config::PermissionsToml = toml::from_str(&raw).map_err(|_| {
anyhow::anyhow!(
"Failed to parse permissions file {}; file contents were omitted",
codewhale_config::quote_os_path(&permissions_path)
)
})?;
if permissions.is_empty() {
Ok(ExecPolicyEngine::new(Vec::new(), Vec::new()))
} else {
Ok(ExecPolicyEngine::with_rulesets(vec![permissions.ruleset()]))
}
}
fn merge_skills_config(
base: Option<SkillsConfig>,
override_cfg: Option<SkillsConfig>,
) -> Option<SkillsConfig> {
match (base, override_cfg) {
(None, None) => None,
(Some(base), None) => Some(base),
(None, Some(override_cfg)) => Some(override_cfg),
(Some(base), Some(override_cfg)) => Some(SkillsConfig {
bundled: BundledSkillsConfig {
install: override_cfg.bundled.install.or(base.bundled.install),
selected: override_cfg.bundled.selected.or(base.bundled.selected),
disabled: override_cfg.bundled.disabled.or(base.bundled.disabled),
explicit_only: override_cfg
.bundled
.explicit_only
.or(base.bundled.explicit_only),
},
listing_max_description_chars: override_cfg
.listing_max_description_chars
.or(base.listing_max_description_chars),
listing_budget_fraction: override_cfg
.listing_budget_fraction
.or(base.listing_budget_fraction),
registry_url: override_cfg.registry_url.or(base.registry_url),
max_install_size_bytes: override_cfg
.max_install_size_bytes
.or(base.max_install_size_bytes),
scan_codewhale_only: override_cfg
.scan_codewhale_only
.or(base.scan_codewhale_only),
flat_workspace_root: override_cfg
.flat_workspace_root
.or(base.flat_workspace_root),
creator_skills: false,
}),
}
}
fn merge_provider_config(base: ProviderConfig, override_cfg: ProviderConfig) -> ProviderConfig {
ProviderConfig {
vendor: override_cfg.vendor.or(base.vendor),
api_key: override_cfg.api_key.or(base.api_key),
base_url: override_cfg.base_url.or(base.base_url),
model: override_cfg.model.or(base.model),
context_window: override_cfg.context_window.or(base.context_window),
model_context_windows: override_cfg
.model_context_windows
.or(base.model_context_windows),
mode: override_cfg.mode.or(base.mode),
wire: override_cfg.wire.or(base.wire),
responses_profile: override_cfg.responses_profile.or(base.responses_profile),
auth_mode: override_cfg.auth_mode.or(base.auth_mode),
oauth: override_cfg.oauth.or(base.oauth),
plugin_authority: base.plugin_authority,
oauth_credential_generation: override_cfg
.oauth_credential_generation
.or(base.oauth_credential_generation),
insecure_skip_tls_verify: override_cfg
.insecure_skip_tls_verify
.or(base.insecure_skip_tls_verify),
allow_insecure_http: override_cfg
.allow_insecure_http
.or(base.allow_insecure_http),
http_headers: override_cfg.http_headers.or(base.http_headers),
path_suffix: override_cfg.path_suffix.or(base.path_suffix),
reasoning_stream_style: override_cfg
.reasoning_stream_style
.or(base.reasoning_stream_style),
max_concurrency: override_cfg.max_concurrency.or(base.max_concurrency),
auth: override_cfg.auth.or(base.auth),
external_credentials: override_cfg
.external_credentials
.or(base.external_credentials),
kind: override_cfg.kind.or(base.kind),
api_key_env: override_cfg.api_key_env.or(base.api_key_env),
}
}
fn merge_custom_providers(
mut base: HashMap<String, ProviderConfig>,
override_cfg: HashMap<String, ProviderConfig>,
) -> HashMap<String, ProviderConfig> {
for (name, entry) in override_cfg {
let merged = match base.remove(&name) {
Some(base_entry) => merge_provider_config(base_entry, entry),
None => entry,
};
base.insert(name, merged);
}
base
}
fn merge_providers(
base: Option<ProvidersConfig>,
override_cfg: Option<ProvidersConfig>,
) -> Option<ProvidersConfig> {
match (base, override_cfg) {
(None, None) => None,
(Some(base), None) => Some(base),
(None, Some(override_cfg)) => Some(override_cfg),
(Some(base), Some(override_cfg)) => Some(ProvidersConfig {
deepseek: merge_provider_config(base.deepseek, override_cfg.deepseek),
deepseek_cn: merge_provider_config(base.deepseek_cn, override_cfg.deepseek_cn),
deepseek_anthropic: merge_provider_config(
base.deepseek_anthropic,
override_cfg.deepseek_anthropic,
),
nvidia_nim: merge_provider_config(base.nvidia_nim, override_cfg.nvidia_nim),
openai: merge_provider_config(base.openai, override_cfg.openai),
anthropic: merge_provider_config(base.anthropic, override_cfg.anthropic),
openmodel: merge_provider_config(base.openmodel, override_cfg.openmodel),
atlascloud: merge_provider_config(base.atlascloud, override_cfg.atlascloud),
wanjie_ark: merge_provider_config(base.wanjie_ark, override_cfg.wanjie_ark),
openrouter: merge_provider_config(base.openrouter, override_cfg.openrouter),
orcarouter: merge_provider_config(base.orcarouter, override_cfg.orcarouter),
xiaomi_mimo: merge_provider_config(base.xiaomi_mimo, override_cfg.xiaomi_mimo),
novita: merge_provider_config(base.novita, override_cfg.novita),
fireworks: merge_provider_config(base.fireworks, override_cfg.fireworks),
siliconflow: merge_provider_config(base.siliconflow, override_cfg.siliconflow),
siliconflow_cn: merge_provider_config(base.siliconflow_cn, override_cfg.siliconflow_cn),
arcee: merge_provider_config(base.arcee, override_cfg.arcee),
moonshot: merge_provider_config(base.moonshot, override_cfg.moonshot),
sglang: merge_provider_config(base.sglang, override_cfg.sglang),
vllm: merge_provider_config(base.vllm, override_cfg.vllm),
ollama: merge_provider_config(base.ollama, override_cfg.ollama),
ollama_cloud: merge_provider_config(base.ollama_cloud, override_cfg.ollama_cloud),
volcengine: merge_provider_config(base.volcengine, override_cfg.volcengine),
huggingface: merge_provider_config(base.huggingface, override_cfg.huggingface),
modelscope: merge_provider_config(base.modelscope, override_cfg.modelscope),
deepinfra: merge_provider_config(base.deepinfra, override_cfg.deepinfra),
together: merge_provider_config(base.together, override_cfg.together),
qianfan: merge_provider_config(base.qianfan, override_cfg.qianfan),
openai_codex: merge_provider_config(base.openai_codex, override_cfg.openai_codex),
zai: merge_provider_config(base.zai, override_cfg.zai),
stepfun: merge_provider_config(base.stepfun, override_cfg.stepfun),
minimax: merge_provider_config(base.minimax, override_cfg.minimax),
minimax_anthropic: merge_provider_config(
base.minimax_anthropic,
override_cfg.minimax_anthropic,
),
sakana: merge_provider_config(base.sakana, override_cfg.sakana),
longcat: merge_provider_config(base.longcat, override_cfg.longcat),
opencode_go: merge_provider_config(base.opencode_go, override_cfg.opencode_go),
opencode_zen: merge_provider_config(base.opencode_zen, override_cfg.opencode_zen),
meta: merge_provider_config(base.meta, override_cfg.meta),
xai: merge_provider_config(base.xai, override_cfg.xai),
mistral: merge_provider_config(base.mistral, override_cfg.mistral),
google: merge_provider_config(base.google, override_cfg.google),
antigravity: merge_provider_config(base.antigravity, override_cfg.antigravity),
telecomjs: merge_provider_config(base.telecomjs, override_cfg.telecomjs),
edenai: merge_provider_config(base.edenai, override_cfg.edenai),
zenmux: merge_provider_config(base.zenmux, override_cfg.zenmux),
csdn: merge_provider_config(base.csdn, override_cfg.csdn),
concentrate: merge_provider_config(base.concentrate, override_cfg.concentrate),
codewhale: merge_provider_config(base.codewhale, override_cfg.codewhale),
modelstudio_token_plan: merge_provider_config(
base.modelstudio_token_plan,
override_cfg.modelstudio_token_plan,
),
modelstudio_token_plan_anthropic: merge_provider_config(
base.modelstudio_token_plan_anthropic,
override_cfg.modelstudio_token_plan_anthropic,
),
modelstudio_coding_plan: merge_provider_config(
base.modelstudio_coding_plan,
override_cfg.modelstudio_coding_plan,
),
modelstudio_coding_plan_anthropic: merge_provider_config(
base.modelstudio_coding_plan_anthropic,
override_cfg.modelstudio_coding_plan_anthropic,
),
custom: merge_custom_providers(base.custom, override_cfg.custom),
}),
}
}
fn load_single_config_file(path: &Path) -> Result<Config> {
let contents = fs::read_to_string(path)
.with_context(|| format!("Failed to read config file: {}", path.display()))?;
let parsed = parse_config_file(&contents).map_err(|_| {
anyhow::anyhow!(
"Failed to parse config file {}; file contents were omitted",
codewhale_config::quote_os_path(path)
)
})?;
Ok(*parsed.base)
}
#[cfg(any(test, feature = "test-support"))]
impl Config {
pub fn with_legacy_root(mut self, api_key: Option<String>, base_url: Option<String>) -> Self {
self.set_legacy_root(api_key, base_url);
self
}
pub fn deepseek_table_api_key(&self) -> Option<&str> {
self.providers.as_ref()?.deepseek.api_key.as_deref()
}
pub fn deepseek_table_base_url(&self) -> Option<&str> {
self.providers.as_ref()?.deepseek.base_url.as_deref()
}
pub fn set_legacy_root(&mut self, api_key: Option<String>, base_url: Option<String>) {
use toml::Value;
let mut root = toml::Table::new();
if let Some(provider) = &self.provider {
root.insert("provider".into(), Value::String(provider.clone()));
}
if let Some(model) = self
.default_text_model
.clone()
.or(self.legacy_model.clone())
{
root.insert("default_text_model".into(), Value::String(model));
}
if let Some(key) = api_key {
root.insert("api_key".into(), Value::String(key));
}
if let Some(url) = base_url {
root.insert("base_url".into(), Value::String(url));
}
let entry_table = |entry: &ProviderConfig| {
let mut table = toml::Table::new();
if let Some(key) = &entry.api_key {
table.insert("api_key".into(), Value::String(key.clone()));
}
if let Some(url) = &entry.base_url {
table.insert("base_url".into(), Value::String(url.clone()));
}
if let Some(model) = &entry.model {
table.insert("model".into(), Value::String(model.clone()));
}
if let Some(kind) = &entry.kind {
table.insert("kind".into(), Value::String(kind.clone()));
}
table
};
let mut providers = toml::Table::new();
if let Some(configured) = self.providers.as_ref() {
for row in codewhale_config::descriptors::provider_compatibility() {
if let Some(entry) =
codewhale_config::provider_config_table!(@read configured, row.id)
{
providers.insert(row.config_key.to_string(), Value::Table(entry_table(entry)));
}
}
for (name, entry) in &configured.custom {
providers.insert(name.clone(), Value::Table(entry_table(entry)));
}
}
root.insert("providers".into(), Value::Table(providers));
if let Some(vision) = &self.vision_model {
let mut table = toml::Table::new();
if let Some(key) = &vision.api_key {
table.insert("api_key".into(), Value::String(key.clone()));
}
root.insert("vision_model".into(), Value::Table(table));
}
self.legacy_root = codewhale_config::legacy_root::apply_to_table(&mut root);
if let Some(provider) = root.get("provider").and_then(Value::as_str) {
self.provider = Some(provider.to_string());
}
if let (Some(vision), Some(key)) = (
self.vision_model.as_mut(),
root.get("vision_model")
.and_then(|table| table.get("api_key"))
.and_then(Value::as_str),
) {
vision.api_key = Some(key.to_string());
}
let Some(providers) = root.get("providers").and_then(Value::as_table) else {
return;
};
for (key, table) in providers {
let Some(table) = table.as_table() else {
continue;
};
let entry = if let Some(row) = codewhale_config::descriptors::provider_compatibility()
.iter()
.find(|row| row.config_key == key && row.kind != ProviderKind::Custom)
{
let configured = self.providers.get_or_insert_with(ProvidersConfig::default);
let Some(entry) =
codewhale_config::provider_config_table!(@write configured, row.id)
else {
continue;
};
entry
} else {
self.providers
.get_or_insert_with(ProvidersConfig::default)
.custom
.entry(key.clone())
.or_default()
};
let get = |field: &str| table.get(field).and_then(Value::as_str).map(str::to_string);
entry.api_key = get("api_key");
entry.base_url = get("base_url");
entry.model = get("model");
entry.kind = get("kind");
}
self.bind_legacy_root_custom_generation();
}
}
pub fn parse_config_base(contents: &str) -> std::result::Result<Config, toml::de::Error> {
let parsed = parse_config_file(contents)?;
let mut config = *parsed.base;
config.legacy_root = parsed.legacy_root;
Ok(config)
}
pub fn parse_config_after_locked_migration(
contents: &str,
moved: &codewhale_config::legacy_root::LegacyRootMigration,
) -> std::result::Result<Config, toml::de::Error> {
let mut config = parse_config_base(contents)?;
config.legacy_root.notes.extend(moved.notes.iter().cloned());
config.bind_legacy_root_custom_generation();
Ok(config)
}
fn parse_config_file(contents: &str) -> std::result::Result<ConfigFile, toml::de::Error> {
let (text, legacy_root) = codewhale_config::legacy_root::canonicalize_text(contents)?;
let mut parsed = toml::from_str::<ConfigFile>(&text)?;
parsed.base.legacy_root = legacy_root.clone();
parsed.base.bind_legacy_root_custom_generation();
parsed.legacy_root = legacy_root;
Ok(parsed)
}
fn warn_on_misplaced_top_level_keys(raw: &str) -> Option<String> {
let doc = toml::from_str::<toml::Value>(raw).ok()?;
const UNKNOWN_SECTIONS: &[&str] = &["general", "sandbox"];
const TOP_LEVEL_KEYS: &[&str] = &[
"allow_shell",
"sandbox_mode",
"approval_policy",
"verbosity",
];
let mut hits: Vec<String> = Vec::new();
for section in UNKNOWN_SECTIONS {
let Some(table) = doc.get(*section).and_then(toml::Value::as_table) else {
continue;
};
for key in TOP_LEVEL_KEYS {
if table.contains_key(*key) {
hits.push(format!("`{section}.{key}`"));
}
}
}
if hits.is_empty() {
return None;
}
Some(format!(
"Ignoring {} — Codewhale has no `[general]` or `[sandbox]` section, so these \
keys are silently dropped. Move them to the TOP of the config file (above any \
`[section]` header), e.g. `allow_shell = true`. Until then, shell tools stay \
disabled. (#2589)",
hits.join(", ")
))
}
fn apply_managed_overrides(config: &mut Config) -> Result<()> {
let Some(path) = managed_config_file(config.managed_config_path.as_deref())? else {
return Ok(());
};
let mut managed = load_single_config_file(&path).with_context(|| {
format!(
"the managed configuration {} cannot be loaded, and Codewhale does not start without a managed configuration it was told to use",
codewhale_config::quote_os_path(&path)
)
})?;
strip_external_credential_consent(&mut managed);
managed.tool_launcher = managed_tool_launcher(&path)?;
let prior_route = config
.active_provider_identity()
.map_err(|error| managed_route_error(config, &path, error))?;
let mut merged = merge_config(config.clone(), managed.clone());
apply_layer_root_model(&mut merged, &managed);
let merged_route = merged
.active_provider_identity()
.map_err(|error| managed_route_error(&merged, &path, error))?;
if managed.provider.is_some() {
merged.route_provenance.provider_from_managed = true;
merged.route_provenance.provider_from_env = false;
merged.route_provenance.provider_from_saved_selection = false;
merged.route_provenance.provider_from_profile = false;
}
if managed.default_text_model.is_some()
|| managed.legacy_model.is_some()
|| managed
.provider_config_for(&merged_route)
.and_then(|entry| entry.model.as_ref())
.is_some()
{
merged.route_provenance.model_from_managed = true;
merged.route_provenance.model_from_saved_selection = false;
merged.route_provenance.model_from_profile = false;
merged.remembered_selection_scope = Some(false);
} else if managed.provider.is_some() {
merged.remembered_selection_scope = Some(false);
}
if prior_route != merged_route || config_defines_base_url_for_effective_route(&managed, &merged)
{
if let BaseUrlEnvReceipt::Route(ProviderKind::Deepseek, key) = &config.base_url_env_receipt
&& let Ok(owner) = merged.resolve_persisted_provider_identity(
Some(ProviderKind::Deepseek.as_str()),
Some(key),
)
&& managed
.provider_config_for(&owner)
.and_then(|entry| entry.base_url.as_ref())
.is_none()
&& let Some(env_value) = env_base_url_override()
&& merged
.provider_config_for(&owner)
.and_then(|entry| entry.base_url.as_deref())
== Some(env_value.as_str())
{
merged.provider_config_for_mut(&owner)?.base_url = None;
}
merged.base_url_env_receipt = BaseUrlEnvReceipt::NoOwner;
}
if managed.network.is_some() {
merged.network_layer_is_managed = true;
}
if managed.tool_launcher.is_some()
&& !matches!(
managed.sandbox_mode.as_deref(),
Some("workspace-write" | "read-only")
)
{
anyhow::bail!(
"`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",
codewhale_config::quote_os_path(&path)
);
}
*config = merged;
Ok(())
}
fn managed_tool_launcher(path: &Path) -> Result<Option<Vec<String>>> {
let raw = fs::read_to_string(path)
.with_context(|| format!("Failed to read config file: {}", path.display()))?;
let Ok(document) = toml::from_str::<toml::Value>(&raw) else {
return Ok(None);
};
if codewhale_config::tool_launcher_in_profiles(&document) {
anyhow::bail!(
"`tool_launcher` in {} belongs at the top level of the managed configuration, not in a profile",
codewhale_config::quote_os_path(path)
);
}
let Some(value) = document.get("tool_launcher") else {
return Ok(None);
};
if !cfg!(all(target_os = "linux", not(target_env = "ohos"))) {
anyhow::bail!(
"`tool_launcher` in {} is supported only on Linux",
codewhale_config::quote_os_path(path)
);
}
let argv = value
.as_array()
.and_then(|items| {
items
.iter()
.map(|item| item.as_str().map(str::to_string))
.collect::<Option<Vec<_>>>()
})
.filter(|argv| {
argv.first()
.is_some_and(|program| Path::new(program).is_absolute())
&& argv.iter().all(|arg| !arg.is_empty() && !arg.contains('\0'))
})
.ok_or_else(|| {
anyhow::anyhow!(
"`tool_launcher` in {} must be a list of strings whose first entry is an absolute program path",
codewhale_config::quote_os_path(path)
)
})?;
if !managed_path_is_named_by_host(path) {
anyhow::bail!(
"`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",
codewhale_config::quote_os_path(path)
);
}
if managed_file_is_replaceable(path) {
anyhow::bail!(
"`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",
codewhale_config::quote_os_path(path)
);
}
Ok(Some(argv))
}
fn managed_path_from_env() -> Option<PathBuf> {
codewhale_env_var(
"CODEWHALE_MANAGED_CONFIG_PATH",
"DEEPSEEK_MANAGED_CONFIG_PATH",
)
.ok()
.map(|value| expand_path(&value))
}
fn managed_config_file(configured: Option<&str>) -> Result<Option<PathBuf>> {
if let Some(path) = managed_path_from_env() {
return Ok(Some(path));
}
let default = default_managed_config_path().filter(|path| {
fs::symlink_metadata(path).map_or_else(
|error| error.kind() != std::io::ErrorKind::NotFound,
|_| true,
)
});
let Some(configured) = configured
.filter(|value| !value.trim().is_empty())
.map(expand_path)
else {
return Ok(default);
};
if let Some(default) = default
&& default != configured
{
anyhow::bail!(
"`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",
codewhale_config::quote_os_path(&configured),
codewhale_config::quote_os_path(&default)
);
}
Ok(Some(configured))
}
fn managed_route_error(config: &Config, path: &Path, error: String) -> anyhow::Error {
let selected = config.provider.as_deref().unwrap_or_default();
let undeclared = !selected.is_empty()
&& ProviderKind::parse(selected).is_none()
&& config
.providers
.as_ref()
.and_then(|providers| providers.custom_provider_config(selected))
.is_none();
if undeclared {
anyhow::anyhow!(
"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",
codewhale_config::quote_os_path(path)
)
} else {
anyhow::anyhow!(
"{error} (while applying the managed configuration {})",
codewhale_config::quote_os_path(path)
)
}
}
fn managed_path_is_named_by_host(path: &Path) -> bool {
managed_path_from_env()
.into_iter()
.chain(default_managed_config_path())
.any(|named| named == path)
}
#[cfg(test)]
static TEST_TREAT_MANAGED_FILE_AS_SEALED: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
fn managed_file_is_replaceable(path: &Path) -> bool {
#[cfg(test)]
if TEST_TREAT_MANAGED_FILE_AS_SEALED.load(std::sync::atomic::Ordering::SeqCst) {
return false;
}
engine_can_replace(path)
}
#[cfg(unix)]
fn engine_can_replace(path: &Path) -> bool {
use std::os::unix::ffi::OsStrExt as _;
use std::os::unix::fs::MetadataExt as _;
fn writable(path: &Path) -> bool {
let Ok(spelled) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
return true;
};
unsafe { libc::access(spelled.as_ptr(), libc::W_OK) == 0 }
}
let euid = unsafe { libc::geteuid() };
let replaceable = |file: &Path| {
if writable(file) {
return true;
}
let mut child = file;
while let Some(dir) = child.parent().filter(|dir| !dir.as_os_str().is_empty()) {
if writable(dir) {
let sticky = std::fs::metadata(dir).is_ok_and(|meta| meta.mode() & 0o1000 != 0);
let child_is_ours =
std::fs::symlink_metadata(child).map_or(true, |meta| meta.uid() == euid);
if !sticky || child_is_ours {
return true;
}
}
child = dir;
}
false
};
let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
let canonical = path.canonicalize().unwrap_or_else(|_| absolute.clone());
replaceable(&absolute) || replaceable(&canonical)
}
#[cfg(not(unix))]
fn engine_can_replace(_path: &Path) -> bool {
true
}
fn strip_external_credential_consent(config: &mut Config) {
if config.providers.is_none() {
return;
}
for row in codewhale_config::descriptors::provider_compatibility() {
if row.kind == ProviderKind::Custom {
continue;
}
let Ok(identity) = config.resolve_persisted_provider_identity(Some(row.id), Some(row.id))
else {
continue;
};
let Ok(entry) = config.provider_config_for_mut(&identity) else {
continue;
};
if entry.external_credentials.as_ref().is_some_and(|consent| {
consent.access != codewhale_config::ExternalCredentialAccess::Disabled
}) {
entry.external_credentials = None;
}
}
if let Some(providers) = config.providers.as_mut() {
for provider in providers.custom.values_mut() {
if provider
.external_credentials
.as_ref()
.is_some_and(|consent| {
consent.access != codewhale_config::ExternalCredentialAccess::Disabled
})
{
provider.external_credentials = None;
}
}
}
}
fn config_defines_base_url_for_effective_route(source: &Config, effective: &Config) -> bool {
let Ok(identity) = effective.active_provider_identity() else {
return false;
};
let mut source = source.clone();
if source.scope_to_provider_identity(&identity).is_err() {
return false;
}
source
.provider_route_string_with_deepseek_fallback(&identity, |entry| entry.base_url.clone())
.is_some_and(|base| !base.trim().is_empty())
}
fn apply_requirements(config: &mut Config) -> Result<()> {
let path = config
.requirements_path
.as_deref()
.map(expand_path)
.or_else(default_requirements_path);
let Some(path) = path else {
return Ok(());
};
if !path.exists() {
return Ok(());
}
let contents = fs::read_to_string(&path)
.with_context(|| format!("Failed to read requirements file: {}", path.display()))?;
let requirements: RequirementsFile = toml::from_str(&contents).map_err(|_| {
anyhow::anyhow!(
"Failed to parse requirements file {}; file contents were omitted",
codewhale_config::quote_os_path(&path)
)
})?;
if !requirements.allowed_approval_policies.is_empty() {
use codewhale_execpolicy::ApprovalMode;
let policy = config
.approval_policy
.as_deref()
.unwrap_or("on-request")
.to_ascii_lowercase();
if !requirements.allowed_approval_policies.iter().any(|p| {
match (
ApprovalMode::from_config_value(p),
ApprovalMode::from_config_value(&policy),
) {
(Some(allowed), Some(effective)) => allowed == effective,
_ => p.eq_ignore_ascii_case(&policy),
}
}) {
anyhow::bail!(
"approval_policy '{policy}' is not allowed by requirements ({})",
requirements.allowed_approval_policies.join(", ")
);
}
}
if !requirements.allowed_sandbox_modes.is_empty() {
let mode = config
.sandbox_mode
.as_deref()
.map(str::to_ascii_lowercase)
.unwrap_or_else(|| {
use codewhale_execpolicy::ApprovalMode;
let approval = config
.approval_policy
.as_deref()
.and_then(ApprovalMode::from_config_value)
.unwrap_or_default();
approval.agent_baseline_sandbox_mode().to_string()
});
if !requirements
.allowed_sandbox_modes
.iter()
.any(|m| m.eq_ignore_ascii_case(&mode))
{
anyhow::bail!(
"sandbox_mode '{mode}' is not allowed by requirements ({})",
requirements.allowed_sandbox_modes.join(", ")
);
}
}
Ok(())
}
fn merge_features(
base: Option<FeaturesToml>,
override_cfg: Option<FeaturesToml>,
) -> Option<FeaturesToml> {
match (base, override_cfg) {
(None, None) => None,
(Some(mut base), Some(override_cfg)) => {
for (key, value) in override_cfg.entries {
base.entries.insert(key, value);
}
Some(base)
}
(Some(base), None) => Some(base),
(None, Some(override_cfg)) => Some(override_cfg),
}
}
pub fn ensure_parent_dir(path: &Path) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("Failed to create directory: {}", parent.display()))?;
#[cfg(unix)]
{
if let Ok(meta) = fs::metadata(parent) {
let mode = meta.permissions().mode();
if mode & 0o077 != 0 {
let mut perms = meta.permissions();
perms.set_mode(mode & !0o077);
if let Err(err) = fs::set_permissions(parent, perms) {
tracing::warn!(
target: "codewhale::config",
path = %parent.display(),
error = %err,
"could not tighten parent dir permissions; \
filesystem may not support Unix chmod \
(Docker bind-mount, NTFS, network share). \
Continuing — the file will still be written."
);
}
}
}
}
}
Ok(())
}
fn write_config_file_secure(path: &Path, content: &str) -> Result<()> {
codewhale_config::create_config_document(path, content)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SavedCredential {
KeyringAndConfigFile {
backend: String,
path: PathBuf,
},
ConfigFile(PathBuf),
}
impl SavedCredential {
#[must_use]
pub fn describe(&self) -> String {
match self {
Self::KeyringAndConfigFile { backend, path } => {
format!(
"secret store ({backend}); credential-free config metadata in {}",
path.display()
)
}
Self::ConfigFile(path) => path.display().to_string(),
}
}
}
pub fn credential_config_path() -> anyhow::Result<PathBuf> {
let resolved = try_default_config_path()?;
if !codewhale_config::config_path_is_workspace_scoped(&resolved) {
return Ok(resolved);
}
let global = home_config_path()
.context("Failed to resolve user-global config path: home directory not found.")?;
tracing::info!(
ambient = %resolved.display(),
global = %global.display(),
"rescoping credential write from workspace config to user-global config"
);
Ok(global)
}
pub fn save_api_key(api_key: &str) -> Result<SavedCredential> {
save_root_api_key_for_secret_slot(api_key, "deepseek", "deepseek")
}
fn save_root_api_key_for_secret_slot(
api_key: &str,
secret_slot: &str,
table: &str,
) -> Result<SavedCredential> {
let normalized = codewhale_secrets::normalize_api_key(api_key);
let trimmed = normalized.as_str();
if trimmed.is_empty() {
anyhow::bail!("Refusing to save an empty API key.");
}
let path = credential_config_path().context("Failed to resolve config path for API key.")?;
if let Some(secrets) = credential_secret_store() {
return crate::credentials::store::with_provider_write_lock(secret_slot, || {
let prior_secret = secrets.get(secret_slot);
match prior_secret.as_ref() {
Ok(prior) => match secrets.set(secret_slot, trimmed) {
Ok(()) => {
if let Err(error) =
save_root_api_key_metadata_without_plaintext(&path, table)
{
let current = secrets.get(secret_slot).map_err(|rollback| {
anyhow::anyhow!(
"{error}; additionally could not verify secret-store rollback for {secret_slot}: {rollback}"
)
})?;
if current.as_deref() == Some(trimmed) {
match prior {
Some(previous) => secrets.set(secret_slot, previous),
None => secrets.delete(secret_slot),
}
.map_err(|rollback| {
anyhow::anyhow!(
"{error}; additionally failed to restore prior secret-store state for {secret_slot}: {rollback}"
)
})?;
}
return Err(error);
}
codewhale_config::scrub_plaintext_api_keys_from_config_backup(&path)?;
let backend = secrets.backend_name().to_string();
log_sensitive_event(
"credential.save",
json!({
"backend": backend.clone(),
"config_path": path.display().to_string(),
"plaintext_config_fallback": false,
}),
);
Ok(SavedCredential::KeyringAndConfigFile { backend, path })
}
Err(err) => Err(plaintext_credential_fallback_refused("write", &path, &err)),
},
Err(error) => Err(plaintext_credential_fallback_refused(
"snapshot", &path, &error,
)),
}
});
}
let path = save_api_key_to_config_file(trimmed, table)?;
codewhale_config::scrub_plaintext_api_keys_from_config_backup(&path)?;
Ok(SavedCredential::ConfigFile(path))
}
fn plaintext_credential_fallback_refused(
operation: &str,
config_path: &Path,
failure: &dyn std::fmt::Display,
) -> anyhow::Error {
anyhow::anyhow!(
"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.",
codewhale_config::quote_os_path(config_path)
)
}
#[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
pub fn credential_secret_store() -> Option<codewhale_secrets::Secrets> {
Some(codewhale_secrets::Secrets::auto_detect())
}
#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
pub fn credential_secret_store() -> Option<codewhale_secrets::Secrets> {
let isolated_home = codewhale_paths::codewhale_home_is_explicit();
let explicit_backend = std::env::var_os("CODEWHALE_SECRET_BACKEND")
.or_else(|| std::env::var_os("DEEPSEEK_SECRET_BACKEND"))
.is_some_and(|value| !value.is_empty());
(crate::test_support::state_from_environment() || (isolated_home && explicit_backend))
.then(codewhale_secrets::Secrets::auto_detect)
}
fn save_root_api_key_metadata_without_plaintext(config_path: &Path, table: &str) -> Result<()> {
ensure_parent_dir(config_path)?;
crate::config_persistence::mutate_config_document(config_path, |doc| {
crate::config_persistence::set_document_value(doc, &["auth_mode"], "api_key")?;
if !doc.contains_key("reasoning_effort") {
crate::config_persistence::set_document_value(doc, &["reasoning_effort"], "auto")?;
}
crate::config_persistence::unset_document_value(doc, &["api_key"])?;
crate::config_persistence::unset_document_value(doc, &["providers", table, "api_key"])?;
crate::config_persistence::set_document_value(
doc,
&["providers", table, "auth_mode"],
"api_key",
)?;
if table == "deepseek" {
crate::config_persistence::unset_document_value(
doc,
&["providers", "deepseek-cn", "api_key"],
)?;
}
Ok(())
})
.with_context(|| format!("Failed to write config to {}", config_path.display()))
}
fn save_api_key_to_config_file(api_key: &str, table: &str) -> Result<PathBuf> {
let config_path =
credential_config_path().context("Failed to resolve config path for API key.")?;
ensure_parent_dir(&config_path)?;
if config_path.exists() {
crate::config_persistence::mutate_config_document(&config_path, |doc| {
crate::config_persistence::set_document_value(
doc,
&["providers", table, "api_key"],
api_key,
)?;
crate::config_persistence::unset_document_value(doc, &["api_key"])?;
crate::config_persistence::set_document_value(doc, &["auth_mode"], "api_key")
})
.with_context(|| format!("Failed to write config to {}", config_path.display()))?;
} else {
let content = format!(
r#"# codewhale Configuration
# Set provider credentials in this file or via environment variables.
# See /links in the TUI for provider-specific credential pages.
auth_mode = "api_key"
# Default model (unset follows the provider default)
# default_text_model = "{DEFAULT_TEXT_MODEL}"
# Thinking mode (DeepSeek V4 reasoning effort):
# "auto" | "off" | "low" | "medium" | "high" | "max"
# Ctrl+T in the TUI (or /effort) cycles the active model's effort levels.
reasoning_effort = "auto"
[providers.{table}]
api_key = "{api_key}"
# Base URL (default: https://api.deepseek.com/beta)
# Set https://api.deepseek.com to opt out of beta features.
# base_url = "https://api.deepseek.com/beta"
"#
);
crate::config_persistence::write_config_toml_atomic(&config_path, &content)
.with_context(|| format!("Failed to write config to {}", config_path.display()))?;
}
log_sensitive_event(
"credential.save",
json!({
"backend": "config_file",
"config_path": config_path.display().to_string(),
}),
);
Ok(config_path)
}
fn provider_uses_oauth_credentials(config: &Config, identity: &ProviderIdentity) -> bool {
let provider = identity.provider;
!auth_mode_disables_api_key(config.auth_mode_for_provider(identity).as_deref())
&& !config.provider_uses_custom_endpoint(identity)
&& (provider == ProviderKind::OpenaiCodex
|| (provider == ProviderKind::Anthropic
&& config.auth_mode_for_provider(identity).as_deref() == Some("oauth"))
|| (provider == ProviderKind::Moonshot
&& config
.provider_config_for(identity)
.is_some_and(provider_config_uses_kimi_imported_token))
|| (provider == ProviderKind::Xai
&& config
.provider_config_for(identity)
.is_some_and(provider_config_uses_xai_oauth)))
}
fn bound_provider_api_key_env_name(config: &Config, identity: &ProviderIdentity) -> Option<String> {
if !config.config_credentials_are_bound_to_provider_endpoint(identity) {
return None;
}
config
.provider_config_for(identity)
.and_then(|entry| entry.api_key_env.as_deref())
.map(str::trim)
.filter(|name| !name.is_empty())
.map(str::to_string)
}
fn provider_config_env_api_key(config: &Config, identity: &ProviderIdentity) -> Option<String> {
let env_name = bound_provider_api_key_env_name(config, identity)?;
std::env::var(env_name)
.ok()
.filter(|value| !value.trim().is_empty())
}
#[must_use]
pub fn active_provider_has_config_api_key(config: &Config) -> bool {
let Ok(identity) = config.active_provider_identity() else {
return false;
};
let provider = identity.provider;
if auth_mode_disables_api_key(config.auth_mode_for_provider(&identity).as_deref()) {
return false;
}
let custom_endpoint = config.provider_uses_custom_endpoint(&identity);
if provider == ProviderKind::Moonshot
&& !custom_endpoint
&& config
.provider_config_for(&identity)
.is_some_and(provider_config_uses_kimi_imported_token)
{
return false;
}
if provider == ProviderKind::OpenaiCodex && !custom_endpoint {
return crate::oauth::credentials_valid(crate::oauth::OAuthProvider::Chatgpt, config);
}
if !custom_endpoint
&& matches!(provider, ProviderKind::Huggingface)
&& std::env::var("HUGGINGFACE_API_KEY")
.or_else(|_| std::env::var("HF_TOKEN"))
.is_ok_and(|k| !k.trim().is_empty())
{
return true;
}
if !custom_endpoint
&& matches!(provider, ProviderKind::Modelscope)
&& std::env::var("MODELSCOPE_API_KEY").is_ok_and(|k| !k.trim().is_empty())
{
return true;
}
if config.config_credentials_are_bound_to_provider_endpoint(&identity)
&& config
.provider_route_string_with_deepseek_fallback(&identity, |entry| entry.api_key.clone())
.is_some_and(|key| {
classify_config_api_key_value(&key) == ConfigApiKeyValueKind::Literal
})
{
return true;
}
if !config.should_skip_secret_store_for_provider(&identity)
&& provider_secret_store_api_key(config, &identity).is_some()
{
return true;
}
false
}
#[must_use]
pub fn active_provider_has_env_api_key(config: &Config) -> bool {
active_provider_env_api_key_source(config).is_some()
}
#[must_use]
pub fn active_provider_env_api_key_source(config: &Config) -> Option<String> {
let identity = config.active_provider_identity().ok()?;
if config.required_account_model_owner.is_some()
|| config.session_provider_keys_only
|| config.session_provider_api_key(&identity).is_some()
{
return None;
}
let provider = identity.provider;
if provider == ProviderKind::OpenaiCodex && !config.provider_uses_custom_endpoint(&identity) {
return None;
}
if auth_mode_disables_api_key(config.auth_mode_for_provider(&identity).as_deref()) {
return None;
}
if !provider_uses_oauth_credentials(config, &identity)
&& explicit_cli_api_key_override().is_some()
{
return Some("--api-key".to_string());
}
if provider_config_env_api_key(config, &identity).is_some() {
return bound_provider_api_key_env_name(config, &identity);
}
if config.should_skip_secret_store_for_provider(&identity) {
return None;
}
provider_env_api_key_named(provider).map(|(name, _)| name.to_string())
}
#[must_use]
pub fn active_provider_uses_env_only_api_key(config: &Config) -> bool {
active_provider_has_env_api_key(config) && !active_provider_has_config_api_key(config)
}
struct UserGlobalConfigCache {
path: PathBuf,
modified: Option<SystemTime>,
len: u64,
json: serde_json::Value,
}
fn user_global_config_json() -> Option<serde_json::Value> {
static CACHE: Mutex<Option<UserGlobalConfigCache>> = Mutex::new(None);
let path = codewhale_config::default_config_path().ok()?;
let meta = fs::metadata(&path).ok()?;
let modified = meta.modified().ok();
let len = meta.len();
let mut guard = CACHE.lock().ok()?;
if let Some(cached) = guard.as_ref()
&& cached.path == path
&& cached.modified == modified
&& cached.len == len
{
return Some(cached.json.clone());
}
let text = fs::read_to_string(&path).ok()?;
let doc = codewhale_config::parse_config_toml(&text).ok()?;
let json = serde_json::to_value(&doc).ok()?;
*guard = Some(UserGlobalConfigCache {
path,
modified,
len,
json: json.clone(),
});
Some(json)
}
fn user_global_config_api_key(identity: &ProviderIdentity) -> Option<String> {
let provider = identity.provider;
if provider == ProviderKind::Custom {
return None;
}
let json = user_global_config_json()?;
let provider_config_key = identity.compatibility()?.config_key;
let key = json
.get("providers")?
.get(provider_config_key)?
.get("api_key")?
.as_str()?;
let key = key.trim();
if key.is_empty() || classify_config_api_key_value(key) != ConfigApiKeyValueKind::Literal {
return None;
}
Some(key.to_string())
}
pub type ResolvedApiKey = (String, String);
pub const XAI_OAUTH_KEY_SOURCE: &str = "xAI OAuth login";
impl Config {
pub fn codex_credentials(&self) -> Result<crate::oauth::OwnedOAuthCredentials> {
anyhow::ensure!(
!self.session_provider_keys_only,
"Stored ChatGPT sign-in is unavailable under session-only provider key policy"
);
let identity = self
.active_provider_identity()
.map_err(anyhow::Error::msg)?;
anyhow::ensure!(
identity.provider == ProviderKind::OpenaiCodex
&& !self.provider_uses_custom_endpoint(&identity),
"ChatGPT credentials are only available on the official public API route"
);
crate::oauth::official_chatgpt_registration(self)?;
crate::oauth::get_owned_credentials(crate::oauth::OAuthProvider::Chatgpt, self)
}
#[cfg(any(test, feature = "test-support"))]
pub fn codex_account_id(&self) -> Option<String> {
self.codex_credentials()
.ok()
.and_then(|credentials| credentials.account_id)
}
}
#[must_use]
pub fn provider_is_configured(
provider: ProviderKind,
is_active: bool,
has_key: bool,
configured: Option<&ProviderConfig>,
is_named_custom_entry: bool,
) -> bool {
if is_active || is_named_custom_entry {
return true;
}
if configured.is_some_and(provider_config_is_explicit) {
return true;
}
if matches!(
provider,
ProviderKind::Ollama | ProviderKind::Sglang | ProviderKind::Vllm
) {
return false;
}
has_key
}
fn provider_config_is_explicit(entry: &ProviderConfig) -> bool {
let non_empty = |value: Option<&String>| value.is_some_and(|value| !value.trim().is_empty());
non_empty(entry.api_key.as_ref())
|| entry.vendor.is_some()
|| non_empty(entry.base_url.as_ref())
|| non_empty(entry.model.as_ref())
|| non_empty(entry.auth_mode.as_ref())
|| entry
.auth
.as_ref()
.is_some_and(|auth| auth.validate().is_ok())
|| entry.context_window.is_some()
|| entry
.model_context_windows
.as_ref()
.is_some_and(|table| !table.is_empty())
|| non_empty(entry.mode.as_ref())
|| entry.max_concurrency.is_some()
|| entry.http_headers.as_ref().is_some_and(|headers| {
headers
.iter()
.any(|(name, value)| !name.trim().is_empty() && !value.trim().is_empty())
})
|| non_empty(entry.path_suffix.as_ref())
|| non_empty(entry.reasoning_stream_style.as_ref())
|| entry.insecure_skip_tls_verify.is_some()
|| entry.allow_insecure_http.is_some()
|| non_empty(entry.kind.as_ref())
|| non_empty(entry.api_key_env.as_ref())
|| entry.external_credentials.is_some()
|| non_empty(entry.oauth_credential_generation.as_ref())
}
#[cfg(any(test, feature = "test-support"))]
pub fn save_api_key_for(provider: ProviderKind, api_key: &str) -> Result<PathBuf> {
match save_api_key_for_identity(
&ProviderIdentity {
provider,
key: provider.as_str().into(),
exact_id: Some(provider.as_str().into()),
migrated_legacy_ollama_cloud_route: false,
legacy_root_custom_generation: None,
},
&Config {
provider: Some(provider.as_str().to_string()),
..Config::default()
},
api_key,
)? {
SavedCredential::KeyringAndConfigFile { path, .. } | SavedCredential::ConfigFile(path) => {
Ok(path)
}
}
}
pub fn save_api_key_for_identity(
identity: &ProviderIdentity,
route_config: &Config,
api_key: &str,
) -> Result<SavedCredential> {
route_config
.verify_provider_identity(identity)
.map_err(anyhow::Error::msg)?;
if identity.provider == ProviderKind::Xai {
return codewhale_config::with_xai_oauth_revocation_transaction(|| {
save_api_key_for_identity_unlocked(identity, route_config, api_key)
});
}
save_api_key_for_identity_unlocked(identity, route_config, api_key)
}
fn save_api_key_for_identity_unlocked(
identity: &ProviderIdentity,
route_config: &Config,
api_key: &str,
) -> Result<SavedCredential> {
route_config
.verify_provider_identity(identity)
.map_err(anyhow::Error::msg)?;
let provider = identity.provider;
if provider == ProviderKind::OpenaiCodex {
anyhow::bail!(codewhale_config::credentials::OPENAI_CODEX_API_KEY_REFUSAL);
}
let is_legacy_literal_custom = provider == ProviderKind::Custom
&& identity.key.as_str().trim() == ProviderKind::Custom.as_str()
&& identity.persisted_id().is_none();
if matches!(provider, ProviderKind::Deepseek) {
return save_api_key(api_key);
}
if is_legacy_literal_custom {
return save_root_api_key_for_secret_slot(api_key, "custom", "custom");
}
let normalized = codewhale_secrets::normalize_api_key(api_key);
let api_key = normalized.as_str();
anyhow::ensure!(!api_key.is_empty(), "Refusing to save an empty API key.");
let config_path =
credential_config_path().context("Failed to resolve config path for provider API key.")?;
ensure_parent_dir(&config_path)?;
let key_inside = if provider == ProviderKind::Custom {
let key = identity.key.as_str().trim();
anyhow::ensure!(!key.is_empty(), "custom provider id cannot be empty");
key
} else {
provider_config_key(identity).context("provider api key table")?
};
let pin_kimi_code_base_url = provider == ProviderKind::Moonshot
&& route_config
.provider_config_for(identity)
.is_some_and(|entry| {
provider_config_uses_kimi_imported_token(entry)
&& entry
.base_url
.as_deref()
.is_none_or(|base_url| base_url.trim().is_empty())
});
if !route_config.should_skip_secret_store_for_provider(identity)
&& let Some(secrets) = credential_secret_store()
{
let secret_slot = provider_secret_store_slot(provider);
return crate::credentials::store::with_provider_write_lock(secret_slot, || {
let prior_secret = secrets.get(secret_slot);
match prior_secret.as_ref() {
Ok(prior) => match secrets.set(secret_slot, api_key) {
Ok(()) => {
let config_result = crate::config_persistence::mutate_config_document(
&config_path,
|doc| {
if pin_kimi_code_base_url {
crate::config_persistence::set_document_value(
doc,
&["providers", key_inside, "base_url"],
DEFAULT_KIMI_CODE_BASE_URL,
)?;
}
crate::config_persistence::set_document_value(
doc,
&["providers", key_inside, "auth_mode"],
"api_key",
)?;
crate::config_persistence::unset_document_value(
doc,
&["providers", key_inside, "external_credentials"],
)?;
if matches!(provider, ProviderKind::Xai | ProviderKind::Anthropic) {
crate::config_persistence::unset_document_value(
doc,
&["providers", key_inside, "oauth_credential_generation"],
)?;
}
crate::config_persistence::unset_document_value(
doc,
&["providers", key_inside, "api_key"],
)?;
Ok(())
},
)
.with_context(|| {
format!("Failed to write config to {}", config_path.display())
});
if let Err(error) = config_result {
let current = secrets.get(secret_slot).map_err(|rollback| {
anyhow::anyhow!(
"{error}; additionally could not verify secret-store rollback for {secret_slot}: {rollback}"
)
})?;
if current.as_deref() == Some(api_key) {
match prior {
Some(previous) => secrets.set(secret_slot, previous),
None => secrets.delete(secret_slot),
}
.map_err(|rollback| {
anyhow::anyhow!(
"{error}; additionally failed to restore prior secret-store state for {secret_slot}: {rollback}"
)
})?;
}
return Err(error);
}
codewhale_config::scrub_plaintext_api_keys_from_config_backup(
&config_path,
)?;
let backend = secrets.backend_name().to_string();
log_sensitive_event(
"credential.save",
json!({
"backend": backend.clone(),
"provider": identity.key,
"config_path": config_path.display().to_string(),
"plaintext_config_fallback": false,
}),
);
Ok(SavedCredential::KeyringAndConfigFile {
backend,
path: config_path,
})
}
Err(err) => Err(plaintext_credential_fallback_refused(
"write",
&config_path,
&err,
)),
},
Err(error) => Err(plaintext_credential_fallback_refused(
"snapshot",
&config_path,
&error,
)),
}
});
}
crate::config_persistence::mutate_config_document(&config_path, |doc| {
if pin_kimi_code_base_url {
crate::config_persistence::set_document_value(
doc,
&["providers", key_inside, "base_url"],
DEFAULT_KIMI_CODE_BASE_URL,
)?;
}
crate::config_persistence::set_document_value(
doc,
&["providers", key_inside, "auth_mode"],
"api_key",
)?;
crate::config_persistence::unset_document_value(
doc,
&["providers", key_inside, "external_credentials"],
)?;
if matches!(provider, ProviderKind::Xai | ProviderKind::Anthropic) {
crate::config_persistence::unset_document_value(
doc,
&["providers", key_inside, "oauth_credential_generation"],
)?;
}
crate::config_persistence::set_document_value(
doc,
&["providers", key_inside, "api_key"],
api_key,
)
})
.with_context(|| format!("Failed to write config to {}", config_path.display()))?;
log_sensitive_event(
"credential.save",
json!({
"backend": "config_file",
"provider": identity.key,
"config_path": config_path.display().to_string(),
}),
);
codewhale_config::scrub_plaintext_api_keys_from_config_backup(&config_path)?;
Ok(SavedCredential::ConfigFile(config_path))
}
pub fn save_provider_model_for_identity(
identity: &ProviderIdentity,
route_config: &Config,
model: &str,
) -> Result<PathBuf> {
route_config
.verify_provider_identity(identity)
.map_err(anyhow::Error::msg)?;
let model = model.trim();
anyhow::ensure!(!model.is_empty(), "model cannot be empty");
let config_path =
try_default_config_path().context("Failed to resolve config path for provider model.")?;
crate::config_persistence::persist_provider_model_key(Some(&config_path), identity, model)
}
pub fn save_provider_base_url_for_identity(
identity: &ProviderIdentity,
route_config: &Config,
base_url: &str,
) -> Result<PathBuf> {
route_config
.verify_provider_identity(identity)
.map_err(anyhow::Error::msg)?;
let base_url = base_url.trim();
anyhow::ensure!(!base_url.is_empty(), "base URL cannot be empty");
let config_path = try_default_config_path()
.context("Failed to resolve config path for provider base URL.")?;
ensure_parent_dir(&config_path)?;
let key_inside = if identity.provider == ProviderKind::Custom {
let key = identity.key.as_str().trim();
anyhow::ensure!(!key.is_empty(), "custom provider id cannot be empty");
key
} else {
provider_config_key(identity).context("provider base URL table")?
};
crate::config_persistence::mutate_config_document(&config_path, |doc| {
crate::config_persistence::set_document_value(
doc,
&["providers", key_inside, "base_url"],
base_url,
)
})
.with_context(|| format!("Failed to write config to {}", config_path.display()))?;
Ok(config_path)
}
pub fn save_provider_context_window_for_identity(
identity: &ProviderIdentity,
route_config: &Config,
context_window: u32,
) -> Result<PathBuf> {
route_config
.verify_provider_identity(identity)
.map_err(anyhow::Error::msg)?;
anyhow::ensure!(context_window > 0, "context window must be greater than 0");
let config_path = try_default_config_path()
.context("Failed to resolve config path for provider context window.")?;
ensure_parent_dir(&config_path)?;
let key_inside = if identity.provider == ProviderKind::Custom {
let key = identity.key.as_str().trim();
anyhow::ensure!(!key.is_empty(), "custom provider id cannot be empty");
key
} else {
provider_config_key(identity).context("provider context window table")?
};
crate::config_persistence::mutate_config_document(&config_path, |doc| {
crate::config_persistence::set_document_value(
doc,
&["providers", key_inside, "context_window"],
i64::from(context_window),
)
})
.with_context(|| format!("Failed to write config to {}", config_path.display()))?;
Ok(config_path)
}
fn validate_external_credential_before_consent(
consent_provider: codewhale_config::ProviderKind,
source: codewhale_config::ExternalCredentialSource,
path: &Path,
) -> Result<()> {
let grant = codewhale_config::ExternalCredentialConsentToml::read_only(
consent_provider,
source,
path.to_path_buf(),
)
.read_grant(consent_provider, source, path)?;
match source {
codewhale_config::ExternalCredentialSource::CodexCli => {
crate::oauth::get_credentials(&grant).map(|_| ())
}
codewhale_config::ExternalCredentialSource::GrokCli => {
crate::oauth::validate_grok_external_credentials(&grant)
}
codewhale_config::ExternalCredentialSource::DshCli => {
crate::dsh_credentials::deepseek_api_key_from_grant(&grant)?
.map(|_| ())
.context("the DeepSeek Harness credentials file holds no DEEPSEEK_API_KEY")
}
codewhale_config::ExternalCredentialSource::AgyCli => {
anyhow::bail!(codewhale_config::LEGACY_ANTIGRAVITY_TOMBSTONE_MESSAGE)
}
codewhale_config::ExternalCredentialSource::KimiCodeCli => anyhow::bail!(
"Kimi CLI credentials are never imported; configure a Kimi API key instead"
),
}
}
pub fn persist_external_credential_consent_for_at(
config_path: Option<&Path>,
live_config: &mut Config,
identity: &ProviderIdentity,
consent_provider: codewhale_config::ProviderKind,
source: codewhale_config::ExternalCredentialSource,
path: &Path,
) -> Result<PathBuf> {
live_config
.verify_provider_identity(identity)
.map_err(anyhow::Error::msg)?;
let provider = identity.provider;
let expected = match provider {
ProviderKind::OpenaiCodex => (
codewhale_config::ProviderKind::OpenaiCodex,
codewhale_config::ExternalCredentialSource::CodexCli,
),
ProviderKind::Xai => (
codewhale_config::ProviderKind::Xai,
codewhale_config::ExternalCredentialSource::GrokCli,
),
_ => anyhow::bail!(
"{} has no supported external credential owner",
provider.as_str()
),
};
anyhow::ensure!(
(consent_provider, source) == expected,
"external credential owner does not match provider {}",
provider.as_str()
);
let path = codewhale_config::resolve_external_credential_path(path)?;
let path_value = path.to_str().context(
"external credential path cannot be persisted losslessly because it is not valid UTF-8",
)?;
validate_external_credential_before_consent(consent_provider, source, &path).with_context(
|| {
format!(
"no usable {} credential was found, so read-only consent was not saved",
source.owner_label()
)
},
)?;
let config_path = match config_path {
Some(path) => path.to_path_buf(),
None => credential_config_path()
.context("Failed to resolve config path for external credential consent.")?,
};
ensure_parent_dir(&config_path)?;
let key_inside = provider_config_key(identity).context("external credential provider key")?;
crate::config_persistence::mutate_config_document(&config_path, |doc| {
crate::config_persistence::set_document_value(
doc,
&["providers", key_inside, "auth_mode"],
"oauth",
)?;
let prefix = &["providers", key_inside, "external_credentials"];
crate::config_persistence::set_document_value(
doc,
&[prefix[0], prefix[1], prefix[2], "access"],
"read_only",
)?;
crate::config_persistence::set_document_value(
doc,
&[prefix[0], prefix[1], prefix[2], "provider"],
consent_provider.as_str(),
)?;
crate::config_persistence::set_document_value(
doc,
&[prefix[0], prefix[1], prefix[2], "source"],
source.as_str(),
)?;
crate::config_persistence::set_document_value(
doc,
&[prefix[0], prefix[1], prefix[2], "path"],
path_value,
)?;
crate::config_persistence::set_document_value(
doc,
&[prefix[0], prefix[1], prefix[2], "consent_version"],
i64::from(codewhale_config::EXTERNAL_CREDENTIAL_CONSENT_VERSION),
)
})
.with_context(|| {
format!(
"Failed to write config to {}",
codewhale_config::quote_os_path(&config_path)
)
})?;
live_config
.providers
.get_or_insert_with(ProvidersConfig::default);
let entry = live_config.provider_config_for_mut(identity)?;
entry.auth_mode = Some("oauth".to_string());
entry.external_credentials = Some(codewhale_config::ExternalCredentialConsentToml::read_only(
consent_provider,
source,
path,
));
Ok(config_path)
}
pub fn revoke_external_credential_consent_for_at(
config_path: Option<&Path>,
live_config: &mut Config,
identity: &ProviderIdentity,
) -> Result<PathBuf> {
live_config
.verify_provider_identity(identity)
.map_err(anyhow::Error::msg)?;
let provider = identity.provider;
anyhow::ensure!(
matches!(provider, ProviderKind::OpenaiCodex | ProviderKind::Xai),
"{} has no supported external credential owner",
provider.as_str()
);
let config_path = match config_path {
Some(path) => path.to_path_buf(),
None => credential_config_path()
.context("Failed to resolve config path for external credential consent.")?,
};
ensure_parent_dir(&config_path)?;
let key_inside = provider_config_key(identity).context("external credential provider key")?;
crate::config_persistence::mutate_config_document(&config_path, |doc| {
crate::config_persistence::unset_document_value(
doc,
&["providers", key_inside, "external_credentials"],
)?;
Ok(())
})
.with_context(|| {
format!(
"Failed to write config to {}",
codewhale_config::quote_os_path(&config_path)
)
})?;
live_config
.provider_config_for_mut(identity)?
.external_credentials = None;
Ok(config_path)
}
pub fn provider_config_key(identity: &ProviderIdentity) -> Result<&str> {
if identity.provider == ProviderKind::Deepseek
&& identity.key.as_str() == ProviderKind::Deepseek.as_str()
{
anyhow::bail!("DeepSeek stores auth at the root config level");
}
identity.config_table_key()
}
fn provider_config_table_name(identity: &ProviderIdentity) -> Result<String> {
Ok(format!("providers.{}", provider_config_key(identity)?))
}
pub fn provider_env_api_key_var(provider: ProviderKind) -> Option<&'static str> {
provider_env_api_key_named(provider).map(|(name, _)| name)
}
fn provider_env_api_key_named(provider: ProviderKind) -> Option<(&'static str, String)> {
let read = || {
let names = provider.provider().env_vars();
names.iter().find_map(|name| {
std::env::var(name)
.ok()
.map(|value| codewhale_secrets::normalize_api_key(&value))
.filter(|value| !value.is_empty())
.map(|value| (*name, value))
})
};
#[cfg(any(test, feature = "test-support"))]
{
codewhale_util::test_env_lock::with_test_env_lock(read)
}
#[cfg(not(any(test, feature = "test-support")))]
{
read()
}
}
pub fn provider_secret_store_slot(provider: ProviderKind) -> &'static str {
provider.secret_store_slot()
}
fn secret_slot_save_marker_on_shared_slot(config: &Config, identity: &ProviderIdentity) -> bool {
let slot = provider_secret_store_slot(identity.provider);
codewhale_config::descriptors::provider_compatibility()
.iter()
.filter(|row| provider_secret_store_slot(row.kind) == slot)
.filter_map(|row| {
config
.resolve_persisted_provider_identity(Some(row.id), Some(row.id))
.ok()
})
.any(|candidate| {
config
.provider_config_for(&candidate)
.is_some_and(|entry| auth_mode_requires_api_key(entry.auth_mode.as_deref()))
})
}
pub fn provider_secret_store_api_key(
config: &Config,
identity: &ProviderIdentity,
) -> Option<String> {
provider_secret_store_api_key_with_mode(config, identity, false)
}
fn provider_secret_store_api_key_with_mode(
config: &Config,
identity: &ProviderIdentity,
read_only: bool,
) -> Option<String> {
let provider = identity.provider;
if config.should_skip_secret_store_for_provider(identity) {
return None;
}
#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
if !crate::test_support::state_from_environment()
&& (!codewhale_paths::codewhale_home_is_explicit()
|| std::env::var_os("CODEWHALE_SECRET_BACKEND").is_none())
{
return None;
}
let secrets = if read_only {
codewhale_secrets::Secrets::auto_detect_read_only()
} else {
codewhale_secrets::Secrets::auto_detect()
};
let store =
crate::credentials::store::SecretStoreCredentials::new(secrets, known_secret_store_slots());
let primary = store
.read(provider_secret_store_slot(provider))
.ok()
.flatten()
.map(|credential| credential.expose_secret().to_string());
if primary.is_some() {
return primary;
}
(provider == ProviderKind::OllamaCloud && identity.migrated_legacy_ollama_cloud_route)
.then(|| {
store
.read(ProviderKind::Ollama.as_str())
.ok()
.flatten()
.map(|credential| credential.expose_secret().to_string())
})
.flatten()
}
fn known_secret_store_slots() -> Vec<String> {
let mut slots: Vec<String> = codewhale_config::descriptors::provider_compatibility()
.iter()
.map(|row| provider_secret_store_slot(row.kind).to_string())
.collect();
slots.sort();
slots.dedup();
slots
}
fn config_api_key_shadow_warning(
config: &Config,
identity: &ProviderIdentity,
config_source: &str,
) -> Option<String> {
let provider = identity.provider;
if config.should_skip_secret_store_for_provider(identity) {
return None;
}
provider_secret_store_api_key_with_mode(config, identity, true).map(|_| {
let slot = provider_secret_store_slot(provider);
let id = provider.as_str();
format!(
"both {config_source} in the config file and secret-store slot \"{slot}\" \
hold a credential for provider {id}; the config-file key won. Run \
`codewhale auth set --provider {id}` to move the key into the secret store \
and strip the plaintext copy, or remove the config-file api_key."
)
})
}
fn warn_on_config_api_key_shadowing(
config: &Config,
identity: &ProviderIdentity,
config_source: &str,
) {
let provider = identity.provider;
let Some(message) = config_api_key_shadow_warning(config, identity, config_source) else {
return;
};
static WARNED_SLOTS: std::sync::OnceLock<
std::sync::Mutex<std::collections::HashSet<&'static str>>,
> = std::sync::OnceLock::new();
let mut warned = WARNED_SLOTS
.get_or_init(|| std::sync::Mutex::new(std::collections::HashSet::new()))
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if !warned.insert(provider_secret_store_slot(provider)) {
return;
}
drop(warned);
tracing::warn!("{message}");
}
pub fn explicit_launch_model_override() -> Option<String> {
codewhale_env_var("CODEWHALE_MODEL", "DEEPSEEK_MODEL")
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
}
pub fn explicit_launch_provider_override() -> Option<String> {
codewhale_env_var("CODEWHALE_PROVIDER", "DEEPSEEK_PROVIDER")
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
}
pub fn explicit_cli_api_key_override() -> Option<String> {
let read = || {
(cli_api_key_source().as_deref() == Some("cli"))
.then(|| {
std::env::var(codewhale_config::CLI_API_KEY_ENV)
.ok()
.filter(|value| !value.trim().is_empty())
})
.flatten()
};
#[cfg(any(test, feature = "test-support"))]
{
codewhale_util::test_env_lock::with_test_env_lock(read)
}
#[cfg(not(any(test, feature = "test-support")))]
{
read()
}
}
pub fn cli_api_key_source() -> Option<String> {
codewhale_env_var(
codewhale_config::CLI_API_KEY_SOURCE_ENV,
codewhale_config::LEGACY_CLI_API_KEY_SOURCE_ENV,
)
.ok()
}
fn missing_provider_api_key_message(identity: &ProviderIdentity) -> Result<String> {
let provider = identity.provider;
let credential_hint = provider
.provider()
.credential_help()
.credential_url
.map(|url| format!(" Get a key: {url}."))
.unwrap_or_default();
let label = identity
.compatibility()
.map_or_else(|| provider.provider().display_name(), |row| row.label);
Ok(format!(
"{} API key not found.{} Run 'codewhale auth set --provider {}', set {}, or add [{}] api_key in ~/.codewhale/config.toml.",
label,
credential_hint,
identity.key,
provider.provider().env_vars().join(" / "),
provider_config_table_name(identity)?
))
}
pub fn clear_api_key() -> Result<()> {
codewhale_config::with_xai_oauth_revocation_transaction(clear_api_key_unlocked)
}
fn clear_api_key_unlocked() -> Result<()> {
crate::credentials::store::with_provider_write_locks(
known_secret_store_slots(),
clear_api_key_under_slot_locks,
)
}
fn clear_api_key_under_slot_locks() -> Result<()> {
let config_path = credential_config_path()
.context("Failed to resolve config path while clearing API keys.")?;
if config_path.exists() {
crate::config_persistence::mutate_config_document(&config_path, |doc| {
crate::config_persistence::remove_document_key_recursive(doc.as_table_mut(), "api_key");
crate::config_persistence::unset_document_value(
doc,
&["providers", "xai", "oauth_credential_generation"],
)?;
crate::config_persistence::unset_document_value(
doc,
&["providers", "xai", "auth_mode"],
)?;
crate::config_persistence::unset_document_value(
doc,
&["providers", "xai", "external_credentials"],
)?;
Ok(())
})
.with_context(|| format!("Failed to write config to {}", config_path.display()))?;
log_sensitive_event(
"credential.clear",
json!({
"backend": "config_file",
"config_path": config_path.display().to_string(),
"scope": "root_and_provider_keys",
}),
);
}
if let Some(secrets) = credential_secret_store() {
let failures = clear_all_provider_api_keys_from_secret_store(secrets);
if !failures.is_empty() {
anyhow::bail!(
"failed to delete stored credentials for: {}",
failures.join(", ")
);
}
}
Ok(())
}
fn clear_all_provider_api_keys_from_secret_store(
secrets: codewhale_secrets::Secrets,
) -> Vec<String> {
let mut failures = Vec::new();
let store = crate::credentials::store::SecretStoreCredentials::new(
secrets.clone(),
known_secret_store_slots(),
);
let stored: Vec<crate::credentials::CredentialInfo> = match store.list() {
Ok(stored) => stored,
Err(error) => {
failures.push(format!("secret store enumeration: {error}"));
return failures;
}
};
for entry in stored {
if let Err(error) = secrets.delete(&entry.provider_id) {
failures.push(format!("{}: {error}", entry.provider_id));
}
}
failures
}
pub fn clear_active_provider_api_key(provider: &str) -> Result<()> {
if provider == ProviderKind::Xai.as_str() {
return codewhale_config::with_xai_oauth_revocation_transaction(|| {
clear_active_provider_api_key_unlocked(provider)
});
}
clear_active_provider_api_key_unlocked(provider)
}
fn clear_active_provider_api_key_unlocked(provider: &str) -> Result<()> {
let slot = compatibility_for_id(provider).map(|row| provider_secret_store_slot(row.kind));
match slot {
Some(slot) => crate::credentials::store::with_provider_write_lock(slot, || {
clear_active_provider_api_key_under_lock(provider)
}),
None => clear_active_provider_api_key_under_lock(provider),
}
}
fn clear_active_provider_api_key_under_lock(provider: &str) -> Result<()> {
let config_path = credential_config_path()
.context("Failed to resolve config path while clearing API keys.")?;
if config_path.exists() {
crate::config_persistence::mutate_config_document_with_migration(
&config_path,
|doc, moved| {
let deepseek_family = provider == ProviderKind::Deepseek.as_str()
|| provider == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id;
if deepseek_family || provider == ProviderKind::Custom.as_str() {
crate::config_persistence::unset_document_value(doc, &["api_key"])?;
}
let table = compatibility_for_id(provider).map_or(provider, |row| row.config_key);
let has_own_key = |doc: &toml_edit::DocumentMut| {
[table, provider].iter().any(|key| {
doc.get("providers")
.and_then(|providers| providers.get(key))
.and_then(|entry| entry.get("api_key"))
.and_then(toml_edit::Item::as_str)
.is_some_and(|value| !value.trim().is_empty())
})
};
let clears_shared_deepseek_key = provider
== codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id
&& (!has_own_key(doc) || moved.moved_root_api_key_to("deepseek"));
crate::config_persistence::unset_document_value(
doc,
&["providers", table, "api_key"],
)?;
if table != provider {
crate::config_persistence::unset_document_value(
doc,
&["providers", provider, "api_key"],
)?;
}
if clears_shared_deepseek_key {
crate::config_persistence::unset_document_value(
doc,
&["providers", "deepseek", "api_key"],
)?;
}
if provider == ProviderKind::Xai.as_str() {
crate::config_persistence::unset_document_value(
doc,
&["providers", "xai", "oauth_credential_generation"],
)?;
crate::config_persistence::unset_document_value(
doc,
&["providers", "xai", "auth_mode"],
)?;
crate::config_persistence::unset_document_value(
doc,
&["providers", "xai", "external_credentials"],
)?;
}
Ok(())
},
)
.with_context(|| format!("Failed to write config to {}", config_path.display()))?;
log_sensitive_event(
"credential.clear",
json!({
"backend": "config_file",
"config_path": config_path.display().to_string(),
"scope": provider,
}),
);
}
if let Some(secrets) = credential_secret_store()
&& let Some(slot) = ProviderKind::all()
.iter()
.find(|candidate| candidate.as_str() == provider)
.map(|candidate| provider_secret_store_slot(*candidate))
{
let has_value = secrets
.get(slot)
.ok()
.flatten()
.is_some_and(|value| !value.trim().is_empty());
if has_value {
secrets
.delete(slot)
.with_context(|| format!("failed to delete stored credential for {slot}"))?;
}
}
Ok(())
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod model_resolution_golden;
#[cfg(test)]
mod credential_scope_tests {
use super::*;
use crate::test_support::{EnvVarGuard, lock_test_env};
#[test]
fn api_key_save_rescopes_workspace_config_to_user_global() -> Result<()> {
let _lock = lock_test_env();
let temp = tempfile::tempdir()?;
let workspace = temp.path().join("repo");
fs::create_dir_all(workspace.join(".git"))?;
let project_dir = workspace.join(".codewhale");
fs::create_dir_all(&project_dir)?;
let project_config = project_dir.join("config.toml");
fs::write(&project_config, "approval_policy = \"never\"\n")?;
let user_home = temp.path().join("user-global-home");
let _home = EnvVarGuard::set("CODEWHALE_HOME", user_home.as_os_str());
let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", project_config.as_os_str());
let _legacy_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
let _backend = EnvVarGuard::remove("CODEWHALE_SECRET_BACKEND");
let _legacy_backend = EnvVarGuard::remove("DEEPSEEK_SECRET_BACKEND");
let saved = save_api_key("workspace-rescope-test-key")?;
let global_config = user_home.join("config.toml");
let saved_path = match saved {
SavedCredential::ConfigFile(path) => path,
other => panic!("expected a config-file save, got {}", other.describe()),
};
assert_eq!(
canonicalize_or_keep(&saved_path),
canonicalize_or_keep(&global_config),
"credential save must surface the user-global destination"
);
let global = fs::read_to_string(&global_config)?;
assert!(
global.contains("workspace-rescope-test-key"),
"user-global config must hold the saved key: {global}"
);
let project = fs::read_to_string(&project_config)?;
assert!(
!project.contains("workspace-rescope-test-key"),
"credential leaked into workspace config: {project}"
);
assert!(
!project.contains("api_key"),
"workspace config must stay credential-free: {project}"
);
Ok(())
}
#[test]
fn provider_api_key_save_rescopes_workspace_config_to_user_global() -> Result<()> {
let _lock = lock_test_env();
let temp = tempfile::tempdir()?;
let workspace = temp.path().join("repo");
fs::create_dir_all(workspace.join(".git"))?;
let project_dir = workspace.join(".codewhale");
fs::create_dir_all(&project_dir)?;
let project_config = project_dir.join("config.toml");
fs::write(&project_config, "approval_policy = \"never\"\n")?;
let user_home = temp.path().join("user-global-home");
let _home = EnvVarGuard::set("CODEWHALE_HOME", user_home.as_os_str());
let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", project_config.as_os_str());
let _legacy_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
let _backend = EnvVarGuard::remove("CODEWHALE_SECRET_BACKEND");
let _legacy_backend = EnvVarGuard::remove("DEEPSEEK_SECRET_BACKEND");
let path = save_api_key_for(ProviderKind::Openrouter, "workspace-rescope-openrouter-key")?;
assert_eq!(
canonicalize_or_keep(&path),
canonicalize_or_keep(&user_home.join("config.toml")),
"provider save must report the user-global destination"
);
let global = fs::read_to_string(&path)?;
assert!(global.contains("workspace-rescope-openrouter-key"));
let project = fs::read_to_string(&project_config)?;
assert!(
!project.contains("workspace-rescope-openrouter-key"),
"credential leaked into workspace config: {project}"
);
Ok(())
}
#[test]
fn managed_auto_review_disabled_replaces_user_table_and_refuses_auto_policy() -> Result<()> {
let _lock = lock_test_env();
let temp = tempfile::tempdir()?;
let home = temp.path().join("home");
fs::create_dir_all(&home)?;
let _home = EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str());
let user_config = home.join("config.toml");
let managed_config = temp.path().join("managed.toml");
let _managed =
EnvVarGuard::set("CODEWHALE_MANAGED_CONFIG_PATH", managed_config.as_os_str());
let _policy = EnvVarGuard::remove("CODEWHALE_APPROVAL_POLICY");
let _legacy_policy = EnvVarGuard::remove("DEEPSEEK_APPROVAL_POLICY");
fs::write(
&user_config,
r#"
[[auto_review.allow]]
tool = "read"
reason = "user allow"
"#,
)?;
fs::write(
&managed_config,
r#"
[auto_review]
disabled = true
"#,
)?;
let loaded = Config::load(Some(user_config.clone()), None)?;
assert!(loaded.auto_review_disabled());
assert!(
loaded
.auto_review
.as_ref()
.is_some_and(|cfg| cfg.allow.is_empty() && cfg.block.is_empty()),
"managed [auto_review] table must replace the user table"
);
fs::write(&user_config, "approval_policy = \"auto\"\n")?;
let file_err = Config::load(Some(user_config.clone()), None)
.expect_err("approval_policy = auto must fail when auto_review.disabled = true");
assert!(
file_err.to_string().contains("auto_review.disabled = true"),
"unexpected error for config approval_policy: {file_err:#}"
);
fs::write(&user_config, "")?;
let _env_policy = EnvVarGuard::set("CODEWHALE_APPROVAL_POLICY", "auto");
let env_err = Config::load(Some(user_config), None).expect_err(
"CODEWHALE_APPROVAL_POLICY=auto must fail when auto_review.disabled = true",
);
assert!(
env_err.to_string().contains("auto_review.disabled = true"),
"unexpected error for CODEWHALE_APPROVAL_POLICY: {env_err:#}"
);
Ok(())
}
#[test]
fn auto_review_reviewer_model_parses_validates_merges_and_ignores_subagents() -> Result<()> {
let _lock = lock_test_env();
let temp = tempfile::tempdir()?;
let home = temp.path().join("home");
fs::create_dir_all(&home)?;
let _home = EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str());
let _managed = EnvVarGuard::remove("CODEWHALE_MANAGED_CONFIG_PATH");
let user_config = home.join("config.toml");
fs::write(
&user_config,
r#"
[auto_review]
reviewer_model = "claude-sonnet-5-5"
[subagents]
reviewer_model = "subagent-only-model"
"#,
)?;
let loaded = Config::load(Some(user_config.clone()), None)?;
assert_eq!(
loaded.auto_review_reviewer_model(),
Some("claude-sonnet-5-5")
);
fs::write(
&user_config,
r#"
[subagents]
reviewer_model = "subagent-only-model"
"#,
)?;
let without_ar_model = Config::load(Some(user_config.clone()), None)?;
assert_eq!(without_ar_model.auto_review_reviewer_model(), None);
fs::write(
&user_config,
r#"
[auto_review]
reviewer_model = " "
"#,
)?;
let empty_err = Config::load(Some(user_config.clone()), None)
.expect_err("blank auto_review.reviewer_model must fail validation");
assert!(
empty_err.to_string().contains("reviewer_model"),
"{empty_err:#}"
);
fs::write(
&user_config,
r#"
[auto_review]
reviewer_model = "bad model\nid"
"#,
)?;
let ws_err = Config::load(Some(user_config.clone()), None)
.expect_err("whitespace in auto_review.reviewer_model must fail validation");
assert!(ws_err.to_string().contains("reviewer_model"), "{ws_err:#}");
fs::write(
&user_config,
r#"
[auto_review]
reviewer_model = "gpt-5.5"
[profiles.fast]
[profiles.fast.auto_review]
reviewer_model = "gpt-5.6"
"#,
)?;
let profiled = Config::load(Some(user_config.clone()), Some("fast"))?;
assert_eq!(profiled.auto_review_reviewer_model(), Some("gpt-5.6"));
let managed_config = temp.path().join("managed.toml");
let _managed_set =
EnvVarGuard::set("CODEWHALE_MANAGED_CONFIG_PATH", managed_config.as_os_str());
fs::write(
&managed_config,
r#"
[auto_review]
reviewer_model = "managed-reviewer"
"#,
)?;
let managed_loaded = Config::load(Some(user_config.clone()), Some("fast"))?;
assert_eq!(
managed_loaded.auto_review_reviewer_model(),
Some("managed-reviewer")
);
drop(_managed_set);
let _ = fs::remove_file(&managed_config);
fs::write(
&user_config,
r#"
[auto_review]
environment = [
"trusted git remote: origin = https://github.com/org/repo",
"trusted staging host: https://staging.example.internal",
]
"#,
)?;
let env_loaded = Config::load(Some(user_config.clone()), None)?;
assert_eq!(
env_loaded.auto_review_environment(),
&[
"trusted git remote: origin = https://github.com/org/repo".to_string(),
"trusted staging host: https://staging.example.internal".to_string(),
]
);
fs::write(
&user_config,
r#"
[auto_review]
environment = [" "]
"#,
)?;
let blank_env_err = Config::load(Some(user_config.clone()), None)
.expect_err("blank auto_review.environment entry must fail validation");
assert!(
blank_env_err
.to_string()
.contains("auto_review.environment"),
"{blank_env_err:#}"
);
fs::write(
&user_config,
r#"
[auto_review]
environment = ["bad\nline"]
"#,
)?;
let control_env_err = Config::load(Some(user_config.clone()), None)
.expect_err("control chars in auto_review.environment must fail validation");
assert!(
control_env_err
.to_string()
.contains("auto_review.environment"),
"{control_env_err:#}"
);
fs::write(
&user_config,
r#"
[auto_review]
environment = ["user remote: github.com/acme/repo"]
"#,
)?;
let _managed_env_set =
EnvVarGuard::set("CODEWHALE_MANAGED_CONFIG_PATH", managed_config.as_os_str());
fs::write(
&managed_config,
r#"
[auto_review]
environment = ["managed remote: github.internal/corp/repo"]
"#,
)?;
let managed_env = Config::load(Some(user_config), None)?;
assert_eq!(
managed_env.auto_review_environment(),
&["managed remote: github.internal/corp/repo".to_string()]
);
let review_shell_dir = tempfile::tempdir()?;
let review_shell_user = review_shell_dir.path().join("config.toml");
let review_shell_managed = review_shell_dir.path().join("managed.toml");
let _managed_unset = EnvVarGuard::remove("CODEWHALE_MANAGED_CONFIG_PATH");
fs::write(
&review_shell_user,
r#"
[auto_review]
review_all_shell = true
"#,
)?;
let default_cfg = Config::default();
assert!(!default_cfg.auto_review_review_all_shell());
let loaded_review_shell = Config::load(Some(review_shell_user.clone()), None)?;
assert!(loaded_review_shell.auto_review_review_all_shell());
let _managed_override = EnvVarGuard::set(
"CODEWHALE_MANAGED_CONFIG_PATH",
review_shell_managed.as_os_str(),
);
fs::write(
&review_shell_managed,
r#"
[auto_review]
review_all_shell = false
"#,
)?;
let managed_override_cfg = Config::load(Some(review_shell_user), None)?;
assert!(!managed_override_cfg.auto_review_review_all_shell());
Ok(())
}
}
#[cfg(any(test, feature = "test-support"))]
pub mod test_support;