Files
zed/crates/settings_content/src/language_model.rs
T
Vlad IonescuandBen Brandt f59c122bee opencode: Add support for OpenCode Go (#53651)
**TL;DR**: add support for OpenCode Go (flat-rate monthly subscription)
along the already-implemented OpenCode Zed (pay-as-you-go billing).

> [!WARNING]
> This code was written by LLMs, under the supervision of a so-called
developer that never wrote Rust profesionally and that spends more time
in Pages&Keynote than in an IDE.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

## Background

OpenCode offers a few different ways to access models:
- **free access to 3 models**, with feedback and data used to improve
the model. These models use the OpenCode Zen API endpoints, but have
different usage limits (200 requests per 5 hours) and have a different
privacy policy. Some people disable or block the free models, some
people are super-excited to have access to LLMs for free, and some
people like using the free models to test new LLMs (at launch MiMo-V2
had 2 free weeks of usage, for example).
- **pay-as-you-go access to 30 models** as part of the [OpenCode
Zen](https://opencode.ai/zen) subscription. These models use the same
OpenCode Zen API endpoints.
- **flat-rate monthly access to 7 models** as part of the [OpenCode
Go](https://opencode.ai/go) subscription. These models use the OpenCode
Zen API endpoints with an extra `/go` appended to the path. There are
5-hour, weekly, and monthly usage limits and, additionally, users can
toggle a switch in the OpenCode Console to use Zen models with their
pay-as-you-go billing after the Go limits are hit.

There's also a currently-paused [OpenCode
Black](https://opencode.ai/black) flat-rate subscription with way higher
usage limits and with access to more models, with $100 and $200 monthly
plans.

The whole thing is a bit messy, but it's great value and highly reliable
LLM access!

<br>

https://github.com/zed-industries/zed/pull/49589 added support for
OpenCode Zen by implementing a new `opencode` provider. OpenCode Go
[could be used by overriding the API
URL](https://github.com/zed-industries/zed/pull/49589#issuecomment-4130300454),
but that is a terrible user experience: some models have to be manually
added, the model list always shows the 30-something OpenCode Zen models,
and free models cannot be used at all.

I was annoyed by the experience of using OpenCode Go with Zed and this
past week I had to test a bunch of LLMs and providers and harnesses, so
I took this on as a test case 🙂

## Implementation

This PR makes the OpenCode provider more general (not just for Zen) and
adds an `OpenCodeModelSubscription` concept which is then used to
implement support for OpenCode Go. The free models are also broken out
into their own subscription for a prettier model list.

For a better user experience, the different subscriptions can be enabled
or disabled, both in the settings file and in the UX:
<img width="434" height="176" alt="Screenshot showing the OpenCode
provider configuration, with the newly added toggles"
src="https://github.com/user-attachments/assets/3520e114-00c8-4794-84bf-35cd72d9c57e"
/>


The code was written by LLMs, but I do understand it and I did a bunch
of "manual" iterations and "manual" tweaks. Still, my Rust experience is
non-existent so **I won't feel offended if y'all reject this PR**! I did
consider alternatives (adding a new `opencode-go` provider and renaming
this to `opencode-zen`, for example, or adding support for custom API
URLs in OpenCode custom models which would've been the smallest code
change but a terrible user experience, and so on) but all alternatives
would have been, in my opinion, a worse user experience.

**Tests I did**:
- confirmed OpenCode Go models work as expected
- confirmed OpenCode Zen Free models work as expected
- confirmed I get an error when trying to use OpenCode Zen models since
I don't have that subscription
- confirmed the subcription toggles work as expected (model are
shown/hidden, settings file is updated)

**Notes**:
- this PR is best reviewed commit-by-commit. I did not create a separate
PR for the model updates to minimize delays
- my exeprience with Rust is roughly zero, but I tried to strike a
balance between idiomatic Rust and easy-to-read code
- users of the OpenCode provider might have to do some re-configuration
after this PR is merged since the model identifiers now include the
subscription, eg `claude-haiku-4-5` is now `zen/claude-haiku-4-5`. Since
this is a relatively new provider and the impact is small, I preffered
that rather than adding complex migration/mapping logic.
- does changing the provider name from "OpenCode Zen" to "OpenCode"
break anything for y'all at Zed?
- does changing the telemetry id from `"opencode/<model-id>"` to
`"opencode/<subscription>/<model-id>"` break anything for y'all at Zed?

---

Release Notes:
- OpenCode provider: add support for OpenCode Go

---------

Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
2026-04-24 14:17:30 +00:00

510 lines
17 KiB
Rust

use crate::merge_from::MergeFrom;
use collections::HashMap;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use settings_macros::{MergeFrom, with_fallible_options};
use std::sync::Arc;
#[with_fallible_options]
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
pub struct AllLanguageModelSettingsContent {
pub anthropic: Option<AnthropicSettingsContent>,
pub bedrock: Option<AmazonBedrockSettingsContent>,
pub deepseek: Option<DeepseekSettingsContent>,
pub google: Option<GoogleSettingsContent>,
pub lmstudio: Option<LmStudioSettingsContent>,
pub mistral: Option<MistralSettingsContent>,
pub ollama: Option<OllamaSettingsContent>,
pub opencode: Option<OpenCodeSettingsContent>,
pub open_router: Option<OpenRouterSettingsContent>,
pub openai: Option<OpenAiSettingsContent>,
pub openai_compatible: Option<HashMap<Arc<str>, OpenAiCompatibleSettingsContent>>,
pub vercel: Option<VercelSettingsContent>,
pub vercel_ai_gateway: Option<VercelAiGatewaySettingsContent>,
pub x_ai: Option<XAiSettingsContent>,
#[serde(rename = "zed.dev")]
pub zed_dot_dev: Option<ZedDotDevSettingsContent>,
}
#[with_fallible_options]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
pub struct AnthropicSettingsContent {
pub api_url: Option<String>,
pub available_models: Option<Vec<AnthropicAvailableModel>>,
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct AnthropicAvailableModel {
/// The model's name in the Anthropic API. e.g. claude-3-5-sonnet-latest, claude-3-opus-20240229, etc
pub name: String,
/// The model's name in Zed's UI, such as in the model selector dropdown menu in the agent panel.
pub display_name: Option<String>,
/// The model's context window size.
pub max_tokens: u64,
/// A model `name` to substitute when calling tools, in case the primary model doesn't support tool calling.
pub tool_override: Option<String>,
/// Configuration of Anthropic's caching API.
pub cache_configuration: Option<LanguageModelCacheConfiguration>,
pub max_output_tokens: Option<u64>,
#[serde(serialize_with = "crate::serialize_optional_f32_with_two_decimal_places")]
pub default_temperature: Option<f32>,
#[serde(default)]
pub extra_beta_headers: Vec<String>,
/// The model's mode (e.g. thinking)
pub mode: Option<ModelMode>,
}
#[with_fallible_options]
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
pub struct AmazonBedrockSettingsContent {
pub available_models: Option<Vec<BedrockAvailableModel>>,
pub endpoint_url: Option<String>,
pub region: Option<String>,
pub profile: Option<String>,
pub authentication_method: Option<BedrockAuthMethodContent>,
pub allow_global: Option<bool>,
/// Enable the 1M token extended context window beta for supported Anthropic models.
pub allow_extended_context: Option<bool>,
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct BedrockAvailableModel {
pub name: String,
pub display_name: Option<String>,
pub max_tokens: u64,
pub cache_configuration: Option<LanguageModelCacheConfiguration>,
pub max_output_tokens: Option<u64>,
#[serde(serialize_with = "crate::serialize_optional_f32_with_two_decimal_places")]
pub default_temperature: Option<f32>,
pub mode: Option<ModelMode>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub enum BedrockAuthMethodContent {
#[serde(rename = "named_profile")]
NamedProfile,
#[serde(rename = "sso")]
SingleSignOn,
#[serde(rename = "api_key")]
ApiKey,
/// IMDSv2, PodIdentity, env vars, etc.
#[serde(rename = "default")]
Automatic,
}
#[with_fallible_options]
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
pub struct OllamaSettingsContent {
pub api_url: Option<String>,
pub auto_discover: Option<bool>,
pub available_models: Option<Vec<OllamaAvailableModel>>,
pub context_window: Option<u64>,
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct OllamaAvailableModel {
/// The model name in the Ollama API (e.g. "llama3.2:latest")
pub name: String,
/// The model's name in Zed's UI, such as in the model selector dropdown menu in the agent panel.
pub display_name: Option<String>,
/// The Context Length parameter to the model (aka num_ctx or n_ctx)
pub max_tokens: u64,
/// The number of seconds to keep the connection open after the last request
pub keep_alive: Option<KeepAlive>,
/// Whether the model supports tools
pub supports_tools: Option<bool>,
/// Whether the model supports vision
pub supports_images: Option<bool>,
/// Whether to enable think mode
pub supports_thinking: Option<bool>,
}
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq, JsonSchema, MergeFrom)]
#[serde(untagged)]
pub enum KeepAlive {
/// Keep model alive for N seconds
Seconds(isize),
/// Keep model alive for a fixed duration. Accepts durations like "5m", "10m", "1h", "1d", etc.
Duration(String),
}
impl KeepAlive {
/// Keep model alive until a new model is loaded or until Ollama shuts down
pub fn indefinite() -> Self {
Self::Seconds(-1)
}
}
impl Default for KeepAlive {
fn default() -> Self {
Self::indefinite()
}
}
#[with_fallible_options]
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
pub struct OpenCodeSettingsContent {
pub api_url: Option<String>,
pub available_models: Option<Vec<OpenCodeAvailableModel>>,
/// Whether to show OpenCode Zen models. Defaults to true.
pub show_zen_models: Option<bool>,
/// Whether to show OpenCode Go models. Defaults to true.
pub show_go_models: Option<bool>,
/// Whether to show OpenCode Free models. Defaults to true.
pub show_free_models: Option<bool>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom)]
#[serde(rename_all = "snake_case")]
pub enum OpenCodeModelSubscription {
Zen,
Go,
Free,
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct OpenCodeAvailableModel {
pub name: String,
pub display_name: Option<String>,
pub max_tokens: u64,
pub max_output_tokens: Option<u64>,
/// The API protocol to use for this model: "anthropic", "openai_responses", "openai_chat", or "google".
pub protocol: String,
/// The subscription for this model: "zen", "go", or "free". Defaults to Zen.
pub subscription: Option<OpenCodeModelSubscription>,
/// Custom Model API URL to use for this model.
pub custom_model_api_url: Option<String>,
}
#[with_fallible_options]
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
pub struct LmStudioSettingsContent {
pub api_url: Option<String>,
pub api_key: Option<String>,
pub available_models: Option<Vec<LmStudioAvailableModel>>,
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct LmStudioAvailableModel {
pub name: String,
pub display_name: Option<String>,
pub max_tokens: u64,
pub supports_tool_calls: bool,
pub supports_images: bool,
}
#[with_fallible_options]
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
pub struct DeepseekSettingsContent {
pub api_url: Option<String>,
pub available_models: Option<Vec<DeepseekAvailableModel>>,
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct DeepseekAvailableModel {
pub name: String,
pub display_name: Option<String>,
pub max_tokens: u64,
pub max_output_tokens: Option<u64>,
}
#[with_fallible_options]
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
pub struct MistralSettingsContent {
pub api_url: Option<String>,
pub available_models: Option<Vec<MistralAvailableModel>>,
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct MistralAvailableModel {
pub name: String,
pub display_name: Option<String>,
pub max_tokens: u64,
pub max_output_tokens: Option<u64>,
pub max_completion_tokens: Option<u64>,
pub supports_tools: Option<bool>,
pub supports_images: Option<bool>,
pub supports_thinking: Option<bool>,
}
#[with_fallible_options]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
pub struct OpenAiSettingsContent {
pub api_url: Option<String>,
pub available_models: Option<Vec<OpenAiAvailableModel>>,
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct OpenAiAvailableModel {
pub name: String,
pub display_name: Option<String>,
pub max_tokens: u64,
pub max_output_tokens: Option<u64>,
pub max_completion_tokens: Option<u64>,
pub reasoning_effort: Option<OpenAiReasoningEffort>,
#[serde(default)]
pub capabilities: OpenAiModelCapabilities,
}
pub use language_model_core::ReasoningEffort as OpenAiReasoningEffort;
impl MergeFrom for OpenAiReasoningEffort {
fn merge_from(&mut self, other: &Self) {
*self = *other;
}
}
#[with_fallible_options]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
pub struct OpenAiCompatibleSettingsContent {
pub api_url: String,
pub available_models: Vec<OpenAiCompatibleAvailableModel>,
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct OpenAiModelCapabilities {
#[serde(default = "default_true")]
pub chat_completions: bool,
#[serde(default = "default_true")]
pub images: bool,
}
impl Default for OpenAiModelCapabilities {
fn default() -> Self {
Self {
chat_completions: default_true(),
images: default_true(),
}
}
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct OpenAiCompatibleAvailableModel {
pub name: String,
pub display_name: Option<String>,
pub max_tokens: u64,
pub max_output_tokens: Option<u64>,
pub max_completion_tokens: Option<u64>,
pub reasoning_effort: Option<OpenAiReasoningEffort>,
#[serde(default)]
pub capabilities: OpenAiCompatibleModelCapabilities,
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct OpenAiCompatibleModelCapabilities {
pub tools: bool,
pub images: bool,
pub parallel_tool_calls: bool,
pub prompt_cache_key: bool,
#[serde(default = "default_true")]
pub chat_completions: bool,
#[serde(default)]
pub interleaved_reasoning: bool,
}
impl Default for OpenAiCompatibleModelCapabilities {
fn default() -> Self {
Self {
tools: true,
images: false,
parallel_tool_calls: false,
prompt_cache_key: false,
chat_completions: default_true(),
interleaved_reasoning: false,
}
}
}
#[with_fallible_options]
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
pub struct VercelSettingsContent {
pub api_url: Option<String>,
pub available_models: Option<Vec<VercelAvailableModel>>,
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct VercelAvailableModel {
pub name: String,
pub display_name: Option<String>,
pub max_tokens: u64,
pub max_output_tokens: Option<u64>,
pub max_completion_tokens: Option<u64>,
}
#[with_fallible_options]
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
pub struct VercelAiGatewaySettingsContent {
pub api_url: Option<String>,
pub available_models: Option<Vec<VercelAiGatewayAvailableModel>>,
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct VercelAiGatewayAvailableModel {
pub name: String,
pub display_name: Option<String>,
pub max_tokens: u64,
pub max_output_tokens: Option<u64>,
pub max_completion_tokens: Option<u64>,
#[serde(default)]
pub capabilities: OpenAiCompatibleModelCapabilities,
}
#[with_fallible_options]
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
pub struct GoogleSettingsContent {
pub api_url: Option<String>,
pub available_models: Option<Vec<GoogleAvailableModel>>,
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct GoogleAvailableModel {
pub name: String,
pub display_name: Option<String>,
pub max_tokens: u64,
pub mode: Option<ModelMode>,
}
#[with_fallible_options]
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
pub struct XAiSettingsContent {
pub api_url: Option<String>,
pub available_models: Option<Vec<XaiAvailableModel>>,
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct XaiAvailableModel {
pub name: String,
pub display_name: Option<String>,
pub max_tokens: u64,
pub max_output_tokens: Option<u64>,
pub max_completion_tokens: Option<u64>,
pub supports_images: Option<bool>,
pub supports_tools: Option<bool>,
pub parallel_tool_calls: Option<bool>,
}
#[with_fallible_options]
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
pub struct ZedDotDevSettingsContent {
pub available_models: Option<Vec<ZedDotDevAvailableModel>>,
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct ZedDotDevAvailableModel {
/// The provider of the language model.
pub provider: ZedDotDevAvailableProvider,
/// The model's name in the provider's API. e.g. claude-3-5-sonnet-20240620
pub name: String,
/// The name displayed in the UI, such as in the agent panel model dropdown menu.
pub display_name: Option<String>,
/// The size of the context window, indicating the maximum number of tokens the model can process.
pub max_tokens: usize,
/// The maximum number of output tokens allowed by the model.
pub max_output_tokens: Option<u64>,
/// The maximum number of completion tokens allowed by the model (o1-* only)
pub max_completion_tokens: Option<u64>,
/// Override this model with a different Anthropic model for tool calls.
pub tool_override: Option<String>,
/// Indicates whether this custom model supports caching.
pub cache_configuration: Option<LanguageModelCacheConfiguration>,
/// The default temperature to use for this model.
#[serde(serialize_with = "crate::serialize_optional_f32_with_two_decimal_places")]
pub default_temperature: Option<f32>,
/// Any extra beta headers to provide when using the model.
#[serde(default)]
pub extra_beta_headers: Vec<String>,
/// The model's mode (e.g. thinking)
pub mode: Option<ModelMode>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
#[serde(rename_all = "lowercase")]
pub enum ZedDotDevAvailableProvider {
Anthropic,
OpenAi,
Google,
}
#[with_fallible_options]
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
pub struct OpenRouterSettingsContent {
pub api_url: Option<String>,
pub available_models: Option<Vec<OpenRouterAvailableModel>>,
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct OpenRouterAvailableModel {
pub name: String,
pub display_name: Option<String>,
pub max_tokens: u64,
pub max_output_tokens: Option<u64>,
pub max_completion_tokens: Option<u64>,
pub supports_tools: Option<bool>,
pub supports_images: Option<bool>,
pub mode: Option<ModelMode>,
pub provider: Option<OpenRouterProvider>,
}
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct OpenRouterProvider {
order: Option<Vec<String>>,
#[serde(default = "default_true")]
allow_fallbacks: bool,
#[serde(default)]
require_parameters: bool,
#[serde(default)]
data_collection: DataCollection,
only: Option<Vec<String>>,
ignore: Option<Vec<String>>,
quantizations: Option<Vec<String>>,
sort: Option<String>,
}
#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
#[serde(rename_all = "lowercase")]
pub enum DataCollection {
#[default]
Allow,
Disallow,
}
fn default_true() -> bool {
true
}
/// Configuration for caching language model messages.
#[with_fallible_options]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
pub struct LanguageModelCacheConfiguration {
pub max_cache_anchors: usize,
pub should_speculate: bool,
pub min_total_token: u64,
}
pub use language_model_core::ModelMode;
impl MergeFrom for ModelMode {
fn merge_from(&mut self, other: &Self) {
*self = *other;
}
}