| 1 | use super::ModelAdapter; |
| 2 | use crate::tui::app::{App, AppAction}; |
| 3 | use codewhale_command_contract::model_setup::{ |
| 4 | CommandModelSelectionContext, CommandProviderRoutesContext, ModelAction, ModelSelection, |
| 5 | ModelSelectionReceipt, ProviderAction, ProviderFallback, ProviderSelection, SetupAction, |
| 6 | }; |
| 7 | use codewhale_config::ProviderKind; |
| 8 | use codewhale_localization::{MessageId, tr}; |
| 9 | use codewhale_runtime::config::normalize_custom_model_id; |
| 10 | |
| 11 | impl<'a> TryFrom<ModelAction<'a>> for AppAction { |
| 12 | type Error = String; |
| 13 | fn try_from(action: ModelAction<'a>) -> Result<Self, String> { |
| 14 | Ok(match action { |
| 15 | ModelAction::OpenPicker => Self::OpenModelPicker, |
| 16 | ModelAction::RefreshCatalog => Self::RefreshModelsDevCatalog, |
| 17 | ModelAction::Router(rest) => Self::RouterSetup { |
| 18 | request: crate::tui::views::router_setup::parse_router_args(Some(rest))?, |
| 19 | }, |
| 20 | ModelAction::UpdateCompaction(config) => { |
| 21 | Self::UpdateCompaction(crate::commands::config_host::to_compaction_config(config)) |
| 22 | } |
| 23 | }) |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | impl<'a> TryFrom<ProviderAction<'a>> for AppAction { |
| 28 | type Error = String; |
| 29 | fn try_from(action: ProviderAction<'a>) -> Result<Self, String> { |
| 30 | Ok(match action { |
| 31 | ProviderAction::OpenPicker => Self::OpenProviderPicker, |
| 32 | ProviderAction::Setup(None) => Self::OpenProviderSetup { provider: None }, |
| 33 | ProviderAction::Setup(Some(name)) => provider_setup_action_for_name(name)?, |
| 34 | ProviderAction::Switch { provider, model } => Self::SwitchProvider { |
| 35 | provider: provider.0.into(), |
| 36 | model, |
| 37 | }, |
| 38 | }) |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | impl<'a> TryFrom<SetupAction<'a>> for AppAction { |
| 43 | type Error = String; |
| 44 | fn try_from(action: SetupAction<'a>) -> Result<Self, String> { |
| 45 | Ok(match action { |
| 46 | SetupAction::OpenWizard(None) => Self::OpenSetupWizard, |
| 47 | SetupAction::OpenWizard(Some(step)) => Self::OpenSetupWizardAt { step }, |
| 48 | SetupAction::Provider(name) => provider_setup_action_for_name(name)?, |
| 49 | }) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | impl CommandModelSelectionContext for ModelAdapter<'_> { |
| 54 | fn select_session_model( |
| 55 | &mut self, |
| 56 | selection: ModelSelection<'_>, |
| 57 | ) -> Result<ModelSelectionReceipt, String> { |
| 58 | select_model(&mut self.host.app.borrow_mut(), selection) |
| 59 | } |
| 60 | fn save_session_route_default(&mut self) -> String { |
| 61 | self.host.app.borrow_mut().apply_route_save_choice( |
| 62 | crate::tui::views::route_save_prompt::RouteSaveChoice::SaveAsDefault, |
| 63 | ) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | fn select_model( |
| 68 | app: &mut App, |
| 69 | selection: ModelSelection<'_>, |
| 70 | ) -> Result<ModelSelectionReceipt, String> { |
| 71 | let auto = matches!(selection, ModelSelection::Auto); |
| 72 | let (model_id, route_resolution) = match selection { |
| 73 | ModelSelection::Auto => ("auto".to_string(), None), |
| 74 | ModelSelection::Named(name) => { |
| 75 | let declared = app.api_provider != ProviderKind::OpenaiCodex |
| 76 | && codewhale_config::catalog::configured::validate_configured_models( |
| 77 | &app.configured_models, |
| 78 | ) |
| 79 | .is_ok() |
| 80 | && app.configured_models.iter().any(|model| { |
| 81 | model.id == name |
| 82 | && model.matches_route( |
| 83 | app.provider_identity_for_persistence(), |
| 84 | &app.active_route_base_url, |
| 85 | ) |
| 86 | }); |
| 87 | let model_id = if declared { |
| 88 | name.to_string() |
| 89 | } else if app.accepts_custom_model_ids() { |
| 90 | let Some(model_id) = normalize_custom_model_id(name) else { |
| 91 | return Err(format!( |
| 92 | "Invalid model '{name}'. Expected a non-empty model ID." |
| 93 | )); |
| 94 | }; |
| 95 | model_id |
| 96 | } else { |
| 97 | let Ok(resolved) = |
| 98 | codewhale_config::route::resolve_model(app.api_provider, name, None) |
| 99 | else { |
| 100 | return Err(format!( |
| 101 | "Invalid model '{name}'. Expected auto or a model for the active provider ({}).", |
| 102 | app.api_provider.as_str() |
| 103 | )); |
| 104 | }; |
| 105 | resolved.wire_id |
| 106 | }; |
| 107 | let strict_direct_custom_endpoint = app.accepts_custom_model_ids() |
| 108 | && matches!(app.api_provider, ProviderKind::Deepseek | ProviderKind::Zai); |
| 109 | let route_resolution = if declared { |
| 110 | Some( |
| 111 | codewhale_engine::route_runtime::resolve_declared_model_candidate( |
| 112 | app.api_provider, |
| 113 | app.provider_identity_for_persistence(), |
| 114 | &model_id, |
| 115 | &app.active_route_base_url, |
| 116 | app.active_context_window_override, |
| 117 | app.active_model_context_windows.as_ref(), |
| 118 | &app.configured_models, |
| 119 | )?, |
| 120 | ) |
| 121 | } else if strict_direct_custom_endpoint { |
| 122 | None |
| 123 | } else { |
| 124 | // `/model` normally resolves against the active provider's |
| 125 | // catalog-default endpoint so it retains the existing local |
| 126 | // provider/model validation. The one endpoint-sensitive model |
| 127 | // selection is Kimi Code's bare `k3`: resolve it against the |
| 128 | // committed Kimi Code route rather than silently falling back to |
| 129 | // Moonshot's direct API route. Do not pass an unrelated stale |
| 130 | // endpoint through here; doing so would turn a foreign provider |
| 131 | // model into an apparent custom-route selection. |
| 132 | let route_base_url = codewhale_runtime::config::is_exact_kimi_code_k3_route( |
| 133 | app.api_provider, |
| 134 | &app.active_route_base_url, |
| 135 | &model_id, |
| 136 | ) |
| 137 | .then(|| app.active_route_base_url.clone()); |
| 138 | Some( |
| 139 | codewhale_engine::route_runtime::resolve_route_candidate_with_context_metadata( |
| 140 | app.api_provider, |
| 141 | Some(&model_id), |
| 142 | None, |
| 143 | route_base_url, |
| 144 | app.active_context_window_override, |
| 145 | app.active_model_context_windows.as_ref(), |
| 146 | None, |
| 147 | )?, |
| 148 | ) |
| 149 | }; |
| 150 | (model_id, route_resolution) |
| 151 | } |
| 152 | }; |
| 153 | let old_model = app.model_display_label(); |
| 154 | let model_changed = app.auto_model != auto || app.model != model_id; |
| 155 | app.set_model_selection(model_id.clone()); |
| 156 | if let Some(resolution) = route_resolution { |
| 157 | app.set_active_route_resolution( |
| 158 | resolution.candidate.endpoint().base_url.clone(), |
| 159 | resolution.candidate.limits(), |
| 160 | resolution.context_window, |
| 161 | ); |
| 162 | } else { |
| 163 | app.active_route_limits = app.context_window_override_limits(); |
| 164 | app.active_context_window = app.configured_context_window_for(&app.model); |
| 165 | app.active_context_window_source = app |
| 166 | .active_context_window |
| 167 | .map(|resolution| resolution.source) |
| 168 | .unwrap_or(codewhale_engine::route_runtime::ContextWindowSource::Fallback); |
| 169 | } |
| 170 | app.update_model_compaction_budget(); |
| 171 | if model_changed { |
| 172 | app.clear_model_scoped_telemetry(); |
| 173 | } else { |
| 174 | app.session.last_prompt_tokens = None; |
| 175 | app.session.last_completion_tokens = None; |
| 176 | } |
| 177 | crate::tui::ui::maybe_warn_context_pressure(app); |
| 178 | let provider_identity = app.provider_identity_for_persistence().to_string(); |
| 179 | app.provider_models |
| 180 | .insert(provider_identity.clone(), model_id.clone()); |
| 181 | if !auto { |
| 182 | app.note_route_used(&provider_identity, &model_id); |
| 183 | } |
| 184 | // Route changes are temporary by default: nothing is written here. |
| 185 | // The route-save prompt offers the explicit persistence choices. |
| 186 | app.note_session_route_change(&provider_identity, &model_id); |
| 187 | let mut message = tr(app.ui_locale, MessageId::ModelChanged) |
| 188 | .replace("{old}", &old_model) |
| 189 | .replace("{new}", &model_id); |
| 190 | message.push_str(&tr(app.ui_locale, MessageId::ModelChangedSessionNote)); |
| 191 | Ok(ModelSelectionReceipt { |
| 192 | message, |
| 193 | compaction: crate::commands::config_host::from_compaction_config(app.compaction_config()), |
| 194 | }) |
| 195 | } |
| 196 | |
| 197 | impl CommandProviderRoutesContext for ModelAdapter<'_> { |
| 198 | fn resolve_switch( |
| 199 | &self, |
| 200 | name: &str, |
| 201 | model_arg: Option<&str>, |
| 202 | ) -> Result<ProviderSelection, String> { |
| 203 | let app = self.host.app.borrow(); |
| 204 | if codewhale_runtime::config::is_legacy_antigravity_identity(name) { |
| 205 | return Err(codewhale_config::LEGACY_ANTIGRAVITY_TOMBSTONE_MESSAGE.to_string()); |
| 206 | } |
| 207 | |
| 208 | let Some(row) = codewhale_config::descriptors::compatibility_for_selector(name) else { |
| 209 | return Err(format!( |
| 210 | "Unknown provider '{name}'. Expected: {}.", |
| 211 | ProviderKind::names_hint() |
| 212 | )); |
| 213 | }; |
| 214 | |
| 215 | let target = row.kind; |
| 216 | let selected_key: codewhale_config::ProviderId = row.id.into(); |
| 217 | |
| 218 | let model = match model_arg { |
| 219 | None => None, |
| 220 | Some(raw) => { |
| 221 | let trimmed = raw.trim(); |
| 222 | if is_route_ambiguous_deepseek_alias(target, trimmed) { |
| 223 | Some(trimmed.to_string()) |
| 224 | } else { |
| 225 | match codewhale_config::route::resolve_model(target, trimmed, None) { |
| 226 | Ok(resolved) => Some(resolved.logical), |
| 227 | Err(_) => { |
| 228 | return Err(format!( |
| 229 | "Invalid model '{raw}'. Provide a non-empty model id." |
| 230 | )); |
| 231 | } |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | }; |
| 236 | |
| 237 | let already_active = app |
| 238 | .provider_identity |
| 239 | .as_ref() |
| 240 | .is_some_and(|identity| identity.key == selected_key) |
| 241 | && model.is_none() |
| 242 | && !(target == ProviderKind::Ollama |
| 243 | && codewhale_runtime::config::is_unresolved_local_ollama_model(&app.model)); |
| 244 | Ok(ProviderSelection { |
| 245 | id: super::to_provider_id(selected_key.as_str()), |
| 246 | model, |
| 247 | already_active, |
| 248 | }) |
| 249 | } |
| 250 | fn fallback(&self) -> ProviderFallback { |
| 251 | let app = self.host.app.borrow(); |
| 252 | ProviderFallback { |
| 253 | current: app.provider_identity_for_persistence().to_string(), |
| 254 | entries: app |
| 255 | .fallback_chain_entries() |
| 256 | .into_iter() |
| 257 | .map(|(index, provider, active)| { |
| 258 | (index, super::to_provider_id(provider.as_str()), active) |
| 259 | }) |
| 260 | .collect(), |
| 261 | last_reason: app.last_fallback_reason.clone(), |
| 262 | } |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | fn provider_setup_action_for_name(raw: &str) -> Result<AppAction, String> { |
| 267 | if codewhale_runtime::config::is_legacy_antigravity_identity(raw) { |
| 268 | return Err(codewhale_config::LEGACY_ANTIGRAVITY_TOMBSTONE_MESSAGE.to_string()); |
| 269 | } |
| 270 | if raw.eq_ignore_ascii_case("ds4") || raw.eq_ignore_ascii_case("dwarfstar") { |
| 271 | return Ok(AppAction::OpenDs4Setup); |
| 272 | } |
| 273 | // First-class aliases (zen, opencode-zen, …) resolve through the provider |
| 274 | // registry. There are no setup templates anymore: named custom hosts are |
| 275 | // configured with `/provider setup` and the blank custom form (#6289). |
| 276 | match codewhale_config::descriptors::compatibility_for_selector(raw) { |
| 277 | Some(provider) => Ok(AppAction::OpenProviderSetup { |
| 278 | provider: Some(provider.id.into()), |
| 279 | }), |
| 280 | None => Err(format!( |
| 281 | "Unknown provider '{raw}'. Expected: {}.", |
| 282 | ProviderKind::names_hint() |
| 283 | )), |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | fn is_route_ambiguous_deepseek_alias(provider: ProviderKind, model: &str) -> bool { |
| 288 | matches!( |
| 289 | provider, |
| 290 | ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic |
| 291 | ) && (model.eq_ignore_ascii_case("deepseek-chat") |
| 292 | || model.eq_ignore_ascii_case("deepseek-reasoner")) |
| 293 | } |
| 294 |