Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
opencode: Fetch models dynamically (#64585)
Bennet Bo Fenner6971ae21e9be
diff --git a/Cargo.lock b/Cargo.lockindex e601b4d31c2..8867d3eebe3 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -12476,7 +12476,6 @@ dependencies = ["schemars 1.0.4","serde","serde_json",- "strum 0.28.0",][[package]]diff --git a/crates/language_models/src/provider/opencode.rs b/crates/language_models/src/provider/opencode.rsindex 94b02441011..e4a472530ba 100644--- a/crates/language_models/src/provider/opencode.rs+++ b/crates/language_models/src/provider/opencode.rs@@ -1,10 +1,10 @@-use anyhow::Result;-use collections::BTreeMap;+use anyhow::{Context as _, Result, anyhow, bail};+use collections::{BTreeMap, HashMap};use credentials_provider::CredentialsProvider;use fs::Fs;-use futures::{FutureExt, StreamExt, future::BoxFuture};+use futures::{AsyncReadExt, FutureExt, StreamExt, future::BoxFuture};use gpui::{App, AsyncApp, Context, Entity, SharedString, Task, TaskExt, Window};-use http_client::{AsyncBody, CustomHeaders, HttpClient, http};+use http_client::{AsyncBody, CustomHeaders, HttpClient, Method, Request, RequestBuilderExt, http};use language_model::{ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, InlineDescription, LanguageModel,LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelEffortLevel,@@ -14,11 +14,11 @@ use language_model::{SubPageProviderSettings, env_var,};use opencode::{ApiProtocol, OPENCODE_API_URL, OpenCodeSubscription};+use serde::Deserialize;pub use settings::OpenCodeApiProtocol;pub use settings::OpenCodeAvailableModel as AvailableModel;use settings::{Settings, SettingsStore, update_settings_file};use std::sync::{Arc, LazyLock};-use strum::IntoEnumIterator;use ui::{Banner, ButtonLink, ConfiguredApiCard, Divider, List, ListBulletItem, Severity, Switch,SwitchLabelPosition, ToggleState, prelude::*,@@ -59,12 +59,20 @@ fn reasoning_effort_display(effort: ReasoningEffort) -> (&'static str, &'static}}+fn model_supports_thinking(model: &opencode::Model) -> bool {+ model+ .supported_reasoning_effort_levels()+ .is_some_and(|levels| levels.iter().any(|effort| *effort != ReasoningEffort::None))+}+const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("opencode");const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("OpenCode");const API_KEY_ENV_VAR_NAME: &str = "OPENCODE_API_KEY";static API_KEY_ENV_VAR: LazyLock<EnvVar> = env_var!(API_KEY_ENV_VAR_NAME);const OPENCODE_SESSION_HEADER_NAME: &str = "x-opencode-session";+const RICH_MODEL_CATALOG_URL: &str = "https://models.opencode.ai/api.json";+const MODEL_CATALOG_RESPONSE_LIMIT_BYTES: u64 = 8 * 1024 * 1024;pub(crate) const RESERVED_HEADER_NAMES: &[&str] = &[OPENCODE_SESSION_HEADER_NAME];#[derive(Default, Clone, Debug, PartialEq)]@@ -84,6 +92,17 @@ pub struct OpenCodeLanguageModelProvider {pub struct State {api_key_state: ApiKeyState,credentials_provider: Arc<dyn CredentialsProvider>,+ http_client: Arc<dyn HttpClient>,+ discovered_models: HashMap<OpenCodeSubscription, Vec<DiscoveredModel>>,+ fetch_models_errors: HashMap<OpenCodeSubscription, SharedString>,+ fetch_models_task: Option<Task<()>>,+}++#[derive(Clone)]+struct DiscoveredModel {+ model: opencode::Model,+ supports_images: bool,+ supports_thinking: bool,}impl State {@@ -94,24 +113,93 @@ impl State {fn set_api_key(&mut self, api_key: Option<String>, cx: &mut Context<Self>) -> Task<Result<()>> {let credentials_provider = self.credentials_provider.clone();let api_url = OpenCodeLanguageModelProvider::api_url(cx);- self.api_key_state.store(+ self.fetch_models_task = None;+ self.discovered_models.clear();+ self.fetch_models_errors.clear();+ let task = self.api_key_state.store(api_url,api_key,|this| &mut this.api_key_state,credentials_provider,cx,- )+ );+ cx.notify();+ cx.spawn(async move |this, cx| {+ let result = task.await;+ if result.is_ok() {+ this.update(cx, |this, cx| this.restart_fetch_models_task(cx))+ .ok();+ }+ result+ })}fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {let credentials_provider = self.credentials_provider.clone();let api_url = OpenCodeLanguageModelProvider::api_url(cx);- self.api_key_state.load_if_needed(+ let task = self.api_key_state.load_if_needed(api_url,|this| &mut this.api_key_state,credentials_provider,cx,- )+ );+ cx.spawn(async move |this, cx| {+ let result = task.await;+ if result.is_ok() {+ this.update(cx, |this, cx| this.restart_fetch_models_task(cx))+ .ok();+ }+ result+ })+ }++ fn restart_fetch_models_task(&mut self, cx: &mut Context<Self>) {+ self.fetch_models_task = None;+ self.discovered_models.clear();+ self.fetch_models_errors.clear();+ let api_url = OpenCodeLanguageModelProvider::api_url(cx);+ let custom_headers = OpenCodeLanguageModelProvider::settings(cx)+ .custom_headers+ .clone();+ let Some(api_key) = self.api_key_state.key(&api_url) else {+ self.fetch_models_task = None;+ cx.notify();+ return;+ };+ let http_client = self.http_client.clone();+ self.fetch_models_task = Some(cx.spawn(async move |this, cx| {+ let mut discovered_models = HashMap::default();+ let mut fetch_models_errors = HashMap::default();+ for subscription in [OpenCodeSubscription::Zen, OpenCodeSubscription::Go] {+ match fetch_discovered_models(+ http_client.clone(),+ &api_url,+ subscription,+ &api_key,+ &custom_headers,+ )+ .await+ {+ Ok(models) => {+ discovered_models.insert(subscription, models);+ }+ Err(error) => {+ log::warn!(+ "Failed to fetch OpenCode {} models: {error:#}",+ subscription.display_name()+ );+ fetch_models_errors.insert(subscription, format!("{error:#}").into());+ }+ }+ }+ this.update(cx, |this, cx| {+ this.discovered_models = discovered_models;+ this.fetch_models_errors = fetch_models_errors;+ this.fetch_models_task = None;+ cx.notify();+ })+ .ok();+ }));}}@@ -122,37 +210,54 @@ impl OpenCodeLanguageModelProvider {cx: &mut App,) -> Self {let state = cx.new(|cx| {- cx.observe_global::<SettingsStore>(|this: &mut State, cx| {- let credentials_provider = this.credentials_provider.clone();- let api_url = Self::api_url(cx);- this.api_key_state.handle_url_change(- api_url,- |this| &mut this.api_key_state,- credentials_provider,- cx,- );- cx.notify();+ cx.observe_global::<SettingsStore>({+ let mut last_api_url = Self::api_url(cx);+ let mut last_custom_headers = Self::settings(cx).custom_headers.clone();+ move |this: &mut State, cx| {+ let api_url = Self::api_url(cx);+ let custom_headers = Self::settings(cx).custom_headers.clone();+ if api_url != last_api_url {+ last_api_url = api_url;+ last_custom_headers = custom_headers;+ this.discovered_models.clear();+ this.fetch_models_errors.clear();+ this.fetch_models_task = None;+ this.authenticate(cx).detach();+ } else if custom_headers != last_custom_headers {+ last_custom_headers = custom_headers;+ this.restart_fetch_models_task(cx);+ }+ cx.notify();+ }}).detach();State {api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),credentials_provider,+ http_client: http_client.clone(),+ discovered_models: HashMap::default(),+ fetch_models_errors: HashMap::default(),+ fetch_models_task: None,}});Self { http_client, state }}- fn create_language_model(+ fn create_language_model_with_capabilities(&self,model: opencode::Model,subscription: OpenCodeSubscription,+ supports_images: bool,+ supports_thinking: bool,) -> Arc<dyn LanguageModel> {let id_str = format!("{}/{}", subscription.id_prefix(), model.id());Arc::new(OpenCodeLanguageModel {id: LanguageModelId::from(id_str),model,subscription,+ supports_images,+ supports_thinking,state: self.state.clone(),http_client: self.http_client.clone(),request_limiter: RateLimiter::new(4),@@ -202,51 +307,27 @@ impl LanguageModelProvider for OpenCodeLanguageModelProvider {IconOrSvg::Icon(IconName::AiOpenCode)}- fn default_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {- if Self::subscription_enabled(OpenCodeSubscription::Go, cx) {- // If both Go and Zen are enabled, prefer Go since it's not pay-as-you-go- Some(- self.create_language_model(opencode::Model::default_go(), OpenCodeSubscription::Go),- )- } else if Self::subscription_enabled(OpenCodeSubscription::Zen, cx) {- Some(self.create_language_model(opencode::Model::default(), OpenCodeSubscription::Zen))- } else {- None- }+ fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {+ None}- fn default_fast_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {- if Self::subscription_enabled(OpenCodeSubscription::Go, cx) {- // If both Go and Zen are enabled, prefer Go since it's not pay-as-you-go- Some(self.create_language_model(- opencode::Model::default_go_fast(),- OpenCodeSubscription::Go,- ))- } else if Self::subscription_enabled(OpenCodeSubscription::Zen, cx) {- Some(- self.create_language_model(- opencode::Model::default_fast(),- OpenCodeSubscription::Zen,- ),- )- } else {- None- }+ fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {+ None}fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {- let mut models: BTreeMap<String, (opencode::Model, OpenCodeSubscription)> =+ let mut models: BTreeMap<String, (DiscoveredModel, OpenCodeSubscription)> =BTreeMap::default();let settings = Self::settings(cx);- for model in opencode::Model::iter() {- if matches!(model, opencode::Model::Custom { .. }) {- continue;- }- for &subscription in model.available_subscriptions() {- if Self::subscription_enabled(subscription, cx) {- let key = format!("{}/{}", subscription.id_prefix(), model.id());- models.insert(key, (model.clone(), subscription));+ let discovered_models = &self.state.read(cx).discovered_models;+ for subscription in [OpenCodeSubscription::Zen, OpenCodeSubscription::Go] {+ if Self::subscription_enabled(subscription, cx) {+ if let Some(discovered) = discovered_models.get(&subscription) {+ for model in discovered {+ let key = format!("{}/{}", subscription.id_prefix(), model.model.id());+ models.insert(key, (model.clone(), subscription));+ }}}}@@ -266,23 +347,40 @@ impl LanguageModelProvider for OpenCodeLanguageModelProvider {if !Self::subscription_enabled(subscription, cx) {continue;}- let custom_model = opencode::Model::Custom {- name: model.name.clone(),- display_name: model.display_name.clone(),- max_tokens: model.max_tokens,- max_output_tokens: model.max_output_tokens,+ let custom_model = opencode::Model::new(+ model.name.clone(),+ model.display_name.clone(),+ model.max_tokens,+ model.max_output_tokens,protocol,- reasoning_effort_levels: model.reasoning_effort_levels.clone(),- custom_model_api_url: model.custom_model_api_url.clone(),- interleaved_reasoning: model.interleaved_reasoning,- };+ model.reasoning_effort_levels.clone(),+ model.custom_model_api_url.clone(),+ model.interleaved_reasoning,+ );let key = format!("{}/{}", subscription.id_prefix(), model.name);- models.insert(key, (custom_model, subscription));+ models.insert(+ key,+ (+ DiscoveredModel {+ supports_images: true,+ supports_thinking: model_supports_thinking(&custom_model),+ model: custom_model,+ },+ subscription,+ ),+ );}models.into_values()- .map(|(model, subscription)| self.create_language_model(model, subscription))+ .map(|(model, subscription)| {+ self.create_language_model_with_capabilities(+ model.model,+ subscription,+ model.supports_images,+ model.supports_thinking,+ )+ }).collect()}@@ -312,6 +410,8 @@ pub struct OpenCodeLanguageModel {id: LanguageModelId,model: opencode::Model,subscription: OpenCodeSubscription,+ supports_images: bool,+ supports_thinking: bool,state: Entity<State>,http_client: Arc<dyn HttpClient>,request_limiter: RateLimiter,@@ -353,14 +453,9 @@ fn opencode_session_header_value(thread_id: Option<&str>) -> http::HeaderValue {impl OpenCodeLanguageModel {fn base_api_url(&self, cx: &AsyncApp) -> SharedString {- // Custom models can override the API URL- if let opencode::Model::Custom {- custom_model_api_url: Some(url),- ..- } = &self.model- {+ if let Some(url) = self.model.custom_model_api_url() {if !url.is_empty() {- return url.clone().into();+ return url.to_string().into();}}@@ -562,13 +657,11 @@ impl LanguageModel for OpenCodeLanguageModel {}fn supports_images(&self) -> bool {- self.model.supports_images()+ self.supports_images}fn supports_thinking(&self) -> bool {- self.model- .supported_reasoning_effort_levels()- .is_some_and(|levels| levels.iter().any(|effort| *effort != ReasoningEffort::None))+ self.supports_thinking}fn supports_disabling_thinking(&self) -> bool {@@ -582,7 +675,8 @@ impl LanguageModel for OpenCodeLanguageModel {.supported_reasoning_effort_levels().map(|levels| {let levels = levels- .into_iter()+ .iter()+ .copied().filter(|effort| *effort != ReasoningEffort::None).collect::<Vec<_>>();if levels.is_empty() {@@ -610,7 +704,7 @@ impl LanguageModel for OpenCodeLanguageModel {LanguageModelToolChoice::Auto | LanguageModelToolChoice::Any => true,LanguageModelToolChoice::None => {// Google models don't support None tool choice- self.model.protocol(self.subscription) != ApiProtocol::Google+ self.model.protocol() != ApiProtocol::Google}}}@@ -624,11 +718,11 @@ impl LanguageModel for OpenCodeLanguageModel {}fn max_token_count(&self) -> u64 {- self.model.max_token_count(self.subscription)+ self.model.max_token_count()}fn max_output_tokens(&self) -> Option<u64> {- self.model.max_output_tokens(self.subscription)+ self.model.max_output_tokens()}fn stream_completion(@@ -652,7 +746,7 @@ impl LanguageModel for OpenCodeLanguageModel {});let extra_headers = self.custom_headers(cx);- match self.model.protocol(self.subscription) {+ match self.model.protocol() {ApiProtocol::Anthropic => {let mode = if self.supports_thinking() && request.thinking_allowed {anthropic::AnthropicModelMode::AdaptiveThinking@@ -663,9 +757,7 @@ impl LanguageModel for OpenCodeLanguageModel {request,self.model.id().to_string(),1.0,- self.model- .max_output_tokens(self.subscription)- .unwrap_or(8192),+ self.model.max_output_tokens().unwrap_or(8192),mode,anthropic::completion::AnthropicPromptCacheMode::Automatic,&PROVIDER_ID,@@ -699,7 +791,7 @@ impl LanguageModel for OpenCodeLanguageModel {self.model.id(),true,false,- self.model.max_output_tokens(self.subscription),+ self.model.max_output_tokens(),ChatCompletionMaxTokensParameter::MaxCompletionTokens,reasoning_effort,self.model.interleaved_reasoning(),@@ -729,7 +821,7 @@ impl LanguageModel for OpenCodeLanguageModel {self.model.id(),true,false,- self.model.max_output_tokens(self.subscription),+ self.model.max_output_tokens(),None,supports_none_reasoning_effort,&PROVIDER_ID,@@ -777,6 +869,230 @@ impl LanguageModel for OpenCodeLanguageModel {}}+#[derive(Deserialize)]+struct AvailableModelsResponse {+ data: Vec<AvailableModelResponse>,+}++#[derive(Deserialize)]+struct AvailableModelResponse {+ id: String,+}++#[derive(Deserialize)]+struct RichCatalogProvider {+ npm: Option<String>,+ models: HashMap<String, RichCatalogModel>,+}++#[derive(Deserialize)]+struct RichCatalogModel {+ id: String,+ name: String,+ #[serde(default)]+ reasoning: bool,+ #[serde(default)]+ reasoning_options: Option<Vec<ReasoningOption>>,+ #[serde(default)]+ tool_call: bool,+ #[serde(default)]+ interleaved: serde_json::Value,+ #[serde(default)]+ modalities: ModelModalities,+ limit: ModelLimits,+ provider: Option<ModelTransport>,+ cost: Option<ModelCost>,+}++#[derive(Deserialize)]+struct ModelCost {+ input: Option<f64>,+ output: Option<f64>,+}++#[derive(Default, Deserialize)]+struct ModelModalities {+ #[serde(default)]+ input: Vec<String>,+ #[serde(default)]+ output: Vec<String>,+}++#[derive(Deserialize)]+struct ModelLimits {+ context: u64,+ output: Option<u64>,+}++#[derive(Deserialize)]+struct ModelTransport {+ npm: String,+}++#[derive(Deserialize)]+struct ReasoningOption {+ #[serde(rename = "type")]+ kind: String,+ #[serde(default)]+ values: Vec<String>,+}++fn parse_discovered_models(+ available_models: &str,+ rich_catalog: &str,+ subscription: OpenCodeSubscription,+) -> Result<Vec<DiscoveredModel>> {+ let available_models = serde_json::from_str::<AvailableModelsResponse>(available_models)?;+ let provider_key = match subscription {+ OpenCodeSubscription::Zen => "opencode",+ OpenCodeSubscription::Go => "opencode-go",+ };+ let rich_catalog = serde_json::from_str::<serde_json::Value>(rich_catalog)?;+ let provider = rich_catalog+ .get(provider_key)+ .cloned()+ .ok_or_else(|| anyhow!("OpenCode catalog is missing {provider_key}"))?;+ let provider = serde_json::from_value::<RichCatalogProvider>(provider)?;+ let mut available_model_count = available_models.data.len();+ let models = available_models+ .data+ .into_iter()+ .filter_map(|available| {+ let metadata = provider.models.get(&available.id)?;+ if subscription == OpenCodeSubscription::Zen+ && metadata+ .cost+ .as_ref()+ .is_some_and(|cost| cost.input == Some(0.0) && cost.output == Some(0.0))+ {+ available_model_count -= 1;+ return None;+ }+ if metadata.id != available.id+ || !metadata.tool_call+ || !metadata+ .modalities+ .output+ .iter()+ .any(|value| value == "text")+ || metadata.limit.context == 0+ {+ return None;+ }+ let transport = metadata+ .provider+ .as_ref()+ .map(|provider| provider.npm.as_str())+ .or(provider.npm.as_deref());+ let protocol = transport.and_then(protocol_for_transport)?;+ let reasoning_effort_levels = metadata+ .reasoning+ .then(|| {+ metadata+ .reasoning_options+ .as_deref()+ .unwrap_or_default()+ .iter()+ .find(|option| option.kind == "effort")+ .into_iter()+ .flat_map(|option| &option.values)+ .filter_map(|effort| normalize_reasoning_effort(effort))+ .collect::<Vec<_>>()+ })+ .filter(|levels| !levels.is_empty());+ Some(DiscoveredModel {+ model: opencode::Model::new(+ metadata.id.clone(),+ Some(metadata.name.clone()),+ metadata.limit.context,+ metadata.limit.output,+ protocol,+ reasoning_effort_levels,+ None,+ metadata.interleaved == serde_json::Value::Bool(true)+ || metadata.interleaved.is_object(),+ ),+ supports_images: metadata+ .modalities+ .input+ .iter()+ .any(|value| value == "image"),+ supports_thinking: metadata.reasoning,+ })+ })+ .collect::<Vec<_>>();+ if available_model_count > 0 && models.is_empty() {+ bail!("OpenCode model metadata did not contain any compatible models");+ }+ Ok(models)+}++fn protocol_for_transport(transport: &str) -> Option<ApiProtocol> {+ match transport {+ "@ai-sdk/anthropic" => Some(ApiProtocol::Anthropic),+ "@ai-sdk/openai" => Some(ApiProtocol::OpenAiResponses),+ "@ai-sdk/openai-compatible" => Some(ApiProtocol::OpenAiChat),+ "@ai-sdk/google" => Some(ApiProtocol::Google),+ _ => None,+ }+}++async fn fetch_discovered_models(+ client: Arc<dyn HttpClient>,+ api_url: &str,+ subscription: OpenCodeSubscription,+ api_key: &str,+ custom_headers: &CustomHeaders,+) -> Result<Vec<DiscoveredModel>> {+ let models_url = format!(+ "{}{}/v1/models",+ api_url.trim_end_matches('/'),+ subscription.api_path_suffix()+ );+ let available_models =+ fetch_catalog_resource(client.as_ref(), &models_url, Some(api_key), custom_headers).await?;+ let rich_catalog = fetch_catalog_resource(+ client.as_ref(),+ RICH_MODEL_CATALOG_URL,+ None,+ &CustomHeaders::default(),+ )+ .await?;+ parse_discovered_models(&available_models, &rich_catalog, subscription)+}++async fn fetch_catalog_resource(+ client: &dyn HttpClient,+ url: &str,+ api_key: Option<&str>,+ custom_headers: &CustomHeaders,+) -> Result<String> {+ let mut request = Request::builder()+ .method(Method::GET)+ .uri(url)+ .extra_headers(custom_headers);+ if let Some(api_key) = api_key {+ request = request.header(http::header::AUTHORIZATION, format!("Bearer {api_key}"));+ }+ let mut response = client+ .send(request.body(AsyncBody::empty())?)+ .await+ .with_context(|| format!("requesting OpenCode catalog at {url}"))?;+ if !response.status().is_success() {+ bail!(+ "OpenCode catalog request to {url} returned {}",+ response.status()+ );+ }+ let mut body = String::new();+ response+ .body_mut()+ .take(MODEL_CATALOG_RESPONSE_LIMIT_BYTES)+ .read_to_string(&mut body)+ .await?;+ Ok(body)+}+struct ConfigurationView {api_key_editor: Entity<InputField>,state: Entity<State>,@@ -982,6 +1298,19 @@ impl Render for ConfigurationView {} else {None};+ let fetch_models_warnings =+ self.state+ .read(cx)+ .fetch_models_errors+ .iter()+ .map(|(subscription, error)| {+ Banner::new()+ .severity(Severity::Error)+ .child(Label::new(format!(+ "Failed to load OpenCode {} models: {error}",+ subscription.display_name()+ )))+ });v_flex().size_full()@@ -991,6 +1320,7 @@ impl Render for ConfigurationView {.child(Divider::horizontal()).child(subscription_toggles).children(no_subscriptions_warning)+ .children(fetch_models_warnings).into_any()}}@@ -1003,6 +1333,239 @@ mod tests {use language_model::{LanguageModelRequestMessage, MessageContent, Role};use parking_lot::Mutex;+ #[gpui::test]+ async fn test_discovery_authenticates_and_applies_custom_headers() {+ let requests = Arc::new(Mutex::new(Vec::new()));+ let http_client = FakeHttpClient::create({+ let requests = requests.clone();+ move |request| {+ let requests = requests.clone();+ async move {+ let uri = request.uri().to_string();+ requests.lock().push((+ uri.clone(),+ request.headers().get(http::header::AUTHORIZATION).cloned(),+ request.headers().get("x-test-header").cloned(),+ ));+ let body = if uri == RICH_MODEL_CATALOG_URL {+ r#"{+ "opencode": {+ "npm": "@ai-sdk/anthropic",+ "models": {+ "new-model": {+ "id": "new-model",+ "name": "New Model",+ "tool_call": true,+ "modalities": {"input":["text"],"output":["text"]},+ "limit": {"context": 12345}+ }+ }+ }+ }"#+ } else {+ r#"{"data":[{"id":"new-model"}]}"#+ };+ Ok(Response::builder()+ .status(200)+ .body(AsyncBody::from(body))?)+ }+ }+ });+ let custom_headers = CustomHeaders::new(vec![(+ http::HeaderName::from_static("x-test-header"),+ http::HeaderValue::from_static("configured"),+ )]);++ let models = fetch_discovered_models(+ http_client,+ "https://api.example.test",+ OpenCodeSubscription::Zen,+ "secret",+ &custom_headers,+ )+ .await+ .unwrap();++ assert_eq!(models.len(), 1);+ let requests = requests.lock();+ assert_eq!(requests.len(), 2);+ assert_eq!(+ requests[0].1.as_ref().and_then(|value| value.to_str().ok()),+ Some("Bearer secret")+ );+ assert_eq!(+ requests[0].2.as_ref().and_then(|value| value.to_str().ok()),+ Some("configured")+ );+ assert_eq!(requests[1].1, None);+ assert_eq!(requests[1].2, None);+ }++ #[gpui::test]+ async fn test_credential_change_invalidates_discovery_before_storing_key(+ cx: &mut gpui::TestAppContext,+ ) {+ let provider = cx.update(|cx| {+ let settings_store = SettingsStore::test(cx);+ cx.set_global(settings_store);+ OpenCodeLanguageModelProvider::new(+ FakeHttpClient::with_404_response(),+ Arc::new(TestCredentialsProvider),+ cx,+ )+ });+ provider+ .state+ .update(cx, |state, cx| {+ state.set_api_key(Some("old-key".to_string()), cx)+ })+ .await+ .unwrap();+ provider.state.update(cx, |state, _cx| {+ state.discovered_models.insert(+ OpenCodeSubscription::Zen,+ vec![DiscoveredModel {+ model: test_model("old-model", ApiProtocol::Anthropic),+ supports_images: true,+ supports_thinking: false,+ }],+ );+ });++ let store_task = provider.state.update(cx, |state, cx| {+ let task = state.set_api_key(Some("new-key".to_string()), cx);+ assert!(state.fetch_models_task.is_none());+ assert!(state.discovered_models.is_empty());+ task+ });++ store_task.await.unwrap();+ }++ #[test]+ fn test_none_only_reasoning_does_not_enable_thinking() {+ let model = opencode::Model::new(+ "none-only".to_string(),+ None,+ 1000,+ None,+ ApiProtocol::OpenAiChat,+ Some(vec![ReasoningEffort::None]),+ None,+ false,+ );++ assert!(!model_supports_thinking(&model));+ }++ #[test]+ fn test_discovery_excludes_only_explicitly_free_zen_models() -> Result<()> {+ for (cost, zen_model_count) in [+ (serde_json::json!({"input": 0, "output": 0}), 0),+ (serde_json::json!({"input": 0, "output": 1}), 1),+ (serde_json::json!({"input": 1, "output": 0}), 1),+ (serde_json::json!({"input": 1, "output": 1}), 1),+ (serde_json::json!({"input": 0}), 1),+ (serde_json::json!({"output": 0}), 1),+ (serde_json::json!({}), 1),+ (serde_json::Value::Null, 1),+ ] {+ let provider = serde_json::json!({+ "npm": "@ai-sdk/openai-compatible",+ "models": {+ "model": {+ "id": "model",+ "name": "Model",+ "tool_call": true,+ "modalities": {"output": ["text"]},+ "limit": {"context": 1000},+ "cost": cost,+ },+ },+ });+ let catalog = serde_json::json!({+ "opencode": provider,+ "opencode-go": provider,+ })+ .to_string();+ for (subscription, expected_count) in [+ (OpenCodeSubscription::Zen, zen_model_count),+ (OpenCodeSubscription::Go, 1),+ ] {+ let models = parse_discovered_models(+ r#"{"data":[{"id":"model"}]}"#,+ &catalog,+ subscription,+ )?;+ assert_eq!(models.len(), expected_count, "{subscription:?}: {cost}");+ }+ }+ Ok(())+ }++ #[test]+ fn test_parse_discovered_models_joins_subscription_and_metadata_catalogs() {+ let models = parse_discovered_models(+ r#"{"data":[{"id":"new-model"}]}"#,+ r#"{+ "opencode-go": {+ "npm": "@ai-sdk/openai-compatible",+ "models": {+ "new-model": {+ "id": "new-model",+ "name": "New Model",+ "reasoning": true,+ "reasoning_options": [{"type":"effort","values":["low","high"]}],+ "tool_call": true,+ "interleaved": true,+ "modalities": {"input":["text","image"],"output":["text"]},+ "limit": {"context": 12345,"output": 678}+ }+ }+ }+ }"#,+ OpenCodeSubscription::Go,+ )+ .unwrap();++ assert_eq!(models.len(), 1);+ assert_eq!(models[0].model.id(), "new-model");+ assert_eq!(models[0].model.display_name(), "New Model");+ assert!(models[0].supports_images);+ assert!(models[0].supports_thinking);+ assert_eq!(+ models[0].model.supported_reasoning_effort_levels(),+ Some([ReasoningEffort::Low, ReasoningEffort::High].as_slice())+ );+ assert_eq!(models[0].model.max_token_count(), 12345);+ assert_eq!(models[0].model.max_output_tokens(), Some(678));+ assert_eq!(models[0].model.protocol(), ApiProtocol::OpenAiChat);+ }++ #[test]+ fn test_parse_discovered_models_rejects_catalog_without_compatible_models() {+ let result = parse_discovered_models(+ r#"{"data":[{"id":"text-only"}]}"#,+ r#"{+ "opencode": {+ "npm": "@ai-sdk/anthropic",+ "models": {+ "text-only": {+ "id": "text-only",+ "name": "Text Only",+ "tool_call": false,+ "modalities": {"input":["text"],"output":["text"]},+ "limit": {"context": 1000}+ }+ }+ }+ }"#,+ OpenCodeSubscription::Zen,+ );++ assert!(result.is_err());+ }+#[test]fn test_opencode_session_header_uses_thread_id() {let value = opencode_session_header_value(Some("thread-123"));@@ -1058,8 +1621,12 @@ mod tests {state.set_api_key(Some("test-key".to_string()), cx)});store_key.await.unwrap();- let model =- provider.create_language_model(opencode::Model::default(), OpenCodeSubscription::Go);+ let model = provider.create_language_model_with_capabilities(+ test_model("test-model", ApiProtocol::Anthropic),+ OpenCodeSubscription::Go,+ true,+ false,+ );let request = LanguageModelRequest {thread_id: None,messages: vec![LanguageModelRequestMessage {@@ -1093,6 +1660,19 @@ mod tests {.expect("generated session id should be a u64");}+ fn test_model(name: &str, protocol: ApiProtocol) -> opencode::Model {+ opencode::Model::new(+ name.to_string(),+ None,+ 1000,+ Some(100),+ protocol,+ None,+ None,+ false,+ )+ }+struct TestCredentialsProvider;impl CredentialsProvider for TestCredentialsProvider {diff --git a/crates/opencode/Cargo.toml b/crates/opencode/Cargo.tomlindex 01ccb35cb9b..f2b5a0007d0 100644--- a/crates/opencode/Cargo.toml+++ b/crates/opencode/Cargo.toml@@ -26,4 +26,3 @@ language_model_core.workspace = trueschemars = { workspace = true, optional = true }serde.workspace = trueserde_json.workspace = true-strum.workspace = truediff --git a/crates/opencode/src/opencode.rs b/crates/opencode/src/opencode.rsindex 51d95d385cc..cfa3dcb34d5 100644--- a/crates/opencode/src/opencode.rs+++ b/crates/opencode/src/opencode.rs@@ -1,3 +1,8 @@+//! OpenCode API types and streaming clients.+//!+//! This crate describes dynamically discovered OpenCode models and sends requests using+//! each model's advertised protocol and capabilities.+use anyhow::{Result, anyhow};use futures::{AsyncBufReadExt, AsyncReadExt, StreamExt, io::BufReader, stream::BoxStream};use http_client::{@@ -5,7 +10,6 @@ use http_client::{};use language_model_core::ReasoningEffort;use serde::{Deserialize, Serialize};-use strum::EnumIter;pub const OPENCODE_API_URL: &str = "https://opencode.ai/zen";@@ -51,145 +55,21 @@ impl OpenCodeSubscription {}}+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]-#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, EnumIter)]-pub enum Model {- // -- Anthropic protocol models --- #[serde(rename = "claude-opus-5")]- ClaudeOpus5,- #[serde(rename = "claude-opus-4-8")]- ClaudeOpus4_8,- #[serde(rename = "claude-opus-4-7")]- ClaudeOpus4_7,- #[serde(rename = "claude-opus-4-6")]- ClaudeOpus4_6,- #[serde(rename = "claude-opus-4-5")]- ClaudeOpus4_5,- #[default]- #[serde(rename = "claude-sonnet-4-6")]- ClaudeSonnet4_6,- #[serde(rename = "claude-sonnet-4-5")]- ClaudeSonnet4_5,- #[serde(rename = "claude-sonnet-4")]- ClaudeSonnet4,- #[serde(rename = "claude-haiku-4-5")]- ClaudeHaiku4_5,- #[serde(rename = "claude-sonnet-5")]- ClaudeSonnet5,- #[serde(rename = "claude-fable-5")]- ClaudeFable5,-- // -- OpenAI Responses API models --- #[serde(rename = "gpt-5.6-sol")]- Gpt5_6Sol,- #[serde(rename = "gpt-5.6-terra")]- Gpt5_6Terra,- #[serde(rename = "gpt-5.6-luna")]- Gpt5_6Luna,- #[serde(rename = "gpt-5.5")]- Gpt5_5,- #[serde(rename = "gpt-5.5-pro")]- Gpt5_5Pro,- #[serde(rename = "gpt-5.4")]- Gpt5_4,- #[serde(rename = "gpt-5.4-pro")]- Gpt5_4Pro,- #[serde(rename = "gpt-5.4-mini")]- Gpt5_4Mini,- #[serde(rename = "gpt-5.4-nano")]- Gpt5_4Nano,- #[serde(rename = "gpt-5.3-codex")]- Gpt5_3Codex,- #[serde(rename = "gpt-5.3-codex-spark")]- Gpt5_3Spark,- #[serde(rename = "gpt-5.2")]- Gpt5_2,- #[serde(rename = "gpt-5.2-codex")]- Gpt5_2Codex,- #[serde(rename = "gpt-5.1")]- Gpt5_1,- #[serde(rename = "gpt-5.1-codex")]- Gpt5_1Codex,- #[serde(rename = "gpt-5.1-codex-max")]- Gpt5_1CodexMax,- #[serde(rename = "gpt-5.1-codex-mini")]- Gpt5_1CodexMini,- #[serde(rename = "gpt-5")]- Gpt5,- #[serde(rename = "gpt-5-codex")]- Gpt5Codex,- #[serde(rename = "gpt-5-nano")]- Gpt5Nano,-- // -- Google protocol models --- #[serde(rename = "gemini-3.1-pro")]- Gemini3_1Pro,- #[serde(rename = "gemini-3-flash")]- Gemini3Flash,- #[serde(rename = "gemini-3.5-flash-lite")]- Gemini3_5FlashLite,- #[serde(rename = "gemini-3.5-flash")]- Gemini3_5Flash,- #[serde(rename = "gemini-3.6-flash")]- Gemini3_6Flash,- #[serde(rename = "gemini-3.7-flash")]- Gemini3_7Flash,-- // -- OpenAI Chat Completions protocol models --- #[serde(rename = "deepseek-v4-pro")]- DeepSeekV4Pro,- #[serde(rename = "deepseek-flash")]- DeepSeekV4_1Flash,- #[serde(rename = "minimax-m2.5")]- MiniMaxM2_5,- #[serde(rename = "glm-5")]- Glm5,- #[serde(rename = "glm-5.1")]- Glm5_1,- #[serde(rename = "glm-5.2")]- Glm5_2,- #[serde(rename = "glm-5.3")]- Glm5_3,- #[serde(rename = "grok-build-0.1")]- GrokBuild0_1,- #[serde(rename = "grok-4.5")]- Grok4_5,- #[serde(rename = "grok-4.6")]- Grok4_6,- #[serde(rename = "muse-spark-1.2")]- MuseSpark1_2,- #[serde(rename = "kimi-k2.5")]- KimiK2_5,- #[serde(rename = "kimi-k2.6")]- KimiK2_6,- #[serde(rename = "kimi-k2.7-code")]- KimiK2_7Code,- #[serde(rename = "kimi-k3")]- KimiK3,- #[serde(rename = "minimax-m2.7")]- MiniMaxM2_7,- #[serde(rename = "minimax-m3")]- MiniMaxM3,- #[serde(rename = "mimo-v2.5-pro")]- MimoV2_5Pro,- #[serde(rename = "mimo-v2.5")]- MimoV2_5,- #[serde(rename = "qwen3.5-plus")]- Qwen3_5Plus,- #[serde(rename = "qwen3.6-plus")]- Qwen3_6Plus,- #[serde(rename = "qwen3.7-plus")]- Qwen3_7Plus,- #[serde(rename = "qwen3.7-max")]- Qwen3_7Max,- #[serde(rename = "qwen3.8-max")]- Qwen3_8Max,- #[serde(rename = "hy3")]- Hy3,+pub struct Model {+ name: String,+ display_name: Option<String>,+ max_tokens: u64,+ max_output_tokens: Option<u64>,+ protocol: ApiProtocol,+ reasoning_effort_levels: Option<Vec<ReasoningEffort>>,+ custom_model_api_url: Option<String>,+ interleaved_reasoning: bool,+}- // -- Custom model --- #[serde(rename = "custom")]- Custom {+impl Model {+ pub fn new(name: String,display_name: Option<String>,max_tokens: u64,@@ -198,738 +78,57 @@ pub enum Model {reasoning_effort_levels: Option<Vec<ReasoningEffort>>,custom_model_api_url: Option<String>,interleaved_reasoning: bool,- },-}--impl Model {- pub fn default_fast() -> Self {- Self::ClaudeHaiku4_5- }-- pub fn default_go() -> Self {- Self::KimiK2_6- }-- pub fn default_go_fast() -> Self {- Self::MiniMaxM2_7- }-- pub fn available_subscriptions(&self) -> &'static [OpenCodeSubscription] {- match self {- // Models available in both Zen and Go- Self::Glm5_1- | Self::Glm5_2- | Self::Grok4_5- | Self::KimiK2_6- | Self::KimiK2_7Code- | Self::KimiK3- | Self::MiniMaxM2_7- | Self::MiniMaxM3- | Self::DeepSeekV4Pro- | Self::Gpt5_6Luna- | Self::Qwen3_6Plus => &[OpenCodeSubscription::Zen, OpenCodeSubscription::Go],-- // Go-only models- Self::MimoV2_5Pro- | Self::MimoV2_5- | Self::Glm5_3- | Self::Qwen3_7Plus- | Self::Qwen3_7Max- | Self::Qwen3_8Max- | Self::DeepSeekV4_1Flash- | Self::Hy3 => &[OpenCodeSubscription::Go],-- // Deprecated on Go (per models.dev); still offered on Zen- Self::Glm5 | Self::KimiK2_5 | Self::MiniMaxM2_5 | Self::Qwen3_5Plus => {- &[OpenCodeSubscription::Zen]- }-- // Custom models get their subscription from settings, not from here- Self::Custom { .. } => &[],-- // All other built-in models are Zen-only- _ => &[OpenCodeSubscription::Zen],+ ) -> Self {+ Self {+ name,+ display_name,+ max_tokens,+ max_output_tokens,+ protocol,+ reasoning_effort_levels,+ custom_model_api_url,+ interleaved_reasoning,}}pub fn id(&self) -> &str {- match self {- Self::ClaudeOpus5 => "claude-opus-5",- Self::ClaudeOpus4_8 => "claude-opus-4-8",- Self::ClaudeOpus4_7 => "claude-opus-4-7",- Self::ClaudeOpus4_6 => "claude-opus-4-6",- Self::ClaudeOpus4_5 => "claude-opus-4-5",- Self::ClaudeSonnet4_6 => "claude-sonnet-4-6",- Self::ClaudeSonnet4_5 => "claude-sonnet-4-5",- Self::ClaudeSonnet4 => "claude-sonnet-4",- Self::ClaudeHaiku4_5 => "claude-haiku-4-5",- Self::ClaudeSonnet5 => "claude-sonnet-5",- Self::ClaudeFable5 => "claude-fable-5",-- Self::Gpt5_6Sol => "gpt-5.6-sol",- Self::Gpt5_6Terra => "gpt-5.6-terra",- Self::Gpt5_6Luna => "gpt-5.6-luna",- Self::Gpt5_5 => "gpt-5.5",- Self::Gpt5_5Pro => "gpt-5.5-pro",- Self::Gpt5_4 => "gpt-5.4",- Self::Gpt5_4Pro => "gpt-5.4-pro",- Self::Gpt5_4Mini => "gpt-5.4-mini",- Self::Gpt5_4Nano => "gpt-5.4-nano",- Self::Gpt5_3Codex => "gpt-5.3-codex",- Self::Gpt5_3Spark => "gpt-5.3-codex-spark",- Self::Gpt5_2 => "gpt-5.2",- Self::Gpt5_2Codex => "gpt-5.2-codex",- Self::Gpt5_1 => "gpt-5.1",- Self::Gpt5_1Codex => "gpt-5.1-codex",- Self::Gpt5_1CodexMax => "gpt-5.1-codex-max",- Self::Gpt5_1CodexMini => "gpt-5.1-codex-mini",- Self::Gpt5 => "gpt-5",- Self::Gpt5Codex => "gpt-5-codex",- Self::Gpt5Nano => "gpt-5-nano",-- Self::Gemini3_1Pro => "gemini-3.1-pro",- Self::Gemini3Flash => "gemini-3-flash",- Self::Gemini3_5FlashLite => "gemini-3.5-flash-lite",- Self::Gemini3_5Flash => "gemini-3.5-flash",- Self::Gemini3_6Flash => "gemini-3.6-flash",- Self::Gemini3_7Flash => "gemini-3.7-flash",-- Self::DeepSeekV4Pro => "deepseek-v4-pro",- Self::DeepSeekV4_1Flash => "deepseek-flash",- Self::MiniMaxM2_5 => "minimax-m2.5",- Self::Glm5 => "glm-5",- Self::Glm5_1 => "glm-5.1",- Self::Glm5_2 => "glm-5.2",- Self::Glm5_3 => "glm-5.3",- Self::GrokBuild0_1 => "grok-build-0.1",- Self::Grok4_5 => "grok-4.5",- Self::Grok4_6 => "grok-4.6",- Self::MuseSpark1_2 => "muse-spark-1.2",- Self::KimiK2_5 => "kimi-k2.5",- Self::KimiK2_6 => "kimi-k2.6",- Self::KimiK2_7Code => "kimi-k2.7-code",- Self::KimiK3 => "kimi-k3",- Self::MiniMaxM2_7 => "minimax-m2.7",- Self::MiniMaxM3 => "minimax-m3",- Self::MimoV2_5Pro => "mimo-v2.5-pro",- Self::MimoV2_5 => "mimo-v2.5",- Self::Qwen3_5Plus => "qwen3.5-plus",- Self::Qwen3_6Plus => "qwen3.6-plus",- Self::Qwen3_7Plus => "qwen3.7-plus",- Self::Qwen3_7Max => "qwen3.7-max",- Self::Qwen3_8Max => "qwen3.8-max",- Self::Hy3 => "hy3",-- Self::Custom { name, .. } => name,- }+ &self.name}pub fn display_name(&self) -> &str {- match self {- Self::ClaudeOpus5 => "Claude Opus 5",- Self::ClaudeOpus4_8 => "Claude Opus 4.8",- Self::ClaudeOpus4_7 => "Claude Opus 4.7",- Self::ClaudeOpus4_6 => "Claude Opus 4.6",- Self::ClaudeOpus4_5 => "Claude Opus 4.5",- Self::ClaudeSonnet4_6 => "Claude Sonnet 4.6",- Self::ClaudeSonnet4_5 => "Claude Sonnet 4.5",- Self::ClaudeSonnet4 => "Claude Sonnet 4",- Self::ClaudeHaiku4_5 => "Claude Haiku 4.5",- Self::ClaudeSonnet5 => "Claude Sonnet 5",- Self::ClaudeFable5 => "Claude Fable 5",-- Self::Gpt5_6Sol => "GPT 5.6 Sol",- Self::Gpt5_6Terra => "GPT 5.6 Terra",- Self::Gpt5_6Luna => "GPT 5.6 Luna",- Self::Gpt5_5 => "GPT 5.5",- Self::Gpt5_5Pro => "GPT 5.5 Pro",- Self::Gpt5_4 => "GPT 5.4",- Self::Gpt5_4Pro => "GPT 5.4 Pro",- Self::Gpt5_4Mini => "GPT 5.4 Mini",- Self::Gpt5_4Nano => "GPT 5.4 Nano",- Self::Gpt5_3Codex => "GPT 5.3 Codex",- Self::Gpt5_3Spark => "GPT 5.3 Codex Spark",- Self::Gpt5_2 => "GPT 5.2",- Self::Gpt5_2Codex => "GPT 5.2 Codex",- Self::Gpt5_1 => "GPT 5.1",- Self::Gpt5_1Codex => "GPT 5.1 Codex",- Self::Gpt5_1CodexMax => "GPT 5.1 Codex Max",- Self::Gpt5_1CodexMini => "GPT 5.1 Codex Mini",- Self::Gpt5 => "GPT 5",- Self::Gpt5Codex => "GPT 5 Codex",- Self::Gpt5Nano => "GPT 5 Nano",-- Self::Gemini3_1Pro => "Gemini 3.1 Pro",- Self::Gemini3Flash => "Gemini 3 Flash",- Self::Gemini3_5FlashLite => "Gemini 3.5 Flash Lite",- Self::Gemini3_5Flash => "Gemini 3.5 Flash",- Self::Gemini3_6Flash => "Gemini 3.6 Flash",- Self::Gemini3_7Flash => "Gemini 3.7 Flash",-- Self::DeepSeekV4Pro => "DeepSeek V4 Pro",- Self::DeepSeekV4_1Flash => "DeepSeek V4.1 Flash",- Self::MiniMaxM2_5 => "MiniMax M2.5",- Self::Glm5 => "GLM 5",- Self::Glm5_1 => "GLM 5.1",- Self::Glm5_2 => "GLM 5.2",- Self::Glm5_3 => "GLM 5.3",- Self::GrokBuild0_1 => "Grok Build 0.1",- Self::Grok4_5 => "Grok 4.5",- Self::Grok4_6 => "Grok 4.6",- Self::MuseSpark1_2 => "Muse Spark 1.2",- Self::KimiK2_5 => "Kimi K2.5",- Self::KimiK2_6 => "Kimi K2.6",- Self::KimiK2_7Code => "Kimi K2.7 Code",- Self::KimiK3 => "Kimi K3",- Self::MiniMaxM2_7 => "MiniMax M2.7",- Self::MiniMaxM3 => "MiniMax M3",- Self::MimoV2_5Pro => "MiMo V2.5 Pro",- Self::MimoV2_5 => "MiMo V2.5",- Self::Qwen3_5Plus => "Qwen3.5 Plus",- Self::Qwen3_6Plus => "Qwen3.6 Plus",- Self::Qwen3_7Plus => "Qwen3.7 Plus",- Self::Qwen3_7Max => "Qwen3.7 Max",- Self::Qwen3_8Max => "Qwen3.8 Max",- Self::Hy3 => "Hy3",-- Self::Custom {- name, display_name, ..- } => display_name.as_deref().unwrap_or(name),- }+ self.display_name.as_deref().unwrap_or(&self.name)}- pub fn protocol(&self, subscription: OpenCodeSubscription) -> ApiProtocol {- match self {- // Models offered by OpenCode have the same configuration across subscriptions- // with one outlier: non-free MiniMax models- Self::MiniMaxM3 | Self::MiniMaxM2_7 | Self::MiniMaxM2_5 => {- if subscription == OpenCodeSubscription::Zen {- ApiProtocol::OpenAiChat- } else {- ApiProtocol::Anthropic- }- }-- Self::ClaudeFable5- | Self::ClaudeOpus5- | Self::ClaudeOpus4_8- | Self::ClaudeOpus4_7- | Self::ClaudeOpus4_6- | Self::ClaudeOpus4_5- | Self::ClaudeSonnet5- | Self::ClaudeSonnet4_6- | Self::ClaudeSonnet4_5- | Self::ClaudeSonnet4- | Self::ClaudeHaiku4_5 => ApiProtocol::Anthropic,-- Self::Gpt5_6Sol- | Self::Gpt5_6Terra- | Self::Gpt5_6Luna- | Self::Gpt5_5- | Self::Gpt5_5Pro- | Self::Gpt5_4- | Self::Gpt5_4Pro- | Self::Gpt5_4Mini- | Self::Gpt5_4Nano- | Self::Gpt5_3Codex- | Self::Gpt5_3Spark- | Self::Gpt5_2- | Self::Gpt5_2Codex- | Self::Gpt5_1- | Self::Gpt5_1Codex- | Self::Gpt5_1CodexMax- | Self::Gpt5_1CodexMini- | Self::Gpt5- | Self::Gpt5Codex- | Self::Gpt5Nano => ApiProtocol::OpenAiResponses,-- Self::Gemini3_1Pro- | Self::Gemini3Flash- | Self::Gemini3_5FlashLite- | Self::Gemini3_5Flash- | Self::Gemini3_6Flash- | Self::Gemini3_7Flash => ApiProtocol::Google,-- Self::Qwen3_8Max- | Self::Qwen3_7Max- | Self::Qwen3_7Plus- | Self::Qwen3_6Plus- | Self::Qwen3_5Plus => ApiProtocol::Anthropic,-- Self::Glm5- | Self::Glm5_1- | Self::Glm5_2- | Self::Glm5_3- | Self::GrokBuild0_1- | Self::KimiK2_5- | Self::KimiK2_6- | Self::KimiK2_7Code- | Self::KimiK3- | Self::MimoV2_5Pro- | Self::MimoV2_5- | Self::DeepSeekV4Pro- | Self::DeepSeekV4_1Flash- | Self::Hy3 => ApiProtocol::OpenAiChat,-- Self::Grok4_6 | Self::Grok4_5 | Self::MuseSpark1_2 => ApiProtocol::OpenAiResponses,-- Self::Custom { protocol, .. } => *protocol,- }+ pub fn protocol(&self) -> ApiProtocol {+ self.protocol}pub fn interleaved_reasoning(&self) -> bool {- match self {- Self::DeepSeekV4Pro- | Self::DeepSeekV4_1Flash- | Self::KimiK2_5- | Self::KimiK2_6- | Self::KimiK2_7Code- | Self::KimiK3- | Self::MimoV2_5- | Self::MimoV2_5Pro- | Self::Glm5- | Self::Glm5_1- | Self::Glm5_2- | Self::Glm5_3- | Self::MiniMaxM2_5- | Self::MiniMaxM2_7- | Self::MiniMaxM3 => true,-- Self::Custom {- interleaved_reasoning,- ..- } => *interleaved_reasoning,-- _ => false,- }+ self.interleaved_reasoning}- pub fn max_token_count(&self, subscription: OpenCodeSubscription) -> u64 {- match self {- // Anthropic models- Self::ClaudeOpus5 | Self::ClaudeOpus4_8 | Self::ClaudeOpus4_7 => 1_000_000,- Self::ClaudeOpus4_6 | Self::ClaudeSonnet4_6 => 1_000_000,- Self::ClaudeSonnet4_5 => 1_000_000,- Self::ClaudeOpus4_5 | Self::ClaudeHaiku4_5 => 200_000,- Self::ClaudeSonnet4 => 1_000_000,- Self::ClaudeSonnet5 => 1_000_000,- Self::ClaudeFable5 => 1_000_000,-- // OpenAI models- Self::Gpt5_6Sol | Self::Gpt5_6Terra | Self::Gpt5_6Luna => 1_050_000,- Self::Gpt5_5 | Self::Gpt5_5Pro => 1_050_000,- Self::Gpt5_4 | Self::Gpt5_4Pro => 1_050_000,- Self::Gpt5_4Mini | Self::Gpt5_4Nano => 400_000,- Self::Gpt5_3Codex => 400_000,- Self::Gpt5_3Spark => 128_000,- Self::Gpt5_2 | Self::Gpt5_2Codex => 400_000,- Self::Gpt5_1 | Self::Gpt5_1Codex | Self::Gpt5_1CodexMax | Self::Gpt5_1CodexMini => {- 400_000- }- Self::Gpt5 | Self::Gpt5Codex | Self::Gpt5Nano => 400_000,-- // Google models- Self::Gemini3_1Pro- | Self::Gemini3Flash- | Self::Gemini3_5FlashLite- | Self::Gemini3_5Flash- | Self::Gemini3_6Flash- | Self::Gemini3_7Flash => 1_048_576,-- // OpenAI-compatible models- Self::MiniMaxM2_7 => 204_800,- Self::MiniMaxM3 => {- if subscription == OpenCodeSubscription::Go {- 1_000_000- } else {- 512_000- }- }- Self::MiniMaxM2_5 => 204_800,- Self::Glm5 | Self::Glm5_1 => {- if subscription == OpenCodeSubscription::Go {- 202_752- } else {- 204_800- }- }- Self::Glm5_3 | Self::Glm5_2 => 1_000_000,- Self::KimiK2_6 | Self::KimiK2_5 | Self::KimiK2_7Code => 262_144,- Self::KimiK3 => 1_048_576,- Self::GrokBuild0_1 => 256_000,- Self::Grok4_6 | Self::Grok4_5 => 500_000,- Self::MuseSpark1_2 => 1_048_576,- Self::MimoV2_5Pro => 1_048_576,- Self::MimoV2_5 => 1_000_000,- Self::Qwen3_5Plus => 262_144,- Self::Qwen3_6Plus => {- if subscription == OpenCodeSubscription::Go {- 1_000_000- } else {- 262_144- }- }- Self::Qwen3_8Max | Self::Qwen3_7Max | Self::Qwen3_7Plus => 1_000_000,- Self::Hy3 => 256_000,- Self::DeepSeekV4Pro | Self::DeepSeekV4_1Flash => 1_000_000,-- Self::Custom { max_tokens, .. } => *max_tokens,- }+ pub fn max_token_count(&self) -> u64 {+ self.max_tokens}- pub fn max_output_tokens(&self, subscription: OpenCodeSubscription) -> Option<u64> {- match self {- // Anthropic models- Self::ClaudeOpus5 | Self::ClaudeOpus4_8 | Self::ClaudeOpus4_7 | Self::ClaudeOpus4_6 => {- Some(128_000)- }- Self::ClaudeOpus4_5- | Self::ClaudeSonnet4_6- | Self::ClaudeSonnet4_5- | Self::ClaudeHaiku4_5- | Self::ClaudeSonnet4 => Some(64_000),- Self::ClaudeSonnet5 => Some(128_000),- Self::ClaudeFable5 => Some(128_000),-- // OpenAI models- Self::Gpt5_6Sol- | Self::Gpt5_6Terra- | Self::Gpt5_6Luna- | Self::Gpt5_5- | Self::Gpt5_5Pro- | Self::Gpt5_4- | Self::Gpt5_4Pro- | Self::Gpt5_4Mini- | Self::Gpt5_4Nano- | Self::Gpt5_3Codex- | Self::Gpt5_3Spark- | Self::Gpt5_2- | Self::Gpt5_2Codex- | Self::Gpt5_1- | Self::Gpt5_1Codex- | Self::Gpt5_1CodexMax- | Self::Gpt5_1CodexMini- | Self::Gpt5- | Self::Gpt5Codex- | Self::Gpt5Nano => Some(128_000),-- // Google models- Self::Gemini3_1Pro- | Self::Gemini3Flash- | Self::Gemini3_5FlashLite- | Self::Gemini3_5Flash- | Self::Gemini3_6Flash- | Self::Gemini3_7Flash => Some(65_536),-- // OpenAI-compatible models- Self::MiniMaxM2_7 => Some(131_072),- Self::MiniMaxM3 => {- if subscription == OpenCodeSubscription::Go {- Some(131_072)- } else {- Some(128_000)- }- }- Self::MiniMaxM2_5 => {- if subscription == OpenCodeSubscription::Go {- Some(65_536)- } else {- Some(131_072)- }- }- Self::Glm5 | Self::Glm5_1 => {- if subscription == OpenCodeSubscription::Go {- Some(32_768)- } else {- Some(131_072)- }- }- Self::Glm5_3 | Self::Glm5_2 => Some(131_072),- Self::KimiK2_6 | Self::KimiK2_5 => Some(65_536),- Self::KimiK2_7Code => Some(262_144),- Self::KimiK3 => Some(131_072),- Self::GrokBuild0_1 => Some(256_000),- Self::Grok4_6 | Self::Grok4_5 => Some(500_000),- Self::MuseSpark1_2 => Some(131_072),- Self::Qwen3_7Max | Self::Qwen3_7Plus | Self::Qwen3_6Plus | Self::Qwen3_5Plus => {- Some(65_536)- }- Self::Qwen3_8Max => Some(131_072),- Self::DeepSeekV4Pro | Self::DeepSeekV4_1Flash => Some(384_000),- Self::MimoV2_5Pro | Self::MimoV2_5 => Some(128_000),- Self::Hy3 => Some(64_000),-- Self::Custom {- max_output_tokens, ..- } => *max_output_tokens,- }+ pub fn max_output_tokens(&self) -> Option<u64> {+ self.max_output_tokens}pub fn supports_tools(&self) -> bool {true}- pub fn supports_images(&self) -> bool {- match self {- // Anthropic models support images- Self::ClaudeOpus5- | Self::ClaudeOpus4_8- | Self::ClaudeOpus4_7- | Self::ClaudeOpus4_6- | Self::ClaudeOpus4_5- | Self::ClaudeSonnet4_6- | Self::ClaudeSonnet4_5- | Self::ClaudeSonnet4- | Self::ClaudeHaiku4_5- | Self::ClaudeSonnet5- | Self::ClaudeFable5 => true,-- // OpenAI models support images- Self::Gpt5_6Sol- | Self::Gpt5_6Terra- | Self::Gpt5_6Luna- | Self::Gpt5_5- | Self::Gpt5_5Pro- | Self::Gpt5_4- | Self::Gpt5_4Pro- | Self::Gpt5_4Mini- | Self::Gpt5_4Nano- | Self::Gpt5_3Codex- | Self::Gpt5_2- | Self::Gpt5_2Codex- | Self::Gpt5_1- | Self::Gpt5_1Codex- | Self::Gpt5_1CodexMax- | Self::Gpt5_1CodexMini- | Self::Gpt5- | Self::Gpt5Codex- | Self::Gpt5Nano => true,-- // OpenAI models without image support- Self::Gpt5_3Spark => false,-- // Google models support images- Self::Gemini3_1Pro- | Self::Gemini3Flash- | Self::Gemini3_5FlashLite- | Self::Gemini3_5Flash- | Self::Gemini3_6Flash- | Self::Gemini3_7Flash => true,-- // OpenAI-compatible models with image support- Self::KimiK2_6- | Self::KimiK3- | Self::KimiK2_7Code- | Self::KimiK2_5- | Self::GrokBuild0_1- | Self::Grok4_5- | Self::Grok4_6- | Self::MuseSpark1_2- | Self::MimoV2_5- | Self::Qwen3_5Plus- | Self::Qwen3_6Plus- | Self::Qwen3_7Plus- | Self::Qwen3_8Max- | Self::MiniMaxM3- | Self::DeepSeekV4_1Flash => true,-- // OpenAI-compatible models without image support- Self::MiniMaxM2_5- | Self::Glm5- | Self::Glm5_1- | Self::Glm5_2- | Self::Glm5_3- | Self::MiniMaxM2_7- | Self::MimoV2_5Pro- | Self::DeepSeekV4Pro- | Self::Qwen3_7Max- | Self::Hy3 => false,-- Self::Custom { protocol, .. } => matches!(- protocol,- ApiProtocol::Anthropic- | ApiProtocol::OpenAiResponses- | ApiProtocol::OpenAiChat- | ApiProtocol::Google- ),- }+ pub fn supported_reasoning_effort_levels(&self) -> Option<&[ReasoningEffort]> {+ self.reasoning_effort_levels.as_deref()}- pub fn supported_reasoning_effort_levels(&self) -> Option<Vec<ReasoningEffort>> {- match self {- // Anthropic models- Self::ClaudeFable5- | Self::ClaudeOpus5- | Self::ClaudeOpus4_8- | Self::ClaudeOpus4_7- | Self::ClaudeSonnet5 => Some(vec![- ReasoningEffort::Low,- ReasoningEffort::Medium,- ReasoningEffort::High,- ReasoningEffort::XHigh,- ReasoningEffort::Max,- ]),-- Self::ClaudeOpus4_6 | Self::ClaudeSonnet4_6 => Some(vec![- ReasoningEffort::Low,- ReasoningEffort::Medium,- ReasoningEffort::High,- ReasoningEffort::Max,- ]),-- Self::ClaudeOpus4_5 => Some(vec![- ReasoningEffort::Low,- ReasoningEffort::Medium,- ReasoningEffort::High,- ]),-- // OpenAI models- Self::Gpt5_5- | Self::Gpt5_4- | Self::Gpt5_4Mini- | Self::Gpt5_4Nano- | Self::Gpt5_3Codex- | Self::Gpt5_2 => Some(vec![- ReasoningEffort::None,- ReasoningEffort::Low,- ReasoningEffort::Medium,- ReasoningEffort::High,- ReasoningEffort::XHigh,- ]),-- Self::Gpt5_5Pro | Self::Gpt5_4Pro => Some(vec![- ReasoningEffort::Medium,- ReasoningEffort::High,- ReasoningEffort::XHigh,- ]),-- Self::Gpt5_2Codex | Self::Gpt5_3Spark | Self::Gpt5_1CodexMax => Some(vec![- ReasoningEffort::Low,- ReasoningEffort::Medium,- ReasoningEffort::High,- ReasoningEffort::XHigh,- ]),-- Self::Gpt5_1 => Some(vec![- ReasoningEffort::None,- ReasoningEffort::Low,- ReasoningEffort::Medium,- ReasoningEffort::High,- ]),-- Self::Gpt5Codex | Self::Gpt5_1Codex | Self::Gpt5_1CodexMini => Some(vec![- ReasoningEffort::Low,- ReasoningEffort::Medium,- ReasoningEffort::High,- ]),-- Self::Gpt5 | Self::Gpt5Nano => Some(vec![- ReasoningEffort::Minimal,- ReasoningEffort::Low,- ReasoningEffort::Medium,- ReasoningEffort::High,- ]),-- Self::Gpt5_6Sol | Self::Gpt5_6Terra | Self::Gpt5_6Luna => Some(vec![- ReasoningEffort::None,- ReasoningEffort::Low,- ReasoningEffort::Medium,- ReasoningEffort::High,- ReasoningEffort::XHigh,- ReasoningEffort::Max,- ]),-- // Google models- Self::Gemini3Flash- | Self::Gemini3_5FlashLite- | Self::Gemini3_5Flash- | Self::Gemini3_6Flash => Some(vec![- ReasoningEffort::Minimal,- ReasoningEffort::Low,- ReasoningEffort::Medium,- ReasoningEffort::High,- ]),-- Self::Gemini3_7Flash | Self::Gemini3_1Pro => Some(vec![- ReasoningEffort::Low,- ReasoningEffort::Medium,- ReasoningEffort::High,- ]),-- // DeepSeek models- Self::DeepSeekV4Pro | Self::DeepSeekV4_1Flash => Some(vec![- // OpenCode also supports Low&Medium but as per DeepSeek those are mapped to High- ReasoningEffort::High,- ReasoningEffort::Max,- ]),-- // Moonshot AI models- Self::KimiK3 => Some(vec![ReasoningEffort::Max]),-- // MiniMax models- Self::MiniMaxM3 => Some(vec![ReasoningEffort::None]),-- // Xiaomi MiMo models- Self::MimoV2_5Pro | Self::MimoV2_5 => Some(vec![- ReasoningEffort::Low,- ReasoningEffort::Medium,- ReasoningEffort::High,- ]),-- // Z AI models- Self::Glm5_2 => Some(vec![ReasoningEffort::High, ReasoningEffort::Max]),-- Self::Glm5_3 => Some(vec![- ReasoningEffort::Low,- ReasoningEffort::High,- ReasoningEffort::Max,- ]),-- // Tencent models- Self::Hy3 => Some(vec![- ReasoningEffort::None,- ReasoningEffort::Low,- ReasoningEffort::High,- ]),-- // SpaceXAI models- Self::Grok4_6 => Some(vec![- ReasoningEffort::Low,- ReasoningEffort::Medium,- ReasoningEffort::High,- ReasoningEffort::XHigh,- ]),-- Self::Grok4_5 => Some(vec![- ReasoningEffort::Low,- ReasoningEffort::Medium,- ReasoningEffort::High,- ]),-- // Meta AI models- Self::MuseSpark1_2 => Some(vec![- ReasoningEffort::Minimal,- ReasoningEffort::Low,- ReasoningEffort::Medium,- ReasoningEffort::High,- ReasoningEffort::XHigh,- ]),-- Self::Custom {- reasoning_effort_levels,- ..- } => reasoning_effort_levels.clone(),-- _ => None,- }+ pub fn custom_model_api_url(&self) -> Option<&str> {+ self.custom_model_api_url.as_deref()}}-/// Stream generate content for Google models via OpenCode.-///-/// Unlike `google_ai::stream_generate_content()`, this uses:-/// - `/v1/models/{model}` path (not `/v1beta/models/{model}`)-/// - `Authorization: Bearer` header (not `key=` query param)+/// Streams Google generate-content responses through OpenCode.pub async fn stream_generate_content(client: &dyn HttpClient,api_url: &str,@@ -938,11 +137,8 @@ pub async fn stream_generate_content(extra_headers: &CustomHeaders,) -> Result<BoxStream<'static, Result<google_ai::GenerateContentResponse>>> {let api_key = api_key.trim();-let model_id = &request.model.model_id;-let uri = format!("{api_url}/v1/models/{model_id}:streamGenerateContent?alt=sse");-let request = HttpRequest::builder().method(Method::POST).uri(uri)diff --git a/docs/src/ai/use-api-access.md b/docs/src/ai/use-api-access.mdindex e6770d5106f..7f29d728ca3 100644--- a/docs/src/ai/use-api-access.md+++ b/docs/src/ai/use-api-access.md@@ -359,13 +359,15 @@ Zed does not sign in to OpenCode with OAuth or detect your OpenCode subscriptionZed also reads `OPENCODE_API_KEY` from the local Zed process environment.-By default, models from all OpenCode subscription types are shown. You can hide subscriptions that are not relevant to you in the provider UI or in settings:+Zed fetches the available Zen and Go models and their capabilities from OpenCode. OpenCode Free models are excluded since they are only allowed to be used from within OpenCode.++By default, both Zen and Go models are shown. You can hide Zen or Go models by adding this to your settings file:```json [settings]{"language_models": {"opencode": {- "show_zen_models": false,+ "show_zen_models": true,"show_go_models": true}}@@ -374,7 +376,7 @@ By default, models from all OpenCode subscription types are shown. You can hide#### Custom OpenCode Models {#opencode-custom-models}-The Zed Agent comes preconfigured with OpenCode models. Add custom OpenCode models when you need newer models or models with custom endpoints.+Add a custom OpenCode model to use a custom endpoint or configure a model that discovery does not include. A custom entry overrides a fetched model with the same `name` and `subscription`.Add custom models in your settings file: