Skip to main content

codewhale_runtime/
config.rs

1//! Configuration loading and defaults for codewhale.
2
3use codewhale_config::extension_host::{ExtensionHostConfig, PluginSettings};
4use codewhale_config::opencode_go_models;
5use codewhale_config::provider_preserves_custom_base_url_model;
6use codewhale_config::{
7    base_url_host, default_snapshots_enabled, resolve_xiaomi_mimo_base_url,
8    xiaomi_mimo_base_url_for_mode, xiaomi_mimo_mode_uses_standard_endpoint,
9};
10use std::borrow::Cow;
11use std::collections::{BTreeMap, HashMap};
12use std::fs;
13use std::path::{Path, PathBuf};
14use std::sync::Mutex;
15use std::time::SystemTime;
16
17use anyhow::{Context, Result};
18use codewhale_execpolicy::ExecPolicyEngine;
19use codewhale_localization::{Locale, MessageId, tr};
20use serde::{Deserialize, Serialize};
21use serde_json::json;
22#[cfg(unix)]
23use std::os::unix::fs::PermissionsExt;
24
25use crate::audit::log_sensitive_event;
26use crate::credentials::CredentialStore;
27use crate::features::{Feature, Features, FeaturesToml, is_known_feature_key};
28use codewhale_config::hooks::HooksConfig;
29
30// Sub-agent concurrency/timeout limit constants and their clamp resolvers live
31// in the `subagent_limits` leaf module. The constants are re-exported (keeping
32// each item's visibility) so `crate::config::<CONST>` paths resolve unchanged;
33// the private resolvers are pulled back in without widening external surface
34// (#3311).
35// The single place provider credential precedence is decided. Lives inside
36// `config` so it can walk the private probe helpers without widening their
37// visibility; `has_api_key_for` is a thin wrapper over it (#pi-auth-port).
38mod credential_resolve;
39pub use credential_resolve::resolve_credential_source;
40mod subagent_limits;
41pub use subagent_limits::*;
42use subagent_limits::{resolve_subagent_api_timeout_secs, resolve_subagent_heartbeat_timeout_secs};
43
44pub const XIAOMI_MIMO_PAY_AS_YOU_GO_BASE_URL: &str = "https://api.xiaomimimo.com/v1";
45pub const XIAOMI_MIMO_TOKEN_PLAN_CN_BASE_URL: &str = "https://token-plan-cn.xiaomimimo.com/v1";
46pub const XIAOMI_MIMO_TOKEN_PLAN_SGP_BASE_URL: &str = DEFAULT_XIAOMI_MIMO_BASE_URL;
47pub const XIAOMI_MIMO_TOKEN_PLAN_AMS_BASE_URL: &str = "https://token-plan-ams.xiaomimimo.com/v1";
48pub const KIMI_CODE_MEMBERSHIP_PLAN_CONSOLE_URL: &str =
49    codewhale_config::provider::KIMI_CODE_MEMBERSHIP_PLAN_CONSOLE_URL;
50/// True when `model` is the pre-refresh local-Ollama placeholder, not a tag.
51#[must_use]
52pub fn is_unresolved_local_ollama_model(model: &str) -> bool {
53    model.trim().eq_ignore_ascii_case(DEFAULT_OLLAMA_MODEL)
54}
55/// Conservative offline floor for an OAuth model absent from a fresh Codex
56/// roster. Fresh account-scoped cache metadata overrides this in route_runtime.
57pub const OPENAI_CODEX_EFFECTIVE_CONTEXT_WINDOW_TOKENS: u32 = 128_000;
58
59#[cfg(test)]
60use codewhale_config::API_KEYRING_SENTINEL;
61use codewhale_config::{ConfigApiKeyValueKind, classify_config_api_key_value};
62
63pub const DEFAULT_ZAI_PROVIDER_MAX_CONCURRENCY: usize = 3;
64pub const MAX_PROVIDER_REQUEST_CONCURRENCY: usize = 64;
65
66/// Default maximum number of automatic re-requests when a reasoning model
67/// returns only hidden thinking without any answer text or tool call.
68pub const DEFAULT_REASONING_ONLY_REPROMPTS: u32 = 2;
69
70/// Nudge sent with a recovery request after a bare clean-stop retry, or
71/// immediately on an opted-in output-limit retry. Configurable via `reprompt_message`.
72///
73/// It rides one outbound request without joining session message history.
74/// A separate prepared-request receipt retains its exact text for inspection.
75pub const DEFAULT_REASONING_ONLY_REPROMPT_MESSAGE: &str =
76    "Continue: give your answer, or make the next tool call.";
77
78pub fn default_stop_words() -> Vec<String> {
79    ["stop", "wait", "pause"]
80        .into_iter()
81        .map(str::to_string)
82        .collect()
83}
84
85use codewhale_config::ProviderKind;
86use codewhale_config::catalog::reviewed::constants::*;
87use codewhale_config::descriptors::defaults::*;
88use codewhale_config::descriptors::{compatibility_for_id, compatibility_for_selector};
89use codewhale_config::route::ProviderId;
90
91/// Exact, non-secret provider identity resolved from live configuration.
92///
93/// Built-ins use their canonical slug (for example `openrouter`). Dynamic
94/// custom providers keep the user-owned `[providers.<name>]` key so session
95/// persistence never collapses `lm-studio` into the generic `custom` kind.
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct ProviderIdentity {
98    pub provider: ProviderKind,
99    pub key: ProviderId,
100    /// Additive exact configured provider id written by current persistence
101    /// schemas. `None` is meaningful: it identifies the released legacy
102    /// root-level `provider = "custom"` route and must never be upgraded to an
103    /// exact `[providers.custom]` table merely because one exists later.
104    pub(crate) exact_id: Option<ProviderId>,
105    /// Runtime provenance for the released `ollama` + exact Cloud route.
106    /// Persistence writes the canonical Cloud kind plus the original `ollama`
107    /// id, then reconstructs this flag on resume; the flag itself is not
108    /// serialized.
109    pub(crate) migrated_legacy_ollama_cloud_route: bool,
110    /// Parse-scoped, redacted proof for the id-less migrated root route.
111    pub(crate) legacy_root_custom_generation:
112        Option<codewhale_config::credentials::CredentialGeneration>,
113}
114
115impl ProviderIdentity {
116    pub fn migrated_legacy_ollama_cloud_route(&self) -> bool {
117        self.migrated_legacy_ollama_cloud_route
118    }
119
120    #[cfg(any(test, feature = "test-support"))]
121    pub fn test_exact_identity(provider: ProviderKind, key: impl Into<String>) -> Self {
122        let key = ProviderId::from(key.into());
123        Self {
124            provider,
125            exact_id: Some(key.clone()),
126            key,
127            migrated_legacy_ollama_cloud_route: false,
128            legacy_root_custom_generation: None,
129        }
130    }
131}
132
133impl std::hash::Hash for ProviderIdentity {
134    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
135        std::hash::Hash::hash(&self.key, state);
136    }
137}
138
139pub fn is_legacy_antigravity_identity(value: &str) -> bool {
140    codewhale_config::ProviderKind::parse_config_identity(value)
141        == Some(codewhale_config::ProviderKind::Antigravity)
142}
143
144impl ProviderIdentity {
145    #[must_use]
146    pub fn persisted_id(&self) -> Option<&str> {
147        self.exact_id.as_ref().map(ProviderId::as_str)
148    }
149
150    /// Released kind spelling, retaining the China table's explicit provenance.
151    pub fn persisted_kind(&self) -> &str {
152        if self.provider == ProviderKind::Deepseek
153            && self.key.as_str() == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id
154        {
155            self.key.as_str()
156        } else {
157            self.provider.as_str()
158        }
159    }
160
161    /// Exact presentation/config leaf after admission. Auth storage policy is
162    /// separate and remains intrinsic Rust authority.
163    pub fn config_table_key(&self) -> Result<&str> {
164        if self.provider == ProviderKind::Custom {
165            return Ok(self.key.as_str());
166        }
167        if self.migrated_legacy_ollama_cloud_route {
168            return Ok(ProviderKind::Ollama.as_str());
169        }
170        self.compatibility()
171            .map(|row| row.config_key)
172            .context("provider config metadata")
173    }
174
175    /// Pure descriptor view after admission; a custom key never borrows a brand.
176    pub fn compatibility(
177        &self,
178    ) -> Option<&'static codewhale_config::descriptors::ProviderCompatibility> {
179        if self.provider == ProviderKind::Custom {
180            return None;
181        }
182        compatibility_for_id(self.key.as_str()).filter(|row| row.kind == self.provider)
183    }
184}
185
186fn normalize_subagent_provider_key(value: &str) -> String {
187    value
188        .trim()
189        .to_ascii_lowercase()
190        .chars()
191        .map(|ch| match ch {
192            '-' | '_' | '.' | ' ' => '_',
193            other => other,
194        })
195        .collect()
196}
197
198pub const DEEPSEEK_ALIAS_RETIREMENT_DATE: &str = "2026-07-24";
199pub const DEEPSEEK_ALIAS_RETIREMENT_UTC: &str = "2026-07-24T15:59:00Z";
200use codewhale_config::catalog::reviewed::constants::DEEPSEEK_ALIAS_REPLACEMENT;
201
202/// Upstream retirement metadata for a model alias that remains compatible.
203#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
204pub struct ModelAliasDeprecation {
205    pub alias: String,
206    pub replacement: String,
207    pub retirement_date: String,
208    pub retirement_utc: String,
209    pub notice: String,
210}
211
212pub fn configured_model_for_route<'a>(
213    config: &'a Config,
214    provider: ProviderKind,
215    identity: &str,
216    base_url: &str,
217    model: &str,
218) -> Option<&'a codewhale_config::catalog::configured::ConfiguredModel> {
219    // Account-owned OAuth rosters retain their separate authority.
220    if provider == ProviderKind::OpenaiCodex {
221        return None;
222    }
223    let models = config.custom_models.as_deref()?;
224    codewhale_config::catalog::configured::validate_configured_models(models).ok()?;
225    models
226        .iter()
227        .find(|row| row.id == model && row.matches_route(identity, base_url))
228}
229
230pub fn deepseek_alias_deprecation(model_lower: &str) -> Option<ModelAliasDeprecation> {
231    match model_lower {
232        "deepseek-chat" | "deepseek-reasoner" => Some(ModelAliasDeprecation {
233            alias: model_lower.to_string(),
234            replacement: DEEPSEEK_ALIAS_REPLACEMENT.to_string(),
235            retirement_date: DEEPSEEK_ALIAS_RETIREMENT_DATE.to_string(),
236            retirement_utc: DEEPSEEK_ALIAS_RETIREMENT_UTC.to_string(),
237            notice: format!(
238                "DeepSeek retired {model_lower} on {DEEPSEEK_ALIAS_RETIREMENT_DATE}; Codewhale sends {DEEPSEEK_ALIAS_REPLACEMENT} instead."
239            ),
240        }),
241        _ => None,
242    }
243}
244
245#[must_use]
246pub fn normalize_custom_model_id(model: &str) -> Option<String> {
247    let trimmed = model.trim();
248    if trimmed.is_empty() || trimmed.chars().any(char::is_control) {
249        None
250    } else {
251        Some(trimmed.to_string())
252    }
253}
254
255pub fn validate_route(provider: ProviderKind, model: &str) -> Result<(), String> {
256    let trimmed = model.trim();
257    if trimmed.is_empty() {
258        return Err(format!(
259            "No model selected for provider '{}'.",
260            provider.as_str()
261        ));
262    }
263    if trimmed.eq_ignore_ascii_case("auto") {
264        return Ok(());
265    }
266
267    if provider == ProviderKind::OpencodeGo {
268        return if opencode_go_model_id(trimmed).is_some() {
269            Ok(())
270        } else {
271            Err(format!(
272                "Model '{trimmed}' is not in OpenCode Go's documented protocol roster. \
273                 Choose one of: {}.",
274                opencode_go_models().join(", ")
275            ))
276        };
277    }
278
279    if codewhale_config::descriptors::provider_passes_model_through(provider) {
280        return Ok(());
281    }
282
283    if matches!(provider, ProviderKind::Deepseek) {
284        if codewhale_config::route::resolve_model(ProviderKind::Deepseek, trimmed, None).is_ok() {
285            return Ok(());
286        }
287        return Err(format!(
288            "Model '{trimmed}' is not a DeepSeek model, but the active provider is '{}'. \
289             Use a DeepSeek model id (for example {}) or switch providers together with the model.",
290            provider.as_str(),
291            COMMON_DEEPSEEK_MODELS.join(", ")
292        ));
293    }
294
295    if root_deepseek_model_is_foreign_to_direct_provider(provider, trimmed) {
296        return Err(format!(
297            "Model '{trimmed}' is a DeepSeek model and is not compatible with provider '{}'. \
298             Switch the provider and model together, or pick a model this provider serves.",
299            provider.as_str()
300        ));
301    }
302
303    Ok(())
304}
305
306fn legacy_deepseek_alias_reasoning_effort(model: &str) -> Option<&'static str> {
307    codewhale_config::legacy_deepseek_alias_reasoning_effort(model)
308}
309
310pub fn opencode_go_model_id(model: &str) -> Option<&'static str> {
311    codewhale_config::opencode_go_model_id(model)
312}
313
314/// Reconcile a remembered `/model` pick with the model the config file names.
315///
316/// `provider_models` in `settings.toml` remembers the last `/model` (or model
317/// picker) selection and outranks `config.toml` on the next launch. The picker
318/// offers catalog spellings, which are lowercase, so a user whose config names
319/// `DeepSeek-V4-Flash` can end up relaunching into `deepseek-v4-flash` — the
320/// wrong id for a self-hosted OpenAI-compatible gateway whose model names are
321/// case-sensitive, and the wrong id in the header.
322///
323/// When the two strings name the *same* model in a different ASCII case, the
324/// config file owns the spelling. A remembered pick that names a genuinely
325/// different model still wins, so `/model` persistence is unchanged: only the
326/// spelling defers, never the selection.
327#[must_use]
328pub(crate) fn prefer_configured_model_spelling(configured: &str, remembered: String) -> String {
329    let configured = configured.trim();
330    if remembered != configured && remembered.eq_ignore_ascii_case(configured) {
331        return configured.to_string();
332    }
333    remembered
334}
335
336/// Recover the behavioral intent of a retiring alias only when the selected
337/// route is a first-party DeepSeek endpoint. Custom endpoints own both the id
338/// and its semantics, so they deliberately return `None` here.
339pub fn legacy_deepseek_alias_effort_for_route(
340    provider: ProviderKind,
341    base_url: &str,
342    model: &str,
343) -> Option<&'static str> {
344    if !matches!(
345        provider,
346        ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
347    ) {
348        return None;
349    }
350    let effort = legacy_deepseek_alias_reasoning_effort(model)?;
351    codewhale_config::route::resolve_model(provider, model, Some(base_url))
352        .is_ok_and(|resolved| resolved.wire_id != model.trim())
353        .then_some(effort)
354}
355
356/// Reviewed per-provider model id projection used **only as a compatibility
357/// fallback** (#4188).
358///
359/// Preferred sources are the live Models.dev catalog and the offline bundled
360/// snapshot via `crate::provider_lake`. Call this directly only for
361/// Codewhale-only / local providers Models.dev does not represent, or when
362/// probing the fallback table in tests. Picker, inventory, and subagent
363/// surfaces must go through the provider lake.
364#[must_use]
365pub fn model_completion_names_for_provider(provider: ProviderKind) -> Vec<&'static str> {
366    codewhale_config::catalog::reviewed::constants::completion_names(provider.as_str()).to_vec()
367}
368
369/// The `[plugins]` table of the user config file at `path`, read on its own so
370/// an edit reaches the extension host at `/plugin reload` without reloading
371/// the whole configuration. A missing file has no settings. Blocking.
372pub fn read_plugin_settings(
373    path: &Path,
374) -> std::result::Result<BTreeMap<String, PluginSettings>, String> {
375    let contents = match fs::read_to_string(path) {
376        Ok(contents) => contents,
377        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
378        Err(error) => return Err(format!("cannot read {}: {error}", path.display())),
379    };
380    // The same parse the whole configuration goes through; its error text
381    // omits file contents, which can hold secrets.
382    parse_config_file(&contents)
383        .map(|file| file.base.plugins.unwrap_or_default())
384        .map_err(|_| format!("cannot parse {}", path.display()))
385}
386
387/// Independent recovery limits for HTTP 429; other transport errors keep their policy.
388#[derive(Debug, Clone, serde::Serialize, Deserialize)]
389#[serde(try_from = "RawRateLimitRetryPolicy")]
390pub struct RateLimitRetryPolicy {
391    pub max_attempts: u32,
392    pub recovery_budget_secs: u64,
393    pub initial_delay_secs: u64,
394    pub max_delay_secs: u64,
395}
396
397impl Default for RateLimitRetryPolicy {
398    fn default() -> Self {
399        Self {
400            max_attempts: 20,
401            recovery_budget_secs: 600,
402            initial_delay_secs: 5,
403            max_delay_secs: 60,
404        }
405    }
406}
407
408#[derive(Deserialize)]
409#[serde(default)]
410struct RawRateLimitRetryPolicy {
411    max_attempts: u32,
412    recovery_budget_secs: u64,
413    initial_delay_secs: u64,
414    max_delay_secs: u64,
415}
416
417impl Default for RawRateLimitRetryPolicy {
418    fn default() -> Self {
419        let p = RateLimitRetryPolicy::default();
420        Self {
421            max_attempts: p.max_attempts,
422            recovery_budget_secs: p.recovery_budget_secs,
423            initial_delay_secs: p.initial_delay_secs,
424            max_delay_secs: p.max_delay_secs,
425        }
426    }
427}
428
429impl TryFrom<RawRateLimitRetryPolicy> for RateLimitRetryPolicy {
430    type Error = String;
431    fn try_from(p: RawRateLimitRetryPolicy) -> Result<Self, Self::Error> {
432        if !(1..=1000).contains(&p.max_attempts)
433            || !(1..=86400).contains(&p.recovery_budget_secs)
434            || p.initial_delay_secs == 0
435            || p.initial_delay_secs > p.max_delay_secs
436            || p.max_delay_secs > 86400
437        {
438            return Err("invalid retry.rate_limit policy: attempts 1..1000, budget 1..86400s, 1 <= initial <= max <= 86400s".into());
439        }
440        Ok(Self {
441            max_attempts: p.max_attempts,
442            recovery_budget_secs: p.recovery_budget_secs,
443            initial_delay_secs: p.initial_delay_secs,
444            max_delay_secs: p.max_delay_secs,
445        })
446    }
447}
448
449/// Raw retry configuration loaded from config files.
450#[derive(Debug, Clone, Deserialize)]
451pub struct RetryConfig {
452    #[serde(default)]
453    pub rate_limit: RateLimitRetryPolicy,
454    pub enabled: Option<bool>,
455    pub max_retries: Option<u32>,
456    pub initial_delay: Option<f64>,
457    pub max_delay: Option<f64>,
458    pub exponential_base: Option<f64>,
459    /// #6700: randomize each backoff delay by `jitter_factor`. Default `true`.
460    #[serde(default)]
461    pub jitter: Option<bool>,
462    /// #6700: jitter spread as a fraction of the delay (`0.1` = ±10%).
463    /// Default `0.1`; values clamp to `0.0..=1.0`, non-finite values use the
464    /// default.
465    #[serde(default)]
466    pub jitter_factor: Option<f64>,
467    /// #6700: honor a server `Retry-After` header instead of the computed
468    /// backoff. Default `true`.
469    #[serde(default)]
470    pub respect_retry_after: Option<bool>,
471}
472
473/// Deserialize `status_items` tolerantly: skip keys unknown to this build
474/// instead of erroring with "unknown variant".  This lets a dev build write
475/// `"balance"` (or any future item) while the stable build still parses the
476/// config file successfully.
477fn deser_status_items<'de, D>(deserializer: D) -> Result<Option<Vec<StatusItem>>, D::Error>
478where
479    D: serde::Deserializer<'de>,
480{
481    let raw: Option<Vec<String>> = Option::deserialize(deserializer)?;
482    Ok(raw.map(|strings| {
483        strings
484            .into_iter()
485            .filter_map(|s| {
486                StatusItem::from_key(&s).or_else(|| {
487                    tracing::warn!("ignoring unknown status item {s:?} in config");
488                    None
489                })
490            })
491            .collect()
492    }))
493}
494
495/// Canonical model-stream and transport settings. The existing `Config`
496/// accessors own resolution; `[tui]` spellings remain read-only compatibility.
497/// Transport changes apply to newly constructed clients, not active requests.
498#[derive(Debug, Clone, Default, Deserialize, Serialize)]
499#[serde(deny_unknown_fields)]
500pub struct StreamConfig {
501    pub open_timeout_secs: Option<u64>,
502    pub chunk_timeout_secs: Option<u64>,
503    pub force_http1: Option<bool>,
504    pub max_resumes: Option<u32>,
505    pub max_transparent_retries: Option<u32>,
506    pub max_stream_errors: Option<u32>,
507    pub max_duration_secs: Option<u64>,
508    pub max_content_mb: Option<u64>,
509    pub connect_timeout_secs: Option<u64>,
510    /// Omitted keeps 30 seconds; zero disables TCP keepalive.
511    pub tcp_keepalive_secs: Option<u64>,
512    /// Omitted keeps 15 seconds; zero disables HTTP/2 PINGs.
513    pub http2_keep_alive_interval_secs: Option<u64>,
514    /// Omitted or zero keeps the 20-second PING acknowledgement deadline.
515    pub http2_keep_alive_timeout_secs: Option<u64>,
516}
517
518/// UI configuration loaded from config files.
519#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
520pub struct RouteProvenance {
521    pub provider_from_saved_selection: bool,
522    pub model_from_saved_selection: bool,
523    pub provider_from_profile: bool,
524    pub model_from_profile: bool,
525    pub provider_from_env: bool,
526    pub provider_from_managed: bool,
527    pub model_from_managed: bool,
528}
529
530#[derive(Debug, Clone, Deserialize, Default)]
531pub struct TuiConfig {
532    pub alternate_screen: Option<String>,
533    pub mouse_capture: Option<bool>,
534    /// Copy a transcript drag selection as Markdown source (`true`, the
535    /// default) instead of rendered terminal text. The payload projects every
536    /// intersected cell through the same canonical serialization Ctrl-Y and
537    /// `/copy` use. Set `false` to restore the rendered-text payload (#6156).
538    /// PRIMARY selection on Linux always keeps rendered text.
539    pub selection_copy_markdown: Option<bool>,
540    /// Per-SSE-chunk idle timeout in seconds. Defaults to 900 seconds when
541    /// omitted. `0` maps to the default; values clamp to `1..=3600`.
542    pub stream_chunk_timeout_secs: Option<u64>,
543    /// Optional ceiling on model steps in a single turn. Omitted or `0`
544    /// leaves model steps uncapped. Explicit positive values are preserved;
545    /// `u32::MAX` also represents no limit. Stream limits remain independent.
546    pub max_model_steps: Option<u32>,
547    /// Cumulative wall-clock budget for a single turn, in seconds.
548    /// Omitted or `0` means no limit; positive values are preserved. Time
549    /// blocked on a human approval decision is excluded from the measurement.
550    pub turn_wall_clock_secs: Option<u64>,
551    /// R1: per-step cap on accumulated streamed content, in megabytes.
552    /// Omitted or `0` resolve to the default (10 MB); explicit values clamp
553    /// to `64 KiB..=512 MiB`.
554    pub stream_max_content_mb: Option<u64>,
555    /// R1: per-step cap on a single stream's wall-clock duration, in
556    /// seconds. Omitted or `0` resolve to the default (1800); explicit
557    /// values clamp to `10..=86_400`.
558    pub stream_max_duration_secs: Option<u64>,
559    /// Proven pre-dispatch stream-open retries. Omitted defaults to3;
560    /// `0` disables them and values clamp to `0..=10`.
561    pub stream_max_resumes: Option<u32>,
562    /// Inactive Core compatibility setting. Omitted defaults to2;
563    /// values remain parsed and clamped to `0..=10`.
564    pub stream_max_transparent_retries: Option<u32>,
565    /// Inactive Core compatibility setting. Core ends on the first uncertain
566    /// stream error; omitted/zero defaults to5 and other values clamp to1..=50.
567    pub stream_max_errors: Option<u32>,
568    /// #6700: wait for SSE response headers, in seconds. Omitted or `0`
569    /// fall back to `CODEWHALE_STREAM_OPEN_TIMEOUT_SECS`, then 180; values
570    /// clamp to `5..=600`.
571    pub stream_open_timeout_secs: Option<u64>,
572    /// #6700: TCP/TLS connect timeout for the model HTTP client, in seconds.
573    /// Omitted or `0` resolve to the default (30); values clamp to `1..=300`.
574    pub connect_timeout_secs: Option<u64>,
575    /// #6700: pin the model HTTP client to HTTP/1.1 (config form of
576    /// `CODEWHALE_FORCE_HTTP1`). Omitted or `false` leaves HTTP/2 on unless
577    /// the env var is truthy; either one pins.
578    pub force_http1: Option<bool>,
579    /// Ordered list of footer items the user wants visible. `None` (the field
580    /// missing from `config.toml`) means "use the built-in default order"; an
581    /// empty `Some(vec![])` means "show nothing in the footer".
582    ///
583    /// Edited interactively via `/statusline`; persisted to `tui.status_items`
584    /// in `~/.deepseek/config.toml`.
585    #[serde(default, deserialize_with = "deser_status_items")]
586    pub status_items: Option<Vec<StatusItem>>,
587    /// How much of the posture bar — the first row under the composer — to
588    /// paint: `full` (default), `compact`, or `hidden`. `hidden` gives the
589    /// row back to the transcript; `compact` keeps the row and starts its
590    /// shed ladder past the clocks, counts and hints (#5950).
591    ///
592    /// `status_items` still composes what is *in* the row; this only decides
593    /// the row's size. Absent from an older `config.toml` means `full`.
594    #[serde(default)]
595    pub posture_bar: Option<ChromeRowPreset>,
596    /// The same three settings for the metrics line under the posture bar.
597    /// `compact` is the default: it keeps the route, the context reading, the cost and the
598    /// balance, the cache rate, and drops the other telemetry and the help hint (#5950, #6565).
599    #[serde(default)]
600    pub metrics_line: Option<ChromeRowPreset>,
601    /// Emit OSC 8 hyperlink escape sequences around URLs in the transcript so
602    /// supporting terminals (iTerm2, Terminal.app 13+, Ghostty, Kitty,
603    /// WezTerm, Alacritty, recent gnome-terminal/konsole) make them clickable
604    /// with the terminal's link gesture (usually Cmd-click on macOS and
605    /// Ctrl-click on Linux/Windows). Terminals without OSC 8 support render the
606    /// plain label and ignore the escape. Defaults to on for macOS/Linux and
607    /// off for Windows legacy consoles; set `false` to suppress everywhere
608    /// (e.g. for a terminal that misrenders the sequence). OSC 8 escapes are
609    /// emitted out-of-band, so buffer-column corruption is not a concern.
610    pub osc8_links: Option<bool>,
611    /// High-level notification trigger condition. When set, controls whether
612    /// operator notifications may interrupt the current terminal and, for
613    /// `Always`, overrides the `[notifications].threshold_secs` gate from the
614    /// lower-level `[notifications]` block:
615    ///
616    /// - `Always` — allow configured operator notifications even while the
617    ///   terminal is focused. Successful turn completion also ignores the
618    ///   duration threshold. Method, category, and quiet gates still apply.
619    /// - `Unfocused` — notify only after the terminal has remained unfocused
620    ///   for the built-in attention grace period. The normal duration
621    ///   threshold still applies.
622    /// - `Never` — suppress all operator notifications.
623    /// - Unset (default) — behave like `Unfocused` and fall back to the
624    ///   `[notifications]` duration threshold.
625    pub notification_condition: Option<NotificationCondition>,
626    /// When `true`, plain Up/Down on an empty composer scroll the
627    /// transcript instead of recalling input history. Useful for
628    /// terminals that map mouse-wheel gestures to arrow keys. Default:
629    /// `true` only when mouse capture is off; otherwise `false`.
630    #[serde(default)]
631    pub composer_arrows_scroll: Option<bool>,
632}
633
634/// How much of one bottom-chrome row to paint (#5950). One value for each
635/// of the two rows under the composer — [`TuiConfig::posture_bar`] and
636/// [`TuiConfig::metrics_line`] — so a small tmux pane can give one or both
637/// rows back to the transcript without touching `status_items`.
638///
639/// `compact` is not a second renderer: it starts the row's existing shed
640/// ladder at a fixed rung and lets width shed the rest, so what it keeps is
641/// exactly what a narrow row keeps.
642#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq)]
643#[serde(rename_all = "snake_case")]
644pub enum ChromeRowPreset {
645    /// Every fact the row owns, shed only by width.
646    #[default]
647    Full,
648    /// The row's shed ladder started past its most expendable rungs.
649    Compact,
650    /// No row: the transcript takes the line.
651    Hidden,
652}
653
654impl ChromeRowPreset {
655    /// Every setting value, in the order `/config` names them.
656    pub const SETTINGS: [&'static str; 3] = ["full", "compact", "hidden"];
657
658    /// Stable name used in `config.toml` and `/config`.
659    #[must_use]
660    pub const fn as_setting(self) -> &'static str {
661        match self {
662            Self::Full => "full",
663            Self::Compact => "compact",
664            Self::Hidden => "hidden",
665        }
666    }
667
668    /// Reverse of [`Self::as_setting`]; `None` for anything else.
669    #[must_use]
670    pub fn from_setting(value: &str) -> Option<Self> {
671        match value.trim().to_ascii_lowercase().as_str() {
672            "full" => Some(Self::Full),
673            "compact" => Some(Self::Compact),
674            "hidden" => Some(Self::Hidden),
675            _ => None,
676        }
677    }
678}
679
680#[cfg(test)]
681use codewhale_config::notifications::{EventSoundConfig, NotificationEventsConfig};
682
683#[cfg(test)]
684use codewhale_config::notifications::{
685    CompletionSound, NotificationConfigUpdate, NotificationMethod,
686};
687use codewhale_config::notifications::{NotificationCondition, NotificationsConfig};
688
689fn default_snapshot_max_age_days() -> u64 {
690    codewhale_config::DEFAULT_SNAPSHOT_MAX_AGE.as_secs() / (24 * 60 * 60)
691}
692
693fn default_snapshot_max_workspace_gb() -> u64 {
694    codewhale_config::DEFAULT_MAX_WORKSPACE_BYTES_FOR_SNAPSHOT / (1024 * 1024 * 1024)
695}
696
697/// Workspace side-git snapshot configuration (#137).
698#[derive(Debug, Clone, Deserialize)]
699pub struct SnapshotsConfig {
700    /// Snapshot the workspace before and after each interactive agent turn.
701    #[serde(default = "default_snapshots_enabled")]
702    pub enabled: bool,
703    /// Prune side-git snapshots older than this many days at session boot.
704    #[serde(default = "default_snapshot_max_age_days")]
705    pub max_age_days: u64,
706    /// Maximum non-excluded workspace size (in GB) before the snapshot
707    /// feature self-disables on first use. Set to `0` to disable the cap
708    /// and snapshot regardless of size (the v0.8.31 behavior). The walk
709    /// honors `.gitignore` and the snapshot module's built-in excludes
710    /// (`node_modules/`, `target/`, ...) so the measured size reflects
711    /// what would actually land in a snapshot commit.
712    #[serde(default = "default_snapshot_max_workspace_gb")]
713    pub max_workspace_gb: u64,
714}
715
716impl Default for SnapshotsConfig {
717    fn default() -> Self {
718        Self {
719            enabled: default_snapshots_enabled(),
720            max_age_days: default_snapshot_max_age_days(),
721            max_workspace_gb: default_snapshot_max_workspace_gb(),
722        }
723    }
724}
725
726/// User-level memory configuration (#489).
727///
728/// Default is opt-in: when this table is absent or `enabled = false`, the
729/// memory file is neither read nor written, and `# foo` quick-adds in the
730/// composer fall through to the normal turn-submission path.
731#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
732#[serde(rename_all = "lowercase")]
733pub enum MemoryBackend {
734    Native,
735    #[default]
736    Off,
737}
738
739#[derive(Debug, Clone, Default, Deserialize)]
740pub struct MemoryConfig {
741    /// When `true`, load the user memory file at `Config::memory_path()`
742    /// into the system prompt as a `<user_memory>` block, and intercept
743    /// `# foo` typed in the composer to append to that file. Default `false`.
744    #[serde(default)]
745    pub enabled: Option<bool>,
746    /// Explicit backend selection for the v0.9.2 memory lifecycle.
747    /// `None` preserves the pre-native opt-in behavior for old configs.
748    #[serde(default)]
749    pub backend: Option<MemoryBackend>,
750}
751
752/// Xiaomi MiMo speech/TTS output configuration.
753#[derive(Debug, Clone, Default, Deserialize)]
754pub struct SpeechConfig {
755    /// Default directory for generated speech/TTS files when no explicit
756    /// output path is provided.
757    #[serde(default)]
758    pub output_dir: Option<String>,
759}
760
761impl SnapshotsConfig {
762    #[must_use]
763    pub fn max_age(&self) -> std::time::Duration {
764        std::time::Duration::from_secs(self.max_age_days.saturating_mul(24 * 60 * 60))
765    }
766}
767
768// Web-search `[search]` table types live in the `search` leaf module and are
769// re-exported below so `crate::config::SearchProvider` (and siblings) resolve
770// unchanged (#3311).
771mod search;
772pub use search::*;
773
774/// Model-visible tool catalog controls (`[tools]` table in config.toml).
775#[derive(Debug, Clone, Deserialize, Default)]
776pub struct ToolsConfig {
777    /// Native tool names to keep loaded even when they are outside the small
778    /// default core catalog. Unknown names are harmless and simply never match.
779    #[serde(default)]
780    pub always_load: Vec<String>,
781
782    /// Optional directory to scan for plugin tool scripts. Scripts with a
783    /// frontmatter header (`# name:`, `# description:`, `# schema:`) are
784    /// auto-discovered and registered as tools.
785    ///
786    /// Defaults to `~/.codewhale/tools/` when `None`.
787    #[serde(default)]
788    pub plugin_dir: Option<String>,
789
790    /// Per-tool overrides keyed by tool name. `disabled` turns any tool off,
791    /// built-ins included; `script` / `command` adds a tool under a name no
792    /// built-in owns (or replaces a drop-in script of that name). A `script` /
793    /// `command` entry keyed by a built-in is refused and the built-in stays
794    /// active (D4; see `ToolRegistry::apply_overrides`).
795    #[serde(default)]
796    pub overrides: Option<HashMap<String, ToolOverride>>,
797
798    /// Ceiling on how many questions one `request_user_input` call may ask
799    /// (#5949). `None` uses
800    /// `DEFAULT_MAX_QUESTIONS` (6). Values outside
801    /// `1..=10` are clamped with a warning rather than failing the load.
802    #[serde(default)]
803    pub user_input_max_questions: Option<u32>,
804
805    /// Ceiling on how many options each `request_user_input` question may
806    /// offer. `None` uses `DEFAULT_MAX_OPTIONS`
807    /// (4). Values outside `2..=10` are clamped with a warning.
808    #[serde(default)]
809    pub user_input_max_options: Option<u32>,
810
811    /// Seconds Codewhale waits for a `request_user_input` answer before
812    /// cancelling it (#6003). Absent, or an explicit `0`, waits until the
813    /// person answers or cancels — the same as an approval. A positive
814    /// value bounds that one wait. Values above 86,400 (24h) are clamped
815    /// with a warning.
816    #[serde(default)]
817    pub user_input_timeout_seconds: Option<u64>,
818
819    /// Seconds a durable task may stay parked on an unanswered approval or
820    /// user-input prompt before it fails with `human_wait_timeout`. Absent,
821    /// or an explicit `0`, uses the 1,800-second (30 minute) default. Values
822    /// are clamped to `1..=86_400` (24h) with a warning.
823    #[serde(default)]
824    pub task_human_wait_cap_seconds: Option<u64>,
825
826    #[serde(default)]
827    pub max_parallel_shell_exec: Option<usize>,
828}
829
830/// Persistent-goal loop controls (`[goal]` table in config.toml, #5052).
831#[derive(Debug, Clone, Copy, Deserialize, Default, PartialEq, Eq)]
832pub struct GoalConfig {
833    /// Optional safety backstop on automatic goal continuation passes.
834    /// Goals are unlimited by default; token/time budgets are telemetry only.
835    ///
836    /// `None` uses the built-in default
837    /// (`codewhale_runtime::goal_loop::DEFAULT_MAX_GOAL_CONTINUATIONS`, currently `0`);
838    /// `0` disables the backstop entirely so only terminal status or user
839    /// control ends the run.
840    #[serde(default)]
841    pub max_continuations: Option<u32>,
842
843    /// Optional per-engine-turn step ceiling while a goal is active (#6512).
844    /// Like ordinary turns, `None` or `0` leaves model steps uncapped;
845    /// positive values are preserved. This bounds each turn, never
846    /// the number of continuation passes; explicit per-invocation ceilings
847    /// (`exec --max-turns`, child-worker caps) still win.
848    #[serde(default)]
849    pub max_steps: Option<u32>,
850    /// Optional quiet period between successful cross-turn continuations.
851    /// `0` preserves immediate continuation. Positive values make long-lived
852    /// coordinator goals yield visibly between turns instead of sleeping
853    /// inside a provider turn.
854    #[serde(default)]
855    pub continuation_delay_seconds: Option<u64>,
856
857    /// Make a goal's `token_budget` a hard stop instead of advisory telemetry
858    /// (#6013). `false`/`None` preserves current behavior: crossing the budget
859    /// logs and continues. `true` stops the run with `BudgetLimit` once
860    /// `tokens_used >= token_budget`; goals created without a token budget
861    /// stay unbounded either way.
862    #[serde(default)]
863    pub enforce_token_budget: Option<bool>,
864
865    /// Gate `update_goal status=complete` behind one independent adversarial
866    /// critique of the completion claim. Upheld completes; refuted or any
867    /// unusable verdict keeps the goal active with the gaps recorded, so a
868    /// persistent outage ends in the `NoProgress` pause. `false`/`None` keeps
869    /// the ungated behavior.
870    #[serde(default)]
871    pub complete_judge: Option<bool>,
872
873    /// Gate `update_goal status=blocked` behind one independent critique of
874    /// the blocker. Upheld blocks; refuted keeps the goal active; an
875    /// unusable verdict hands the goal back as a yield (needs input).
876    /// `false`/`None` keeps the ungated behavior.
877    #[serde(default)]
878    pub blocked_judge: Option<bool>,
879}
880
881/// Reasoning-only recovery controls (`[reasoning_only]` table in config.toml).
882/// When the model returns only hidden reasoning (thinking) without any answer
883/// text or tool call, the engine can re-request the answer automatically.
884#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
885#[serde(default)]
886pub struct ReasoningOnlyConfig {
887    pub on_output_limit: bool,
888    /// Maximum number of automatic re-requests when the model returns only
889    /// reasoning without any answer or tool call.
890    /// Defaults to 2. Set to 0 to disable automatic recovery.
891    pub max_reprompts: Option<u32>,
892    /// Nudge attached after the first bare clean-stop retry, or immediately
893    /// for an opted-in output-limit retry. Unset uses the built-in text.
894    ///
895    /// The nudge rides a single outbound request and is never added to the
896    /// session or later model context. Its exact text is logged separately
897    /// as a prepared-request receipt for transcript inspection and exports.
898    pub reprompt_message: Option<String>,
899}
900
901/// One configurable bottom-chrome item.
902///
903/// Every variant owns exactly one thing on screen, and `/statusline` turns
904/// that thing on or off:
905///
906/// | Variant | What it paints |
907/// | --- | --- |
908/// | `Mode` | the posture bar's `plan`/`act`/`operate` chip |
909/// | `Model` | the metrics line's route segment |
910/// | `ContextPercent` | the metrics line's `ctx NN%` reading |
911/// | `Cost` | the metrics line's session price |
912/// | `SessionMetrics` | the metrics line's `ttft` and `tok/s` |
913/// | `Cache` | the metrics line's `cache NN%` |
914/// | `Tokens` | the metrics line's `↓ NNN` output tokens |
915/// | `Balance` | the metrics line's prepaid-credit reading (also gates the fetch) |
916/// | `Workspace` | the metrics line's workspace leaf-directory chip |
917/// | `GitBranch` | the metrics line's current-branch chip (short SHA when detached) |
918///
919/// A variant that paints nothing does not belong here. Eight variants were
920/// retired in #5950 because the 0.9.12 shell gave their facts to a surface
921/// `/statusline` does not own — the posture bar's clock and live counts
922/// (`Status`, `Agents`), the launch header and git dock (`GitBranch`) — or
923/// because they were never wired at all (`ReasoningReplay`,
924/// `PrefixStability`, `LastToolElapsed`, `RateLimit`). #6112 revived
925/// `GitBranch` (and added `Workspace`) as opt-in metrics-line chips fed by
926/// the cached workspace context, not by a per-frame git call. The other
927/// retired keys still parse out of an old `config.toml`:
928/// [`StatusItem::from_key`] returns `None` and `deser_status_items` skips
929/// them with a warning, so an upgrader's file keeps loading.
930#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Hash)]
931#[serde(rename_all = "snake_case")]
932pub enum StatusItem {
933    /// "act" / "plan" / "operate" chip.
934    Mode,
935    /// Model identifier (e.g. `deepseek-v4-pro`).
936    Model,
937    /// Session cost in the configured display currency.
938    Cost,
939    /// Cache hit rate ("cache 73%").
940    Cache,
941    /// Context-window utilisation percent ("ctx 48%").
942    ContextPercent,
943    /// Output tokens of the live or last turn ("↓ 1.2K").
944    Tokens,
945    /// Prepaid remaining credit, refreshed once per turn completion.
946    Balance,
947    /// Legacy configuration alias enabling both TTFT and output rate.
948    /// The picker expands it into independently editable readings.
949    SessionMetrics,
950    /// Mean measured time from request dispatch to the first token.
951    Ttft,
952    /// Provider output tokens divided by measured request time.
953    OutputRate,
954    /// Leaf directory of the session workspace, left-truncated when long.
955    /// Opt-in (#6112); off the default footer.
956    Workspace,
957    /// Current git branch from the cached workspace context — the short SHA
958    /// when HEAD is detached, absent outside a repository. Opt-in (#6112);
959    /// off the default footer.
960    GitBranch,
961}
962
963impl StatusItem {
964    /// Default footer composition for the always-on status line. Used when
965    /// `tui.status_items` is missing from `config.toml` so upgraders see a
966    /// concise footer by default; diagnostic chips remain available via
967    /// `/statusline` without crowding the main UI.
968    #[must_use]
969    pub fn default_footer() -> Vec<StatusItem> {
970        vec![
971            StatusItem::Mode,
972            StatusItem::Model,
973            StatusItem::ContextPercent,
974            StatusItem::Cost,
975            StatusItem::Cache,
976            StatusItem::Tokens,
977            StatusItem::Ttft,
978            StatusItem::OutputRate,
979        ]
980    }
981
982    /// Stable canonical name used in TOML and the picker label.
983    #[must_use]
984    pub fn key(self) -> &'static str {
985        match self {
986            StatusItem::Mode => "mode",
987            StatusItem::Model => "model",
988            StatusItem::Cost => "cost",
989            StatusItem::Cache => "cache",
990            StatusItem::ContextPercent => "context_percent",
991            StatusItem::Tokens => "tokens",
992            StatusItem::Balance => "balance",
993            StatusItem::SessionMetrics => "session_metrics",
994            StatusItem::Ttft => "ttft",
995            StatusItem::OutputRate => "output_rate",
996            StatusItem::Workspace => "workspace",
997            StatusItem::GitBranch => "git_branch",
998        }
999    }
1000
1001    /// Reverse of [`key`](Self::key): parse a config string back to a variant.
1002    /// Returns `None` for unknown keys so the config parser can silently skip
1003    /// items added by newer versions rather than crashing with "unknown variant".
1004    #[must_use]
1005    pub fn from_key(key: &str) -> Option<Self> {
1006        match key {
1007            "mode" => Some(Self::Mode),
1008            "model" => Some(Self::Model),
1009            "cost" => Some(Self::Cost),
1010            "cache" => Some(Self::Cache),
1011            "context_percent" => Some(Self::ContextPercent),
1012            "tokens" => Some(Self::Tokens),
1013            // Retired in #5950; skipped rather than rejected so an old
1014            // `config.toml` still parses. See the type's doc comment.
1015            "status" | "agents" | "reasoning_replay" | "prefix_stability" | "last_tool_elapsed"
1016            | "rate_limit" => None,
1017            "balance" => Some(Self::Balance),
1018            "session_metrics" => Some(Self::SessionMetrics),
1019            "ttft" => Some(Self::Ttft),
1020            "output_rate" => Some(Self::OutputRate),
1021            "workspace" => Some(Self::Workspace),
1022            // Revived in #6112 as an opt-in metrics-line chip; it parses
1023            // again, so a config written between its #5950 retirement and
1024            // the revival simply gets the chip back.
1025            "git_branch" => Some(Self::GitBranch),
1026            _ => None,
1027        }
1028    }
1029
1030    /// Human-readable label for the picker.
1031    #[must_use]
1032    pub fn label(self) -> &'static str {
1033        match self {
1034            StatusItem::Mode => "Mode",
1035            StatusItem::Model => "Model",
1036            StatusItem::Cost => "Session cost",
1037            StatusItem::Cache => "Prompt cache hit rate",
1038            StatusItem::ContextPercent => "Context window %",
1039            StatusItem::Tokens => "Output tokens",
1040            StatusItem::Balance => "Account balance",
1041            StatusItem::SessionMetrics => "Session metrics",
1042            StatusItem::Ttft => "Time to first token",
1043            StatusItem::OutputRate => "Output rate",
1044            StatusItem::Workspace => "Workspace",
1045            StatusItem::GitBranch => "Git branch",
1046        }
1047    }
1048
1049    /// One-line hint shown beside the label so the user knows what each item
1050    /// surfaces without having to toggle it on first.
1051    #[must_use]
1052    pub fn hint(self, locale: Locale) -> Cow<'static, str> {
1053        tr(
1054            locale,
1055            match self {
1056                StatusItem::Mode => MessageId::StatusPickerModeHint,
1057                StatusItem::Model => MessageId::StatusPickerModelHint,
1058                StatusItem::Cost => MessageId::StatusPickerCostHint,
1059                StatusItem::Cache => MessageId::StatusPickerCacheHint,
1060                StatusItem::ContextPercent => MessageId::StatusPickerContextPercentHint,
1061                StatusItem::Tokens => MessageId::StatusPickerTokensHint,
1062                StatusItem::Balance => MessageId::StatusPickerBalanceHint,
1063                StatusItem::SessionMetrics => MessageId::StatusPickerSessionMetricsHint,
1064                StatusItem::Ttft => MessageId::StatusPickerTtftHint,
1065                StatusItem::OutputRate => MessageId::StatusPickerOutputRateHint,
1066                StatusItem::Workspace => MessageId::StatusPickerWorkspaceHint,
1067                StatusItem::GitBranch => MessageId::StatusPickerGitBranchHint,
1068            },
1069        )
1070    }
1071
1072    /// Editable items in display order. Legacy combined metrics parse but
1073    /// expand to the two individual controls instead of appearing twice.
1074    #[must_use]
1075    pub fn all() -> &'static [StatusItem] {
1076        &[
1077            StatusItem::Mode,
1078            StatusItem::Model,
1079            StatusItem::ContextPercent,
1080            StatusItem::Cost,
1081            StatusItem::Balance,
1082            StatusItem::Cache,
1083            StatusItem::Tokens,
1084            StatusItem::Ttft,
1085            StatusItem::OutputRate,
1086            StatusItem::Workspace,
1087            StatusItem::GitBranch,
1088        ]
1089    }
1090
1091    /// Whether this item is relevant for `provider`.  Provider-specific
1092    /// items return `false` for unsupported providers so the picker doesn't
1093    /// offer toggles that can never show useful data.
1094    #[must_use]
1095    pub fn is_available_for(self, provider: ProviderKind) -> bool {
1096        match self {
1097            StatusItem::Balance => provider_has_balance_api(provider),
1098            _ => true,
1099        }
1100    }
1101}
1102
1103/// Prepaid providers that publish a remaining-credit endpoint Codewhale
1104/// can fetch. Local runtimes and invoice-only vendors stay out.
1105#[must_use]
1106pub fn provider_has_balance_api(provider: ProviderKind) -> bool {
1107    matches!(
1108        provider,
1109        ProviderKind::Deepseek
1110            | ProviderKind::Openrouter
1111            | ProviderKind::Siliconflow
1112            | ProviderKind::SiliconflowCN
1113    )
1114}
1115
1116/// Resolved retry policy with defaults applied.
1117#[derive(Debug, Clone)]
1118pub struct RetryPolicy {
1119    pub rate_limit: RateLimitRetryPolicy,
1120    pub enabled: bool,
1121    pub max_retries: u32,
1122    pub initial_delay: f64,
1123    pub max_delay: f64,
1124    pub exponential_base: f64,
1125    pub jitter: bool,
1126    pub jitter_factor: f64,
1127    pub respect_retry_after: bool,
1128}
1129
1130/// Context management configuration.
1131///
1132/// `project_pack` is the only setting. The removed "Flash seam" layered-context
1133/// keys (`enabled`, `verbatim_window_turns`, `l1/l2/l3_threshold`,
1134/// `seam_model`, #159) are no longer fields: this table does not deny unknown
1135/// fields, so an older config that still carries them keeps loading and they
1136/// are simply ignored (#6516).
1137#[derive(Debug, Clone, Deserialize, Default)]
1138pub struct ContextConfig {
1139    /// Include a deterministic project context pack in the stable prompt
1140    /// prefix. Default: false — the pack is a large pretty-printed directory
1141    /// listing the model can rebuild with one `File` call (#4781). Set
1142    /// `[context] project_pack = true` to opt in (useful for weak tool-calling
1143    /// models).
1144    #[serde(default)]
1145    pub project_pack: Option<bool>,
1146}
1147
1148/// Maximum characters of `[compaction] summary_instructions` that are
1149/// appended to the summarizer prompt. Longer values are truncated (with a
1150/// warning) rather than rejected: a long standing instruction should not fail
1151/// the compaction pass that keeps the session alive.
1152pub const COMPACTION_SUMMARY_INSTRUCTIONS_MAX_CHARS: usize = 4_000;
1153/// Default verbatim retention budget for recent plain user messages in the
1154/// compaction replacement history (Codex parity). Unset config keeps this.
1155pub const DEFAULT_COMPACTION_RETAINED_USER_MESSAGE_TOKENS: usize = 20_000;
1156/// Lower clamp: below this the replacement history stops carrying a usable
1157/// amount of the user's own words.
1158pub const MIN_COMPACTION_RETAINED_USER_MESSAGE_TOKENS: usize = 2_000;
1159/// Upper clamp: above this the "compacted" history is large enough to
1160/// re-trigger compaction on the next turn.
1161pub const MAX_COMPACTION_RETAINED_USER_MESSAGE_TOKENS: usize = 200_000;
1162
1163/// Compaction summarizer tuning (`[compaction]`, #5956).
1164///
1165/// `auto_compact` / `auto_compact_threshold_percent` (settings.toml) decide
1166/// *when* compaction runs; these two keys decide *how* the pass behaves. Both
1167/// are absent by default and absent means today's built-in behavior, byte for
1168/// byte.
1169#[derive(Debug, Clone, Deserialize, Default)]
1170pub struct CompactionSettings {
1171    /// Standing operator instructions appended to the built-in summarizer
1172    /// prompt on every pass, manual and automatic — the effort-free
1173    /// counterpart to a one-off `/compact <focus>`, which still composes
1174    /// after this text. Empty or whitespace-only is treated as unset;
1175    /// longer than [`COMPACTION_SUMMARY_INSTRUCTIONS_MAX_CHARS`] is
1176    /// truncated where it is applied.
1177    #[serde(default)]
1178    pub summary_instructions: Option<String>,
1179    /// Token budget for the recent plain user messages kept verbatim in the
1180    /// replacement history. Clamped to
1181    /// [`MIN_COMPACTION_RETAINED_USER_MESSAGE_TOKENS`]..=
1182    /// [`MAX_COMPACTION_RETAINED_USER_MESSAGE_TOKENS`]; unset keeps
1183    /// [`DEFAULT_COMPACTION_RETAINED_USER_MESSAGE_TOKENS`].
1184    #[serde(default, alias = "retained_user_message_max_tokens")]
1185    pub retained_user_message_tokens: Option<usize>,
1186}
1187
1188/// Fleet-role model overrides for delegated workers. Canonical keys in
1189/// `models` are `worker`, `scout`, `planner`, `reviewer`, `builder`,
1190/// `verifier`, and `custom`. Legacy sub-agent type names remain accepted for
1191/// v0.9.x compatibility. Explicit manual pins are authoritative at admission.
1192#[derive(Debug, Clone, Deserialize, Default)]
1193pub struct SubagentsConfig {
1194    /// Top-level switch for the model-facing `agent` tool. `None` preserves
1195    /// the feature-flag default; `false` hides/refuses sub-agent spawning
1196    /// without changing the numeric queue/depth knobs.
1197    #[serde(default)]
1198    pub enabled: Option<bool>,
1199    #[serde(default)]
1200    pub default_model: Option<String>,
1201    #[serde(default)]
1202    pub worker_model: Option<String>,
1203    #[serde(default, rename = "scout_model", alias = "explorer_model")]
1204    pub explorer_model: Option<String>,
1205    #[serde(default, rename = "planner_model", alias = "awaiter_model")]
1206    pub awaiter_model: Option<String>,
1207    #[serde(default, rename = "reviewer_model", alias = "review_model")]
1208    pub review_model: Option<String>,
1209    #[serde(default)]
1210    pub custom_model: Option<String>,
1211    #[serde(default)]
1212    pub models: Option<HashMap<String, String>>,
1213    /// Structured role pins, folded into the same override map as the legacy
1214    /// scalar and `models` inputs. These entries take precedence over both.
1215    #[serde(default)]
1216    pub roles: Option<HashMap<String, SubagentRoleConfig>>,
1217    /// Maximum concurrent sub-agents. Overrides the top-level max_subagents
1218    /// setting. Clamped to [1, MAX_SUBAGENTS].
1219    #[serde(default)]
1220    pub max_concurrent: Option<usize>,
1221    /// How many levels of nested sub-agents the interactive `agent` tool may
1222    /// spawn. `0` blocks the model-facing `agent` tool at this runtime depth;
1223    /// use `[subagents] enabled = false` for the clearer durable off switch.
1224    /// `1` allows one level, `2` two, and so on. When unset, defaults to
1225    /// [`codewhale_protocol::fleet::DEFAULT_SPAWN_DEPTH`], with no product depth cap.
1226    /// Fleet workers are governed separately by `[fleet.exec] max_spawn_depth`;
1227    /// both use the same default.
1228    #[serde(default)]
1229    pub max_depth: Option<u32>,
1230    /// Number of direct (depth-1) sub-agents that may execute concurrently
1231    /// before further launches queue for a launch slot (#3095). When unset,
1232    /// defaults to the full resolved `max_subagents()` (no artificial
1233    /// throttle); explicit values are clamped to [1, max_subagents].
1234    #[serde(default)]
1235    pub launch_concurrency: Option<usize>,
1236    /// Maximum queued + running sub-agents admitted for one session. Defaults
1237    /// to a large bounded queue while `launch_concurrency` keeps instantaneous
1238    /// execution bounded.
1239    #[serde(default, alias = "max_total", alias = "admission_limit")]
1240    pub max_admitted: Option<usize>,
1241    /// Deprecated pre-v0.8.61 alias for `launch_concurrency`. Honored only
1242    /// when `launch_concurrency` is unset, so the new key always wins.
1243    #[serde(default, rename = "interactive_max_launch")]
1244    pub interactive_max_launch_legacy: Option<usize>,
1245    /// Per-step DeepSeek API timeout for sub-agent requests, in seconds. The
1246    /// timeout wraps `client.create_message` so a stuck single step cannot
1247    /// pin the parent's parent-completion wakeup channel indefinitely.
1248    /// Defaults to `DEFAULT_SUBAGENT_API_TIMEOUT_SECS` (600) and is clamped
1249    /// to `MIN_SUBAGENT_API_TIMEOUT_SECS..=MAX_SUBAGENT_API_TIMEOUT_SECS`
1250    /// (1..=3600). Zero or unset uses the 600s default (#1806, #1808).
1251    #[serde(default)]
1252    pub api_timeout_secs: Option<u64>,
1253    /// Wall-clock timeout for a running sub-agent that stops making
1254    /// manager-visible progress. Defaults to 5 minutes and is kept above the
1255    /// per-step API timeout so slow but legitimate model calls are not
1256    /// cancelled before their request timeout can fire (#2614).
1257    #[serde(default)]
1258    pub heartbeat_timeout_secs: Option<u64>,
1259    /// Operator-selected per-child model-turn budget. Unset or zero leaves
1260    /// every Fleet role unbounded unless an inherited limit applies.
1261    #[serde(default)]
1262    pub default_max_steps: Option<u32>,
1263    /// Operator-selected per-child wall-clock budget in seconds. Unset or
1264    /// zero leaves the run unbounded unless an inherited deadline applies.
1265    #[serde(default)]
1266    pub default_wall_time_secs: Option<u64>,
1267    /// Per-provider overrides for sub-agent fanout and budget knobs. Keys are
1268    /// provider names such as `deepseek`, `zai`, `openrouter`, or `anthropic`.
1269    #[serde(default)]
1270    pub providers: Option<HashMap<String, SubagentProviderConfig>>,
1271}
1272
1273/// One authored role pin. This new field accepts an explicit `provider/model`
1274/// declaration, or a bare model on the session provider. Legacy model inputs
1275/// retain their opaque provider-owned ids, including any slashes.
1276#[derive(Debug, Clone, Deserialize)]
1277#[serde(deny_unknown_fields)]
1278pub struct SubagentRoleConfig {
1279    pub model: String,
1280    /// Operator-approved `provider/model` routes, tried in order only when
1281    /// this pin's first request is refused before the agent has done any
1282    /// work (exhausted quota, rejected credentials or authorization, or an
1283    /// unavailable model). Listing a route authorizes sending the agent's
1284    /// task to that provider. Empty keeps the pin exact.
1285    #[serde(default)]
1286    pub replacements: Vec<String>,
1287}
1288
1289fn parse_subagent_role_pin(value: &str) -> SubagentModelOverride {
1290    let value = value.trim();
1291    match value.split_once('/') {
1292        Some((provider, model)) => SubagentModelOverride {
1293            provider: Some(provider.trim().to_string()),
1294            model: model.trim().to_string(),
1295        },
1296        None => value.into(),
1297    }
1298}
1299
1300/// One role override carried through Config, Engine, and child admission.
1301/// Provider identity is retained until the existing route resolver binds it.
1302#[derive(Debug, Clone, PartialEq, Eq)]
1303pub struct SubagentModelOverride {
1304    pub provider: Option<String>,
1305    pub model: String,
1306}
1307
1308impl From<String> for SubagentModelOverride {
1309    fn from(model: String) -> Self {
1310        Self {
1311            provider: None,
1312            model,
1313        }
1314    }
1315}
1316
1317impl From<&str> for SubagentModelOverride {
1318    fn from(model: &str) -> Self {
1319        model.to_string().into()
1320    }
1321}
1322
1323/// Provider-specific sub-agent limit overrides.
1324///
1325/// Every field inherits from `[subagents]` when unset, so a provider profile
1326/// can tighten only the knobs that matter for that API's rate limits.
1327#[derive(Debug, Clone, Deserialize, Default)]
1328pub struct SubagentProviderConfig {
1329    #[serde(default)]
1330    pub enabled: Option<bool>,
1331    #[serde(default)]
1332    pub max_concurrent: Option<usize>,
1333    #[serde(default)]
1334    pub max_depth: Option<u32>,
1335    #[serde(default)]
1336    pub launch_concurrency: Option<usize>,
1337    #[serde(default, alias = "max_total", alias = "admission_limit")]
1338    pub max_admitted: Option<usize>,
1339    #[serde(default)]
1340    pub api_timeout_secs: Option<u64>,
1341    #[serde(default)]
1342    pub heartbeat_timeout_secs: Option<u64>,
1343}
1344
1345/// `[auto]` table — knobs for the `--model auto` / `/model auto` router.
1346///
1347/// `cost_saving` (#1207): when `true`, the auto-mode router prefers the
1348/// active provider's known fast sibling for ambiguous requests, only using
1349/// its strong tier when the task clearly benefits from deeper reasoning.
1350/// Providers without a validated sibling stay on the active model. Default
1351/// is `false` (balanced — match the existing routing voice).
1352///
1353/// `cross_provider` (#4411): Auto routing is scoped to the active provider
1354/// unless this persisted opt-in is set to `true`. Without it, neither the
1355/// classifier inventory nor the local heuristic may leave the provider the
1356/// session is actually configured to use.
1357#[derive(Debug, Clone, Deserialize, Default)]
1358pub struct AutoConfig {
1359    #[serde(default)]
1360    pub cost_saving: Option<bool>,
1361    /// Persisted opt-in for cross-provider Auto routing (`[auto]
1362    /// cross_provider = true`). Default `false`: active provider only.
1363    #[serde(default)]
1364    pub cross_provider: Option<bool>,
1365    /// Optional explicit auto-router classifier route (`[auto.router]`).
1366    #[serde(default)]
1367    pub router: Option<AutoRouterConfig>,
1368}
1369
1370/// Default classifier call timeout for `[auto.router]` (seconds).
1371pub(crate) const DEFAULT_AUTO_ROUTER_TIMEOUT_SECS: u64 = 4;
1372/// Upper clamp for a configured classifier timeout: a hung local router must
1373/// not stall an Auto turn forever.
1374pub const MAX_AUTO_ROUTER_TIMEOUT_SECS: u64 = 300;
1375
1376/// Explicit classifier route for Auto model mode (`[auto.router]`).
1377///
1378/// When `provider` + `model` are set, Auto mode's classifier call goes to that
1379/// route. When unset, Auto stays local and free: it uses the heuristic and
1380/// makes no classifier call at all.
1381///
1382/// There is deliberately no implicit default. Holding a DeepSeek key used to
1383/// elect `deepseek-v4-flash` as the classifier for every Auto turn, which spent
1384/// a user's tokens on a route they never chose and privileged one provider over
1385/// the rest. Electing a network classifier is now something the operator writes
1386/// down.
1387#[derive(Debug, Clone, Default, Deserialize)]
1388pub struct AutoRouterConfig {
1389    /// Provider id for the classifier route (e.g. `"deepseek"`, `"zai"`).
1390    #[serde(default)]
1391    pub provider: Option<String>,
1392    /// Model id on that provider (e.g. `"deepseek-v4-flash"`).
1393    #[serde(default)]
1394    pub model: Option<String>,
1395    /// Thinking tier for the classifier call (e.g. `"off"`). Defaults to off.
1396    #[serde(default)]
1397    pub thinking: Option<String>,
1398    /// Classifier call timeout in seconds. Defaults to
1399    /// `DEFAULT_AUTO_ROUTER_TIMEOUT_SECS` (4); `0` means "use the default".
1400    /// Values above [`MAX_AUTO_ROUTER_TIMEOUT_SECS`] (300) are clamped so a
1401    /// hung local router cannot stall a turn indefinitely.
1402    #[serde(default)]
1403    pub timeout_secs: Option<u64>,
1404    /// Router kind (#6525): `"chat"` (default) asks a chat model for JSON;
1405    /// `"decision"` asks a System One decision model (Jev) a typed Choice
1406    /// between the active provider's fast and strong tiers. Any other value
1407    /// leaves the router unconfigured (shown as failing, never guessed).
1408    #[serde(default)]
1409    pub kind: Option<String>,
1410    /// Decision routers only: below this answer confidence (0..=1, default
1411    /// [`DEFAULT_AUTO_ROUTER_MIN_CONFIDENCE`]) the turn takes the local
1412    /// fallback instead of the decision.
1413    #[serde(default)]
1414    pub min_confidence: Option<f64>,
1415    /// Decision routers only: endpoint override for `provider = "typesafe"`
1416    /// (default `https://api.typesafe.ai/v1`). OpenRouter decision routers use
1417    /// the configured OpenRouter base URL.
1418    #[serde(default)]
1419    pub base_url: Option<String>,
1420}
1421
1422/// `[auto.router] kind` (#6525).
1423#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
1424#[serde(rename_all = "snake_case")]
1425pub enum AutoRouterKind {
1426    /// A chat model returns `{provider, model, thinking}` JSON.
1427    Chat,
1428    /// A System One decision model answers a typed Choice over tiers.
1429    Decision,
1430}
1431
1432impl AutoRouterKind {
1433    /// `None` (absent) is the chat default; an unknown value is `None` so the
1434    /// caller reports the router as not configured instead of guessing.
1435    #[must_use]
1436    pub fn parse(raw: Option<&str>) -> Option<Self> {
1437        match raw.map(str::trim).filter(|kind| !kind.is_empty()) {
1438            None => Some(Self::Chat),
1439            Some(kind) if kind.eq_ignore_ascii_case("chat") => Some(Self::Chat),
1440            Some(kind) if kind.eq_ignore_ascii_case("decision") => Some(Self::Decision),
1441            Some(_) => None,
1442        }
1443    }
1444}
1445
1446/// Default `[auto.router] min_confidence` for decision routers: TypeSafe's
1447/// "below 0.5, don't act" band (for two options, the chosen tier's
1448/// probability must reach 0.75).
1449pub const DEFAULT_AUTO_ROUTER_MIN_CONFIDENCE: f64 = 0.5;
1450
1451fn default_update_check_for_updates() -> bool {
1452    true
1453}
1454
1455fn default_update_check_interval_hours() -> u64 {
1456    codewhale_release::check::DEFAULT_CHECK_INTERVAL_HOURS
1457}
1458
1459/// Startup update-check configuration (`[update]` table in config.toml).
1460#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
1461pub struct UpdateConfig {
1462    /// When false, skip the TUI startup background update check entirely.
1463    #[serde(default = "default_update_check_for_updates")]
1464    pub check_for_updates: bool,
1465    /// Hours between network checks. The answer is cached on disk in between,
1466    /// so the notice still appears on every launch — only the request is
1467    /// throttled. `0` disables caching and checks on every launch.
1468    #[serde(default = "default_update_check_interval_hours")]
1469    pub check_interval_hours: u64,
1470    /// Optional GitHub-compatible latest-release JSON endpoint.
1471    #[serde(default)]
1472    pub update_uri: Option<String>,
1473    #[serde(default = "default_update_show_whats_new")]
1474    pub show_whats_new: bool,
1475    #[serde(default)]
1476    pub mode: Option<String>,
1477}
1478
1479fn default_update_show_whats_new() -> bool {
1480    true
1481}
1482
1483impl Default for UpdateConfig {
1484    fn default() -> Self {
1485        Self {
1486            check_for_updates: true,
1487            check_interval_hours: default_update_check_interval_hours(),
1488            update_uri: None,
1489            show_whats_new: true,
1490            mode: None,
1491        }
1492    }
1493}
1494
1495impl UpdateConfig {
1496    #[must_use]
1497    pub fn update_uri(&self) -> Option<&str> {
1498        self.update_uri
1499            .as_deref()
1500            .map(str::trim)
1501            .filter(|value| !value.is_empty())
1502    }
1503}
1504
1505fn default_cloud_facts_channel() -> String {
1506    "stable".to_string()
1507}
1508
1509fn default_cloud_facts_ttl_hours() -> u64 {
1510    codewhale_cloud_facts::DEFAULT_TTL_SECS / 3600
1511}
1512
1513/// Cloud facts overlay (`[cloud_facts]` table in config.toml). Off by default;
1514/// see `docs/CLOUD_FACTS.md`. Env: `CODEWHALE_CLOUD_FACTS=1|0` overrides
1515/// `enabled`, `CODEWHALE_DISABLE_CLOUD_FACTS=1` is a hard kill switch.
1516#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
1517pub struct CloudFactsConfig {
1518    /// When false (default), no cloud facts are read or fetched; the binary
1519    /// behaves exactly as it ships.
1520    #[serde(default)]
1521    pub enabled: bool,
1522    /// Channel slug (`stable` / `beta`).
1523    #[serde(default = "default_cloud_facts_channel")]
1524    pub channel: String,
1525    /// Optional endpoint override (`{channel}` placeholder allowed).
1526    #[serde(default)]
1527    pub url: Option<String>,
1528    /// Hours between refreshes of a verified payload.
1529    #[serde(default = "default_cloud_facts_ttl_hours")]
1530    pub ttl_hours: u64,
1531}
1532
1533impl Default for CloudFactsConfig {
1534    fn default() -> Self {
1535        Self {
1536            enabled: false,
1537            channel: default_cloud_facts_channel(),
1538            url: None,
1539            ttl_hours: default_cloud_facts_ttl_hours(),
1540        }
1541    }
1542}
1543
1544impl CloudFactsConfig {
1545    /// Runtime settings with env overrides applied.
1546    #[must_use]
1547    pub fn settings(&self) -> codewhale_cloud_facts::Settings {
1548        let channel = self.channel.trim();
1549        codewhale_cloud_facts::Settings {
1550            enabled: self.enabled,
1551            channel: if codewhale_cloud_facts::valid_channel(channel) {
1552                channel.to_string()
1553            } else {
1554                default_cloud_facts_channel()
1555            },
1556            url: self
1557                .url
1558                .as_deref()
1559                .map(str::trim)
1560                .filter(|u| !u.is_empty())
1561                .map(str::to_string),
1562            ttl_secs: self.ttl_hours.max(1).saturating_mul(3600),
1563            ..codewhale_cloud_facts::Settings::default()
1564        }
1565        .resolve()
1566    }
1567}
1568
1569/// Which approval option a freshly rendered approval card highlights.
1570#[derive(Debug, Clone, Copy, Deserialize, Default, PartialEq, Eq)]
1571#[serde(rename_all = "snake_case")]
1572pub enum ApprovalDefaultSelection {
1573    /// Highlight the deny option, so a reflexive Enter refuses the call.
1574    #[default]
1575    Deny,
1576    /// Highlight "allow once", restoring the pre-v0.9.6 Enter-to-approve flow.
1577    AllowOnce,
1578}
1579
1580/// Approval-card presentation (`[approval]` table in config.toml). Approval
1581/// *policy* stays the top-level `approval_policy` key; this table only governs
1582/// how the card is presented once a prompt is already required.
1583#[derive(Debug, Clone, Copy, Deserialize, Default, PartialEq, Eq)]
1584pub struct ApprovalConfig {
1585    /// Option highlighted when an approval card first appears (#5293).
1586    /// Default: `deny`.
1587    #[serde(default)]
1588    pub default_selection: ApprovalDefaultSelection,
1589    /// Seconds an interactive approval card may wait before it resolves
1590    /// **deny** on its own (#6101). Absent or an explicit `0` waits
1591    /// indefinitely — the operator is at the terminal, so the card stays
1592    /// unbounded by default. Values above 86,400 (24h) are clamped with a
1593    /// warning.
1594    #[serde(default)]
1595    pub timeout_seconds: Option<u64>,
1596}
1597
1598/// `transcript.prose_measure` exactly as written in `config.toml`.
1599///
1600/// Parsed permissively (any scalar shape) so an invalid value can surface as
1601/// a targeted `transcript.prose_measure` config error via [`Config::validate`]
1602/// instead of a generic whole-file parse failure that names no key.
1603#[derive(Debug, Clone, Deserialize)]
1604#[serde(untagged)]
1605pub enum RawProseMeasure {
1606    Integer(i64),
1607    Float(f64),
1608    Boolean(bool),
1609    Text(String),
1610}
1611
1612impl RawProseMeasure {
1613    /// Render the raw file value for config diagnostics.
1614    fn describe(&self) -> String {
1615        match self {
1616            Self::Integer(value) => value.to_string(),
1617            Self::Float(value) => value.to_string(),
1618            Self::Boolean(value) => value.to_string(),
1619            Self::Text(value) => format!("'{value}'"),
1620        }
1621    }
1622}
1623
1624/// Transcript rendering controls (`[transcript]` table in config.toml).
1625#[derive(Debug, Clone, Default, Deserialize)]
1626#[serde(deny_unknown_fields)]
1627pub struct TranscriptConfig {
1628    /// Wrap cap, in terminal columns, for prose cells — user messages,
1629    /// assistant answers, and reasoning/thinking blocks — in the live
1630    /// transcript (#5436). Absent or `0` spends the full content width,
1631    /// matching tool/status cells and the #5322 wide-frame decision. A
1632    /// positive integer caps prose at that many columns for owners who
1633    /// want a bounded reading measure on ultrawide displays. Tool, diff,
1634    /// and status cells never inherit this cap.
1635    #[serde(default)]
1636    pub prose_measure: Option<RawProseMeasure>,
1637}
1638
1639impl TranscriptConfig {
1640    /// Resolve the raw file value into a prose wrap cap.
1641    ///
1642    /// `Ok(None)` means full content width. Errors describe the raw value so
1643    /// [`Config::validate`] can name the offending key and setting.
1644    fn prose_measure_columns(&self) -> Result<Option<u16>, String> {
1645        match &self.prose_measure {
1646            None | Some(RawProseMeasure::Integer(0)) => Ok(None),
1647            Some(RawProseMeasure::Integer(columns)) if *columns > 0 => {
1648                Ok(Some((*columns).min(i64::from(u16::MAX)) as u16))
1649            }
1650            Some(raw) => Err(format!(
1651                "expected a positive whole number of columns \
1652                 (0 or absent = full width), got {}",
1653                raw.describe()
1654            )),
1655        }
1656    }
1657}
1658
1659/// Process-only account auth transform. Shared by Config clones so logout and
1660/// expiry affect future request resolution without rewriting provider config.
1661/// Running turns retain their materialized client; immediate revocation of
1662/// that credential remains the account service's responsibility.
1663#[derive(Debug, Clone)]
1664pub struct AccountModelAccess {
1665    pub session_id: String,
1666    pub credential: crate::credentials::Credential,
1667    pub expires_at: i64,
1668    pub profile: Option<String>,
1669}
1670
1671pub trait ModelHttpPolicy: std::fmt::Debug + Send + Sync {
1672    fn configure(
1673        &self,
1674        builder: reqwest::ClientBuilder,
1675        base_url: &str,
1676    ) -> Result<reqwest::ClientBuilder>;
1677}
1678
1679/// Resolved CLI configuration, including defaults and environment overrides.
1680#[derive(Debug, Clone, Default, Deserialize)]
1681pub struct Config {
1682    #[serde(skip)]
1683    pub model_http_policy: Option<std::sync::Arc<dyn ModelHttpPolicy>>,
1684    #[serde(skip)]
1685    pub account_profile: Option<String>,
1686    /// Diagnostic clones must never refresh or mutate plugin OAuth credentials.
1687    #[serde(skip)]
1688    pub plugin_oauth_read_only: bool,
1689    /// Never deserialized from disk or exposed as provider configuration.
1690    #[serde(skip)]
1691    pub account_model_access: std::sync::Arc<parking_lot::RwLock<Option<AccountModelAccess>>>,
1692    #[serde(skip)]
1693    pub session_provider_keys_only: bool,
1694    #[serde(skip)]
1695    pub session_provider_keys: std::sync::Arc<
1696        parking_lot::RwLock<HashMap<ProviderIdentity, (String, crate::credentials::Credential)>>,
1697    >,
1698    #[serde(skip)]
1699    pub required_account_model_owner: Option<String>,
1700    /// Runtime-only extra roots the tool layer may read and write outside the
1701    /// workspace, set by `codewhale exec --add-dir`.
1702    #[serde(skip)]
1703    pub extra_trusted_paths: Vec<std::path::PathBuf>,
1704    /// Persisted exact-route declarations, separate from provider credentials.
1705    #[serde(
1706        default,
1707        deserialize_with = "codewhale_config::catalog::configured::deserialize_configured_models"
1708    )]
1709    pub custom_models: Option<Vec<codewhale_config::catalog::configured::ConfiguredModel>>,
1710    /// Single-token inputs that cancel the active turn before dispatch.
1711    #[serde(default)]
1712    pub stop_words: Option<Vec<String>>,
1713    pub provider: Option<String>,
1714    // No top-level `api_key` / `base_url`: `parse_config_file` moves the
1715    // legacy keys into `[providers.<name>]` before this struct is built
1716    // (#6394).
1717    /// Optional extra HTTP headers sent to model API requests.
1718    #[serde(alias = "httpHeaders")]
1719    pub http_headers: Option<HashMap<String, String>>,
1720    /// Optional user-facing tab/window title shown as `[title] …` in front of
1721    /// the terminal window title (the `Codewhale` / `reasoning…` / `done.`
1722    /// states). This is the default for every session in this config scope;
1723    /// the `/title` command overrides it per session, and `/config title …
1724    /// --save` persists a new default here. Multi-window setups can point each
1725    /// workspace at its own `--config` file (or profile) so alt-tabbed
1726    /// sessions are identifiable at a glance.
1727    pub title: Option<String>,
1728    #[serde(alias = "defaultTextModel")]
1729    pub default_text_model: Option<String>,
1730    /// Read-only compatibility for the dispatcher's historical root `model`.
1731    /// New durable choices are written to the provider model slot.
1732    #[serde(rename = "model", skip_serializing)]
1733    pub legacy_model: Option<String>,
1734    #[serde(alias = "authMode")]
1735    pub auth_mode: Option<String>,
1736    /// DeepSeek reasoning-effort tier: `"auto" | "off" | "low" | "medium" | "high" | "max"`.
1737    /// Defaults to `"auto"` at runtime if unset.
1738    pub reasoning_effort: Option<String>,
1739    /// True only when compatibility migration inferred `reasoning_effort`
1740    /// from a retiring DeepSeek alias. This distinguishes that inferred value
1741    /// from a user override during an in-session provider switch.
1742    #[serde(skip)]
1743    pub reasoning_effort_inferred_from_legacy_alias: bool,
1744    /// Runtime-only receipt that a fresh launch adopted the selected Fleet's
1745    /// operator provider/model pair. App initialization uses it to prevent
1746    /// generic remembered `/model` preferences from replacing that selected
1747    /// Fleet route later in the same launch.
1748    #[serde(skip)]
1749    pub fleet_operator_route_applied: bool,
1750    /// Runtime-only receipt that the selected Fleet also supplied a reasoning
1751    /// tier. Kept separate because an operator with no tier deliberately
1752    /// inherits the ordinary session/settings reasoning preference.
1753    #[serde(skip)]
1754    pub fleet_operator_reasoning_applied: bool,
1755    /// Original first-party DeepSeek alias captured before model normalization.
1756    /// This runtime-only receipt lets diagnostics explain why the resolved
1757    /// model changed without persisting compatibility state back to config.
1758    #[serde(skip)]
1759    pub migrated_deepseek_model_alias: Option<String>,
1760    /// Runtime-only receipt that the released `ollama` + exact
1761    /// `https://ollama.com/v1` tuple was upgraded to `ollama-cloud` in memory.
1762    ///
1763    /// This survives route-scoped config clones so old provider-table and
1764    /// secret-slot reads remain available to that exact migrated route. It is
1765    /// never serialized and is never set for an explicit `ollama-cloud`
1766    /// selection.
1767    #[serde(skip)]
1768    pub(crate) migrated_legacy_ollama_cloud_route: bool,
1769    /// Runtime-only isolation boundary for account-owned managed Chat.
1770    ///
1771    /// This is never user-configurable or serialized. The Runtime Chat relay
1772    /// sets it on its private config clone so the Engine suppresses all host
1773    /// workspace metadata and constructs no model-visible MCP, sub-agent, or
1774    /// native tool surface for those turns.
1775    #[serde(skip)]
1776    pub runtime_chat_isolated: bool,
1777    /// Runtime-only marker for an independent RuntimeThreadManager store.
1778    ///
1779    /// Those threads are not projected into the interactive TUI's attached
1780    /// CWC run, so their provider requests do not participate in that run's
1781    /// exclusive Chat ownership gate. RuntimeThreadManager sets this marker on
1782    /// its private config clone; it is never user-configurable or serialized.
1783    #[serde(skip)]
1784    pub runtime_thread_inference_unrelated: bool,
1785    /// Native tool catalog controls. This table controls built-in
1786    /// tool loading policy.
1787    #[serde(default)]
1788    pub tools: Option<ToolsConfig>,
1789    pub skills_dir: Option<String>,
1790    pub mcp_config_path: Option<String>,
1791    pub mcp_oauth_callback_port: Option<u16>,
1792    pub mcp_oauth_callback_url: Option<String>,
1793    pub notes_path: Option<String>,
1794    pub memory_path: Option<String>,
1795    /// When true, set `tool_choice: "required"` and opt compatible function
1796    /// schemas into DeepSeek beta strict mode. Schemas with root alternatives
1797    /// stay non-strict to avoid changing optional/one-of tool semantics.
1798    pub strict_tool_mode: Option<bool>,
1799    /// Additional user-owned system-prompt sources concatenated in declared
1800    /// order (#454). Paths are expanded via `expand_path` so `~` and env vars
1801    /// work. Project-scope config is not allowed to set this field; the TUI
1802    /// project overlay ignores `instructions` so a cloned repo cannot choose
1803    /// arbitrary local files to place into the prompt. Each configured file is
1804    /// loaded, capped at 100 KiB, and skipped (with a warning) on read errors so
1805    /// a missing optional file doesn't fail the launch.
1806    pub instructions: Option<Vec<String>>,
1807    pub allow_shell: Option<bool>,
1808    /// Opt-in ghost-text follow-up prompt suggestion after each completed turn.
1809    /// Default: false — the user must explicitly set this to true to enable.
1810    pub prompt_suggestion: Option<bool>,
1811    #[serde(alias = "approvalPolicy")]
1812    pub approval_policy: Option<String>,
1813    #[serde(alias = "sandboxMode")]
1814    pub sandbox_mode: Option<String>,
1815    /// Whether a workspace-write sandbox also grants the shell outbound
1816    /// network access. Defaults to `false`: editing the workspace is not a
1817    /// reason to be able to reach the internet. Network comes from an explicit
1818    /// opt-in here, from a `danger-full-access` posture, or from the
1819    /// post-denial elevation prompt. `yolo`/`Bypass` is unaffected — it
1820    /// resolves to `danger-full-access`, which is unsandboxed by definition.
1821    #[serde(alias = "sandboxNetworkAccess")]
1822    pub sandbox_network_access: Option<bool>,
1823    /// Foreign-agent instruction formats to import as project instructions.
1824    /// Empty by default: a `CLAUDE.md`, `.cursorrules`, or
1825    /// `.github/copilot-instructions.md` written as law for another tool is
1826    /// not silently treated as law for this one. Accepts `claude`, `cursor`,
1827    /// `cline`, `windsurf`, `gemini`, `copilot`, `muse`, or `all`.
1828    #[serde(default, alias = "projectInstructionImports")]
1829    pub project_instruction_imports: Vec<String>,
1830    /// Per-scope standing-instruction budgets (#6526).
1831    ///
1832    /// User config only, like `instructions`: the project-scope overlay
1833    /// cannot set it, so a cloned repository cannot shrink the user's global
1834    /// budget or force `policy = "refuse"`.
1835    #[serde(default, alias = "instructionBudget")]
1836    pub instruction_budget: Option<codewhale_config::instruction_budget::InstructionBudgetConfig>,
1837    /// `telemetry` as written to the config file, before environment and
1838    /// default resolution. Kept so doctor and config displays can state the
1839    /// *resolved* consent with its source (default | env | config) instead of
1840    /// reading "unset" while batches ship (#5441).
1841    #[serde(default)]
1842    pub telemetry: Option<bool>,
1843    #[serde(default, alias = "fallbackProviders")]
1844    pub fallback_providers: Vec<codewhale_config::ProviderKind>,
1845    pub yolo: Option<bool>,
1846    pub verbosity: Option<String>,
1847    /// External sandbox backend: `"none"` or `"opensandbox"`.
1848    /// When set, exec_shell routes commands through the backend's HTTP API
1849    /// instead of spawning a local process.
1850    #[serde(alias = "sandboxBackend")]
1851    pub sandbox_backend: Option<String>,
1852    /// Base URL for the external sandbox backend (default: `"http://localhost:8080"`).
1853    #[serde(alias = "sandboxUrl")]
1854    pub sandbox_url: Option<String>,
1855    /// Optional API key for the external sandbox backend (sent as Bearer token).
1856    #[serde(alias = "sandboxApiKey")]
1857    pub sandbox_api_key: Option<String>,
1858    /// When true and bubblewrap actually works on this Linux host, route
1859    /// sandboxed exec_shell commands through it (#2184).
1860    /// Defaults to true — an unset key means sandboxed commands run under
1861    /// bwrap whenever `/usr/bin/bwrap` is installed and can create its
1862    /// namespaces. An explicit `prefer_bwrap = false` opts out and leaves
1863    /// Linux commands unwrapped (the posture then reports policy-only).
1864    /// Requires the `bubblewrap` package to be installed separately — we do
1865    /// NOT vendor bwrap.
1866    #[serde(alias = "preferBwrap")]
1867    pub prefer_bwrap: Option<bool>,
1868    #[serde(skip)]
1869    pub tool_launcher: Option<Vec<String>>,
1870    /// Additional host paths to bind read-only inside the bubblewrap sandbox
1871    /// (Linux, `prefer_bwrap = true`, #5410). The default root bind already
1872    /// exposes the host filesystem read-only; these cover setups where a
1873    /// policy or future default narrows it. Non-existent paths are skipped.
1874    #[serde(default, alias = "bwrapRoRoots")]
1875    pub bwrap_ro_roots: Vec<std::path::PathBuf>,
1876    /// Host device nodes to bind read-write inside the bubblewrap sandbox
1877    /// (#5410), e.g. `/dev/null` for shell redirection against the host node.
1878    /// Only character/block devices are honored — never directories — so
1879    /// this key cannot become a writable-root escape hatch. Non-existent or
1880    /// non-device paths are skipped. The default private `/dev` already
1881    /// provides fresh device nodes, so most users never need this.
1882    #[serde(default, alias = "bwrapDevRoots")]
1883    pub bwrap_dev_roots: Vec<std::path::PathBuf>,
1884    /// Opt-in sandbox read deny-list (S1, #5568). Listed subpaths are
1885    /// unreadable inside sandboxed shell commands even though the sandbox
1886    /// otherwise grants full-disk read: Seatbelt appends last-match-wins
1887    /// deny rules; bubblewrap masks each existing path with an empty tmpfs
1888    /// (directories) or a /dev/null bind (files). A leading `~` expands to
1889    /// the user's home. Empty (the default) preserves current behavior.
1890    /// Example: `sandbox_denied_read_paths = ["~/.ssh", "~/.aws"]`.
1891    #[serde(default, alias = "sandboxDeniedReadPaths")]
1892    pub sandbox_denied_read_paths: Vec<std::path::PathBuf>,
1893    /// Apply the built-in credential-store read deny-list (S1). Defaults to
1894    /// `true`: `~/.ssh`, cloud credential dirs, keychains, browser profiles,
1895    /// `.env` files, and Codewhale's own secret stores are unreadable by the
1896    /// file-reading tools and by sandboxed shell commands. Set to `false` to
1897    /// restore the pre-S1 full-disk-read behavior. See
1898    /// `sandbox::read_guard` for the exact list and its honest limits — it is
1899    /// defense-in-depth, not a security boundary.
1900    #[serde(default, alias = "sandboxReadDenylistDefaults")]
1901    pub sandbox_read_denylist_defaults: Option<bool>,
1902    /// Subtract paths from the *built-in* deny-list defaults when a project
1903    /// genuinely needs one of them. Has no effect on
1904    /// `sandbox_denied_read_paths`: an explicit deny always wins.
1905    #[serde(default, alias = "sandboxReadDenylistExempt")]
1906    pub sandbox_read_denylist_exempt: Vec<std::path::PathBuf>,
1907    #[serde(alias = "managedConfigPath")]
1908    pub managed_config_path: Option<String>,
1909    #[serde(alias = "requirementsPath")]
1910    pub requirements_path: Option<String>,
1911    #[serde(alias = "maxSubagents")]
1912    pub max_subagents: Option<usize>,
1913    pub retry: Option<RetryConfig>,
1914    pub stream: Option<StreamConfig>,
1915    pub features: Option<FeaturesToml>,
1916    /// Experimental TypeScript extension host settings.
1917    #[serde(default)]
1918    pub extension_host: Option<ExtensionHostConfig>,
1919    /// Per-plugin settings (`[plugins."<name>".config]`). User config only.
1920    #[serde(default)]
1921    pub plugins: Option<BTreeMap<String, PluginSettings>>,
1922
1923    /// Deterministic user-level auto-review policy for tool calls. The engine
1924    /// applies these rules after built-in safety floors, so config cannot
1925    /// bypass publish/destructive-background holds.
1926    #[serde(default)]
1927    pub auto_review: Option<AutoReviewConfig>,
1928
1929    /// TUI configuration (alternate screen, etc.)
1930    pub tui: Option<TuiConfig>,
1931
1932    /// Transcript rendering controls (`[transcript]` table). Absent means
1933    /// prose uses the full content width (#5436).
1934    #[serde(default)]
1935    pub transcript: Option<TranscriptConfig>,
1936
1937    /// Lifecycle hooks configuration
1938    #[serde(default)]
1939    pub hooks: Option<HooksConfig>,
1940
1941    /// Lifecycle event outbox (`[lifecycle_outbox]`). Opt-in: an unset or
1942    /// empty `path` disables the feature and leaves behavior unchanged.
1943    /// Fires for interactive TUI sessions and headless `codewhale exec` runs.
1944    #[serde(default)]
1945    pub lifecycle_outbox: Option<codewhale_config::LifecycleOutboxToml>,
1946
1947    /// Per-session control socket (`[control_socket]`). Opt-in: an absent
1948    /// table or `enabled = false` (the default) leaves the feature off.
1949    /// When enabled, the interactive TUI binds a unix socket per running
1950    /// session (see `crate::tui::control_socket`).
1951    #[serde(default)]
1952    pub control_socket: Option<codewhale_config::ControlSocketToml>,
1953
1954    /// Provider-specific credentials and defaults shared with the `codewhale` facade.
1955    #[serde(default)]
1956    pub providers: Option<ProvidersConfig>,
1957
1958    /// Desktop notification settings (OSC 9 / BEL on long turn completion).
1959    #[serde(default)]
1960    pub notifications: Option<NotificationsConfig>,
1961
1962    /// Approval-card presentation (`[approval]`). Absent means deny-by-default
1963    /// preselection.
1964    #[serde(default)]
1965    pub approval: Option<ApprovalConfig>,
1966
1967    /// Per-domain network policy (#135). When absent, network tools fall back
1968    /// to a permissive default that mirrors pre-v0.7.0 behavior.
1969    #[serde(default)]
1970    pub network: Option<codewhale_config::NetworkPolicyToml>,
1971
1972    /// Verifier-preview behavior (#2093). When absent, automatic verifier
1973    /// preview stays off and verifier verdicts use the hunt policy.
1974    #[serde(default)]
1975    pub verifier: Option<codewhale_config::VerifierConfigToml>,
1976
1977    /// Background advisor watcher (#3982). When absent, the advisor is off
1978    /// by default. Enable with `[advisor] enabled = true` or `/advisor on`.
1979    #[serde(default)]
1980    pub advisor: Option<codewhale_config::AdvisorConfigToml>,
1981
1982    /// Community skill installer settings (#140). When absent, installer
1983    /// commands fall back to the bundled defaults
1984    /// (`codewhale_skill_install::install::DEFAULT_REGISTRY_URL` +
1985    /// `codewhale_skill_install::install::DEFAULT_MAX_SIZE_BYTES`).
1986    #[serde(default)]
1987    pub skills: Option<SkillsConfig>,
1988
1989    /// Workspace side-git snapshots (#137). Defaults to enabled with 7-day
1990    /// retention when the table is absent.
1991    #[serde(default)]
1992    pub snapshots: Option<SnapshotsConfig>,
1993
1994    /// Web search provider configuration. When absent, defaults to keyless
1995    /// Firecrawl. Other API services require credentials; SearXNG requires a
1996    /// trusted `base_url`.
1997    #[serde(default)]
1998    pub search: Option<SearchConfig>,
1999
2000    /// Persistent-goal loop controls (#5052). When absent, goals have no
2001    /// continuation ceiling. Users can opt into one with
2002    /// `[goal] max_continuations`.
2003    #[serde(default)]
2004    pub goal: Option<GoalConfig>,
2005
2006    /// Reasoning-only recovery controls. When absent, the engine uses the
2007    /// built-in default (2 retries, no custom message). Configure with
2008    /// `[reasoning_only] max_reprompts`, `reprompt_message`, and `on_output_limit`.
2009    #[serde(default)]
2010    pub reasoning_only: Option<ReasoningOnlyConfig>,
2011
2012    /// User-level memory (#489). Default behaviour is **opt-in**:
2013    /// loading + injection happens only when `[memory] enabled = true` or
2014    /// `DEEPSEEK_MEMORY=on` is set. The surviving store is the native
2015    /// Markdown + SQLite FTS5 system (`memory/global/MEMORY.md`).
2016    #[serde(default)]
2017    pub memory: Option<MemoryConfig>,
2018
2019    /// Xiaomi MiMo speech/TTS defaults.
2020    #[serde(default)]
2021    pub speech: Option<SpeechConfig>,
2022
2023    /// Tunables for `--model auto` (#1207). When absent, the auto router
2024    /// keeps its existing balanced behaviour.
2025    #[serde(default)]
2026    pub auto: Option<AutoConfig>,
2027
2028    /// Optional 1-8 hotbar slot bindings (#2064). When absent, hotbar UI and
2029    /// dispatch layers use the built-in defaults from `codewhale_config`.
2030    #[serde(default)]
2031    pub hotbar: Option<Vec<codewhale_config::HotbarBindingToml>>,
2032
2033    /// Startup update-check behavior. When absent, the TUI keeps the default
2034    /// fire-and-forget latest-release check.
2035    #[serde(default)]
2036    pub update: Option<UpdateConfig>,
2037
2038    /// Cloud facts overlay (`[cloud_facts]`). Absent/false = off.
2039    #[serde(default)]
2040    pub cloud_facts: Option<CloudFactsConfig>,
2041
2042    /// Post-edit LSP diagnostics injection (#136). When absent, the engine
2043    /// applies the defaults documented in [`codewhale_config::LspConfigToml`].
2044    #[serde(default)]
2045    pub lsp: Option<codewhale_config::LspConfigToml>,
2046
2047    /// Context configuration (project context pack; legacy seam keys are
2048    /// parsed but ignored since the 2026-07-23 removal).
2049    #[serde(default)]
2050    pub context: ContextConfig,
2051
2052    /// Compaction summarizer tuning (#5956). Absent keeps the built-in
2053    /// summarizer prompt and the 20 000-token verbatim retention budget.
2054    #[serde(default)]
2055    pub compaction: Option<CompactionSettings>,
2056
2057    /// Agent Fleet trust/security/role/exec config.
2058    #[serde(default)]
2059    pub fleet: Option<codewhale_config::FleetConfigToml>,
2060
2061    /// Workflow automatic-launch, approval, isolation, and activity
2062    /// persistence knobs (#4128). When absent, consumers use
2063    /// [`codewhale_config::WorkflowConfigToml::default`] via
2064    /// [`Self::workflow_config`].
2065    #[serde(default)]
2066    pub workflow: Option<codewhale_config::WorkflowConfigToml>,
2067
2068    /// Sub-agent model overrides.
2069    #[serde(default)]
2070    pub subagents: Option<SubagentsConfig>,
2071
2072    /// Runtime API server tuning (`codewhale serve --http`). Currently only
2073    /// hosts the CORS allow-list extension (whalescale#255 / #561). When the
2074    /// table is absent, the daemon ships with localhost:3000 / localhost:1420
2075    /// as the only allowed dev origins.
2076    #[serde(default)]
2077    pub runtime_api: Option<RuntimeApiConfig>,
2078
2079    /// Workshop / large-tool-output routing (#548). When absent, the global
2080    /// default threshold of 4 096 tokens applies and routing is active.
2081    #[serde(default)]
2082    pub workshop: Option<codewhale_config::WorkshopConfig>,
2083
2084    /// Vision model configuration for the `image_analyze` tool.
2085    #[serde(default)]
2086    pub vision_model: Option<VisionModelConfig>,
2087
2088    /// Model-bound credential redaction policy (`[redaction]`). When absent,
2089    /// masking is enabled — the shipped security default. A `"disabled"`
2090    /// request only takes effect after a TUI restart and an explicit
2091    /// confirmation on the startup gate; see
2092    /// [`codewhale_config::redaction`].
2093    #[serde(default)]
2094    pub redaction: Option<codewhale_config::redaction::RedactionToml>,
2095
2096    /// Local provenance of the config actually loaded, including --config and
2097    /// CODEWHALE_CONFIG_PATH. Consent must not borrow another config's receipt.
2098    #[serde(skip)]
2099    pub loaded_config_path: Option<PathBuf>,
2100
2101    /// Runtime-only receipt that a higher-precedence layer supplied `[network]`
2102    /// — a managed overlay. The resolved policy is then not the user
2103    /// document's to replace: a mid-session re-read of that document must not
2104    /// widen what the higher layer set.
2105    #[serde(skip)]
2106    pub network_layer_is_managed: bool,
2107
2108    /// A resolved startup snapshot never reads remembered route choices again.
2109    /// False means an explicit config/profile owns the route instead.
2110    #[serde(skip)]
2111    pub remembered_selection_scope: Option<bool>,
2112
2113    /// An explicit model applied by the environment/CLI layer outranks project
2114    /// defaults, including when it equals the previously saved model.
2115    #[serde(skip)]
2116    pub environment_model_applied: bool,
2117
2118    #[serde(skip)]
2119    pub route_provenance: RouteProvenance,
2120
2121    /// Atomic migration receipt: provider/model selections now belong to this
2122    /// config document. Settings route fields are legacy inputs only.
2123    pub route_preferences_version: Option<u32>,
2124
2125    /// Sibling `permissions.toml` ask-rules compiled for runtime checks.
2126    ///
2127    /// This is deliberately not part of `config.toml`; it is loaded from the
2128    /// companion permissions file after profile/env/managed config resolution.
2129    #[serde(skip)]
2130    pub exec_policy_engine: ExecPolicyEngine,
2131
2132    /// Receipt describing what the environment layer did to this config's
2133    /// effective base URL.
2134    ///
2135    /// This provenance cannot be reconstructed from the merged provider table:
2136    /// environment overrides are written into the same `base_url` field as
2137    /// file-owned routes. Keep the receipt so a saved provider/root key (or a
2138    /// configured `api_key_env`) cannot silently follow an env-selected custom
2139    /// host, and so a cross-provider child cannot borrow an ambient generic
2140    /// host that was never addressed to it.
2141    #[serde(skip)]
2142    pub base_url_env_receipt: BaseUrlEnvReceipt,
2143
2144    /// What loading moved in memory from legacy top-level `base_url` /
2145    /// `api_key` keys (#6394). Reported by doctor; never rewrites the file.
2146    #[serde(skip)]
2147    pub legacy_root: codewhale_config::legacy_root::LegacyRootMigration,
2148
2149    /// Bound at parse time, never reconstructed from later diagnostic notes.
2150    #[serde(skip)]
2151    legacy_root_custom_generation: Option<codewhale_config::credentials::CredentialGeneration>,
2152
2153    /// Mini-window (pinned, always-on-top) mode layout preferences
2154    /// (`[mini_window]` in config.toml). When the host terminal window is
2155    /// pinned into its small always-on-top form, the TUI switches to a
2156    /// compact layout that keeps only the elements listed here.
2157    #[serde(default)]
2158    pub mini_window: Option<MiniWindowConfig>,
2159}
2160
2161/// Layout preferences for the pinned (always-on-top) mini-window mode.
2162///
2163/// When the host window is shrunk into its mini form (the right-click
2164/// "弹出置顶小窗" action), the TUI hides the shell chrome and keeps only the
2165/// message stream plus whatever the user opted to keep here.
2166#[derive(Debug, Clone, PartialEq, Deserialize)]
2167pub struct MiniWindowConfig {
2168    /// Keep the composer (message input box) visible in mini mode.
2169    /// Default: true — the mini window stays interactive.
2170    #[serde(default = "mini_default_keep_input")]
2171    pub keep_input: bool,
2172    /// Keep the Tasks + To-do strip visible in mini mode. Default: false.
2173    #[serde(default)]
2174    pub keep_todo: bool,
2175    /// Keep the side work rail (work surface side panel) visible in mini
2176    /// mode. Default: false.
2177    #[serde(default)]
2178    pub keep_sidebar: bool,
2179    /// Keep the bottom phase strip visible in mini mode. Default: false.
2180    #[serde(default)]
2181    pub keep_footer: bool,
2182    /// Keep the top status bar (route/mode/effort/permission header) visible
2183    /// in mini mode. Default: false.
2184    #[serde(default)]
2185    pub keep_header: bool,
2186}
2187
2188impl Default for MiniWindowConfig {
2189    fn default() -> Self {
2190        Self {
2191            keep_input: true,
2192            keep_todo: false,
2193            keep_sidebar: false,
2194            keep_footer: false,
2195            keep_header: false,
2196        }
2197    }
2198}
2199
2200fn mini_default_keep_input() -> bool {
2201    true
2202}
2203
2204/// What the environment layer decided about the generic
2205/// `CODEWHALE_BASE_URL` / `DEEPSEEK_BASE_URL` override.
2206///
2207/// The distinction that matters is between "no receipt" and "a receipt saying
2208/// nobody owns it". They are not the same state and must not collapse: a
2209/// missing receipt is a config that never passed through the environment
2210/// layer, while [`BaseUrlEnvReceipt::NoOwner`] is a positive statement that a
2211/// higher-precedence layer took the endpoint away from the environment.
2212#[derive(Debug, Clone, Default, PartialEq, Eq)]
2213pub enum BaseUrlEnvReceipt {
2214    /// The environment layer never ran for this config — directly constructed
2215    /// configs, embedded profiles, and unit-test fixtures. These keep the
2216    /// established global fallback: the generic override applies to whatever
2217    /// route is asked about.
2218    #[default]
2219    Unrecorded,
2220    /// The environment layer ran and no route owns the generic override —
2221    /// either it was absent, or a higher-precedence file layer (a managed
2222    /// overlay) supplied/reselected the effective route's endpoint. No route,
2223    /// active or pinned, may borrow the ambient generic host.
2224    NoOwner,
2225    /// The environment layer ran and addressed the override to exactly this
2226    /// `(provider, identity)`. Only that route resolves it; every other route
2227    /// falls through to its own default.
2228    Route(ProviderKind, String),
2229}
2230
2231impl BaseUrlEnvReceipt {
2232    /// Whether `(provider, identity)` is the route this receipt names.
2233    fn owns(&self, provider: ProviderKind, identity: &str) -> bool {
2234        match self {
2235            Self::Route(owner, owner_identity) => *owner == provider && owner_identity == identity,
2236            Self::Unrecorded | Self::NoOwner => false,
2237        }
2238    }
2239}
2240
2241#[derive(Debug, Clone, Default, Deserialize)]
2242pub struct AutoReviewConfig {
2243    #[serde(default)]
2244    pub disabled: bool,
2245    #[serde(default)]
2246    pub review_all_shell: bool,
2247    #[serde(default)]
2248    pub reviewer_model: Option<String>,
2249    #[serde(default)]
2250    pub allow: Vec<AutoReviewRuleConfig>,
2251    #[serde(default)]
2252    pub block: Vec<AutoReviewRuleConfig>,
2253    #[serde(default)]
2254    pub environment: Vec<String>,
2255}
2256
2257#[derive(Debug, Clone, Default, Deserialize)]
2258pub struct AutoReviewRuleConfig {
2259    pub id: Option<String>,
2260    #[serde(default, alias = "toolName", alias = "tool_name")]
2261    pub tool: Option<String>,
2262    #[serde(default, alias = "actionKind", alias = "action_kind")]
2263    pub action_kind: Option<String>,
2264    #[serde(default, alias = "textContains")]
2265    pub(crate) text_contains: Option<String>,
2266    pub reason: Option<String>,
2267}
2268
2269impl AutoReviewConfig {
2270    fn validate(&self) -> Result<()> {
2271        if let Some(reviewer_model) = self.reviewer_model.as_deref() {
2272            validate_auto_review_reviewer_model(reviewer_model)?;
2273        }
2274        validate_auto_review_rules("allow", &self.allow)?;
2275        validate_auto_review_rules("block", &self.block)?;
2276        validate_auto_review_environment(&self.environment)?;
2277        Ok(())
2278    }
2279}
2280
2281pub fn validate_auto_review_environment(entries: &[String]) -> Result<()> {
2282    for (index, entry) in entries.iter().enumerate() {
2283        let trimmed = entry.trim();
2284        if trimmed.is_empty() || entry.chars().any(char::is_control) {
2285            anyhow::bail!(
2286                "Invalid auto_review.environment[{index}]: expected a non-empty entry without control characters."
2287            );
2288        }
2289    }
2290    Ok(())
2291}
2292
2293pub fn validate_auto_review_reviewer_model(raw: &str) -> Result<()> {
2294    let trimmed = raw.trim();
2295    if trimmed.is_empty()
2296        || raw != trimmed
2297        || trimmed
2298            .chars()
2299            .any(|ch| ch.is_whitespace() || ch.is_control())
2300    {
2301        anyhow::bail!(
2302            "Invalid auto_review.reviewer_model: expected a non-empty model identifier without whitespace or control characters."
2303        );
2304    }
2305    Ok(())
2306}
2307
2308impl AutoReviewRuleConfig {
2309    fn has_matcher(&self) -> bool {
2310        self.tool
2311            .as_deref()
2312            .is_some_and(|value| !value.trim().is_empty())
2313            || self
2314                .action_kind
2315                .as_deref()
2316                .is_some_and(|value| !value.trim().is_empty())
2317    }
2318}
2319
2320fn validate_auto_review_rules(kind: &str, rules: &[AutoReviewRuleConfig]) -> Result<()> {
2321    for (index, rule) in rules.iter().enumerate() {
2322        if rule
2323            .text_contains
2324            .as_deref()
2325            .is_some_and(|value| !value.trim().is_empty())
2326        {
2327            anyhow::bail!(
2328                "Invalid auto_review.{kind}[{index}].text_contains: user-intent matching was retired; scope the rule with tool and/or action_kind."
2329            );
2330        }
2331        if !rule.has_matcher() {
2332            anyhow::bail!(
2333                "Invalid auto_review.{kind}[{index}]: set at least one of tool or action_kind."
2334            );
2335        }
2336        if let Some(action_kind) = rule.action_kind.as_deref() {
2337            let normalized = action_kind.trim().to_ascii_lowercase().replace('-', "_");
2338            if auto_review_action_kind_name(&normalized).is_none() {
2339                anyhow::bail!(
2340                    "Invalid auto_review.{kind}[{index}].action_kind '{action_kind}': expected read, write, shell, external, publish, or destructive."
2341                );
2342            }
2343            if kind == "allow"
2344                && !matches!(
2345                    normalized.as_str(),
2346                    "read" | "write" | "shell" | "external" | "publish" | "destructive"
2347                )
2348            {
2349                anyhow::bail!(
2350                    "Invalid auto_review.allow[{index}].action_kind '{action_kind}': this retired narrow kind cannot safely widen to a v0.9.8 decision class; replace it with an exact tool rule or a current action_kind."
2351                );
2352            }
2353        }
2354    }
2355    Ok(())
2356}
2357
2358/// Canonical action-kind name for an `auto_review` `action_kind` spelling,
2359/// including the retired narrow kinds that fold into a current class.
2360#[must_use]
2361pub fn auto_review_action_kind_name(raw: &str) -> Option<&'static str> {
2362    match raw.trim().to_ascii_lowercase().replace('-', "_").as_str() {
2363        "read" | "mcp_read" => Some("read"),
2364        "write" => Some("write"),
2365        "shell" => Some("shell"),
2366        "external" | "network" | "git" | "mcp_action" | "browser" | "unknown" => Some("external"),
2367        "publish" => Some("publish"),
2368        "destructive" | "secret" => Some("destructive"),
2369        _ => None,
2370    }
2371}
2372
2373/// How a user wants to disable a tool or supply a script / command tool.
2374/// Only `Disabled` may target a built-in; see `ToolsConfig::overrides`.
2375#[derive(Debug, Clone, Deserialize)]
2376#[serde(tag = "type", rename_all = "snake_case")]
2377pub enum ToolOverride {
2378    /// Run a local script file. The script receives the tool's JSON input
2379    /// on stdin and must return a JSON `ToolResult` on stdout.
2380    Script {
2381        /// Path to the script (absolute, or relative to `~/.codewhale/tools/`).
2382        path: String,
2383        /// Optional static arguments prepended before the tool's JSON input.
2384        #[serde(default)]
2385        args: Option<Vec<String>>,
2386    },
2387    /// Run an external command. The command receives the tool's JSON input
2388    /// on stdin and must return a JSON `ToolResult` on stdout.
2389    Command {
2390        /// The command to run (binary name or absolute path).
2391        command: String,
2392        /// Optional static arguments prepended before the tool's JSON input.
2393        #[serde(default)]
2394        args: Option<Vec<String>>,
2395    },
2396    /// Completely disable a tool, built-in or not. The tool will not appear in
2397    /// the model-visible catalog and cannot be called.
2398    Disabled,
2399}
2400
2401/// Vision model configuration for the `image_analyze` tool.
2402/// Uses an OpenAI-compatible vision model API.
2403#[derive(Debug, Clone, Deserialize)]
2404pub struct VisionModelConfig {
2405    #[serde(skip)]
2406    pub model_http_policy: Option<std::sync::Arc<dyn ModelHttpPolicy>>,
2407    /// Model identifier (e.g., "gemini-3.1-flash-lite-preview").
2408    pub model: String,
2409    /// API key for the vision model. Inherits from main config if not specified.
2410    #[serde(default)]
2411    pub api_key: Option<String>,
2412    /// Base URL for the vision model API. Defaults to OpenAI.
2413    #[serde(default)]
2414    pub base_url: Option<String>,
2415}
2416
2417/// `[runtime_api]` table — knobs for the local HTTP/SSE daemon.
2418#[derive(Debug, Clone, Deserialize, Default)]
2419pub struct RuntimeApiConfig {
2420    /// Additional CORS origins to allow on top of the built-in defaults
2421    /// (`http://localhost:{3000,1420}`, `http://127.0.0.1:{3000,1420}`). Useful when developing a UI against a non-default
2422    /// dev server port (e.g. Vite's default `:5173`).
2423    ///
2424    /// Resolution order (highest priority first): `--cors-origin` CLI flag,
2425    /// `DEEPSEEK_CORS_ORIGINS` env var (comma-separated), this field. Whalescale#255 / #561.
2426    #[serde(default)]
2427    pub cors_origins: Option<Vec<String>>,
2428}
2429
2430/// `[skills]` table — discovery, ambient index and installer configuration.
2431#[derive(Debug, Clone, Deserialize, Default)]
2432pub struct SkillsConfig {
2433    #[serde(default)]
2434    pub bundled: BundledSkillsConfig,
2435    #[serde(default)]
2436    pub listing_max_description_chars: Option<usize>,
2437    #[serde(default)]
2438    pub listing_budget_fraction: Option<f64>,
2439    /// Curated registry index. `/skill install <name>` looks up the spec here.
2440    /// Defaults to `codewhale_skill_install::install::DEFAULT_REGISTRY_URL`.
2441    #[serde(default)]
2442    pub registry_url: Option<String>,
2443    /// Per-skill maximum *uncompressed* size in bytes. Tarballs that exceed
2444    /// this limit are rejected during validation. Defaults to 5 MiB.
2445    #[serde(default)]
2446    pub max_install_size_bytes: Option<u64>,
2447    /// When true, skill discovery scans only Codewhale-owned skill roots
2448    /// (plus any explicit `skills_dir`) instead of importing compatible
2449    /// directories from other AI tools such as Claude, OpenCode, or Cursor.
2450    #[serde(default, alias = "scanCodewhaleOnly")]
2451    pub scan_codewhale_only: Option<bool>,
2452    /// Opt in to discovery from `<workspace>/skills` after workspace trust.
2453    /// Otherwise the flat root is visible only to compatible audit.
2454    #[serde(default)]
2455    pub flat_workspace_root: Option<bool>,
2456    #[serde(skip)]
2457    pub creator_skills: bool,
2458}
2459
2460#[derive(Debug, Clone, Copy, Deserialize, Default, PartialEq, Eq, Hash, Serialize)]
2461#[serde(rename_all = "lowercase")]
2462pub enum BundledSkillsInstall {
2463    #[default]
2464    Auto,
2465    All,
2466    None,
2467}
2468
2469#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq, Hash, Serialize)]
2470pub struct BundledSkillsConfig {
2471    pub install: Option<BundledSkillsInstall>,
2472    pub selected: Option<Vec<String>>,
2473    pub disabled: Option<Vec<String>>,
2474    pub explicit_only: Option<Vec<String>>,
2475}
2476
2477impl SkillsConfig {
2478    #[must_use]
2479    pub fn flat_workspace_root(&self) -> bool {
2480        self.flat_workspace_root.unwrap_or(false)
2481    }
2482
2483    /// Resolve whether session-time discovery should ignore cross-tool skill
2484    /// directories. Defaults to the compatibility-preserving broad scan.
2485    #[must_use]
2486    pub fn scan_codewhale_only(&self) -> bool {
2487        self.scan_codewhale_only.unwrap_or(false)
2488    }
2489}
2490
2491#[derive(Debug, Clone, Default, Deserialize, Serialize)]
2492pub struct ProviderConfig {
2493    /// OpenRouter upstream slug; disables upstream fallbacks when set.
2494    pub vendor: Option<String>,
2495    #[serde(alias = "apiKey")]
2496    pub api_key: Option<String>,
2497    #[serde(alias = "baseUrl")]
2498    pub base_url: Option<String>,
2499    pub model: Option<String>,
2500    #[serde(
2501        default,
2502        alias = "contextWindow",
2503        alias = "context_window_tokens",
2504        alias = "contextWindowTokens",
2505        alias = "context_length",
2506        alias = "contextLength"
2507    )]
2508    pub context_window: Option<u32>,
2509    /// Per-model context-window overrides keyed by exact wire model id
2510    /// (`[providers.<name>.model_context_windows]`, #6108). A matching entry
2511    /// wins over this provider's `context_window` for that model only, so one
2512    /// gateway can front models with heterogeneous windows.
2513    #[serde(default, alias = "modelContextWindows")]
2514    pub model_context_windows: Option<std::collections::BTreeMap<String, u32>>,
2515    pub mode: Option<String>,
2516    /// Dual-wire dialect toggle: `openai` (default) or `anthropic`.
2517    /// Not a separate catalog provider — config only (DeepSeek / MiniMax /
2518    /// Model Studio).
2519    #[serde(
2520        default,
2521        alias = "apiStyle",
2522        alias = "api_style",
2523        alias = "protocol",
2524        alias = "wire_format",
2525        alias = "wireFormat",
2526        alias = "dialect"
2527    )]
2528    pub wire: Option<String>,
2529    /// Responses dialect for a custom table whose `wire` is `responses`.
2530    #[serde(default, alias = "responsesProfile")]
2531    pub responses_profile: Option<String>,
2532    #[serde(alias = "authMode")]
2533    pub auth_mode: Option<String>,
2534    /// Core-owned public-client OAuth descriptor for a named plugin provider.
2535    #[serde(default)]
2536    pub oauth: Option<crate::oauth::PluginOAuthConfig>,
2537    /// Validated basename of the active Codewhale-owned xAI OAuth generation.
2538    /// The file always lives below Codewhale's private credentials directory.
2539    #[serde(default, alias = "oauthCredentialGeneration")]
2540    pub oauth_credential_generation: Option<String>,
2541    #[serde(alias = "insecureSkipTlsVerify")]
2542    pub insecure_skip_tls_verify: Option<bool>,
2543    /// Per-provider consent to a plain-HTTP `base_url` (#5991). Loopback is
2544    /// always allowed without it.
2545    #[serde(default, alias = "allowInsecureHttp")]
2546    pub allow_insecure_http: Option<bool>,
2547    #[serde(alias = "httpHeaders")]
2548    pub http_headers: Option<HashMap<String, String>>,
2549    #[serde(alias = "pathSuffix")]
2550    pub path_suffix: Option<String>,
2551    #[serde(alias = "reasoningStyle", alias = "reasoningStreamStyle")]
2552    pub reasoning_stream_style: Option<String>,
2553    #[serde(
2554        default,
2555        alias = "max-concurrency",
2556        alias = "maxConcurrency",
2557        alias = "concurrency"
2558    )]
2559    pub max_concurrency: Option<usize>,
2560    pub auth: Option<codewhale_config::ProviderAuthSourceToml>,
2561    /// Explicit, provider-scoped consent for one credential file owned by
2562    /// another CLI. Absence is the disabled default.
2563    #[serde(default, alias = "externalCredentials")]
2564    pub external_credentials: Option<codewhale_config::ExternalCredentialConsentToml>,
2565    /// Wire-protocol selector for a custom `[providers.<name>]` entry (#1519).
2566    ///
2567    /// Only `"openai-compatible"` is accepted for now; any other value is
2568    /// rejected at selection time so unsupported wire formats fail loudly rather
2569    /// than silently routing as OpenAI. Built-in providers leave this unset.
2570    #[serde(default)]
2571    pub kind: Option<String>,
2572    /// Runtime-only receipt; a config file cannot manufacture plugin authority.
2573    #[serde(skip)]
2574    pub plugin_authority: Option<codewhale_config::PluginAuthority>,
2575    /// Name of the environment variable holding this custom provider's API key
2576    /// (#1519), e.g. `api_key_env = "EXAMPLE_API_KEY"`. The key value itself is
2577    /// never stored in config; only the env var name is.
2578    #[serde(default, alias = "apiKeyEnv")]
2579    pub api_key_env: Option<String>,
2580}
2581
2582impl ProviderConfig {
2583    /// True when this entry selects the OpenAI-compatible custom wire protocol.
2584    ///
2585    /// `kind` is matched case-insensitively against `openai-compatible` (and the
2586    /// `openai_compatible` underscore spelling). Returns `false` when `kind` is
2587    /// unset (built-in providers) or names any other value.
2588    #[must_use]
2589    pub fn is_openai_compatible_custom(&self) -> bool {
2590        self.kind.as_deref().is_some_and(|kind| {
2591            let normalized = kind.trim().to_ascii_lowercase().replace('_', "-");
2592            normalized == "openai-compatible"
2593        })
2594    }
2595}
2596
2597#[derive(Debug, Clone, Default, Deserialize)]
2598pub struct ProvidersConfig {
2599    #[serde(default)]
2600    pub deepseek: ProviderConfig,
2601    #[serde(default, alias = "deepseekCn")]
2602    pub deepseek_cn: ProviderConfig,
2603    #[serde(
2604        default,
2605        alias = "deepseek-anthropic",
2606        alias = "deepseekAnthropic",
2607        alias = "deepseek-claude",
2608        alias = "deepseek_claude"
2609    )]
2610    pub deepseek_anthropic: ProviderConfig,
2611    #[serde(default, alias = "nvidiaNim")]
2612    pub nvidia_nim: ProviderConfig,
2613    #[serde(default)]
2614    pub openai: ProviderConfig,
2615    #[serde(default)]
2616    pub atlascloud: ProviderConfig,
2617    #[serde(default, alias = "wanjieArk")]
2618    pub wanjie_ark: ProviderConfig,
2619    #[serde(default)]
2620    pub volcengine: ProviderConfig,
2621    #[serde(default)]
2622    pub openrouter: ProviderConfig,
2623    #[serde(default, alias = "orca_router", alias = "orca")]
2624    pub orcarouter: ProviderConfig,
2625    #[serde(
2626        default,
2627        alias = "xiaomi",
2628        alias = "mimo",
2629        alias = "xiaomimimo",
2630        alias = "xiaomiMimo"
2631    )]
2632    pub xiaomi_mimo: ProviderConfig,
2633    #[serde(default)]
2634    pub novita: ProviderConfig,
2635    #[serde(default)]
2636    pub fireworks: ProviderConfig,
2637    #[serde(default)]
2638    pub siliconflow: ProviderConfig,
2639    #[serde(
2640        default,
2641        alias = "siliconflow-CN",
2642        alias = "siliconflow-cn",
2643        alias = "siliconflowCn"
2644    )]
2645    pub siliconflow_cn: ProviderConfig,
2646    #[serde(default)]
2647    pub arcee: ProviderConfig,
2648    #[serde(default)]
2649    pub moonshot: ProviderConfig,
2650    #[serde(default)]
2651    pub sglang: ProviderConfig,
2652    #[serde(default)]
2653    pub vllm: ProviderConfig,
2654    #[serde(default)]
2655    pub ollama: ProviderConfig,
2656    #[serde(default, alias = "ollama-cloud", alias = "ollamaCloud")]
2657    pub ollama_cloud: ProviderConfig,
2658    #[serde(default, alias = "hugging-face", alias = "hf")]
2659    pub huggingface: ProviderConfig,
2660    #[serde(default, alias = "model-scope", alias = "model_scope")]
2661    pub modelscope: ProviderConfig,
2662    #[serde(default, alias = "deep-infra", alias = "deep_infra")]
2663    pub deepinfra: ProviderConfig,
2664    #[serde(default, alias = "together-ai")]
2665    pub together: ProviderConfig,
2666    #[serde(
2667        default,
2668        alias = "baidu-qianfan",
2669        alias = "baidu_qianfan",
2670        alias = "baidu"
2671    )]
2672    pub qianfan: ProviderConfig,
2673    #[serde(
2674        default,
2675        alias = "openai-codex",
2676        alias = "openaiCodex",
2677        alias = "codex",
2678        alias = "chatgpt"
2679    )]
2680    pub openai_codex: ProviderConfig,
2681    #[serde(default, alias = "claude")]
2682    pub anthropic: ProviderConfig,
2683    #[serde(default, alias = "open-model", alias = "open_model")]
2684    pub openmodel: ProviderConfig,
2685    #[serde(
2686        default,
2687        alias = "zhipu",
2688        alias = "zhipuai",
2689        alias = "bigmodel",
2690        alias = "big-model"
2691    )]
2692    pub zai: ProviderConfig,
2693    #[serde(default)]
2694    pub stepfun: ProviderConfig,
2695    #[serde(default)]
2696    pub minimax: ProviderConfig,
2697    #[serde(
2698        default,
2699        alias = "minimax-anthropic",
2700        alias = "minimaxAnthropic",
2701        alias = "mini-max-anthropic",
2702        alias = "mini_max_anthropic"
2703    )]
2704    pub minimax_anthropic: ProviderConfig,
2705    #[serde(default, alias = "sakana-ai", alias = "sakana_ai", alias = "fugu")]
2706    pub sakana: ProviderConfig,
2707    #[serde(
2708        default,
2709        alias = "long-cat",
2710        alias = "meituan-longcat",
2711        alias = "meituan"
2712    )]
2713    pub longcat: ProviderConfig,
2714    #[serde(default, alias = "opencode-go", alias = "opencodego")]
2715    pub opencode_go: ProviderConfig,
2716    #[serde(
2717        default,
2718        alias = "opencode-zen",
2719        alias = "opencodezen",
2720        alias = "zen",
2721        alias = "opencode"
2722    )]
2723    pub opencode_zen: ProviderConfig,
2724    #[serde(
2725        default,
2726        alias = "meta-ai",
2727        alias = "meta_ai",
2728        alias = "meta-model-api",
2729        alias = "meta_model_api",
2730        alias = "muse",
2731        alias = "muse-spark"
2732    )]
2733    pub meta: ProviderConfig,
2734    #[serde(default, alias = "x-ai", alias = "x_ai", alias = "grok")]
2735    pub xai: ProviderConfig,
2736    #[serde(
2737        default,
2738        alias = "mistral-ai",
2739        alias = "mistral_ai",
2740        alias = "mistralai",
2741        alias = "la-plateforme",
2742        alias = "la_plateforme"
2743    )]
2744    pub mistral: ProviderConfig,
2745    #[serde(
2746        default,
2747        alias = "google-gemini",
2748        alias = "google_gemini",
2749        alias = "gemini"
2750    )]
2751    pub google: ProviderConfig,
2752    #[serde(default, alias = "agy")]
2753    pub antigravity: ProviderConfig,
2754    #[serde(
2755        default,
2756        alias = "telecom-js",
2757        alias = "telecom_js",
2758        alias = "telecomjs-cn",
2759        alias = "tokenhub"
2760    )]
2761    pub telecomjs: ProviderConfig,
2762    /// Eden AI — OpenAI-compatible AI gateway (aggregator).
2763    #[serde(default, alias = "eden-ai", alias = "eden_ai")]
2764    pub edenai: ProviderConfig,
2765    /// ZenMux — OpenAI-compatible AI gateway (aggregator).
2766    #[serde(default, alias = "zen-mux", alias = "zen_mux")]
2767    pub zenmux: ProviderConfig,
2768    /// CSDN 星图 — OpenAI-compatible hosted platform and Coding Plan.
2769    #[serde(
2770        default,
2771        alias = "csdn-ai",
2772        alias = "csdn_ai",
2773        alias = "csdn-coding-plan",
2774        alias = "csdn_coding_plan",
2775        alias = "starmap"
2776    )]
2777    pub csdn: ProviderConfig,
2778    /// Concentrate — OpenAI Responses-compatible AI gateway (aggregator).
2779    #[serde(
2780        default,
2781        alias = "concentrate-ai",
2782        alias = "concentrate_ai",
2783        alias = "concentrateai"
2784    )]
2785    pub concentrate: ProviderConfig,
2786    /// Codewhale API — account-backed model access over connected provider keys.
2787    #[serde(
2788        default,
2789        alias = "codewhale-api",
2790        alias = "codewhale_api",
2791        alias = "cw-api",
2792        alias = "codewhale-cloud"
2793    )]
2794    pub codewhale: ProviderConfig,
2795    /// Alibaba Cloud Model Studio — Token Plan (OpenAI-compatible Chat Completions).
2796    #[serde(default, alias = "modelstudio-token-plan")]
2797    pub modelstudio_token_plan: ProviderConfig,
2798    /// Alibaba Cloud Model Studio — Token Plan Anthropic-compatible endpoint.
2799    #[serde(default, alias = "modelstudio-token-plan-anthropic")]
2800    pub modelstudio_token_plan_anthropic: ProviderConfig,
2801    /// Alibaba Cloud Model Studio — Coding Plan (OpenAI-compatible Chat Completions).
2802    #[serde(default, alias = "modelstudio-coding-plan")]
2803    pub modelstudio_coding_plan: ProviderConfig,
2804    /// Alibaba Cloud Model Studio — Coding Plan Anthropic-compatible endpoint.
2805    #[serde(default, alias = "modelstudio-coding-plan-anthropic")]
2806    pub modelstudio_coding_plan_anthropic: ProviderConfig,
2807    /// Arbitrary user-named custom providers (#1519).
2808    ///
2809    /// Captures every `[providers.<name>]` table whose key is not one of the
2810    /// built-in providers above. Each entry is an OpenAI-compatible custom
2811    /// endpoint selected via `provider = "<name>"`; routing reads its
2812    /// `base_url` / `model` / `api_key_env` through [`ProviderKind::Custom`].
2813    #[serde(flatten, default)]
2814    pub custom: HashMap<String, ProviderConfig>,
2815}
2816
2817impl ProvidersConfig {
2818    /// Look up a user-defined custom provider table by its `[providers.<name>]`
2819    /// key (#1519). Returns `None` when no entry with that exact name exists.
2820    #[must_use]
2821    pub fn custom_provider_config(&self, name: &str) -> Option<&ProviderConfig> {
2822        self.custom.get(name)
2823    }
2824
2825    fn validate(&self) -> Result<()> {
2826        let builtins = [
2827            ("providers.deepseek", &self.deepseek),
2828            ("providers.deepseek_cn", &self.deepseek_cn),
2829            ("providers.deepseek_anthropic", &self.deepseek_anthropic),
2830            ("providers.nvidia_nim", &self.nvidia_nim),
2831            ("providers.openai", &self.openai),
2832            ("providers.atlascloud", &self.atlascloud),
2833            ("providers.wanjie_ark", &self.wanjie_ark),
2834            ("providers.volcengine", &self.volcengine),
2835            ("providers.openrouter", &self.openrouter),
2836            ("providers.xiaomi_mimo", &self.xiaomi_mimo),
2837            ("providers.novita", &self.novita),
2838            ("providers.fireworks", &self.fireworks),
2839            ("providers.siliconflow", &self.siliconflow),
2840            ("providers.siliconflow_cn", &self.siliconflow_cn),
2841            ("providers.arcee", &self.arcee),
2842            ("providers.moonshot", &self.moonshot),
2843            ("providers.sglang", &self.sglang),
2844            ("providers.vllm", &self.vllm),
2845            ("providers.ollama", &self.ollama),
2846            ("providers.ollama_cloud", &self.ollama_cloud),
2847            ("providers.huggingface", &self.huggingface),
2848            ("providers.deepinfra", &self.deepinfra),
2849            ("providers.together", &self.together),
2850            ("providers.qianfan", &self.qianfan),
2851            ("providers.openai_codex", &self.openai_codex),
2852            ("providers.anthropic", &self.anthropic),
2853            ("providers.openmodel", &self.openmodel),
2854            ("providers.zai", &self.zai),
2855            ("providers.stepfun", &self.stepfun),
2856            ("providers.minimax", &self.minimax),
2857            ("providers.minimax_anthropic", &self.minimax_anthropic),
2858            ("providers.sakana", &self.sakana),
2859            ("providers.opencode_go", &self.opencode_go),
2860            ("providers.opencode_zen", &self.opencode_zen),
2861            ("providers.meta", &self.meta),
2862            ("providers.xai", &self.xai),
2863        ];
2864        for (name, config) in builtins {
2865            validate_provider_context_window(name, config.context_window)?;
2866            validate_model_context_windows(name, config.model_context_windows.as_ref())?;
2867        }
2868        for (name, config) in &self.custom {
2869            let name = format!("providers.{name}");
2870            validate_provider_context_window(&name, config.context_window)?;
2871            validate_model_context_windows(&name, config.model_context_windows.as_ref())?;
2872        }
2873        Ok(())
2874    }
2875}
2876
2877fn validate_provider_context_window(name: &str, value: Option<u32>) -> Result<()> {
2878    if value == Some(0) {
2879        anyhow::bail!("{name}.context_window must be greater than 0");
2880    }
2881    Ok(())
2882}
2883
2884fn validate_model_context_windows(
2885    name: &str,
2886    table: Option<&std::collections::BTreeMap<String, u32>>,
2887) -> Result<()> {
2888    if let Some(table) = table {
2889        for (model, window) in table {
2890            if *window == 0 {
2891                anyhow::bail!("{name}.model_context_windows.{model} must be greater than 0");
2892            }
2893        }
2894    }
2895    Ok(())
2896}
2897
2898#[derive(Debug, Clone, Deserialize, Default)]
2899struct ConfigFile {
2900    /// Boxed so the parsed document never carries the multi-kilobyte
2901    /// `Config` by value through `toml::de` and `apply_profile` frames. A
2902    /// `#[tokio::test]` runs those frames on libtest's default 2 MiB stack,
2903    /// which the by-value copies overflowed (#6362).
2904    #[serde(flatten)]
2905    base: Box<Config>,
2906    profiles: Option<HashMap<String, Config>>,
2907    #[serde(skip)]
2908    legacy_root: codewhale_config::legacy_root::LegacyRootMigration,
2909}
2910
2911#[derive(Debug, Clone, Deserialize, Default)]
2912struct RequirementsFile {
2913    #[serde(default)]
2914    allowed_approval_policies: Vec<String>,
2915    #[serde(default)]
2916    allowed_sandbox_modes: Vec<String>,
2917}
2918
2919/// The highest-precedence source that can currently own approval policy.
2920///
2921/// The resolved [`Config`] historically retained only the final string, which
2922/// made an in-session editor unable to distinguish a user-owned root key from
2923/// a profile, environment, managed, requirements, or project constraint. The
2924/// destructive Full Access preset uses this classification to fail closed
2925/// unless it can prove that removing the root key is the operation requested.
2926#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2927pub enum ApprovalPolicyControl {
2928    Unset,
2929    RootConfig,
2930    Profile,
2931    Environment,
2932    ManagedConfig,
2933    ProjectConfig,
2934    Requirements,
2935    Ambiguous,
2936}
2937
2938impl ApprovalPolicyControl {
2939    #[must_use]
2940    pub fn editable_root(self) -> bool {
2941        matches!(self, Self::Unset | Self::RootConfig)
2942    }
2943
2944    #[must_use]
2945    pub fn label(self) -> &'static str {
2946        match self {
2947            Self::Unset => "saved TUI posture",
2948            Self::RootConfig => "the root config.toml approval_policy",
2949            Self::Profile => "the active config profile",
2950            Self::Environment => {
2951                set_env_var_name(APPROVAL_POLICY_ENV).unwrap_or(APPROVAL_POLICY_ENV[0])
2952            }
2953            Self::ManagedConfig => "managed configuration",
2954            Self::ProjectConfig => "project configuration",
2955            Self::Requirements => "managed approval requirements",
2956            Self::Ambiguous => "an unresolved configuration source",
2957        }
2958    }
2959}
2960
2961/// Highest-precedence source that owns the interactive shell availability
2962/// switch. Project/profile/environment/managed constraints are intentionally
2963/// read-only from the root settings editor.
2964#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2965pub enum ShellAccessControl {
2966    Unset,
2967    RootConfig,
2968    Profile,
2969    Environment,
2970    ManagedConfig,
2971    ProjectConfig,
2972    Ambiguous,
2973}
2974
2975impl ShellAccessControl {
2976    #[must_use]
2977    pub fn editable_root(self) -> bool {
2978        matches!(self, Self::Unset | Self::RootConfig)
2979    }
2980
2981    #[must_use]
2982    pub fn label(self) -> &'static str {
2983        match self {
2984            Self::Unset => "the session default",
2985            Self::RootConfig => "the root config.toml allow_shell",
2986            Self::Profile => "the active config profile",
2987            Self::Environment => set_env_var_name(ALLOW_SHELL_ENV).unwrap_or(ALLOW_SHELL_ENV[0]),
2988            Self::ManagedConfig => "managed configuration",
2989            Self::ProjectConfig => "project configuration",
2990            Self::Ambiguous => "an unresolved configuration source",
2991        }
2992    }
2993}
2994
2995const APPROVAL_POLICY_ENV: [&str; 2] = ["CODEWHALE_APPROVAL_POLICY", "DEEPSEEK_APPROVAL_POLICY"];
2996const ALLOW_SHELL_ENV: [&str; 2] = ["CODEWHALE_ALLOW_SHELL", "DEEPSEEK_ALLOW_SHELL"];
2997
2998/// The variable of a `[CODEWHALE_*, legacy DEEPSEEK_*]` pair that is set,
2999/// in the precedence the config readers use (the `CODEWHALE_*` name wins).
3000/// The dispatcher only exports `CODEWHALE_*` (#6516), so a `DEEPSEEK_*` hit
3001/// means the user set the legacy name themselves; naming it keeps the
3002/// settings editor pointing at the variable that actually owns the value.
3003fn set_env_var_name(names: [&'static str; 2]) -> Option<&'static str> {
3004    let read = || {
3005        names
3006            .into_iter()
3007            .find(|name| std::env::var_os(name).is_some())
3008    };
3009    #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
3010    {
3011        crate::test_support::with_test_env_lock(read)
3012    }
3013    #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
3014    {
3015        read()
3016    }
3017}
3018
3019fn approval_policy_env_is_set() -> bool {
3020    set_env_var_name(APPROVAL_POLICY_ENV).is_some()
3021}
3022
3023fn allow_shell_env_is_set() -> bool {
3024    set_env_var_name(ALLOW_SHELL_ENV).is_some()
3025}
3026
3027fn project_config_root_bool(workspace: &Path, key: &str) -> Option<bool> {
3028    [
3029        workspace
3030            .join(codewhale_config::CODEWHALE_APP_DIR)
3031            .join("config.toml"),
3032        workspace
3033            .join(codewhale_config::LEGACY_APP_DIR)
3034            .join("config.toml"),
3035    ]
3036    .into_iter()
3037    .find(|path| path.exists())
3038    .and_then(|path| std::fs::read_to_string(path).ok())
3039    .and_then(|raw| toml::from_str::<toml::Value>(&raw).ok())
3040    .and_then(|document| document.get(key).and_then(toml::Value::as_bool))
3041}
3042
3043/// Map the saved TUI permission posture onto the approval-policy ordering used
3044/// by project config. Full Access is looser than every project policy, so its
3045/// baseline is the loosest ranked policy (`auto`).
3046#[must_use]
3047pub fn approval_policy_baseline_from_permission_posture(
3048    posture: Option<&str>,
3049) -> Option<&'static str> {
3050    posture.and_then(
3051        |posture| match posture.trim().to_ascii_lowercase().as_str() {
3052            "ask" | "suggest" | "on-request" | "untrusted" => Some("on-request"),
3053            "accept-edits" | "accept_edits" | "acceptedits" | "edits" => Some("accept-edits"),
3054            "auto" | "auto-review" | "auto_review" => Some("auto"),
3055            "full" | "full-access" | "full_access" | "bypass" => Some("auto"),
3056            _ => None,
3057        },
3058    )
3059}
3060
3061// === Config Loading ===
3062
3063impl Config {
3064    /// Whether Linux shell commands prefer bubblewrap confinement.
3065    ///
3066    /// On by default: an unset `prefer_bwrap` means sandboxed commands use
3067    /// the OS wrapper whenever `/usr/bin/bwrap` works on this host, matching
3068    /// the Seatbelt behavior macOS already has. An explicit `false` opts out
3069    /// and leaves Linux commands unwrapped.
3070    #[must_use]
3071    pub fn prefers_bwrap(&self) -> bool {
3072        self.prefer_bwrap.unwrap_or(true)
3073    }
3074
3075    #[must_use]
3076    pub fn stop_words(&self) -> Vec<String> {
3077        self.stop_words.clone().unwrap_or_else(default_stop_words)
3078    }
3079
3080    /// Structural external-credential status for user-facing inventory. This
3081    /// resolves only environment/config strings and performs no filesystem or
3082    /// network access.
3083    pub fn external_credential_consent_status(
3084        &self,
3085        identity: &ProviderIdentity,
3086    ) -> Option<codewhale_config::ExternalCredentialConsentStatus> {
3087        if identity.key.as_str() == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id {
3088            return None;
3089        }
3090        let provider = identity.provider;
3091        let (kind, source, path) = match provider {
3092            ProviderKind::OpenaiCodex => (
3093                codewhale_config::ProviderKind::OpenaiCodex,
3094                codewhale_config::ExternalCredentialSource::CodexCli,
3095                crate::oauth::auth_file_path(),
3096            ),
3097            ProviderKind::Xai => (
3098                codewhale_config::ProviderKind::Xai,
3099                codewhale_config::ExternalCredentialSource::GrokCli,
3100                crate::oauth::grok_auth_file_path(),
3101            ),
3102            ProviderKind::Deepseek => (
3103                codewhale_config::ProviderKind::Deepseek,
3104                codewhale_config::ExternalCredentialSource::DshCli,
3105                codewhale_config::default_dsh_credentials_path(),
3106            ),
3107            ProviderKind::DeepseekAnthropic => (
3108                codewhale_config::ProviderKind::DeepseekAnthropic,
3109                codewhale_config::ExternalCredentialSource::DshCli,
3110                codewhale_config::default_dsh_credentials_path(),
3111            ),
3112            _ => return None,
3113        };
3114        self.verify_provider_identity(identity).ok()?;
3115        let active = self.active_provider_identity().ok()?;
3116        let consent = self
3117            .provider_config_for(identity)
3118            .and_then(|entry| entry.external_credentials.as_ref());
3119        let mut status = codewhale_config::external_credential_consent_status(
3120            consent,
3121            kind,
3122            source,
3123            &path,
3124            active.provider,
3125        );
3126        if active != *identity {
3127            status.route_state = "dormant";
3128        }
3129        Some(status)
3130    }
3131
3132    /// Return the non-root source that prevents an interactive runtime preset
3133    /// from safely rewriting approval, shell, and sandbox posture. Presets may
3134    /// edit user-owned root keys, but must never overwrite a profile, env,
3135    /// managed, requirements, or project constraint in the live merged Config.
3136    #[must_use]
3137    pub fn runtime_preset_blocker(
3138        &self,
3139        config_path: Option<&Path>,
3140        profile: Option<&str>,
3141        workspace: &Path,
3142    ) -> Option<&'static str> {
3143        let requirements_path = self
3144            .requirements_path
3145            .as_deref()
3146            .map(expand_path)
3147            .or_else(default_requirements_path);
3148        if let Some(path) = requirements_path
3149            && path.exists()
3150        {
3151            let controlled = std::fs::read_to_string(path)
3152                .ok()
3153                .and_then(|raw| toml::from_str::<RequirementsFile>(&raw).ok())
3154                .is_none_or(|requirements| {
3155                    !requirements.allowed_approval_policies.is_empty()
3156                        || !requirements.allowed_sandbox_modes.is_empty()
3157                });
3158            if controlled {
3159                return Some("managed runtime requirements");
3160            }
3161        }
3162
3163        let workspace_is_home = codewhale_paths::user_home().is_some_and(|home| {
3164            let workspace = workspace
3165                .canonicalize()
3166                .unwrap_or_else(|_| workspace.to_path_buf());
3167            let home = home.canonicalize().unwrap_or(home);
3168            workspace == home
3169        });
3170        let project_controls_runtime = || {
3171            let saved_approval_baseline = crate::settings::Settings::load_persisted()
3172                .ok()
3173                .and_then(|settings| settings.permission_posture)
3174                .and_then(|posture| {
3175                    approval_policy_baseline_from_permission_posture(Some(&posture))
3176                });
3177            let approval_baseline = self.approval_policy.as_deref().or(saved_approval_baseline);
3178            let parsed_controls =
3179                codewhale_config::load_project_config(workspace).is_some_and(|project| {
3180                    project.approval_policy.as_deref().is_some_and(|policy| {
3181                        codewhale_config::project_approval_policy_is_allowed(
3182                            approval_baseline,
3183                            policy,
3184                        )
3185                    }) || project.sandbox_mode.as_deref().is_some_and(|sandbox| {
3186                        codewhale_config::project_sandbox_mode_is_allowed(
3187                            self.sandbox_mode.as_deref(),
3188                            sandbox,
3189                        )
3190                    })
3191                });
3192            parsed_controls || project_config_root_bool(workspace, "allow_shell") == Some(false)
3193        };
3194        if !workspace_is_home && project_controls_runtime() {
3195            return Some("project runtime configuration");
3196        }
3197
3198        match managed_config_file(self.managed_config_path.as_deref()) {
3199            Err(_) => return Some("an unreadable managed runtime configuration"),
3200            Ok(None) => {}
3201            Ok(Some(path)) => match load_single_config_file(&path) {
3202                Ok(managed)
3203                    if managed.approval_policy.is_some()
3204                        || managed.sandbox_mode.is_some()
3205                        || managed.allow_shell.is_some() =>
3206                {
3207                    return Some("managed runtime configuration");
3208                }
3209                Err(_) => return Some("an unreadable managed runtime configuration"),
3210                Ok(_) => {}
3211            },
3212        }
3213
3214        let env_controls_runtime = || {
3215            approval_policy_env_is_set()
3216                || allow_shell_env_is_set()
3217                || std::env::var_os("CODEWHALE_SANDBOX_MODE").is_some()
3218                || std::env::var_os("DEEPSEEK_SANDBOX_MODE").is_some()
3219        };
3220        #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
3221        let env_controls_runtime = crate::test_support::with_test_env_lock(env_controls_runtime);
3222        #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
3223        let env_controls_runtime = env_controls_runtime();
3224        if env_controls_runtime {
3225            return Some("environment-controlled runtime posture");
3226        }
3227
3228        if let Some(profile) = profile {
3229            let path = match resolve_load_config_path(config_path.map(Path::to_path_buf)) {
3230                Ok(Some(path)) => path,
3231                Ok(None) => return Some("an unresolved active config profile"),
3232                Err(_) => return Some("an invalid active config path override"),
3233            };
3234            let Some(parsed) = std::fs::read_to_string(path)
3235                .ok()
3236                .and_then(|raw| parse_config_file(&raw).ok())
3237            else {
3238                return Some("an unreadable active config profile");
3239            };
3240            if parsed
3241                .profiles
3242                .as_ref()
3243                .and_then(|profiles| profiles.get(profile))
3244                .is_some_and(|profile| {
3245                    profile.approval_policy.is_some()
3246                        || profile.sandbox_mode.is_some()
3247                        || profile.allow_shell.is_some()
3248                })
3249            {
3250                return Some("the active config profile");
3251            }
3252        }
3253
3254        None
3255    }
3256
3257    /// Identify whether the effective approval policy can safely be edited by
3258    /// changing the root user config. Sources applied later in the load chain
3259    /// are deliberately treated as controlling even when their value happens
3260    /// to equal the root value; equality is not provenance.
3261    #[must_use]
3262    pub fn approval_policy_control(
3263        &self,
3264        config_path: Option<&Path>,
3265        profile: Option<&str>,
3266        workspace: &Path,
3267    ) -> ApprovalPolicyControl {
3268        if self.approval_policy_is_requirements_managed() {
3269            return ApprovalPolicyControl::Requirements;
3270        }
3271
3272        let workspace_is_home = codewhale_paths::user_home().is_some_and(|home| {
3273            let workspace = workspace
3274                .canonicalize()
3275                .unwrap_or_else(|_| workspace.to_path_buf());
3276            let home = home.canonicalize().unwrap_or(home);
3277            workspace == home
3278        });
3279        if !workspace_is_home {
3280            let saved_approval_baseline = crate::settings::Settings::load_persisted()
3281                .ok()
3282                .and_then(|settings| settings.permission_posture)
3283                .and_then(|posture| {
3284                    approval_policy_baseline_from_permission_posture(Some(&posture))
3285                });
3286            let approval_baseline = self.approval_policy.as_deref().or(saved_approval_baseline);
3287            if codewhale_config::load_project_config(workspace)
3288                .and_then(|project| project.approval_policy)
3289                .is_some_and(|policy| {
3290                    codewhale_config::project_approval_policy_is_allowed(approval_baseline, &policy)
3291                })
3292            {
3293                return ApprovalPolicyControl::ProjectConfig;
3294            }
3295        }
3296
3297        match managed_config_file(self.managed_config_path.as_deref()) {
3298            Err(_) => return ApprovalPolicyControl::Ambiguous,
3299            Ok(None) => {}
3300            Ok(Some(path)) => match load_single_config_file(&path) {
3301                Ok(managed) if managed.approval_policy.is_some() => {
3302                    return ApprovalPolicyControl::ManagedConfig;
3303                }
3304                Err(_) => return ApprovalPolicyControl::Ambiguous,
3305                Ok(_) => {}
3306            },
3307        }
3308
3309        if approval_policy_env_is_set() {
3310            return ApprovalPolicyControl::Environment;
3311        }
3312
3313        let path = match resolve_load_config_path(config_path.map(Path::to_path_buf)) {
3314            Ok(Some(path)) => path,
3315            Ok(None) | Err(_) => {
3316                return if self.approval_policy.is_some() {
3317                    ApprovalPolicyControl::Ambiguous
3318                } else {
3319                    ApprovalPolicyControl::Unset
3320                };
3321            }
3322        };
3323        let parsed = std::fs::read_to_string(path)
3324            .ok()
3325            .and_then(|raw| parse_config_file(&raw).ok());
3326        let Some(parsed) = parsed else {
3327            return if self.approval_policy.is_some() {
3328                ApprovalPolicyControl::Ambiguous
3329            } else {
3330                ApprovalPolicyControl::Unset
3331            };
3332        };
3333        if let Some(profile) = profile
3334            && parsed
3335                .profiles
3336                .as_ref()
3337                .and_then(|profiles| profiles.get(profile))
3338                .is_some_and(|profile| profile.approval_policy.is_some())
3339        {
3340            return ApprovalPolicyControl::Profile;
3341        }
3342        if parsed.base.approval_policy.is_some() {
3343            ApprovalPolicyControl::RootConfig
3344        } else if self.approval_policy.is_some() {
3345            ApprovalPolicyControl::Ambiguous
3346        } else {
3347            ApprovalPolicyControl::Unset
3348        }
3349    }
3350
3351    /// Identify whether shell availability can safely be edited through the
3352    /// user-owned root config. Later sources are controlling even when their
3353    /// effective value happens to match the root value.
3354    #[must_use]
3355    pub fn allow_shell_control(
3356        &self,
3357        config_path: Option<&Path>,
3358        profile: Option<&str>,
3359        workspace: &Path,
3360    ) -> ShellAccessControl {
3361        let workspace_is_home = codewhale_paths::user_home().is_some_and(|home| {
3362            let workspace = workspace
3363                .canonicalize()
3364                .unwrap_or_else(|_| workspace.to_path_buf());
3365            let home = home.canonicalize().unwrap_or(home);
3366            workspace == home
3367        });
3368        if !workspace_is_home && project_config_root_bool(workspace, "allow_shell") == Some(false) {
3369            return ShellAccessControl::ProjectConfig;
3370        }
3371
3372        match managed_config_file(self.managed_config_path.as_deref()) {
3373            Err(_) => return ShellAccessControl::Ambiguous,
3374            Ok(None) => {}
3375            Ok(Some(path)) => match load_single_config_file(&path) {
3376                Ok(managed) if managed.allow_shell.is_some() => {
3377                    return ShellAccessControl::ManagedConfig;
3378                }
3379                Err(_) => return ShellAccessControl::Ambiguous,
3380                Ok(_) => {}
3381            },
3382        }
3383
3384        if allow_shell_env_is_set() {
3385            return ShellAccessControl::Environment;
3386        }
3387
3388        let path = match resolve_load_config_path(config_path.map(Path::to_path_buf)) {
3389            Ok(Some(path)) => path,
3390            Ok(None) | Err(_) => {
3391                return if self.allow_shell.is_some() {
3392                    ShellAccessControl::Ambiguous
3393                } else {
3394                    ShellAccessControl::Unset
3395                };
3396            }
3397        };
3398        let parsed = std::fs::read_to_string(path)
3399            .ok()
3400            .and_then(|raw| parse_config_file(&raw).ok());
3401        let Some(parsed) = parsed else {
3402            return if self.allow_shell.is_some() {
3403                ShellAccessControl::Ambiguous
3404            } else {
3405                ShellAccessControl::Unset
3406            };
3407        };
3408        if let Some(profile) = profile
3409            && parsed
3410                .profiles
3411                .as_ref()
3412                .and_then(|profiles| profiles.get(profile))
3413                .is_some_and(|profile| profile.allow_shell.is_some())
3414        {
3415            return ShellAccessControl::Profile;
3416        }
3417        if parsed.base.allow_shell.is_some() {
3418            ShellAccessControl::RootConfig
3419        } else if self.allow_shell.is_some() {
3420            ShellAccessControl::Ambiguous
3421        } else {
3422            ShellAccessControl::Unset
3423        }
3424    }
3425
3426    /// Whether organization requirements, rather than a user-editable config
3427    /// key, own approval posture. User config still outranks TUI settings, but
3428    /// `/config approval_mode ... --save` may edit that user-owned key.
3429    /// Sandbox requirements also lock posture: Full Access changes the implicit
3430    /// sandbox. This conservatively locks even posture changes that would fit.
3431    #[must_use]
3432    pub fn approval_policy_is_requirements_managed(&self) -> bool {
3433        let path = self
3434            .requirements_path
3435            .as_deref()
3436            .map(expand_path)
3437            .or_else(default_requirements_path);
3438        let Some(path) = path else {
3439            return false;
3440        };
3441        if !path.exists() {
3442            return false;
3443        }
3444        // Fail closed if a present requirements file becomes unreadable or
3445        // malformed between Config::load and App::new.
3446        std::fs::read_to_string(path)
3447            .ok()
3448            .and_then(|contents| toml::from_str::<RequirementsFile>(&contents).ok())
3449            .is_none_or(|requirements| {
3450                !requirements.allowed_approval_policies.is_empty()
3451                    || !requirements.allowed_sandbox_modes.is_empty()
3452            })
3453    }
3454
3455    #[must_use]
3456    pub fn search_provider_resolution(&self) -> SearchProviderResolution {
3457        if let Ok(raw) = std::env::var("CODEWHALE_SEARCH_PROVIDER")
3458            .or_else(|_| std::env::var("DEEPSEEK_SEARCH_PROVIDER"))
3459            && let Some(provider) = SearchProvider::parse(&raw)
3460        {
3461            return SearchProviderResolution {
3462                provider,
3463                source: SearchProviderSource::EnvOverride,
3464            };
3465        }
3466
3467        if let Some(provider) = self.search.as_ref().and_then(|search| search.provider) {
3468            return SearchProviderResolution {
3469                provider,
3470                source: SearchProviderSource::Config,
3471            };
3472        }
3473
3474        // Tavily autodetect: a dedicated `TAVILY_API_KEY`, or a generic
3475        // `[search] api_key` in the `tvly-` family. Runtime-only — never write
3476        // `[search] provider` from here, and never merge the env key into
3477        // `search.api_key`.
3478        let generic_key = self
3479            .search
3480            .as_ref()
3481            .and_then(|search| search.api_key.as_deref());
3482        if tavily_key_from(generic_key).is_some() {
3483            return SearchProviderResolution {
3484                provider: SearchProvider::Tavily,
3485                source: SearchProviderSource::TavilyKey,
3486            };
3487        }
3488
3489        SearchProviderResolution {
3490            provider: SearchProvider::default(),
3491            source: SearchProviderSource::Default,
3492        }
3493    }
3494
3495    #[must_use]
3496    pub fn search_provider(&self) -> SearchProvider {
3497        self.search_provider_resolution().provider
3498    }
3499
3500    /// Whether provider-native search may lead the search chain.
3501    ///
3502    /// `[search] native = true|false` is explicit. Unset, a user-chosen
3503    /// provider (config, env, or a Tavily key) wins over provider-native
3504    /// search (`Some(false)`); with no provider configured it stays `None`,
3505    /// which keeps native search first on routes that offer it.
3506    #[must_use]
3507    pub fn search_native(&self) -> Option<bool> {
3508        self.search
3509            .as_ref()
3510            .and_then(|search| search.native)
3511            .or_else(|| {
3512                (self.search_provider_resolution().source != SearchProviderSource::Default)
3513                    .then_some(false)
3514            })
3515    }
3516
3517    /// Store a session/config provider choice and return the effective runtime
3518    /// provider after applying the documented environment precedence.
3519    pub fn set_search_provider(&mut self, provider: SearchProvider) -> SearchProvider {
3520        self.search
3521            .get_or_insert_with(SearchConfig::default)
3522            .provider = Some(provider);
3523        self.search_provider()
3524    }
3525
3526    /// Return `true` if the `[auto] cost_saving = true` opt-in is set
3527    /// (#1207). When true, the auto-mode router biases toward the active
3528    /// provider's validated fast sibling for ambiguous requests instead of
3529    /// its strong tier. Providers without a known sibling stay on the active
3530    /// model. Default: `false` (balanced behaviour).
3531    #[must_use]
3532    pub fn auto_cost_saving(&self) -> bool {
3533        self.auto
3534            .as_ref()
3535            .and_then(|a| a.cost_saving)
3536            .unwrap_or(false)
3537    }
3538
3539    /// Return `true` only when `[auto] cross_provider = true` is persisted in
3540    /// config (#4411). Auto mode otherwise stays on the active provider: the
3541    /// classifier never sees other providers' routes, and the local fallback
3542    /// never selects one. There is no interactive toggle — enabling
3543    /// cross-provider Auto is an explicit, durable config edit.
3544    #[must_use]
3545    pub fn auto_cross_provider(&self) -> bool {
3546        self.auto
3547            .as_ref()
3548            .and_then(|a| a.cross_provider)
3549            .unwrap_or(false)
3550    }
3551
3552    /// Classifier call timeout for `[auto.router]` in seconds. Defaults to
3553    /// `DEFAULT_AUTO_ROUTER_TIMEOUT_SECS` (4); `0` means "use the default".
3554    /// Values above [`MAX_AUTO_ROUTER_TIMEOUT_SECS`] (300) are clamped so a
3555    /// hung local router cannot stall a turn indefinitely.
3556    #[must_use]
3557    pub fn auto_router_timeout_secs(&self) -> u64 {
3558        self.auto
3559            .as_ref()
3560            .and_then(|a| a.router.as_ref())
3561            .and_then(|r| r.timeout_secs)
3562            .filter(|secs| *secs > 0)
3563            .unwrap_or(DEFAULT_AUTO_ROUTER_TIMEOUT_SECS)
3564            .min(MAX_AUTO_ROUTER_TIMEOUT_SECS)
3565    }
3566
3567    /// Decision-router confidence floor, clamped to `0..=1`; absent or
3568    /// non-finite values use [`DEFAULT_AUTO_ROUTER_MIN_CONFIDENCE`].
3569    #[must_use]
3570    pub fn auto_router_min_confidence(&self) -> f64 {
3571        self.auto
3572            .as_ref()
3573            .and_then(|a| a.router.as_ref())
3574            .and_then(|r| r.min_confidence)
3575            .filter(|value| value.is_finite())
3576            .unwrap_or(DEFAULT_AUTO_ROUTER_MIN_CONFIDENCE)
3577            .clamp(0.0, 1.0)
3578    }
3579
3580    #[must_use]
3581    pub fn tools_always_load(&self) -> std::collections::HashSet<String> {
3582        self.tools
3583            .as_ref()
3584            .map(|tools| {
3585                tools
3586                    .always_load
3587                    .iter()
3588                    .map(|name| name.trim())
3589                    .filter(|name| !name.is_empty())
3590                    .map(ToOwned::to_owned)
3591                    .collect()
3592            })
3593            .unwrap_or_default()
3594    }
3595
3596    /// Effective wait for a user-input answer or an approval decision
3597    /// (#6003). `None` or `0` waits until the person answers or cancels.
3598    /// A positive value bounds that one wait; values above 24h clamp.
3599    #[must_use]
3600    pub fn user_input_timeout(&self) -> Option<std::time::Duration> {
3601        const MAX_SECONDS: u64 = 86_400;
3602        let seconds = self
3603            .tools
3604            .as_ref()
3605            .and_then(|tools| tools.user_input_timeout_seconds)?;
3606        if seconds > MAX_SECONDS {
3607            tracing::warn!(
3608                "[tools] user_input_timeout_seconds={seconds} exceeds 24h; clamping to {MAX_SECONDS}"
3609            );
3610        }
3611        Some(std::time::Duration::from_secs(seconds.min(MAX_SECONDS)))
3612    }
3613
3614    /// Effective ceiling for how long one durable task may stay parked on a
3615    /// human answer. Absent or `0` is the 30 minute default; other values
3616    /// clamp to `1..=86_400` seconds.
3617    #[must_use]
3618    pub fn task_human_wait_cap(&self) -> std::time::Duration {
3619        const DEFAULT_SECONDS: u64 = 30 * 60;
3620        const MAX_SECONDS: u64 = 86_400;
3621        let seconds = self
3622            .tools
3623            .as_ref()
3624            .and_then(|tools| tools.task_human_wait_cap_seconds)
3625            .filter(|seconds| *seconds > 0)
3626            .unwrap_or(DEFAULT_SECONDS);
3627        if seconds > MAX_SECONDS {
3628            tracing::warn!(
3629                "[tools] task_human_wait_cap_seconds={seconds} exceeds 24h; clamping to {MAX_SECONDS}"
3630            );
3631        }
3632        std::time::Duration::from_secs(seconds.min(MAX_SECONDS))
3633    }
3634
3635    /// Load configuration from disk and merge with environment overrides.
3636    ///
3637    /// # Examples
3638    ///
3639    /// ```ignore
3640    /// # use crate::config::Config;
3641    /// let config = Config::load(None, None)?;
3642    /// # Ok::<(), anyhow::Error>(())
3643    /// ```
3644    #[cfg(any(test, feature = "test-support"))]
3645    pub fn load(path: Option<PathBuf>, profile: Option<&str>) -> Result<Self> {
3646        Self::load_with(path, profile, ConfigEnvironmentPolicy::Runtime, &mut |_| {
3647            Ok(())
3648        })
3649    }
3650
3651    /// Load configuration for a structural diagnostic without materializing
3652    /// secret-bearing environment values into the returned configuration.
3653    ///
3654    /// This still applies the ordinary safe routing, model, and policy
3655    /// overrides so doctor describes the runtime the user selected. Provider
3656    /// credentials are resolved only inside an explicit live-probe boundary.
3657    #[cfg(any(test, feature = "test-support"))]
3658    pub fn load_structural(path: Option<PathBuf>, profile: Option<&str>) -> Result<Self> {
3659        Self::load_with(
3660            path,
3661            profile,
3662            ConfigEnvironmentPolicy::StructuralDiagnostic,
3663            &mut |_| Ok(()),
3664        )
3665    }
3666
3667    /// Parse persisted configuration through the same profile precedence used
3668    /// at startup, without environment, credentials, or filesystem writes.
3669    pub fn from_saved_document(contents: &str, profile: Option<&str>) -> Result<Self> {
3670        let parsed = parse_config_file(contents).map_err(|_| {
3671            anyhow::anyhow!("Failed to parse configuration; file contents were omitted")
3672        })?;
3673        let legacy_root = parsed.legacy_root.clone();
3674        let mut config = apply_profile(parsed, profile)?;
3675        config.account_profile = profile.map(str::to_owned);
3676        config.legacy_root = legacy_root;
3677        Ok(config)
3678    }
3679
3680    pub fn migrated_legacy_ollama_cloud_route(&self) -> bool {
3681        self.migrated_legacy_ollama_cloud_route
3682    }
3683
3684    pub fn load_with(
3685        path: Option<PathBuf>,
3686        profile: Option<&str>,
3687        environment_policy: ConfigEnvironmentPolicy,
3688        extend: &mut dyn FnMut(&mut Config) -> Result<()>,
3689    ) -> Result<Self> {
3690        let path = resolve_load_config_path(path)?;
3691        let mut config = if let Some(path) = path.as_ref() {
3692            if path.exists() {
3693                let contents = fs::read_to_string(path)
3694                    .with_context(|| format!("Failed to read config file: {}", path.display()))?;
3695                let parsed = Self::from_saved_document(&contents, profile).with_context(|| {
3696                    format!(
3697                        "Failed to load config file {}",
3698                        codewhale_config::quote_os_path(path)
3699                    )
3700                })?;
3701                if let Some(msg) = warn_on_misplaced_top_level_keys(&contents) {
3702                    tracing::warn!("{msg}");
3703                }
3704                if let Ok(document) = toml::from_str::<toml::Value>(&contents) {
3705                    codewhale_config::reject_unmanaged_tool_launcher(&document, path)?;
3706                }
3707                parsed
3708            } else {
3709                apply_profile(ConfigFile::default(), profile)?;
3710                Config::default()
3711            }
3712        } else {
3713            apply_profile(ConfigFile::default(), profile)?;
3714            Config::default()
3715        };
3716
3717        // Scope and profile choices outrank device startup memory. Environment
3718        config.account_profile = profile.map(str::to_owned);
3719        // and managed values are applied afterwards, so their models win too.
3720        if profile.is_none() && path.as_deref().is_some_and(is_home_config_path) {
3721            if let Ok(settings) =
3722                crate::settings::Settings::load_legacy_route_preferences_read_only()
3723            {
3724                config.apply_saved_selection(&settings);
3725            }
3726            config.remembered_selection_scope = Some(true);
3727        } else {
3728            config.remembered_selection_scope = Some(false);
3729        }
3730        apply_env_overrides(&mut config, environment_policy);
3731        apply_managed_overrides(&mut config)?;
3732        apply_requirements(&mut config)?;
3733        extend(&mut config)?;
3734        normalize_model_config(&mut config);
3735        config.exec_policy_engine = load_sibling_exec_policy_engine(path.as_deref())?;
3736        config.loaded_config_path = path.as_deref().map(std::path::absolute).transpose()?;
3737        config.validate()?;
3738        Ok(config)
3739    }
3740
3741    #[cfg(any(test, feature = "test-support"))]
3742    pub fn remembered_selection_is_applicable(&self) -> bool {
3743        self.remembered_selection_scope.unwrap_or(true)
3744    }
3745
3746    /// Old chooser memory used the public Cloud key even when the active
3747    /// hosted Ollama route still owns the legacy `ollama` table.
3748    pub fn legacy_selection_identity(
3749        &self,
3750        key: &str,
3751    ) -> std::result::Result<ProviderIdentity, String> {
3752        if let Ok(active) = self.active_provider_identity()
3753            && active.key.as_str() == key
3754        {
3755            Ok(active)
3756        } else {
3757            self.resolve_provider_pin_identity(key)
3758        }
3759    }
3760
3761    /// Resolve the existing startup preferences into the Config snapshot shared
3762    /// by the TUI, inventory and Runtime. Never touch persisted preferences or
3763    /// reread them while binding a saved thread's route.
3764    pub fn apply_saved_selection(&mut self, settings: &crate::settings::Settings) -> bool {
3765        if self.remembered_selection_scope.is_some() {
3766            return false;
3767        }
3768        self.remembered_selection_scope = Some(true);
3769        if self.default_text_model.is_none() {
3770            self.default_text_model.clone_from(&self.legacy_model);
3771        }
3772        if self.fleet_operator_route_applied || self.route_preferences_version.is_some() {
3773            return false;
3774        }
3775        let mut active_changed = false;
3776        if let Some(provider) = settings.default_provider.as_deref()
3777            && let Ok(identity) = self.resolve_provider_identity(provider)
3778        {
3779            active_changed = self
3780                .active_provider_identity()
3781                .is_ok_and(|active| active != identity);
3782            if self.scope_to_provider_identity(&identity).is_err() {
3783                return false;
3784            }
3785            self.route_provenance.provider_from_saved_selection = true;
3786        }
3787        let mut choices = settings.provider_models.clone().unwrap_or_default();
3788        if let Some(model) = settings.default_model.as_ref() {
3789            for key in [
3790                ProviderKind::Deepseek.as_str(),
3791                codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id,
3792            ] {
3793                choices.entry(key.into()).or_insert_with(|| model.clone());
3794            }
3795        }
3796        let mut choices: Vec<_> = choices.into_iter().collect();
3797        // Old TUI reads used the exact public identity. If a hand-edited
3798        // archive contains aliases too, process that canonical entry last.
3799        choices.sort_by_key(|(key, _)| {
3800            (
3801                self.legacy_selection_identity(key)
3802                    .is_ok_and(|identity| identity.key.as_str() == key),
3803                key.clone(),
3804            )
3805        });
3806        for (key, remembered) in choices {
3807            let remembered = remembered.trim();
3808            if remembered.is_empty() || remembered.chars().any(char::is_control) {
3809                continue;
3810            }
3811            let Ok(identity) = self.legacy_selection_identity(&key) else {
3812                continue;
3813            };
3814            let provider = identity.provider;
3815            let mut scoped = self.clone();
3816            if scoped.scope_to_provider_identity(&identity).is_err() {
3817                continue;
3818            }
3819            let configured = scoped
3820                .provider_config_for(&identity)
3821                .and_then(|entry| entry.model.as_deref())
3822                .or_else(|| {
3823                    self.active_provider_identity()
3824                        .is_ok_and(|active| active == identity)
3825                        .then_some(self.default_text_model.as_deref())
3826                        .flatten()
3827                })
3828                .unwrap_or_default();
3829            let declared = configured_model_for_route(
3830                &scoped,
3831                provider,
3832                identity.key.as_str(),
3833                &scoped.base_url_for_route(&identity),
3834                remembered,
3835            )
3836            .is_some();
3837            let model = if declared {
3838                remembered.to_string()
3839            } else {
3840                prefer_configured_model_spelling(configured, remembered.to_string())
3841            };
3842            if provider == ProviderKind::Custom && identity.persisted_id().is_some() {
3843                if let Some(entry) = self
3844                    .providers
3845                    .as_mut()
3846                    .and_then(|providers| providers.custom.get_mut(identity.key.as_str()))
3847                {
3848                    entry.model = Some(model);
3849                }
3850            } else if identity.migrated_legacy_ollama_cloud_route {
3851                self.providers
3852                    .get_or_insert_with(ProvidersConfig::default)
3853                    .ollama
3854                    .model = Some(model);
3855            } else {
3856                self.set_provider_model_override(&identity, Some(model))
3857                    .unwrap();
3858            }
3859            let is_active = self
3860                .active_provider_identity()
3861                .is_ok_and(|active| active == identity);
3862            if is_active {
3863                self.route_provenance.model_from_saved_selection = true;
3864            }
3865            active_changed |= is_active;
3866        }
3867        active_changed
3868    }
3869
3870    /// Validate that critical config fields are present.
3871    pub fn validate(&self) -> Result<()> {
3872        if let Some(skills) = &self.skills {
3873            if skills
3874                .listing_max_description_chars
3875                .is_some_and(|value| !(1..=40_000).contains(&value))
3876            {
3877                anyhow::bail!("[skills] listing_max_description_chars must be between 1 and 40000");
3878            }
3879            if skills
3880                .listing_budget_fraction
3881                .is_some_and(|value| !value.is_finite() || value <= 0.0 || value > 1.0)
3882            {
3883                anyhow::bail!(
3884                    "[skills] listing_budget_fraction must be finite and greater than 0 and at most 1"
3885                );
3886            }
3887        }
3888        if let Some(retry) = &self.retry {
3889            for (key, value) in [
3890                ("initial_delay", retry.initial_delay),
3891                ("max_delay", retry.max_delay),
3892                ("exponential_base", retry.exponential_base),
3893            ] {
3894                if value.is_some_and(|value| !value.is_finite() || value < 0.0) {
3895                    anyhow::bail!("[retry] {key} must be a finite number of at least 0");
3896                }
3897            }
3898        }
3899        if let Some(budget) = self.instruction_budget.as_ref() {
3900            budget
3901                .validate()
3902                .map_err(|error| anyhow::anyhow!("invalid [instruction_budget]: {error}"))?;
3903        }
3904        if let Some(provider) = self.provider.as_deref()
3905            && !is_legacy_antigravity_identity(provider)
3906            && compatibility_for_selector(provider).is_none()
3907            && self
3908                .providers
3909                .as_ref()
3910                .and_then(|providers| providers.custom_provider_config(provider))
3911                .is_none()
3912        {
3913            return Err(invalid_provider_diagnostic(provider).into());
3914        }
3915        let identity = self
3916            .active_provider_identity()
3917            .map_err(anyhow::Error::msg)?;
3918        let active_provider = identity.provider;
3919        codewhale_config::catalog::configured::validate_configured_models(
3920            self.custom_models.as_deref().unwrap_or_default(),
3921        )?;
3922        self.openrouter_vendor()?;
3923        if self
3924            .provider
3925            .as_deref()
3926            .is_some_and(is_legacy_antigravity_identity)
3927        {
3928            anyhow::bail!(codewhale_config::LEGACY_ANTIGRAVITY_TOMBSTONE_MESSAGE);
3929        }
3930        match validate_kimi_code_api_model_id(
3931            active_provider,
3932            &self.active_route_base_url(),
3933            &self.default_model(),
3934        ) {
3935            Err(error) if error == KIMI_CODE_CLAUDE_ALIAS_GUIDANCE => {
3936                return Err(SafeConfigDiagnostic::KimiCodeClaudeAlias.into());
3937            }
3938            result => result.map_err(anyhow::Error::msg)?,
3939        }
3940        if let Some(features) = &self.features {
3941            for key in features.entries.keys() {
3942                if !is_known_feature_key(key) {
3943                    anyhow::bail!("Unknown feature flag: {key}");
3944                }
3945            }
3946        }
3947        let configured_model = self
3948            .provider_config_string_with_runtime_fallback(&identity, |entry| entry.model.clone())
3949            .or_else(|| self.default_text_model.clone());
3950        if let Some(model) = configured_model.as_deref()
3951            && !model.trim().eq_ignore_ascii_case("auto")
3952            && !codewhale_config::descriptors::provider_passes_model_through(active_provider)
3953            && !self.active_provider_preserves_custom_base_url_model()
3954            && configured_model_for_route(
3955                self,
3956                active_provider,
3957                identity.key.as_str(),
3958                &self.base_url_for_route(&identity),
3959                model,
3960            )
3961            .is_none()
3962            && codewhale_config::route::resolve_model(active_provider, model, None).is_err()
3963        {
3964            let provider = active_provider;
3965            let known = model_completion_names_for_provider(provider);
3966            let hint = if known.is_empty() {
3967                String::new()
3968            } else {
3969                format!(" (for example: {})", known.join(", "))
3970            };
3971            return Err(SafeConfigDiagnostic::invalid_value(
3972                "model",
3973                model,
3974                &format!(
3975                    "auto or a model ID provider '{}' serves{hint}",
3976                    provider.as_str()
3977                ),
3978                user_config_fix("model", "auto", Some("a *_MODEL environment variable")),
3979            )
3980            .into());
3981        }
3982        // One vocabulary with `codewhale config set`, which refuses the same
3983        // values before writing them (`codewhale_config::config_toml_choices`).
3984        for (key, value, replacement, env_var) in [
3985            (
3986                "approval_policy",
3987                self.approval_policy.as_deref(),
3988                "on-request",
3989                Some("CODEWHALE_APPROVAL_POLICY"),
3990            ),
3991            ("verbosity", self.verbosity.as_deref(), "normal", None),
3992            (
3993                "sandbox_mode",
3994                self.sandbox_mode.as_deref(),
3995                "workspace-write",
3996                Some("CODEWHALE_SANDBOX_MODE"),
3997            ),
3998        ] {
3999            let (Some(value), Some(choices)) = (value, codewhale_config::config_toml_choices(key))
4000            else {
4001                continue;
4002            };
4003            if !choices.contains(&value.trim().to_ascii_lowercase().as_str()) {
4004                let expected = match choices.split_last() {
4005                    Some((last, [])) => (*last).to_string(),
4006                    Some((last, [only])) => format!("{only} or {last}"),
4007                    Some((last, rest)) => format!("{}, or {last}", rest.join(", ")),
4008                    None => String::new(),
4009                };
4010                let displayed_value = codewhale_sanitize::redact::redact_secrets(value);
4011                return Err(SafeConfigDiagnostic::invalid_value(
4012                    key,
4013                    &displayed_value,
4014                    &expected,
4015                    user_config_fix(key, replacement, env_var),
4016                )
4017                .into());
4018            }
4019        }
4020        if let Some(tui) = &self.tui
4021            && let Some(mode) = tui.alternate_screen.as_deref()
4022        {
4023            let mode = mode.to_ascii_lowercase();
4024            if !matches!(mode.as_str(), "auto" | "always" | "never") {
4025                return Err(SafeConfigDiagnostic::invalid_value(
4026                    "tui.alternate_screen",
4027                    &mode,
4028                    "auto, always, or never",
4029                    user_config_fix("tui.alternate_screen", "auto", None),
4030                )
4031                .into());
4032            }
4033        }
4034        if let Some(transcript) = &self.transcript
4035            && let Err(detail) = transcript.prose_measure_columns()
4036        {
4037            anyhow::bail!("Invalid transcript.prose_measure: {detail}.");
4038        }
4039        if let Some(auto_review) = &self.auto_review {
4040            auto_review.validate()?;
4041            if auto_review.disabled
4042                && self
4043                    .approval_policy
4044                    .as_deref()
4045                    .and_then(codewhale_execpolicy::ApprovalMode::from_config_value)
4046                    == Some(codewhale_execpolicy::ApprovalMode::Auto)
4047            {
4048                anyhow::bail!(
4049                    "approval_policy = \"auto\" is disabled by managed configuration (`auto_review.disabled = true`)"
4050                );
4051            }
4052        }
4053        if let Some(providers) = &self.providers {
4054            providers.validate()?;
4055        }
4056        Ok(())
4057    }
4058
4059    /// Resolved prose wrap cap from `[transcript] prose_measure` (#5436).
4060    ///
4061    /// `None` (absent or `0`) means prose uses the full content width,
4062    /// consistent with tool/status cells. Invalid values are rejected by
4063    /// [`Config::validate`], which every load path runs, so this resolver
4064    /// cannot fail here.
4065    #[must_use]
4066    pub fn prose_measure(&self) -> Option<u16> {
4067        self.transcript
4068            .as_ref()
4069            .and_then(|transcript| transcript.prose_measure_columns().ok().flatten())
4070    }
4071
4072    #[must_use]
4073    /// Whether the live config uses the released route-sensitive Ollama Cloud
4074    /// shape. This is a pure in-memory compatibility check: no config or
4075    /// secret state is rewritten, and only the exact official `/v1` endpoint
4076    /// upgrades from `ollama` to `ollama-cloud`.
4077    fn selects_legacy_ollama_cloud_route(&self) -> bool {
4078        if self.migrated_legacy_ollama_cloud_route {
4079            return true;
4080        }
4081        if self.provider.as_deref().and_then(ProviderKind::parse) != Some(ProviderKind::Ollama) {
4082            return false;
4083        }
4084        self.legacy_ollama_cloud_route_configured()
4085    }
4086
4087    /// Whether the legacy Ollama table itself names the exact hosted route,
4088    /// independent of which provider the parent session currently selects.
4089    /// Fleet and subagent pins need this route-scoped form.
4090    fn legacy_ollama_cloud_route_configured(&self) -> bool {
4091        let base_url = self
4092            .providers
4093            .as_ref()
4094            .and_then(|providers| providers.ollama.base_url.as_deref())
4095            .map(str::to_string)
4096            .or_else(|| first_nonempty_env(&["OLLAMA_BASE_URL"]));
4097        base_url.is_some_and(|base_url| {
4098            codewhale_config::provider::migrates_legacy_ollama_cloud_route(
4099                codewhale_config::ProviderKind::Ollama,
4100                &base_url,
4101            )
4102        })
4103    }
4104
4105    /// Resolve the currently selected live route, keeping its exact id.
4106    pub fn active_provider_identity(&self) -> std::result::Result<ProviderIdentity, String> {
4107        let selected = self
4108            .provider
4109            .as_deref()
4110            .unwrap_or(ProviderKind::Deepseek.as_str());
4111        if self.migrated_legacy_ollama_cloud_route && selected == ProviderKind::OllamaCloud.as_str()
4112        {
4113            return self.resolve_persisted_provider_identity(
4114                Some(ProviderKind::OllamaCloud.as_str()),
4115                Some(ProviderKind::Ollama.as_str()),
4116            );
4117        }
4118        // Tombstones remain visible to inspection/clear; execution preflight
4119        // refuses the intrinsic retired kind before obtaining credentials.
4120        if is_legacy_antigravity_identity(selected) {
4121            return Ok(ProviderIdentity {
4122                provider: ProviderKind::Antigravity,
4123                key: ProviderId::from(ProviderKind::Antigravity.as_str()),
4124                exact_id: Some(ProviderId::from(ProviderKind::Antigravity.as_str())),
4125                migrated_legacy_ollama_cloud_route: false,
4126                legacy_root_custom_generation: None,
4127            });
4128        }
4129        if self.selects_literal_custom_provider()
4130            && self.current_legacy_root_custom_generation().is_some()
4131        {
4132            return self.resolve_persisted_provider_identity(Some("custom"), None);
4133        }
4134        self.resolve_provider_identity(selected)
4135    }
4136
4137    /// Test fixtures use the same canonical resolver. This convenience never
4138    /// supplies an absent custom ID or reconstructs production admission.
4139    #[cfg(any(test, feature = "test-support"))]
4140    pub fn test_identity_for_kind(&self, kind: ProviderKind) -> ProviderIdentity {
4141        if let Ok(active) = self.active_provider_identity()
4142            && active.provider == kind
4143        {
4144            return active;
4145        }
4146        self.builtin_provider_identity(kind)
4147            .expect("test fixture must declare an admitted provider identity")
4148    }
4149
4150    /// Snapshot admitted identities in descriptor order, then exact custom-key order.
4151    /// This lists routes through the same resolver used by final dispatch; it
4152    /// neither activates them nor reads credentials.
4153    pub fn provider_identities(&self) -> Vec<ProviderIdentity> {
4154        let active = self.active_provider_identity().ok();
4155        let mut identities = Vec::new();
4156        for row in codewhale_config::descriptors::provider_compatibility() {
4157            if row.kind == ProviderKind::Custom {
4158                continue;
4159            }
4160            let identity = active
4161                .as_ref()
4162                .filter(|identity| identity.key.as_str() == row.id)
4163                .cloned()
4164                .or_else(|| self.resolve_provider_pin_identity(row.id).ok());
4165            if let Some(identity) = identity
4166                && identity.provider == row.kind
4167                && !identities
4168                    .iter()
4169                    .any(|existing: &ProviderIdentity| existing == &identity)
4170            {
4171                identities.push(identity);
4172            }
4173        }
4174        if let Some(active) = active
4175            && !identities.contains(&active)
4176        {
4177            identities.push(active);
4178        }
4179        if let Some(providers) = &self.providers {
4180            for key in providers.custom.keys() {
4181                if let Ok(identity) = self.resolve_provider_pin_identity(key)
4182                    && !identities
4183                        .iter()
4184                        .any(|existing| existing.key == identity.key)
4185                {
4186                    identities.push(identity);
4187                }
4188            }
4189        }
4190        identities
4191    }
4192
4193    /// Preserve broken/manual selections in diagnostic rosters without admitting them.
4194    pub fn unadmitted_provider_keys(&self) -> Vec<&str> {
4195        let admitted = self.provider_identities();
4196        let mut keys = Vec::new();
4197        if let Some(providers) = &self.providers {
4198            keys.extend(providers.custom.keys().map(String::as_str).filter(|key| {
4199                !admitted
4200                    .iter()
4201                    .any(|identity| identity.key.as_str() == *key)
4202            }));
4203        }
4204        if let Some(key) = self.provider.as_deref()
4205            && self.active_provider_identity().is_err()
4206            && !keys.contains(&key)
4207        {
4208            keys.push(key);
4209        }
4210        keys.sort_unstable();
4211        keys
4212    }
4213
4214    pub fn builtin_provider_identity(
4215        &self,
4216        kind: ProviderKind,
4217    ) -> std::result::Result<ProviderIdentity, String> {
4218        self.resolve_persisted_provider_identity(Some(kind.as_str()), Some(kind.as_str()))
4219    }
4220
4221    /// Resolve a persisted provider key against the current live config.
4222    ///
4223    /// Named custom providers are exact and fail closed: a removed, renamed,
4224    /// or malformed table can never fall through to DeepSeek or whichever
4225    /// provider happens to be selected now. The literal legacy value `custom`
4226    /// remains loadable only for the old root-field config shape where the live
4227    /// provider is also literally `custom` and both `base_url` and
4228    /// `default_text_model` identify one valid route.
4229    pub fn resolve_provider_identity(
4230        &self,
4231        persisted: &str,
4232    ) -> std::result::Result<ProviderIdentity, String> {
4233        let key = persisted.trim();
4234        if key.is_empty() {
4235            return Err(
4236                "saved session has an empty provider identity; choose a valid session or repair its `metadata.model_provider` field"
4237                    .to_string(),
4238            );
4239        }
4240
4241        let has_exact_custom_table = self
4242            .providers
4243            .as_ref()
4244            .and_then(|providers| providers.custom_provider_config(key))
4245            .is_some();
4246
4247        if !has_exact_custom_table
4248            && let Some(row) = compatibility_for_selector(key)
4249            && row.kind != ProviderKind::Antigravity
4250            && row.kind != ProviderKind::Custom
4251        {
4252            let mut provider = row.kind;
4253            let migrated_legacy_ollama_cloud_route =
4254                provider == ProviderKind::Ollama && self.legacy_ollama_cloud_route_configured();
4255            if provider == ProviderKind::Ollama && migrated_legacy_ollama_cloud_route {
4256                provider = ProviderKind::OllamaCloud;
4257            }
4258            return Ok(ProviderIdentity {
4259                provider,
4260                key: ProviderId::from(if migrated_legacy_ollama_cloud_route {
4261                    provider.as_str()
4262                } else {
4263                    row.id
4264                }),
4265                exact_id: Some(if migrated_legacy_ollama_cloud_route {
4266                    ProviderId::from(ProviderKind::Ollama.as_str())
4267                } else {
4268                    ProviderId::from(row.id)
4269                }),
4270                migrated_legacy_ollama_cloud_route,
4271                legacy_root_custom_generation: None,
4272            });
4273        }
4274
4275        if !has_exact_custom_table && key.eq_ignore_ascii_case(ProviderKind::Custom.as_str()) {
4276            if self.selects_literal_custom_provider() {
4277                // The literal `provider = "custom"` route lives in
4278                // `[providers.custom]`; parsing moved an older top-level
4279                // endpoint there (#6394). Without that table there is no
4280                // route to resume.
4281                return Err(
4282                    "`provider = \"custom\"` requires a `[providers.custom]` table with a `base_url`; Codewhale will not use the custom-provider placeholder or fall back"
4283                        .to_string(),
4284                );
4285            }
4286
4287            // Pre-exact releases persisted every named custom route as the
4288            // generic literal `custom`. Migrate that record only when the live
4289            // config selects the sole valid named custom table; otherwise the
4290            // old value is genuinely ambiguous and must fail closed.
4291            if !self.selects_literal_custom_provider() {
4292                let selected = self.provider.as_deref().map(str::trim).unwrap_or_default();
4293                let valid_named = self
4294                    .providers
4295                    .as_ref()
4296                    .map(|providers| {
4297                        providers
4298                            .custom
4299                            .keys()
4300                            .filter(|name| {
4301                                !name.eq_ignore_ascii_case(ProviderKind::Custom.as_str())
4302                                    && ProviderKind::parse(name).is_none()
4303                                    && self.resolve_provider_identity(name).is_ok()
4304                            })
4305                            .cloned()
4306                            .collect::<Vec<_>>()
4307                    })
4308                    .unwrap_or_default();
4309                if let [name] = valid_named.as_slice()
4310                    && selected == name
4311                {
4312                    return self.resolve_provider_identity(name);
4313                }
4314                return Err(format!(
4315                    "legacy session records only the generic `custom` provider kind, but the live config does not select exactly one valid named custom route (selected '{}', valid named routes: {}). Restore the original single `[providers.<name>]` route or repair the saved provider identity; Codewhale will not guess or fall back",
4316                    if selected.is_empty() {
4317                        "<unset>"
4318                    } else {
4319                        selected
4320                    },
4321                    valid_named.len()
4322                ));
4323            }
4324        }
4325
4326        let exact_key = key;
4327
4328        let entry = self
4329            .providers
4330            .as_ref()
4331            .and_then(|providers| providers.custom_provider_config(exact_key))
4332            .ok_or_else(|| {
4333                format!(
4334                    "saved session requires custom provider '{exact_key}', but `[providers.{exact_key}]` is missing from the live config. Restore that exact table and retry; Codewhale will not fall back"
4335                )
4336            })?;
4337        if !entry.is_openai_compatible_custom() {
4338            return Err(format!(
4339                "saved session requires custom provider '{exact_key}', but `[providers.{exact_key}]` must set `kind = \"openai-compatible\"`. Fix the live config and retry; Codewhale will not fall back"
4340            ));
4341        }
4342        let base_url = entry
4343            .base_url
4344            .as_deref()
4345            .map(str::trim)
4346            .filter(|base_url| !base_url.is_empty())
4347            .ok_or_else(|| {
4348                format!(
4349                    "saved session requires custom provider '{exact_key}', but `[providers.{exact_key}]` has no `base_url`. Fix the live config and retry; Codewhale will not fall back"
4350                )
4351            })?;
4352        let parsed = reqwest::Url::parse(base_url).map_err(|err| {
4353            format!(
4354                "saved session requires custom provider '{exact_key}', but `[providers.{exact_key}].base_url` is invalid: {err}. Fix the live config and retry; Codewhale will not fall back"
4355            )
4356        })?;
4357        if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
4358            return Err(format!(
4359                "saved session requires custom provider '{exact_key}', but `[providers.{exact_key}].base_url` must be an http(s) URL with a host. Fix the live config and retry; Codewhale will not fall back"
4360            ));
4361        }
4362
4363        Ok(ProviderIdentity {
4364            provider: ProviderKind::Custom,
4365            key: ProviderId::from(exact_key),
4366            exact_id: Some(ProviderId::from(exact_key)),
4367            migrated_legacy_ollama_cloud_route: false,
4368            legacy_root_custom_generation: None,
4369        })
4370    }
4371
4372    /// Resolve a provider explicitly pinned by a current Fleet/subagent
4373    /// declaration.
4374    ///
4375    /// A scoped legacy Ollama Cloud config retains its migration marker so the
4376    /// active client can keep reading `[providers.ollama]` and the old secret
4377    /// slot. That marker is provenance for the active route, not an alias for a
4378    /// newly declared `ollama-cloud` pin: the explicit pin must bind the
4379    /// first-class table and credential slot even when it is declared by a
4380    /// child of the migrated route.
4381    pub fn resolve_provider_pin_identity(
4382        &self,
4383        provider_id: &str,
4384    ) -> std::result::Result<ProviderIdentity, String> {
4385        let mut identity = self.resolve_provider_identity(provider_id)?;
4386        if provider_id
4387            .trim()
4388            .eq_ignore_ascii_case(ProviderKind::Custom.as_str())
4389            && !identity
4390                .key
4391                .as_str()
4392                .eq_ignore_ascii_case(ProviderKind::Custom.as_str())
4393        {
4394            return Err(format!(
4395                "an explicit provider pin must name the configured provider '{}'; `custom` is not a wildcard for a named provider",
4396                identity.key
4397            ));
4398        }
4399        if identity.provider == ProviderKind::OllamaCloud
4400            && ProviderKind::parse(provider_id.trim()) == Some(ProviderKind::OllamaCloud)
4401        {
4402            identity.migrated_legacy_ollama_cloud_route = false;
4403        }
4404        Ok(identity)
4405    }
4406
4407    /// Resolve a provider a user is selecting now (`codewhale config set
4408    /// provider <name>`). A name that is neither a built-in provider nor a
4409    /// configured table is a typo, not a saved session missing its route, so
4410    /// it gets config validation's wording instead of the resume wording.
4411    pub fn resolve_provider_selection_identity(
4412        &self,
4413        provider_id: &str,
4414    ) -> std::result::Result<ProviderIdentity, String> {
4415        let requested = provider_id.trim();
4416        if !requested.is_empty()
4417            && compatibility_for_selector(requested).is_none()
4418            && !requested.eq_ignore_ascii_case(ProviderKind::Custom.as_str())
4419            && self
4420                .providers
4421                .as_ref()
4422                .and_then(|providers| providers.custom_provider_config(requested))
4423                .is_none()
4424        {
4425            return Err(invalid_provider_message(requested));
4426        }
4427        if is_legacy_antigravity_identity(requested) {
4428            return Err("Antigravity is retired and cannot be selected".to_string());
4429        }
4430        self.resolve_provider_pin_identity(provider_id)
4431    }
4432
4433    /// Resolve an additive exact provider id. Unlike raw selector resolution,
4434    /// an id means the record requires that exact `[providers.<id>]` table.
4435    fn resolve_exact_provider_identity(
4436        &self,
4437        persisted: &str,
4438    ) -> std::result::Result<ProviderIdentity, String> {
4439        let id = persisted.trim();
4440        if id.is_empty() {
4441            return Err(
4442                "persisted provider route has an empty exact provider id; Codewhale will not guess or fall back"
4443                    .to_string(),
4444            );
4445        }
4446        let has_exact_custom_table = self
4447            .providers
4448            .as_ref()
4449            .and_then(|providers| providers.custom_provider_config(id))
4450            .is_some();
4451        if id.eq_ignore_ascii_case(ProviderKind::Custom.as_str()) && !has_exact_custom_table {
4452            return Err(format!(
4453                "persisted provider route requires exact custom provider '{id}', but `[providers.{id}]` is missing from the live config. Restore that exact table and retry; Codewhale will not fall back"
4454            ));
4455        }
4456
4457        let identity = self.resolve_provider_identity(id)?;
4458        if identity.provider == ProviderKind::Custom && identity.persisted_id() != Some(id) {
4459            return Err(format!(
4460                "persisted provider route requires exact custom provider '{id}', but the live config does not provide that exact table. Restore `[providers.{id}]` and retry; Codewhale will not fall back"
4461            ));
4462        }
4463        Ok(identity)
4464    }
4465
4466    /// Resolve the two-field provider route written by current session/thread
4467    /// schemas without erasing which field supplied the identity.
4468    ///
4469    /// `provider_kind` is the generic wire/provider class (`custom` for every
4470    /// named OpenAI-compatible endpoint); `provider_id` is the additive exact
4471    /// configured key. Older records have no id and may have overloaded the
4472    /// kind field with an exact custom name. Keeping those cases distinct is
4473    /// security-sensitive: a legacy built-in record must never be captured by
4474    /// a later same-key custom table, while a current `custom` + exact-id pair
4475    /// must retain that user-owned table identity.
4476    pub fn resolve_persisted_provider_identity(
4477        &self,
4478        provider_kind: Option<&str>,
4479        provider_id: Option<&str>,
4480    ) -> std::result::Result<ProviderIdentity, String> {
4481        let kind = provider_kind
4482            .map(str::trim)
4483            .filter(|value| !value.is_empty());
4484        // Missing and malformed are different security states. An explicitly
4485        // persisted empty id must reach `resolve_exact_provider_identity` so
4486        // it fails closed instead of being reinterpreted as an id-less legacy
4487        // root route.
4488        let id = provider_id.map(str::trim);
4489
4490        let Some(kind) = kind else {
4491            return id.map_or_else(
4492                || {
4493                    Err(
4494                        "persisted provider route has neither a provider kind nor an exact provider id; Codewhale will not guess or fall back"
4495                            .to_string(),
4496                    )
4497                },
4498                |id| self.resolve_exact_provider_identity(id),
4499            );
4500        };
4501
4502        let source =
4503            compatibility_for_selector(kind).filter(|row| row.kind != ProviderKind::Antigravity);
4504        let Some(mut provider) = source.map(|row| row.kind) else {
4505            // Pre-additive releases sometimes wrote an exact named custom key
4506            // into `model_provider`. Preserve that shape, but reject a
4507            // contradictory additive id instead of silently choosing one.
4508            if let Some(id) = id
4509                && id != kind
4510            {
4511                return Err(format!(
4512                    "persisted provider route has legacy identity '{kind}' but exact provider id '{id}'; repair the mismatched fields because Codewhale will not guess or fall back"
4513                ));
4514            }
4515            return match id {
4516                Some(id) => self.resolve_exact_provider_identity(id),
4517                None => self.resolve_provider_identity(kind),
4518            };
4519        };
4520        let migrated_legacy_ollama_cloud = (provider == ProviderKind::Ollama
4521            && self.legacy_ollama_cloud_route_configured())
4522            || (provider == ProviderKind::OllamaCloud
4523                && id.and_then(ProviderKind::parse) == Some(ProviderKind::Ollama)
4524                && self.legacy_ollama_cloud_route_configured());
4525        if migrated_legacy_ollama_cloud {
4526            provider = ProviderKind::OllamaCloud;
4527        }
4528
4529        if provider == ProviderKind::Custom {
4530            if let Some(id) = id {
4531                let identity = self.resolve_exact_provider_identity(id)?;
4532                if identity.provider != ProviderKind::Custom {
4533                    return Err(format!(
4534                        "persisted provider route declares generic kind 'custom' but exact provider id '{id}' resolves as built-in '{}'; use the matching built-in kind or restore `[providers.{id}]`. Codewhale will not guess or fall back",
4535                        identity.provider.as_str()
4536                    ));
4537                }
4538                return Ok(identity);
4539            }
4540
4541            // A table is not evidence for a released id-less root record.
4542            // Only the root-scope canonicalizer's parse-bound receipt admits it.
4543            let generation = self.current_legacy_root_custom_generation().filter(|_| self.selects_literal_custom_provider()).ok_or_else(|| {
4544                "legacy id-less `custom` route requires the unchanged root-scope migrated `base_url`; a table-only, conflicting, changed, or profile-only route cannot supply that provenance. Repair the saved exact provider id; Codewhale will not guess or fall back".to_string()
4545            })?;
4546            let mut identity =
4547                self.resolve_exact_provider_identity(ProviderKind::Custom.as_str())?;
4548            identity.exact_id = None;
4549            identity.legacy_root_custom_generation = Some(generation);
4550            return Ok(identity);
4551        }
4552
4553        let exact = id.and_then(compatibility_for_selector);
4554        if let Some(id) = id
4555            && (exact.is_none_or(|row| row.kind != provider)
4556                || source.is_some_and(|row| {
4557                    row.id != row.kind.as_str() && exact.is_some_and(|exact| exact.id != row.id)
4558                }))
4559            && !(migrated_legacy_ollama_cloud
4560                && ProviderKind::parse(id) == Some(ProviderKind::Ollama))
4561        {
4562            return Err(format!(
4563                "persisted provider route declares built-in kind '{}' but exact provider id '{id}' names a different route; repair the mismatched fields because Codewhale will not guess or fall back",
4564                provider.as_str()
4565            ));
4566        }
4567
4568        let key = if migrated_legacy_ollama_cloud {
4569            provider.as_str()
4570        } else {
4571            exact.or(source).expect("parsed built-in compatibility").id
4572        };
4573
4574        // Exact custom keys normally win raw string resolution. A persisted
4575        // built-in kind is stronger evidence than that raw key, but Config's
4576        // single selector cannot represent both routes simultaneously. Fail
4577        // closed instead of constructing a descriptor whose client would read
4578        // credentials/settings from the shadowing custom table.
4579        if self
4580            .providers
4581            .as_ref()
4582            .and_then(|providers| providers.custom_provider_config(key))
4583            .is_some()
4584        {
4585            return Err(format!(
4586                "persisted provider route requires built-in '{}', but an exact `[providers.{}]` custom route shadows the same selector. Rename the custom route or update the saved provider kind/id pair; Codewhale will not guess or fall back",
4587                provider.as_str(),
4588                provider.as_str()
4589            ));
4590        }
4591
4592        Ok(ProviderIdentity {
4593            provider,
4594            key: ProviderId::from(key),
4595            exact_id: Some(if migrated_legacy_ollama_cloud {
4596                ProviderId::from(ProviderKind::Ollama.as_str())
4597            } else {
4598                ProviderId::from(key)
4599            }),
4600            migrated_legacy_ollama_cloud_route: migrated_legacy_ollama_cloud,
4601            legacy_root_custom_generation: None,
4602        })
4603    }
4604
4605    /// Scope a runtime clone to one admitted identity; the parse-bound table
4606    /// remains present and every later table projection revalidates its receipt.
4607    pub fn scope_to_provider_identity(
4608        &mut self,
4609        identity: &ProviderIdentity,
4610    ) -> std::result::Result<(), String> {
4611        self.verify_provider_identity(identity)?;
4612        self.migrated_legacy_ollama_cloud_route = identity.migrated_legacy_ollama_cloud_route;
4613        self.provider = Some(identity.key.to_string());
4614        Ok(())
4615    }
4616
4617    fn legacy_root_custom_table_generation(
4618        &self,
4619    ) -> Option<codewhale_config::credentials::CredentialGeneration> {
4620        let entry = self.providers.as_ref()?.custom.get("custom")?;
4621        let value = serde_json::to_value(entry).ok()?;
4622        Some(codewhale_config::credentials::CredentialGeneration::derive(
4623            "codewhale/legacy-root-custom-table/v1",
4624            &crate::hashing::canonical_json(&value),
4625        ))
4626    }
4627
4628    fn bind_legacy_root_custom_generation(&mut self) {
4629        use codewhale_config::legacy_root::{LegacyRootField, LegacyRootNote};
4630        let moved = self.legacy_root.notes.iter().any(|note| {
4631            matches!(note,
4632                LegacyRootNote::Moved { scope: None, field: LegacyRootField::BaseUrl, to }
4633                | LegacyRootNote::Merged { scope: None, field: LegacyRootField::BaseUrl, to }
4634                if to == "providers.custom"
4635            )
4636        });
4637        let conflicting = self.legacy_root.notes.iter().any(|note| {
4638            matches!(
4639                note,
4640                LegacyRootNote::Conflict {
4641                    scope: None,
4642                    field: LegacyRootField::BaseUrl,
4643                    ..
4644                } | LegacyRootNote::DroppedEmpty {
4645                    scope: None,
4646                    field: LegacyRootField::BaseUrl
4647                }
4648            )
4649        });
4650        self.legacy_root_custom_generation =
4651            (moved && !conflicting && self.selects_literal_custom_provider())
4652                .then(|| self.legacy_root_custom_table_generation())
4653                .flatten();
4654    }
4655
4656    fn current_legacy_root_custom_generation(
4657        &self,
4658    ) -> Option<codewhale_config::credentials::CredentialGeneration> {
4659        let captured = self.legacy_root_custom_generation.as_ref()?;
4660        let current = self.legacy_root_custom_table_generation()?;
4661        (captured == &current).then_some(current)
4662    }
4663
4664    pub fn selects_literal_custom_provider(&self) -> bool {
4665        self.provider
4666            .as_deref()
4667            .map(str::trim)
4668            .is_some_and(|name| name.eq_ignore_ascii_case(ProviderKind::Custom.as_str()))
4669    }
4670
4671    /// Whether `identity` names a custom route that this config can resolve.
4672    ///
4673    /// Only an exact `[providers.<name>]` custom table (the literal `custom`
4674    /// route included, since #6394). Anything else — an empty key, a
4675    /// removed table, a built-in provider name — is an unresolvable custom
4676    /// identity and endpoint resolution must fail closed on it.
4677    ///
4678    /// The predicate that pins that contract for the regression suite; the
4679    /// resolver itself fails closed without consulting it.
4680    #[cfg(test)]
4681    pub(crate) fn custom_identity_is_resolvable(&self, identity: &str) -> bool {
4682        self.custom_provider_entry_for_identity(identity).is_some()
4683    }
4684
4685    /// Trimmed, non-empty `wire` dialect preference for `provider`'s config
4686    /// table (`[providers.<name>] wire = "responses" | "anthropic" | "chat"`).
4687    ///
4688    /// Single source for the client wire resolver and the capability reporter
4689    /// so the two cannot drift. `None` means "no preference" — the provider's
4690    /// static policy applies.
4691    pub fn provider_wire_dialect(&self, identity: &ProviderIdentity) -> Option<&str> {
4692        self.provider_config_for(identity)?
4693            .wire
4694            .as_deref()
4695            .map(str::trim)
4696            .filter(|value| !value.is_empty())
4697    }
4698
4699    pub fn provider_responses_profile(&self, identity: &ProviderIdentity) -> Option<&str> {
4700        self.provider_config_for(identity)?
4701            .responses_profile
4702            .as_deref()
4703            .map(str::trim)
4704            .filter(|value| !value.is_empty())
4705    }
4706
4707    pub fn verify_provider_identity(
4708        &self,
4709        identity: &ProviderIdentity,
4710    ) -> std::result::Result<(), String> {
4711        let admitted = self.resolve_persisted_provider_identity(
4712            Some(identity.persisted_kind()),
4713            identity.persisted_id(),
4714        )?;
4715        if admitted == *identity {
4716            Ok(())
4717        } else {
4718            Err("provider identity changed before projection".into())
4719        }
4720    }
4721
4722    pub fn provider_config_for(&self, identity: &ProviderIdentity) -> Option<&ProviderConfig> {
4723        let providers = self.providers.as_ref()?;
4724        self.verify_provider_identity(identity).ok()?;
4725        if identity.provider == ProviderKind::Custom {
4726            return providers.custom_provider_config(identity.key.as_str());
4727        }
4728        let table = if identity.migrated_legacy_ollama_cloud_route {
4729            ProviderKind::Ollama.as_str()
4730        } else {
4731            identity.key.as_str()
4732        };
4733        codewhale_config::provider_config_table!(@read providers, table)
4734    }
4735
4736    /// Resolve the pin from the selected provider only, before any request.
4737    pub fn openrouter_vendor(&self) -> Result<Option<String>> {
4738        let identity = self
4739            .active_provider_identity()
4740            .map_err(anyhow::Error::msg)?;
4741        let provider = identity.provider;
4742
4743        let Some(vendor) = self
4744            .provider_config_for(&identity)
4745            .and_then(|entry| entry.vendor.as_deref())
4746        else {
4747            return Ok(None);
4748        };
4749        let vendor = codewhale_config::validate_openrouter_vendor(vendor)?;
4750        if vendor.is_some() && provider != ProviderKind::Openrouter {
4751            anyhow::bail!("vendor is only supported by providers.openrouter");
4752        }
4753        Ok(vendor.map(str::to_string))
4754    }
4755
4756    pub fn subagent_provider_config(
4757        &self,
4758        identity: &ProviderIdentity,
4759    ) -> Option<&SubagentProviderConfig> {
4760        let providers = self.subagents.as_ref()?.providers.as_ref()?;
4761        providers.iter().find_map(|(key, config)| {
4762            let matches = if identity.provider == ProviderKind::Custom {
4763                key == identity.key.as_str()
4764            } else if let Some(row) = identity.compatibility() {
4765                let normalized = normalize_subagent_provider_key(key);
4766                compatibility_for_selector(key).is_some_and(|candidate| candidate.id == row.id)
4767                    || normalized == normalize_subagent_provider_key(row.id)
4768                    || row.subagent_aliases.contains(&normalized.as_str())
4769            } else {
4770                false
4771            };
4772            matches.then_some(config)
4773        })
4774    }
4775
4776    pub fn provider_config_for_mut(
4777        &mut self,
4778        identity: &ProviderIdentity,
4779    ) -> Result<&mut ProviderConfig> {
4780        self.verify_provider_identity(identity)
4781            .map_err(anyhow::Error::msg)?;
4782        let providers = self.providers.get_or_insert_with(ProvidersConfig::default);
4783        if identity.provider == ProviderKind::Custom {
4784            return providers
4785                .custom
4786                .get_mut(identity.key.as_str())
4787                .context("exact custom provider table missing before mutation");
4788        }
4789        let table = if identity.migrated_legacy_ollama_cloud_route {
4790            ProviderKind::Ollama.as_str()
4791        } else {
4792            identity.key.as_str()
4793        };
4794        codewhale_config::provider_config_table!(@write providers, table)
4795            .context("provider has no generated typed config table")
4796    }
4797
4798    /// Apply a runtime model override to the route's own table.
4799    pub fn set_provider_model_override(
4800        &mut self,
4801        identity: &ProviderIdentity,
4802        model: Option<String>,
4803    ) -> Result<()> {
4804        self.provider_config_for_mut(identity)?.model = model;
4805        // A deliberate model-only preparation keeps the canonicalizer's root
4806        // origin, but yields a new captured generation. Old snapshots refuse
4807        // the changed content. Endpoint/auth mutations never rebind this proof.
4808        if identity.legacy_root_custom_generation.is_some() {
4809            self.legacy_root_custom_generation = self.legacy_root_custom_table_generation();
4810        }
4811        Ok(())
4812    }
4813
4814    /// Apply a runtime endpoint override to the route's own table.
4815    pub fn set_provider_base_url_override(
4816        &mut self,
4817        identity: &ProviderIdentity,
4818        base_url: Option<String>,
4819    ) -> Result<()> {
4820        self.provider_config_for_mut(identity)?.base_url = base_url;
4821        Ok(())
4822    }
4823
4824    /// Apply an in-memory credential update to the route's own table.
4825    pub fn set_provider_api_key_override(
4826        &mut self,
4827        identity: &ProviderIdentity,
4828        api_key: Option<String>,
4829    ) -> Result<()> {
4830        self.provider_config_for_mut(identity)?.api_key = api_key;
4831        Ok(())
4832    }
4833
4834    /// Mirror a successful native xAI login into the live route config.
4835    /// Codewhale-owned OAuth storage supersedes any dormant Grok CLI consent.
4836    pub(crate) fn mark_codewhale_owned_xai_oauth(&mut self, generation: String) -> Result<()> {
4837        let identity = self
4838            .builtin_provider_identity(ProviderKind::Xai)
4839            .map_err(anyhow::Error::msg)?;
4840        let entry = self.provider_config_for_mut(&identity)?;
4841        entry.auth_mode = Some("oauth".to_string());
4842        entry.oauth_credential_generation = Some(generation);
4843        entry.external_credentials = None;
4844        Ok(())
4845    }
4846
4847    /// Mirror a successful native ChatGPT PKCE login into the live Codex route.
4848    /// Codewhale-owned OAuth storage supersedes any dormant Codex CLI consent.
4849    pub(crate) fn mark_codewhale_owned_chatgpt_oauth(&mut self, generation: String) -> Result<()> {
4850        let identity = self
4851            .builtin_provider_identity(ProviderKind::OpenaiCodex)
4852            .map_err(anyhow::Error::msg)?;
4853        let entry = self.provider_config_for_mut(&identity)?;
4854        entry.auth_mode = Some("oauth".to_string());
4855        entry.oauth_credential_generation = Some(generation);
4856        entry.external_credentials = None;
4857        Ok(())
4858    }
4859
4860    pub fn clear_codewhale_owned_chatgpt_oauth(&mut self) -> Result<()> {
4861        let identity = self
4862            .builtin_provider_identity(ProviderKind::OpenaiCodex)
4863            .map_err(anyhow::Error::msg)?;
4864        let entry = self.provider_config_for_mut(&identity)?;
4865        if entry
4866            .oauth_credential_generation
4867            .as_deref()
4868            .is_some_and(codewhale_config::is_valid_chatgpt_oauth_generation)
4869        {
4870            entry.oauth_credential_generation = None;
4871            if entry.auth_mode.as_deref() == Some("oauth") {
4872                entry.auth_mode = None;
4873            }
4874        }
4875        Ok(())
4876    }
4877
4878    /// Refresh only model-provider route material from a newly loaded disk
4879    /// snapshot. The receiver is the already-effective interactive Config,
4880    /// including CLI feature toggles and workspace/project permission overlays;
4881    /// replacing it wholesale during `/load` could silently loosen those
4882    /// controls. Provider tables carry their endpoint, auth, headers, TLS,
4883    /// model-passthrough, and per-route limits as one atomic registry.
4884    pub fn refresh_provider_routes_from(&mut self, fresh: &Self) {
4885        self.custom_models.clone_from(&fresh.custom_models);
4886        self.provider.clone_from(&fresh.provider);
4887        self.http_headers.clone_from(&fresh.http_headers);
4888        self.default_text_model
4889            .clone_from(&fresh.default_text_model);
4890        self.legacy_model.clone_from(&fresh.legacy_model);
4891        self.remembered_selection_scope = fresh.remembered_selection_scope;
4892        self.route_preferences_version = fresh.route_preferences_version;
4893        self.environment_model_applied = fresh.environment_model_applied;
4894        self.auth_mode.clone_from(&fresh.auth_mode);
4895        self.fallback_providers
4896            .clone_from(&fresh.fallback_providers);
4897        self.retry.clone_from(&fresh.retry);
4898        self.providers.clone_from(&fresh.providers);
4899        self.base_url_env_receipt
4900            .clone_from(&fresh.base_url_env_receipt);
4901        self.legacy_root.clone_from(&fresh.legacy_root);
4902        self.legacy_root_custom_generation
4903            .clone_from(&fresh.legacy_root_custom_generation);
4904        self.reasoning_effort_inferred_from_legacy_alias =
4905            fresh.reasoning_effort_inferred_from_legacy_alias;
4906        self.migrated_deepseek_model_alias
4907            .clone_from(&fresh.migrated_deepseek_model_alias);
4908    }
4909
4910    /// Return the configured provider request concurrency cap.
4911    ///
4912    /// `None` means the client does not apply an extra in-flight request
4913    /// semaphore. Z.ai/GLM gets a conservative default because its SSE endpoint
4914    /// times out under sustained parallel stream opens well below the advertised
4915    /// service concurrency (#3496). Operators can raise it with
4916    /// `[providers.zai] max_concurrency = N`; `0` explicitly disables the
4917    /// client-side cap for that provider.
4918    #[must_use]
4919    pub fn provider_max_concurrency(&self, identity: &ProviderIdentity) -> Option<usize> {
4920        let provider = identity.provider;
4921        let configured = self
4922            .provider_config_for(identity)
4923            .and_then(|entry| entry.max_concurrency);
4924        match configured {
4925            Some(0) => None,
4926            Some(limit) => Some(limit.clamp(1, MAX_PROVIDER_REQUEST_CONCURRENCY)),
4927            None if provider == ProviderKind::Zai => Some(DEFAULT_ZAI_PROVIDER_MAX_CONCURRENCY),
4928            None => None,
4929        }
4930    }
4931
4932    pub fn provider_config(&self) -> Option<&ProviderConfig> {
4933        let identity = self.active_provider_identity().ok()?;
4934        self.provider_config_for(&identity)
4935    }
4936
4937    fn provider_config_string_with_runtime_fallback<F>(
4938        &self,
4939        identity: &ProviderIdentity,
4940        get: F,
4941    ) -> Option<String>
4942    where
4943        F: Fn(&ProviderConfig) -> Option<String>,
4944    {
4945        let provider = identity.provider;
4946        if let Some(value) = self.provider_config_for(identity).and_then(&get) {
4947            return Some(value);
4948        }
4949        if provider == ProviderKind::SiliconflowCN {
4950            return self
4951                .builtin_provider_identity(ProviderKind::Siliconflow)
4952                .ok()
4953                .as_ref()
4954                .and_then(|sibling| self.provider_config_for(sibling))
4955                .and_then(get);
4956        }
4957        None
4958    }
4959
4960    /// [`Config::provider_config_string_with_runtime_fallback`] for a route's
4961    /// endpoint or key. DeepSeek-CN also reads `[providers.deepseek]`: the two
4962    /// identities used to share the top-level `base_url` / `api_key`, which
4963    /// now live there (#6394). Only these two fields are shared — never the
4964    /// model — and never a DeepSeek value the environment addressed to the
4965    /// DeepSeek identity alone.
4966    pub(crate) fn provider_route_string_with_deepseek_fallback<F>(
4967        &self,
4968        identity: &ProviderIdentity,
4969        get: F,
4970    ) -> Option<String>
4971    where
4972        F: Fn(&ProviderConfig) -> Option<String>,
4973    {
4974        if let Some(value) = self.provider_config_string_with_runtime_fallback(identity, &get) {
4975            return Some(value);
4976        }
4977        if identity.key.as_str() == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id
4978            && !matches!(
4979                &self.base_url_env_receipt,
4980                BaseUrlEnvReceipt::Route(ProviderKind::Deepseek, key) if key == ProviderKind::Deepseek.as_str()
4981            )
4982        {
4983            return self
4984                .builtin_provider_identity(ProviderKind::Deepseek)
4985                .ok()
4986                .as_ref()
4987                .and_then(|sibling| self.provider_config_for(sibling))
4988                .and_then(get)
4989                .filter(|value| !value.trim().is_empty());
4990        }
4991        None
4992    }
4993
4994    #[must_use]
4995    pub fn insecure_skip_tls_verify(&self) -> bool {
4996        self.provider_config()
4997            .and_then(|provider| provider.insecure_skip_tls_verify)
4998            .unwrap_or(false)
4999    }
5000
5001    /// Per-provider consent to a plain-HTTP `base_url` (#5991). Loopback is
5002    /// always allowed without it; this covers named LAN/internal hosts the
5003    /// user explicitly trusts. Narrower than the env-var override, which
5004    /// applies to every provider in the process.
5005    #[must_use]
5006    pub fn allow_insecure_http(&self) -> bool {
5007        self.provider_config()
5008            .and_then(|provider| provider.allow_insecure_http)
5009            .unwrap_or(false)
5010    }
5011
5012    #[must_use]
5013    pub fn context_window_for_provider_config(&self, identity: &ProviderIdentity) -> Option<u32> {
5014        let provider = identity.provider;
5015        if let Some(window) = self
5016            .provider_config_for(identity)
5017            .and_then(|entry| entry.context_window)
5018            .filter(|window| *window > 0)
5019        {
5020            return Some(window);
5021        }
5022        if provider == ProviderKind::SiliconflowCN {
5023            return self
5024                .builtin_provider_identity(ProviderKind::Siliconflow)
5025                .ok()
5026                .as_ref()
5027                .and_then(|sibling| self.provider_config_for(sibling))
5028                .and_then(|entry| entry.context_window)
5029                .filter(|window| *window > 0);
5030        }
5031        None
5032    }
5033
5034    /// `[providers.<id>.model_context_windows]` for this provider, keyed by
5035    /// exact wire model id (#6108). Follows the same SiliconFlow CN sibling
5036    /// fallback as [`Self::context_window_for_provider_config`].
5037    #[must_use]
5038    pub fn model_context_windows_for(
5039        &self,
5040        identity: &ProviderIdentity,
5041    ) -> Option<&std::collections::BTreeMap<String, u32>> {
5042        let provider = identity.provider;
5043        let table = self
5044            .provider_config_for(identity)
5045            .and_then(|entry| entry.model_context_windows.as_ref())
5046            .filter(|table| !table.is_empty());
5047        if table.is_some() {
5048            return table;
5049        }
5050        if provider == ProviderKind::SiliconflowCN {
5051            return self
5052                .builtin_provider_identity(ProviderKind::Siliconflow)
5053                .ok()
5054                .as_ref()
5055                .and_then(|sibling| self.provider_config_for(sibling))
5056                .and_then(|entry| entry.model_context_windows.as_ref())
5057                .filter(|table| !table.is_empty());
5058        }
5059        None
5060    }
5061
5062    #[must_use]
5063    pub fn http_headers(&self) -> HashMap<String, String> {
5064        let Ok(identity) = self.active_provider_identity() else {
5065            return HashMap::new();
5066        };
5067        let mut headers = self.http_headers.clone().unwrap_or_default();
5068        if let Some(provider_headers) = self
5069            .provider_config_for(&identity)
5070            .and_then(|provider| provider.http_headers.as_ref())
5071        {
5072            headers.extend(provider_headers.clone());
5073        }
5074        headers.retain(|name, value| !name.trim().is_empty() && !value.trim().is_empty());
5075        if auth_mode_disables_api_key(self.auth_mode_for_provider(&identity).as_deref()) {
5076            headers.retain(|name, _| !codewhale_config::is_upstream_auth_header(name));
5077        }
5078        headers
5079    }
5080
5081    fn active_configured_model_id(&self) -> Option<&str> {
5082        let identity = self.active_provider_identity().ok()?;
5083        self.provider_config_for(&identity)
5084            .and_then(|entry| entry.model.as_deref())
5085            .map(str::trim)
5086            .filter(|model| !model.is_empty())
5087            .or_else(|| {
5088                self.default_text_model
5089                    .as_deref()
5090                    .map(str::trim)
5091                    .filter(|model| !model.is_empty())
5092            })
5093    }
5094
5095    /// Describe a first-party DeepSeek alias that was migrated for the active
5096    /// route. Custom endpoints retain ownership of the same model strings and
5097    /// must not receive DeepSeek's deprecation claim.
5098    pub fn active_deepseek_alias_deprecation(&self) -> Option<ModelAliasDeprecation> {
5099        let identity = self.active_provider_identity().ok()?;
5100        let provider = identity.provider;
5101
5102        if !matches!(
5103            provider,
5104            ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
5105        ) {
5106            return None;
5107        }
5108
5109        let alias = self
5110            .migrated_deepseek_model_alias
5111            .as_deref()
5112            .or_else(|| self.active_configured_model_id())?
5113            .trim()
5114            .to_ascii_lowercase();
5115        // A custom endpoint owns the same model strings, so DeepSeek's
5116        // retirement claim must not travel to it. Ask that question directly:
5117        // the previous proxy for it — "the wire id was rewritten" — also
5118        // excluded every id DeepSeek retires while still accepting, which is
5119        // exactly the V4 Pro case.
5120        let base_url = self.active_route_base_url();
5121        if base_url_is_custom_for_provider(provider, &base_url) {
5122            return None;
5123        }
5124
5125        deepseek_alias_deprecation(&alias)
5126    }
5127
5128    /// The root `default_text_model` alias is the *active* route's fallback.
5129    /// When a switch to `incoming` leaves a route that has no model leaf of its
5130    /// own and was actually resolving the alias, return that outgoing identity
5131    /// and value: the choice belongs to the outgoing route and must follow it
5132    /// onto its own leaf, rather than stay at the root where the incoming route
5133    /// would inherit it and the outgoing route would forget it (falling back to
5134    /// its catalog default on the way back). The alias is `default_text_model`
5135    /// or, when that is unset, the legacy root `model` it falls back to. A
5136    /// persisted writer that moves it clears both roots
5137    /// (`config_persistence::unset_root_model_aliases`); clearing only the
5138    /// first would resurrect the second on the incoming route after reload.
5139    pub fn root_model_alias_owned_by_outgoing(
5140        &self,
5141        incoming: &ProviderIdentity,
5142    ) -> Option<(ProviderIdentity, String)> {
5143        // `default_model` reads the legacy root `model` whenever
5144        // `default_text_model` is unset, so the effective alias is either one.
5145        let value = self
5146            .default_text_model
5147            .as_deref()
5148            .or(self.legacy_model.as_deref())?
5149            .trim();
5150        if value.is_empty()
5151            || value.eq_ignore_ascii_case("auto")
5152            || value.chars().any(char::is_control)
5153        {
5154            return None;
5155        }
5156        let outgoing = self.active_provider_identity().ok()?;
5157        // An unnamed custom route stores its model in the alias itself.
5158        if outgoing == *incoming
5159            || (outgoing.provider == ProviderKind::Custom && outgoing.persisted_id().is_none())
5160        {
5161            return None;
5162        }
5163        let mut scoped = self.clone();
5164        scoped.scope_to_provider_identity(&outgoing).ok()?;
5165        if scoped
5166            .provider_config_for(&outgoing)
5167            .and_then(|entry| entry.model.as_deref())
5168            .is_some()
5169        {
5170            return None;
5171        }
5172        (scoped.default_model() == value).then(|| (outgoing, value.to_string()))
5173    }
5174
5175    fn select_configured_model(
5176        &self,
5177        identity: &ProviderIdentity,
5178    ) -> codewhale_config::ConfiguredModelSelection {
5179        let provider = identity.provider;
5180        let base_url = self.base_url_for_route(identity);
5181        let auth_mode = self.auth_mode_for_provider(identity);
5182        let provider_model = self
5183            .provider_config_string_with_runtime_fallback(identity, |entry| entry.model.clone());
5184        let codex_preferred = || {
5185            crate::codex_model_roster::cached_roster_for(self)
5186                .preferred_model_id()
5187                .map(str::to_owned)
5188        };
5189        let descriptor_default = Some(identity.compatibility().map_or("", |row| row.default_model));
5190        codewhale_config::resolve_configured_model(&codewhale_config::ConfiguredModelInputs {
5191            provider,
5192            provider_identity: identity.key.as_str(),
5193            base_url: &base_url,
5194            auth_mode: auth_mode.as_deref(),
5195            cli_model: None,
5196            env_model: None,
5197            provider_model: provider_model.as_deref(),
5198            default_text_model: self.default_text_model.as_deref(),
5199            legacy_root_model: self.legacy_model.as_deref(),
5200            custom_models: self.custom_models.as_deref(),
5201            codex_preferred_model: (provider == ProviderKind::OpenaiCodex)
5202                .then_some(&codex_preferred as &dyn Fn() -> Option<String>),
5203            descriptor_default,
5204        })
5205    }
5206
5207    #[must_use]
5208    pub fn default_model(&self) -> String {
5209        let Ok(identity) = self.active_provider_identity() else {
5210            return String::new();
5211        };
5212        self.select_configured_model(&identity)
5213            .resolved
5214            .map_or_else(|_| String::new(), |resolved| resolved.wire_id)
5215    }
5216
5217    #[must_use]
5218    pub fn default_model_uses_root_default_text_model(&self) -> bool {
5219        let Ok(identity) = self.active_provider_identity() else {
5220            return false;
5221        };
5222        let selection = self.select_configured_model(&identity);
5223        selection.resolved.is_ok()
5224            && matches!(
5225                selection.source,
5226                codewhale_config::ModelSource::RootDefaultTextModel
5227                    | codewhale_config::ModelSource::RootModel
5228            )
5229    }
5230
5231    #[must_use]
5232    pub fn configured_model_error(&self) -> Option<String> {
5233        let identity = self.active_provider_identity().ok()?;
5234        let selection = self.select_configured_model(&identity);
5235        match selection.resolved {
5236            Ok(_) => None,
5237            Err(_) if !selection.source.is_explicit() && selection.raw.is_empty() => None,
5238            Err(error) => Some(codewhale_config::format_configured_model_error(
5239                identity.key.as_str(),
5240                &selection.raw,
5241                &error,
5242            )),
5243        }
5244    }
5245
5246    /// Return the configured API base URL (normalized) for the selected route.
5247    #[must_use]
5248    pub fn active_route_base_url(&self) -> String {
5249        self.active_provider_identity()
5250            .map(|identity| self.base_url_for_route(&identity))
5251            .unwrap_or_default()
5252    }
5253
5254    /// Resolve `provider`'s endpoint from the layers that provider actually
5255    /// owns, in precedence order:
5256    ///
5257    /// 1. its own `[providers.<table>]` entry (including in-memory runtime
5258    ///    overrides; DeepSeek-CN also reads `[providers.deepseek]`). A legacy
5259    ///    top-level `base_url` was moved into its owner's table on parse
5260    ///    (#6394);
5261    /// 2. its provider-specific environment contract (`MOONSHOT_BASE_URL`,
5262    ///    `OPENAI_BASE_URL`, ...), which names exactly one provider and is
5263    ///    therefore sound to read for a route that is not the session's;
5264    /// 3. the generic `CODEWHALE_BASE_URL` / `DEEPSEEK_BASE_URL` override, but
5265    ///    only when this config is still the route that override selected;
5266    /// 4. the provider's canonical default endpoint.
5267    ///
5268    /// Step 3 is why this is identity-aware instead of a bare env read.
5269    /// `CODEWHALE_BASE_URL` is documented as "base URL for the active
5270    /// provider", and `apply_env_overrides` writes it onto exactly one
5271    /// provider entry. Every cross-provider construction seam — a pinned
5272    /// subagent/fleet child, the per-turn auto-router, tool routing, a picker
5273    /// preview — works by cloning the session config and re-pointing
5274    /// `provider`, so without the ownership check a Moonshot/Z.ai/MiniMax
5275    /// child in a DeepSeek session would silently inherit the DeepSeek host
5276    /// and dispatch a pinned model to the wrong vendor.
5277    pub fn base_url_for_route(&self, identity: &ProviderIdentity) -> String {
5278        if self.verify_provider_identity(identity).is_err() {
5279            return String::new();
5280        }
5281        let provider = identity.provider;
5282        let provider_base = if provider == ProviderKind::Custom {
5283            self.provider_config_for(identity)
5284                .and_then(|entry| entry.base_url.clone())
5285        } else {
5286            self.provider_route_string_with_deepseek_fallback(identity, |entry| {
5287                entry.base_url.clone()
5288            })
5289        };
5290        // A provider-scoped endpoint variable names exactly one provider, so it
5291        // resolves for the selected identity whether or not that identity is
5292        // the session route. `apply_env_overrides` only merges these into the
5293        // active provider's table, which is why a non-active route has to read
5294        // them here instead of relying on the merged config.
5295        let configured_base_url =
5296            provider_base.or_else(|| provider_env_base_url_override(provider));
5297        let entry = self.provider_config_for(identity);
5298        let mode = entry.and_then(|e| e.mode.as_deref());
5299        let wire = entry.and_then(|e| e.wire.as_deref());
5300        let base = if provider == ProviderKind::XiaomiMimo {
5301            let config_api_key = entry.and_then(|e| e.api_key.as_deref()).filter(|value| {
5302                classify_config_api_key_value(value) == ConfigApiKeyValueKind::Literal
5303            });
5304            let env_api_key =
5305                xiaomi_mimo_env_api_key_for_runtime(mode, configured_base_url.as_deref());
5306            let api_key = config_api_key.or(env_api_key.as_deref());
5307            resolve_xiaomi_mimo_base_url(configured_base_url, api_key, mode)
5308        } else if matches!(
5309            provider,
5310            ProviderKind::ModelstudioTokenPlan
5311                | ProviderKind::ModelstudioTokenPlanAnthropic
5312                | ProviderKind::ModelstudioCodingPlan
5313                | ProviderKind::ModelstudioCodingPlanAnthropic
5314        ) {
5315            resolve_modelstudio_base_url_for_tui(configured_base_url, provider, mode, wire)
5316        } else if matches!(
5317            provider,
5318            ProviderKind::Minimax | ProviderKind::MinimaxAnthropic
5319        ) {
5320            resolve_minimax_base_url_for_tui(configured_base_url, provider, wire)
5321        } else if matches!(
5322            provider,
5323            ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
5324        ) {
5325            resolve_deepseek_base_url_for_tui(configured_base_url, provider, wire)
5326        } else {
5327            configured_base_url
5328                .or_else(|| self.route_owned_generic_env_base_url(identity))
5329                .unwrap_or_else(|| {
5330                    // Membership-token routing is an execution fact, not a
5331                    // provider metadata default. All other defaults use the
5332                    // same descriptor-backed facade as every caller.
5333                    if provider == ProviderKind::Moonshot
5334                        && self
5335                            .provider_config_for(identity)
5336                            .is_some_and(provider_config_uses_kimi_imported_token)
5337                    {
5338                        DEFAULT_KIMI_CODE_BASE_URL
5339                    } else {
5340                        identity.compatibility().map_or("", |row| row.base_url)
5341                    }
5342                    .to_string()
5343                })
5344        };
5345        normalize_base_url(&base)
5346    }
5347
5348    /// The generic `CODEWHALE_BASE_URL` / `DEEPSEEK_BASE_URL` override, but
5349    /// only for the route that override actually selected.
5350    ///
5351    /// [`apply_env_overrides`] records the owning `(provider, identity)` in
5352    /// [`Config::base_url_env_receipt`] at load time and writes the value onto
5353    /// that provider's own entry. A config later re-pointed at another identity
5354    /// is a different route: it must fall through to that provider's own
5355    /// default rather than borrow the session host.
5356    fn route_owned_generic_env_base_url(&self, identity: &ProviderIdentity) -> Option<String> {
5357        match &self.base_url_env_receipt {
5358            BaseUrlEnvReceipt::Unrecorded => env_base_url_override(),
5359            BaseUrlEnvReceipt::NoOwner => None,
5360            BaseUrlEnvReceipt::Route(..) => self
5361                .base_url_env_receipt
5362                .owns(identity.provider, identity.key.as_str())
5363                .then(env_base_url_override)
5364                .flatten(),
5365        }
5366    }
5367
5368    /// Resolve a named custom provider's table by explicit identity.
5369    ///
5370    /// Fails closed: an empty identity, or one that names no
5371    /// `[providers.<name>]` custom table, resolves to nothing instead of
5372    /// falling back to whichever custom route the session is currently on.
5373    #[cfg(test)]
5374    fn custom_provider_entry_for_identity(&self, identity: &str) -> Option<&ProviderConfig> {
5375        let key = identity.trim();
5376        if key.is_empty() {
5377            return None;
5378        }
5379        self.providers.as_ref()?.custom_provider_config(key)
5380    }
5381
5382    fn active_provider_preserves_custom_base_url_model(&self) -> bool {
5383        self.active_provider_identity()
5384            .is_ok_and(|identity| self.provider_uses_custom_endpoint(&identity))
5385    }
5386
5387    /// Whether `provider`'s effective endpoint is a custom host rather than its
5388    /// shipped one. Resolved through the same identity-aware resolver the
5389    /// client is built from, so this predicate cannot disagree with the URL the
5390    /// request will actually be sent to.
5391    pub fn provider_uses_custom_endpoint(&self, identity: &ProviderIdentity) -> bool {
5392        let provider = identity.provider;
5393        provider_preserves_custom_base_url_model(provider, &self.base_url_for_route(identity))
5394    }
5395
5396    /// Whether file-owned credential slots are bound to `provider`'s
5397    /// effective endpoint.
5398    ///
5399    /// The environment can replace the active route's base URL after config
5400    /// parsing. In that case, a root/provider `api_key` or configured
5401    /// `api_key_env` still belongs to the file-owned endpoint and must not
5402    /// follow a newly selected custom host. An explicit source-marked CLI key
5403    /// remains a deliberate endpoint override and is handled before this
5404    /// predicate by the runtime resolver.
5405    pub fn config_credentials_are_bound_to_provider_endpoint(
5406        &self,
5407        identity: &ProviderIdentity,
5408    ) -> bool {
5409        !self
5410            .active_provider_identity()
5411            .is_ok_and(|active| active == *identity)
5412            || !self.active_base_url_is_environment_owned(identity)
5413            || !self.provider_uses_custom_endpoint(identity)
5414    }
5415
5416    fn active_base_url_is_environment_owned(&self, identity: &ProviderIdentity) -> bool {
5417        let provider = identity.provider;
5418        if !self
5419            .active_provider_identity()
5420            .is_ok_and(|active| active == *identity)
5421        {
5422            return false;
5423        }
5424        let route_key = identity.key.as_str();
5425        if self.base_url_env_receipt.owns(provider, route_key) {
5426            return true;
5427        }
5428
5429        // Below the receipt, the environment can still supply the endpoint for
5430        // a route that has none of its own. A provider-scoped variable names
5431        // exactly one provider, so it always owns that route's endpoint. The
5432        // generic variable only does so while no receipt has said otherwise —
5433        // once a receipt exists and does not name this route,
5434        // `route_owned_generic_env_base_url` refuses it, so claiming env
5435        // ownership here would contradict the URL actually resolved.
5436        if self.configured_base_url_for_provider(identity).is_some() {
5437            return false;
5438        }
5439        provider_env_base_url_override(provider).is_some()
5440            || (matches!(self.base_url_env_receipt, BaseUrlEnvReceipt::Unrecorded)
5441                && env_base_url_override().is_some())
5442    }
5443
5444    /// The active route names its own endpoint: its `[providers.<name>]`
5445    /// `base_url` (where a legacy top-level `base_url` lands too) or an
5446    /// environment endpoint override. An endpoint is a configured route even
5447    /// without a model or a working key.
5448    pub fn active_route_endpoint_configured(&self) -> bool {
5449        self.active_provider_identity().is_ok_and(|identity| {
5450            self.configured_base_url_for_provider(&identity).is_some()
5451                || self.active_base_url_is_environment_owned(&identity)
5452        })
5453    }
5454
5455    /// The endpoint `provider` owns through a file or in-memory layer, before
5456    /// the environment layer is consulted: its own `[providers.<name>]` table
5457    /// (DeepSeek-CN also reading `[providers.deepseek]`). There is no
5458    /// top-level endpoint any more (#6394).
5459    fn configured_base_url_for_provider(&self, identity: &ProviderIdentity) -> Option<String> {
5460        self.provider_route_string_with_deepseek_fallback(identity, |entry| entry.base_url.clone())
5461            .filter(|base| !base.trim().is_empty())
5462    }
5463
5464    /// Whether model ids for `provider` belong to the configured endpoint.
5465    ///
5466    /// Every route — active or pinned — is judged on the endpoint it will
5467    /// actually be dispatched to, so a pinned child cannot canonicalize model
5468    /// ids for a host that owns its own namespace (or pass through ids on a
5469    /// route that resolves to a canonical endpoint). The resolver behind
5470    /// [`Config::provider_uses_custom_endpoint`] is identity-aware, so this no
5471    /// longer risks attributing the session's endpoint to another provider.
5472    pub fn model_ids_pass_through_for_provider(&self, identity: &ProviderIdentity) -> bool {
5473        let provider = identity.provider;
5474        codewhale_config::descriptors::provider_passes_model_through(provider)
5475            || self.provider_uses_custom_endpoint(identity)
5476    }
5477
5478    pub fn model_ids_pass_through(&self) -> bool {
5479        self.active_provider_identity()
5480            .is_ok_and(|identity| self.model_ids_pass_through_for_provider(&identity))
5481    }
5482
5483    pub fn auth_mode_for_provider(&self, identity: &ProviderIdentity) -> Option<String> {
5484        self.provider_config_string_with_runtime_fallback(identity, |entry| entry.auth_mode.clone())
5485            .or_else(|| {
5486                (self
5487                    .active_provider_identity()
5488                    .is_ok_and(|active| active == *identity))
5489                .then(|| self.auth_mode.clone())
5490                .flatten()
5491            })
5492    }
5493
5494    /// Mint a read capability for the exact external credential path selected
5495    /// when consent was granted.
5496    ///
5497    /// Path resolution itself is side-effect free. The returned capability is
5498    /// required by every external credential adapter before it may stat or
5499    /// read the selected file. `suggested_path` is used only in disabled-mode
5500    /// guidance; an existing grant remains pinned to its persisted path even
5501    /// if ambient CLI-home environment variables change later.
5502    pub(crate) fn external_credential_read_grant(
5503        &self,
5504        identity: &ProviderIdentity,
5505        source: codewhale_config::ExternalCredentialSource,
5506        suggested_path: &Path,
5507    ) -> Result<codewhale_config::ExternalCredentialReadGrant> {
5508        anyhow::ensure!(
5509            identity.key.as_str() != codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id,
5510            "external credentials are unsupported for the legacy DeepSeek China route"
5511        );
5512        let provider = identity.provider;
5513        if !self
5514            .active_provider_identity()
5515            .is_ok_and(|active| active == *identity)
5516        {
5517            anyhow::bail!(
5518                "external credential access for {} is dormant until that provider is explicitly selected",
5519                provider.provider().display_name()
5520            );
5521        }
5522        let kind = provider;
5523        let consent = self
5524            .provider_config_for(identity)
5525            .and_then(|entry| entry.external_credentials.as_ref())
5526            .with_context(|| {
5527                format!(
5528                    "External credentials owned by {} are disabled for {}. To allow read-only access to this exact file, run:\n  codewhale auth external-consent --provider {} --mode read-only --path {}",
5529                    source.as_str(),
5530                    provider.provider().display_name(),
5531                    kind.as_str(),
5532                    codewhale_config::quote_os_path(suggested_path)
5533                )
5534            })?;
5535        consent
5536            .read_grant(kind, source, &consent.path)
5537            .map_err(|error| {
5538                anyhow::anyhow!(
5539                    "external credential consent for {}: {error}",
5540                    provider.provider().display_name()
5541                )
5542            })
5543    }
5544
5545    /// Whether a structurally valid read-only consent record exists for an
5546    /// external credential source. This never stats or reads the selected
5547    /// file and never mints the capability required to do so.
5548    pub fn external_credential_read_consent_configured(
5549        &self,
5550        identity: &ProviderIdentity,
5551        source: codewhale_config::ExternalCredentialSource,
5552    ) -> bool {
5553        if identity.key.as_str() == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id {
5554            return false;
5555        }
5556        let provider = identity.provider;
5557        let kind = provider;
5558        let Some(consent) = self
5559            .provider_config_for(identity)
5560            .and_then(|entry| entry.external_credentials.as_ref())
5561        else {
5562            return false;
5563        };
5564        consent
5565            .validate_read_scope(kind, source, &consent.path)
5566            .is_ok()
5567    }
5568
5569    pub fn should_skip_secret_store_for_provider(&self, identity: &ProviderIdentity) -> bool {
5570        if self.verify_provider_identity(identity).is_err() {
5571            return true;
5572        }
5573        let provider = identity.provider;
5574        // The CLI's durable credential namespace has one compatibility slot
5575        // named `custom`; it cannot identify an arbitrary named custom route.
5576        // Reusing that slot for `[providers.<name>]` could send endpoint A's
5577        // bearer token to endpoint B. Named routes therefore resolve only
5578        // their own config/auth/api_key_env sources. The generic slot remains
5579        // valid solely for the literal `custom` route (whose older top-level
5580        // endpoint now lives in `[providers.custom]`, #6394).
5581        if provider == ProviderKind::Custom
5582            && !identity
5583                .key
5584                .as_str()
5585                .eq_ignore_ascii_case(ProviderKind::Custom.as_str())
5586        {
5587            return true;
5588        }
5589
5590        let auth_mode = self.auth_mode_for_provider(identity);
5591        if auth_mode_disables_api_key(auth_mode.as_deref()) {
5592            return true;
5593        }
5594        if self.provider_uses_custom_endpoint(identity) {
5595            // An explicitly authenticated loopback runtime may intentionally
5596            // use the durable provider slot (for example a protected local
5597            // vLLM server). Remote custom endpoints must never inherit an
5598            // official provider's saved credential.
5599            let explicitly_authenticated_loopback = self
5600                .active_provider_identity()
5601                .is_ok_and(|active| active == *identity)
5602                && auth_mode_requires_api_key(auth_mode.as_deref())
5603                && base_url_uses_local_host(&self.active_route_base_url());
5604            if !explicitly_authenticated_loopback {
5605                return true;
5606            }
5607        }
5608        if auth_mode_requires_api_key(auth_mode.as_deref()) {
5609            return false;
5610        }
5611
5612        // The Codewhale API is authenticated on every origin it is allowed to
5613        // reach. A loopback `CODEWHALE_API_BASE` is a test origin for that
5614        // same contract, not a keyless local runtime, so it must not suppress
5615        // the route's saved or exported key.
5616        if provider == ProviderKind::Codewhale {
5617            return false;
5618        }
5619
5620        provider_route_is_keyless_self_hosted(provider, &self.base_url_for_route(identity))
5621            || (self
5622                .active_provider_identity()
5623                .is_ok_and(|active| active == *identity)
5624                && base_url_uses_local_host(&self.active_route_base_url()))
5625    }
5626
5627    pub fn bind_account_model_owner(&mut self, owner: &str) -> Result<()> {
5628        anyhow::ensure!(
5629            !owner.is_empty()
5630                && owner.len() <= 240
5631                && !owner.chars().any(|c| c.is_control() || c.is_whitespace()),
5632            "Invalid account model owner"
5633        );
5634        let access = self
5635            .account_model_access
5636            .read()
5637            .clone()
5638            .context("Connect account model access before running the Codewhale agent")?;
5639        self.account_model_access = std::sync::Arc::new(parking_lot::RwLock::new(Some(access)));
5640        self.required_account_model_owner = Some(owner.to_string());
5641        let identity = self
5642            .resolve_persisted_provider_identity(Some("codewhale"), Some("codewhale"))
5643            .map_err(anyhow::Error::msg)?;
5644        anyhow::ensure!(
5645            self.account_model_api_key(&identity).is_some(),
5646            "Codewhale agent model access must belong to the signed-in account"
5647        );
5648        Ok(())
5649    }
5650
5651    pub fn session_provider_api_key(&self, identity: &ProviderIdentity) -> Option<String> {
5652        self.verify_provider_identity(identity).ok()?;
5653        if self.should_skip_secret_store_for_provider(identity) {
5654            return None;
5655        }
5656        let endpoint = self.base_url_for_route(identity);
5657        self.session_provider_keys
5658            .read()
5659            .get(identity)
5660            .filter(|(bound_endpoint, _)| bound_endpoint == &endpoint)
5661            .map(|(_, credential)| credential.expose_secret().to_string())
5662    }
5663
5664    pub fn preserve_runtime_credentials(&mut self, current: &Self) {
5665        self.account_model_access = current.account_model_access.clone();
5666        self.session_provider_keys = current.session_provider_keys.clone();
5667        self.session_provider_keys_only = current.session_provider_keys_only;
5668    }
5669
5670    pub fn retain_compatible_session_keys(&self) {
5671        self.session_provider_keys
5672            .write()
5673            .retain(|identity, (endpoint, _)| {
5674                self.verify_provider_identity(identity).is_ok()
5675                    && !self.should_skip_secret_store_for_provider(identity)
5676                    && self.base_url_for_route(identity) == *endpoint
5677            });
5678    }
5679
5680    pub fn session_policy_without_key(
5681        &self,
5682        identity: &ProviderIdentity,
5683    ) -> Option<crate::credentials::CredentialSource> {
5684        use crate::credentials::{CredentialProbe, CredentialSource};
5685        if !self.session_provider_keys_only {
5686            return None;
5687        }
5688        let mode = self.auth_mode_for_provider(identity);
5689        if auth_mode_disables_api_key(mode.as_deref()) {
5690            return Some(CredentialSource::AuthModeNone);
5691        }
5692        let endpoint = self.base_url_for_route(identity);
5693        if identity.provider != ProviderKind::Codewhale
5694            && !auth_mode_requires_api_key(mode.as_deref())
5695            && !provider_uses_oauth_credentials(self, identity)
5696            && !self
5697                .provider_config_for(identity)
5698                .is_some_and(|entry| entry.oauth.is_some())
5699            && (provider_route_is_keyless_self_hosted(identity.provider, &endpoint)
5700                || base_url_uses_local_host(&endpoint))
5701        {
5702            return Some(CredentialSource::KeylessRoute { base_url: endpoint });
5703        }
5704        Some(CredentialSource::Missing {
5705            probed: vec![CredentialProbe::with_fix(
5706                "session-only provider key",
5707                "connect a session key to this Engine; stored credentials are disabled",
5708            )],
5709        })
5710    }
5711
5712    pub fn account_model_api_key(&self, identity: &ProviderIdentity) -> Option<String> {
5713        self.account_model_key_and_owner(identity)
5714            .map(|(key, _)| key)
5715    }
5716
5717    fn account_model_key_and_owner(&self, identity: &ProviderIdentity) -> Option<(String, String)> {
5718        let provider = identity.provider;
5719        // Exact endpoint binding, including path. A custom Codewhale route
5720        // must never inherit the account's credential, even on the same host.
5721        if provider != ProviderKind::Codewhale
5722            || self.base_url_for_route(identity).trim_end_matches('/') != DEFAULT_CODEWHALE_BASE_URL
5723            || auth_mode_disables_api_key(self.auth_mode_for_provider(identity).as_deref())
5724            || self
5725                .provider_config_for(identity)
5726                .is_some_and(|entry| entry.auth.is_some() || entry.api_key_env.is_some())
5727        {
5728            return None;
5729        }
5730        if std::env::var(codewhale_secrets::account::ACCOUNT_API_BASE_ENV)
5731            .ok()
5732            .filter(|base| !base.trim().is_empty())
5733            .is_some_and(|base| {
5734                base.trim().trim_end_matches('/')
5735                    != codewhale_secrets::account::DEFAULT_ACCOUNT_API_BASE
5736            })
5737        {
5738            return None;
5739        }
5740        let access = self.account_model_access.read().clone();
5741        let profile = self.account_profile.as_deref();
5742        if access.as_ref().is_some_and(|access| {
5743            codewhale_secrets::account::normalize_account_profile(access.profile.as_deref())
5744                != codewhale_secrets::account::normalize_account_profile(profile)
5745        }) {
5746            return None;
5747        }
5748        // Check the shared session again at use, so a late install cannot
5749        // resurrect a session removed by another local process.
5750        let secrets = codewhale_secrets::account::secure_account_session_secrets().ok()?;
5751        let snapshot = codewhale_secrets::account::AccountSessionStore::new(
5752            secrets,
5753            profile,
5754            codewhale_secrets::account::DEFAULT_ACCOUNT_API_BASE,
5755        )
5756        .snapshot()
5757        .ok()?;
5758        let now = chrono::Utc::now();
5759        let account = snapshot.runtime_info_at(now).ok()?;
5760        if access
5761            .as_ref()
5762            .is_some_and(|access| account.session_id.as_deref() != Some(access.session_id.as_str()))
5763        {
5764            return None;
5765        }
5766        if self
5767            .required_account_model_owner
5768            .as_ref()
5769            .is_some_and(|owner| account.account_id.as_ref() != Some(owner))
5770        {
5771            return None;
5772        }
5773        if !self.session_provider_keys_only
5774            && matches!(
5775                account.state,
5776                codewhale_secrets::account::AccountSessionState::Authenticated
5777                    | codewhale_secrets::account::AccountSessionState::OfflineCached
5778            )
5779            && let Some(cached) = snapshot.device_access().ok()?
5780            && cached.expires_at > now.timestamp()
5781            && account.account_id.as_deref() == Some(cached.account_id.as_str())
5782            && account.session_id.as_deref() == Some(cached.session_id.as_str())
5783        {
5784            return Some((cached.credential, cached.account_id));
5785        }
5786        let access = access.filter(|access| access.expires_at > now.timestamp())?;
5787        let owner = account.account_id?;
5788        (account.state == codewhale_secrets::account::AccountSessionState::Authenticated
5789            && account.session_id.as_deref() == Some(access.session_id.as_str()))
5790        .then(|| (access.credential.expose_secret().to_string(), owner))
5791    }
5792
5793    /// Prove a current health-cache credential generation without commands,
5794    /// refresh, secret-store reads, or external credential files. Opaque sources
5795    /// deliberately remain unchecked; this is not a credential resolver.
5796    pub fn readonly_health_credential_generation(
5797        &self,
5798        identity: &ProviderIdentity,
5799    ) -> Option<codewhale_config::credentials::CredentialGeneration> {
5800        if self.required_account_model_owner.is_some() {
5801            return None;
5802        }
5803        self.verify_provider_identity(identity).ok()?;
5804        let mut scoped = self.clone();
5805        scoped.scope_to_provider_identity(identity).ok()?;
5806        let endpoint = scoped.base_url_for_route(identity);
5807        let mode = scoped.auth_mode_for_provider(identity);
5808        let generation = |value: &str| {
5809            codewhale_config::credentials::CredentialGeneration::derive(
5810                &endpoint,
5811                &codewhale_secrets::normalize_api_key(value),
5812            )
5813        };
5814        if let Some(key) = scoped.session_provider_api_key(identity) {
5815            return Some(generation(&key));
5816        }
5817        if let Some(source) = scoped.session_policy_without_key(identity) {
5818            return match source {
5819                crate::credentials::CredentialSource::AuthModeNone
5820                | crate::credentials::CredentialSource::KeylessRoute { .. } => Some(generation("")),
5821                _ => None,
5822            };
5823        }
5824        if auth_mode_disables_api_key(mode.as_deref()) {
5825            return Some(generation(""));
5826        }
5827        if provider_uses_oauth_credentials(&scoped, identity)
5828            || scoped
5829                .provider_config_for(identity)
5830                .is_some_and(|entry| entry.auth.is_some())
5831        {
5832            return None;
5833        }
5834        if let Some(key) = explicit_cli_api_key_override() {
5835            return Some(generation(&key));
5836        }
5837        // The legacy CLI source marker can make DeepSeek prefer an ambient
5838        // provider key before a saved literal. Without the captured CLI key,
5839        // this read-only cache projection cannot prove that precedence.
5840        if identity.provider == ProviderKind::Deepseek
5841            && cli_api_key_source().as_deref() == Some("cli")
5842        {
5843            return None;
5844        }
5845        if scoped.config_credentials_are_bound_to_provider_endpoint(identity)
5846            && let Some(key) = scoped
5847                .provider_route_string_with_deepseek_fallback(identity, |entry| {
5848                    entry.api_key.clone()
5849                })
5850            && classify_config_api_key_value(&key) == ConfigApiKeyValueKind::Literal
5851        {
5852            return Some(generation(&key));
5853        }
5854        if let Some(key) = provider_config_env_api_key(&scoped, identity) {
5855            return Some(generation(&key));
5856        }
5857        // An unresolved named binding cannot fall through to unauthenticated local.
5858        if bound_provider_api_key_env_name(&scoped, identity).is_some() {
5859            return None;
5860        }
5861        if !auth_mode_requires_api_key(mode.as_deref())
5862            && scoped.should_skip_secret_store_for_provider(identity)
5863            && identity.provider != ProviderKind::Codewhale
5864            && scoped
5865                .provider_config_for(identity)
5866                .is_none_or(|entry| entry.external_credentials.is_none())
5867            && (provider_route_is_keyless_self_hosted(identity.provider, &endpoint)
5868                || base_url_uses_local_host(&endpoint))
5869        {
5870            return Some(generation(""));
5871        }
5872        None
5873    }
5874
5875    /// Read the API key.
5876    ///
5877    /// Precedence: **required account owner → session key → route-specific explicitly consented OAuth token → source-marked explicit CLI key →
5878    /// provider/root config → configured custom-provider environment →
5879    /// secret store → ambient provider environment**.
5880    ///
5881    /// An in-memory provider-table key is only honored when the user
5882    /// explicitly set the field (not the legacy `API_KEYRING_SENTINEL`
5883    /// placeholder, not empty whitespace).
5884    pub fn active_route_api_key(&self) -> Result<String> {
5885        self.active_route_api_key_with_source().map(|(key, _)| key)
5886    }
5887
5888    /// The active route's key with a display label naming its source
5889    /// (secret store slot, config file, env var name, CLI, OAuth, …) for
5890    /// authentication diagnostics. The key is normalized with
5891    /// [`codewhale_secrets::normalize_api_key`] (#6528).
5892    pub fn active_route_api_key_with_source(&self) -> Result<(String, String)> {
5893        self.active_route_api_key_with_secret_store_mode(false)
5894    }
5895
5896    pub fn active_route_api_key_with_owner(&self) -> Result<(ResolvedApiKey, Option<String>)> {
5897        let mut owner = None;
5898        let key = self.active_route_api_key_with_owner_and_mode(false, &mut owner)?;
5899        Ok((key, owner))
5900    }
5901
5902    /// The resolver's xAI OAuth step: `Some` when the active route is xAI on
5903    /// the official endpoint with `auth_mode = "oauth"` and a usable sign-in
5904    /// exists (configured owned generation, legacy owned file, or consented
5905    /// Grok CLI import), holding that sign-in's credentials.
5906    pub fn xai_oauth_route_credentials(
5907        &self,
5908    ) -> Option<Result<crate::oauth::OwnedOAuthCredentials>> {
5909        let identity = self.active_provider_identity().ok()?;
5910        if self.required_account_model_owner.is_some()
5911            || self.session_provider_keys_only
5912            || self.session_provider_api_key(&identity).is_some()
5913        {
5914            return None;
5915        }
5916        let provider = identity.provider;
5917
5918        let selected = provider == ProviderKind::Xai
5919            && !self.provider_uses_custom_endpoint(&identity)
5920            && self
5921                .provider_config_for(&identity)
5922                .is_some_and(provider_config_uses_xai_oauth)
5923            && crate::oauth::credentials_present(crate::oauth::OAuthProvider::Xai, self);
5924        selected.then(|| crate::oauth::get_xai_credentials(self))
5925    }
5926
5927    /// Resolve an API key for a diagnostic without migrating a legacy secret
5928    /// store or opening a write-capable secret backend.
5929    ///
5930    /// This retains ordinary credential precedence, including a legacy
5931    /// file-backed secret as a fallback, but it must only be used by static
5932    /// diagnostic/reporting paths. Normal runtime and authentication paths use
5933    /// [`Self::active_route_api_key`] and preserve their existing migration
5934    /// behavior.
5935    pub fn active_route_api_key_read_only(&self) -> Result<String> {
5936        self.active_route_api_key_with_secret_store_mode(true)
5937            .map(|(key, _)| key)
5938    }
5939
5940    fn active_route_api_key_with_secret_store_mode(
5941        &self,
5942        read_only: bool,
5943    ) -> Result<(String, String)> {
5944        self.active_route_api_key_with_owner_and_mode(read_only, &mut None)
5945    }
5946
5947    fn active_route_api_key_with_owner_and_mode(
5948        &self,
5949        read_only: bool,
5950        account_owner: &mut Option<String>,
5951    ) -> Result<ResolvedApiKey> {
5952        self.resolve_active_route_api_key(read_only, account_owner)
5953            .map(|(key, source)| (codewhale_secrets::normalize_api_key(&key), source))
5954    }
5955
5956    /// Clone this route with a diagnostic-only credential in its in-memory
5957    /// provider slot.
5958    ///
5959    /// A live `doctor` probe still needs to construct the ordinary client. By
5960    /// materializing the credential on an isolated clone first, that client
5961    /// never reaches the normal migrating secret-store resolver while it is
5962    /// only checking connectivity. The clone is process-local and is never
5963    /// persisted.
5964    pub fn with_read_only_api_key_for_diagnostic(&self) -> Result<Self> {
5965        let identity = self
5966            .active_provider_identity()
5967            .map_err(anyhow::Error::msg)?;
5968
5969        let mut diagnostic = self.clone();
5970        if self.session_provider_keys_only
5971            || (self.required_account_model_owner.is_none()
5972                && self.session_provider_api_key(&identity).is_some())
5973        {
5974            return Ok(diagnostic);
5975        }
5976        if identity.provider == ProviderKind::Anthropic
5977            && self.auth_mode_for_provider(&identity).as_deref() == Some("oauth")
5978        {
5979            diagnostic.plugin_oauth_read_only = true;
5980            return Ok(diagnostic);
5981        }
5982        if identity.provider == ProviderKind::Custom
5983            && self
5984                .provider_config_for(&identity)
5985                .is_some_and(|entry| entry.oauth.is_some())
5986        {
5987            diagnostic.plugin_oauth_read_only = true;
5988            return Ok(diagnostic);
5989        }
5990        let api_key = self.active_route_api_key_read_only()?;
5991        diagnostic.set_provider_api_key_override(&identity, Some(api_key))?;
5992        Ok(diagnostic)
5993    }
5994
5995    /// The active route's key and a display label for where it came from
5996    /// (#6528). Callers go through [`Self::active_route_api_key_with_source`],
5997    /// which normalizes the key.
5998    fn resolve_active_route_api_key(
5999        &self,
6000        read_only: bool,
6001        account_owner: &mut Option<String>,
6002    ) -> Result<ResolvedApiKey> {
6003        let identity = self
6004            .active_provider_identity()
6005            .map_err(anyhow::Error::msg)?;
6006        self.verify_provider_identity(&identity)
6007            .map_err(anyhow::Error::msg)?;
6008        if self.required_account_model_owner.is_some() {
6009            return self.account_model_key_and_owner(&identity)
6010                .map(|(key, owner)| {
6011                    *account_owner = Some(owner);
6012                    (key, "Codewhale account".to_string())
6013                })
6014                .context("The selected account model access is unavailable; no credential fallback is allowed");
6015        }
6016        if let Some(key) = self.session_provider_api_key(&identity) {
6017            return Ok((
6018                key,
6019                crate::credentials::CredentialSource::SessionKey
6020                    .label()
6021                    .into_owned(),
6022            ));
6023        }
6024        if let Some(source) = self.session_policy_without_key(&identity) {
6025            return match &source {
6026                crate::credentials::CredentialSource::AuthModeNone
6027                | crate::credentials::CredentialSource::KeylessRoute { .. } => {
6028                    Ok((String::new(), source.label().into_owned()))
6029                }
6030                _ => anyhow::bail!(
6031                    "This Engine requires a session provider key; stored credentials are disabled"
6032                ),
6033            };
6034        }
6035        let provider = identity.provider;
6036        let keyless = || (String::new(), "none (keyless route)".to_string());
6037
6038        if provider == ProviderKind::Antigravity {
6039            anyhow::bail!(codewhale_config::LEGACY_ANTIGRAVITY_TOMBSTONE_MESSAGE);
6040        }
6041        let auth_mode = self.auth_mode_for_provider(&identity);
6042        if provider == ProviderKind::Custom
6043            && let Some(entry) = self.provider_config_for(&identity)
6044            && let Some(oauth) = entry.oauth.as_ref()
6045        {
6046            entry
6047                .plugin_authority
6048                .as_ref()
6049                .context("Plugin OAuth route lacks an approved plugin authority")?;
6050            anyhow::ensure!(
6051                auth_mode.as_deref() == Some("oauth"),
6052                "Plugin OAuth route requires auth_mode = oauth"
6053            );
6054            self.provider
6055                .as_deref()
6056                .context("Plugin OAuth route has no provider name")?;
6057            oauth.validate()?;
6058            // Generic config/client construction must never read secure storage,
6059            // hash plugin files or refresh OAuth on an async caller's thread.
6060            // The request worker verifies the receipt, resolves the bound token
6061            // and checks revocation again immediately before each actual send.
6062            return Ok((String::new(), "host-managed plugin OAuth".to_string()));
6063        }
6064
6065        if codewhale_config::credentials::auth_mode_is_claude_org(auth_mode.as_deref()) {
6066            anyhow::ensure!(
6067                provider == ProviderKind::Anthropic
6068                    && !self.provider_uses_custom_endpoint(&identity),
6069                "auth_mode = \"claude-org\" works only for the anthropic provider on its official endpoint; remove base_url or the auth_mode from [providers.{}]",
6070                identity.key.as_str()
6071            );
6072            return Ok((
6073                String::new(),
6074                codewhale_config::credentials::CLAUDE_ORG_KEY_SOURCE.to_string(),
6075            ));
6076        }
6077        if auth_mode_disables_api_key(auth_mode.as_deref()) {
6078            return Ok(keyless());
6079        }
6080        if provider == ProviderKind::Anthropic && auth_mode.as_deref() == Some("oauth") {
6081            anyhow::bail!(codewhale_config::credentials::CLAUDE_SIGN_IN_REMOVED);
6082        }
6083        let custom_endpoint = self.provider_uses_custom_endpoint(&identity);
6084        let explicit_cli_key = explicit_cli_api_key_override();
6085
6086        // 0. When the CLI dispatcher forwards an explicit `--api-key`
6087        // through the provider-neutral CLI bridge with its source marker, that
6088        // intentional override must win over the saved root key. This is
6089        // essential for DeepSeek-compatible subscription endpoints where the
6090        // user runs something like:
6091        //   codewhale --provider deepseek --api-key ark-... --base-url ... --model auto
6092        if matches!(provider, ProviderKind::Deepseek)
6093            && cli_api_key_source().as_deref() == Some("cli")
6094            && let Some((env_key, source)) = explicit_cli_key
6095                .as_ref()
6096                .cloned()
6097                .map(|key| (key, "--api-key (CLI)".to_string()))
6098                .or_else(|| {
6099                    provider_env_api_key_named(provider)
6100                        .map(|(name, key)| (key, format!("env var {name}")))
6101                })
6102            && !env_key.trim().is_empty()
6103        {
6104            return Ok((env_key, source));
6105        }
6106
6107        if provider == ProviderKind::Moonshot
6108            && !custom_endpoint
6109            && self
6110                .provider_config_for(&identity)
6111                .is_some_and(provider_config_uses_kimi_imported_token)
6112        {
6113            let credential_help =
6114                credential_help_for_provider_route(provider, &self.active_route_base_url());
6115            anyhow::bail!(
6116                "Kimi CLI credential import is unsupported. Codewhale does not impersonate or reuse Kimi OAuth clients; configure an API key from {} instead.",
6117                credential_help
6118                    .credential_url
6119                    .unwrap_or("the selected provider's API-key console")
6120            );
6121        }
6122
6123        // xAI OAuth prefers Codewhale-owned device-login storage. An existing
6124        // Grok CLI file is considered only with provider/path-scoped read-only
6125        // consent. Activated by [providers.xai] auth_mode = "oauth". No
6126        // earlier step applies to xAI.
6127        if let Some(credentials) = self.xai_oauth_route_credentials() {
6128            return credentials
6129                .map(|credentials| (credentials.access_token, XAI_OAUTH_KEY_SOURCE.to_string()));
6130        }
6131
6132        if provider == ProviderKind::OpenaiCodex && !custom_endpoint {
6133            let access_token = if read_only {
6134                crate::oauth::get_owned_credentials_read_only(
6135                    crate::oauth::OAuthProvider::Chatgpt,
6136                    self,
6137                )?
6138                .access_token
6139            } else {
6140                self.codex_credentials()?.access_token
6141            };
6142            return Ok((access_token, "ChatGPT sign-in".to_string()));
6143        }
6144
6145        // The dispatcher cannot know the effective provider until the TUI
6146        // applies `--profile`. A provider-neutral, source-marked CLI override
6147        // therefore wins over saved API-key slots here, after OAuth routes
6148        // have made their own credential decision.
6149        if let Some(value) = explicit_cli_key {
6150            return Ok((value, "--api-key (CLI)".to_string()));
6151        }
6152
6153        // 1. Config file (provider-scoped slot). This intentionally wins
6154        // over ambient env so `codewhale auth set` fixes stale shell exports.
6155        if self.config_credentials_are_bound_to_provider_endpoint(&identity)
6156            && let Some(configured) = self
6157                .provider_route_string_with_deepseek_fallback(&identity, |entry| {
6158                    entry.api_key.clone()
6159                })
6160            && classify_config_api_key_value(&configured) == ConfigApiKeyValueKind::Literal
6161        {
6162            let config_source = match provider_config_table_name(&identity) {
6163                Ok(table) => format!("`{table}` api_key"),
6164                Err(_) => "the provider config-table api_key".to_string(),
6165            };
6166            warn_on_config_api_key_shadowing(self, &identity, &config_source);
6167            return Ok((configured, format!("config file ({config_source})")));
6168        }
6169
6170        // 1b. A route can explicitly bind an environment variable by name via
6171        // `[providers.<name>] api_key_env = "..."`. This remains safe for a
6172        // custom endpoint because the binding belongs to that route; ambient
6173        // provider variables below do not.
6174        //
6175        // For a custom provider, a binding that names an unset (or empty)
6176        // variable is a broken credential contract, not a keyless route: fail
6177        // loudly with the route-scoped fix instead of silently degrading to
6178        // the self-hosted loopback keyless fallback below (#5104). Without
6179        // this, an `api_key_env` route on a loopback host dispatched
6180        // unauthenticated while the operator believed credentials were wired,
6181        // and the composer-side preflight recovery never saw an error.
6182        if provider == ProviderKind::Custom
6183            && let Some(env_name) = bound_provider_api_key_env_name(self, &identity)
6184        {
6185            return match std::env::var(&env_name) {
6186                Ok(value) if !value.trim().is_empty() => {
6187                    Ok((value, format!("env var {env_name} (api_key_env)")))
6188                }
6189                _ => {
6190                    let route_name = self.provider.as_deref().unwrap_or("<name>");
6191                    Err(anyhow::anyhow!(
6192                        "Custom provider '{route_name}' API key not found: the route binds \
6193                         api_key_env = \"{env_name}\" but that environment variable is not set. \
6194                         Set {env_name} to your key, or remove api_key_env from \
6195                         [providers.{route_name}] to run the endpoint without credentials."
6196                    ))
6197                }
6198            };
6199        }
6200        if let Some(value) = provider_config_env_api_key(self, &identity) {
6201            let name = bound_provider_api_key_env_name(self, &identity).unwrap_or_default();
6202            return Ok((value, format!("env var {name} (api_key_env)")));
6203        }
6204
6205        // 2. The dispatcher resolves this same provider slot before launching
6206        // the TUI. Standalone `codewhale-tui` launches must see the identical
6207        // durable credential. Auto-detection is file-backed and prompt-free by
6208        // default; the OS keyring is queried only when the user explicitly
6209        // selects the system backend.
6210        if !self.should_skip_secret_store_for_provider(&identity)
6211            && let Some(value) = provider_secret_store_api_key_with_mode(self, &identity, read_only)
6212        {
6213            return Ok((
6214                value,
6215                format!(
6216                    "secret store slot `{}`",
6217                    provider_secret_store_slot(provider)
6218                ),
6219            ));
6220        }
6221
6222        // 3. Ambient provider environment variables are scoped to official
6223        // endpoints. Never send an official-provider export to a custom host.
6224        if !self.should_skip_secret_store_for_provider(&identity)
6225            && provider == ProviderKind::XiaomiMimo
6226        {
6227            let mode = self
6228                .provider_config_for(&identity)
6229                .and_then(|provider| provider.mode.as_deref());
6230            if let Some(value) =
6231                xiaomi_mimo_env_api_key_for_runtime(mode, Some(&self.active_route_base_url()))
6232                && !value.trim().is_empty()
6233            {
6234                return Ok((
6235                    value,
6236                    format!("env var ({})", provider.provider().env_vars().join(" / ")),
6237                ));
6238            }
6239        }
6240        if !self.should_skip_secret_store_for_provider(&identity)
6241            && let Some((name, value)) = provider_env_api_key_named(provider)
6242        {
6243            return Ok((value, format!("env var {name}")));
6244        }
6245
6246        // Official DeepSeek Harness credentials, only after explicit
6247        // read-only consent to one exact `$DSH_HOME/.credentials.yaml`.
6248        if matches!(
6249            provider,
6250            ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
6251        ) && identity.key.as_str() != codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id
6252            && !custom_endpoint
6253        {
6254            let path = codewhale_config::default_dsh_credentials_path();
6255            if let Ok(grant) = self.external_credential_read_grant(
6256                &identity,
6257                codewhale_config::ExternalCredentialSource::DshCli,
6258                &path,
6259            ) && let Some(value) = crate::dsh_credentials::deepseek_api_key_from_grant(&grant)?
6260            {
6261                return Ok((
6262                    value,
6263                    "DeepSeek Harness credentials (consented)".to_string(),
6264                ));
6265            }
6266        }
6267
6268        // Account auth is a reversible fallback, never an overwrite of an
6269        // environment, config-file, or durable provider credential.
6270        if let Some((key, owner)) = self.account_model_key_and_owner(&identity) {
6271            *account_owner = Some(owner);
6272            return Ok((key, "Codewhale account".to_string()));
6273        }
6274
6275        // The Codewhale API always authenticates. It is not a self-hosted
6276        // runtime, and a loopback `CODEWHALE_API_BASE` is a test origin for
6277        // the same authenticated contract — never a keyless one. Without this
6278        // the loopback arm below returned an empty key and the request went
6279        // out with no `Authorization` header at all.
6280        if provider != ProviderKind::Codewhale
6281            && !auth_mode_requires_api_key(auth_mode.as_deref())
6282            && (provider_route_is_keyless_self_hosted(provider, &self.active_route_base_url())
6283                || base_url_uses_local_host(&self.active_route_base_url()))
6284        {
6285            return Ok(keyless());
6286        }
6287
6288        if custom_endpoint {
6289            let route_name = self
6290                .provider
6291                .as_deref()
6292                .unwrap_or_else(|| provider.as_str());
6293            anyhow::bail!(
6294                "Custom endpoint credentials for {route_name} must be bound explicitly. Ambient provider credentials are not sent to {}. Add api_key or api_key_env to this provider route, or pass --api-key with --base-url.",
6295                self.active_route_base_url()
6296            );
6297        }
6298
6299        match provider {
6300            ProviderKind::Codewhale => anyhow::bail!(
6301                "Codewhale API key not found, so no request was sent.\n\
6302                 \n\
6303                 The Codewhale API authenticates every model with one account \
6304                 API key carrying the `models:infer` scope.\n\
6305                 \n\
6306                 1. Create one and save it on this machine:\n\
6307                        codewhale account api-keys create --name <name> --scope models:infer --use\n\
6308                 2. Or export it for this shell:\n\
6309                        export CODEWHALE_API_KEY=cwc_key_...\n\
6310                 \n\
6311                 You can also create a key at {} and put it in \
6312                 [providers.codewhale] api_key (or api_key_env).",
6313                provider
6314                    .provider()
6315                    .credential_help()
6316                    .credential_url
6317                    .unwrap_or("https://app.codewhale.net/settings?section=api")
6318            ),
6319            ProviderKind::Deepseek => {
6320                anyhow::bail!(deepseek_missing_key_message())
6321            }
6322            ProviderKind::SiliconflowCN => anyhow::bail!(
6323                "SiliconFlow China API key not found. Get a key: {}. Run 'codewhale auth set --provider siliconflow-CN', \
6324                 set {}, or add [{}] api_key in ~/.codewhale/config.toml. \
6325                 [providers.siliconflow] remains a fallback when the CN table omits api_key.",
6326                provider
6327                    .provider()
6328                    .credential_help()
6329                    .credential_url
6330                    .unwrap_or("https://cloud.siliconflow.com/account/ak"),
6331                provider.provider().env_vars().join(" / "),
6332                provider_config_table_name(&identity)?
6333            ),
6334            ProviderKind::Moonshot => {
6335                let credential_help =
6336                    credential_help_for_provider_route(provider, &self.active_route_base_url());
6337                if moonshot_base_url_is_exact_kimi_code(&self.active_route_base_url()) {
6338                    anyhow::bail!(
6339                        "Kimi Code membership-plan API key not found. Get a plan key: {}. This route uses api.kimi.com/coding/v1 and does not import Kimi CLI credentials. Run 'codewhale auth set --provider moonshot', set {}, or add [{}] api_key.",
6340                        credential_help
6341                            .credential_url
6342                            .unwrap_or(KIMI_CODE_MEMBERSHIP_PLAN_CONSOLE_URL),
6343                        provider.provider().env_vars().join(" / "),
6344                        provider_config_table_name(&identity)?
6345                    );
6346                }
6347                anyhow::bail!(
6348                    "Moonshot/Kimi API key not found. Get a key: {}. Run 'codewhale auth set --provider moonshot', \
6349                     set {}, or add [{}] api_key. \
6350                     For a Kimi Code plan key, set [providers.moonshot] base_url = \
6351                     \"https://api.kimi.com/coding/v1\" and model = \"kimi-for-coding\".",
6352                    credential_help
6353                        .credential_url
6354                        .unwrap_or("https://platform.kimi.ai/console/api-keys"),
6355                    provider.provider().env_vars().join(" / "),
6356                    provider_config_table_name(&identity)?
6357                );
6358            }
6359            ProviderKind::Anthropic | ProviderKind::Openmodel => {
6360                anyhow::bail!("{}", missing_provider_api_key_message(&identity)?)
6361            }
6362            ProviderKind::OpencodeZen => {
6363                anyhow::bail!("{}", missing_provider_api_key_message(&identity)?)
6364            }
6365            ProviderKind::OpenaiCodex => anyhow::bail!(
6366                "{}",
6367                crate::oauth::missing_auth_message(crate::oauth::OAuthProvider::Chatgpt)
6368            ),
6369            ProviderKind::Xai => {
6370                // Prefer OAuth guidance when auth_mode requests it or Grok CLI
6371                // tokens already exist; otherwise show both API-key and OAuth.
6372                if self
6373                    .provider_config_for(&identity)
6374                    .is_some_and(provider_config_uses_xai_oauth)
6375                    || crate::oauth::credentials_present(crate::oauth::OAuthProvider::Xai, self)
6376                {
6377                    anyhow::bail!(
6378                        "{}",
6379                        crate::oauth::missing_auth_message(crate::oauth::OAuthProvider::Xai)
6380                    );
6381                }
6382                anyhow::bail!(
6383                    "xAI API key not found. Get a key: https://console.x.ai/\n\
6384                     Run 'codewhale auth set --provider xai', set XAI_API_KEY, or add \
6385                     [providers.xai] api_key.\n\
6386                     OAuth alternative: run `codewhale auth xai-device` for \
6387                     Codewhale-owned storage and set [providers.xai] auth_mode = \"oauth\"."
6388                );
6389            }
6390            // Self-hosted deployments commonly run without auth on localhost.
6391            // Return an empty key and let the client omit the Authorization header.
6392            ProviderKind::Sglang | ProviderKind::Vllm => Ok(keyless()),
6393            ProviderKind::Ollama
6394                if provider_route_is_keyless_self_hosted(
6395                    provider,
6396                    &self.active_route_base_url(),
6397                ) =>
6398            {
6399                Ok(keyless())
6400            }
6401            ProviderKind::Ollama => {
6402                let help =
6403                    credential_help_for_provider_route(provider, &self.active_route_base_url());
6404                anyhow::bail!(
6405                    "Ollama Cloud API key not found. Get a key: {}. Run 'codewhale auth set --provider ollama', set OLLAMA_API_KEY, or add [providers.ollama] api_key in ~/.codewhale/config.toml.",
6406                    help.credential_url
6407                        .unwrap_or(codewhale_config::provider::OLLAMA_CLOUD_API_KEY_URL)
6408                )
6409            }
6410            // Custom OpenAI-compatible endpoints (#1519): the key comes from the
6411            // env var named by `[providers.<name>] api_key_env`. If we reached
6412            // here it is unset/empty (and the endpoint is not loopback).
6413            ProviderKind::Custom => {
6414                let provider_name = self.provider.as_deref().unwrap_or("<name>");
6415                match self
6416                    .provider_config_for(&identity)
6417                    .and_then(|entry| entry.api_key_env.as_deref())
6418                    .map(str::trim)
6419                    .filter(|name| !name.is_empty())
6420                {
6421                    Some(env_name) => anyhow::bail!(
6422                        "Custom provider '{provider_name}' API key not found.\n\
6423                         Set the environment variable {env_name} to your key, \
6424                         or add api_key to [providers.{provider_name}]."
6425                    ),
6426                    None => anyhow::bail!(
6427                        "Custom provider '{provider_name}' has no auth configured.\n\
6428                         Add api_key_env = \"YOUR_ENV_VAR\" (or api_key) to \
6429                         [providers.{provider_name}] in ~/.codewhale/config.toml."
6430                    ),
6431                }
6432            }
6433            _ => anyhow::bail!("{}", missing_provider_api_key_message(&identity)?),
6434        }
6435    }
6436
6437    /// Resolve the skills directory path.
6438    #[must_use]
6439    pub fn skills_dir(&self) -> PathBuf {
6440        self.skills_dir
6441            .as_deref()
6442            .map(expand_path)
6443            .or_else(default_skills_dir)
6444            .unwrap_or_else(|| PathBuf::from("./skills"))
6445    }
6446
6447    #[must_use]
6448    pub fn bundled_skills_install_dir(&self) -> Option<PathBuf> {
6449        match self.skills_config().bundled.install.unwrap_or_default() {
6450            BundledSkillsInstall::None => return None,
6451            BundledSkillsInstall::All => return owned_skills_dir(),
6452            BundledSkillsInstall::Auto if self.skills_dir.is_some() => return None,
6453            BundledSkillsInstall::Auto => {}
6454        }
6455        let directory = default_skills_dir()?;
6456        let owned = owned_skills_dir()?;
6457        (directory == owned).then_some(directory)
6458    }
6459
6460    /// Resolve the MCP config path.
6461    #[must_use]
6462    pub fn mcp_config_path(&self) -> PathBuf {
6463        let configured = self.mcp_config_path.as_deref().map(expand_path);
6464        match configured {
6465            Some(path) if path.is_absolute() => path,
6466            Some(path) => {
6467                tracing::warn!(
6468                    configured_path = %path.display(),
6469                    "relative mcp_config_path is not stable across launch directories; using the user-global MCP config"
6470                );
6471                default_mcp_config_path().unwrap_or_else(|| PathBuf::from("./mcp.json"))
6472            }
6473            None => default_mcp_config_path().unwrap_or_else(|| PathBuf::from("./mcp.json")),
6474        }
6475    }
6476
6477    /// Resolve the notes file path.
6478    #[must_use]
6479    pub fn notes_path(&self) -> PathBuf {
6480        self.notes_path
6481            .as_deref()
6482            .map(expand_path)
6483            .or_else(default_notes_path)
6484            .unwrap_or_else(|| PathBuf::from("./notes.txt"))
6485    }
6486
6487    /// Resolve the memory file path.
6488    #[must_use]
6489    pub fn memory_path(&self) -> PathBuf {
6490        let legacy_path = self
6491            .memory_path
6492            .as_deref()
6493            .map(expand_path)
6494            .or_else(default_memory_path)
6495            .unwrap_or_else(|| PathBuf::from("./memory.md"));
6496        if self.memory_backend() == MemoryBackend::Native {
6497            // The configured value is historically a *legacy single-file*
6498            // path (`$CODEWHALE_HOME/memory.md`), and the native store lives
6499            // beside it. Deriving from the parent is therefore right for the
6500            // default and for anyone still carrying the old setting.
6501            //
6502            // But someone who points `memory_path` at a native store — the
6503            // obvious reading of the name — used to get a second one nested
6504            // inside it (`…/memory/global/memory/global/MEMORY.md`), silently
6505            // writing somewhere other than the file they named. Honour an
6506            // already-native path as itself.
6507            if crate::native_memory::NativeMemoryStore::from_global_path(&legacy_path).is_some() {
6508                return legacy_path;
6509            }
6510            return legacy_path
6511                .parent()
6512                .unwrap_or_else(|| Path::new("."))
6513                .join("memory")
6514                .join("global")
6515                .join("MEMORY.md");
6516        }
6517        legacy_path
6518    }
6519
6520    /// Resolve the default speech/TTS output directory, if configured.
6521    #[must_use]
6522    pub fn speech_output_dir(&self) -> Option<PathBuf> {
6523        std::env::var("XIAOMI_MIMO_SPEECH_OUTPUT_DIR")
6524            .or_else(|_| std::env::var("MIMO_SPEECH_OUTPUT_DIR"))
6525            .or_else(|_| std::env::var("XIAOMIMIMO_SPEECH_OUTPUT_DIR"))
6526            .ok()
6527            .map(|value| value.trim().to_string())
6528            .filter(|value| !value.is_empty())
6529            .map(|value| expand_path(&value))
6530            .or_else(|| {
6531                self.speech
6532                    .as_ref()
6533                    .and_then(|speech| speech.output_dir.as_deref())
6534                    .map(str::trim)
6535                    .filter(|value| !value.is_empty())
6536                    .map(expand_path)
6537            })
6538    }
6539
6540    /// Resolve the configured `instructions = [...]` array (#454)
6541    /// to absolute paths, in declared order. Empty when unset or
6542    /// when every entry is empty after trimming. Each entry runs
6543    /// through `expand_path` so `~` and env vars are honoured.
6544    #[must_use]
6545    pub fn instructions_paths(&self) -> Vec<PathBuf> {
6546        self.instructions
6547            .as_deref()
6548            .unwrap_or(&[])
6549            .iter()
6550            .map(String::as_str)
6551            .map(str::trim)
6552            .filter(|s| !s.is_empty())
6553            .map(expand_path)
6554            .collect()
6555    }
6556
6557    #[must_use]
6558    pub fn auto_review_disabled(&self) -> bool {
6559        self.auto_review.as_ref().is_some_and(|cfg| cfg.disabled)
6560    }
6561
6562    #[must_use]
6563    pub fn auto_review_review_all_shell(&self) -> bool {
6564        self.auto_review
6565            .as_ref()
6566            .is_some_and(|cfg| cfg.review_all_shell)
6567    }
6568
6569    pub fn auto_review_reviewer_model(&self) -> Option<&str> {
6570        self.auto_review
6571            .as_ref()
6572            .and_then(|cfg| cfg.reviewer_model.as_deref())
6573            .map(str::trim)
6574            .filter(|model| !model.is_empty())
6575    }
6576
6577    #[must_use]
6578    pub fn auto_review_environment(&self) -> &[String] {
6579        self.auto_review
6580            .as_ref()
6581            .map_or(&[], |cfg| cfg.environment.as_slice())
6582    }
6583
6584    /// Whether the user-memory feature is enabled. The default is **off**
6585    /// to preserve zero-overhead behavior for users who haven't opted in.
6586    /// Flips to `true` when `[memory] enabled = true` in `config.toml` or
6587    /// `DEEPSEEK_MEMORY=on` is set in the environment.
6588    #[must_use]
6589    pub fn memory_enabled(&self) -> bool {
6590        if let Some(backend) = self.memory.as_ref().and_then(|memory| memory.backend) {
6591            return backend != MemoryBackend::Off;
6592        }
6593        self.memory
6594            .as_ref()
6595            .and_then(|m| m.enabled)
6596            .unwrap_or(false)
6597    }
6598
6599    /// Effective safety backstop on automatic goal continuation passes
6600    /// (#5052). Goals are unlimited by default. `[goal] max_continuations`
6601    /// opts into a ceiling; `0` disables it so only terminal status or user
6602    /// control stops an operate-mode goal run.
6603    #[must_use]
6604    pub fn goal_max_continuations(&self) -> u32 {
6605        self.goal
6606            .as_ref()
6607            .and_then(|goal| goal.max_continuations)
6608            .unwrap_or(crate::goal_loop::DEFAULT_MAX_GOAL_CONTINUATIONS)
6609    }
6610
6611    /// Per-engine-turn model-step budget while a goal is active (#6512).
6612    /// Uses the ordinary turn resolver: omitted or zero is uncapped, and
6613    /// explicit positive ceilings are clamped to its supported range.
6614    #[must_use]
6615    pub fn goal_max_steps(&self) -> u32 {
6616        let configured = self.goal.as_ref().and_then(|goal| goal.max_steps);
6617        let resolved = crate::turn_budget::resolve_max_model_steps(configured);
6618        if let Some(steps) = configured
6619            && steps > 0
6620            && resolved != steps
6621        {
6622            tracing::warn!("[goal] max_steps={steps} out of range; clamping to {resolved}");
6623        }
6624        resolved
6625    }
6626
6627    /// Whether a goal's `token_budget` is a hard stop (#6013). Default `false`
6628    /// keeps the advisory/telemetry behavior.
6629    #[must_use]
6630    pub fn goal_enforce_token_budget(&self) -> bool {
6631        self.goal
6632            .as_ref()
6633            .and_then(|goal| goal.enforce_token_budget)
6634            .unwrap_or(false)
6635    }
6636
6637    /// Whether `update_goal complete` is gated by an independent judge (#6013).
6638    #[must_use]
6639    pub fn goal_complete_judge(&self) -> bool {
6640        self.goal
6641            .as_ref()
6642            .and_then(|goal| goal.complete_judge)
6643            .unwrap_or(false)
6644    }
6645
6646    /// Whether `update_goal blocked` is gated by an independent judge (#6013).
6647    #[must_use]
6648    pub fn goal_blocked_judge(&self) -> bool {
6649        self.goal
6650            .as_ref()
6651            .and_then(|goal| goal.blocked_judge)
6652            .unwrap_or(false)
6653    }
6654
6655    /// Quiet period between successful interactive goal turns (#5508).
6656    /// Absent/zero keeps the existing immediate-continuation behavior.
6657    #[must_use]
6658    pub fn goal_continuation_delay_seconds(&self) -> u64 {
6659        self.goal
6660            .as_ref()
6661            .and_then(|goal| goal.continuation_delay_seconds)
6662            .unwrap_or(0)
6663            .min(crate::goal_loop::MAX_GOAL_CONTINUATION_DELAY_SECONDS)
6664    }
6665
6666    #[must_use]
6667    pub fn reasoning_only_on_output_limit(&self) -> bool {
6668        self.reasoning_only
6669            .as_ref()
6670            .is_some_and(|cfg| cfg.on_output_limit)
6671    }
6672
6673    /// Maximum number of automatic re-requests when the model returns only
6674    /// reasoning without any answer or tool call. Defaults to 2.
6675    /// Set via `[reasoning_only] max_reprompts` in config.toml.
6676    #[must_use]
6677    pub fn reasoning_only_max_reprompts(&self) -> u32 {
6678        self.reasoning_only
6679            .as_ref()
6680            .and_then(|cfg| cfg.max_reprompts)
6681            .unwrap_or(DEFAULT_REASONING_ONLY_REPROMPTS)
6682    }
6683
6684    /// Optional custom message sent to the model on each re-request when the
6685    /// model returns only reasoning without any answer or tool call.
6686    /// Set via `[reasoning_only] reprompt_message` in config.toml.
6687    /// When unset, the built-in default is used.
6688    #[must_use]
6689    pub fn reasoning_only_reprompt_message(&self) -> &str {
6690        self.reasoning_only
6691            .as_ref()
6692            .and_then(|cfg| cfg.reprompt_message.as_deref())
6693            .unwrap_or(DEFAULT_REASONING_ONLY_REPROMPT_MESSAGE)
6694    }
6695
6696    /// Resolve the explicit local-memory backend.
6697    #[must_use]
6698    pub fn memory_backend(&self) -> MemoryBackend {
6699        self.memory
6700            .as_ref()
6701            .and_then(|memory| memory.backend)
6702            .unwrap_or_else(|| {
6703                let Some(memory) = self.memory.as_ref() else {
6704                    return MemoryBackend::Off;
6705                };
6706                if memory.enabled.unwrap_or(false) {
6707                    MemoryBackend::Native
6708                } else {
6709                    MemoryBackend::Off
6710                }
6711            })
6712    }
6713
6714    /// Return the configured vision model config. A `[vision_model]` that
6715    /// used to inherit the top-level `api_key` carries its own copy since
6716    /// parsing moved that key (#6394). An unset runtime HTTP policy inherits
6717    /// from the main config; provider credentials never follow
6718    /// `vision_model.base_url` to another host.
6719    #[must_use]
6720    pub fn vision_model_config(&self) -> Option<VisionModelConfig> {
6721        let mut config = self.vision_model.clone()?;
6722        if config.model_http_policy.is_none() {
6723            config.model_http_policy = self.model_http_policy.clone();
6724        }
6725        Some(config)
6726    }
6727
6728    #[must_use]
6729    pub fn project_context_pack_enabled(&self) -> bool {
6730        self.context.project_pack.unwrap_or(false)
6731    }
6732
6733    /// Return whether shell execution is allowed for noninteractive and
6734    /// durable-task profiles. Defaults to `false`: in headless, app-server, and
6735    /// background-task contexts there is no human to approve commands, so shell
6736    /// access must be opted into explicitly (GHSA-72w5-pf8h-xfp4).
6737    #[must_use]
6738    pub fn allow_shell(&self) -> bool {
6739        self.allow_shell.unwrap_or(false)
6740    }
6741
6742    /// Return whether shell execution is allowed for an *interactive* TUI Agent
6743    /// session. Defaults to `true`: the interactive composer always gates each
6744    /// shell command behind an approval prompt, so the catalog can expose shell
6745    /// by default while still preserving consent (GHSA-72w5-pf8h-xfp4). An
6746    /// explicit `allow_shell = false` still hides shell tools. This is the
6747    /// single source of truth for the interactive default; both startup
6748    /// (`run_interactive`) and the durable Agent permission baseline read it so
6749    /// the default cannot drift between them.
6750    #[must_use]
6751    pub fn interactive_allow_shell(&self) -> bool {
6752        self.allow_shell.unwrap_or(true)
6753    }
6754
6755    /// Whether ghost-text prompt suggestion is enabled (opt-in, default off).
6756    pub fn prompt_suggestion_enabled(&self) -> bool {
6757        self.prompt_suggestion.unwrap_or(false)
6758    }
6759
6760    /// Standing operator instructions for the compaction summarizer
6761    /// (`[compaction] summary_instructions`, #5956).
6762    ///
6763    /// Trimmed; empty or whitespace-only reads as unset so an accidentally
6764    /// blank key cannot append an empty delimited section to every prompt.
6765    /// The character cap is applied where the suffix is built, so the warning
6766    /// fires once per compaction pass rather than once per turn.
6767    #[must_use]
6768    pub fn compaction_summary_instructions(&self) -> Option<String> {
6769        self.compaction
6770            .as_ref()
6771            .and_then(|compaction| compaction.summary_instructions.as_deref())
6772            .map(str::trim)
6773            .filter(|text| !text.is_empty())
6774            .map(str::to_string)
6775    }
6776
6777    /// Verbatim retention budget for recent plain user messages in the
6778    /// compaction replacement history (`[compaction]
6779    /// retained_user_message_tokens`, #5956).
6780    ///
6781    /// Unset returns the historical hard-coded 20 000. Explicit values clamp
6782    /// to `2_000..=200_000`: below the floor the replacement history stops
6783    /// carrying a usable amount of the user's own words, above the ceiling
6784    /// the "compacted" history is large enough to re-trigger compaction on
6785    /// the next turn.
6786    #[must_use]
6787    pub fn compaction_retained_user_message_tokens(&self) -> usize {
6788        let Some(requested) = self
6789            .compaction
6790            .as_ref()
6791            .and_then(|compaction| compaction.retained_user_message_tokens)
6792        else {
6793            return DEFAULT_COMPACTION_RETAINED_USER_MESSAGE_TOKENS;
6794        };
6795        let clamped = requested.clamp(
6796            MIN_COMPACTION_RETAINED_USER_MESSAGE_TOKENS,
6797            MAX_COMPACTION_RETAINED_USER_MESSAGE_TOKENS,
6798        );
6799        if clamped != requested {
6800            tracing::warn!(
6801                "[compaction] retained_user_message_tokens = {requested} is outside {}..={}; using {clamped}",
6802                MIN_COMPACTION_RETAINED_USER_MESSAGE_TOKENS,
6803                MAX_COMPACTION_RETAINED_USER_MESSAGE_TOKENS
6804            );
6805        }
6806        clamped
6807    }
6808
6809    /// Return the maximum number of concurrent sub-agents.
6810    /// Checks `[subagents] max_concurrent` first, then top-level `max_subagents`,
6811    /// then falls back to `DEFAULT_MAX_SUBAGENTS`.
6812    #[must_use]
6813    pub fn max_subagents(&self) -> usize {
6814        // Check [subagents] max_concurrent first
6815        if let Some(subagents_cfg) = self.subagents.as_ref()
6816            && let Some(max) = subagents_cfg.max_concurrent
6817        {
6818            return max.clamp(1, MAX_SUBAGENTS);
6819        }
6820        // Fall back to top-level max_subagents
6821        self.max_subagents
6822            .unwrap_or(DEFAULT_MAX_SUBAGENTS)
6823            .clamp(1, MAX_SUBAGENTS)
6824    }
6825
6826    /// Return the provider-specific maximum number of concurrent sub-agents.
6827    /// `[subagents.providers.<provider>] max_concurrent` inherits from the
6828    /// global `[subagents]` value when unset.
6829    #[must_use]
6830    pub fn max_subagents_for_provider(&self, identity: &ProviderIdentity) -> usize {
6831        self.subagent_provider_config(identity)
6832            .and_then(|cfg| cfg.max_concurrent)
6833            .map(|max| max.clamp(1, MAX_SUBAGENTS))
6834            .unwrap_or_else(|| self.max_subagents())
6835    }
6836
6837    /// Whether the model-facing `agent` tool is available after applying the
6838    /// feature flag, explicit `[subagents] enabled` switch, and legacy
6839    /// zero-valued opt-outs.
6840    #[must_use]
6841    pub fn subagents_enabled(&self) -> bool {
6842        self.subagents_disabled_reason().is_none()
6843    }
6844
6845    /// Whether the model-facing `agent` tool is available for this provider
6846    /// after applying global and provider-specific sub-agent controls.
6847    #[must_use]
6848    pub fn subagents_enabled_for_provider(&self, identity: &ProviderIdentity) -> bool {
6849        if !self.subagents_enabled() {
6850            return false;
6851        }
6852        let Some(provider_cfg) = self.subagent_provider_config(identity) else {
6853            return true;
6854        };
6855        provider_cfg.enabled != Some(false)
6856            && provider_cfg.max_concurrent != Some(0)
6857            && provider_cfg.max_depth != Some(0)
6858    }
6859
6860    /// Machine-readable reason sub-agents are disabled, in precedence order.
6861    #[must_use]
6862    pub fn subagents_disabled_reason(&self) -> Option<&'static str> {
6863        if !self.features().enabled(Feature::Subagents) {
6864            return Some("features.subagents=false");
6865        }
6866        let subagents_cfg = self.subagents.as_ref()?;
6867        if subagents_cfg.enabled == Some(false) {
6868            return Some("subagents.enabled=false");
6869        }
6870        if subagents_cfg.max_concurrent == Some(0) {
6871            return Some("subagents.max_concurrent=0");
6872        }
6873        if subagents_cfg.max_depth == Some(0) {
6874            return Some("subagents.max_depth=0");
6875        }
6876        None
6877    }
6878
6879    /// How many levels of nested sub-agents the interactive `agent` tool may
6880    /// spawn. Reads `[subagents] max_depth`; when unset it defaults to
6881    /// [`codewhale_protocol::fleet::DEFAULT_SPAWN_DEPTH`]. `0` is a valid value that
6882    /// blocks the `agent` tool at this runtime depth. Positive owner choices
6883    /// are preserved without another product ceiling.
6884    #[must_use]
6885    pub fn subagent_max_spawn_depth(&self) -> u32 {
6886        self.subagents
6887            .as_ref()
6888            .and_then(|cfg| cfg.max_depth)
6889            .unwrap_or(codewhale_protocol::fleet::DEFAULT_SPAWN_DEPTH)
6890    }
6891
6892    /// Return the provider-specific maximum sub-agent recursion depth.
6893    #[must_use]
6894    pub fn subagent_max_spawn_depth_for_provider(&self, identity: &ProviderIdentity) -> u32 {
6895        self.subagent_provider_config(identity)
6896            .and_then(|cfg| cfg.max_depth)
6897            .unwrap_or_else(|| self.subagent_max_spawn_depth())
6898    }
6899
6900    /// Number of direct (depth-1) sub-agents that may execute concurrently
6901    /// before further launches queue for a launch slot (#3095). Reads
6902    /// `[subagents] launch_concurrency` (or the deprecated
6903    /// `interactive_max_launch` alias); when unset it defaults to the full
6904    /// resolved `max_subagents()` (no artificial throttle), and any explicit
6905    /// value is clamped to `[1, max_subagents]`.
6906    #[must_use]
6907    pub fn launch_concurrency(&self) -> usize {
6908        let max = self.max_subagents();
6909        self.subagents
6910            .as_ref()
6911            .and_then(|cfg| cfg.launch_concurrency.or(cfg.interactive_max_launch_legacy))
6912            .unwrap_or(max)
6913            .clamp(1, max)
6914    }
6915
6916    /// Return the provider-specific direct launch throttle. Children above
6917    /// this limit queue for a launch slot instead of starting immediately.
6918    #[must_use]
6919    pub fn launch_concurrency_for_provider(&self, identity: &ProviderIdentity) -> usize {
6920        let max = self.max_subagents_for_provider(identity);
6921        self.subagent_provider_config(identity)
6922            .and_then(|cfg| cfg.launch_concurrency)
6923            .or_else(|| {
6924                self.subagents
6925                    .as_ref()
6926                    .and_then(|cfg| cfg.launch_concurrency.or(cfg.interactive_max_launch_legacy))
6927            })
6928            .unwrap_or(max)
6929            .clamp(1, max)
6930    }
6931
6932    /// Maximum queued + running sub-agents admitted for the session.
6933    ///
6934    /// Defaults to [`MAX_SUBAGENT_ADMISSION`] so distinct `agent` calls can
6935    /// queue and drain through `launch_concurrency` instead of being rejected
6936    /// at the instantaneous concurrency cap. Explicit values are clamped to
6937    /// `[max_subagents, MAX_SUBAGENT_ADMISSION]`.
6938    #[must_use]
6939    pub fn max_admitted_subagents(&self) -> usize {
6940        let max_concurrent = self.max_subagents();
6941        self.subagents
6942            .as_ref()
6943            .and_then(|cfg| cfg.max_admitted)
6944            .unwrap_or(MAX_SUBAGENT_ADMISSION)
6945            .clamp(max_concurrent, MAX_SUBAGENT_ADMISSION)
6946    }
6947
6948    /// Return the provider-specific queued + running admission cap.
6949    #[must_use]
6950    pub fn max_admitted_subagents_for_provider(&self, identity: &ProviderIdentity) -> usize {
6951        let max_concurrent = self.max_subagents_for_provider(identity);
6952        self.subagent_provider_config(identity)
6953            .and_then(|cfg| cfg.max_admitted)
6954            .or_else(|| self.subagents.as_ref().and_then(|cfg| cfg.max_admitted))
6955            .unwrap_or(MAX_SUBAGENT_ADMISSION)
6956            .clamp(max_concurrent, MAX_SUBAGENT_ADMISSION)
6957    }
6958
6959    /// Default per-child model-turn budget from `[subagents]
6960    /// default_max_steps`. `None` or `0` mean unbounded; positive values
6961    /// remain an owner limit that descendants cannot widen.
6962    #[must_use]
6963    pub fn subagent_default_max_steps(&self) -> Option<u32> {
6964        self.subagents
6965            .as_ref()
6966            .and_then(|cfg| cfg.default_max_steps)
6967            .filter(|steps| *steps > 0)
6968    }
6969
6970    /// Default per-child wall-clock budget in seconds from `[subagents]
6971    /// default_wall_time_secs`. `None` or `0` mean unbounded; positive
6972    /// values remain an owner limit that descendants cannot widen.
6973    #[must_use]
6974    pub fn subagent_default_wall_time_secs(&self) -> Option<u64> {
6975        self.subagents
6976            .as_ref()
6977            .and_then(|cfg| cfg.default_wall_time_secs)
6978            .filter(|secs| *secs > 0)
6979    }
6980
6981    /// Resolved per-step DeepSeek API timeout for sub-agents, in seconds.
6982    ///
6983    /// Reads `[subagents] api_timeout_secs` and clamps to
6984    /// `[MIN_SUBAGENT_API_TIMEOUT_SECS, MAX_SUBAGENT_API_TIMEOUT_SECS]`
6985    /// (1..=3600). `None` or `0` resolve to
6986    /// `DEFAULT_SUBAGENT_API_TIMEOUT_SECS` (600); explicit `1` is honored,
6987    /// useful only in fast fail-fast tests, not production (#1806, #1808).
6988    #[must_use]
6989    pub fn subagent_api_timeout_secs(&self) -> u64 {
6990        resolve_subagent_api_timeout_secs(
6991            self.subagents.as_ref().and_then(|cfg| cfg.api_timeout_secs),
6992        )
6993    }
6994
6995    /// Return the provider-specific per-step API timeout for sub-agents.
6996    #[must_use]
6997    pub fn subagent_api_timeout_secs_for_provider(&self, identity: &ProviderIdentity) -> u64 {
6998        resolve_subagent_api_timeout_secs(
6999            self.subagent_provider_config(identity)
7000                .and_then(|cfg| cfg.api_timeout_secs)
7001                .or_else(|| self.subagents.as_ref().and_then(|cfg| cfg.api_timeout_secs)),
7002        )
7003    }
7004
7005    /// Resolved no-progress heartbeat timeout for running sub-agents.
7006    ///
7007    /// Reads `[subagents] heartbeat_timeout_secs` and clamps to
7008    /// `[MIN_SUBAGENT_HEARTBEAT_TIMEOUT_SECS, MAX_SUBAGENT_HEARTBEAT_TIMEOUT_SECS]`.
7009    /// `None` or `0` resolve to the default 300 seconds. The final value is
7010    /// also kept at least 30 seconds above `subagent_api_timeout_secs()` so a
7011    /// configured long model request is not pre-empted by heartbeat cleanup,
7012    /// and at least 30 seconds above the sub-agent tool timeout so a single
7013    /// long tool execution is not cancelled as "no progress" (2026-08-04
7014    /// sub-agent hunt, finding 4).
7015    #[must_use]
7016    pub fn subagent_heartbeat_timeout_secs(&self) -> u64 {
7017        resolve_subagent_heartbeat_timeout_secs(
7018            self.subagents
7019                .as_ref()
7020                .and_then(|cfg| cfg.heartbeat_timeout_secs),
7021            self.subagent_api_timeout_secs(),
7022            DEFAULT_SUBAGENT_TOOL_TIMEOUT_SECS,
7023        )
7024    }
7025
7026    /// Return the provider-specific no-progress heartbeat timeout.
7027    #[must_use]
7028    pub fn subagent_heartbeat_timeout_secs_for_provider(&self, identity: &ProviderIdentity) -> u64 {
7029        let api_timeout = self.subagent_api_timeout_secs_for_provider(identity);
7030        resolve_subagent_heartbeat_timeout_secs(
7031            self.subagent_provider_config(identity)
7032                .and_then(|cfg| cfg.heartbeat_timeout_secs)
7033                .or_else(|| {
7034                    self.subagents
7035                        .as_ref()
7036                        .and_then(|cfg| cfg.heartbeat_timeout_secs)
7037                }),
7038            api_timeout,
7039            DEFAULT_SUBAGENT_TOOL_TIMEOUT_SECS,
7040        )
7041    }
7042
7043    /// Resolved per-SSE-chunk idle timeout in seconds.
7044    ///
7045    /// Reads `[stream].chunk_timeout_secs`, then legacy `[tui]`, then the
7046    /// `CODEWHALE_STREAM_IDLE_TIMEOUT_SECS` env var (legacy alias:
7047    /// `DEEPSEEK_STREAM_IDLE_TIMEOUT_SECS`) when the config key is
7048    /// omitted. `None` or `0` resolve to the default 900 seconds; explicit
7049    /// values are clamped to `1..=3600`.
7050    #[must_use]
7051    pub fn stream_chunk_timeout_secs(&self) -> u64 {
7052        let raw = self
7053            .stream
7054            .as_ref()
7055            .and_then(|cfg| cfg.chunk_timeout_secs)
7056            .or_else(|| {
7057                self.tui
7058                    .as_ref()
7059                    .and_then(|cfg| cfg.stream_chunk_timeout_secs)
7060            })
7061            .or_else(|| {
7062                std::env::var(STREAM_CHUNK_TIMEOUT_ENV)
7063                    .or_else(|_| std::env::var(LEGACY_STREAM_CHUNK_TIMEOUT_ENV))
7064                    .ok()
7065                    .and_then(|value| value.parse::<u64>().ok())
7066            })
7067            .unwrap_or(DEFAULT_STREAM_CHUNK_TIMEOUT_SECS);
7068        if raw == 0 {
7069            return DEFAULT_STREAM_CHUNK_TIMEOUT_SECS;
7070        }
7071        raw.clamp(MIN_STREAM_CHUNK_TIMEOUT_SECS, MAX_STREAM_CHUNK_TIMEOUT_SECS)
7072    }
7073
7074    /// Resolved optional ceiling on model steps in a single turn.
7075    ///
7076    /// Reads `[tui].max_model_steps`, falling back to the
7077    /// `CODEWHALE_MAX_MODEL_STEPS` env var, then to the uncapped default.
7078    /// `0` from either source also selects the uncapped default.
7079    #[must_use]
7080    pub fn max_model_steps(&self) -> u32 {
7081        let raw = self
7082            .tui
7083            .as_ref()
7084            .and_then(|cfg| cfg.max_model_steps)
7085            .or_else(|| {
7086                std::env::var(MAX_MODEL_STEPS_ENV)
7087                    .ok()
7088                    .and_then(|value| value.trim().parse::<u32>().ok())
7089            });
7090        crate::turn_budget::resolve_max_model_steps(raw)
7091    }
7092
7093    /// R1: resolved cumulative per-turn wall-clock budget.
7094    ///
7095    /// Reads `[tui].turn_wall_clock_secs`, falling back to the
7096    /// `CODEWHALE_TURN_WALL_CLOCK_SECS` env var, then to no limit. `0`
7097    /// also means no limit.
7098    #[must_use]
7099    pub fn turn_wall_clock(&self) -> std::time::Duration {
7100        let raw = self
7101            .tui
7102            .as_ref()
7103            .and_then(|cfg| cfg.turn_wall_clock_secs)
7104            .or_else(|| {
7105                std::env::var(TURN_WALL_CLOCK_ENV)
7106                    .ok()
7107                    .and_then(|value| value.trim().parse::<u64>().ok())
7108            });
7109        crate::turn_budget::resolve_turn_wall_clock(raw)
7110    }
7111
7112    /// R1: resolved per-step cap on accumulated streamed content, in bytes.
7113    #[must_use]
7114    pub fn stream_max_content_bytes(&self) -> usize {
7115        crate::turn_budget::resolve_stream_max_content_bytes(
7116            self.stream
7117                .as_ref()
7118                .and_then(|cfg| cfg.max_content_mb)
7119                .or_else(|| self.tui.as_ref().and_then(|cfg| cfg.stream_max_content_mb)),
7120        )
7121    }
7122
7123    /// R1: resolved per-step cap on a single stream's wall-clock duration.
7124    #[must_use]
7125    pub fn stream_max_duration(&self) -> std::time::Duration {
7126        std::time::Duration::from_secs(crate::turn_budget::resolve_stream_max_duration_secs(
7127            self.stream
7128                .as_ref()
7129                .and_then(|cfg| cfg.max_duration_secs)
7130                .or_else(|| {
7131                    self.tui
7132                        .as_ref()
7133                        .and_then(|cfg| cfg.stream_max_duration_secs)
7134                }),
7135        ))
7136    }
7137
7138    /// Resolved `[stream]` retry budgets, falling back to legacy `[tui]` keys.
7139    #[must_use]
7140    pub fn stream_retry_limits(&self) -> crate::turn_budget::StreamRetryLimits {
7141        let tui = self.tui.as_ref();
7142        let stream = self.stream.as_ref();
7143        crate::turn_budget::resolve_stream_retry_limits(
7144            stream
7145                .and_then(|cfg| cfg.max_resumes)
7146                .or_else(|| tui.and_then(|cfg| cfg.stream_max_resumes)),
7147            stream
7148                .and_then(|cfg| cfg.max_transparent_retries)
7149                .or_else(|| tui.and_then(|cfg| cfg.stream_max_transparent_retries)),
7150            stream
7151                .and_then(|cfg| cfg.max_stream_errors)
7152                .or_else(|| tui.and_then(|cfg| cfg.stream_max_errors)),
7153        )
7154    }
7155
7156    /// #6700: resolved wait for SSE response headers.
7157    #[must_use]
7158    pub fn stream_open_timeout(&self) -> std::time::Duration {
7159        codewhale_config::resolve_stream_open_timeout(
7160            self.stream
7161                .as_ref()
7162                .and_then(|cfg| cfg.open_timeout_secs)
7163                .or_else(|| {
7164                    self.tui
7165                        .as_ref()
7166                        .and_then(|cfg| cfg.stream_open_timeout_secs)
7167                }),
7168        )
7169    }
7170
7171    /// #6700: whether the model HTTP client is pinned to HTTP/1.1 —
7172    /// `[stream].force_http1` (legacy `[tui]` fallback), OR the environment pin.
7173    #[must_use]
7174    pub fn force_http1(&self) -> bool {
7175        self.stream
7176            .as_ref()
7177            .and_then(|cfg| cfg.force_http1)
7178            .or_else(|| self.tui.as_ref().and_then(|cfg| cfg.force_http1))
7179            .unwrap_or(false)
7180            || codewhale_config::force_http1_from_env()
7181    }
7182
7183    /// #6700: resolved TCP/TLS connect timeout for the model HTTP client.
7184    #[must_use]
7185    pub fn connect_timeout(&self) -> std::time::Duration {
7186        let secs = match self
7187            .stream
7188            .as_ref()
7189            .and_then(|cfg| cfg.connect_timeout_secs)
7190            .or_else(|| self.tui.as_ref().and_then(|cfg| cfg.connect_timeout_secs))
7191        {
7192            None | Some(0) => DEFAULT_CONNECT_TIMEOUT_SECS,
7193            Some(secs) => secs.clamp(MIN_CONNECT_TIMEOUT_SECS, MAX_CONNECT_TIMEOUT_SECS),
7194        };
7195        std::time::Duration::from_secs(secs)
7196    }
7197
7198    /// TCP keepalive idle time. Zero disables; positive values clamp to 1..=3600.
7199    pub fn tcp_keepalive(&self) -> Option<std::time::Duration> {
7200        let secs = self
7201            .stream
7202            .as_ref()
7203            .and_then(|cfg| cfg.tcp_keepalive_secs)
7204            .unwrap_or(30);
7205        (secs > 0).then(|| std::time::Duration::from_secs(secs.min(3600)))
7206    }
7207
7208    /// HTTP/2 PING interval for active connections (not idle pooled connections).
7209    pub fn http2_keep_alive_interval(&self) -> Option<std::time::Duration> {
7210        let secs = self
7211            .stream
7212            .as_ref()
7213            .and_then(|cfg| cfg.http2_keep_alive_interval_secs)
7214            .unwrap_or(15);
7215        (secs > 0).then(|| std::time::Duration::from_secs(secs.min(3600)))
7216    }
7217
7218    pub fn http2_keep_alive_timeout(&self) -> std::time::Duration {
7219        let secs = match self
7220            .stream
7221            .as_ref()
7222            .and_then(|cfg| cfg.http2_keep_alive_timeout_secs)
7223        {
7224            None | Some(0) => 20,
7225            Some(secs) => secs.min(3600),
7226        };
7227        std::time::Duration::from_secs(secs)
7228    }
7229
7230    /// Non-secret effective settings for `config dump`/`get`. This projection
7231    /// calls the runtime accessors, so aliases, environment and clamps cannot
7232    /// acquire a second policy in the dispatcher. It does not save defaults.
7233    pub fn resolved_stream_settings(&self) -> StreamConfig {
7234        let limits = self.stream_retry_limits();
7235        StreamConfig {
7236            open_timeout_secs: Some(self.stream_open_timeout().as_secs()),
7237            chunk_timeout_secs: Some(self.stream_chunk_timeout_secs()),
7238            force_http1: Some(self.force_http1()),
7239            max_resumes: Some(limits.max_resumes),
7240            max_transparent_retries: Some(limits.max_transparent_retries),
7241            max_stream_errors: Some(limits.max_errors),
7242            max_duration_secs: Some(self.stream_max_duration().as_secs()),
7243            max_content_mb: Some((self.stream_max_content_bytes() / (1024 * 1024)) as u64),
7244            connect_timeout_secs: Some(self.connect_timeout().as_secs()),
7245            tcp_keepalive_secs: Some(self.tcp_keepalive().map_or(0, |value| value.as_secs())),
7246            http2_keep_alive_interval_secs: Some(
7247                self.http2_keep_alive_interval()
7248                    .map_or(0, |value| value.as_secs()),
7249            ),
7250            http2_keep_alive_timeout_secs: Some(self.http2_keep_alive_timeout().as_secs()),
7251        }
7252    }
7253
7254    /// Raw sub-agent model override map. Values are validated at spawn time
7255    /// so an invalid role/type model fails before any partial agent spawn.
7256    #[must_use]
7257    pub fn subagent_model_overrides(&self) -> HashMap<String, SubagentModelOverride> {
7258        let mut overrides = HashMap::new();
7259        let Some(cfg) = self.subagents.as_ref() else {
7260            return overrides;
7261        };
7262
7263        let mut insert = |key: &str, value: &Option<String>| {
7264            if let Some(model) = value.as_deref().map(str::trim).filter(|v| !v.is_empty()) {
7265                overrides.insert(key.to_string(), model.into());
7266            }
7267        };
7268        insert("default", &cfg.default_model);
7269        insert("worker", &cfg.worker_model);
7270        insert("general", &cfg.worker_model);
7271        insert("scout", &cfg.explorer_model);
7272        insert("explorer", &cfg.explorer_model);
7273        insert("explore", &cfg.explorer_model);
7274        insert("planner", &cfg.awaiter_model);
7275        insert("awaiter", &cfg.awaiter_model);
7276        insert("plan", &cfg.awaiter_model);
7277        insert("reviewer", &cfg.review_model);
7278        insert("review", &cfg.review_model);
7279        insert("custom", &cfg.custom_model);
7280
7281        if let Some(models) = cfg.models.as_ref() {
7282            for (key, model) in models {
7283                let key = key.trim();
7284                let model = model.trim();
7285                if !key.is_empty() && !model.is_empty() {
7286                    overrides.insert(key.to_ascii_lowercase(), model.into());
7287                }
7288            }
7289        }
7290
7291        if let Some(roles) = cfg.roles.as_ref() {
7292            let mut entries: Vec<_> = roles.iter().collect();
7293            // Apply legacy aliases first, then canonical keys, deterministically.
7294            // `default` is the all-role fallback, not the legacy general alias.
7295            let canonical = |key: &str| {
7296                let key = key.trim().to_ascii_lowercase();
7297                if key == "default" {
7298                    key
7299                } else {
7300                    codewhale_protocol::fleet::migrate_legacy_role_token(&key)
7301                        .unwrap_or(&key)
7302                        .to_string()
7303                }
7304            };
7305            entries
7306                .sort_by_key(|(key, _)| (canonical(key) == key.trim().to_ascii_lowercase(), *key));
7307            for (key, pin) in entries {
7308                // Keep blank explicit pins so admission rejects them rather
7309                // than silently inheriting a different route.
7310                overrides.insert(canonical(key), parse_subagent_role_pin(&pin.model));
7311            }
7312        }
7313
7314        overrides
7315    }
7316
7317    /// The operator-approved replacement routes declared beside the role pin
7318    /// that [`Self::subagent_model_overrides`] resolved under `key`. A
7319    /// canonical role key wins over a legacy alias, matching pin precedence.
7320    pub fn subagent_route_replacements(&self, key: &str) -> Vec<SubagentModelOverride> {
7321        let Some(roles) = self.subagents.as_ref().and_then(|cfg| cfg.roles.as_ref()) else {
7322            return Vec::new();
7323        };
7324        let canonical = |raw: &str| {
7325            let raw = raw.trim().to_ascii_lowercase();
7326            if raw == "default" {
7327                raw
7328            } else {
7329                codewhale_protocol::fleet::migrate_legacy_role_token(&raw)
7330                    .unwrap_or(&raw)
7331                    .to_string()
7332            }
7333        };
7334        roles
7335            .iter()
7336            .filter(|(raw, _)| canonical(raw) == key)
7337            .max_by_key(|(raw, _)| (canonical(raw) == raw.trim().to_ascii_lowercase(), *raw))
7338            .map(|(_, pin)| {
7339                pin.replacements
7340                    .iter()
7341                    .map(|route| parse_subagent_role_pin(route))
7342                    .collect()
7343            })
7344            .unwrap_or_default()
7345    }
7346
7347    /// Parsed `[fleet]` table, or defaults when the table is absent
7348    /// (#fleet-roster cutover (v0.8.67)).
7349    #[must_use]
7350    pub fn fleet_config(&self) -> codewhale_config::FleetConfigToml {
7351        self.fleet.clone().unwrap_or_default()
7352    }
7353
7354    #[must_use]
7355    pub fn mcp_backend(&self) -> codewhale_config::McpBackend {
7356        self.extension_host
7357            .as_ref()
7358            .map_or(codewhale_config::McpBackend::default(), |host| {
7359                host.mcp_backend
7360            })
7361    }
7362
7363    /// Parsed `[workflow]` table, or product defaults when the table is absent
7364    /// (#4128 / Section 2.11). Automatic launch, approval, isolation, and
7365    /// activity-persistence consumers should read through this accessor so
7366    /// omitted keys share one model.
7367    #[must_use]
7368    pub fn workflow_config(&self) -> codewhale_config::WorkflowConfigToml {
7369        self.workflow.clone().unwrap_or_default()
7370    }
7371
7372    /// The requested model-bound masking mode (`[redaction] model_bound`),
7373    /// defaulting to enabled. This is the user's *request*; the effective mode
7374    /// also depends on the startup-gate confirmation receipt, see
7375    /// [`codewhale_config::redaction::effective_masking`].
7376    #[must_use]
7377    pub fn model_bound_redaction(&self) -> codewhale_config::redaction::ModelBoundMasking {
7378        self.redaction
7379            .as_ref()
7380            .map(codewhale_config::redaction::RedactionToml::model_bound_masking)
7381            .unwrap_or_default()
7382    }
7383
7384    /// Whether the startup gate must ask before the current config's
7385    /// `[redaction] model_bound` request can take effect.
7386    pub fn redaction_confirmation_required(&self) -> bool {
7387        codewhale_config::redaction::confirmation_required(
7388            self.model_bound_redaction(),
7389            self.loaded_config_path.as_deref(),
7390        )
7391    }
7392
7393    /// Persist the confirmation and return the written receipt path. Called after
7394    /// the user picks the explicit "confirm" action.
7395    pub fn record_redaction_confirmation(&self) -> anyhow::Result<std::path::PathBuf> {
7396        let path = self.loaded_config_path.as_deref().ok_or_else(|| {
7397            anyhow::anyhow!("No loaded config file can receive this confirmation")
7398        })?;
7399        codewhale_config::redaction::record_model_bound_disabled_confirmation(path)
7400            .map_err(anyhow::Error::from)
7401    }
7402
7403    /// Return the configured DeepSeek reasoning-effort tier, if any.
7404    #[must_use]
7405    pub fn reasoning_effort(&self) -> Option<&str> {
7406        self.reasoning_effort.as_deref()
7407    }
7408
7409    pub fn reasoning_effort_is_explicit(&self) -> bool {
7410        self.reasoning_effort.is_some() && !self.reasoning_effort_inferred_from_legacy_alias
7411    }
7412
7413    /// Get hooks configuration, returning default if not configured.
7414    pub fn hooks_config(&self) -> HooksConfig {
7415        self.hooks.clone().unwrap_or_default()
7416    }
7417
7418    /// Resolve the notifications configuration with defaults applied.
7419    #[must_use]
7420    pub fn notifications_config(&self) -> NotificationsConfig {
7421        let mut notifications = self.notifications.clone().unwrap_or_default();
7422        notifications.condition = Some(
7423            notifications
7424                .condition
7425                .or_else(|| self.tui.as_ref().and_then(|tui| tui.notification_condition))
7426                .unwrap_or(NotificationCondition::Unfocused),
7427        );
7428        notifications
7429    }
7430
7431    /// Resolve which approval option a fresh card highlights (#5293).
7432    #[must_use]
7433    pub fn approval_default_selection(&self) -> ApprovalDefaultSelection {
7434        self.approval.unwrap_or_default().default_selection
7435    }
7436
7437    /// Effective expiry for the Engine-held approval request (#6101).
7438    /// `None` (absent or an explicit `0`) waits indefinitely; a positive
7439    /// value bounds the wait, including a hidden card, and expiry blocks the call.
7440    /// Values above 24h clamp with a warning.
7441    #[must_use]
7442    pub fn approval_timeout(&self) -> Option<std::time::Duration> {
7443        const MAX_SECONDS: u64 = 86_400;
7444        let seconds = self.approval.unwrap_or_default().timeout_seconds?;
7445        if seconds == 0 {
7446            return None;
7447        }
7448        if seconds > MAX_SECONDS {
7449            tracing::warn!(
7450                "[approval] timeout_seconds={seconds} exceeds 24h; clamping to {MAX_SECONDS}"
7451            );
7452        }
7453        Some(std::time::Duration::from_secs(seconds.min(MAX_SECONDS)))
7454    }
7455
7456    /// Resolve workspace side-git snapshot settings with defaults applied.
7457    #[must_use]
7458    pub fn snapshots_config(&self) -> SnapshotsConfig {
7459        self.snapshots.clone().unwrap_or_default()
7460    }
7461
7462    /// Resolve community skill settings with defaults applied.
7463    #[must_use]
7464    pub fn skills_config(&self) -> SkillsConfig {
7465        self.skills.clone().unwrap_or_default()
7466    }
7467
7468    /// Resolve startup update-check settings with defaults applied.
7469    #[must_use]
7470    pub fn update_config(&self) -> UpdateConfig {
7471        self.update.clone().unwrap_or_default()
7472    }
7473
7474    /// Resolve cloud facts settings with defaults applied (off by default).
7475    #[must_use]
7476    pub fn cloud_facts_config(&self) -> CloudFactsConfig {
7477        self.cloud_facts.clone().unwrap_or_default()
7478    }
7479
7480    /// Resolve durable hotbar bindings for render/dispatch layers.
7481    #[must_use]
7482    pub fn resolve_hotbar_bindings(
7483        &self,
7484        known_action_ids: &[&str],
7485    ) -> codewhale_config::HotbarConfigResolution {
7486        codewhale_config::resolve_hotbar_bindings(self.hotbar.as_deref(), known_action_ids)
7487    }
7488
7489    /// Resolve enabled features from defaults and config entries.
7490    #[must_use]
7491    pub fn features(&self) -> Features {
7492        let mut features = Features::with_defaults();
7493        if let Some(table) = &self.features {
7494            features.apply_map(&table.entries);
7495        }
7496        features
7497    }
7498
7499    /// Override a feature flag in memory (used by CLI overrides).
7500    pub fn set_feature(&mut self, key: &str, enabled: bool) -> Result<()> {
7501        if !is_known_feature_key(key) {
7502            anyhow::bail!("Unknown feature flag: {key}");
7503        }
7504        let table = self.features.get_or_insert_with(FeaturesToml::default);
7505        table.entries.insert(key.to_string(), enabled);
7506        Ok(())
7507    }
7508
7509    /// Resolve the effective retry policy with defaults applied.
7510    #[must_use]
7511    pub fn retry_policy(&self) -> RetryPolicy {
7512        let defaults = RetryPolicy {
7513            rate_limit: RateLimitRetryPolicy::default(),
7514            enabled: true,
7515            max_retries: 3,
7516            initial_delay: 1.0,
7517            max_delay: 60.0,
7518            exponential_base: 2.0,
7519            jitter: true,
7520            jitter_factor: 0.1,
7521            respect_retry_after: true,
7522        };
7523
7524        let Some(cfg) = &self.retry else {
7525            return defaults;
7526        };
7527
7528        RetryPolicy {
7529            rate_limit: cfg.rate_limit.clone(),
7530            enabled: cfg.enabled.unwrap_or(defaults.enabled),
7531            max_retries: cfg.max_retries.unwrap_or(defaults.max_retries),
7532            initial_delay: cfg.initial_delay.unwrap_or(defaults.initial_delay),
7533            max_delay: cfg.max_delay.unwrap_or(defaults.max_delay),
7534            exponential_base: cfg.exponential_base.unwrap_or(defaults.exponential_base),
7535            jitter: cfg.jitter.unwrap_or(defaults.jitter),
7536            jitter_factor: cfg
7537                .jitter_factor
7538                .filter(|factor| factor.is_finite())
7539                .map_or(defaults.jitter_factor, |factor| factor.clamp(0.0, 1.0)),
7540            respect_retry_after: cfg
7541                .respect_retry_after
7542                .unwrap_or(defaults.respect_retry_after),
7543        }
7544    }
7545}
7546
7547/// Controls whether configuration loading may copy secret-bearing environment
7548/// values into the in-memory configuration.
7549///
7550/// Structural diagnostics intentionally retain safe environment routing and
7551/// policy fields while refusing values that could be secrets when later
7552/// rendered or included in an error path.
7553#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7554pub enum ConfigEnvironmentPolicy {
7555    Runtime,
7556    StructuralDiagnostic,
7557}
7558
7559impl ConfigEnvironmentPolicy {
7560    const fn permits_secret_bearing_values(self) -> bool {
7561        matches!(self, Self::Runtime)
7562    }
7563}
7564
7565fn root_deepseek_model_is_foreign_to_direct_provider(provider: ProviderKind, model: &str) -> bool {
7566    if matches!(
7567        provider,
7568        ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
7569    ) || codewhale_config::descriptors::provider_passes_model_through(provider)
7570    {
7571        return false;
7572    }
7573    if matches!(
7574        provider,
7575        ProviderKind::NvidiaNim
7576            | ProviderKind::Openrouter
7577            | ProviderKind::Orcarouter
7578            | ProviderKind::Novita
7579            | ProviderKind::Fireworks
7580            | ProviderKind::Siliconflow
7581            | ProviderKind::SiliconflowCN
7582            | ProviderKind::Deepinfra
7583            | ProviderKind::Together
7584            | ProviderKind::Sglang
7585            | ProviderKind::Vllm
7586            | ProviderKind::Volcengine
7587            | ProviderKind::Atlascloud
7588            | ProviderKind::OpencodeGo
7589            | ProviderKind::WanjieArk
7590            | ProviderKind::Huggingface
7591            | ProviderKind::XiaomiMimo
7592            | ProviderKind::Moonshot
7593    ) {
7594        return false;
7595    }
7596    codewhale_config::route::resolve_model(ProviderKind::Deepseek, model, None)
7597        .is_ok_and(|resolved| !resolved.is_auto)
7598}
7599
7600// === Defaults ===
7601
7602// Pure filesystem path helpers live in the `paths` leaf module. Shared
7603// entry points are re-exported so external `crate::config::`
7604// callers resolve unchanged; the remaining helpers are imported privately for
7605// the workspace-trust/config-load logic that stays in this file (#3311).
7606mod paths;
7607#[cfg(any(test, feature = "test-support"))]
7608pub use paths::clipboard_images_dir_for_home;
7609use paths::{
7610    canonicalize_or_keep, codewhale_home_dir, default_config_path, default_managed_config_path,
7611    default_mcp_config_path, default_memory_path, default_notes_path, default_requirements_path,
7612    default_skills_dir, env_config_path, expand_pathbuf, try_default_config_path,
7613    workspace_config_key,
7614};
7615pub use paths::{
7616    clipboard_images_dir, expand_path, home_config_path, is_home_config_path, owned_skills_dir,
7617};
7618
7619/// Activate facts only at accepted inference runtime settings boundaries.
7620/// Identical settings preserve the shared ticket; readers track its generation.
7621pub fn initialize_cloud_facts(config: &Config) {
7622    let settings = config.cloud_facts_config().settings();
7623    codewhale_cloud_facts::configure(&settings);
7624    codewhale_cloud_facts::maybe_load_persisted_cache(&settings);
7625    if tokio::runtime::Handle::try_current().is_ok() {
7626        codewhale_cloud_facts::spawn_background_refresh(settings, None);
7627    }
7628}
7629
7630pub fn workspace_trust_config_candidate_paths() -> Vec<PathBuf> {
7631    #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
7632    {
7633        if !crate::test_support::guarded_environment_provides_state_paths() {
7634            return vec![
7635                crate::test_support::unsealed_test_state_root()
7636                    .join(codewhale_config::CONFIG_FILE_NAME),
7637            ];
7638        }
7639    }
7640
7641    match env_config_path() {
7642        Ok(Some(path)) => return vec![path],
7643        Ok(None) => {}
7644        Err(error) => {
7645            tracing::error!(
7646                error = %error,
7647                "invalid config path override; refusing workspace-trust fallback"
7648            );
7649            return Vec::new();
7650        }
7651    }
7652
7653    match codewhale_home_dir() {
7654        Ok(Some(codewhale_home)) => return vec![codewhale_home.join("config.toml")],
7655        Ok(None) => {}
7656        Err(error) => {
7657            tracing::error!(
7658                error = %error,
7659                "invalid Codewhale home override; refusing workspace-trust fallback"
7660            );
7661            return Vec::new();
7662        }
7663    }
7664
7665    let Some(home) = codewhale_paths::user_home() else {
7666        return Vec::new();
7667    };
7668    vec![
7669        home.join(".codewhale").join("config.toml"),
7670        home.join(".deepseek").join("config.toml"),
7671    ]
7672}
7673
7674pub fn needs_trust(workspace: &Path) -> bool {
7675    if is_workspace_trusted(workspace) {
7676        return false;
7677    }
7678
7679    let markers = [
7680        workspace.join(".deepseek").join("trusted"),
7681        workspace.join(".deepseek").join("trust.json"),
7682    ];
7683    !markers.iter().any(|path| path.exists())
7684}
7685
7686#[must_use]
7687pub fn is_workspace_trusted(workspace: &Path) -> bool {
7688    let config_path = match default_config_path() {
7689        Ok(path) => path,
7690        Err(error) => {
7691            tracing::error!(
7692                error = %error,
7693                "failed to resolve workspace-trust config; treating workspace as untrusted"
7694            );
7695            return false;
7696        }
7697    };
7698    let Ok(raw) = fs::read_to_string(config_path) else {
7699        return false;
7700    };
7701    let Ok(doc) = toml::from_str::<toml::Value>(&raw) else {
7702        return false;
7703    };
7704    workspace_trust_level_from_doc(&doc, workspace).is_some_and(is_trusted_level)
7705}
7706
7707pub fn save_workspace_trust(workspace: &Path) -> Result<PathBuf> {
7708    set_workspace_trust(workspace, true)
7709}
7710
7711pub fn set_workspace_trust(workspace: &Path, trusted: bool) -> Result<PathBuf> {
7712    let config_path =
7713        try_default_config_path().context("Failed to resolve config path for workspace trust.")?;
7714    ensure_parent_dir(&config_path)?;
7715
7716    let project_key = workspace_config_key(workspace);
7717    crate::config_persistence::mutate_config_document(&config_path, |doc| {
7718        crate::config_persistence::set_document_value(
7719            doc,
7720            &["projects", project_key.as_str(), "trust_level"],
7721            if trusted { "trusted" } else { "untrusted" },
7722        )
7723    })
7724    .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
7725    Ok(config_path)
7726}
7727
7728/// Project file approvals live only in user-owned config, never in the repo.
7729pub const HOOKS_RECEIPT_KEY: &str = "hooks_sha256";
7730pub const MCP_RECEIPT_KEY: &str = "mcp_sha256";
7731
7732pub fn project_receipt_for_workspace(workspace: &Path, key: &str) -> Option<String> {
7733    let raw = fs::read_to_string(default_config_path().ok()?).ok()?;
7734    let doc = toml::from_str::<toml::Value>(&raw).ok()?;
7735    doc.get("projects")?
7736        .get(workspace_config_key(workspace))?
7737        .get(key)?
7738        .as_str()
7739        .map(str::to_owned)
7740}
7741
7742pub fn save_workspace_project_receipt(
7743    workspace: &Path,
7744    key: &str,
7745    digest: &str,
7746) -> Result<PathBuf> {
7747    let config_path = try_default_config_path()?;
7748    ensure_parent_dir(&config_path)?;
7749    let project_key = workspace_config_key(workspace);
7750    crate::config_persistence::mutate_config_document(&config_path, |doc| {
7751        crate::config_persistence::set_document_value(
7752            doc,
7753            &["projects", project_key.as_str(), key],
7754            digest,
7755        )
7756    })?;
7757    Ok(config_path)
7758}
7759
7760pub fn hook_receipt_for_workspace(workspace: &Path) -> Option<String> {
7761    project_receipt_for_workspace(workspace, HOOKS_RECEIPT_KEY)
7762}
7763
7764pub fn save_workspace_hook_receipt(workspace: &Path, digest: &str) -> Result<PathBuf> {
7765    save_workspace_project_receipt(workspace, HOOKS_RECEIPT_KEY, digest)
7766}
7767
7768fn workspace_trust_level_from_doc<'a>(doc: &'a toml::Value, workspace: &Path) -> Option<&'a str> {
7769    let workspace = canonicalize_or_keep(workspace);
7770    // Trust records may sit at the top level or — from the historic
7771    // extras-nesting write bug (healed on mutation since 2026-07-23) — under
7772    // one or more literal `extras` tables. Read tolerantly so a not-yet-
7773    // healed config file still recognizes its trusted workspaces.
7774    let mut scope = Some(doc);
7775    while let Some(current) = scope {
7776        if let Some(projects) = current.get("projects").and_then(toml::Value::as_table) {
7777            for (raw_path, project) in projects {
7778                let project_path = canonicalize_or_keep(&expand_path(raw_path));
7779                if project_path == workspace {
7780                    return project.get("trust_level").and_then(toml::Value::as_str);
7781                }
7782            }
7783        }
7784        scope = current.get("extras");
7785    }
7786    None
7787}
7788
7789fn is_trusted_level(level: &str) -> bool {
7790    level.trim().eq_ignore_ascii_case("trusted")
7791}
7792
7793pub fn resolve_load_config_path(path: Option<PathBuf>) -> Result<Option<PathBuf>> {
7794    if let Some(path) = path {
7795        return Ok(Some(expand_pathbuf(path)));
7796    }
7797
7798    try_default_config_path().map(Some)
7799}
7800
7801/// Create an inspectable config file on first interactive launch.
7802///
7803/// The file intentionally omits `api_key`; onboarding or `codewhale auth set`
7804/// writes that field after the user supplies a key.
7805pub fn ensure_config_file_exists(path: Option<PathBuf>) -> Result<Option<PathBuf>> {
7806    let config_path = match path {
7807        Some(path) => expand_pathbuf(path),
7808        None => default_config_path().context("Failed to resolve config path.")?,
7809    };
7810    if config_path.exists() {
7811        return Ok(None);
7812    }
7813
7814    ensure_parent_dir(&config_path)?;
7815    let content = format!(
7816        r#"# codewhale Configuration
7817# Get your API key from https://platform.deepseek.com
7818# Save it with: codewhale auth set --provider deepseek
7819
7820# Base URL (default: https://api.deepseek.com/beta)
7821# Set https://api.deepseek.com to opt out of beta features.
7822# base_url = "https://api.deepseek.com/beta"
7823
7824# Default model
7825default_text_model = "{DEFAULT_TEXT_MODEL}"
7826
7827# Thinking mode (DeepSeek V4 reasoning effort):
7828# "auto" | "off" | "low" | "medium" | "high" | "max"
7829# Ctrl+T in the TUI (or /effort) cycles the active model's effort levels.
7830reasoning_effort = "auto"
7831
7832# Startup update check
7833[update]
7834check_for_updates = true
7835# check_interval_hours = 1
7836# update_uri = "https://internal.mirror.example/codewhale/releases/latest"
7837"#
7838    );
7839    write_config_file_secure(&config_path, &content)
7840        .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
7841    Ok(Some(config_path))
7842}
7843
7844// === Environment Overrides ===
7845
7846/// Read the `CODEWHALE_BASE_URL` env var that the CLI dispatcher forwards from
7847/// `--base-url`, or the user-set legacy `DEEPSEEK_BASE_URL` alias.  Returns `None` when the var is
7848/// absent or empty so that provider-specific defaults still apply.
7849fn env_base_url_override() -> Option<String> {
7850    codewhale_env_var("CODEWHALE_BASE_URL", "DEEPSEEK_BASE_URL")
7851        .ok()
7852        .filter(|v| !v.trim().is_empty())
7853}
7854
7855fn first_nonempty_env(names: &[&str]) -> Option<String> {
7856    let read = || {
7857        names.iter().find_map(|name| {
7858            std::env::var(name)
7859                .ok()
7860                .filter(|value| !value.trim().is_empty())
7861        })
7862    };
7863    #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
7864    {
7865        crate::test_support::with_test_env_lock(read)
7866    }
7867    #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
7868    {
7869        read()
7870    }
7871}
7872
7873/// Return the provider-scoped endpoint override that `apply_env_overrides`
7874/// will apply to the active route. This is intentionally kept beside the
7875/// mutation code: after the write, a provider-table `base_url` no longer
7876/// carries enough information to distinguish a file-owned route from an
7877/// environment-selected host.
7878fn provider_env_base_url_override(provider: ProviderKind) -> Option<String> {
7879    let names: &[&str] = match provider {
7880        ProviderKind::NvidiaNim => &["NVIDIA_NIM_BASE_URL", "NIM_BASE_URL", "NVIDIA_BASE_URL"],
7881        ProviderKind::Openai => &["OPENAI_BASE_URL"],
7882        ProviderKind::Atlascloud => &["ATLASCLOUD_BASE_URL"],
7883        ProviderKind::Openrouter => &["OPENROUTER_BASE_URL"],
7884        // The inference/catalog origin. OrcaRouter's **auth** origin is a
7885        // different host and is resolved by
7886        // `crate::oauth::resolve_orcarouter_auth_base`; the two never derive
7887        // from each other.
7888        ProviderKind::Orcarouter => &["ORCA_API_BASE_URL", "ORCA_BASE_URL", "ORCAROUTER_BASE_URL"],
7889        ProviderKind::XiaomiMimo => &["XIAOMI_MIMO_BASE_URL", "MIMO_BASE_URL"],
7890        ProviderKind::WanjieArk => &[
7891            "WANJIE_ARK_BASE_URL",
7892            "WANJIE_BASE_URL",
7893            "WANJIE_MAAS_BASE_URL",
7894        ],
7895        ProviderKind::Volcengine => &[
7896            "VOLCENGINE_BASE_URL",
7897            "VOLCENGINE_ARK_BASE_URL",
7898            "ARK_BASE_URL",
7899        ],
7900        ProviderKind::Novita => &["NOVITA_BASE_URL"],
7901        ProviderKind::Fireworks => &["FIREWORKS_BASE_URL"],
7902        ProviderKind::Siliconflow | ProviderKind::SiliconflowCN => &["SILICONFLOW_BASE_URL"],
7903        ProviderKind::Arcee => &["ARCEE_BASE_URL"],
7904        ProviderKind::Moonshot => &["MOONSHOT_BASE_URL", "KIMI_BASE_URL"],
7905        ProviderKind::Sglang => &["SGLANG_BASE_URL"],
7906        ProviderKind::Vllm => &["VLLM_BASE_URL"],
7907        ProviderKind::Ollama => &["OLLAMA_BASE_URL"],
7908        ProviderKind::OllamaCloud => &["OLLAMA_CLOUD_BASE_URL"],
7909        ProviderKind::Huggingface => &["HUGGINGFACE_BASE_URL", "HF_BASE_URL"],
7910        ProviderKind::Modelscope => &["MODELSCOPE_BASE_URL"],
7911        ProviderKind::Meta => &["META_MODEL_API_BASE_URL", "MODEL_API_BASE_URL"],
7912        ProviderKind::Xai => &["XAI_BASE_URL"],
7913        ProviderKind::Mistral => &["MISTRAL_BASE_URL"],
7914        ProviderKind::Google => &["GOOGLE_BASE_URL", "GEMINI_BASE_URL"],
7915        ProviderKind::Antigravity => &[],
7916        ProviderKind::Telecomjs => &["TELECOMJS_BASE_URL"],
7917        ProviderKind::Edenai => &["EDENAI_BASE_URL"],
7918        ProviderKind::Zenmux => &["ZENMUX_BASE_URL"],
7919        ProviderKind::Csdn => &["CSDN_BASE_URL"],
7920        ProviderKind::Concentrate => &["CONCENTRATE_BASE_URL"],
7921        ProviderKind::Codewhale => &["CODEWHALE_API_BASE"],
7922        ProviderKind::ModelstudioTokenPlan | ProviderKind::ModelstudioTokenPlanAnthropic => {
7923            &["MODELSTUDIO_TOKEN_PLAN_BASE_URL"]
7924        }
7925        ProviderKind::ModelstudioCodingPlan | ProviderKind::ModelstudioCodingPlanAnthropic => {
7926            &["MODELSTUDIO_CODING_PLAN_BASE_URL"]
7927        }
7928        ProviderKind::OpencodeGo => &["OPENCODE_GO_BASE_URL"],
7929        ProviderKind::OpencodeZen => &["OPENCODE_ZEN_BASE_URL"],
7930        ProviderKind::Deepseek
7931        | ProviderKind::DeepseekAnthropic
7932        | ProviderKind::Anthropic
7933        | ProviderKind::Openmodel
7934        | ProviderKind::Deepinfra
7935        | ProviderKind::Together
7936        | ProviderKind::Qianfan
7937        | ProviderKind::OpenaiCodex
7938        | ProviderKind::Zai
7939        | ProviderKind::Stepfun
7940        | ProviderKind::Minimax
7941        | ProviderKind::MinimaxAnthropic
7942        | ProviderKind::Sakana
7943        | ProviderKind::LongCat
7944        | ProviderKind::Custom => &[],
7945    };
7946    // `CODEWHALE_API_BASE` carries a `cwc_key_…` bearer, which has no replay
7947    // protection, so it is a trust boundary rather than a plain string: an
7948    // origin the account surface would refuse is dropped here instead of
7949    // becoming a route, and the workspace-wide insecure-HTTP escape hatch
7950    // deliberately does not reopen it.
7951    if provider == ProviderKind::Codewhale {
7952        return first_nonempty_env(names)
7953            .as_deref()
7954            .and_then(codewhale_config::provider::codewhale_api_base);
7955    }
7956    first_nonempty_env(names)
7957}
7958
7959/// Resolve an env var, preferring the `CODEWHALE_*` form over the
7960/// legacy `DEEPSEEK_*` form. Empty values are ignored so a blank shell export
7961/// does not erase configured provider settings.
7962fn codewhale_env_var(
7963    codewhale_name: &str,
7964    legacy_name: &str,
7965) -> Result<String, std::env::VarError> {
7966    let read = || {
7967        std::env::var(codewhale_name)
7968            .ok()
7969            .filter(|value| !value.trim().is_empty())
7970            .or_else(|| {
7971                std::env::var(legacy_name)
7972                    .ok()
7973                    .filter(|value| !value.trim().is_empty())
7974            })
7975            .ok_or(std::env::VarError::NotPresent)
7976    };
7977    #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
7978    {
7979        crate::test_support::with_test_env_lock(read)
7980    }
7981    #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
7982    {
7983        read()
7984    }
7985}
7986
7987fn apply_env_overrides(config: &mut Config, policy: ConfigEnvironmentPolicy) {
7988    #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
7989    {
7990        crate::test_support::with_test_env_lock(|| {
7991            apply_env_overrides_unlocked(config, policy);
7992        })
7993    }
7994    #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
7995    {
7996        apply_env_overrides_unlocked(config, policy);
7997    }
7998}
7999
8000fn apply_env_overrides_unlocked(config: &mut Config, policy: ConfigEnvironmentPolicy) {
8001    if let Ok(value) = codewhale_env_var("CODEWHALE_PROVIDER", "DEEPSEEK_PROVIDER") {
8002        config.provider = Some(value);
8003        config.route_provenance.provider_from_env = true;
8004        config.route_provenance.provider_from_saved_selection = false;
8005        config.route_provenance.provider_from_profile = false;
8006    }
8007    let Ok(identity) = config.active_provider_identity() else {
8008        return;
8009    };
8010    let active_provider = identity.provider;
8011    let active_base_url_from_env = env_base_url_override().is_some()
8012        || provider_env_base_url_override(active_provider).is_some()
8013        || (config.selects_legacy_ollama_cloud_route()
8014            && first_nonempty_env(&["OLLAMA_BASE_URL"]).is_some());
8015    let changes_root_authority = active_base_url_from_env
8016        || (policy.permits_secret_bearing_values()
8017            && std::env::var("CODEWHALE_HTTP_HEADERS")
8018                .or_else(|_| std::env::var("DEEPSEEK_HTTP_HEADERS"))
8019                .is_ok());
8020    let identity = if identity.legacy_root_custom_generation.is_some() && changes_root_authority {
8021        let Ok(exact) = config.resolve_exact_provider_identity(identity.key.as_str()) else {
8022            return;
8023        };
8024        config.legacy_root_custom_generation = None;
8025        exact
8026    } else {
8027        identity
8028    };
8029    if let Ok(value) = codewhale_env_var("CODEWHALE_BASE_URL", "DEEPSEEK_BASE_URL")
8030        && let Ok(entry) = config.provider_config_for_mut(&identity)
8031    {
8032        entry.base_url = Some(value);
8033    }
8034    if matches!(active_provider, ProviderKind::NvidiaNim)
8035        && let Ok(value) = std::env::var("NVIDIA_NIM_BASE_URL")
8036            .or_else(|_| std::env::var("NIM_BASE_URL"))
8037            .or_else(|_| std::env::var("NVIDIA_BASE_URL"))
8038        && let Ok(entry) = config.provider_config_for_mut(&identity)
8039    {
8040        entry.base_url = Some(value);
8041    }
8042    // OpenAI-compatible and non-DeepSeek hosted providers are scoped only on
8043    // their own provider entry.
8044    if matches!(active_provider, ProviderKind::Openai)
8045        && let Ok(value) = std::env::var("OPENAI_BASE_URL")
8046        && !value.trim().is_empty()
8047        && let Ok(entry) = config.provider_config_for_mut(&identity)
8048    {
8049        entry.base_url = Some(value);
8050    }
8051    if matches!(active_provider, ProviderKind::Atlascloud)
8052        && let Ok(value) = std::env::var("ATLASCLOUD_BASE_URL")
8053        && !value.trim().is_empty()
8054        && let Ok(entry) = config.provider_config_for_mut(&identity)
8055    {
8056        entry.base_url = Some(value);
8057    }
8058    if matches!(active_provider, ProviderKind::Openrouter)
8059        && let Ok(value) = std::env::var("OPENROUTER_BASE_URL")
8060        && !value.trim().is_empty()
8061        && let Ok(entry) = config.provider_config_for_mut(&identity)
8062    {
8063        entry.base_url = Some(value);
8064    }
8065    if matches!(active_provider, ProviderKind::XiaomiMimo)
8066        && let Ok(value) =
8067            std::env::var("XIAOMI_MIMO_BASE_URL").or_else(|_| std::env::var("MIMO_BASE_URL"))
8068        && !value.trim().is_empty()
8069        && let Ok(entry) = config.provider_config_for_mut(&identity)
8070    {
8071        entry.base_url = Some(value);
8072    }
8073    if matches!(active_provider, ProviderKind::XiaomiMimo)
8074        && let Ok(value) = std::env::var("XIAOMI_MIMO_MODE").or_else(|_| std::env::var("MIMO_MODE"))
8075        && !value.trim().is_empty()
8076        && let Ok(entry) = config.provider_config_for_mut(&identity)
8077    {
8078        entry.mode = Some(value);
8079    }
8080    if matches!(active_provider, ProviderKind::WanjieArk)
8081        && let Ok(value) = std::env::var("WANJIE_ARK_BASE_URL")
8082            .or_else(|_| std::env::var("WANJIE_BASE_URL"))
8083            .or_else(|_| std::env::var("WANJIE_MAAS_BASE_URL"))
8084        && !value.trim().is_empty()
8085        && let Ok(entry) = config.provider_config_for_mut(&identity)
8086    {
8087        entry.base_url = Some(value);
8088    }
8089    if matches!(active_provider, ProviderKind::Volcengine)
8090        && let Ok(value) = std::env::var("VOLCENGINE_BASE_URL")
8091            .or_else(|_| std::env::var("VOLCENGINE_ARK_BASE_URL"))
8092            .or_else(|_| std::env::var("ARK_BASE_URL"))
8093        && !value.trim().is_empty()
8094        && let Ok(entry) = config.provider_config_for_mut(&identity)
8095    {
8096        entry.base_url = Some(value);
8097    }
8098    if matches!(active_provider, ProviderKind::Novita)
8099        && let Ok(value) = std::env::var("NOVITA_BASE_URL")
8100        && !value.trim().is_empty()
8101        && let Ok(entry) = config.provider_config_for_mut(&identity)
8102    {
8103        entry.base_url = Some(value);
8104    }
8105    if matches!(active_provider, ProviderKind::Fireworks)
8106        && let Ok(value) = std::env::var("FIREWORKS_BASE_URL")
8107        && !value.trim().is_empty()
8108        && let Ok(entry) = config.provider_config_for_mut(&identity)
8109    {
8110        entry.base_url = Some(value);
8111    }
8112    if matches!(
8113        active_provider,
8114        ProviderKind::Siliconflow | ProviderKind::SiliconflowCN
8115    ) && let Ok(value) = std::env::var("SILICONFLOW_BASE_URL")
8116        && !value.trim().is_empty()
8117        && let Ok(entry) = config.provider_config_for_mut(&identity)
8118    {
8119        entry.base_url = Some(value);
8120    }
8121    if matches!(active_provider, ProviderKind::Arcee)
8122        && let Ok(value) = std::env::var("ARCEE_BASE_URL")
8123        && !value.trim().is_empty()
8124        && let Ok(entry) = config.provider_config_for_mut(&identity)
8125    {
8126        entry.base_url = Some(value);
8127    }
8128    if matches!(active_provider, ProviderKind::Huggingface)
8129        && let Ok(value) =
8130            std::env::var("HUGGINGFACE_BASE_URL").or_else(|_| std::env::var("HF_BASE_URL"))
8131        && !value.trim().is_empty()
8132        && let Ok(entry) = config.provider_config_for_mut(&identity)
8133    {
8134        entry.base_url = Some(value);
8135    }
8136    if matches!(active_provider, ProviderKind::Modelscope)
8137        && let Ok(value) = std::env::var("MODELSCOPE_BASE_URL")
8138        && !value.trim().is_empty()
8139        && let Ok(entry) = config.provider_config_for_mut(&identity)
8140    {
8141        entry.base_url = Some(value);
8142    }
8143    if matches!(active_provider, ProviderKind::Moonshot)
8144        && let Ok(value) =
8145            std::env::var("MOONSHOT_BASE_URL").or_else(|_| std::env::var("KIMI_BASE_URL"))
8146        && !value.trim().is_empty()
8147        && let Ok(entry) = config.provider_config_for_mut(&identity)
8148    {
8149        entry.base_url = Some(value);
8150    }
8151    if matches!(active_provider, ProviderKind::Sglang)
8152        && let Ok(value) = std::env::var("SGLANG_BASE_URL")
8153        && !value.trim().is_empty()
8154        && let Ok(entry) = config.provider_config_for_mut(&identity)
8155    {
8156        entry.base_url = Some(value);
8157    }
8158    if matches!(active_provider, ProviderKind::Vllm)
8159        && let Ok(value) = std::env::var("VLLM_BASE_URL")
8160        && !value.trim().is_empty()
8161        && let Ok(entry) = config.provider_config_for_mut(&identity)
8162    {
8163        entry.base_url = Some(value);
8164    }
8165    if matches!(active_provider, ProviderKind::Meta)
8166        && let Ok(value) = std::env::var("META_MODEL_API_BASE_URL")
8167            .or_else(|_| std::env::var("MODEL_API_BASE_URL"))
8168        && !value.trim().is_empty()
8169        && let Ok(entry) = config.provider_config_for_mut(&identity)
8170    {
8171        entry.base_url = Some(value);
8172    }
8173    if matches!(active_provider, ProviderKind::Xai)
8174        && let Ok(value) = std::env::var("XAI_BASE_URL")
8175        && !value.trim().is_empty()
8176        && let Ok(entry) = config.provider_config_for_mut(&identity)
8177    {
8178        entry.base_url = Some(value);
8179    }
8180    if matches!(active_provider, ProviderKind::Mistral)
8181        && let Ok(value) = std::env::var("MISTRAL_BASE_URL")
8182        && !value.trim().is_empty()
8183        && let Ok(entry) = config.provider_config_for_mut(&identity)
8184    {
8185        entry.base_url = Some(value);
8186    }
8187    if matches!(active_provider, ProviderKind::Telecomjs)
8188        && let Ok(value) = std::env::var("TELECOMJS_BASE_URL")
8189        && !value.trim().is_empty()
8190        && let Ok(entry) = config.provider_config_for_mut(&identity)
8191    {
8192        entry.base_url = Some(value);
8193    }
8194    if matches!(active_provider, ProviderKind::Edenai)
8195        && let Ok(value) = std::env::var("EDENAI_BASE_URL")
8196        && !value.trim().is_empty()
8197        && let Ok(entry) = config.provider_config_for_mut(&identity)
8198    {
8199        entry.base_url = Some(value);
8200    }
8201    if matches!(active_provider, ProviderKind::Zenmux)
8202        && let Ok(value) = std::env::var("ZENMUX_BASE_URL")
8203        && !value.trim().is_empty()
8204        && let Ok(entry) = config.provider_config_for_mut(&identity)
8205    {
8206        entry.base_url = Some(value);
8207    }
8208    if matches!(active_provider, ProviderKind::Csdn)
8209        && let Ok(value) = std::env::var("CSDN_BASE_URL")
8210        && !value.trim().is_empty()
8211        && let Ok(entry) = config.provider_config_for_mut(&identity)
8212    {
8213        entry.base_url = Some(value);
8214    }
8215    // Concentrate has no inline block here on purpose: CONCENTRATE_BASE_URL
8216    // is already served by `provider_env_base_url_override`, which the route
8217    // resolver consults — a second inline assignment was a duplicate.
8218    if matches!(
8219        active_provider,
8220        ProviderKind::ModelstudioTokenPlan | ProviderKind::ModelstudioTokenPlanAnthropic
8221    ) && let Ok(value) = std::env::var("MODELSTUDIO_TOKEN_PLAN_BASE_URL")
8222        && !value.trim().is_empty()
8223        && let Ok(entry) = config.provider_config_for_mut(&identity)
8224    {
8225        entry.base_url = Some(value);
8226    }
8227    if matches!(
8228        active_provider,
8229        ProviderKind::ModelstudioCodingPlan | ProviderKind::ModelstudioCodingPlanAnthropic
8230    ) && let Ok(value) = std::env::var("MODELSTUDIO_CODING_PLAN_BASE_URL")
8231        && !value.trim().is_empty()
8232        && let Ok(entry) = config.provider_config_for_mut(&identity)
8233    {
8234        entry.base_url = Some(value);
8235    }
8236    if policy.permits_secret_bearing_values()
8237        && let Ok(value) = std::env::var("CODEWHALE_HTTP_HEADERS")
8238            .or_else(|_| std::env::var("DEEPSEEK_HTTP_HEADERS"))
8239        && let Ok(headers) = parse_http_headers(&value)
8240        && !headers.is_empty()
8241    {
8242        let mut root_headers = config.http_headers.clone().unwrap_or_default();
8243        root_headers.extend(headers.clone());
8244        config.http_headers = Some(root_headers);
8245
8246        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8247            let mut provider_headers = entry.http_headers.clone().unwrap_or_default();
8248            provider_headers.extend(headers);
8249            entry.http_headers = Some(provider_headers);
8250        }
8251    }
8252    if config.provider.as_deref().and_then(ProviderKind::parse) == Some(ProviderKind::Ollama)
8253        && let Ok(value) = std::env::var("OLLAMA_BASE_URL")
8254        && !value.trim().is_empty()
8255        && let Ok(entry) = config.provider_config_for_mut(&identity)
8256    {
8257        entry.base_url = Some(value);
8258    }
8259    if matches!(active_provider, ProviderKind::OllamaCloud)
8260        && config.provider.as_deref().and_then(ProviderKind::parse)
8261            == Some(ProviderKind::OllamaCloud)
8262        && let Ok(value) = std::env::var("OLLAMA_CLOUD_BASE_URL")
8263        && !value.trim().is_empty()
8264        && let Ok(entry) = config.provider_config_for_mut(&identity)
8265    {
8266        entry.base_url = Some(value);
8267    }
8268    if matches!(active_provider, ProviderKind::Sglang)
8269        && let Ok(value) = std::env::var("SGLANG_MODEL")
8270    {
8271        config.default_text_model = Some(value.clone());
8272        config
8273            .set_provider_model_override(&identity, Some(value))
8274            .unwrap();
8275        config.environment_model_applied = true;
8276    }
8277    if matches!(active_provider, ProviderKind::Vllm)
8278        && let Ok(value) = std::env::var("VLLM_MODEL")
8279    {
8280        config.default_text_model = Some(value.clone());
8281        config
8282            .set_provider_model_override(&identity, Some(value))
8283            .unwrap();
8284        config.environment_model_applied = true;
8285    }
8286    if matches!(
8287        active_provider,
8288        ProviderKind::Ollama | ProviderKind::OllamaCloud
8289    ) && let Ok(value) = std::env::var("OLLAMA_MODEL")
8290    {
8291        config.default_text_model = Some(value.clone());
8292        config
8293            .set_provider_model_override(&identity, Some(value))
8294            .unwrap();
8295        config.environment_model_applied = true;
8296    }
8297    if matches!(active_provider, ProviderKind::OllamaCloud)
8298        && let Ok(value) = std::env::var("OLLAMA_CLOUD_MODEL")
8299    {
8300        config.default_text_model = Some(value.clone());
8301        config
8302            .set_provider_model_override(&identity, Some(value))
8303            .unwrap();
8304        config.environment_model_applied = true;
8305    }
8306    if matches!(active_provider, ProviderKind::Openai)
8307        && let Ok(value) = std::env::var("OPENAI_MODEL")
8308    {
8309        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8310            entry.model = Some(value);
8311        }
8312        config.environment_model_applied = true;
8313    }
8314    if matches!(active_provider, ProviderKind::XiaomiMimo)
8315        && let Ok(value) =
8316            std::env::var("XIAOMI_MIMO_MODEL").or_else(|_| std::env::var("MIMO_MODEL"))
8317    {
8318        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8319            entry.model = Some(value);
8320        }
8321        config.environment_model_applied = true;
8322    }
8323    if matches!(active_provider, ProviderKind::Atlascloud)
8324        && let Ok(value) = std::env::var("ATLASCLOUD_MODEL")
8325    {
8326        config.default_text_model = Some(value.clone());
8327        config
8328            .set_provider_model_override(&identity, Some(value))
8329            .unwrap();
8330        config.environment_model_applied = true;
8331    }
8332    if matches!(active_provider, ProviderKind::WanjieArk)
8333        && let Ok(value) = std::env::var("WANJIE_ARK_MODEL")
8334            .or_else(|_| std::env::var("WANJIE_MODEL"))
8335            .or_else(|_| std::env::var("WANJIE_MAAS_MODEL"))
8336        && !value.trim().is_empty()
8337    {
8338        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8339            entry.model = Some(value);
8340        }
8341        config.environment_model_applied = true;
8342    }
8343    if matches!(active_provider, ProviderKind::Openrouter)
8344        && let Ok(value) = std::env::var("OPENROUTER_MODEL")
8345        && !value.trim().is_empty()
8346    {
8347        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8348            entry.model = Some(value);
8349        }
8350        config.environment_model_applied = true;
8351    }
8352    if matches!(active_provider, ProviderKind::Volcengine)
8353        && let Ok(value) =
8354            std::env::var("VOLCENGINE_MODEL").or_else(|_| std::env::var("VOLCENGINE_ARK_MODEL"))
8355        && !value.trim().is_empty()
8356    {
8357        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8358            entry.model = Some(value);
8359        }
8360        config.environment_model_applied = true;
8361    }
8362    if matches!(active_provider, ProviderKind::Novita)
8363        && let Ok(value) = std::env::var("NOVITA_MODEL")
8364        && !value.trim().is_empty()
8365    {
8366        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8367            entry.model = Some(value);
8368        }
8369        config.environment_model_applied = true;
8370    }
8371    if matches!(active_provider, ProviderKind::Fireworks)
8372        && let Ok(value) = std::env::var("FIREWORKS_MODEL")
8373        && !value.trim().is_empty()
8374    {
8375        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8376            entry.model = Some(value);
8377        }
8378        config.environment_model_applied = true;
8379    }
8380    if matches!(active_provider, ProviderKind::Moonshot)
8381        && let Ok(value) = std::env::var("MOONSHOT_MODEL")
8382            .or_else(|_| std::env::var("KIMI_MODEL_NAME"))
8383            .or_else(|_| std::env::var("KIMI_MODEL"))
8384        && !value.trim().is_empty()
8385    {
8386        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8387            entry.model = Some(value);
8388        }
8389        config.environment_model_applied = true;
8390    }
8391    if matches!(
8392        active_provider,
8393        ProviderKind::Siliconflow | ProviderKind::SiliconflowCN
8394    ) && let Ok(value) = std::env::var("SILICONFLOW_MODEL")
8395        && !value.trim().is_empty()
8396    {
8397        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8398            entry.model = Some(value);
8399        }
8400        config.environment_model_applied = true;
8401    }
8402    if matches!(active_provider, ProviderKind::Arcee)
8403        && let Ok(value) = std::env::var("ARCEE_MODEL")
8404        && !value.trim().is_empty()
8405    {
8406        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8407            entry.model = Some(value);
8408        }
8409        config.environment_model_applied = true;
8410    }
8411    if matches!(active_provider, ProviderKind::Huggingface)
8412        && let Ok(value) = std::env::var("HUGGINGFACE_MODEL").or_else(|_| std::env::var("HF_MODEL"))
8413        && !value.trim().is_empty()
8414    {
8415        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8416            entry.model = Some(value);
8417        }
8418        config.environment_model_applied = true;
8419    }
8420    if matches!(active_provider, ProviderKind::Modelscope)
8421        && let Ok(value) = std::env::var("MODELSCOPE_MODEL")
8422        && !value.trim().is_empty()
8423    {
8424        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8425            entry.model = Some(value);
8426        }
8427        config.environment_model_applied = true;
8428    }
8429    if matches!(active_provider, ProviderKind::Meta)
8430        && let Ok(value) =
8431            std::env::var("META_MODEL_API_MODEL").or_else(|_| std::env::var("MODEL_API_MODEL"))
8432        && !value.trim().is_empty()
8433    {
8434        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8435            entry.model = Some(value);
8436        }
8437        config.environment_model_applied = true;
8438    }
8439    if matches!(active_provider, ProviderKind::Xai)
8440        && let Ok(value) = std::env::var("XAI_MODEL")
8441        && !value.trim().is_empty()
8442    {
8443        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8444            entry.model = Some(value);
8445        }
8446        config.environment_model_applied = true;
8447    }
8448    if matches!(active_provider, ProviderKind::Mistral)
8449        && let Ok(value) = std::env::var("MISTRAL_MODEL")
8450        && !value.trim().is_empty()
8451    {
8452        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8453            entry.model = Some(value);
8454        }
8455        config.environment_model_applied = true;
8456    }
8457    if matches!(active_provider, ProviderKind::OpencodeGo)
8458        && let Ok(value) = std::env::var("OPENCODE_GO_MODEL")
8459        && !value.trim().is_empty()
8460    {
8461        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8462            entry.model = Some(value);
8463        }
8464        config.environment_model_applied = true;
8465    }
8466    if matches!(active_provider, ProviderKind::Telecomjs)
8467        && let Ok(value) = std::env::var("TELECOMJS_MODEL")
8468        && !value.trim().is_empty()
8469    {
8470        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8471            entry.model = Some(value);
8472        }
8473        config.environment_model_applied = true;
8474    }
8475    if matches!(active_provider, ProviderKind::Concentrate)
8476        && let Ok(value) = std::env::var("CONCENTRATE_MODEL")
8477        && !value.trim().is_empty()
8478    {
8479        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8480            entry.model = Some(value);
8481        }
8482        config.environment_model_applied = true;
8483    }
8484    if matches!(active_provider, ProviderKind::Edenai)
8485        && let Ok(value) = std::env::var("EDENAI_MODEL")
8486        && !value.trim().is_empty()
8487    {
8488        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8489            entry.model = Some(value);
8490        }
8491        config.environment_model_applied = true;
8492    }
8493    if matches!(active_provider, ProviderKind::Zenmux)
8494        && let Ok(value) = std::env::var("ZENMUX_MODEL")
8495        && !value.trim().is_empty()
8496    {
8497        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8498            entry.model = Some(value);
8499        }
8500        config.environment_model_applied = true;
8501    }
8502    if matches!(active_provider, ProviderKind::Csdn)
8503        && let Ok(value) = std::env::var("CSDN_MODEL")
8504        && !value.trim().is_empty()
8505    {
8506        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8507            entry.model = Some(value);
8508        }
8509        config.environment_model_applied = true;
8510    }
8511    if matches!(
8512        active_provider,
8513        ProviderKind::ModelstudioTokenPlan | ProviderKind::ModelstudioTokenPlanAnthropic
8514    ) && let Ok(value) = std::env::var("MODELSTUDIO_TOKEN_PLAN_MODEL")
8515        && !value.trim().is_empty()
8516    {
8517        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8518            entry.model = Some(value);
8519        }
8520        config.environment_model_applied = true;
8521    }
8522    if matches!(
8523        active_provider,
8524        ProviderKind::ModelstudioCodingPlan | ProviderKind::ModelstudioCodingPlanAnthropic
8525    ) && let Ok(value) = std::env::var("MODELSTUDIO_CODING_PLAN_MODEL")
8526        && !value.trim().is_empty()
8527    {
8528        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8529            entry.model = Some(value);
8530        }
8531        config.environment_model_applied = true;
8532    }
8533    if matches!(active_provider, ProviderKind::OpencodeZen)
8534        && let Ok(value) = std::env::var("OPENCODE_ZEN_MODEL")
8535        && !value.trim().is_empty()
8536    {
8537        if let Ok(entry) = config.provider_config_for_mut(&identity) {
8538            entry.model = Some(value);
8539        }
8540        config.environment_model_applied = true;
8541    }
8542    if matches!(active_provider, ProviderKind::NvidiaNim)
8543        && let Ok(value) = std::env::var("NVIDIA_NIM_MODEL")
8544    {
8545        config.default_text_model = Some(value.clone());
8546        config
8547            .set_provider_model_override(&identity, Some(value))
8548            .unwrap();
8549        config.environment_model_applied = true;
8550    }
8551    if let Some(value) = codewhale_env_var("CODEWHALE_MODEL", "DEEPSEEK_MODEL")
8552        .ok()
8553        .or_else(|| {
8554            std::env::var("DEEPSEEK_DEFAULT_TEXT_MODEL")
8555                .ok()
8556                .filter(|value| !value.trim().is_empty())
8557        })
8558    {
8559        if matches!(
8560            active_provider,
8561            ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
8562        ) {
8563            config.default_text_model = Some(value.clone());
8564        }
8565        config
8566            .set_provider_model_override(&identity, Some(value))
8567            .unwrap();
8568        config.environment_model_applied = true;
8569    }
8570    if let Ok(value) =
8571        std::env::var("CODEWHALE_SKILLS_DIR").or_else(|_| std::env::var("DEEPSEEK_SKILLS_DIR"))
8572    {
8573        config.skills_dir = Some(value);
8574    }
8575    if let Ok(value) =
8576        std::env::var("CODEWHALE_MCP_CONFIG").or_else(|_| std::env::var("DEEPSEEK_MCP_CONFIG"))
8577    {
8578        config.mcp_config_path = Some(value);
8579    }
8580    if let Ok(value) =
8581        std::env::var("CODEWHALE_NOTES_PATH").or_else(|_| std::env::var("DEEPSEEK_NOTES_PATH"))
8582    {
8583        config.notes_path = Some(value);
8584    }
8585    if let Ok(value) =
8586        std::env::var("CODEWHALE_MEMORY_PATH").or_else(|_| std::env::var("DEEPSEEK_MEMORY_PATH"))
8587    {
8588        config.memory_path = Some(value);
8589    }
8590    if let Ok(value) =
8591        std::env::var("CODEWHALE_MEMORY").or_else(|_| std::env::var("DEEPSEEK_MEMORY"))
8592    {
8593        let on = matches!(
8594            value.trim().to_ascii_lowercase().as_str(),
8595            "1" | "on" | "true" | "yes" | "y" | "enabled"
8596        );
8597        config
8598            .memory
8599            .get_or_insert_with(MemoryConfig::default)
8600            .enabled = Some(on);
8601    }
8602    if let Ok(value) =
8603        std::env::var("CODEWHALE_ALLOW_SHELL").or_else(|_| std::env::var("DEEPSEEK_ALLOW_SHELL"))
8604    {
8605        config.allow_shell = Some(value == "1" || value.eq_ignore_ascii_case("true"));
8606    }
8607    if let Ok(value) = std::env::var("CODEWHALE_APPROVAL_POLICY")
8608        .or_else(|_| std::env::var("DEEPSEEK_APPROVAL_POLICY"))
8609    {
8610        config.approval_policy = Some(value);
8611    }
8612    if let Ok(value) =
8613        std::env::var("CODEWHALE_SANDBOX_MODE").or_else(|_| std::env::var("DEEPSEEK_SANDBOX_MODE"))
8614    {
8615        config.sandbox_mode = Some(value);
8616    }
8617    if let Ok(value) = std::env::var("CODEWHALE_SANDBOX_NETWORK_ACCESS")
8618        .or_else(|_| std::env::var("DEEPSEEK_SANDBOX_NETWORK_ACCESS"))
8619    {
8620        config.sandbox_network_access = Some(value == "1" || value.eq_ignore_ascii_case("true"));
8621    }
8622    if let Ok(value) = std::env::var("CODEWHALE_PROJECT_INSTRUCTION_IMPORTS") {
8623        config.project_instruction_imports = value
8624            .split(',')
8625            .map(str::trim)
8626            .filter(|part| !part.is_empty())
8627            .map(str::to_string)
8628            .collect();
8629    }
8630    // `DEEPSEEK_YOLO` is a read-only deprecated alias of `CODEWHALE_YOLO`
8631    // (removable in 0.10 per issue #5443); `CODEWHALE_YOLO` wins when both
8632    // are set.
8633    if let Ok(value) = std::env::var("CODEWHALE_YOLO").or_else(|_| std::env::var("DEEPSEEK_YOLO")) {
8634        config.yolo = Some(value == "1" || value.eq_ignore_ascii_case("true"));
8635    }
8636    if let Ok(value) =
8637        std::env::var("CODEWHALE_VERBOSITY").or_else(|_| std::env::var("DEEPSEEK_VERBOSITY"))
8638    {
8639        config.verbosity = Some(value);
8640    }
8641    if let Ok(value) = std::env::var("CODEWHALE_SANDBOX_BACKEND")
8642        .or_else(|_| std::env::var("DEEPSEEK_SANDBOX_BACKEND"))
8643    {
8644        config.sandbox_backend = Some(value);
8645    }
8646    if let Ok(value) = codewhale_env_var("CODEWHALE_PREFER_BWRAP", "DEEPSEEK_PREFER_BWRAP") {
8647        let primary_is_set = std::env::var("CODEWHALE_PREFER_BWRAP")
8648            .ok()
8649            .is_some_and(|value| !value.trim().is_empty());
8650        let legacy_is_set = std::env::var("DEEPSEEK_PREFER_BWRAP")
8651            .ok()
8652            .is_some_and(|value| !value.trim().is_empty());
8653        if !primary_is_set && legacy_is_set {
8654            tracing::warn!(
8655                "DEEPSEEK_PREFER_BWRAP is deprecated; use CODEWHALE_PREFER_BWRAP (the legacy alias is removed in 0.10.0)"
8656            );
8657        }
8658        config.prefer_bwrap = Some(value == "1" || value.eq_ignore_ascii_case("true"));
8659    }
8660    if let Ok(value) =
8661        std::env::var("CODEWHALE_SANDBOX_URL").or_else(|_| std::env::var("DEEPSEEK_SANDBOX_URL"))
8662    {
8663        config.sandbox_url = Some(value);
8664    }
8665    if policy.permits_secret_bearing_values()
8666        && let Ok(value) = std::env::var("CODEWHALE_SANDBOX_API_KEY")
8667            .or_else(|_| std::env::var("DEEPSEEK_SANDBOX_API_KEY"))
8668    {
8669        config.sandbox_api_key = Some(value);
8670    }
8671    if let Ok(value) = codewhale_env_var(
8672        "CODEWHALE_MANAGED_CONFIG_PATH",
8673        "DEEPSEEK_MANAGED_CONFIG_PATH",
8674    ) {
8675        config.managed_config_path = Some(value);
8676    }
8677    if policy.permits_secret_bearing_values()
8678        && let Ok(value) = std::env::var("CODEWHALE_SEARCH_API_KEY")
8679            .or_else(|_| std::env::var("DEEPSEEK_SEARCH_API_KEY"))
8680        && !value.trim().is_empty()
8681    {
8682        config
8683            .search
8684            .get_or_insert_with(SearchConfig::default)
8685            .api_key = Some(value);
8686    }
8687    if let Ok(value) = codewhale_env_var("CODEWHALE_SEARCH_BASE_URL", "DEEPSEEK_SEARCH_BASE_URL") {
8688        config
8689            .search
8690            .get_or_insert_with(SearchConfig::default)
8691            .base_url = Some(value);
8692    }
8693    if let Ok(value) = std::env::var("CODEWHALE_REQUIREMENTS_PATH")
8694        .or_else(|_| std::env::var("DEEPSEEK_REQUIREMENTS_PATH"))
8695    {
8696        config.requirements_path = Some(value);
8697    }
8698    if let Ok(value) = std::env::var("CODEWHALE_MAX_SUBAGENTS")
8699        .or_else(|_| std::env::var("DEEPSEEK_MAX_SUBAGENTS"))
8700        && let Ok(parsed) = value.parse::<usize>()
8701    {
8702        config.max_subagents = Some(parsed.clamp(1, MAX_SUBAGENTS));
8703    }
8704    // Always leave a receipt: "the environment layer ran and nobody owns the
8705    // base URL" is a different, stronger statement than "no receipt", and only
8706    // the explicit form stops a pinned cross-provider child from treating the
8707    // ambient generic host as a global fallback.
8708    config.base_url_env_receipt = if active_base_url_from_env {
8709        BaseUrlEnvReceipt::Route(active_provider, identity.key.to_string())
8710    } else {
8711        BaseUrlEnvReceipt::NoOwner
8712    };
8713}
8714
8715fn normalize_model_config(config: &mut Config) {
8716    if config.default_text_model.is_none() {
8717        config.default_text_model.clone_from(&config.legacy_model);
8718    }
8719    let Ok(identity) = config.active_provider_identity() else {
8720        return;
8721    };
8722    let provider = identity.provider;
8723    let base_url = config.active_route_base_url();
8724    let mut declared = Vec::new();
8725    for row in codewhale_config::descriptors::provider_compatibility() {
8726        let Ok(candidate) = config.resolve_persisted_provider_identity(Some(row.id), Some(row.id))
8727        else {
8728            continue;
8729        };
8730        for model in config.custom_models.as_deref().unwrap_or_default() {
8731            if configured_model_for_route(
8732                config,
8733                candidate.provider,
8734                candidate.key.as_str(),
8735                &config.base_url_for_route(&candidate),
8736                &model.id,
8737            )
8738            .is_some()
8739            {
8740                declared.push((candidate.key.clone(), model.id.clone()));
8741            }
8742        }
8743    }
8744    let is_declared = |key: &str, model: &str| {
8745        declared
8746            .iter()
8747            .any(|(id, value)| id.as_str() == key && value == model)
8748    };
8749    config.migrated_deepseek_model_alias = if matches!(
8750        provider,
8751        ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
8752    ) {
8753        config
8754            .active_configured_model_id()
8755            .filter(|model| !is_declared(identity.key.as_str(), model))
8756            .map(str::to_ascii_lowercase)
8757            .filter(|model| deepseek_alias_deprecation(model).is_some())
8758            .filter(|model| {
8759                codewhale_config::route::resolve_model(provider, model, Some(&base_url))
8760                    .is_ok_and(|resolved| resolved.wire_id != model.as_str())
8761            })
8762    } else {
8763        None
8764    };
8765
8766    if config.reasoning_effort.is_none() {
8767        let alias_effort = config
8768            .migrated_deepseek_model_alias
8769            .as_deref()
8770            .and_then(legacy_deepseek_alias_reasoning_effort);
8771        if let Some(effort) = alias_effort {
8772            config.reasoning_effort = Some(effort.to_string());
8773            config.reasoning_effort_inferred_from_legacy_alias = true;
8774        }
8775    }
8776
8777    if let Some(model) = config.default_text_model.as_deref()
8778        && !is_declared(identity.key.as_str(), model)
8779        && !codewhale_config::descriptors::provider_passes_model_through(provider)
8780        && !config.active_provider_preserves_custom_base_url_model()
8781        && let Ok(resolved) = codewhale_config::route::resolve_model(provider, model, None)
8782    {
8783        config.default_text_model = Some(resolved.wire_id);
8784    }
8785
8786    if let Some(providers) = config.providers.as_mut() {
8787        if let Some(model) = providers.deepseek.model.as_deref()
8788            && !provider_entry_uses_custom_base_url(ProviderKind::Deepseek, &providers.deepseek)
8789            && !is_declared(ProviderKind::Deepseek.as_str(), model)
8790            && let Ok(resolved) =
8791                codewhale_config::route::resolve_model(ProviderKind::Deepseek, model, None)
8792        {
8793            providers.deepseek.model = Some(resolved.wire_id);
8794        }
8795        if let Some(model) = providers.deepseek_cn.model.as_deref()
8796            && !provider_entry_uses_custom_base_url(ProviderKind::Deepseek, &providers.deepseek_cn)
8797            && !is_declared(codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id, model)
8798            && let Ok(resolved) =
8799                codewhale_config::route::resolve_model(ProviderKind::Deepseek, model, None)
8800        {
8801            providers.deepseek_cn.model = Some(resolved.wire_id);
8802        }
8803        if let Some(model) = providers.deepseek_anthropic.model.as_deref()
8804            && !provider_entry_uses_custom_base_url(
8805                ProviderKind::DeepseekAnthropic,
8806                &providers.deepseek_anthropic,
8807            )
8808            && !is_declared(ProviderKind::DeepseekAnthropic.as_str(), model)
8809            && let Ok(resolved) =
8810                codewhale_config::route::resolve_model(ProviderKind::DeepseekAnthropic, model, None)
8811        {
8812            providers.deepseek_anthropic.model = Some(resolved.wire_id);
8813        }
8814        if let Some(model) = providers.nvidia_nim.model.as_deref()
8815            && !provider_entry_uses_custom_base_url(ProviderKind::NvidiaNim, &providers.nvidia_nim)
8816            && !is_declared(ProviderKind::NvidiaNim.as_str(), model)
8817            && let Ok(resolved) =
8818                codewhale_config::route::resolve_model(ProviderKind::NvidiaNim, model, None)
8819        {
8820            providers.nvidia_nim.model = Some(resolved.wire_id);
8821        }
8822        if let Some(model) = providers.openrouter.model.as_deref()
8823            && !provider_entry_uses_custom_base_url(ProviderKind::Openrouter, &providers.openrouter)
8824            && !is_declared(ProviderKind::Openrouter.as_str(), model)
8825            && let Ok(resolved) =
8826                codewhale_config::route::resolve_model(ProviderKind::Openrouter, model, None)
8827        {
8828            providers.openrouter.model = Some(resolved.wire_id);
8829        }
8830        if let Some(model) = providers.novita.model.as_deref()
8831            && !provider_entry_uses_custom_base_url(ProviderKind::Novita, &providers.novita)
8832            && !is_declared(ProviderKind::Novita.as_str(), model)
8833            && let Ok(resolved) =
8834                codewhale_config::route::resolve_model(ProviderKind::Novita, model, None)
8835        {
8836            providers.novita.model = Some(resolved.wire_id);
8837        }
8838        if let Some(model) = providers.fireworks.model.as_deref()
8839            && !provider_entry_uses_custom_base_url(ProviderKind::Fireworks, &providers.fireworks)
8840            && !is_declared(ProviderKind::Fireworks.as_str(), model)
8841            && let Ok(resolved) =
8842                codewhale_config::route::resolve_model(ProviderKind::Fireworks, model, None)
8843        {
8844            providers.fireworks.model = Some(resolved.wire_id);
8845        }
8846        if let Some(model) = providers.siliconflow.model.as_deref()
8847            && !provider_entry_uses_custom_base_url(
8848                ProviderKind::Siliconflow,
8849                &providers.siliconflow,
8850            )
8851            && !is_declared(ProviderKind::Siliconflow.as_str(), model)
8852            && let Ok(resolved) =
8853                codewhale_config::route::resolve_model(ProviderKind::Siliconflow, model, None)
8854        {
8855            providers.siliconflow.model = Some(resolved.wire_id);
8856        }
8857        if let Some(model) = providers.siliconflow_cn.model.as_deref()
8858            && !provider_entry_uses_custom_base_url(
8859                ProviderKind::SiliconflowCN,
8860                &providers.siliconflow_cn,
8861            )
8862            && !is_declared(ProviderKind::SiliconflowCN.as_str(), model)
8863            && let Ok(resolved) =
8864                codewhale_config::route::resolve_model(ProviderKind::SiliconflowCN, model, None)
8865        {
8866            providers.siliconflow_cn.model = Some(resolved.wire_id);
8867        }
8868        if let Some(model) = providers.moonshot.model.as_deref()
8869            && !provider_entry_uses_custom_base_url(ProviderKind::Moonshot, &providers.moonshot)
8870            && !is_declared(ProviderKind::Moonshot.as_str(), model)
8871            && let Ok(resolved) =
8872                codewhale_config::route::resolve_model(ProviderKind::Moonshot, model, None)
8873        {
8874            providers.moonshot.model = Some(resolved.wire_id);
8875        }
8876        if let Some(model) = providers.sglang.model.as_deref()
8877            && !provider_entry_uses_custom_base_url(ProviderKind::Sglang, &providers.sglang)
8878            && !is_declared(ProviderKind::Sglang.as_str(), model)
8879            && let Ok(resolved) =
8880                codewhale_config::route::resolve_model(ProviderKind::Sglang, model, None)
8881        {
8882            providers.sglang.model = Some(resolved.wire_id);
8883        }
8884        if let Some(model) = providers.vllm.model.as_deref()
8885            && !provider_entry_uses_custom_base_url(ProviderKind::Vllm, &providers.vllm)
8886            && !is_declared(ProviderKind::Vllm.as_str(), model)
8887            && let Ok(resolved) =
8888                codewhale_config::route::resolve_model(ProviderKind::Vllm, model, None)
8889        {
8890            providers.vllm.model = Some(resolved.wire_id);
8891        }
8892        if let Some(model) = providers.deepinfra.model.as_deref()
8893            && !provider_entry_uses_custom_base_url(ProviderKind::Deepinfra, &providers.deepinfra)
8894            && !is_declared(ProviderKind::Deepinfra.as_str(), model)
8895            && let Ok(resolved) =
8896                codewhale_config::route::resolve_model(ProviderKind::Deepinfra, model, None)
8897        {
8898            providers.deepinfra.model = Some(resolved.wire_id);
8899        }
8900    }
8901}
8902
8903#[cfg(any(test, feature = "test-support"))]
8904pub fn normalize_model_config_for_test(config: &mut Config) {
8905    normalize_model_config(config);
8906}
8907
8908fn provider_entry_uses_custom_base_url(provider: ProviderKind, entry: &ProviderConfig) -> bool {
8909    entry
8910        .base_url
8911        .as_deref()
8912        .is_some_and(|base_url| provider_preserves_custom_base_url_model(provider, base_url))
8913}
8914
8915fn xiaomi_mimo_base_url_uses_token_plan(base_url: &str) -> bool {
8916    let normalized = normalize_base_url(base_url).to_ascii_lowercase();
8917    normalized == XIAOMI_MIMO_TOKEN_PLAN_CN_BASE_URL
8918        || normalized == XIAOMI_MIMO_TOKEN_PLAN_SGP_BASE_URL
8919        || normalized == XIAOMI_MIMO_TOKEN_PLAN_AMS_BASE_URL
8920}
8921
8922fn xiaomi_mimo_env_var(candidates: &[&str]) -> Option<String> {
8923    candidates.iter().find_map(|name| {
8924        std::env::var(name)
8925            .ok()
8926            .filter(|value| !value.trim().is_empty())
8927    })
8928}
8929
8930fn xiaomi_mimo_env_api_key_for_runtime(
8931    mode: Option<&str>,
8932    base_url: Option<&str>,
8933) -> Option<String> {
8934    const TOKEN_PLAN_ENV_VARS: &[&str] =
8935        &["XIAOMI_MIMO_TOKEN_PLAN_API_KEY", "MIMO_TOKEN_PLAN_API_KEY"];
8936    const STANDARD_ENV_VARS: &[&str] = &["XIAOMI_MIMO_API_KEY", "XIAOMI_API_KEY", "MIMO_API_KEY"];
8937
8938    let normalized_mode =
8939        mode.map(|value| value.trim().to_ascii_lowercase().replace(['_', ' '], "-"));
8940    let standard_selected = normalized_mode
8941        .as_deref()
8942        .is_some_and(xiaomi_mimo_mode_uses_standard_endpoint)
8943        || base_url.is_some_and(xiaomi_mimo_base_url_is_pay_as_you_go);
8944    if standard_selected {
8945        return xiaomi_mimo_env_var(STANDARD_ENV_VARS);
8946    }
8947
8948    let token_plan_selected = normalized_mode
8949        .as_deref()
8950        .and_then(xiaomi_mimo_base_url_for_mode)
8951        .is_some()
8952        || base_url.is_some_and(xiaomi_mimo_base_url_uses_token_plan);
8953    if token_plan_selected {
8954        return xiaomi_mimo_env_var(TOKEN_PLAN_ENV_VARS);
8955    }
8956
8957    xiaomi_mimo_env_var(TOKEN_PLAN_ENV_VARS).or_else(|| xiaomi_mimo_env_var(STANDARD_ENV_VARS))
8958}
8959
8960fn wire_config_prefers_anthropic(wire: Option<&str>) -> bool {
8961    codewhale_config::provider::wire_dialect_prefers_anthropic(wire)
8962}
8963
8964fn modelstudio_mode_is_coding_plan(provider: ProviderKind, mode: Option<&str>) -> bool {
8965    if matches!(
8966        provider,
8967        ProviderKind::ModelstudioCodingPlan | ProviderKind::ModelstudioCodingPlanAnthropic
8968    ) {
8969        return true;
8970    }
8971    let Some(raw) = mode.map(str::trim).filter(|value| !value.is_empty()) else {
8972        return false;
8973    };
8974    let normalized = raw.to_ascii_lowercase().replace(['_', ' '], "-");
8975    matches!(
8976        normalized.as_str(),
8977        "coding-plan" | "coding" | "codingplan" | "dashscope-coding" | "code"
8978    )
8979}
8980
8981fn resolve_modelstudio_base_url_for_tui(
8982    configured: Option<String>,
8983    provider: ProviderKind,
8984    mode: Option<&str>,
8985    wire: Option<&str>,
8986) -> String {
8987    if let Some(url) = configured.filter(|value| !value.trim().is_empty()) {
8988        return url;
8989    }
8990    let coding = modelstudio_mode_is_coding_plan(provider, mode);
8991    let anthropic = matches!(
8992        provider,
8993        ProviderKind::ModelstudioTokenPlanAnthropic | ProviderKind::ModelstudioCodingPlanAnthropic
8994    ) || wire_config_prefers_anthropic(wire);
8995    match (coding, anthropic) {
8996        (true, true) => MODELSTUDIO_CODING_PLAN_ANTHROPIC_BASE_URL.to_string(),
8997        (true, false) => DEFAULT_MODELSTUDIO_CODING_PLAN_BASE_URL.to_string(),
8998        (false, true) => MODELSTUDIO_TOKEN_PLAN_ANTHROPIC_BASE_URL.to_string(),
8999        (false, false) => DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL.to_string(),
9000    }
9001}
9002
9003fn resolve_minimax_base_url_for_tui(
9004    configured: Option<String>,
9005    provider: ProviderKind,
9006    wire: Option<&str>,
9007) -> String {
9008    if let Some(url) = configured.filter(|value| !value.trim().is_empty()) {
9009        return url;
9010    }
9011    if matches!(provider, ProviderKind::MinimaxAnthropic) || wire_config_prefers_anthropic(wire) {
9012        DEFAULT_MINIMAX_ANTHROPIC_BASE_URL.to_string()
9013    } else {
9014        DEFAULT_MINIMAX_BASE_URL.to_string()
9015    }
9016}
9017
9018fn resolve_deepseek_base_url_for_tui(
9019    configured: Option<String>,
9020    provider: ProviderKind,
9021    wire: Option<&str>,
9022) -> String {
9023    if let Some(url) = configured.filter(|value| !value.trim().is_empty()) {
9024        return url;
9025    }
9026    if matches!(provider, ProviderKind::DeepseekAnthropic) || wire_config_prefers_anthropic(wire) {
9027        DEFAULT_DEEPSEEK_ANTHROPIC_BASE_URL.to_string()
9028    } else {
9029        DEFAULT_DEEPSEEK_BASE_URL.to_string()
9030    }
9031}
9032
9033fn xiaomi_mimo_base_url_is_pay_as_you_go(base_url: &str) -> bool {
9034    matches!(
9035        normalize_base_url(base_url).to_ascii_lowercase().as_str(),
9036        "https://api.xiaomimimo.com" | "https://api.xiaomimimo.com/v1"
9037    )
9038}
9039
9040fn base_url_is_custom_for_provider(provider: ProviderKind, base_url: &str) -> bool {
9041    codewhale_config::provider_preserves_custom_base_url_model(provider, base_url)
9042}
9043
9044/// Whether this concrete route is a self-hosted endpoint whose credentials
9045/// are optional by default.
9046///
9047/// Ollama is local; the released exact `ollama` + `https://ollama.com/v1`
9048/// tuple is upgraded to `OllamaCloud` before this helper runs. Cloud is never
9049/// self-hosted, while neighboring remote Ollama URLs remain custom and are
9050/// rejected before they can inherit ambient or saved credentials.
9051pub fn provider_route_is_keyless_self_hosted(provider: ProviderKind, base_url: &str) -> bool {
9052    if provider == ProviderKind::Ollama {
9053        return base_url_uses_local_host(base_url);
9054    }
9055    matches!(
9056        provider,
9057        ProviderKind::Ollama | ProviderKind::Sglang | ProviderKind::Vllm
9058    )
9059}
9060
9061/// The Kimi Code API endpoint, normalized only for insignificant trailing
9062/// slashes. This must stay stricter than `moonshot_base_url_uses_kimi_code`:
9063/// route-specific K3 capability and request shaping are not safe for arbitrary
9064/// Kimi-hosted paths.
9065pub fn moonshot_base_url_is_exact_kimi_code(base_url: &str) -> bool {
9066    codewhale_config::provider::is_exact_kimi_code_route(
9067        codewhale_config::ProviderKind::Moonshot,
9068        base_url,
9069    )
9070}
9071
9072/// The exact Moonshot direct-API endpoint, normalized only for an
9073/// insignificant trailing slash. Custom gateways must retain their own wire
9074/// contract even when they expose a `kimi-k3` model id.
9075pub fn moonshot_base_url_is_exact_direct_platform(base_url: &str) -> bool {
9076    codewhale_config::provider::is_exact_moonshot_platform_route(
9077        codewhale_config::ProviderKind::Moonshot,
9078        base_url,
9079    )
9080}
9081
9082/// Whether a route is exactly Moonshot's direct pay-as-you-go K3 route.
9083pub fn is_exact_direct_moonshot_k3_route(
9084    provider: ProviderKind,
9085    base_url: &str,
9086    model: &str,
9087) -> bool {
9088    provider == ProviderKind::Moonshot
9089        && moonshot_base_url_is_exact_direct_platform(base_url)
9090        && model.trim().eq_ignore_ascii_case(MOONSHOT_KIMI_K3_MODEL)
9091}
9092
9093/// Whether a route uses either official Kimi Code K3 membership model.
9094pub fn is_exact_kimi_code_k3_route(provider: ProviderKind, base_url: &str, model: &str) -> bool {
9095    provider == ProviderKind::Moonshot
9096        && moonshot_base_url_is_exact_kimi_code(base_url)
9097        && [KIMI_CODE_K3_MODEL, KIMI_CODE_K3_256K_MODEL]
9098            .iter()
9099            .any(|id| model.trim().eq_ignore_ascii_case(id))
9100}
9101
9102/// Whether a route uses plan-tier-dependent bare `k3`.
9103///
9104/// Keep entitlement handling separate from `k3-256k`, whose window is fixed.
9105#[must_use]
9106pub fn is_exact_kimi_code_bare_k3_route(
9107    provider: ProviderKind,
9108    base_url: &str,
9109    model: &str,
9110) -> bool {
9111    provider == ProviderKind::Moonshot
9112        && moonshot_base_url_is_exact_kimi_code(base_url)
9113        && model.trim().eq_ignore_ascii_case(KIMI_CODE_K3_MODEL)
9114}
9115
9116/// Whether a route is one of Z.ai's exact first-party Chat endpoints.
9117#[must_use]
9118pub fn is_exact_zai_chat_route(provider: ProviderKind, base_url: &str) -> bool {
9119    provider == ProviderKind::Zai
9120        && codewhale_config::provider::is_exact_zai_chat_route(
9121            codewhale_config::ProviderKind::Zai,
9122            base_url,
9123        )
9124}
9125
9126/// Whether a route is an exact first-party Z.ai model that exposes **tiered**
9127/// reasoning effort (`reasoning_effort: high | max`) rather than only the
9128/// generic thinking toggle.
9129///
9130/// GLM-5.2 is the verified member. GLM-5.3 and GLM-5.3-Flash inherit it
9131/// because their catalog rows inherit GLM-5.2's `reasoning_options`
9132/// wholesale. Where the 5.3 family does diverge — forced thinking — is
9133/// captured by [`is_exact_zai_forced_thinking_route`].
9134#[must_use]
9135pub fn is_exact_zai_tiered_effort_route(
9136    provider: ProviderKind,
9137    base_url: &str,
9138    model: &str,
9139) -> bool {
9140    is_exact_zai_chat_route(provider, base_url)
9141        && (model.trim().eq_ignore_ascii_case(ZAI_GLM_5_2_MODEL)
9142            || is_exact_zai_forced_thinking_route(provider, base_url, model))
9143}
9144
9145/// Whether a route is exactly first-party Z.ai GLM-5.3 or GLM-5.3-Flash.
9146///
9147/// Both BigModel (`docs.bigmodel.cn/cn/guide/capabilities/thinking`) and
9148/// Z.ai (`docs.z.ai/guides/capabilities/thinking`) document the 5.3 family
9149/// as forced-thinking: `thinking.type: "disabled"` is rejected with an error
9150/// and `reasoning_effort` accepts only `low` / `high` / `max`. The migration
9151/// note for a former `disabled` payload is `enabled` + `reasoning_effort:
9152/// "low"`. GLM-5.2 stays outside this predicate because it still honours
9153/// the generic disabled toggle.
9154#[must_use]
9155pub fn is_exact_zai_forced_thinking_route(
9156    provider: ProviderKind,
9157    base_url: &str,
9158    model: &str,
9159) -> bool {
9160    is_exact_zai_chat_route(provider, base_url)
9161        && (model.trim().eq_ignore_ascii_case(ZAI_GLM_5_3_MODEL)
9162            || model.trim().eq_ignore_ascii_case(ZAI_GLM_5_3_FLASH_MODEL))
9163}
9164
9165/// Whether a route is exactly first-party Z.ai GLM-5-Turbo.
9166#[must_use]
9167pub(crate) fn is_exact_zai_glm_5_turbo_route(
9168    provider: ProviderKind,
9169    base_url: &str,
9170    model: &str,
9171) -> bool {
9172    is_exact_zai_chat_route(provider, base_url)
9173        && model.trim().eq_ignore_ascii_case(ZAI_GLM_5_TURBO_MODEL)
9174}
9175
9176/// Whether a route is an exact first-party Z.ai model with a verified
9177/// reasoning control. GLM-5.2, GLM-5.3, and GLM-5.3-Flash have tiered
9178/// effort; GLM-5.1 and GLM-5-Turbo only expose the generic thinking toggle.
9179#[must_use]
9180pub fn is_exact_known_zai_reasoning_route(
9181    provider: ProviderKind,
9182    base_url: &str,
9183    model: &str,
9184) -> bool {
9185    is_exact_zai_tiered_effort_route(provider, base_url, model)
9186        || is_exact_zai_glm_5_turbo_route(provider, base_url, model)
9187        || (is_exact_zai_chat_route(provider, base_url)
9188            && model.trim().eq_ignore_ascii_case(ZAI_GLM_5_1_MODEL))
9189}
9190
9191/// MiniMax's own hosted routes, for both wire dialects.
9192///
9193/// Kept as a pure string predicate so a dispatch receipt can be judged without
9194/// a `Config`, and shared with billing classification so a MiniMax-compatible
9195/// gateway cannot inherit the first-party PAYG/Token Plan duality. Both the
9196/// `.io` and `.com` hosts are first-party; anything else is a gateway.
9197#[must_use]
9198pub fn minimax_base_url_is_supported_direct(base_url: &str) -> bool {
9199    codewhale_config::provider::is_exact_minimax_chat_route(
9200        codewhale_config::ProviderKind::Minimax,
9201        base_url,
9202    ) || codewhale_config::provider::is_exact_minimax_anthropic_route(
9203        codewhale_config::ProviderKind::MinimaxAnthropic,
9204        base_url,
9205    )
9206}
9207
9208/// Whether a route is exactly MiniMax-M3 on the first-party OpenAI-compatible
9209/// Chat API. Compatible gateways and the Anthropic Messages route retain
9210/// their own token-limit dialects.
9211#[must_use]
9212pub fn is_exact_minimax_m3_route(provider: ProviderKind, base_url: &str, model: &str) -> bool {
9213    provider == ProviderKind::Minimax
9214        && codewhale_config::provider::is_exact_minimax_chat_route(
9215            codewhale_config::ProviderKind::Minimax,
9216            base_url,
9217        )
9218        && model.trim().eq_ignore_ascii_case(DEFAULT_MINIMAX_MODEL)
9219}
9220
9221/// Whether a route is exactly MiniMax-M3 on a first-party Anthropic-compatible
9222/// Messages endpoint. The wire supports adaptive/disabled thinking, but no
9223/// distinct effort tier.
9224#[must_use]
9225pub fn is_exact_minimax_anthropic_m3_route(
9226    provider: ProviderKind,
9227    base_url: &str,
9228    model: &str,
9229) -> bool {
9230    provider == ProviderKind::MinimaxAnthropic
9231        && codewhale_config::provider::is_exact_minimax_anthropic_route(
9232            codewhale_config::ProviderKind::MinimaxAnthropic,
9233            base_url,
9234        )
9235        && model.trim().eq_ignore_ascii_case(DEFAULT_MINIMAX_MODEL)
9236}
9237
9238#[must_use]
9239pub fn minimax_m3_route_uses_max_completion_tokens(
9240    provider: ProviderKind,
9241    base_url: &str,
9242    model: &str,
9243) -> bool {
9244    is_exact_minimax_m3_route(provider, base_url, model)
9245}
9246
9247/// The Kimi Code membership roster, as one fact.
9248///
9249/// The picker offers these ids, `validate_kimi_code_api_model_id` accepts them
9250/// on the membership endpoint and rejects them on the direct platform, and the
9251/// model picker labels them as plan routes. Those sites previously kept
9252/// independent literal lists and had already drifted (`kimi-for-coding` was
9253/// missing from the picker label), so the roster lives here and nowhere else.
9254pub const KIMI_CODE_MEMBERSHIP_MODELS: [&str; 4] = [
9255    KIMI_CODE_K3_MODEL,
9256    KIMI_CODE_K3_256K_MODEL,
9257    DEFAULT_KIMI_CODE_MODEL,
9258    KIMI_CODE_HIGHSPEED_MODEL,
9259];
9260
9261/// Whether `model` is a Kimi Code membership model id.
9262///
9263/// The single membership-roster predicate. Callers that need to name the
9264/// product — output-ceiling provenance, picker rosters, setup validation, and
9265/// the model picker's route label — must use this rather than re-listing ids.
9266#[must_use]
9267pub fn is_kimi_code_membership_model(model: &str) -> bool {
9268    let model = model.trim();
9269    KIMI_CODE_MEMBERSHIP_MODELS
9270        .iter()
9271        .any(|id| model.eq_ignore_ascii_case(id))
9272}
9273
9274/// Keep the recovery command visible in small terminals. The optional DSH
9275/// advice is conditional prose: producing an error must not inspect PATH or
9276/// another application's credential file on the runtime thread.
9277fn deepseek_missing_key_message() -> &'static str {
9278    concat!(
9279        "DeepSeek API key not found.\n",
9280        "Save a key for every folder:\n",
9281        "  codewhale auth set --provider deepseek\n",
9282        "Get a key: https://platform.deepseek.com/api_keys\n",
9283        "Or export DEEPSEEK_API_KEY=<your-key> (this shell only).\n",
9284        "In zsh, ~/.zshrc is read only by interactive shells.\n",
9285        "Or set api_key in ~/.codewhale/config.toml.\n",
9286        "If you already use DeepSeek Harness, grant read-only access:\n",
9287        "  codewhale auth external-consent --provider deepseek --mode read-only"
9288    )
9289}
9290
9291/// The Moonshot direct-platform roster, as one fact. Mirror of
9292/// [`KIMI_CODE_MEMBERSHIP_MODELS`] for the pay-as-you-go product.
9293pub(crate) const MOONSHOT_DIRECT_PLATFORM_MODELS: [&str; 3] = [
9294    MOONSHOT_KIMI_K3_MODEL,
9295    DEFAULT_MOONSHOT_MODEL,
9296    MOONSHOT_KIMI_K2_6_MODEL,
9297];
9298
9299pub(crate) const KIMI_CODE_CLAUDE_ALIAS_GUIDANCE: &str = "Kimi Code model `k3[1m]` is a Claude Code environment convention, not an API model id. Use model = \"k3\". If your Kimi Code plan includes 1M context, also set context_window = 1048576; otherwise keep the 262144 safe default.";
9300
9301/// Configuration errors whose text is safe to show in diagnostics such as
9302/// `codewhale doctor`. Everything else stays suppressed there because parse
9303/// errors and credential fields can echo secret material.
9304#[derive(Debug, thiserror::Error)]
9305pub enum SafeConfigDiagnostic {
9306    #[error("{}", KIMI_CODE_CLAUDE_ALIAS_GUIDANCE)]
9307    KimiCodeClaudeAlias,
9308    /// A plain enum/value validation failure on a non-credential key.
9309    /// `message` quotes the rejected value for the local error; `shareable`
9310    /// omits it, because a mistyped value can still be a pasted secret.
9311    #[error("{message}")]
9312    InvalidValue {
9313        message: String,
9314        shareable: String,
9315        /// A `codewhale config set <key> <valid>` command, when one fixes it.
9316        fix: Option<String>,
9317    },
9318}
9319
9320impl SafeConfigDiagnostic {
9321    fn invalid_value(key: &str, value: &str, expected: &str, fix: String) -> Self {
9322        Self::InvalidValue {
9323            message: format!("Invalid {key} '{value}': expected {expected}."),
9324            shareable: format!("Invalid {key} (value not shown): expected {expected}."),
9325            fix: Some(fix),
9326        }
9327    }
9328
9329    /// The diagnostic text for reports such as `codewhale doctor`, without
9330    /// the rejected value and redacted defensively.
9331    pub fn display_message(&self) -> String {
9332        let text = match self {
9333            Self::KimiCodeClaudeAlias => self.to_string(),
9334            Self::InvalidValue { shareable, .. } => shareable.clone(),
9335        };
9336        codewhale_sanitize::redact::redact_secrets(&text)
9337    }
9338
9339    pub fn fix(&self) -> Option<&str> {
9340        match self {
9341            Self::KimiCodeClaudeAlias => None,
9342            Self::InvalidValue { fix, .. } => fix.as_deref(),
9343        }
9344    }
9345
9346    /// Find a safe diagnostic anywhere in an error chain (loaders wrap
9347    /// validation errors in file-path context).
9348    pub fn find_in(error: &anyhow::Error) -> Option<&Self> {
9349        error.chain().find_map(|cause| cause.downcast_ref::<Self>())
9350    }
9351}
9352
9353/// How to correct a rejected value in the user config. `config set` does not
9354/// take dotted keys, so a table field names the table to edit. Validation runs
9355/// after the environment, profile and managed layers are applied, and any of
9356/// them outranks the user config, so the fix names those layers too.
9357fn user_config_fix(key: &str, valid: &str, env_var: Option<&str>) -> String {
9358    let edit = match key.split_once('.') {
9359        Some((table, field)) => {
9360            format!("set {field} = \"{valid}\" in the [{table}] table of config.toml")
9361        }
9362        None => format!("codewhale config set {key} {valid}"),
9363    };
9364    let layers = match env_var {
9365        Some(env_var) => format!("{env_var}, a profile, or managed config"),
9366        None => "a profile or managed config".to_string(),
9367    };
9368    format!("{edit} (if {layers} sets it, correct it there)")
9369}
9370
9371fn invalid_provider_diagnostic(provider: &str) -> SafeConfigDiagnostic {
9372    SafeConfigDiagnostic::invalid_value(
9373        "provider",
9374        provider,
9375        &ProviderKind::names_hint(),
9376        user_config_fix(
9377            "provider",
9378            ProviderKind::Deepseek.as_str(),
9379            Some("CODEWHALE_PROVIDER"),
9380        ),
9381    )
9382}
9383
9384/// The one wording for an unknown provider name, shared by config validation
9385/// and `config set provider`.
9386pub(crate) fn invalid_provider_message(provider: &str) -> String {
9387    invalid_provider_diagnostic(provider).to_string()
9388}
9389
9390/// Fail closed on known-bad model/endpoint pairings (#4687).
9391///
9392/// Canonical endpoints reject `k3[1m]` and known membership/direct cross-pairings.
9393/// Unknown IDs and custom Moonshot-compatible gateways remain pass-through.
9394pub fn validate_kimi_code_api_model_id(
9395    provider: ProviderKind,
9396    base_url: &str,
9397    model: &str,
9398) -> std::result::Result<(), String> {
9399    if provider != ProviderKind::Moonshot {
9400        return Ok(());
9401    }
9402    let model = model.trim();
9403    if model.is_empty() {
9404        return Ok(());
9405    }
9406
9407    if moonshot_base_url_is_exact_kimi_code(base_url) {
9408        if model.eq_ignore_ascii_case("k3[1m]") {
9409            return Err(KIMI_CODE_CLAUDE_ALIAS_GUIDANCE.to_string());
9410        }
9411        for direct_id in MOONSHOT_DIRECT_PLATFORM_MODELS {
9412            if model.eq_ignore_ascii_case(direct_id) {
9413                return Err(format!(
9414                    "Kimi Code membership route (api.kimi.com/coding/v1) does not accept model = \"{model}\": it is a direct Moonshot platform id. Use a Kimi Code membership model (\"k3\", \"k3-256k\", \"kimi-for-coding\", or \"kimi-for-coding-highspeed\") for this base_url. Direct Moonshot pay-as-you-go uses base_url = \"https://api.moonshot.ai/v1\" with model = \"{direct_id}\"."
9415                ));
9416            }
9417        }
9418        return Ok(());
9419    }
9420
9421    if moonshot_base_url_is_exact_direct_platform(base_url) {
9422        for membership_id in KIMI_CODE_MEMBERSHIP_MODELS {
9423            if model.eq_ignore_ascii_case(membership_id) {
9424                return Err(format!(
9425                    "Moonshot direct route (api.moonshot.ai/v1) does not accept model = \"{model}\": it is a Kimi Code membership model id, not a direct-platform catalog model. Kimi Code membership uses base_url = \"https://api.kimi.com/coding/v1\" with model = \"{membership_id}\"; direct Moonshot pay-as-you-go K3 uses model = \"kimi-k3\"."
9426                ));
9427            }
9428        }
9429    }
9430
9431    Ok(())
9432}
9433
9434#[cfg(test)]
9435mod kimi_code_pairing_tests {
9436    use super::*;
9437
9438    #[test]
9439    fn membership_roster_passes_on_kimi_code_endpoint() {
9440        for model in [
9441            KIMI_CODE_K3_MODEL,
9442            KIMI_CODE_K3_256K_MODEL,
9443            DEFAULT_KIMI_CODE_MODEL,
9444            KIMI_CODE_HIGHSPEED_MODEL,
9445        ] {
9446            assert!(
9447                validate_kimi_code_api_model_id(
9448                    ProviderKind::Moonshot,
9449                    DEFAULT_KIMI_CODE_BASE_URL,
9450                    model,
9451                )
9452                .is_ok(),
9453                "{model} must be accepted on the exact Kimi Code membership endpoint"
9454            );
9455        }
9456    }
9457
9458    #[test]
9459    fn direct_platform_ids_fail_on_kimi_code_endpoint() {
9460        for model in [
9461            MOONSHOT_KIMI_K3_MODEL,
9462            DEFAULT_MOONSHOT_MODEL,
9463            MOONSHOT_KIMI_K2_6_MODEL,
9464        ] {
9465            let err = validate_kimi_code_api_model_id(
9466                ProviderKind::Moonshot,
9467                DEFAULT_KIMI_CODE_BASE_URL,
9468                model,
9469            )
9470            .expect_err("direct-platform ids are not Kimi Code membership roster models");
9471            assert!(err.contains(model), "{err}");
9472            assert!(err.contains("api.moonshot.ai/v1"), "{err}");
9473        }
9474    }
9475
9476    #[test]
9477    fn membership_ids_fail_on_direct_moonshot_endpoint() {
9478        for model in [
9479            KIMI_CODE_K3_MODEL,
9480            KIMI_CODE_K3_256K_MODEL,
9481            DEFAULT_KIMI_CODE_MODEL,
9482            KIMI_CODE_HIGHSPEED_MODEL,
9483        ] {
9484            let err = validate_kimi_code_api_model_id(
9485                ProviderKind::Moonshot,
9486                DEFAULT_MOONSHOT_BASE_URL,
9487                model,
9488            )
9489            .expect_err("membership ids are not direct-platform catalog models");
9490            assert!(err.contains(model), "{err}");
9491            assert!(err.contains("api.kimi.com/coding/v1"), "{err}");
9492        }
9493    }
9494
9495    #[test]
9496    fn canonical_pairs_pass_and_custom_gateways_are_untouched() {
9497        // Canonical pairs pass on both endpoints.
9498        for (base_url, model) in [
9499            (DEFAULT_KIMI_CODE_BASE_URL, KIMI_CODE_K3_MODEL),
9500            (DEFAULT_KIMI_CODE_BASE_URL, KIMI_CODE_K3_256K_MODEL),
9501            (DEFAULT_KIMI_CODE_BASE_URL, DEFAULT_KIMI_CODE_MODEL),
9502            (DEFAULT_KIMI_CODE_BASE_URL, KIMI_CODE_HIGHSPEED_MODEL),
9503            (DEFAULT_MOONSHOT_BASE_URL, MOONSHOT_KIMI_K3_MODEL),
9504            (DEFAULT_MOONSHOT_BASE_URL, DEFAULT_MOONSHOT_MODEL),
9505            (DEFAULT_MOONSHOT_BASE_URL, MOONSHOT_KIMI_K2_6_MODEL),
9506        ] {
9507            assert!(
9508                validate_kimi_code_api_model_id(ProviderKind::Moonshot, base_url, model).is_ok(),
9509                "{base_url} / {model}"
9510            );
9511        }
9512        // The pre-existing cross-pairings still fail closed.
9513        assert!(
9514            validate_kimi_code_api_model_id(
9515                ProviderKind::Moonshot,
9516                DEFAULT_KIMI_CODE_BASE_URL,
9517                MOONSHOT_KIMI_K3_MODEL,
9518            )
9519            .is_err()
9520        );
9521        assert!(
9522            validate_kimi_code_api_model_id(
9523                ProviderKind::Moonshot,
9524                DEFAULT_MOONSHOT_BASE_URL,
9525                KIMI_CODE_K3_MODEL,
9526            )
9527            .is_err()
9528        );
9529        // Custom gateways keep their own wire contract, membership ids
9530        // included: only the two canonical endpoints enforce pairings.
9531        for model in [
9532            KIMI_CODE_K3_MODEL,
9533            KIMI_CODE_K3_256K_MODEL,
9534            DEFAULT_KIMI_CODE_MODEL,
9535            KIMI_CODE_HIGHSPEED_MODEL,
9536            MOONSHOT_KIMI_K3_MODEL,
9537        ] {
9538            assert!(
9539                validate_kimi_code_api_model_id(
9540                    ProviderKind::Moonshot,
9541                    "https://proxy.example/v1",
9542                    model,
9543                )
9544                .is_ok(),
9545                "{model} on a custom gateway"
9546            );
9547        }
9548    }
9549}
9550
9551/// Short route label for header/diagnostics without credentials (#4687).
9552pub fn moonshot_k3_route_display_name(base_url: &str, model: &str) -> Option<&'static str> {
9553    if is_exact_kimi_code_bare_k3_route(ProviderKind::Moonshot, base_url, model) {
9554        return Some("Kimi Code membership / k3");
9555    }
9556    if is_exact_kimi_code_k3_route(ProviderKind::Moonshot, base_url, model) {
9557        return Some("Kimi Code membership / k3-256k");
9558    }
9559    if is_exact_direct_moonshot_k3_route(ProviderKind::Moonshot, base_url, model) {
9560        return Some("Moonshot direct / kimi-k3");
9561    }
9562    None
9563}
9564
9565/// Credential help for a concrete provider route.
9566///
9567/// `ProviderKind::Moonshot` intentionally retains its generic direct-API
9568/// metadata in `codewhale-config`: that remains correct for Moonshot's own
9569/// platform route. The Kimi Code membership endpoint is a distinct route and
9570/// must not send its users to the generic API console or imply CLI credential
9571/// import support.
9572pub fn credential_help_for_provider_route(
9573    provider: ProviderKind,
9574    base_url: &str,
9575) -> codewhale_config::provider::CredentialHelp {
9576    codewhale_config::provider::credential_help_for_route(provider, base_url)
9577}
9578
9579pub fn provider_config_uses_kimi_imported_token(config: &ProviderConfig) -> bool {
9580    config
9581        .auth_mode
9582        .as_deref()
9583        .is_some_and(auth_mode_uses_kimi_imported_token)
9584}
9585
9586use codewhale_config::{
9587    auth_mode_disables_api_key, auth_mode_requires_api_key, auth_mode_uses_kimi_imported_token,
9588};
9589
9590fn provider_config_uses_xai_oauth(config: &ProviderConfig) -> bool {
9591    config
9592        .auth_mode
9593        .as_deref()
9594        .is_some_and(crate::oauth::auth_mode_uses_xai_oauth)
9595}
9596
9597/// Whether a base URL points at a loopback/unspecified host, i.e. a local
9598/// runtime rather than a hosted endpoint. Shared by the active-provider
9599/// local-base-url check above and the `/provider` picker's custom-provider
9600/// auth-optionality heuristic (#3830).
9601pub fn base_url_uses_local_host(base_url: &str) -> bool {
9602    let Some(host) = base_url_host(base_url) else {
9603        return false;
9604    };
9605    let host = host.trim_matches(['[', ']']).to_ascii_lowercase();
9606    if matches!(host.as_str(), "localhost" | "0.0.0.0") {
9607        return true;
9608    }
9609    host.parse::<std::net::IpAddr>()
9610        .is_ok_and(|addr| addr.is_loopback() || addr.is_unspecified())
9611}
9612
9613pub fn normalize_base_url(base: &str) -> String {
9614    let trimmed = base.trim_end_matches('/');
9615    let deepseek_domains = ["api.deepseek.com", "api.deepseeki.com"];
9616    if deepseek_domains
9617        .iter()
9618        .any(|domain| trimmed.contains(domain))
9619    {
9620        return trimmed.trim_end_matches("/v1").to_string();
9621    }
9622    trimmed.to_string()
9623}
9624
9625fn parse_http_headers(raw: &str) -> Result<HashMap<String, String>> {
9626    let mut headers = HashMap::new();
9627    for pair in raw.trim().split(',') {
9628        let pair = pair.trim();
9629        if pair.is_empty() {
9630            continue;
9631        }
9632        let Some((name, value)) = pair.split_once('=') else {
9633            anyhow::bail!("invalid header pair '{pair}', expected name=value");
9634        };
9635        let name = name.trim();
9636        let value = value.trim();
9637        if name.is_empty() {
9638            anyhow::bail!("header name cannot be empty");
9639        }
9640        if value.is_empty() {
9641            continue;
9642        }
9643        headers.insert(name.to_string(), value.to_string());
9644    }
9645    Ok(headers)
9646}
9647
9648// A higher file layer's legacy root model must not be masked by an inherited
9649// provider slot. Clear that lower slot in memory so the existing root-model
9650// validation and foreign-model guards still decide what this layer means.
9651fn apply_layer_root_model(config: &mut Config, layer: &Config) {
9652    if layer.default_text_model.is_none() && layer.legacy_model.is_none() {
9653        return;
9654    }
9655    let Ok(identity) = config.active_provider_identity() else {
9656        return;
9657    };
9658    let mut scoped = layer.clone();
9659    if scoped.scope_to_provider_identity(&identity).is_err() {
9660        return;
9661    }
9662    if scoped
9663        .provider_config_for(&identity)
9664        .and_then(|entry| entry.model.as_ref())
9665        .is_none()
9666    {
9667        config.set_provider_model_override(&identity, None).unwrap();
9668    }
9669}
9670
9671fn apply_profile(config: ConfigFile, profile: Option<&str>) -> Result<Config> {
9672    if let Some(profile_name) = profile {
9673        let profiles = config.profiles.as_ref();
9674        match profiles.and_then(|profiles| profiles.get(profile_name)) {
9675            Some(override_cfg) => {
9676                let mut merged = merge_config(*config.base, override_cfg.clone());
9677                apply_layer_root_model(&mut merged, override_cfg);
9678                merged.route_provenance.provider_from_profile = override_cfg.provider.is_some();
9679                let merged_identity = merged.active_provider_identity().ok();
9680                merged.route_provenance.model_from_profile =
9681                    override_cfg.default_text_model.is_some()
9682                        || override_cfg.legacy_model.is_some()
9683                        || merged_identity.as_ref().is_some_and(|id| {
9684                            override_cfg
9685                                .provider_config_for(id)
9686                                .and_then(|entry| entry.model.as_deref())
9687                                .is_some()
9688                        });
9689                Ok(merged)
9690            }
9691            None => {
9692                let available = profiles
9693                    .map(|profiles| {
9694                        let mut keys = profiles.keys().cloned().collect::<Vec<_>>();
9695                        keys.sort();
9696                        if keys.is_empty() {
9697                            "none".to_string()
9698                        } else {
9699                            keys.join(", ")
9700                        }
9701                    })
9702                    .unwrap_or_else(|| "none".to_string());
9703                // Profile names are user-typed (`--profile`), so the shareable
9704                // text omits the requested one like every other InvalidValue;
9705                // the available names are config table keys, not values.
9706                Err(SafeConfigDiagnostic::InvalidValue {
9707                    message: format!(
9708                        "Profile '{profile_name}' not found. Available profiles: {available}"
9709                    ),
9710                    shareable: format!(
9711                        "Profile not found (name not shown). Available profiles: {available}"
9712                    ),
9713                    fix: None,
9714                }
9715                .into())
9716            }
9717        }
9718    } else {
9719        Ok(*config.base)
9720    }
9721}
9722
9723fn merge_config(base: Config, override_cfg: Config) -> Config {
9724    Config {
9725        model_http_policy: override_cfg.model_http_policy.or(base.model_http_policy),
9726        custom_models: override_cfg.custom_models.or(base.custom_models),
9727        extra_trusted_paths: if override_cfg.extra_trusted_paths.is_empty() {
9728            base.extra_trusted_paths
9729        } else {
9730            override_cfg.extra_trusted_paths
9731        },
9732        provider: override_cfg.provider.or(base.provider),
9733        telemetry: override_cfg.telemetry.or(base.telemetry),
9734        http_headers: override_cfg.http_headers.or(base.http_headers),
9735        default_text_model: override_cfg
9736            .default_text_model
9737            .or_else(|| override_cfg.legacy_model.clone())
9738            .or(base.default_text_model)
9739            .or_else(|| base.legacy_model.clone()),
9740        legacy_model: override_cfg.legacy_model.or(base.legacy_model),
9741        redaction: override_cfg.redaction.or(base.redaction),
9742        loaded_config_path: override_cfg.loaded_config_path.or(base.loaded_config_path),
9743        remembered_selection_scope: override_cfg
9744            .remembered_selection_scope
9745            .or(base.remembered_selection_scope),
9746        route_preferences_version: override_cfg
9747            .route_preferences_version
9748            .or(base.route_preferences_version),
9749        environment_model_applied: override_cfg.environment_model_applied
9750            || base.environment_model_applied,
9751        route_provenance: base.route_provenance,
9752        auth_mode: override_cfg.auth_mode.or(base.auth_mode),
9753        reasoning_effort: override_cfg.reasoning_effort.or(base.reasoning_effort),
9754        reasoning_effort_inferred_from_legacy_alias: override_cfg
9755            .reasoning_effort_inferred_from_legacy_alias
9756            || base.reasoning_effort_inferred_from_legacy_alias,
9757        fleet_operator_route_applied: override_cfg.fleet_operator_route_applied
9758            || base.fleet_operator_route_applied,
9759        fleet_operator_reasoning_applied: override_cfg.fleet_operator_reasoning_applied
9760            || base.fleet_operator_reasoning_applied,
9761        migrated_legacy_ollama_cloud_route: override_cfg.migrated_legacy_ollama_cloud_route
9762            || base.migrated_legacy_ollama_cloud_route,
9763        migrated_deepseek_model_alias: override_cfg
9764            .migrated_deepseek_model_alias
9765            .or(base.migrated_deepseek_model_alias),
9766        tools: override_cfg.tools.or(base.tools),
9767        skills_dir: override_cfg.skills_dir.or(base.skills_dir),
9768        mcp_config_path: override_cfg.mcp_config_path.or(base.mcp_config_path),
9769        mcp_oauth_callback_port: override_cfg
9770            .mcp_oauth_callback_port
9771            .or(base.mcp_oauth_callback_port),
9772        mcp_oauth_callback_url: override_cfg
9773            .mcp_oauth_callback_url
9774            .or(base.mcp_oauth_callback_url),
9775        notes_path: override_cfg.notes_path.or(base.notes_path),
9776        memory_path: override_cfg.memory_path.or(base.memory_path),
9777        vision_model: override_cfg.vision_model.or(base.vision_model),
9778        // #454: user-owned overlays such as profiles and managed config may
9779        // replace the instruction array. Project-scope config is filtered in
9780        // main.rs and cannot set instruction paths.
9781        instructions: override_cfg.instructions.or(base.instructions),
9782        // #6526: the instruction-budget table is user authority for the same
9783        // reason `instructions` is — a workspace does not get to decide how
9784        // much of the user's context its own files may claim.
9785        instruction_budget: override_cfg.instruction_budget.or(base.instruction_budget),
9786        stop_words: override_cfg.stop_words.or(base.stop_words),
9787        allow_shell: override_cfg.allow_shell.or(base.allow_shell),
9788        prompt_suggestion: override_cfg.prompt_suggestion.or(base.prompt_suggestion),
9789        yolo: override_cfg.yolo.or(base.yolo),
9790        verbosity: override_cfg.verbosity.or(base.verbosity),
9791        approval_policy: override_cfg.approval_policy.or(base.approval_policy),
9792        sandbox_mode: override_cfg.sandbox_mode.or(base.sandbox_mode),
9793        sandbox_network_access: override_cfg
9794            .sandbox_network_access
9795            .or(base.sandbox_network_access),
9796        project_instruction_imports: if override_cfg.project_instruction_imports.is_empty() {
9797            base.project_instruction_imports
9798        } else {
9799            override_cfg.project_instruction_imports
9800        },
9801        fallback_providers: if override_cfg.fallback_providers.is_empty() {
9802            base.fallback_providers
9803        } else {
9804            override_cfg.fallback_providers
9805        },
9806        sandbox_backend: override_cfg.sandbox_backend.or(base.sandbox_backend),
9807        sandbox_url: override_cfg.sandbox_url.or(base.sandbox_url),
9808        sandbox_api_key: override_cfg.sandbox_api_key.or(base.sandbox_api_key),
9809        prefer_bwrap: override_cfg.prefer_bwrap.or(base.prefer_bwrap),
9810        tool_launcher: override_cfg.tool_launcher.or(base.tool_launcher),
9811        bwrap_ro_roots: if override_cfg.bwrap_ro_roots.is_empty() {
9812            base.bwrap_ro_roots
9813        } else {
9814            override_cfg.bwrap_ro_roots
9815        },
9816        bwrap_dev_roots: if override_cfg.bwrap_dev_roots.is_empty() {
9817            base.bwrap_dev_roots
9818        } else {
9819            override_cfg.bwrap_dev_roots
9820        },
9821        sandbox_denied_read_paths: if override_cfg.sandbox_denied_read_paths.is_empty() {
9822            base.sandbox_denied_read_paths
9823        } else {
9824            override_cfg.sandbox_denied_read_paths
9825        },
9826        sandbox_read_denylist_defaults: override_cfg
9827            .sandbox_read_denylist_defaults
9828            .or(base.sandbox_read_denylist_defaults),
9829        sandbox_read_denylist_exempt: if override_cfg.sandbox_read_denylist_exempt.is_empty() {
9830            base.sandbox_read_denylist_exempt
9831        } else {
9832            override_cfg.sandbox_read_denylist_exempt
9833        },
9834        managed_config_path: override_cfg
9835            .managed_config_path
9836            .or(base.managed_config_path),
9837        requirements_path: override_cfg.requirements_path.or(base.requirements_path),
9838        max_subagents: override_cfg.max_subagents.or(base.max_subagents),
9839        retry: override_cfg.retry.or(base.retry),
9840        stream: match (base.stream, override_cfg.stream) {
9841            (Some(base), Some(over)) => Some(StreamConfig {
9842                open_timeout_secs: over.open_timeout_secs.or(base.open_timeout_secs),
9843                chunk_timeout_secs: over.chunk_timeout_secs.or(base.chunk_timeout_secs),
9844                force_http1: over.force_http1.or(base.force_http1),
9845                max_resumes: over.max_resumes.or(base.max_resumes),
9846                max_transparent_retries: over
9847                    .max_transparent_retries
9848                    .or(base.max_transparent_retries),
9849                max_stream_errors: over.max_stream_errors.or(base.max_stream_errors),
9850                max_duration_secs: over.max_duration_secs.or(base.max_duration_secs),
9851                max_content_mb: over.max_content_mb.or(base.max_content_mb),
9852                connect_timeout_secs: over.connect_timeout_secs.or(base.connect_timeout_secs),
9853                tcp_keepalive_secs: over.tcp_keepalive_secs.or(base.tcp_keepalive_secs),
9854                http2_keep_alive_interval_secs: over
9855                    .http2_keep_alive_interval_secs
9856                    .or(base.http2_keep_alive_interval_secs),
9857                http2_keep_alive_timeout_secs: over
9858                    .http2_keep_alive_timeout_secs
9859                    .or(base.http2_keep_alive_timeout_secs),
9860            }),
9861            (base, over) => over.or(base),
9862        },
9863
9864        auto_review: override_cfg.auto_review.or(base.auto_review),
9865        tui: override_cfg.tui.or(base.tui),
9866        transcript: override_cfg.transcript.or(base.transcript),
9867        hooks: override_cfg.hooks.or(base.hooks),
9868        lifecycle_outbox: override_cfg.lifecycle_outbox.or(base.lifecycle_outbox),
9869        control_socket: override_cfg.control_socket.or(base.control_socket),
9870        providers: merge_providers(base.providers, override_cfg.providers),
9871        features: merge_features(base.features, override_cfg.features),
9872        extension_host: override_cfg.extension_host.or(base.extension_host),
9873        plugins: override_cfg.plugins.or(base.plugins),
9874        notifications: override_cfg.notifications.or(base.notifications),
9875        approval: override_cfg.approval.or(base.approval),
9876        network: override_cfg.network.or(base.network),
9877        network_layer_is_managed: override_cfg.network_layer_is_managed
9878            || base.network_layer_is_managed,
9879        verifier: override_cfg.verifier.or(base.verifier),
9880        advisor: override_cfg.advisor.or(base.advisor),
9881        skills: merge_skills_config(base.skills, override_cfg.skills),
9882        snapshots: override_cfg.snapshots.or(base.snapshots),
9883        search: override_cfg.search.or(base.search),
9884        goal: override_cfg.goal.or(base.goal),
9885        memory: override_cfg.memory.or(base.memory),
9886        speech: override_cfg.speech.or(base.speech),
9887        auto: override_cfg.auto.or(base.auto),
9888        hotbar: override_cfg.hotbar.or(base.hotbar),
9889        update: override_cfg.update.or(base.update),
9890        cloud_facts: override_cfg.cloud_facts.or(base.cloud_facts),
9891        lsp: override_cfg.lsp.or(base.lsp),
9892        context: ContextConfig {
9893            project_pack: override_cfg
9894                .context
9895                .project_pack
9896                .or(base.context.project_pack),
9897        },
9898        compaction: override_cfg.compaction.or(base.compaction),
9899        fleet: override_cfg.fleet.or(base.fleet),
9900        workflow: override_cfg.workflow.or(base.workflow),
9901        subagents: override_cfg.subagents.or(base.subagents),
9902        strict_tool_mode: override_cfg.strict_tool_mode.or(base.strict_tool_mode),
9903        runtime_api: override_cfg.runtime_api.or(base.runtime_api),
9904        workshop: override_cfg.workshop.or(base.workshop),
9905        exec_policy_engine: override_cfg.exec_policy_engine,
9906        base_url_env_receipt: match override_cfg.base_url_env_receipt {
9907            BaseUrlEnvReceipt::Unrecorded => base.base_url_env_receipt,
9908            recorded => recorded,
9909        },
9910        legacy_root: base.legacy_root,
9911        legacy_root_custom_generation: base.legacy_root_custom_generation,
9912        account_model_access: base.account_model_access,
9913        session_provider_keys: base.session_provider_keys,
9914        session_provider_keys_only: base.session_provider_keys_only,
9915        required_account_model_owner: base.required_account_model_owner,
9916        account_profile: override_cfg.account_profile.or(base.account_profile),
9917        plugin_oauth_read_only: base.plugin_oauth_read_only || override_cfg.plugin_oauth_read_only,
9918        runtime_chat_isolated: override_cfg.runtime_chat_isolated || base.runtime_chat_isolated,
9919        runtime_thread_inference_unrelated: override_cfg.runtime_thread_inference_unrelated
9920            || base.runtime_thread_inference_unrelated,
9921        mini_window: override_cfg.mini_window.or(base.mini_window),
9922        reasoning_only: override_cfg.reasoning_only.or(base.reasoning_only),
9923        title: override_cfg.title.or(base.title),
9924    }
9925}
9926
9927fn load_sibling_exec_policy_engine(config_path: Option<&Path>) -> Result<ExecPolicyEngine> {
9928    let Some(config_path) = config_path else {
9929        return Ok(ExecPolicyEngine::new(Vec::new(), Vec::new()));
9930    };
9931    let permissions_path = codewhale_config::permissions_path_for_config_path(config_path);
9932    if !permissions_path.exists() {
9933        return Ok(ExecPolicyEngine::new(Vec::new(), Vec::new()));
9934    }
9935
9936    let raw = fs::read_to_string(&permissions_path).with_context(|| {
9937        format!(
9938            "Failed to read permissions file: {}",
9939            permissions_path.display()
9940        )
9941    })?;
9942    let permissions: codewhale_config::PermissionsToml = toml::from_str(&raw).map_err(|_| {
9943        anyhow::anyhow!(
9944            "Failed to parse permissions file {}; file contents were omitted",
9945            codewhale_config::quote_os_path(&permissions_path)
9946        )
9947    })?;
9948    if permissions.is_empty() {
9949        Ok(ExecPolicyEngine::new(Vec::new(), Vec::new()))
9950    } else {
9951        Ok(ExecPolicyEngine::with_rulesets(vec![permissions.ruleset()]))
9952    }
9953}
9954
9955fn merge_skills_config(
9956    base: Option<SkillsConfig>,
9957    override_cfg: Option<SkillsConfig>,
9958) -> Option<SkillsConfig> {
9959    match (base, override_cfg) {
9960        (None, None) => None,
9961        (Some(base), None) => Some(base),
9962        (None, Some(override_cfg)) => Some(override_cfg),
9963        (Some(base), Some(override_cfg)) => Some(SkillsConfig {
9964            bundled: BundledSkillsConfig {
9965                install: override_cfg.bundled.install.or(base.bundled.install),
9966                selected: override_cfg.bundled.selected.or(base.bundled.selected),
9967                disabled: override_cfg.bundled.disabled.or(base.bundled.disabled),
9968                explicit_only: override_cfg
9969                    .bundled
9970                    .explicit_only
9971                    .or(base.bundled.explicit_only),
9972            },
9973            listing_max_description_chars: override_cfg
9974                .listing_max_description_chars
9975                .or(base.listing_max_description_chars),
9976            listing_budget_fraction: override_cfg
9977                .listing_budget_fraction
9978                .or(base.listing_budget_fraction),
9979            registry_url: override_cfg.registry_url.or(base.registry_url),
9980            max_install_size_bytes: override_cfg
9981                .max_install_size_bytes
9982                .or(base.max_install_size_bytes),
9983            scan_codewhale_only: override_cfg
9984                .scan_codewhale_only
9985                .or(base.scan_codewhale_only),
9986            flat_workspace_root: override_cfg
9987                .flat_workspace_root
9988                .or(base.flat_workspace_root),
9989            creator_skills: false,
9990        }),
9991    }
9992}
9993
9994fn merge_provider_config(base: ProviderConfig, override_cfg: ProviderConfig) -> ProviderConfig {
9995    ProviderConfig {
9996        vendor: override_cfg.vendor.or(base.vendor),
9997        api_key: override_cfg.api_key.or(base.api_key),
9998        base_url: override_cfg.base_url.or(base.base_url),
9999        model: override_cfg.model.or(base.model),
10000        context_window: override_cfg.context_window.or(base.context_window),
10001        model_context_windows: override_cfg
10002            .model_context_windows
10003            .or(base.model_context_windows),
10004        mode: override_cfg.mode.or(base.mode),
10005        wire: override_cfg.wire.or(base.wire),
10006        responses_profile: override_cfg.responses_profile.or(base.responses_profile),
10007        auth_mode: override_cfg.auth_mode.or(base.auth_mode),
10008        oauth: override_cfg.oauth.or(base.oauth),
10009        plugin_authority: base.plugin_authority,
10010        oauth_credential_generation: override_cfg
10011            .oauth_credential_generation
10012            .or(base.oauth_credential_generation),
10013        insecure_skip_tls_verify: override_cfg
10014            .insecure_skip_tls_verify
10015            .or(base.insecure_skip_tls_verify),
10016        allow_insecure_http: override_cfg
10017            .allow_insecure_http
10018            .or(base.allow_insecure_http),
10019        http_headers: override_cfg.http_headers.or(base.http_headers),
10020        path_suffix: override_cfg.path_suffix.or(base.path_suffix),
10021        reasoning_stream_style: override_cfg
10022            .reasoning_stream_style
10023            .or(base.reasoning_stream_style),
10024        max_concurrency: override_cfg.max_concurrency.or(base.max_concurrency),
10025        auth: override_cfg.auth.or(base.auth),
10026        external_credentials: override_cfg
10027            .external_credentials
10028            .or(base.external_credentials),
10029        kind: override_cfg.kind.or(base.kind),
10030        api_key_env: override_cfg.api_key_env.or(base.api_key_env),
10031    }
10032}
10033
10034/// Merge the per-name custom provider maps (#1519): the union of both key sets,
10035/// with each shared key deep-merged via [`merge_provider_config`] (override
10036/// wins field-by-field). Keys present in only one map are carried through as-is.
10037fn merge_custom_providers(
10038    mut base: HashMap<String, ProviderConfig>,
10039    override_cfg: HashMap<String, ProviderConfig>,
10040) -> HashMap<String, ProviderConfig> {
10041    for (name, entry) in override_cfg {
10042        let merged = match base.remove(&name) {
10043            Some(base_entry) => merge_provider_config(base_entry, entry),
10044            None => entry,
10045        };
10046        base.insert(name, merged);
10047    }
10048    base
10049}
10050
10051fn merge_providers(
10052    base: Option<ProvidersConfig>,
10053    override_cfg: Option<ProvidersConfig>,
10054) -> Option<ProvidersConfig> {
10055    match (base, override_cfg) {
10056        (None, None) => None,
10057        (Some(base), None) => Some(base),
10058        (None, Some(override_cfg)) => Some(override_cfg),
10059        (Some(base), Some(override_cfg)) => Some(ProvidersConfig {
10060            deepseek: merge_provider_config(base.deepseek, override_cfg.deepseek),
10061            deepseek_cn: merge_provider_config(base.deepseek_cn, override_cfg.deepseek_cn),
10062            deepseek_anthropic: merge_provider_config(
10063                base.deepseek_anthropic,
10064                override_cfg.deepseek_anthropic,
10065            ),
10066            nvidia_nim: merge_provider_config(base.nvidia_nim, override_cfg.nvidia_nim),
10067            openai: merge_provider_config(base.openai, override_cfg.openai),
10068            anthropic: merge_provider_config(base.anthropic, override_cfg.anthropic),
10069            openmodel: merge_provider_config(base.openmodel, override_cfg.openmodel),
10070            atlascloud: merge_provider_config(base.atlascloud, override_cfg.atlascloud),
10071            wanjie_ark: merge_provider_config(base.wanjie_ark, override_cfg.wanjie_ark),
10072            openrouter: merge_provider_config(base.openrouter, override_cfg.openrouter),
10073            orcarouter: merge_provider_config(base.orcarouter, override_cfg.orcarouter),
10074            xiaomi_mimo: merge_provider_config(base.xiaomi_mimo, override_cfg.xiaomi_mimo),
10075            novita: merge_provider_config(base.novita, override_cfg.novita),
10076            fireworks: merge_provider_config(base.fireworks, override_cfg.fireworks),
10077            siliconflow: merge_provider_config(base.siliconflow, override_cfg.siliconflow),
10078            siliconflow_cn: merge_provider_config(base.siliconflow_cn, override_cfg.siliconflow_cn),
10079            arcee: merge_provider_config(base.arcee, override_cfg.arcee),
10080            moonshot: merge_provider_config(base.moonshot, override_cfg.moonshot),
10081            sglang: merge_provider_config(base.sglang, override_cfg.sglang),
10082            vllm: merge_provider_config(base.vllm, override_cfg.vllm),
10083            ollama: merge_provider_config(base.ollama, override_cfg.ollama),
10084            ollama_cloud: merge_provider_config(base.ollama_cloud, override_cfg.ollama_cloud),
10085            volcengine: merge_provider_config(base.volcengine, override_cfg.volcengine),
10086            huggingface: merge_provider_config(base.huggingface, override_cfg.huggingface),
10087            modelscope: merge_provider_config(base.modelscope, override_cfg.modelscope),
10088            deepinfra: merge_provider_config(base.deepinfra, override_cfg.deepinfra),
10089            together: merge_provider_config(base.together, override_cfg.together),
10090            qianfan: merge_provider_config(base.qianfan, override_cfg.qianfan),
10091            openai_codex: merge_provider_config(base.openai_codex, override_cfg.openai_codex),
10092            zai: merge_provider_config(base.zai, override_cfg.zai),
10093            stepfun: merge_provider_config(base.stepfun, override_cfg.stepfun),
10094            minimax: merge_provider_config(base.minimax, override_cfg.minimax),
10095            minimax_anthropic: merge_provider_config(
10096                base.minimax_anthropic,
10097                override_cfg.minimax_anthropic,
10098            ),
10099            sakana: merge_provider_config(base.sakana, override_cfg.sakana),
10100            longcat: merge_provider_config(base.longcat, override_cfg.longcat),
10101            opencode_go: merge_provider_config(base.opencode_go, override_cfg.opencode_go),
10102            opencode_zen: merge_provider_config(base.opencode_zen, override_cfg.opencode_zen),
10103            meta: merge_provider_config(base.meta, override_cfg.meta),
10104            xai: merge_provider_config(base.xai, override_cfg.xai),
10105            mistral: merge_provider_config(base.mistral, override_cfg.mistral),
10106            google: merge_provider_config(base.google, override_cfg.google),
10107            antigravity: merge_provider_config(base.antigravity, override_cfg.antigravity),
10108            telecomjs: merge_provider_config(base.telecomjs, override_cfg.telecomjs),
10109            edenai: merge_provider_config(base.edenai, override_cfg.edenai),
10110            zenmux: merge_provider_config(base.zenmux, override_cfg.zenmux),
10111            csdn: merge_provider_config(base.csdn, override_cfg.csdn),
10112            concentrate: merge_provider_config(base.concentrate, override_cfg.concentrate),
10113            codewhale: merge_provider_config(base.codewhale, override_cfg.codewhale),
10114            modelstudio_token_plan: merge_provider_config(
10115                base.modelstudio_token_plan,
10116                override_cfg.modelstudio_token_plan,
10117            ),
10118            modelstudio_token_plan_anthropic: merge_provider_config(
10119                base.modelstudio_token_plan_anthropic,
10120                override_cfg.modelstudio_token_plan_anthropic,
10121            ),
10122            modelstudio_coding_plan: merge_provider_config(
10123                base.modelstudio_coding_plan,
10124                override_cfg.modelstudio_coding_plan,
10125            ),
10126            modelstudio_coding_plan_anthropic: merge_provider_config(
10127                base.modelstudio_coding_plan_anthropic,
10128                override_cfg.modelstudio_coding_plan_anthropic,
10129            ),
10130            custom: merge_custom_providers(base.custom, override_cfg.custom),
10131        }),
10132    }
10133}
10134
10135fn load_single_config_file(path: &Path) -> Result<Config> {
10136    let contents = fs::read_to_string(path)
10137        .with_context(|| format!("Failed to read config file: {}", path.display()))?;
10138    let parsed = parse_config_file(&contents).map_err(|_| {
10139        anyhow::anyhow!(
10140            "Failed to parse config file {}; file contents were omitted",
10141            codewhale_config::quote_os_path(path)
10142        )
10143    })?;
10144    Ok(*parsed.base)
10145}
10146
10147/// Table key for a built-in route's `[providers.<key>]` entry.
10148#[cfg(any(test, feature = "test-support"))]
10149impl Config {
10150    /// Test shorthand for a config file's legacy top-level `api_key` /
10151    /// `base_url`: they go through the #6394 canonicalizer exactly as a
10152    /// parsed file's would, landing in whichever table owns them.
10153    pub fn with_legacy_root(mut self, api_key: Option<String>, base_url: Option<String>) -> Self {
10154        self.set_legacy_root(api_key, base_url);
10155        self
10156    }
10157
10158    /// `[providers.deepseek] api_key`, where a legacy top-level key lands.
10159    pub fn deepseek_table_api_key(&self) -> Option<&str> {
10160        self.providers.as_ref()?.deepseek.api_key.as_deref()
10161    }
10162
10163    /// `[providers.deepseek] base_url`, where a legacy top-level endpoint
10164    /// lands.
10165    pub fn deepseek_table_base_url(&self) -> Option<&str> {
10166        self.providers.as_ref()?.deepseek.base_url.as_deref()
10167    }
10168
10169    /// In-place form of [`Config::with_legacy_root`].
10170    pub fn set_legacy_root(&mut self, api_key: Option<String>, base_url: Option<String>) {
10171        use toml::Value;
10172        let mut root = toml::Table::new();
10173        if let Some(provider) = &self.provider {
10174            root.insert("provider".into(), Value::String(provider.clone()));
10175        }
10176        if let Some(model) = self
10177            .default_text_model
10178            .clone()
10179            .or(self.legacy_model.clone())
10180        {
10181            root.insert("default_text_model".into(), Value::String(model));
10182        }
10183        if let Some(key) = api_key {
10184            root.insert("api_key".into(), Value::String(key));
10185        }
10186        if let Some(url) = base_url {
10187            root.insert("base_url".into(), Value::String(url));
10188        }
10189        let entry_table = |entry: &ProviderConfig| {
10190            let mut table = toml::Table::new();
10191            if let Some(key) = &entry.api_key {
10192                table.insert("api_key".into(), Value::String(key.clone()));
10193            }
10194            if let Some(url) = &entry.base_url {
10195                table.insert("base_url".into(), Value::String(url.clone()));
10196            }
10197            if let Some(model) = &entry.model {
10198                table.insert("model".into(), Value::String(model.clone()));
10199            }
10200            if let Some(kind) = &entry.kind {
10201                table.insert("kind".into(), Value::String(kind.clone()));
10202            }
10203            table
10204        };
10205        let mut providers = toml::Table::new();
10206        if let Some(configured) = self.providers.as_ref() {
10207            for row in codewhale_config::descriptors::provider_compatibility() {
10208                if let Some(entry) =
10209                    codewhale_config::provider_config_table!(@read configured, row.id)
10210                {
10211                    providers.insert(row.config_key.to_string(), Value::Table(entry_table(entry)));
10212                }
10213            }
10214            for (name, entry) in &configured.custom {
10215                providers.insert(name.clone(), Value::Table(entry_table(entry)));
10216            }
10217        }
10218        root.insert("providers".into(), Value::Table(providers));
10219        if let Some(vision) = &self.vision_model {
10220            let mut table = toml::Table::new();
10221            if let Some(key) = &vision.api_key {
10222                table.insert("api_key".into(), Value::String(key.clone()));
10223            }
10224            root.insert("vision_model".into(), Value::Table(table));
10225        }
10226
10227        self.legacy_root = codewhale_config::legacy_root::apply_to_table(&mut root);
10228
10229        if let Some(provider) = root.get("provider").and_then(Value::as_str) {
10230            self.provider = Some(provider.to_string());
10231        }
10232        if let (Some(vision), Some(key)) = (
10233            self.vision_model.as_mut(),
10234            root.get("vision_model")
10235                .and_then(|table| table.get("api_key"))
10236                .and_then(Value::as_str),
10237        ) {
10238            vision.api_key = Some(key.to_string());
10239        }
10240        let Some(providers) = root.get("providers").and_then(Value::as_table) else {
10241            return;
10242        };
10243        for (key, table) in providers {
10244            let Some(table) = table.as_table() else {
10245                continue;
10246            };
10247            let entry = if let Some(row) = codewhale_config::descriptors::provider_compatibility()
10248                .iter()
10249                .find(|row| row.config_key == key && row.kind != ProviderKind::Custom)
10250            {
10251                let configured = self.providers.get_or_insert_with(ProvidersConfig::default);
10252                let Some(entry) =
10253                    codewhale_config::provider_config_table!(@write configured, row.id)
10254                else {
10255                    continue;
10256                };
10257                entry
10258            } else {
10259                self.providers
10260                    .get_or_insert_with(ProvidersConfig::default)
10261                    .custom
10262                    .entry(key.clone())
10263                    .or_default()
10264            };
10265            let get = |field: &str| table.get(field).and_then(Value::as_str).map(str::to_string);
10266            entry.api_key = get("api_key");
10267            entry.base_url = get("base_url");
10268            entry.model = get("model");
10269            entry.kind = get("kind");
10270        }
10271        self.bind_legacy_root_custom_generation();
10272    }
10273}
10274
10275/// Parse one `config.toml`-shaped layer (no profile applied) through
10276/// `parse_config_file`, so the legacy top-level keys are canonicalized.
10277pub fn parse_config_base(contents: &str) -> std::result::Result<Config, toml::de::Error> {
10278    let parsed = parse_config_file(contents)?;
10279    let mut config = *parsed.base;
10280    config.legacy_root = parsed.legacy_root;
10281    Ok(config)
10282}
10283
10284/// Project the fresh receipt returned by the existing locked document writer.
10285/// This does not reuse the caller's diagnostic notes: a root-less document
10286/// receives no missing-id provenance, and verification still compares the
10287/// complete current table generation against the previously captured identity.
10288pub fn parse_config_after_locked_migration(
10289    contents: &str,
10290    moved: &codewhale_config::legacy_root::LegacyRootMigration,
10291) -> std::result::Result<Config, toml::de::Error> {
10292    let mut config = parse_config_base(contents)?;
10293    config.legacy_root.notes.extend(moved.notes.iter().cloned());
10294    config.bind_legacy_root_custom_generation();
10295    Ok(config)
10296}
10297
10298/// Parse a `config.toml`-shaped document. The legacy top-level `base_url` /
10299/// `api_key` move into their `[providers.<name>]` tables first (#6394), so no
10300/// reader here ever sees them; this is the only way a `ConfigFile` is parsed.
10301fn parse_config_file(contents: &str) -> std::result::Result<ConfigFile, toml::de::Error> {
10302    let (text, legacy_root) = codewhale_config::legacy_root::canonicalize_text(contents)?;
10303    let mut parsed = toml::from_str::<ConfigFile>(&text)?;
10304    parsed.base.legacy_root = legacy_root.clone();
10305    parsed.base.bind_legacy_root_custom_generation();
10306    parsed.legacy_root = legacy_root;
10307    Ok(parsed)
10308}
10309
10310/// Build a one-line warning when top-level-only keys are nested under a section
10311/// Codewhale does not define (`[general]` / `[sandbox]`). TOML silently drops
10312/// those keys, so e.g. `[general]\nallow_shell = true` never takes effect and
10313/// the shell tools (`exec_shell`, `task_shell_start`, …) are absent from the
10314/// catalog with no explanation. Returns `None` when nothing is misplaced.
10315///
10316/// This is the exact confusion behind #2589: `allow_shell` and `sandbox_mode`
10317/// belong at the top of the file, above any `[section]` header.
10318fn warn_on_misplaced_top_level_keys(raw: &str) -> Option<String> {
10319    let doc = toml::from_str::<toml::Value>(raw).ok()?;
10320    // Sections Codewhale does not recognize but users nest settings under.
10321    const UNKNOWN_SECTIONS: &[&str] = &["general", "sandbox"];
10322    // Keys that are only ever read from the top level of the config.
10323    const TOP_LEVEL_KEYS: &[&str] = &[
10324        "allow_shell",
10325        "sandbox_mode",
10326        "approval_policy",
10327        "verbosity",
10328    ];
10329
10330    let mut hits: Vec<String> = Vec::new();
10331    for section in UNKNOWN_SECTIONS {
10332        let Some(table) = doc.get(*section).and_then(toml::Value::as_table) else {
10333            continue;
10334        };
10335        for key in TOP_LEVEL_KEYS {
10336            if table.contains_key(*key) {
10337                hits.push(format!("`{section}.{key}`"));
10338            }
10339        }
10340    }
10341    if hits.is_empty() {
10342        return None;
10343    }
10344    Some(format!(
10345        "Ignoring {} — Codewhale has no `[general]` or `[sandbox]` section, so these \
10346         keys are silently dropped. Move them to the TOP of the config file (above any \
10347         `[section]` header), e.g. `allow_shell = true`. Until then, shell tools stay \
10348         disabled. (#2589)",
10349        hits.join(", ")
10350    ))
10351}
10352
10353fn apply_managed_overrides(config: &mut Config) -> Result<()> {
10354    let Some(path) = managed_config_file(config.managed_config_path.as_deref())? else {
10355        return Ok(());
10356    };
10357    let mut managed = load_single_config_file(&path).with_context(|| {
10358        format!(
10359            "the managed configuration {} cannot be loaded, and Codewhale does not start without a managed configuration it was told to use",
10360            codewhale_config::quote_os_path(&path)
10361        )
10362    })?;
10363    strip_external_credential_consent(&mut managed);
10364    managed.tool_launcher = managed_tool_launcher(&path)?;
10365    let prior_route = config
10366        .active_provider_identity()
10367        .map_err(|error| managed_route_error(config, &path, error))?;
10368    let mut merged = merge_config(config.clone(), managed.clone());
10369    apply_layer_root_model(&mut merged, &managed);
10370    let merged_route = merged
10371        .active_provider_identity()
10372        .map_err(|error| managed_route_error(&merged, &path, error))?;
10373    if managed.provider.is_some() {
10374        merged.route_provenance.provider_from_managed = true;
10375        merged.route_provenance.provider_from_env = false;
10376        merged.route_provenance.provider_from_saved_selection = false;
10377        merged.route_provenance.provider_from_profile = false;
10378    }
10379    if managed.default_text_model.is_some()
10380        || managed.legacy_model.is_some()
10381        || managed
10382            .provider_config_for(&merged_route)
10383            .and_then(|entry| entry.model.as_ref())
10384            .is_some()
10385    {
10386        merged.route_provenance.model_from_managed = true;
10387        merged.route_provenance.model_from_saved_selection = false;
10388        merged.route_provenance.model_from_profile = false;
10389        merged.remembered_selection_scope = Some(false);
10390    } else if managed.provider.is_some() {
10391        merged.remembered_selection_scope = Some(false);
10392    }
10393    if prior_route != merged_route || config_defines_base_url_for_effective_route(&managed, &merged)
10394    {
10395        // Managed configuration is a higher-precedence file layer. If it
10396        // selects a different route or supplies that route's endpoint, the
10397        // lower environment layer no longer owns the effective base URL.
10398        //
10399        // Record that as an explicit "nobody owns it" rather than clearing the
10400        // receipt. Clearing it would read as "this config never met the
10401        // environment layer", which re-enables the generic
10402        // `CODEWHALE_BASE_URL` fallback for every route — including pinned
10403        // cross-provider children, which would then borrow an ambient host
10404        // that managed routing had just taken authority over.
10405        //
10406        // DeepSeek's env-written endpoint lives in its own table now that
10407        // there is no shared top-level field (#6394). Managed authority takes
10408        // that ambient value away from every route, as it always did.
10409        if let BaseUrlEnvReceipt::Route(ProviderKind::Deepseek, key) = &config.base_url_env_receipt
10410            && let Ok(owner) = merged.resolve_persisted_provider_identity(
10411                Some(ProviderKind::Deepseek.as_str()),
10412                Some(key),
10413            )
10414            && managed
10415                .provider_config_for(&owner)
10416                .and_then(|entry| entry.base_url.as_ref())
10417                .is_none()
10418            && let Some(env_value) = env_base_url_override()
10419            && merged
10420                .provider_config_for(&owner)
10421                .and_then(|entry| entry.base_url.as_deref())
10422                == Some(env_value.as_str())
10423        {
10424            merged.provider_config_for_mut(&owner)?.base_url = None;
10425        }
10426        merged.base_url_env_receipt = BaseUrlEnvReceipt::NoOwner;
10427    }
10428    // A managed `[network]` table outranks the user document. Record that the
10429    // resolved policy is not the document's to replace, so a mid-session
10430    // re-read of that document folds onto it instead of widening it.
10431    if managed.network.is_some() {
10432        merged.network_layer_is_managed = true;
10433    }
10434    if managed.tool_launcher.is_some()
10435        && !matches!(
10436            managed.sandbox_mode.as_deref(),
10437            Some("workspace-write" | "read-only")
10438        )
10439    {
10440        anyhow::bail!(
10441            "`tool_launcher` in the managed configuration {} needs `sandbox_mode = \"workspace-write\"` or `\"read-only\"` beside it: commands run through the launcher only inside the sandbox",
10442            codewhale_config::quote_os_path(&path)
10443        );
10444    }
10445    *config = merged;
10446    Ok(())
10447}
10448
10449fn managed_tool_launcher(path: &Path) -> Result<Option<Vec<String>>> {
10450    let raw = fs::read_to_string(path)
10451        .with_context(|| format!("Failed to read config file: {}", path.display()))?;
10452    let Ok(document) = toml::from_str::<toml::Value>(&raw) else {
10453        return Ok(None);
10454    };
10455    if codewhale_config::tool_launcher_in_profiles(&document) {
10456        anyhow::bail!(
10457            "`tool_launcher` in {} belongs at the top level of the managed configuration, not in a profile",
10458            codewhale_config::quote_os_path(path)
10459        );
10460    }
10461    let Some(value) = document.get("tool_launcher") else {
10462        return Ok(None);
10463    };
10464    if !cfg!(all(target_os = "linux", not(target_env = "ohos"))) {
10465        anyhow::bail!(
10466            "`tool_launcher` in {} is supported only on Linux",
10467            codewhale_config::quote_os_path(path)
10468        );
10469    }
10470    let argv = value
10471        .as_array()
10472        .and_then(|items| {
10473            items
10474                .iter()
10475                .map(|item| item.as_str().map(str::to_string))
10476                .collect::<Option<Vec<_>>>()
10477        })
10478        .filter(|argv| {
10479            argv.first()
10480                .is_some_and(|program| Path::new(program).is_absolute())
10481                && argv.iter().all(|arg| !arg.is_empty() && !arg.contains('\0'))
10482        })
10483        .ok_or_else(|| {
10484            anyhow::anyhow!(
10485                "`tool_launcher` in {} must be a list of strings whose first entry is an absolute program path",
10486                codewhale_config::quote_os_path(path)
10487            )
10488        })?;
10489    if !managed_path_is_named_by_host(path) {
10490        anyhow::bail!(
10491            "`tool_launcher` in {} is not accepted: that file is not CODEWHALE_MANAGED_CONFIG_PATH or the default managed path, and a launcher is read only from one of those",
10492            codewhale_config::quote_os_path(path)
10493        );
10494    }
10495    if managed_file_is_replaceable(path) {
10496        anyhow::bail!(
10497            "`tool_launcher` in {} is not accepted: the Engine's own user can change that file or its directory, so it is not a managed configuration",
10498            codewhale_config::quote_os_path(path)
10499        );
10500    }
10501    Ok(Some(argv))
10502}
10503
10504fn managed_path_from_env() -> Option<PathBuf> {
10505    codewhale_env_var(
10506        "CODEWHALE_MANAGED_CONFIG_PATH",
10507        "DEEPSEEK_MANAGED_CONFIG_PATH",
10508    )
10509    .ok()
10510    .map(|value| expand_path(&value))
10511}
10512
10513fn managed_config_file(configured: Option<&str>) -> Result<Option<PathBuf>> {
10514    if let Some(path) = managed_path_from_env() {
10515        return Ok(Some(path));
10516    }
10517    let default = default_managed_config_path().filter(|path| {
10518        fs::symlink_metadata(path).map_or_else(
10519            |error| error.kind() != std::io::ErrorKind::NotFound,
10520            |_| true,
10521        )
10522    });
10523    let Some(configured) = configured
10524        .filter(|value| !value.trim().is_empty())
10525        .map(expand_path)
10526    else {
10527        return Ok(default);
10528    };
10529    if let Some(default) = default
10530        && default != configured
10531    {
10532        anyhow::bail!(
10533            "`managed_config_path` names {}, but the default managed configuration {} exists, and a config file cannot replace it; name another managed file with CODEWHALE_MANAGED_CONFIG_PATH instead",
10534            codewhale_config::quote_os_path(&configured),
10535            codewhale_config::quote_os_path(&default)
10536        );
10537    }
10538    Ok(Some(configured))
10539}
10540
10541fn managed_route_error(config: &Config, path: &Path, error: String) -> anyhow::Error {
10542    let selected = config.provider.as_deref().unwrap_or_default();
10543    let undeclared = !selected.is_empty()
10544        && ProviderKind::parse(selected).is_none()
10545        && config
10546            .providers
10547            .as_ref()
10548            .and_then(|providers| providers.custom_provider_config(selected))
10549            .is_none();
10550    if undeclared {
10551        anyhow::anyhow!(
10552            "provider '{selected}' has no `[providers.{selected}]` table in the configuration, and the managed configuration {} applies: a provider that only a plugin declares cannot be used under a managed configuration. Declare `[providers.{selected}]` in the config file, or select a built-in provider",
10553            codewhale_config::quote_os_path(path)
10554        )
10555    } else {
10556        anyhow::anyhow!(
10557            "{error} (while applying the managed configuration {})",
10558            codewhale_config::quote_os_path(path)
10559        )
10560    }
10561}
10562
10563fn managed_path_is_named_by_host(path: &Path) -> bool {
10564    managed_path_from_env()
10565        .into_iter()
10566        .chain(default_managed_config_path())
10567        .any(|named| named == path)
10568}
10569
10570#[cfg(test)]
10571static TEST_TREAT_MANAGED_FILE_AS_SEALED: std::sync::atomic::AtomicBool =
10572    std::sync::atomic::AtomicBool::new(false);
10573
10574fn managed_file_is_replaceable(path: &Path) -> bool {
10575    #[cfg(test)]
10576    if TEST_TREAT_MANAGED_FILE_AS_SEALED.load(std::sync::atomic::Ordering::SeqCst) {
10577        return false;
10578    }
10579    engine_can_replace(path)
10580}
10581
10582#[cfg(unix)]
10583fn engine_can_replace(path: &Path) -> bool {
10584    use std::os::unix::ffi::OsStrExt as _;
10585    use std::os::unix::fs::MetadataExt as _;
10586    fn writable(path: &Path) -> bool {
10587        let Ok(spelled) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
10588            return true;
10589        };
10590        // SAFETY: `spelled` is a valid NUL-terminated path for the call's duration.
10591        unsafe { libc::access(spelled.as_ptr(), libc::W_OK) == 0 }
10592    }
10593    // SAFETY: geteuid has no preconditions.
10594    let euid = unsafe { libc::geteuid() };
10595    let replaceable = |file: &Path| {
10596        if writable(file) {
10597            return true;
10598        }
10599        let mut child = file;
10600        while let Some(dir) = child.parent().filter(|dir| !dir.as_os_str().is_empty()) {
10601            if writable(dir) {
10602                let sticky = std::fs::metadata(dir).is_ok_and(|meta| meta.mode() & 0o1000 != 0);
10603                let child_is_ours =
10604                    std::fs::symlink_metadata(child).map_or(true, |meta| meta.uid() == euid);
10605                if !sticky || child_is_ours {
10606                    return true;
10607                }
10608            }
10609            child = dir;
10610        }
10611        false
10612    };
10613    let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
10614    let canonical = path.canonicalize().unwrap_or_else(|_| absolute.clone());
10615    replaceable(&absolute) || replaceable(&canonical)
10616}
10617
10618#[cfg(not(unix))]
10619fn engine_can_replace(_path: &Path) -> bool {
10620    true
10621}
10622
10623/// Organization-managed overlays may constrain routing and policy, but they
10624/// cannot consent on a user's behalf to credential files owned by another
10625/// CLI. Only the user config/profile loaded before this layer may carry these
10626/// grants. A managed `disabled` record is a tightening tombstone and is kept
10627/// so a lower-precedence user grant cannot survive an administrator deny.
10628fn strip_external_credential_consent(config: &mut Config) {
10629    if config.providers.is_none() {
10630        return;
10631    }
10632    for row in codewhale_config::descriptors::provider_compatibility() {
10633        if row.kind == ProviderKind::Custom {
10634            continue;
10635        }
10636        let Ok(identity) = config.resolve_persisted_provider_identity(Some(row.id), Some(row.id))
10637        else {
10638            continue;
10639        };
10640        let Ok(entry) = config.provider_config_for_mut(&identity) else {
10641            continue;
10642        };
10643        if entry.external_credentials.as_ref().is_some_and(|consent| {
10644            consent.access != codewhale_config::ExternalCredentialAccess::Disabled
10645        }) {
10646            entry.external_credentials = None;
10647        }
10648    }
10649    if let Some(providers) = config.providers.as_mut() {
10650        for provider in providers.custom.values_mut() {
10651            if provider
10652                .external_credentials
10653                .as_ref()
10654                .is_some_and(|consent| {
10655                    consent.access != codewhale_config::ExternalCredentialAccess::Disabled
10656                })
10657            {
10658                provider.external_credentials = None;
10659            }
10660        }
10661    }
10662}
10663
10664fn config_defines_base_url_for_effective_route(source: &Config, effective: &Config) -> bool {
10665    let Ok(identity) = effective.active_provider_identity() else {
10666        return false;
10667    };
10668    let mut source = source.clone();
10669    if source.scope_to_provider_identity(&identity).is_err() {
10670        return false;
10671    }
10672    source
10673        .provider_route_string_with_deepseek_fallback(&identity, |entry| entry.base_url.clone())
10674        .is_some_and(|base| !base.trim().is_empty())
10675}
10676
10677fn apply_requirements(config: &mut Config) -> Result<()> {
10678    let path = config
10679        .requirements_path
10680        .as_deref()
10681        .map(expand_path)
10682        .or_else(default_requirements_path);
10683    let Some(path) = path else {
10684        return Ok(());
10685    };
10686    if !path.exists() {
10687        return Ok(());
10688    }
10689    let contents = fs::read_to_string(&path)
10690        .with_context(|| format!("Failed to read requirements file: {}", path.display()))?;
10691    let requirements: RequirementsFile = toml::from_str(&contents).map_err(|_| {
10692        anyhow::anyhow!(
10693            "Failed to parse requirements file {}; file contents were omitted",
10694            codewhale_config::quote_os_path(&path)
10695        )
10696    })?;
10697
10698    if !requirements.allowed_approval_policies.is_empty() {
10699        use codewhale_execpolicy::ApprovalMode;
10700
10701        let policy = config
10702            .approval_policy
10703            .as_deref()
10704            .unwrap_or("on-request")
10705            .to_ascii_lowercase();
10706        if !requirements.allowed_approval_policies.iter().any(|p| {
10707            match (
10708                ApprovalMode::from_config_value(p),
10709                ApprovalMode::from_config_value(&policy),
10710            ) {
10711                (Some(allowed), Some(effective)) => allowed == effective,
10712                _ => p.eq_ignore_ascii_case(&policy),
10713            }
10714        }) {
10715            anyhow::bail!(
10716                "approval_policy '{policy}' is not allowed by requirements ({})",
10717                requirements.allowed_approval_policies.join(", ")
10718            );
10719        }
10720    }
10721    if !requirements.allowed_sandbox_modes.is_empty() {
10722        // At config load there is no live turn mode yet. Check the Agent
10723        // baseline that the engine's resolver derives from the same approval
10724        // posture; Plan can narrow it later.
10725        // Explicit settings retain their existing allow-list check.
10726        let mode = config
10727            .sandbox_mode
10728            .as_deref()
10729            .map(str::to_ascii_lowercase)
10730            .unwrap_or_else(|| {
10731                use codewhale_execpolicy::ApprovalMode;
10732
10733                // Sandbox requirements lock approval posture at startup,
10734                // excluding saved preferences and every YOLO override.
10735                let approval = config
10736                    .approval_policy
10737                    .as_deref()
10738                    .and_then(ApprovalMode::from_config_value)
10739                    .unwrap_or_default();
10740                approval.agent_baseline_sandbox_mode().to_string()
10741            });
10742        if !requirements
10743            .allowed_sandbox_modes
10744            .iter()
10745            .any(|m| m.eq_ignore_ascii_case(&mode))
10746        {
10747            anyhow::bail!(
10748                "sandbox_mode '{mode}' is not allowed by requirements ({})",
10749                requirements.allowed_sandbox_modes.join(", ")
10750            );
10751        }
10752    }
10753
10754    Ok(())
10755}
10756
10757fn merge_features(
10758    base: Option<FeaturesToml>,
10759    override_cfg: Option<FeaturesToml>,
10760) -> Option<FeaturesToml> {
10761    match (base, override_cfg) {
10762        (None, None) => None,
10763        (Some(mut base), Some(override_cfg)) => {
10764            for (key, value) in override_cfg.entries {
10765                base.entries.insert(key, value);
10766            }
10767            Some(base)
10768        }
10769        (Some(base), None) => Some(base),
10770        (None, Some(override_cfg)) => Some(override_cfg),
10771    }
10772}
10773
10774pub fn ensure_parent_dir(path: &Path) -> Result<()> {
10775    if let Some(parent) = path.parent() {
10776        fs::create_dir_all(parent)
10777            .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
10778        #[cfg(unix)]
10779        {
10780            // Tighten group/other bits on the parent dir as a hardening pass.
10781            // The dir lives under the user's home, so the chmod is best-effort:
10782            // filesystems that don't accept Unix permission bits (Docker
10783            // bind-mounts of NTFS, network shares, FAT, certain CI volumes —
10784            // see #897) return EPERM/ENOTSUP. The dir already exists by the
10785            // time we get here, so failing the whole save just because we
10786            // couldn't tighten perms strands the user mid-onboarding. Warn
10787            // loudly so a security-sensitive operator can still notice via
10788            // `RUST_LOG=warn`, then continue.
10789            if let Ok(meta) = fs::metadata(parent) {
10790                let mode = meta.permissions().mode();
10791                if mode & 0o077 != 0 {
10792                    let mut perms = meta.permissions();
10793                    perms.set_mode(mode & !0o077);
10794                    if let Err(err) = fs::set_permissions(parent, perms) {
10795                        tracing::warn!(
10796                            target: "codewhale::config",
10797                            path = %parent.display(),
10798                            error = %err,
10799                            "could not tighten parent dir permissions; \
10800                             filesystem may not support Unix chmod \
10801                             (Docker bind-mount, NTFS, network share). \
10802                             Continuing — the file will still be written."
10803                        );
10804                    }
10805                }
10806            }
10807        }
10808    }
10809    Ok(())
10810}
10811
10812/// Write content to a config file with restrictive permissions (owner-only read/write).
10813/// On Unix this sets mode 0o600 before writing.
10814fn write_config_file_secure(path: &Path, content: &str) -> Result<()> {
10815    codewhale_config::create_config_document(path, content)
10816}
10817
10818/// Where a saved credential ended up. Returned by [`save_api_key`] so
10819/// the caller can show a confirmation message without leaking the key.
10820#[derive(Debug, Clone, PartialEq, Eq)]
10821pub enum SavedCredential {
10822    /// Stored in the durable secret store. The config file contains only
10823    /// non-secret provider metadata and has any matching plaintext `api_key`
10824    /// entry removed. The `backend` label is the value of
10825    /// [`codewhale_secrets::Secrets::backend_name`] at write time so the toast
10826    /// text can name the actual backend (`"system keyring"`,
10827    /// `"file-based (~/.codewhale/secrets/)"`).
10828    KeyringAndConfigFile {
10829        /// `Secrets::backend_name()` at write time.
10830        backend: String,
10831        /// Absolute path to the credential-free config metadata file.
10832        path: PathBuf,
10833    },
10834    /// Stored in the Codewhale config file only under `cfg(test)` so unit tests
10835    /// without an explicitly isolated secret backend do not pollute the host
10836    /// credential store. Production save flows never automatically downgrade
10837    /// a failed secret-store write to plaintext.
10838    ConfigFile(PathBuf),
10839}
10840
10841impl SavedCredential {
10842    /// Human-readable description for status / log output. Never
10843    /// includes the key value.
10844    #[must_use]
10845    pub fn describe(&self) -> String {
10846        match self {
10847            Self::KeyringAndConfigFile { backend, path } => {
10848                format!(
10849                    "secret store ({backend}); credential-free config metadata in {}",
10850                    path.display()
10851                )
10852            }
10853            Self::ConfigFile(path) => path.display().to_string(),
10854        }
10855    }
10856}
10857
10858/// Resolve the config document for CREDENTIAL writes: api_key values,
10859/// `auth_mode` markers, and oauth/external-credential pointers.
10860///
10861/// Credentials are user-global — a key saved while working in one repo must be
10862/// visible from every other repo (#5045, #5193). The ambient
10863/// `CODEWHALE_CONFIG_PATH`/`DEEPSEEK_CONFIG_PATH` override can point at a
10864/// workspace-scoped document (`<repo>/.codewhale/config.toml`, plaintext and
10865/// easy to commit by accident), so credential writes that would land there are
10866/// rescoped to the user-global config instead. Non-credential settings keep
10867/// the ambient scoping, and callers that pass an explicit config path never
10868/// consult this resolver; a per-workspace destination stays possible only as
10869/// that kind of explicit opt-in.
10870pub fn credential_config_path() -> anyhow::Result<PathBuf> {
10871    let resolved = try_default_config_path()?;
10872    if !codewhale_config::config_path_is_workspace_scoped(&resolved) {
10873        return Ok(resolved);
10874    }
10875    let global = home_config_path()
10876        .context("Failed to resolve user-global config path: home directory not found.")?;
10877    tracing::info!(
10878        ambient = %resolved.display(),
10879        global = %global.display(),
10880        "rescoping credential write from workspace config to user-global config"
10881    );
10882    Ok(global)
10883}
10884
10885/// Save the active provider's API key.
10886///
10887/// The selected durable secret backend is attempted first. On success the
10888/// config keeps only non-secret auth metadata and any older plaintext copy is
10889/// removed. When the secret-store write fails (OS permission denied, corrupt
10890/// or read-only file backend, etc.), the save fails loudly rather than writing
10891/// the key to plaintext `config.toml`.
10892///
10893/// Under `cfg(test)` the secret-store path is enabled only when the test sets
10894/// both an isolated `CODEWHALE_HOME` and an explicit backend, preventing unit
10895/// tests from touching the developer's real credential store.
10896pub fn save_api_key(api_key: &str) -> Result<SavedCredential> {
10897    save_root_api_key_for_secret_slot(api_key, "deepseek", "deepseek")
10898}
10899
10900fn save_root_api_key_for_secret_slot(
10901    api_key: &str,
10902    secret_slot: &str,
10903    table: &str,
10904) -> Result<SavedCredential> {
10905    // #6528: strip pasted invisible characters and whitespace in one place.
10906    let normalized = codewhale_secrets::normalize_api_key(api_key);
10907    let trimmed = normalized.as_str();
10908    if trimmed.is_empty() {
10909        anyhow::bail!("Refusing to save an empty API key.");
10910    }
10911
10912    let path = credential_config_path().context("Failed to resolve config path for API key.")?;
10913
10914    if let Some(secrets) = credential_secret_store() {
10915        // Same read-modify-write as the per-provider save below; hold the slot's
10916        // write lock across snapshot, store write, config write, and rollback.
10917        return crate::credentials::store::with_provider_write_lock(secret_slot, || {
10918            let prior_secret = secrets.get(secret_slot);
10919            match prior_secret.as_ref() {
10920                Ok(prior) => match secrets.set(secret_slot, trimmed) {
10921                    Ok(()) => {
10922                        if let Err(error) =
10923                            save_root_api_key_metadata_without_plaintext(&path, table)
10924                        {
10925                            let current = secrets.get(secret_slot).map_err(|rollback| {
10926                        anyhow::anyhow!(
10927                            "{error}; additionally could not verify secret-store rollback for {secret_slot}: {rollback}"
10928                        )
10929                    })?;
10930                            if current.as_deref() == Some(trimmed) {
10931                                match prior {
10932                            Some(previous) => secrets.set(secret_slot, previous),
10933                            None => secrets.delete(secret_slot),
10934                        }
10935                        .map_err(|rollback| {
10936                            anyhow::anyhow!(
10937                                "{error}; additionally failed to restore prior secret-store state for {secret_slot}: {rollback}"
10938                            )
10939                        })?;
10940                            }
10941                            return Err(error);
10942                        }
10943                        codewhale_config::scrub_plaintext_api_keys_from_config_backup(&path)?;
10944                        let backend = secrets.backend_name().to_string();
10945                        log_sensitive_event(
10946                            "credential.save",
10947                            json!({
10948                                "backend": backend.clone(),
10949                                "config_path": path.display().to_string(),
10950                                "plaintext_config_fallback": false,
10951                            }),
10952                        );
10953                        Ok(SavedCredential::KeyringAndConfigFile { backend, path })
10954                    }
10955                    Err(err) => Err(plaintext_credential_fallback_refused("write", &path, &err)),
10956                },
10957                Err(error) => Err(plaintext_credential_fallback_refused(
10958                    "snapshot", &path, &error,
10959                )),
10960            }
10961        });
10962    }
10963
10964    let path = save_api_key_to_config_file(trimmed, table)?;
10965    codewhale_config::scrub_plaintext_api_keys_from_config_backup(&path)?;
10966    Ok(SavedCredential::ConfigFile(path))
10967}
10968
10969fn plaintext_credential_fallback_refused(
10970    operation: &str,
10971    config_path: &Path,
10972    failure: &dyn std::fmt::Display,
10973) -> anyhow::Error {
10974    anyhow::anyhow!(
10975        "Secret storage {operation} failed: {failure}. Refusing to write the API key in plaintext to {}. Fix the configured secret backend and retry; Codewhale did not change that file.",
10976        codewhale_config::quote_os_path(config_path)
10977    )
10978}
10979
10980/// The durable secret store for credential saves and logout-time deletes.
10981///
10982/// Under `cfg(test)` the store is only exposed when the test set both an
10983/// isolated `CODEWHALE_HOME` and an explicit backend, so unit tests can never
10984/// touch the developer's real credential store.
10985#[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
10986pub fn credential_secret_store() -> Option<codewhale_secrets::Secrets> {
10987    Some(codewhale_secrets::Secrets::auto_detect())
10988}
10989
10990#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
10991pub fn credential_secret_store() -> Option<codewhale_secrets::Secrets> {
10992    let isolated_home = codewhale_paths::codewhale_home_is_explicit();
10993    let explicit_backend = std::env::var_os("CODEWHALE_SECRET_BACKEND")
10994        .or_else(|| std::env::var_os("DEEPSEEK_SECRET_BACKEND"))
10995        .is_some_and(|value| !value.is_empty());
10996    (crate::test_support::state_from_environment() || (isolated_home && explicit_backend))
10997        .then(codewhale_secrets::Secrets::auto_detect)
10998}
10999
11000fn save_root_api_key_metadata_without_plaintext(config_path: &Path, table: &str) -> Result<()> {
11001    ensure_parent_dir(config_path)?;
11002    crate::config_persistence::mutate_config_document(config_path, |doc| {
11003        crate::config_persistence::set_document_value(doc, &["auth_mode"], "api_key")?;
11004        // Saving a key never pins a model (see
11005        // `codewhale_config::credentials::prepare_provider_api_key_metadata`).
11006        if !doc.contains_key("reasoning_effort") {
11007            crate::config_persistence::set_document_value(doc, &["reasoning_effort"], "auto")?;
11008        }
11009        crate::config_persistence::unset_document_value(doc, &["api_key"])?;
11010        crate::config_persistence::unset_document_value(doc, &["providers", table, "api_key"])?;
11011        crate::config_persistence::set_document_value(
11012            doc,
11013            &["providers", table, "auth_mode"],
11014            "api_key",
11015        )?;
11016        if table == "deepseek" {
11017            crate::config_persistence::unset_document_value(
11018                doc,
11019                &["providers", "deepseek-cn", "api_key"],
11020            )?;
11021        }
11022        Ok(())
11023    })
11024    .with_context(|| format!("Failed to write config to {}", config_path.display()))
11025}
11026
11027/// Write the key directly to `[providers.<table>] api_key` in `config.toml`.
11028fn save_api_key_to_config_file(api_key: &str, table: &str) -> Result<PathBuf> {
11029    let config_path =
11030        credential_config_path().context("Failed to resolve config path for API key.")?;
11031
11032    ensure_parent_dir(&config_path)?;
11033
11034    if config_path.exists() {
11035        // TOML-aware upsert. The old line scan keyed off
11036        // `existing.contains("api_key")`, so a comment that merely mentioned
11037        // api_key made it skip the insert entirely; editing the document
11038        // replaces or inserts the real key and keeps user comments.
11039        crate::config_persistence::mutate_config_document(&config_path, |doc| {
11040            // DeepSeek's key lives in its own table (#6394); an explicit save
11041            // also ends any disagreement with an older top-level key.
11042            crate::config_persistence::set_document_value(
11043                doc,
11044                &["providers", table, "api_key"],
11045                api_key,
11046            )?;
11047            crate::config_persistence::unset_document_value(doc, &["api_key"])?;
11048            crate::config_persistence::set_document_value(doc, &["auth_mode"], "api_key")
11049        })
11050        .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
11051    } else {
11052        // Create new minimal config
11053        let content = format!(
11054            r#"# codewhale Configuration
11055# Set provider credentials in this file or via environment variables.
11056# See /links in the TUI for provider-specific credential pages.
11057
11058auth_mode = "api_key"
11059
11060# Default model (unset follows the provider default)
11061# default_text_model = "{DEFAULT_TEXT_MODEL}"
11062
11063# Thinking mode (DeepSeek V4 reasoning effort):
11064# "auto" | "off" | "low" | "medium" | "high" | "max"
11065# Ctrl+T in the TUI (or /effort) cycles the active model's effort levels.
11066reasoning_effort = "auto"
11067
11068[providers.{table}]
11069api_key = "{api_key}"
11070# Base URL (default: https://api.deepseek.com/beta)
11071# Set https://api.deepseek.com to opt out of beta features.
11072# base_url = "https://api.deepseek.com/beta"
11073"#
11074        );
11075        crate::config_persistence::write_config_toml_atomic(&config_path, &content)
11076            .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
11077    }
11078
11079    log_sensitive_event(
11080        "credential.save",
11081        json!({
11082            "backend": "config_file",
11083            "config_path": config_path.display().to_string(),
11084        }),
11085    );
11086
11087    Ok(config_path)
11088}
11089
11090fn provider_uses_oauth_credentials(config: &Config, identity: &ProviderIdentity) -> bool {
11091    let provider = identity.provider;
11092    !auth_mode_disables_api_key(config.auth_mode_for_provider(identity).as_deref())
11093        && !config.provider_uses_custom_endpoint(identity)
11094        && (provider == ProviderKind::OpenaiCodex
11095            || (provider == ProviderKind::Anthropic
11096                && config.auth_mode_for_provider(identity).as_deref() == Some("oauth"))
11097            || (provider == ProviderKind::Moonshot
11098                && config
11099                    .provider_config_for(identity)
11100                    .is_some_and(provider_config_uses_kimi_imported_token))
11101            || (provider == ProviderKind::Xai
11102                && config
11103                    .provider_config_for(identity)
11104                    .is_some_and(provider_config_uses_xai_oauth)))
11105}
11106
11107/// The environment variable name a provider route explicitly binds via
11108/// `[providers.<name>] api_key_env`, when credentials are bound to the active
11109/// endpoint. `None` when the route declares no binding.
11110fn bound_provider_api_key_env_name(config: &Config, identity: &ProviderIdentity) -> Option<String> {
11111    if !config.config_credentials_are_bound_to_provider_endpoint(identity) {
11112        return None;
11113    }
11114    config
11115        .provider_config_for(identity)
11116        .and_then(|entry| entry.api_key_env.as_deref())
11117        .map(str::trim)
11118        .filter(|name| !name.is_empty())
11119        .map(str::to_string)
11120}
11121
11122fn provider_config_env_api_key(config: &Config, identity: &ProviderIdentity) -> Option<String> {
11123    let env_name = bound_provider_api_key_env_name(config, identity)?;
11124    std::env::var(env_name)
11125        .ok()
11126        .filter(|value| !value.trim().is_empty())
11127}
11128
11129#[must_use]
11130pub fn active_provider_has_config_api_key(config: &Config) -> bool {
11131    let Ok(identity) = config.active_provider_identity() else {
11132        return false;
11133    };
11134    let provider = identity.provider;
11135    if auth_mode_disables_api_key(config.auth_mode_for_provider(&identity).as_deref()) {
11136        return false;
11137    }
11138    let custom_endpoint = config.provider_uses_custom_endpoint(&identity);
11139
11140    if provider == ProviderKind::Moonshot
11141        && !custom_endpoint
11142        && config
11143            .provider_config_for(&identity)
11144            .is_some_and(provider_config_uses_kimi_imported_token)
11145    {
11146        return false;
11147    }
11148    if provider == ProviderKind::OpenaiCodex && !custom_endpoint {
11149        return crate::oauth::credentials_valid(crate::oauth::OAuthProvider::Chatgpt, config);
11150    }
11151    if !custom_endpoint
11152        && matches!(provider, ProviderKind::Huggingface)
11153        && std::env::var("HUGGINGFACE_API_KEY")
11154            .or_else(|_| std::env::var("HF_TOKEN"))
11155            .is_ok_and(|k| !k.trim().is_empty())
11156    {
11157        return true;
11158    }
11159    if !custom_endpoint
11160        && matches!(provider, ProviderKind::Modelscope)
11161        && std::env::var("MODELSCOPE_API_KEY").is_ok_and(|k| !k.trim().is_empty())
11162    {
11163        return true;
11164    }
11165
11166    if config.config_credentials_are_bound_to_provider_endpoint(&identity)
11167        && config
11168            .provider_route_string_with_deepseek_fallback(&identity, |entry| entry.api_key.clone())
11169            .is_some_and(|key| {
11170                classify_config_api_key_value(&key) == ConfigApiKeyValueKind::Literal
11171            })
11172    {
11173        return true;
11174    }
11175    if !config.should_skip_secret_store_for_provider(&identity)
11176        && provider_secret_store_api_key(config, &identity).is_some()
11177    {
11178        return true;
11179    }
11180
11181    false
11182}
11183
11184#[must_use]
11185pub fn active_provider_has_env_api_key(config: &Config) -> bool {
11186    active_provider_env_api_key_source(config).is_some()
11187}
11188
11189/// Where the active provider's environment key comes from, in the resolver's
11190/// env precedence (`credential_resolve` steps 4-6): `--api-key`, the route's
11191/// `api_key_env` variable, or the provider's own ambient variable. Returns the
11192/// place's name only; any value read to test presence is dropped here.
11193#[must_use]
11194pub fn active_provider_env_api_key_source(config: &Config) -> Option<String> {
11195    let identity = config.active_provider_identity().ok()?;
11196    if config.required_account_model_owner.is_some()
11197        || config.session_provider_keys_only
11198        || config.session_provider_api_key(&identity).is_some()
11199    {
11200        return None;
11201    }
11202    let provider = identity.provider;
11203    if provider == ProviderKind::OpenaiCodex && !config.provider_uses_custom_endpoint(&identity) {
11204        return None;
11205    }
11206    if auth_mode_disables_api_key(config.auth_mode_for_provider(&identity).as_deref()) {
11207        return None;
11208    }
11209    if !provider_uses_oauth_credentials(config, &identity)
11210        && explicit_cli_api_key_override().is_some()
11211    {
11212        return Some("--api-key".to_string());
11213    }
11214    if provider_config_env_api_key(config, &identity).is_some() {
11215        return bound_provider_api_key_env_name(config, &identity);
11216    }
11217    if config.should_skip_secret_store_for_provider(&identity) {
11218        return None;
11219    }
11220    provider_env_api_key_named(provider).map(|(name, _)| name.to_string())
11221}
11222
11223#[must_use]
11224pub fn active_provider_uses_env_only_api_key(config: &Config) -> bool {
11225    active_provider_has_env_api_key(config) && !active_provider_has_config_api_key(config)
11226}
11227
11228/// A key saved in the user-global config file stays visible even when this
11229/// process loaded a DIFFERENT config (e.g. an explicit workspace `--config`
11230/// path). Credentials are user-global: a workspace override may select a
11231/// different route, but it must never make a global credential appear locked.
11232///
11233/// Bounded, read-only, non-migrating: parses the default config file's raw
11234/// provider table directly (never runs legacy migration, never opens a
11235/// write-capable backend). Returns the key only when it reads as a real
11236/// literal, not a placeholder.
11237struct UserGlobalConfigCache {
11238    path: PathBuf,
11239    modified: Option<SystemTime>,
11240    len: u64,
11241    json: serde_json::Value,
11242}
11243
11244fn user_global_config_json() -> Option<serde_json::Value> {
11245    static CACHE: Mutex<Option<UserGlobalConfigCache>> = Mutex::new(None);
11246    let path = codewhale_config::default_config_path().ok()?;
11247    let meta = fs::metadata(&path).ok()?;
11248    let modified = meta.modified().ok();
11249    let len = meta.len();
11250    let mut guard = CACHE.lock().ok()?;
11251    if let Some(cached) = guard.as_ref()
11252        && cached.path == path
11253        && cached.modified == modified
11254        && cached.len == len
11255    {
11256        return Some(cached.json.clone());
11257    }
11258    let text = fs::read_to_string(&path).ok()?;
11259    let doc = codewhale_config::parse_config_toml(&text).ok()?;
11260    let json = serde_json::to_value(&doc).ok()?;
11261    *guard = Some(UserGlobalConfigCache {
11262        path,
11263        modified,
11264        len,
11265        json: json.clone(),
11266    });
11267    Some(json)
11268}
11269
11270fn user_global_config_api_key(identity: &ProviderIdentity) -> Option<String> {
11271    let provider = identity.provider;
11272    if provider == ProviderKind::Custom {
11273        // Custom providers are per-config by nature; the probe applies to
11274        // built-in ids whose keys are saved under the user-global file.
11275        return None;
11276    }
11277    let json = user_global_config_json()?;
11278    let provider_config_key = identity.compatibility()?.config_key;
11279    let key = json
11280        .get("providers")?
11281        .get(provider_config_key)?
11282        .get("api_key")?
11283        .as_str()?;
11284    let key = key.trim();
11285    if key.is_empty() || classify_config_api_key_value(key) != ConfigApiKeyValueKind::Literal {
11286        return None;
11287    }
11288    Some(key.to_string())
11289}
11290
11291/// `(key, source label)` as the active-route resolver returns it.
11292pub type ResolvedApiKey = (String, String);
11293
11294/// Key-source label the resolver gives a key minted by xAI OAuth (owned
11295/// sign-in or consented Grok CLI import), named in authentication errors.
11296pub const XAI_OAUTH_KEY_SOURCE: &str = "xAI OAuth login";
11297
11298impl Config {
11299    /// Resolve Codewhale's verified ChatGPT grant. Credential refresh remains
11300    /// serialized by the owned-store lifecycle transaction.
11301    pub fn codex_credentials(&self) -> Result<crate::oauth::OwnedOAuthCredentials> {
11302        anyhow::ensure!(
11303            !self.session_provider_keys_only,
11304            "Stored ChatGPT sign-in is unavailable under session-only provider key policy"
11305        );
11306        let identity = self
11307            .active_provider_identity()
11308            .map_err(anyhow::Error::msg)?;
11309        anyhow::ensure!(
11310            identity.provider == ProviderKind::OpenaiCodex
11311                && !self.provider_uses_custom_endpoint(&identity),
11312            "ChatGPT credentials are only available on the official public API route"
11313        );
11314        crate::oauth::official_chatgpt_registration(self)?;
11315        crate::oauth::get_owned_credentials(crate::oauth::OAuthProvider::Chatgpt, self)
11316    }
11317
11318    /// Account identifier from the selected Codewhale-owned ChatGPT grant.
11319    #[cfg(any(test, feature = "test-support"))]
11320    pub fn codex_account_id(&self) -> Option<String> {
11321        self.codex_credentials()
11322            .ok()
11323            .and_then(|credentials| credentials.account_id)
11324    }
11325}
11326
11327/// Whether a provider counts as "configured" for the default `/provider`
11328/// and `/model` manager views (#3830). Shared by both pickers so "what shows
11329/// up without browsing the full catalog" stays a single definition.
11330/// Self-hosted providers (Ollama/Sglang/Vllm) report `has_key = true`
11331/// unconditionally in `codewhale_tui::provider_readiness::has_api_key_for` since they don't require auth to
11332/// route to — that's correct for routing, but wrong for "did the user set
11333/// this up," so a self-hosted provider only qualifies via an explicit
11334/// `[providers.<name>]` entry or being active, never via `has_key` alone
11335/// (otherwise every self-hosted provider type would always show up).
11336#[must_use]
11337pub fn provider_is_configured(
11338    provider: ProviderKind,
11339    is_active: bool,
11340    has_key: bool,
11341    configured: Option<&ProviderConfig>,
11342    is_named_custom_entry: bool,
11343) -> bool {
11344    // A *named* custom provider entry (one the user actually added) always
11345    // counts. The unconfigured `Custom` placeholder row that fills the slot
11346    // when no custom provider exists yet is not itself "configured" — it's
11347    // the catalog's invitation to add one.
11348    if is_active || is_named_custom_entry {
11349        return true;
11350    }
11351    if configured.is_some_and(provider_config_is_explicit) {
11352        return true;
11353    }
11354    if matches!(
11355        provider,
11356        ProviderKind::Ollama | ProviderKind::Sglang | ProviderKind::Vllm
11357    ) {
11358        return false;
11359    }
11360    has_key
11361}
11362
11363/// True when a `[providers.<name>]` table entry has any field the user would
11364/// have had to set explicitly — base URL, model, auth, etc. Used by
11365/// [`provider_is_configured`]: merely existing in the
11366/// (always-`Some`-once-any-provider-is-configured) `ProvidersConfig` struct
11367/// isn't enough, since untouched providers still resolve to a
11368/// `ProviderConfig::default()` there.
11369fn provider_config_is_explicit(entry: &ProviderConfig) -> bool {
11370    let non_empty = |value: Option<&String>| value.is_some_and(|value| !value.trim().is_empty());
11371
11372    non_empty(entry.api_key.as_ref())
11373        || entry.vendor.is_some()
11374        || non_empty(entry.base_url.as_ref())
11375        || non_empty(entry.model.as_ref())
11376        || non_empty(entry.auth_mode.as_ref())
11377        || entry
11378            .auth
11379            .as_ref()
11380            .is_some_and(|auth| auth.validate().is_ok())
11381        || entry.context_window.is_some()
11382        || entry
11383            .model_context_windows
11384            .as_ref()
11385            .is_some_and(|table| !table.is_empty())
11386        || non_empty(entry.mode.as_ref())
11387        || entry.max_concurrency.is_some()
11388        || entry.http_headers.as_ref().is_some_and(|headers| {
11389            headers
11390                .iter()
11391                .any(|(name, value)| !name.trim().is_empty() && !value.trim().is_empty())
11392        })
11393        || non_empty(entry.path_suffix.as_ref())
11394        || non_empty(entry.reasoning_stream_style.as_ref())
11395        || entry.insecure_skip_tls_verify.is_some()
11396        || entry.allow_insecure_http.is_some()
11397        || non_empty(entry.kind.as_ref())
11398        || non_empty(entry.api_key_env.as_ref())
11399        || entry.external_credentials.is_some()
11400        || non_empty(entry.oauth_credential_generation.as_ref())
11401}
11402
11403/// Save an API key to the appropriate place for the given provider.
11404/// DeepSeek goes through [`save_api_key`]. Other providers write
11405/// `[providers.<name>] api_key = "..."` to `~/.codewhale/config.toml`.
11406/// Returns the config file path.
11407#[cfg(any(test, feature = "test-support"))]
11408pub fn save_api_key_for(provider: ProviderKind, api_key: &str) -> Result<PathBuf> {
11409    match save_api_key_for_identity(
11410        &ProviderIdentity {
11411            provider,
11412            key: provider.as_str().into(),
11413            exact_id: Some(provider.as_str().into()),
11414            migrated_legacy_ollama_cloud_route: false,
11415            legacy_root_custom_generation: None,
11416        },
11417        &Config {
11418            provider: Some(provider.as_str().to_string()),
11419            ..Config::default()
11420        },
11421        api_key,
11422    )? {
11423        SavedCredential::KeyringAndConfigFile { path, .. } | SavedCredential::ConfigFile(path) => {
11424            Ok(path)
11425        }
11426    }
11427}
11428
11429/// Save an API key for the given provider identity and return where the
11430/// credential actually landed ([`SavedCredential`]) so callers can state the
11431/// true destination — the durable secret store plus credential-free config
11432/// metadata, or (tests only) the plaintext config file (#5195).
11433pub fn save_api_key_for_identity(
11434    identity: &ProviderIdentity,
11435    route_config: &Config,
11436    api_key: &str,
11437) -> Result<SavedCredential> {
11438    route_config
11439        .verify_provider_identity(identity)
11440        .map_err(anyhow::Error::msg)?;
11441    if identity.provider == ProviderKind::Xai {
11442        return codewhale_config::with_xai_oauth_revocation_transaction(|| {
11443            save_api_key_for_identity_unlocked(identity, route_config, api_key)
11444        });
11445    }
11446    save_api_key_for_identity_unlocked(identity, route_config, api_key)
11447}
11448
11449fn save_api_key_for_identity_unlocked(
11450    identity: &ProviderIdentity,
11451    route_config: &Config,
11452    api_key: &str,
11453) -> Result<SavedCredential> {
11454    route_config
11455        .verify_provider_identity(identity)
11456        .map_err(anyhow::Error::msg)?;
11457    let provider = identity.provider;
11458    if provider == ProviderKind::OpenaiCodex {
11459        anyhow::bail!(codewhale_config::credentials::OPENAI_CODEX_API_KEY_REFUSAL);
11460    }
11461    let is_legacy_literal_custom = provider == ProviderKind::Custom
11462        && identity.key.as_str().trim() == ProviderKind::Custom.as_str()
11463        && identity.persisted_id().is_none();
11464    if matches!(provider, ProviderKind::Deepseek) {
11465        return save_api_key(api_key);
11466    }
11467    if is_legacy_literal_custom {
11468        return save_root_api_key_for_secret_slot(api_key, "custom", "custom");
11469    }
11470
11471    let normalized = codewhale_secrets::normalize_api_key(api_key);
11472    let api_key = normalized.as_str();
11473    anyhow::ensure!(!api_key.is_empty(), "Refusing to save an empty API key.");
11474
11475    let config_path =
11476        credential_config_path().context("Failed to resolve config path for provider API key.")?;
11477    ensure_parent_dir(&config_path)?;
11478
11479    let key_inside = if provider == ProviderKind::Custom {
11480        let key = identity.key.as_str().trim();
11481        anyhow::ensure!(!key.is_empty(), "custom provider id cannot be empty");
11482        key
11483    } else {
11484        provider_config_key(identity).context("provider api key table")?
11485    };
11486    // A legacy, manually-selected Kimi CLI import implicitly routed Moonshot
11487    // traffic to Kimi Code. Once the user replaces that import with the
11488    // supported API-key route, persist the endpoint before changing auth_mode
11489    // so the key is not silently sent to the ordinary Moonshot endpoint.
11490    // Respect an explicit user-owned endpoint.
11491    let pin_kimi_code_base_url = provider == ProviderKind::Moonshot
11492        && route_config
11493            .provider_config_for(identity)
11494            .is_some_and(|entry| {
11495                provider_config_uses_kimi_imported_token(entry)
11496                    && entry
11497                        .base_url
11498                        .as_deref()
11499                        .is_none_or(|base_url| base_url.trim().is_empty())
11500            });
11501
11502    if !route_config.should_skip_secret_store_for_provider(identity)
11503        && let Some(secrets) = credential_secret_store()
11504    {
11505        let secret_slot = provider_secret_store_slot(provider);
11506        // Snapshot -> write -> config-write -> rollback is a read-modify-write.
11507        // Hold this provider's credential write lock across the whole sequence
11508        // so a concurrent save or logout on the same slot cannot interleave and
11509        // leave the secret store and the config document disagreeing. This is
11510        // the `modify`-is-the-only-write-path rule ported from pi-mono; see
11511        // `codewhale_runtime::credentials::store`.
11512        return crate::credentials::store::with_provider_write_lock(secret_slot, || {
11513            let prior_secret = secrets.get(secret_slot);
11514            match prior_secret.as_ref() {
11515                Ok(prior) => match secrets.set(secret_slot, api_key) {
11516                    Ok(()) => {
11517                        let config_result = crate::config_persistence::mutate_config_document(
11518                            &config_path,
11519                            |doc| {
11520                                if pin_kimi_code_base_url {
11521                                    crate::config_persistence::set_document_value(
11522                                        doc,
11523                                        &["providers", key_inside, "base_url"],
11524                                        DEFAULT_KIMI_CODE_BASE_URL,
11525                                    )?;
11526                                }
11527                                crate::config_persistence::set_document_value(
11528                                    doc,
11529                                    &["providers", key_inside, "auth_mode"],
11530                                    "api_key",
11531                                )?;
11532                                crate::config_persistence::unset_document_value(
11533                                    doc,
11534                                    &["providers", key_inside, "external_credentials"],
11535                                )?;
11536                                if matches!(provider, ProviderKind::Xai | ProviderKind::Anthropic) {
11537                                    crate::config_persistence::unset_document_value(
11538                                        doc,
11539                                        &["providers", key_inside, "oauth_credential_generation"],
11540                                    )?;
11541                                }
11542                                crate::config_persistence::unset_document_value(
11543                                    doc,
11544                                    &["providers", key_inside, "api_key"],
11545                                )?;
11546                                Ok(())
11547                            },
11548                        )
11549                        .with_context(|| {
11550                            format!("Failed to write config to {}", config_path.display())
11551                        });
11552                        if let Err(error) = config_result {
11553                            let current = secrets.get(secret_slot).map_err(|rollback| {
11554                        anyhow::anyhow!(
11555                            "{error}; additionally could not verify secret-store rollback for {secret_slot}: {rollback}"
11556                        )
11557                    })?;
11558                            if current.as_deref() == Some(api_key) {
11559                                match prior {
11560                            Some(previous) => secrets.set(secret_slot, previous),
11561                            None => secrets.delete(secret_slot),
11562                        }
11563                        .map_err(|rollback| {
11564                            anyhow::anyhow!(
11565                                "{error}; additionally failed to restore prior secret-store state for {secret_slot}: {rollback}"
11566                            )
11567                        })?;
11568                            }
11569                            return Err(error);
11570                        }
11571                        codewhale_config::scrub_plaintext_api_keys_from_config_backup(
11572                            &config_path,
11573                        )?;
11574                        let backend = secrets.backend_name().to_string();
11575                        log_sensitive_event(
11576                            "credential.save",
11577                            json!({
11578                                "backend": backend.clone(),
11579                                "provider": identity.key,
11580                                "config_path": config_path.display().to_string(),
11581                                "plaintext_config_fallback": false,
11582                            }),
11583                        );
11584                        Ok(SavedCredential::KeyringAndConfigFile {
11585                            backend,
11586                            path: config_path,
11587                        })
11588                    }
11589                    Err(err) => Err(plaintext_credential_fallback_refused(
11590                        "write",
11591                        &config_path,
11592                        &err,
11593                    )),
11594                },
11595                Err(error) => Err(plaintext_credential_fallback_refused(
11596                    "snapshot",
11597                    &config_path,
11598                    &error,
11599                )),
11600            }
11601        });
11602    }
11603
11604    // Edit the `[providers.<name>]` table in place so unrelated sections,
11605    // comments, and formatting survive the write.
11606    crate::config_persistence::mutate_config_document(&config_path, |doc| {
11607        if pin_kimi_code_base_url {
11608            crate::config_persistence::set_document_value(
11609                doc,
11610                &["providers", key_inside, "base_url"],
11611                DEFAULT_KIMI_CODE_BASE_URL,
11612            )?;
11613        }
11614        crate::config_persistence::set_document_value(
11615            doc,
11616            &["providers", key_inside, "auth_mode"],
11617            "api_key",
11618        )?;
11619        crate::config_persistence::unset_document_value(
11620            doc,
11621            &["providers", key_inside, "external_credentials"],
11622        )?;
11623        if matches!(provider, ProviderKind::Xai | ProviderKind::Anthropic) {
11624            crate::config_persistence::unset_document_value(
11625                doc,
11626                &["providers", key_inside, "oauth_credential_generation"],
11627            )?;
11628        }
11629        crate::config_persistence::set_document_value(
11630            doc,
11631            &["providers", key_inside, "api_key"],
11632            api_key,
11633        )
11634    })
11635    .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
11636    log_sensitive_event(
11637        "credential.save",
11638        json!({
11639            "backend": "config_file",
11640            "provider": identity.key,
11641            "config_path": config_path.display().to_string(),
11642        }),
11643    );
11644    codewhale_config::scrub_plaintext_api_keys_from_config_backup(&config_path)?;
11645
11646    Ok(SavedCredential::ConfigFile(config_path))
11647}
11648
11649/// Persist a guided-setup model through the same canonical route writer used
11650/// by Runtime and the interactive model picker.
11651pub fn save_provider_model_for_identity(
11652    identity: &ProviderIdentity,
11653    route_config: &Config,
11654    model: &str,
11655) -> Result<PathBuf> {
11656    route_config
11657        .verify_provider_identity(identity)
11658        .map_err(anyhow::Error::msg)?;
11659    let model = model.trim();
11660    anyhow::ensure!(!model.is_empty(), "model cannot be empty");
11661    let config_path =
11662        try_default_config_path().context("Failed to resolve config path for provider model.")?;
11663    crate::config_persistence::persist_provider_model_key(Some(&config_path), identity, model)
11664}
11665
11666/// Persist a guided-setup endpoint choice into the provider's own
11667/// `[providers.<name>] base_url` (#4526).
11668///
11669/// Deliberately narrow: it never touches the root `base_url`, another
11670/// provider's table, or any other key, so a billing-route choice cannot
11671/// repoint an unrelated route.
11672pub fn save_provider_base_url_for_identity(
11673    identity: &ProviderIdentity,
11674    route_config: &Config,
11675    base_url: &str,
11676) -> Result<PathBuf> {
11677    route_config
11678        .verify_provider_identity(identity)
11679        .map_err(anyhow::Error::msg)?;
11680    let base_url = base_url.trim();
11681    anyhow::ensure!(!base_url.is_empty(), "base URL cannot be empty");
11682    let config_path = try_default_config_path()
11683        .context("Failed to resolve config path for provider base URL.")?;
11684    ensure_parent_dir(&config_path)?;
11685    let key_inside = if identity.provider == ProviderKind::Custom {
11686        let key = identity.key.as_str().trim();
11687        anyhow::ensure!(!key.is_empty(), "custom provider id cannot be empty");
11688        key
11689    } else {
11690        provider_config_key(identity).context("provider base URL table")?
11691    };
11692    crate::config_persistence::mutate_config_document(&config_path, |doc| {
11693        crate::config_persistence::set_document_value(
11694            doc,
11695            &["providers", key_inside, "base_url"],
11696            base_url,
11697        )
11698    })
11699    .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
11700    Ok(config_path)
11701}
11702
11703/// Persist a guided-setup context-window choice without replacing the user's
11704/// surrounding TOML comments or formatting.
11705pub fn save_provider_context_window_for_identity(
11706    identity: &ProviderIdentity,
11707    route_config: &Config,
11708    context_window: u32,
11709) -> Result<PathBuf> {
11710    route_config
11711        .verify_provider_identity(identity)
11712        .map_err(anyhow::Error::msg)?;
11713    anyhow::ensure!(context_window > 0, "context window must be greater than 0");
11714    let config_path = try_default_config_path()
11715        .context("Failed to resolve config path for provider context window.")?;
11716    ensure_parent_dir(&config_path)?;
11717    let key_inside = if identity.provider == ProviderKind::Custom {
11718        let key = identity.key.as_str().trim();
11719        anyhow::ensure!(!key.is_empty(), "custom provider id cannot be empty");
11720        key
11721    } else {
11722        provider_config_key(identity).context("provider context window table")?
11723    };
11724    crate::config_persistence::mutate_config_document(&config_path, |doc| {
11725        crate::config_persistence::set_document_value(
11726            doc,
11727            &["providers", key_inside, "context_window"],
11728            i64::from(context_window),
11729        )
11730    })
11731    .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
11732    Ok(config_path)
11733}
11734
11735/// Grant-time validation (#5772): read the exact file the user just confirmed,
11736/// through the same secure adapter the request path uses, and require it to
11737/// hold a usable credential.
11738///
11739/// This runs *after* the confirmation disclosure and *before* any consent
11740/// record is written, which is the whole ordering the consent model depends
11741/// on. Persisting first would leave a record claiming a credential exists for
11742/// a file that is missing, malformed, or expired — and every status surface
11743/// downstream would then have to trust it. Nothing here refreshes, rewrites,
11744/// or makes a network request, and no credential value escapes this function.
11745fn validate_external_credential_before_consent(
11746    consent_provider: codewhale_config::ProviderKind,
11747    source: codewhale_config::ExternalCredentialSource,
11748    path: &Path,
11749) -> Result<()> {
11750    let grant = codewhale_config::ExternalCredentialConsentToml::read_only(
11751        consent_provider,
11752        source,
11753        path.to_path_buf(),
11754    )
11755    .read_grant(consent_provider, source, path)?;
11756    match source {
11757        codewhale_config::ExternalCredentialSource::CodexCli => {
11758            crate::oauth::get_credentials(&grant).map(|_| ())
11759        }
11760        codewhale_config::ExternalCredentialSource::GrokCli => {
11761            crate::oauth::validate_grok_external_credentials(&grant)
11762        }
11763        codewhale_config::ExternalCredentialSource::DshCli => {
11764            crate::dsh_credentials::deepseek_api_key_from_grant(&grant)?
11765                .map(|_| ())
11766                .context("the DeepSeek Harness credentials file holds no DEEPSEEK_API_KEY")
11767        }
11768        // Retired: the reader is gone, so a legacy consent record validates
11769        // to nothing rather than resolving a route (PRD §4.4 PROD-002).
11770        codewhale_config::ExternalCredentialSource::AgyCli => {
11771            anyhow::bail!(codewhale_config::LEGACY_ANTIGRAVITY_TOMBSTONE_MESSAGE)
11772        }
11773        codewhale_config::ExternalCredentialSource::KimiCodeCli => anyhow::bail!(
11774            "Kimi CLI credentials are never imported; configure a Kimi API key instead"
11775        ),
11776    }
11777}
11778
11779/// Persist an explicitly confirmed read-only external credential grant and
11780/// update the live mirror only after the comment-preserving disk mutation
11781/// succeeds.
11782///
11783/// Order is load-bearing (#5772): the caller has already shown the
11784/// confirmation disclosure, this function then reads and validates the exact
11785/// consented file, and only a usable credential is allowed to produce a
11786/// persisted consent record.
11787pub fn persist_external_credential_consent_for_at(
11788    config_path: Option<&Path>,
11789    live_config: &mut Config,
11790    identity: &ProviderIdentity,
11791    consent_provider: codewhale_config::ProviderKind,
11792    source: codewhale_config::ExternalCredentialSource,
11793    path: &Path,
11794) -> Result<PathBuf> {
11795    live_config
11796        .verify_provider_identity(identity)
11797        .map_err(anyhow::Error::msg)?;
11798    let provider = identity.provider;
11799    let expected = match provider {
11800        ProviderKind::OpenaiCodex => (
11801            codewhale_config::ProviderKind::OpenaiCodex,
11802            codewhale_config::ExternalCredentialSource::CodexCli,
11803        ),
11804        ProviderKind::Xai => (
11805            codewhale_config::ProviderKind::Xai,
11806            codewhale_config::ExternalCredentialSource::GrokCli,
11807        ),
11808        _ => anyhow::bail!(
11809            "{} has no supported external credential owner",
11810            provider.as_str()
11811        ),
11812    };
11813    anyhow::ensure!(
11814        (consent_provider, source) == expected,
11815        "external credential owner does not match provider {}",
11816        provider.as_str()
11817    );
11818    let path = codewhale_config::resolve_external_credential_path(path)?;
11819    let path_value = path.to_str().context(
11820        "external credential path cannot be persisted losslessly because it is not valid UTF-8",
11821    )?;
11822    validate_external_credential_before_consent(consent_provider, source, &path).with_context(
11823        || {
11824            format!(
11825                "no usable {} credential was found, so read-only consent was not saved",
11826                source.owner_label()
11827            )
11828        },
11829    )?;
11830    let config_path = match config_path {
11831        Some(path) => path.to_path_buf(),
11832        None => credential_config_path()
11833            .context("Failed to resolve config path for external credential consent.")?,
11834    };
11835    ensure_parent_dir(&config_path)?;
11836    let key_inside = provider_config_key(identity).context("external credential provider key")?;
11837    crate::config_persistence::mutate_config_document(&config_path, |doc| {
11838        crate::config_persistence::set_document_value(
11839            doc,
11840            &["providers", key_inside, "auth_mode"],
11841            "oauth",
11842        )?;
11843        let prefix = &["providers", key_inside, "external_credentials"];
11844        crate::config_persistence::set_document_value(
11845            doc,
11846            &[prefix[0], prefix[1], prefix[2], "access"],
11847            "read_only",
11848        )?;
11849        crate::config_persistence::set_document_value(
11850            doc,
11851            &[prefix[0], prefix[1], prefix[2], "provider"],
11852            consent_provider.as_str(),
11853        )?;
11854        crate::config_persistence::set_document_value(
11855            doc,
11856            &[prefix[0], prefix[1], prefix[2], "source"],
11857            source.as_str(),
11858        )?;
11859        crate::config_persistence::set_document_value(
11860            doc,
11861            &[prefix[0], prefix[1], prefix[2], "path"],
11862            path_value,
11863        )?;
11864        crate::config_persistence::set_document_value(
11865            doc,
11866            &[prefix[0], prefix[1], prefix[2], "consent_version"],
11867            i64::from(codewhale_config::EXTERNAL_CREDENTIAL_CONSENT_VERSION),
11868        )
11869    })
11870    .with_context(|| {
11871        format!(
11872            "Failed to write config to {}",
11873            codewhale_config::quote_os_path(&config_path)
11874        )
11875    })?;
11876    live_config
11877        .providers
11878        .get_or_insert_with(ProvidersConfig::default);
11879    let entry = live_config.provider_config_for_mut(identity)?;
11880    entry.auth_mode = Some("oauth".to_string());
11881    entry.external_credentials = Some(codewhale_config::ExternalCredentialConsentToml::read_only(
11882        consent_provider,
11883        source,
11884        path,
11885    ));
11886    Ok(config_path)
11887}
11888
11889/// Revoke one provider's external-file access without inspecting that file.
11890pub fn revoke_external_credential_consent_for_at(
11891    config_path: Option<&Path>,
11892    live_config: &mut Config,
11893    identity: &ProviderIdentity,
11894) -> Result<PathBuf> {
11895    live_config
11896        .verify_provider_identity(identity)
11897        .map_err(anyhow::Error::msg)?;
11898    let provider = identity.provider;
11899    anyhow::ensure!(
11900        matches!(provider, ProviderKind::OpenaiCodex | ProviderKind::Xai),
11901        "{} has no supported external credential owner",
11902        provider.as_str()
11903    );
11904    let config_path = match config_path {
11905        Some(path) => path.to_path_buf(),
11906        None => credential_config_path()
11907            .context("Failed to resolve config path for external credential consent.")?,
11908    };
11909    ensure_parent_dir(&config_path)?;
11910    let key_inside = provider_config_key(identity).context("external credential provider key")?;
11911    crate::config_persistence::mutate_config_document(&config_path, |doc| {
11912        crate::config_persistence::unset_document_value(
11913            doc,
11914            &["providers", key_inside, "external_credentials"],
11915        )?;
11916        Ok(())
11917    })
11918    .with_context(|| {
11919        format!(
11920            "Failed to write config to {}",
11921            codewhale_config::quote_os_path(&config_path)
11922        )
11923    })?;
11924    live_config
11925        .provider_config_for_mut(identity)?
11926        .external_credentials = None;
11927    Ok(config_path)
11928}
11929
11930pub fn provider_config_key(identity: &ProviderIdentity) -> Result<&str> {
11931    if identity.provider == ProviderKind::Deepseek
11932        && identity.key.as_str() == ProviderKind::Deepseek.as_str()
11933    {
11934        anyhow::bail!("DeepSeek stores auth at the root config level");
11935    }
11936    identity.config_table_key()
11937}
11938
11939fn provider_config_table_name(identity: &ProviderIdentity) -> Result<String> {
11940    Ok(format!("providers.{}", provider_config_key(identity)?))
11941}
11942
11943/// Name of the ambient provider variable that currently holds a non-empty key
11944/// for `provider`. Presence only: the value is dropped here.
11945pub fn provider_env_api_key_var(provider: ProviderKind) -> Option<&'static str> {
11946    provider_env_api_key_named(provider).map(|(name, _)| name)
11947}
11948
11949/// The provider's ambient env key and the variable that supplied it,
11950/// normalized with [`codewhale_secrets::normalize_api_key`] (#6528).
11951fn provider_env_api_key_named(provider: ProviderKind) -> Option<(&'static str, String)> {
11952    let read = || {
11953        let names = provider.provider().env_vars();
11954        names.iter().find_map(|name| {
11955            std::env::var(name)
11956                .ok()
11957                .map(|value| codewhale_secrets::normalize_api_key(&value))
11958                .filter(|value| !value.is_empty())
11959                .map(|value| (*name, value))
11960        })
11961    };
11962    #[cfg(any(test, feature = "test-support"))]
11963    {
11964        codewhale_util::test_env_lock::with_test_env_lock(read)
11965    }
11966    #[cfg(not(any(test, feature = "test-support")))]
11967    {
11968        read()
11969    }
11970}
11971
11972/// Canonical durable-credential slot shared with the CLI dispatcher.
11973pub fn provider_secret_store_slot(provider: ProviderKind) -> &'static str {
11974    provider.secret_store_slot()
11975}
11976
11977/// Whether the secret-store save marker (`auth_mode = "api_key"` with no
11978/// config literal, written by the save path) exists for `provider` or for any
11979/// provider sharing its durable credential slot.
11980///
11981/// One Model Studio account authenticates all four plan/dialect variants, so
11982/// saving a key on `modelstudio-token-plan` marks only that variant's config
11983/// table; the sibling variants must still treat the family slot as saved.
11984fn secret_slot_save_marker_on_shared_slot(config: &Config, identity: &ProviderIdentity) -> bool {
11985    let slot = provider_secret_store_slot(identity.provider);
11986    codewhale_config::descriptors::provider_compatibility()
11987        .iter()
11988        .filter(|row| provider_secret_store_slot(row.kind) == slot)
11989        .filter_map(|row| {
11990            config
11991                .resolve_persisted_provider_identity(Some(row.id), Some(row.id))
11992                .ok()
11993        })
11994        .any(|candidate| {
11995            config
11996                .provider_config_for(&candidate)
11997                .is_some_and(|entry| auth_mode_requires_api_key(entry.auth_mode.as_deref()))
11998        })
11999}
12000
12001/// Read only the durable secret-store layer (no environment fallback).
12002///
12003/// This keeps `config -> secret store -> env` precedence explicit in the TUI
12004/// and lets status surfaces distinguish a saved key from an ambient export.
12005pub fn provider_secret_store_api_key(
12006    config: &Config,
12007    identity: &ProviderIdentity,
12008) -> Option<String> {
12009    provider_secret_store_api_key_with_mode(config, identity, false)
12010}
12011
12012fn provider_secret_store_api_key_with_mode(
12013    config: &Config,
12014    identity: &ProviderIdentity,
12015    read_only: bool,
12016) -> Option<String> {
12017    let provider = identity.provider;
12018    // Keep the named-custom exclusion at the credential boundary itself.
12019    // Callers also use this policy to avoid unnecessary keyring probes, but a
12020    // future caller must not be able to read the legacy `custom` slot for an
12021    // arbitrary `[providers.<name>]` endpoint by omitting that outer guard.
12022    if config.should_skip_secret_store_for_provider(identity) {
12023        return None;
12024    }
12025
12026    // Unit tests must never inspect the developer's real credential store.
12027    // Secret-store regressions opt in with an isolated CODEWHALE_HOME and an
12028    // explicit backend, matching the secrets crate's own test discipline.
12029    #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
12030    if !crate::test_support::state_from_environment()
12031        && (!codewhale_paths::codewhale_home_is_explicit()
12032            || std::env::var_os("CODEWHALE_SECRET_BACKEND").is_none())
12033    {
12034        return None;
12035    }
12036
12037    let secrets = if read_only {
12038        codewhale_secrets::Secrets::auto_detect_read_only()
12039    } else {
12040        codewhale_secrets::Secrets::auto_detect()
12041    };
12042    // Read through the credential-store trait so every read of a durable slot
12043    // goes through one adapter (`codewhale_runtime::credentials::store`), and the value is
12044    // carried as a type-tagged `Credential` rather than a bare String that can
12045    // drift into a log line.
12046    let store =
12047        crate::credentials::store::SecretStoreCredentials::new(secrets, known_secret_store_slots());
12048    let primary = store
12049        .read(provider_secret_store_slot(provider))
12050        .ok()
12051        .flatten()
12052        .map(|credential| credential.expose_secret().to_string());
12053    if primary.is_some() {
12054        return primary;
12055    }
12056
12057    // The old local identity owned the hosted slot only when the live config
12058    // selected the exact Ollama Cloud route. Never apply this fallback to a
12059    // neighboring/custom endpoint or to an explicit new `ollama-cloud`
12060    // selection, and never write/copy/delete either slot while resolving.
12061    (provider == ProviderKind::OllamaCloud && identity.migrated_legacy_ollama_cloud_route)
12062        .then(|| {
12063            store
12064                .read(ProviderKind::Ollama.as_str())
12065                .ok()
12066                .flatten()
12067                .map(|credential| credential.expose_secret().to_string())
12068        })
12069        .flatten()
12070}
12071
12072/// Every durable credential slot CodeWhale knows how to write.
12073///
12074/// The backing keyring exposes no key enumeration, so
12075/// [`codewhale_runtime::credentials::store::SecretStoreCredentials::list`] is given the
12076/// slot names to probe. Deduplicated because shared-account families collapse
12077/// several providers onto one slot.
12078fn known_secret_store_slots() -> Vec<String> {
12079    let mut slots: Vec<String> = codewhale_config::descriptors::provider_compatibility()
12080        .iter()
12081        .map(|row| provider_secret_store_slot(row.kind).to_string())
12082        .collect();
12083    slots.sort();
12084    slots.dedup();
12085    slots
12086}
12087
12088/// The shadowing warning for a config-file `api_key` that wins over a live
12089/// secret-store credential, if both exist (#5194).
12090///
12091/// The config file intentionally outranks the secret store in the read
12092/// chain, but a shadowed slot is invisible: the user rotates the key with
12093/// `codewhale auth set` and nothing changes, because the stale plaintext
12094/// copy still wins. Mirror the fleet-roster shadowing rule (#5098):
12095/// precedence is normal, but it must be VISIBLE. The message names both
12096/// sources, which one won, and the command that resolves the shadow.
12097/// Split from [`warn_on_config_api_key_shadowing`] so the decision is
12098/// testable without capturing tracing output.
12099fn config_api_key_shadow_warning(
12100    config: &Config,
12101    identity: &ProviderIdentity,
12102    config_source: &str,
12103) -> Option<String> {
12104    let provider = identity.provider;
12105    if config.should_skip_secret_store_for_provider(identity) {
12106        return None;
12107    }
12108    provider_secret_store_api_key_with_mode(config, identity, true).map(|_| {
12109        let slot = provider_secret_store_slot(provider);
12110        let id = provider.as_str();
12111        format!(
12112            "both {config_source} in the config file and secret-store slot \"{slot}\" \
12113             hold a credential for provider {id}; the config-file key won. Run \
12114             `codewhale auth set --provider {id}` to move the key into the secret store \
12115             and strip the plaintext copy, or remove the config-file api_key."
12116        )
12117    })
12118}
12119
12120/// Emit the #5194 shadowing warning at most once per provider slot per
12121/// process: credential resolution runs on every request, and a repeating
12122/// warning is noise, not signal.
12123fn warn_on_config_api_key_shadowing(
12124    config: &Config,
12125    identity: &ProviderIdentity,
12126    config_source: &str,
12127) {
12128    let provider = identity.provider;
12129    let Some(message) = config_api_key_shadow_warning(config, identity, config_source) else {
12130        return;
12131    };
12132    static WARNED_SLOTS: std::sync::OnceLock<
12133        std::sync::Mutex<std::collections::HashSet<&'static str>>,
12134    > = std::sync::OnceLock::new();
12135    let mut warned = WARNED_SLOTS
12136        .get_or_init(|| std::sync::Mutex::new(std::collections::HashSet::new()))
12137        .lock()
12138        .unwrap_or_else(|poisoned| poisoned.into_inner());
12139    if !warned.insert(provider_secret_store_slot(provider)) {
12140        return;
12141    }
12142    drop(warned);
12143    tracing::warn!("{message}");
12144}
12145
12146/// The model this launch was explicitly asked for, if any.
12147///
12148/// The `codewhale` dispatcher forwards `--model` to this binary as
12149/// `CODEWHALE_MODEL` (with the legacy `DEEPSEEK_MODEL` alias), so an explicit
12150/// flag and an explicit shell export are the same signal here: *the user named
12151/// a model for this run*. That has to outrank the remembered per-provider
12152/// selection in `settings.toml`, which is a convenience memory of the last
12153/// `/model` pick — never a reason to run something the user did not ask for
12154/// (v0.9.1 kimi-k3 dogfood report).
12155pub fn explicit_launch_model_override() -> Option<String> {
12156    codewhale_env_var("CODEWHALE_MODEL", "DEEPSEEK_MODEL")
12157        .ok()
12158        .map(|value| value.trim().to_string())
12159        .filter(|value| !value.is_empty())
12160}
12161
12162/// The provider this launch was explicitly asked for, if any.
12163///
12164/// An environment/CLI override is a one-run instruction and must outrank the
12165/// user's saved startup default. A provider merely named in config.toml is a
12166/// seed instead: the user can deliberately replace that seed from `/model`.
12167pub fn explicit_launch_provider_override() -> Option<String> {
12168    codewhale_env_var("CODEWHALE_PROVIDER", "DEEPSEEK_PROVIDER")
12169        .ok()
12170        .map(|value| value.trim().to_string())
12171        .filter(|value| !value.is_empty())
12172}
12173
12174pub fn explicit_cli_api_key_override() -> Option<String> {
12175    let read = || {
12176        (cli_api_key_source().as_deref() == Some("cli"))
12177            .then(|| {
12178                std::env::var(codewhale_config::CLI_API_KEY_ENV)
12179                    .ok()
12180                    .filter(|value| !value.trim().is_empty())
12181            })
12182            .flatten()
12183    };
12184    #[cfg(any(test, feature = "test-support"))]
12185    {
12186        codewhale_util::test_env_lock::with_test_env_lock(read)
12187    }
12188    #[cfg(not(any(test, feature = "test-support")))]
12189    {
12190        read()
12191    }
12192}
12193
12194pub fn cli_api_key_source() -> Option<String> {
12195    codewhale_env_var(
12196        codewhale_config::CLI_API_KEY_SOURCE_ENV,
12197        codewhale_config::LEGACY_CLI_API_KEY_SOURCE_ENV,
12198    )
12199    .ok()
12200}
12201
12202fn missing_provider_api_key_message(identity: &ProviderIdentity) -> Result<String> {
12203    let provider = identity.provider;
12204    let credential_hint = provider
12205        .provider()
12206        .credential_help()
12207        .credential_url
12208        .map(|url| format!(" Get a key: {url}."))
12209        .unwrap_or_default();
12210    let label = identity
12211        .compatibility()
12212        .map_or_else(|| provider.provider().display_name(), |row| row.label);
12213    Ok(format!(
12214        "{} API key not found.{} Run 'codewhale auth set --provider {}', set {}, or add [{}] api_key in ~/.codewhale/config.toml.",
12215        label,
12216        credential_hint,
12217        identity.key,
12218        provider.provider().env_vars().join(" / "),
12219        provider_config_table_name(identity)?
12220    ))
12221}
12222
12223/// Clear every saved API key from config-file storage AND the durable
12224/// secret store.
12225///
12226/// The full-wipe logout path (`codewhale-tui --logout`, `auth logout`)
12227/// calls this to remove credentials so the next request can't
12228/// silently use a stale config key (#343). The function removes the legacy
12229/// root `api_key` entry *and* every `api_key` entry nested in a
12230/// `[providers.<name>]` table, leaving keys like `api_key_env`, comments,
12231/// and formatting untouched, then deletes every provider's secret-store
12232/// slot — symmetric with CLI logout (#5159) — so a stored credential cannot
12233/// survive logout and reappear through the read chain (#5196). The TUI
12234/// `/logout` command stays single-provider and goes through
12235/// [`clear_active_provider_api_key`] instead.
12236///
12237/// Environment variables (`DEEPSEEK_API_KEY`, etc.) are intentionally
12238/// **not** unset — they are managed by the user's shell and outside the
12239/// CLI's purview. `Config::active_route_api_key`'s explicit-override path
12240/// (Path 0) ensures a freshly-entered key still wins over a stale env
12241/// var that lingers from a previous session.
12242pub fn clear_api_key() -> Result<()> {
12243    codewhale_config::with_xai_oauth_revocation_transaction(clear_api_key_unlocked)
12244}
12245
12246fn clear_api_key_unlocked() -> Result<()> {
12247    // Same read-modify-write as the saves: hold every durable slot's write
12248    // lock across the config-document mutation and the store deletes so a
12249    // concurrent save cannot interleave and leave the two disagreeing.
12250    crate::credentials::store::with_provider_write_locks(
12251        known_secret_store_slots(),
12252        clear_api_key_under_slot_locks,
12253    )
12254}
12255
12256fn clear_api_key_under_slot_locks() -> Result<()> {
12257    // Strip api_key entries from config.toml, including provider-scoped
12258    // nested entries. Clearing a config file must not trigger platform
12259    // credential prompts. Clears target the same user-global document that
12260    // credential saves write, so logout removes what login stored (#5045).
12261    let config_path = credential_config_path()
12262        .context("Failed to resolve config path while clearing API keys.")?;
12263
12264    if config_path.exists() {
12265        crate::config_persistence::mutate_config_document(&config_path, |doc| {
12266            crate::config_persistence::remove_document_key_recursive(doc.as_table_mut(), "api_key");
12267            crate::config_persistence::unset_document_value(
12268                doc,
12269                &["providers", "xai", "oauth_credential_generation"],
12270            )?;
12271            crate::config_persistence::unset_document_value(
12272                doc,
12273                &["providers", "xai", "auth_mode"],
12274            )?;
12275            crate::config_persistence::unset_document_value(
12276                doc,
12277                &["providers", "xai", "external_credentials"],
12278            )?;
12279            Ok(())
12280        })
12281        .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
12282        log_sensitive_event(
12283            "credential.clear",
12284            json!({
12285                "backend": "config_file",
12286                "config_path": config_path.display().to_string(),
12287                "scope": "root_and_provider_keys",
12288            }),
12289        );
12290    }
12291
12292    // The config scrub alone leaves the durable secret-store credential
12293    // alive, and the read chain prefers the secret store over the file, so a
12294    // "cleared" key silently came back on the next launch (#5196). Delete
12295    // every provider slot too, symmetric with CLI logout (#5159). This runs
12296    // even when the config file is absent: the slot survives independently
12297    // of the file.
12298    if let Some(secrets) = credential_secret_store() {
12299        let failures = clear_all_provider_api_keys_from_secret_store(secrets);
12300        if !failures.is_empty() {
12301            anyhow::bail!(
12302                "failed to delete stored credentials for: {}",
12303                failures.join(", ")
12304            );
12305        }
12306    }
12307
12308    Ok(())
12309}
12310
12311/// Delete the credential slot of every provider that has one stored.
12312///
12313/// Mirrors the CLI logout helper (#5159): each slot is probed first so
12314/// backends that error on deleting a missing item stay quiet, slots shared
12315/// by several providers (e.g. the historical `siliconflow` slot) are deleted
12316/// once, and every deletion failure is returned as a human-readable entry so
12317/// the caller can fail loudly instead of claiming a clean logout while
12318/// credentials linger in the store (#5196).
12319fn clear_all_provider_api_keys_from_secret_store(
12320    secrets: codewhale_secrets::Secrets,
12321) -> Vec<String> {
12322    let mut failures = Vec::new();
12323    let store = crate::credentials::store::SecretStoreCredentials::new(
12324        secrets.clone(),
12325        known_secret_store_slots(),
12326    );
12327    // `list` enumerates the slots that actually hold something, without
12328    // exposing any value — the deduplication that used to live here is now the
12329    // slot table's job.
12330    let stored: Vec<crate::credentials::CredentialInfo> = match store.list() {
12331        Ok(stored) => stored,
12332        Err(error) => {
12333            failures.push(format!("secret store enumeration: {error}"));
12334            return failures;
12335        }
12336    };
12337    for entry in stored {
12338        // The caller already holds this slot's write lock for the whole
12339        // logout. Delete through the backend rather than `store.delete`,
12340        // which would re-acquire the same non-reentrant mutex and deadlock.
12341        if let Err(error) = secrets.delete(&entry.provider_id) {
12342            failures.push(format!("{}: {error}", entry.provider_id));
12343        }
12344    }
12345    failures
12346}
12347
12348/// Clear only the active provider's API key from the config file and delete
12349/// that provider's durable secret-store slot (#5196).
12350/// Unlike `clear_api_key()` which strips ALL api_key entries, this
12351/// removes only the key for the specified provider section (plus a leftover
12352/// legacy top-level `api_key` for DeepSeek or the literal custom route).
12353pub fn clear_active_provider_api_key(provider: &str) -> Result<()> {
12354    if provider == ProviderKind::Xai.as_str() {
12355        return codewhale_config::with_xai_oauth_revocation_transaction(|| {
12356            clear_active_provider_api_key_unlocked(provider)
12357        });
12358    }
12359    clear_active_provider_api_key_unlocked(provider)
12360}
12361
12362fn clear_active_provider_api_key_unlocked(provider: &str) -> Result<()> {
12363    let slot = compatibility_for_id(provider).map(|row| provider_secret_store_slot(row.kind));
12364    match slot {
12365        Some(slot) => crate::credentials::store::with_provider_write_lock(slot, || {
12366            clear_active_provider_api_key_under_lock(provider)
12367        }),
12368        None => clear_active_provider_api_key_under_lock(provider),
12369    }
12370}
12371
12372fn clear_active_provider_api_key_under_lock(provider: &str) -> Result<()> {
12373    let config_path = credential_config_path()
12374        .context("Failed to resolve config path while clearing API keys.")?;
12375
12376    if config_path.exists() {
12377        crate::config_persistence::mutate_config_document_with_migration(
12378            &config_path,
12379            |doc, moved| {
12380                // The write itself moved any older top-level `api_key` into its
12381                // provider table (#6394); clear a conflicting leftover too.
12382                let deepseek_family = provider == ProviderKind::Deepseek.as_str()
12383                    || provider == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id;
12384                if deepseek_family || provider == ProviderKind::Custom.as_str() {
12385                    crate::config_persistence::unset_document_value(doc, &["api_key"])?;
12386                }
12387                let table = compatibility_for_id(provider).map_or(provider, |row| row.config_key);
12388                let has_own_key = |doc: &toml_edit::DocumentMut| {
12389                    [table, provider].iter().any(|key| {
12390                        doc.get("providers")
12391                            .and_then(|providers| providers.get(key))
12392                            .and_then(|entry| entry.get("api_key"))
12393                            .and_then(toml_edit::Item::as_str)
12394                            .is_some_and(|value| !value.trim().is_empty())
12395                    })
12396                };
12397                // DeepSeek-CN reads `[providers.deepseek] api_key` only when it has
12398                // no key of its own, and older releases kept both behind one
12399                // top-level key. Signing CN out clears the DeepSeek key only when
12400                // it is that shared key: CN was reading it, or this write just
12401                // moved the top-level key there. A DeepSeek key the user saved
12402                // for DeepSeek itself stays.
12403                let clears_shared_deepseek_key = provider
12404                    == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id
12405                    && (!has_own_key(doc) || moved.moved_root_api_key_to("deepseek"));
12406                crate::config_persistence::unset_document_value(
12407                    doc,
12408                    &["providers", table, "api_key"],
12409                )?;
12410                if table != provider {
12411                    // Older writers used the provider id as the table key.
12412                    crate::config_persistence::unset_document_value(
12413                        doc,
12414                        &["providers", provider, "api_key"],
12415                    )?;
12416                }
12417                if clears_shared_deepseek_key {
12418                    crate::config_persistence::unset_document_value(
12419                        doc,
12420                        &["providers", "deepseek", "api_key"],
12421                    )?;
12422                }
12423                if provider == ProviderKind::Xai.as_str() {
12424                    crate::config_persistence::unset_document_value(
12425                        doc,
12426                        &["providers", "xai", "oauth_credential_generation"],
12427                    )?;
12428                    crate::config_persistence::unset_document_value(
12429                        doc,
12430                        &["providers", "xai", "auth_mode"],
12431                    )?;
12432                    crate::config_persistence::unset_document_value(
12433                        doc,
12434                        &["providers", "xai", "external_credentials"],
12435                    )?;
12436                }
12437                Ok(())
12438            },
12439        )
12440        .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
12441        log_sensitive_event(
12442            "credential.clear",
12443            json!({
12444                "backend": "config_file",
12445                "config_path": config_path.display().to_string(),
12446                "scope": provider,
12447            }),
12448        );
12449    }
12450
12451    // The durable secret-store slot survives a config-file scrub and the
12452    // read chain prefers it, so the cleared key would silently come back
12453    // (#5196). Delete the provider's slot too — even when the config file
12454    // itself is absent. Exact named custom providers have no secret-store
12455    // slot, so an unmatched provider string skips this step.
12456    if let Some(secrets) = credential_secret_store()
12457        && let Some(slot) = ProviderKind::all()
12458            .iter()
12459            .find(|candidate| candidate.as_str() == provider)
12460            .map(|candidate| provider_secret_store_slot(*candidate))
12461    {
12462        let has_value = secrets
12463            .get(slot)
12464            .ok()
12465            .flatten()
12466            .is_some_and(|value| !value.trim().is_empty());
12467        if has_value {
12468            secrets
12469                .delete(slot)
12470                .with_context(|| format!("failed to delete stored credential for {slot}"))?;
12471        }
12472    }
12473
12474    Ok(())
12475}
12476
12477#[cfg(test)]
12478mod tests;
12479
12480#[cfg(test)]
12481mod model_resolution_golden;
12482
12483/// #5045 regression coverage: credential writes must never land in a
12484/// workspace-scoped `.codewhale/config.toml`.
12485#[cfg(test)]
12486mod credential_scope_tests {
12487    use super::*;
12488    use crate::test_support::{EnvVarGuard, lock_test_env};
12489
12490    /// With the ambient config path pointing at a workspace-local
12491    /// `.codewhale/config.toml` (a checkout the user works in), saving an
12492    /// API key must write the user-global config under the isolated
12493    /// `CODEWHALE_HOME`, never the project file. The `.git` marker stands in
12494    /// for cwd-inside-the-workspace: chdir is process-global and unsafe in a
12495    /// parallel test binary, and production classifies on either signal.
12496    #[test]
12497    fn api_key_save_rescopes_workspace_config_to_user_global() -> Result<()> {
12498        let _lock = lock_test_env();
12499        let temp = tempfile::tempdir()?;
12500        let workspace = temp.path().join("repo");
12501        fs::create_dir_all(workspace.join(".git"))?;
12502        let project_dir = workspace.join(".codewhale");
12503        fs::create_dir_all(&project_dir)?;
12504        let project_config = project_dir.join("config.toml");
12505        fs::write(&project_config, "approval_policy = \"never\"\n")?;
12506
12507        let user_home = temp.path().join("user-global-home");
12508        let _home = EnvVarGuard::set("CODEWHALE_HOME", user_home.as_os_str());
12509        let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", project_config.as_os_str());
12510        let _legacy_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
12511        // No explicit secret backend: under cfg(test) the save takes the
12512        // plaintext config-file path, which is exactly the surface this
12513        // regression guards.
12514        let _backend = EnvVarGuard::remove("CODEWHALE_SECRET_BACKEND");
12515        let _legacy_backend = EnvVarGuard::remove("DEEPSEEK_SECRET_BACKEND");
12516
12517        let saved = save_api_key("workspace-rescope-test-key")?;
12518
12519        let global_config = user_home.join("config.toml");
12520        // Compare canonicalized paths: the resolved config path runs through
12521        // `normalize_config_file_path`, which canonicalizes the parent, so on
12522        // macOS the lexical `/var/folders/…` tempdir and its canonical
12523        // `/private/var/folders/…` form are the same file. A lexical compare
12524        // both false-fails and false-passes on that symlink.
12525        let saved_path = match saved {
12526            SavedCredential::ConfigFile(path) => path,
12527            other => panic!("expected a config-file save, got {}", other.describe()),
12528        };
12529        assert_eq!(
12530            canonicalize_or_keep(&saved_path),
12531            canonicalize_or_keep(&global_config),
12532            "credential save must surface the user-global destination"
12533        );
12534        let global = fs::read_to_string(&global_config)?;
12535        assert!(
12536            global.contains("workspace-rescope-test-key"),
12537            "user-global config must hold the saved key: {global}"
12538        );
12539        let project = fs::read_to_string(&project_config)?;
12540        assert!(
12541            !project.contains("workspace-rescope-test-key"),
12542            "credential leaked into workspace config: {project}"
12543        );
12544        assert!(
12545            !project.contains("api_key"),
12546            "workspace config must stay credential-free: {project}"
12547        );
12548        Ok(())
12549    }
12550
12551    /// Provider-table saves go through the same resolver: an OpenRouter key
12552    /// saved with a workspace-scoped ambient config path must land in the
12553    /// user-global document.
12554    #[test]
12555    fn provider_api_key_save_rescopes_workspace_config_to_user_global() -> Result<()> {
12556        let _lock = lock_test_env();
12557        let temp = tempfile::tempdir()?;
12558        let workspace = temp.path().join("repo");
12559        fs::create_dir_all(workspace.join(".git"))?;
12560        let project_dir = workspace.join(".codewhale");
12561        fs::create_dir_all(&project_dir)?;
12562        let project_config = project_dir.join("config.toml");
12563        fs::write(&project_config, "approval_policy = \"never\"\n")?;
12564
12565        let user_home = temp.path().join("user-global-home");
12566        let _home = EnvVarGuard::set("CODEWHALE_HOME", user_home.as_os_str());
12567        let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", project_config.as_os_str());
12568        let _legacy_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
12569        let _backend = EnvVarGuard::remove("CODEWHALE_SECRET_BACKEND");
12570        let _legacy_backend = EnvVarGuard::remove("DEEPSEEK_SECRET_BACKEND");
12571
12572        let path = save_api_key_for(ProviderKind::Openrouter, "workspace-rescope-openrouter-key")?;
12573
12574        // Canonicalized comparison: see the root-key test above.
12575        assert_eq!(
12576            canonicalize_or_keep(&path),
12577            canonicalize_or_keep(&user_home.join("config.toml")),
12578            "provider save must report the user-global destination"
12579        );
12580        let global = fs::read_to_string(&path)?;
12581        assert!(global.contains("workspace-rescope-openrouter-key"));
12582        let project = fs::read_to_string(&project_config)?;
12583        assert!(
12584            !project.contains("workspace-rescope-openrouter-key"),
12585            "credential leaked into workspace config: {project}"
12586        );
12587        Ok(())
12588    }
12589
12590    #[test]
12591    fn managed_auto_review_disabled_replaces_user_table_and_refuses_auto_policy() -> Result<()> {
12592        let _lock = lock_test_env();
12593        let temp = tempfile::tempdir()?;
12594        let home = temp.path().join("home");
12595        fs::create_dir_all(&home)?;
12596        let _home = EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str());
12597        let user_config = home.join("config.toml");
12598        let managed_config = temp.path().join("managed.toml");
12599        let _managed =
12600            EnvVarGuard::set("CODEWHALE_MANAGED_CONFIG_PATH", managed_config.as_os_str());
12601        let _policy = EnvVarGuard::remove("CODEWHALE_APPROVAL_POLICY");
12602        let _legacy_policy = EnvVarGuard::remove("DEEPSEEK_APPROVAL_POLICY");
12603
12604        fs::write(
12605            &user_config,
12606            r#"
12607[[auto_review.allow]]
12608tool = "read"
12609reason = "user allow"
12610"#,
12611        )?;
12612        fs::write(
12613            &managed_config,
12614            r#"
12615[auto_review]
12616disabled = true
12617"#,
12618        )?;
12619
12620        let loaded = Config::load(Some(user_config.clone()), None)?;
12621        assert!(loaded.auto_review_disabled());
12622        assert!(
12623            loaded
12624                .auto_review
12625                .as_ref()
12626                .is_some_and(|cfg| cfg.allow.is_empty() && cfg.block.is_empty()),
12627            "managed [auto_review] table must replace the user table"
12628        );
12629
12630        fs::write(&user_config, "approval_policy = \"auto\"\n")?;
12631        let file_err = Config::load(Some(user_config.clone()), None)
12632            .expect_err("approval_policy = auto must fail when auto_review.disabled = true");
12633        assert!(
12634            file_err.to_string().contains("auto_review.disabled = true"),
12635            "unexpected error for config approval_policy: {file_err:#}"
12636        );
12637
12638        fs::write(&user_config, "")?;
12639        let _env_policy = EnvVarGuard::set("CODEWHALE_APPROVAL_POLICY", "auto");
12640        let env_err = Config::load(Some(user_config), None).expect_err(
12641            "CODEWHALE_APPROVAL_POLICY=auto must fail when auto_review.disabled = true",
12642        );
12643        assert!(
12644            env_err.to_string().contains("auto_review.disabled = true"),
12645            "unexpected error for CODEWHALE_APPROVAL_POLICY: {env_err:#}"
12646        );
12647        Ok(())
12648    }
12649
12650    #[test]
12651    fn auto_review_reviewer_model_parses_validates_merges_and_ignores_subagents() -> Result<()> {
12652        let _lock = lock_test_env();
12653        let temp = tempfile::tempdir()?;
12654        let home = temp.path().join("home");
12655        fs::create_dir_all(&home)?;
12656        let _home = EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str());
12657        let _managed = EnvVarGuard::remove("CODEWHALE_MANAGED_CONFIG_PATH");
12658        let user_config = home.join("config.toml");
12659
12660        fs::write(
12661            &user_config,
12662            r#"
12663[auto_review]
12664reviewer_model = "claude-sonnet-5-5"
12665
12666[subagents]
12667reviewer_model = "subagent-only-model"
12668"#,
12669        )?;
12670        let loaded = Config::load(Some(user_config.clone()), None)?;
12671        assert_eq!(
12672            loaded.auto_review_reviewer_model(),
12673            Some("claude-sonnet-5-5")
12674        );
12675
12676        fs::write(
12677            &user_config,
12678            r#"
12679[subagents]
12680reviewer_model = "subagent-only-model"
12681"#,
12682        )?;
12683        let without_ar_model = Config::load(Some(user_config.clone()), None)?;
12684        assert_eq!(without_ar_model.auto_review_reviewer_model(), None);
12685
12686        fs::write(
12687            &user_config,
12688            r#"
12689[auto_review]
12690reviewer_model = "  "
12691"#,
12692        )?;
12693        let empty_err = Config::load(Some(user_config.clone()), None)
12694            .expect_err("blank auto_review.reviewer_model must fail validation");
12695        assert!(
12696            empty_err.to_string().contains("reviewer_model"),
12697            "{empty_err:#}"
12698        );
12699
12700        fs::write(
12701            &user_config,
12702            r#"
12703[auto_review]
12704reviewer_model = "bad model\nid"
12705"#,
12706        )?;
12707        let ws_err = Config::load(Some(user_config.clone()), None)
12708            .expect_err("whitespace in auto_review.reviewer_model must fail validation");
12709        assert!(ws_err.to_string().contains("reviewer_model"), "{ws_err:#}");
12710
12711        fs::write(
12712            &user_config,
12713            r#"
12714[auto_review]
12715reviewer_model = "gpt-5.5"
12716
12717[profiles.fast]
12718[profiles.fast.auto_review]
12719reviewer_model = "gpt-5.6"
12720"#,
12721        )?;
12722        let profiled = Config::load(Some(user_config.clone()), Some("fast"))?;
12723        assert_eq!(profiled.auto_review_reviewer_model(), Some("gpt-5.6"));
12724
12725        let managed_config = temp.path().join("managed.toml");
12726        let _managed_set =
12727            EnvVarGuard::set("CODEWHALE_MANAGED_CONFIG_PATH", managed_config.as_os_str());
12728        fs::write(
12729            &managed_config,
12730            r#"
12731[auto_review]
12732reviewer_model = "managed-reviewer"
12733"#,
12734        )?;
12735        let managed_loaded = Config::load(Some(user_config.clone()), Some("fast"))?;
12736        assert_eq!(
12737            managed_loaded.auto_review_reviewer_model(),
12738            Some("managed-reviewer")
12739        );
12740        drop(_managed_set);
12741        let _ = fs::remove_file(&managed_config);
12742
12743        fs::write(
12744            &user_config,
12745            r#"
12746[auto_review]
12747environment = [
12748    "trusted git remote: origin = https://github.com/org/repo",
12749    "trusted staging host: https://staging.example.internal",
12750]
12751"#,
12752        )?;
12753        let env_loaded = Config::load(Some(user_config.clone()), None)?;
12754        assert_eq!(
12755            env_loaded.auto_review_environment(),
12756            &[
12757                "trusted git remote: origin = https://github.com/org/repo".to_string(),
12758                "trusted staging host: https://staging.example.internal".to_string(),
12759            ]
12760        );
12761
12762        fs::write(
12763            &user_config,
12764            r#"
12765[auto_review]
12766environment = ["   "]
12767"#,
12768        )?;
12769        let blank_env_err = Config::load(Some(user_config.clone()), None)
12770            .expect_err("blank auto_review.environment entry must fail validation");
12771        assert!(
12772            blank_env_err
12773                .to_string()
12774                .contains("auto_review.environment"),
12775            "{blank_env_err:#}"
12776        );
12777
12778        fs::write(
12779            &user_config,
12780            r#"
12781[auto_review]
12782environment = ["bad\nline"]
12783"#,
12784        )?;
12785        let control_env_err = Config::load(Some(user_config.clone()), None)
12786            .expect_err("control chars in auto_review.environment must fail validation");
12787        assert!(
12788            control_env_err
12789                .to_string()
12790                .contains("auto_review.environment"),
12791            "{control_env_err:#}"
12792        );
12793
12794        fs::write(
12795            &user_config,
12796            r#"
12797[auto_review]
12798environment = ["user remote: github.com/acme/repo"]
12799"#,
12800        )?;
12801        let _managed_env_set =
12802            EnvVarGuard::set("CODEWHALE_MANAGED_CONFIG_PATH", managed_config.as_os_str());
12803        fs::write(
12804            &managed_config,
12805            r#"
12806[auto_review]
12807environment = ["managed remote: github.internal/corp/repo"]
12808"#,
12809        )?;
12810        let managed_env = Config::load(Some(user_config), None)?;
12811        assert_eq!(
12812            managed_env.auto_review_environment(),
12813            &["managed remote: github.internal/corp/repo".to_string()]
12814        );
12815
12816        let review_shell_dir = tempfile::tempdir()?;
12817        let review_shell_user = review_shell_dir.path().join("config.toml");
12818        let review_shell_managed = review_shell_dir.path().join("managed.toml");
12819        let _managed_unset = EnvVarGuard::remove("CODEWHALE_MANAGED_CONFIG_PATH");
12820        fs::write(
12821            &review_shell_user,
12822            r#"
12823[auto_review]
12824review_all_shell = true
12825"#,
12826        )?;
12827        let default_cfg = Config::default();
12828        assert!(!default_cfg.auto_review_review_all_shell());
12829        let loaded_review_shell = Config::load(Some(review_shell_user.clone()), None)?;
12830        assert!(loaded_review_shell.auto_review_review_all_shell());
12831
12832        let _managed_override = EnvVarGuard::set(
12833            "CODEWHALE_MANAGED_CONFIG_PATH",
12834            review_shell_managed.as_os_str(),
12835        );
12836        fs::write(
12837            &review_shell_managed,
12838            r#"
12839[auto_review]
12840review_all_shell = false
12841"#,
12842        )?;
12843        let managed_override_cfg = Config::load(Some(review_shell_user), None)?;
12844        assert!(!managed_override_cfg.auto_review_review_all_shell());
12845        Ok(())
12846    }
12847}
12848
12849#[cfg(any(test, feature = "test-support"))]
12850pub mod test_support;