Skip to main content

adk_model/opencode/
mod.rs

1//! OpenCode Go and Zen integration using the existing protocol clients.
2//!
3//! Enable the `opencode` feature. API selection follows the published
4//! endpoint table for each service; unknown models
5//! require an explicit API selection. No network request is made during construction.
6
7mod config;
8pub use config::{OpenCodeApi, OpenCodeConfig};
9mod service;
10pub use service::OpenCodeService;
11
12use crate::anthropic::{AnthropicClient, AnthropicConfig};
13use crate::gemini::GeminiModel;
14use crate::openai::{OpenAIResponsesClient, OpenAIResponsesConfig};
15use crate::openai_compatible::{OpenAICompatible, OpenAICompatibleConfig};
16use adk_core::{
17    AdkError, ErrorCategory, ErrorComponent, Llm, LlmRequest, LlmResponseStream, SchemaAdapter,
18};
19use async_trait::async_trait;
20use http::header::{HeaderMap, HeaderValue, USER_AGENT};
21use std::sync::Arc;
22
23/// An OpenCode model bound to one conversation.
24///
25/// The selected protocol client owns wire conversion, streaming, usage, errors,
26/// and tool calls. The OpenCode adapter supplies routing and conversation headers.
27///
28/// # Example
29///
30/// ```no_run
31/// use adk_model::opencode::{OpenCodeClient, OpenCodeConfig, OpenCodeService};
32/// let model = OpenCodeClient::new(
33///     OpenCodeConfig::new(OpenCodeService::Go, std::env::var("OPENCODE_API_KEY")?, "deepseek-v4.1-flash")
34///         .with_user_agent("example-coding-agent/1.0")
35///         .with_session_id("conversation-42"),
36/// )?;
37/// # Ok::<(), Box<dyn std::error::Error>>(())
38/// ```
39pub struct OpenCodeClient {
40    inner: Arc<dyn Llm>,
41    api: OpenCodeApi,
42    provider: &'static str,
43}
44
45impl OpenCodeClient {
46    /// Builds an OpenCode client using the configured model's API.
47    ///
48    /// # Errors
49    ///
50    /// Returns an `InvalidInput` error with code `model.opencode.invalid_config` for an
51    /// empty API key, missing client/session identity, invalid HTTP headers or base URL,
52    /// unknown models without an explicit API, or reasoning settings for a different
53    /// API. Errors from building the selected protocol client are returned unchanged.
54    pub fn new(config: OpenCodeConfig) -> Result<Self, AdkError> {
55        let service = config.service;
56        let invalid = |message: &str| {
57            AdkError::new(
58                ErrorComponent::Model,
59                ErrorCategory::InvalidInput,
60                "model.opencode.invalid_config",
61                message,
62            )
63            .with_provider(service.provider())
64        };
65        let api = config.api.or_else(|| service.api(&config.model)).ok_or_else(|| {
66            invalid("unknown OpenCode model; select its documented API with with_api")
67        })?;
68        if config.api_key.trim().is_empty() {
69            return Err(invalid("OpenCode API key must not be empty"));
70        }
71        let mut endpoint = reqwest::Url::parse(&config.base_url)
72            .map_err(|_| invalid("invalid OpenCode base URL"))?;
73        let local = endpoint.host_str().is_some_and(|host| {
74            host == "localhost"
75                || host
76                    .trim_matches(['[', ']'])
77                    .parse::<std::net::IpAddr>()
78                    .is_ok_and(|ip| ip.is_loopback())
79        });
80        // `Url::parse` silently drops surrounding whitespace and embedded tabs or
81        // newlines, so such input is rejected rather than reinterpreted.
82        let valid = !config.base_url.contains(|c: char| c.is_whitespace() || c.is_control())
83            && (endpoint.scheme() == "https" || endpoint.scheme() == "http" && local)
84            && endpoint.username().is_empty()
85            && endpoint.password().is_none()
86            && endpoint.query().is_none()
87            && endpoint.fragment().is_none();
88        endpoint.set_path(&format!("{}/", endpoint.path().trim_end_matches('/')));
89        let base_url = endpoint.as_str().trim_end_matches('/').to_owned();
90        let (true, Some(root)) = (valid, base_url.strip_suffix("/v1")) else {
91            return Err(invalid(
92                "OpenCode base URL must use HTTPS (or loopback HTTP), end in /v1, and contain no whitespace, credentials, query, or fragment",
93            ));
94        };
95        let mut headers = HeaderMap::new();
96        for (name, value) in [
97            (USER_AGENT, &config.user_agent),
98            (http::header::HeaderName::from_static("x-opencode-session"), &config.session_id),
99        ] {
100            if value.trim().is_empty() {
101                return Err(invalid(
102                    "OpenCode requires a nonempty user agent and stable session ID",
103                ));
104            }
105            headers.insert(
106                name,
107                HeaderValue::from_str(value).map_err(|_| {
108                    invalid("OpenCode client/session identity must be a valid HTTP header value")
109                })?,
110            );
111        }
112        let inner: Arc<dyn Llm> = match api {
113            OpenCodeApi::ChatCompletions | OpenCodeApi::Responses => {
114                if config.thinking.is_some()
115                    || config.anthropic_effort.is_some()
116                    || config.gemini_thinking.is_some()
117                {
118                    return Err(invalid("Chat and Responses reasoning uses with_reasoning_effort"));
119                }
120                if api == OpenCodeApi::ChatCompletions {
121                    let mut client = OpenAICompatible::new_with_reasoning_effort(
122                        OpenAICompatibleConfig::new(config.api_key, config.model)
123                            .with_base_url(base_url)
124                            .with_provider_name(service.provider()),
125                        config.reasoning_effort,
126                    )?;
127                    if let Some(timeouts) = config.timeouts {
128                        client = client.with_timeouts(timeouts)?;
129                    }
130                    Arc::new(
131                        client
132                            .with_reasoning_replay(true)
133                            .with_default_headers(headers)?
134                            .with_retry_config(config.retry),
135                    )
136                } else {
137                    let native = OpenAIResponsesConfig::new(config.api_key, config.model)
138                        .with_base_url(base_url)
139                        .with_open_responses_mode(true);
140                    let mut client = match config.reasoning_effort {
141                        Some(effort) => {
142                            OpenAIResponsesClient::new_with_reasoning_effort(native, effort)
143                        }
144                        None => OpenAIResponsesClient::new(native),
145                    }?;
146                    if let Some(timeouts) = config.timeouts {
147                        client = client.with_timeouts(timeouts)?;
148                    }
149                    Arc::new(client.with_default_headers(headers)?.with_retry_config(config.retry))
150                }
151            }
152            OpenCodeApi::Messages => {
153                if config.reasoning_effort.is_some() || config.gemini_thinking.is_some() {
154                    return Err(invalid(
155                        "Messages reasoning uses with_anthropic_effort or with_anthropic_thinking",
156                    ));
157                }
158                let mut native =
159                    AnthropicConfig::new(config.api_key, config.model).with_base_url(root);
160                if let Some(thinking) = config.thinking {
161                    native = native.with_thinking_mode(thinking);
162                }
163                if let Some(effort) = config.anthropic_effort {
164                    native = native.with_effort(effort);
165                }
166                let mut client = AnthropicClient::new(native)?;
167                if let Some(timeouts) = config.timeouts {
168                    client = client.with_timeouts(timeouts)?;
169                }
170                Arc::new(client.with_default_headers(headers).with_retry_config(config.retry))
171            }
172            OpenCodeApi::GenerateContent => {
173                if config.reasoning_effort.is_some()
174                    || config.thinking.is_some()
175                    || config.anthropic_effort.is_some()
176                {
177                    return Err(invalid("GenerateContent reasoning uses with_gemini_thinking"));
178                }
179                let http = reqwest::Client::builder().default_headers(headers);
180                let http = match config.timeouts {
181                    Some(timeouts) => timeouts.apply(http),
182                    None => http,
183                };
184                let client = adk_gemini::GeminiBuilder::new(config.api_key)
185                    .with_model(adk_gemini::Model::Custom(format!("models/{}", config.model)))
186                    .with_base_url(endpoint)
187                    .with_http_client(http)
188                    .build()
189                    .map_err(|err| crate::gemini::client::gemini_error_to_adk(&err))?;
190                let mut model =
191                    GeminiModel::from_client(client, config.model).with_retry_config(config.retry);
192                if let Some(thinking) = config.gemini_thinking {
193                    model = model.with_thinking_config(thinking);
194                }
195                Arc::new(model)
196            }
197        };
198        Ok(Self { inner, api, provider: service.provider() })
199    }
200
201    /// Returns the selected wire API.
202    pub fn api(&self) -> OpenCodeApi {
203        self.api
204    }
205}
206
207#[async_trait]
208impl Llm for OpenCodeClient {
209    fn name(&self) -> &str {
210        self.inner.name()
211    }
212    fn schema_adapter(&self) -> &dyn SchemaAdapter {
213        self.inner.schema_adapter()
214    }
215    fn data_locality(&self) -> adk_core::DataLocality {
216        self.inner.data_locality()
217    }
218    // The protocol client's endpoint, under the provider OpenCode's responses are attributed to.
219    fn data_destinations(&self) -> Vec<adk_core::DataDestination> {
220        let hosts = adk_core::DataDestination::all_hosts(&self.inner.data_destinations());
221        vec![adk_core::DataDestination::new(self.provider, hosts)]
222    }
223    async fn generate_content(
224        &self,
225        request: LlmRequest,
226        stream: bool,
227    ) -> Result<LlmResponseStream, AdkError> {
228        use futures::StreamExt;
229        // The protocol clients price by the upstream vendor; OpenCode bills on its own terms,
230        // so its responses are attributed to OpenCode and left unpriced.
231        let provider = self.provider;
232        let responses = self.inner.generate_content(request, stream).await?;
233        Ok(Box::pin(responses.map(move |result| {
234            result.map(|mut response| {
235                response.provider = Some(provider.to_string());
236                if let Some(usage) = response.usage_metadata.as_mut() {
237                    usage.cost = None;
238                }
239                response
240            })
241        })))
242    }
243}