Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(opencode): select transport by Go or Zen catalogue
Lucas Oliveira30a17e891c72
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ae16bdb4..333a6ea9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -118,12 +118,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0subagent under its parent's session id, so a subagent's events no longermark that session as a subagent: the parent's Stop, SessionEnd, summary andhandoff are kept. (#1041, #1048)-- The OpenCode provider now selects the published wire API for supported Zen+- The OpenCode provider now selects the published wire API for supported Go/Zenmodels: Responses, Anthropic Messages, or OpenAI-compatible Chat Completions.Claude Sonnet 5.5 and the legacy Sonnet 4 ID also use Messages.Its default model is now `mimo-v2.6-flash`, matching the default Go catalogue;Claude models require an explicit Zen base URL. Configured base URLs remainauthoritative, with no automatic switching between Go and Zen billing.+ MiniMax M3/M2.7 and Qwen3.8 Max use Messages on Go and Chat Completions on+ Zen; Go's Muse Contributor IDs use Responses. Changing the base URL also+ reselects the transport while preserving configured headers, reasoning,+ and timeout.(#1080)### Docsdiff --git a/crates/ai-memory-llm/src/opencode.rs b/crates/ai-memory-llm/src/opencode.rsindex d78189b9..cb8aa6f4 100644--- a/crates/ai-memory-llm/src/opencode.rs+++ b/crates/ai-memory-llm/src/opencode.rs@@ -49,13 +49,10 @@ pub const OPENCODE_SESSION_HEADER: &str = "x-opencode-session";/// Responses, Anthropic Messages, or Chat Completions wire format. Authenticate/// with the `sk-...` key obtained from <https://opencode.ai/auth>.pub struct OpenCodeProvider {- transport: OpenCodeTransport,-}--enum OpenCodeTransport {- ChatCompletions(OpenAiCompatProvider),- Responses(OpenCodeResponsesProvider),- AnthropicMessages(AnthropicProvider),+ base_url: String,+ chat_completions: OpenAiCompatProvider,+ responses: OpenCodeResponsesProvider,+ anthropic_messages: AnthropicProvider,}impl OpenCodeProvider {@@ -74,31 +71,28 @@ impl OpenCodeProvider {) -> LlmResult<Self> {let model = model.into();let base_url = base_url.into();- let transport = match model_api(&model) {- OpenCodeApi::Responses => OpenCodeTransport::Responses(OpenCodeResponsesProvider::new(- api_key, model, base_url,- )?),- OpenCodeApi::AnthropicMessages => OpenCodeTransport::AnthropicMessages(- AnthropicProvider::new(api_key, model)?- .with_base_url(anthropic_base_url(&base_url))- .with_client_headers(crate::DEFAULT_USER_AGENT, OPENCODE_SESSION_HEADER),- ),- OpenCodeApi::ChatCompletions => OpenCodeTransport::ChatCompletions(- OpenAiCompatProvider::new(base_url, Some(api_key), model)?- .with_client_headers(crate::DEFAULT_USER_AGENT, OPENCODE_SESSION_HEADER),- ),- };- Ok(Self { transport })+ Ok(Self {+ chat_completions: OpenAiCompatProvider::new(+ base_url.clone(),+ Some(api_key.clone()),+ model.clone(),+ )?+ .with_client_headers(crate::DEFAULT_USER_AGENT, OPENCODE_SESSION_HEADER),+ responses: OpenCodeResponsesProvider::new(+ api_key.clone(),+ model.clone(),+ base_url.clone(),+ )?,+ anthropic_messages: AnthropicProvider::new(api_key, model)?+ .with_base_url(anthropic_base_url(&base_url))+ .with_client_headers(crate::DEFAULT_USER_AGENT, OPENCODE_SESSION_HEADER),+ base_url,+ })}#[cfg(test)]fn with_strict(mut self, strict: bool) -> Self {- self.transport = match self.transport {- OpenCodeTransport::ChatCompletions(provider) => {- OpenCodeTransport::ChatCompletions(provider.with_strict(strict))- }- responses => responses,- };+ self.chat_completions = self.chat_completions.with_strict(strict);self}@@ -107,34 +101,18 @@ impl OpenCodeProvider {/// `ProviderConfig::request_timeout_secs`.#[must_use]pub fn with_timeout_secs(mut self, secs: u64) -> Self {- self.transport = match self.transport {- OpenCodeTransport::ChatCompletions(provider) => {- OpenCodeTransport::ChatCompletions(provider.with_timeout_secs(secs))- }- OpenCodeTransport::Responses(provider) => {- OpenCodeTransport::Responses(provider.with_timeout_secs(secs))- }- OpenCodeTransport::AnthropicMessages(provider) => {- OpenCodeTransport::AnthropicMessages(provider.with_timeout_secs(secs))- }- };+ self.chat_completions = self.chat_completions.with_timeout_secs(secs);+ self.responses = self.responses.with_timeout_secs(secs);+ self.anthropic_messages = self.anthropic_messages.with_timeout_secs(secs);self}/// Forward reasoning effort to the OpenAI-compatible Zen/Go client.#[must_use]pub fn with_reasoning_effort(mut self, effort: Option<ReasoningEffort>) -> Self {- self.transport = match self.transport {- OpenCodeTransport::ChatCompletions(provider) => {- OpenCodeTransport::ChatCompletions(provider.with_reasoning_effort(effort))- }- OpenCodeTransport::Responses(provider) => {- OpenCodeTransport::Responses(provider.with_reasoning_effort(effort))- }- OpenCodeTransport::AnthropicMessages(provider) => {- OpenCodeTransport::AnthropicMessages(provider.with_reasoning_effort(effort))- }- };+ self.chat_completions = self.chat_completions.with_reasoning_effort(effort);+ self.responses = self.responses.with_reasoning_effort(effort);+ self.anthropic_messages = self.anthropic_messages.with_reasoning_effort(effort);self}@@ -144,17 +122,12 @@ impl OpenCodeProvider {#[must_use]pub fn with_base_url(mut self, url: impl Into<String>) -> Self {let url = url.into();- self.transport = match self.transport {- OpenCodeTransport::ChatCompletions(provider) => {- OpenCodeTransport::ChatCompletions(provider.with_base_url(url))- }- OpenCodeTransport::Responses(provider) => {- OpenCodeTransport::Responses(provider.with_base_url(url))- }- OpenCodeTransport::AnthropicMessages(provider) => OpenCodeTransport::AnthropicMessages(- provider.with_base_url(anthropic_base_url(&url)),- ),- };+ self.chat_completions = self.chat_completions.with_base_url(url.clone());+ self.responses = self.responses.with_base_url(url.clone());+ self.anthropic_messages = self+ .anthropic_messages+ .with_base_url(anthropic_base_url(&url));+ self.base_url = url;self}@@ -163,27 +136,19 @@ impl OpenCodeProvider {/// operator entry for either name wins.#[must_use]pub fn with_extra_headers(mut self, headers: ExtraHeaders) -> Self {- self.transport = match self.transport {- OpenCodeTransport::ChatCompletions(provider) => {- OpenCodeTransport::ChatCompletions(provider.with_extra_headers(headers))- }- OpenCodeTransport::Responses(provider) => {- OpenCodeTransport::Responses(provider.with_extra_headers(headers))- }- OpenCodeTransport::AnthropicMessages(provider) => {- OpenCodeTransport::AnthropicMessages(provider.with_extra_headers(headers))- }- };+ self.chat_completions = self.chat_completions.with_extra_headers(headers.clone());+ self.responses = self.responses.with_extra_headers(headers.clone());+ self.anthropic_messages = self.anthropic_messages.with_extra_headers(headers);self}+ fn api(&self) -> OpenCodeApi {+ model_api(self.model(), &self.base_url)+ }+#[cfg(test)]fn base_url(&self) -> &str {- match &self.transport {- OpenCodeTransport::ChatCompletions(provider) => provider.base_url(),- OpenCodeTransport::Responses(provider) => &provider.base_url,- OpenCodeTransport::AnthropicMessages(_) => "",- }+ self.chat_completions.base_url()}}@@ -194,11 +159,7 @@ impl LlmProvider for OpenCodeProvider {}fn model(&self) -> &str {- match &self.transport {- OpenCodeTransport::ChatCompletions(provider) => provider.model(),- OpenCodeTransport::Responses(provider) => &provider.model,- OpenCodeTransport::AnthropicMessages(provider) => provider.model(),- }+ self.chat_completions.model()}async fn complete(&self, request: ChatRequest) -> LlmResult<ChatResponse> {@@ -211,17 +172,15 @@ impl LlmProvider for OpenCodeProvider {request: ChatRequest,operation_id: LlmOperationId,) -> LlmResult<ChatResponse> {- match &self.transport {- OpenCodeTransport::ChatCompletions(provider) => {- provider+ match self.api() {+ OpenCodeApi::ChatCompletions => {+ self.chat_completions.complete_with_operation_id(request, operation_id).await}- OpenCodeTransport::Responses(provider) => {- provider.complete(request, operation_id).await- }- OpenCodeTransport::AnthropicMessages(provider) => {- provider+ OpenCodeApi::Responses => self.responses.complete(request, operation_id).await,+ OpenCodeApi::AnthropicMessages => {+ self.anthropic_messages.complete_with_operation_id(request, operation_id).await}@@ -243,19 +202,19 @@ impl LlmProvider for OpenCodeProvider {schema: serde_json::Value,operation_id: LlmOperationId,) -> LlmResult<serde_json::Value> {- match &self.transport {- OpenCodeTransport::ChatCompletions(provider) => {- provider+ match self.api() {+ OpenCodeApi::ChatCompletions => {+ self.chat_completions.complete_structured_raw_with_operation_id(request, schema, operation_id).await}- OpenCodeTransport::Responses(provider) => {- provider+ OpenCodeApi::Responses => {+ self.responses.complete_structured(request, schema, operation_id).await}- OpenCodeTransport::AnthropicMessages(provider) => {- provider+ OpenCodeApi::AnthropicMessages => {+ self.anthropic_messages.complete_structured_raw_with_operation_id(request, schema, operation_id).await}@@ -263,13 +222,22 @@ impl LlmProvider for OpenCodeProvider {}}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum OpenCodeApi {Responses,AnthropicMessages,ChatCompletions,}-fn model_api(model: &str) -> OpenCodeApi {+fn model_api(model: &str, base_url: &str) -> OpenCodeApi {+ if is_go_base_url(base_url) {+ if matches_model(model, GO_RESPONSES_MODELS) {+ return OpenCodeApi::Responses;+ }+ if matches_model(model, GO_ANTHROPIC_MESSAGES_MODELS) {+ return OpenCodeApi::AnthropicMessages;+ }+ }if matches_model(model, RESPONSES_MODELS) {OpenCodeApi::Responses} else if matches_model(model, ANTHROPIC_MESSAGES_MODELS) {@@ -279,6 +247,18 @@ fn model_api(model: &str) -> OpenCodeApi {}}+fn is_go_base_url(base_url: &str) -> bool {+ reqwest::Url::parse(base_url).ok().is_some_and(|url| {+ let path = url.path().trim_end_matches('/');+ let base = path+ .strip_suffix("/chat/completions")+ .or_else(|| path.strip_suffix("/responses"))+ .or_else(|| path.strip_suffix("/messages"))+ .unwrap_or(path);+ base.ends_with("/zen/go/v1") || base.ends_with("/zen/go")+ })+}+fn matches_model(model: &str, models: &[&str]) -> bool {models.iter()@@ -294,6 +274,10 @@ fn anthropic_base_url(base_url: &str) -> String {.to_string()}+const GO_RESPONSES_MODELS: &[&str] = &["muse-spark-1.3-contributor", "muse-spark-1.2-contributor"];++const GO_ANTHROPIC_MESSAGES_MODELS: &[&str] = &["minimax-m3", "minimax-m2.7", "qwen3.8-max"];+const RESPONSES_MODELS: &[&str] = &["gpt-6-astra","gpt-6-sol",@@ -655,10 +639,7 @@ mod tests {fn luna_models_select_the_responses_transport() {for model in ["gpt-5.6-luna", "gpt-6-luna", "GPT-6-LUNA"] {let provider = OpenCodeProvider::new(SecretString::from("sk-test"), model).unwrap();- assert!(matches!(- provider.transport,- OpenCodeTransport::Responses(_)- ));+ assert!(matches!(provider.api(), OpenCodeApi::Responses));}}@@ -666,17 +647,411 @@ mod tests {fn published_models_select_their_documented_transports() {for model in RESPONSES_MODELS {let provider = OpenCodeProvider::new(SecretString::from("sk-test"), *model).unwrap();- assert!(matches!(- provider.transport,- OpenCodeTransport::Responses(_)- ));+ assert!(matches!(provider.api(), OpenCodeApi::Responses));}for model in ANTHROPIC_MESSAGES_MODELS {let provider = OpenCodeProvider::new(SecretString::from("sk-test"), *model).unwrap();- assert!(matches!(- provider.transport,- OpenCodeTransport::AnthropicMessages(_)- ));+ assert!(matches!(provider.api(), OpenCodeApi::AnthropicMessages));+ }+ }++ #[test]+ fn catalogue_specific_models_select_the_documented_api() {+ let cases = [+ (+ "minimax-m3",+ OpenCodeApi::ChatCompletions,+ OpenCodeApi::AnthropicMessages,+ ),+ (+ "minimax-m2.7",+ OpenCodeApi::ChatCompletions,+ OpenCodeApi::AnthropicMessages,+ ),+ (+ "qwen3.8-max",+ OpenCodeApi::ChatCompletions,+ OpenCodeApi::AnthropicMessages,+ ),+ (+ "muse-spark-1.3-contributor",+ OpenCodeApi::ChatCompletions,+ OpenCodeApi::Responses,+ ),+ (+ "muse-spark-1.2-contributor",+ OpenCodeApi::ChatCompletions,+ OpenCodeApi::Responses,+ ),+ ("gpt-6-luna", OpenCodeApi::Responses, OpenCodeApi::Responses),+ (+ "qwen3.8-flash",+ OpenCodeApi::AnthropicMessages,+ OpenCodeApi::AnthropicMessages,+ ),+ (+ "deepseek-v4-flash",+ OpenCodeApi::ChatCompletions,+ OpenCodeApi::ChatCompletions,+ ),+ ];+ for (model, zen_api, go_api) in cases {+ for model in [model.to_string(), model.to_ascii_uppercase()] {+ let mut provider =+ OpenCodeProvider::new(SecretString::from("sk-test"), &model).unwrap();+ assert_eq!(provider.api(), go_api, "{model}");+ for (url, expected) in [+ ("https://opencode.ai/zen/v1", zen_api),+ (OPENCODE_GO_BASE_URL, go_api),+ ("https://opencode.ai/zen", zen_api),+ ] {+ provider = provider.with_base_url(url);+ assert_eq!(provider.api(), expected, "{model} at {url}");+ assert_eq!(provider.model(), model);+ assert_eq!(provider.base_url(), url);+ }+ }+ }+ }++ #[test]+ fn go_catalogue_detection_uses_url_paths() {+ for url in [+ "https://opencode.ai/zen/go",+ "https://opencode.ai/zen/go/v1/",+ "https://opencode.ai/zen/go/v1/messages",+ "https://opencode.ai/zen/go/v1/responses/",+ "https://opencode.ai/zen/go/v1/chat/completions",+ "http://localhost:1234/proxy/zen/go/v1",+ "https://opencode.ai/zen/go/v1?key=value",+ ] {+ assert!(is_go_base_url(url), "{url}");+ }+ for url in [+ "https://opencode.ai/zen/v1",+ "https://opencode.ai/zen/v1/messages",+ "https://opencode.ai/zen/go-other/v1",+ "https://opencode.ai/zen/go/v1/models",+ "https://proxy.example/v1?upstream=/zen/go/v1",+ "https://proxy.example/v1#/zen/go/v1",+ "http://localhost:1234/v1",+ "not-a-url/zen/go/v1",+ ] {+ assert!(!is_go_base_url(url), "{url}");+ }+ }++ #[tokio::test]+ async fn factory_routes_plain_and_structured_requests_for_both_catalogues() {+ use crate::{ProviderAuth, ProviderChoice, ProviderConfig, build_provider};++ for model in [+ "minimax-m3",+ "minimax-m2.7",+ "qwen3.8-max",+ "muse-spark-1.3-contributor",+ "muse-spark-1.2-contributor",+ "gpt-6-luna",+ "gpt-5.6-luna",+ "qwen3.8-flash",+ "deepseek-v4-flash",+ ] {+ for catalogue in ["zen", "zen/go"] {+ let server = MockServer::start().await;+ let base = format!("{}/{catalogue}/v1", server.uri());+ let api = match (model, catalogue) {+ ("minimax-m3" | "minimax-m2.7" | "qwen3.8-max", "zen/go")+ | ("qwen3.8-flash", _) => OpenCodeApi::AnthropicMessages,+ ("muse-spark-1.3-contributor" | "muse-spark-1.2-contributor", "zen/go")+ | ("gpt-6-luna" | "gpt-5.6-luna", _) => OpenCodeApi::Responses,+ _ => OpenCodeApi::ChatCompletions,+ };+ let endpoint = match api {+ OpenCodeApi::ChatCompletions => "chat/completions",+ OpenCodeApi::Responses => "responses",+ OpenCodeApi::AnthropicMessages => "messages",+ };+ Mock::given(method("POST"))+ .and(path(format!("/{catalogue}/v1/{endpoint}")))+ .respond_with(move |request: &Request| {+ let body: serde_json::Value =+ serde_json::from_slice(&request.body).unwrap();+ let mut response = match api {+ OpenCodeApi::ChatCompletions => response_with_content(r#"{"ok":true}"#),+ OpenCodeApi::Responses => {+ responses_response_with_content(r#"{"ok":true}"#)+ }+ OpenCodeApi::AnthropicMessages if body.get("tools").is_some() => {+ json!({+ "content": [{"type": "tool_use", "input": {"ok": true}}],+ })+ }+ OpenCodeApi::AnthropicMessages => {+ anthropic_response_with_content(r#"{"ok":true}"#)+ }+ };+ response["model"] = body["model"].clone();+ ResponseTemplate::new(200).set_body_json(response)+ })+ .expect(2)+ .mount(&server)+ .await;+ let provider = build_provider(ProviderConfig {+ provider: ProviderChoice::OpenCode,+ model: model.into(),+ auth: ProviderAuth::required_api_key_from_env(+ "OPENCODE_API_KEY",+ Some(SecretString::from("sk-test")),+ ),+ base_url: Some(base),+ compat_strict: false,+ request_timeout_secs: 5,+ reasoning_effort: Some(ReasoningEffort::High),+ extra_headers: ExtraHeaders::parse(["x-test: routed"]).unwrap(),+ })+ .unwrap();+ let operation_id = LlmOperationId::new();+ let request = ChatRequest::user_prompt("hello");+ let response = provider+ .complete_with_operation_id(request.clone(), operation_id)+ .await+ .unwrap();+ assert_eq!(response.model, model);+ let schema = json!({"type": "object", "properties": {"ok": {"type": "boolean"}}, "required": ["ok"]});+ let result = provider+ .complete_structured_raw_with_operation_id(request, schema, operation_id)+ .await+ .unwrap();+ assert_eq!(result, json!({"ok": true}));+ let requests = server.received_requests().await.unwrap();+ assert_eq!(requests.len(), 2, "{model} at {catalogue}");+ for (index, request) in requests.iter().enumerate() {+ assert_eq!(header_value(request, "x-test"), Some("routed"));+ assert_eq!(+ header_value(request, "user-agent"),+ Some(crate::DEFAULT_USER_AGENT)+ );+ assert_eq!(+ header_value(request, OPENCODE_SESSION_HEADER),+ Some(operation_id.to_string().as_str())+ );+ let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();+ assert_eq!(body["model"], model);+ match api {+ OpenCodeApi::ChatCompletions => {+ assert_eq!(+ header_value(request, "authorization"),+ Some("Bearer sk-test")+ );+ assert!(header_value(request, "x-api-key").is_none());+ assert_eq!(body["messages"][0]["content"], "hello");+ assert_eq!(body["reasoning_effort"], "high");+ assert!(body.get("input").is_none());+ assert!(body.get("tools").is_none());+ }+ OpenCodeApi::Responses => {+ assert_eq!(+ header_value(request, "authorization"),+ Some("Bearer sk-test")+ );+ assert!(header_value(request, "x-api-key").is_none());+ assert_eq!(body["input"][0]["content"][0]["type"], "input_text");+ assert_eq!(body["reasoning"]["effort"], "high");+ assert!(body.get("messages").is_none());+ if index == 1 {+ assert_eq!(body["text"]["format"]["type"], "json_schema");+ }+ }+ OpenCodeApi::AnthropicMessages => {+ assert_eq!(header_value(request, "x-api-key"), Some("sk-test"));+ assert_eq!(+ header_value(request, "anthropic-version"),+ Some(crate::anthropic::ANTHROPIC_VERSION)+ );+ assert!(header_value(request, "authorization").is_none());+ assert_eq!(body["messages"][0]["content"], "hello");+ assert!(body.get("input").is_none());+ if index == 1 {+ assert_eq!(body["tool_choice"]["name"], "result");+ assert_eq!(+ body["tools"][0]["input_schema"]["properties"]["ok"]["type"],+ "boolean"+ );+ }+ }+ }+ }+ }+ }+ }++ #[tokio::test]+ async fn repeated_catalogue_switches_preserve_operator_settings() {+ for model in ["minimax-m3", "muse-spark-1.3-contributor"] {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .respond_with(|request: &Request| {+ let response = match request.url.path() {+ "/zen/go/v1/messages" => anthropic_response_with_content("ok"),+ "/zen/go/v1/responses" => responses_response_with_content("ok"),+ "/zen/v1/chat/completions" => response_with_content("ok"),+ other => panic!("unexpected endpoint: {other}"),+ };+ ResponseTemplate::new(200).set_body_json(response)+ })+ .expect(3)+ .mount(&server)+ .await;+ let mut provider = OpenCodeProvider::new(SecretString::from("sk-test"), model)+ .unwrap()+ .with_timeout_secs(7)+ .with_reasoning_effort(Some(ReasoningEffort::High))+ .with_extra_headers(+ ExtraHeaders::parse([+ "user-agent: custom-client",+ "x-opencode-session: custom-session",+ ])+ .unwrap(),+ );+ for catalogue in ["zen", "zen/go", "zen"] {+ provider = provider.with_base_url(format!("{}/{catalogue}/v1", server.uri()));+ provider+ .complete(ChatRequest::user_prompt("hello"))+ .await+ .unwrap();+ }+ let requests = server.received_requests().await.unwrap();+ assert_eq!(requests.len(), 3);+ for request in requests {+ assert_eq!(header_value(&request, "user-agent"), Some("custom-client"));+ assert_eq!(+ header_value(&request, OPENCODE_SESSION_HEADER),+ Some("custom-session")+ );+ let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();+ if request.url.path().ends_with("chat/completions") {+ assert_eq!(body["reasoning_effort"], "high");+ } else if request.url.path().ends_with("responses") {+ assert_eq!(body["reasoning"]["effort"], "high");+ }+ }+ }+ }++ #[tokio::test]+ async fn timeout_survives_switching_catalogues_and_transports() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .respond_with(+ ResponseTemplate::new(200)+ .set_body_json(response_with_content("ok"))+ .set_delay(Duration::from_millis(50)),+ )+ .mount(&server)+ .await;+ for model in ["minimax-m3", "muse-spark-1.3-contributor"] {+ let mut provider = OpenCodeProvider::new(SecretString::from("sk-test"), model)+ .unwrap()+ .with_timeout_secs(0);+ for catalogue in ["zen", "zen/go", "zen"] {+ provider = provider.with_base_url(format!("{}/{catalogue}/v1", server.uri()));+ let error = provider+ .complete(ChatRequest::user_prompt("hello"))+ .await+ .unwrap_err();+ assert!(matches!(error, LlmError::Http(error) if error.is_timeout()));+ }+ }+ }++ #[tokio::test]+ async fn catalogue_endpoints_normalize_bare_versioned_and_complete_urls() {+ for (model, catalogue, endpoint, api) in [+ (+ "minimax-m3",+ "zen/go",+ "messages",+ OpenCodeApi::AnthropicMessages,+ ),+ (+ "minimax-m3",+ "zen",+ "chat/completions",+ OpenCodeApi::ChatCompletions,+ ),+ ("gpt-6-luna", "zen/go", "responses", OpenCodeApi::Responses),+ ("gpt-6-luna", "zen", "responses", OpenCodeApi::Responses),+ (+ "claude-sonnet-5-5",+ "zen",+ "messages",+ OpenCodeApi::AnthropicMessages,+ ),+ ] {+ let server = MockServer::start().await;+ let response = match api {+ OpenCodeApi::ChatCompletions => response_with_content("ok"),+ OpenCodeApi::Responses => responses_response_with_content("ok"),+ OpenCodeApi::AnthropicMessages => anthropic_response_with_content("ok"),+ };+ Mock::given(method("POST"))+ .and(path(format!("/{catalogue}/v1/{endpoint}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(response))+ .expect(4)+ .mount(&server)+ .await;+ for suffix in [+ String::new(),+ "/v1/".into(),+ format!("/v1/{endpoint}"),+ format!("/v1/{endpoint}/"),+ ] {+ let provider = OpenCodeProvider::new(SecretString::from("sk-test"), model)+ .unwrap()+ .with_base_url(format!("{}/{catalogue}{suffix}", server.uri()));+ assert_eq!(provider.api(), api);+ let response = provider+ .complete(ChatRequest::user_prompt("hello"))+ .await+ .unwrap();+ assert_eq!(response.text, "ok");+ }+ assert_eq!(server.received_requests().await.unwrap().len(), 4);+ }+ }++ #[tokio::test]+ async fn catalogue_switches_preserve_provider_errors_without_retrying() {+ for (model, catalogue, endpoint) in [+ ("minimax-m3", "zen/go", "messages"),+ ("minimax-m3", "zen", "chat/completions"),+ ("muse-spark-1.3-contributor", "zen/go", "responses"),+ ] {+ for status in [401, 500] {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path(format!("/{catalogue}/v1/{endpoint}")))+ .respond_with(ResponseTemplate::new(status).set_body_string("gateway error"))+ .expect(2)+ .mount(&server)+ .await;+ let provider = OpenCodeProvider::new(SecretString::from("sk-test"), model)+ .unwrap()+ .with_base_url(format!("{}/{catalogue}/v1", server.uri()));+ let request = ChatRequest::user_prompt("hello");+ for error in [+ provider.complete(request.clone()).await.unwrap_err(),+ provider+ .complete_structured_raw(request, json!({"type": "object"}))+ .await+ .unwrap_err(),+ ] {+ assert!(+ matches!(error, LlmError::Provider { status: code, body } if code == status && body == "gateway error")+ );+ }+ assert_eq!(server.received_requests().await.unwrap().len(), 2);+ }}}@@ -684,10 +1059,7 @@ mod tests {fn default_model_selects_go_chat_completions_transport() {let provider =OpenCodeProvider::new(SecretString::from("sk-test"), OPENCODE_DEFAULT_MODEL).unwrap();- assert!(matches!(- provider.transport,- OpenCodeTransport::ChatCompletions(_)- ));+ assert!(matches!(provider.api(), OpenCodeApi::ChatCompletions));assert_eq!(provider.model(), "mimo-v2.6-flash");assert_eq!(provider.base_url(), OPENCODE_GO_BASE_URL);}@@ -696,10 +1068,7 @@ mod tests {fn chat_completions_models_keep_the_existing_transport() {let provider =OpenCodeProvider::new(SecretString::from("sk-test"), "deepseek-v4-flash").unwrap();- assert!(matches!(- provider.transport,- OpenCodeTransport::ChatCompletions(_)- ));+ assert!(matches!(provider.api(), OpenCodeApi::ChatCompletions));}#[test]diff --git a/docs/install.md b/docs/install.mdindex d8647dfa..eabe4231 100644--- a/docs/install.md+++ b/docs/install.md@@ -1741,7 +1741,7 @@ If you set only the provider, ai-memory picks a sensible default:| `AI_MEMORY_LLM_PROVIDER=codex` | `gpt-5.6-luna` | Reuses only `access_token` and `account_id` from Codex's `auth.json`; token renewal is delegated to `codex app-server --stdio`. || `AI_MEMORY_LLM_PROVIDER=copilot` | `gpt-5.5` | GitHub Copilot Chat backend. ai-memory stores a GitHub user token in `<data_dir>/auth.json`, exchanges it for a short-lived Copilot API token, and refreshes before expiry. || `AI_MEMORY_LLM_PROVIDER=gemini` | `gemini-3.5-flash` | Google's hosted option with a generous free tier. ai-memory disables Gemini 3.5 Flash's default dynamic thinking so hidden thought tokens do not truncate strict JSON. Set `GEMINI_API_KEY` (or `GOOGLE_API_KEY`). |-| `AI_MEMORY_LLM_PROVIDER=opencode` | `mimo-v2.6-flash` | [OpenCode](https://opencode.ai) cloud API. Defaults to the **Go** endpoint, `opencode.ai/zen/go/v1` — a cost-optimised model subset. Published Responses models, including GPT-5.6 Luna and GPT-6 Luna, use `/responses`; supported Claude and Qwen Messages models use `/messages`; other models retain Chat Completions. For **Zen**'s full catalogue, set `AI_MEMORY_LLM_BASE_URL=https://opencode.ai/zen/v1` plus an `AI_MEMORY_LLM_MODEL` from it, such as `claude-sonnet-5-5`; the default model id is Go's. Requests identify ai-memory by version and reuse one session header across related attempts. Both endpoints take `OPENCODE_API_KEY` (key from `opencode.ai/auth`). Alias: `opencode-zen` — historical, and it selects Go like the others; the endpoint is chosen by the base URL, not the alias, with no automatic billing-product switch. |+| `AI_MEMORY_LLM_PROVIDER=opencode` | `mimo-v2.6-flash` | [OpenCode](https://opencode.ai) cloud API. Defaults to the **Go** endpoint, `opencode.ai/zen/go/v1` — a cost-optimised model subset. Published Responses models, including GPT-5.6 Luna and GPT-6 Luna, use `/responses`; supported Claude and Qwen Messages models use `/messages`. MiniMax M3/M2.7 and Qwen3.8 Max use Messages on Go and Chat Completions on Zen; Go Muse Contributor models use Responses. Changing the base URL reselects the transport and preserves request settings. See the [Go](https://opencode.ai/docs/go/#endpoints) and [Zen](https://opencode.ai/docs/zen/#endpoints) endpoint tables. For **Zen**'s full catalogue, set `AI_MEMORY_LLM_BASE_URL=https://opencode.ai/zen/v1` plus an `AI_MEMORY_LLM_MODEL` from it, such as `claude-sonnet-5-5`; the default model id is Go's. Requests identify ai-memory by version and reuse one session header across related attempts. Both endpoints take `OPENCODE_API_KEY` (key from `opencode.ai/auth`). Alias: `opencode-zen` — historical, and it selects Go like the others; the endpoint is chosen by the base URL, not the alias, with no automatic billing-product switch. || `AI_MEMORY_EMBEDDING_PROVIDER=openai` | `text-embedding-3-small` (1536-dim) | 5× cheaper than `-3-large` with marginal recall loss. || `AI_MEMORY_EMBEDDING_PROVIDER=openai` + `AI_MEMORY_EMBEDDING_BASE_URL=https://openrouter.ai/api/v1` | `openai/text-embedding-3-small` via [OpenRouter](https://openrouter.ai) | Uses `EMBEDDING_API_KEY`, else reuses `LLM_API_KEY` or `OPENAI_API_KEY`, with the OpenAI-compatible embedding client. || `AI_MEMORY_EMBEDDING_PROVIDER=openai` + `AI_MEMORY_EMBEDDING_BASE_URL=https://api.orcarouter.ai/v1` | `openai/text-embedding-3-small` via [OrcaRouter](https://www.orcarouter.ai) | Uses `EMBEDDING_API_KEY`, else reuses `LLM_API_KEY`, with the OpenAI-compatible embedding client. |diff --git a/docs/llm-providers.md b/docs/llm-providers.mdindex c66245f3..8fe94b27 100644--- a/docs/llm-providers.md+++ b/docs/llm-providers.md@@ -95,8 +95,20 @@ default is `mimo-v2.6-flash`, served by Go. When selecting Zen, set`AI_MEMORY_LLM_MODEL` to a model from its catalogue, such as `claude-sonnet-5-5`.The provider preserves the chosen catalogue and does not switch billing productsautomatically. Published Responses models, including `gpt-5.6-luna` and-`gpt-6-luna`, use `/responses`; supported Claude and Qwen Messages models use-`/messages`; other models retain Chat Completions. The provider sends the+`gpt-6-luna`, use `/responses`. The wire API follows the selected catalogue:+`minimax-m3`, `minimax-m2.7`, and `qwen3.8-max` use `/messages` on Go and+Chat Completions on Zen. Go's `muse-spark-1.3-contributor` and+`muse-spark-1.2-contributor` use `/responses`. Supported Claude and the other+mapped Qwen models use `/messages`; remaining models retain Chat Completions.+Changing the base URL reselects the transport and preserves timeout, reasoning+effort, and operator headers. Go is identified by a URL path ending in+`/zen/go` or `/zen/go/v1`, optionally including a complete endpoint;+custom proxy URLs with other paths use the Zen mapping.+See the official [Go endpoints](https://opencode.ai/docs/go/#endpoints) and+[Zen endpoints](https://opencode.ai/docs/zen/#endpoints), whose source tables+are [go.mdx](https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/go.mdx)+and [zen.mdx](https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/zen.mdx).+The provider sends the`x-opencode-session` correlation header OpenCode asks for, one id per logicaloperation, and its own `User-Agent`; `AI_MEMORY_LLM_HEADERS` overrideseither. `AI_MEMORY_LLM_REASONING_EFFORT` and `AI_MEMORY_LLM_TIMEOUT_SECS`