Craft Anything: understand how any software works, and craft your own.
Rust
Offer OpenCode Go as a backend, with its session header (#672)
Fireflyc7caf7de15af
diff --git a/crates/ai/src/config.rs b/crates/ai/src/config.rsindex d8a984e9..b28745bc 100644--- a/crates/ai/src/config.rs+++ b/crates/ai/src/config.rs@@ -174,6 +174,10 @@ pub struct AiConfig {pub fallback_chain: Vec<String>,/// Price overrides by model id.pub prices: BTreeMap<String, Price>,+ /// This installation's OpenCode Go session id, made on first use and kept with the settings so+ /// prompt caching survives restarts (and tests stay inside their own settings file).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub install_id: Option<String>,}pub fn role_key(r: Role) -> &'static str {diff --git a/crates/ai/src/detect.rs b/crates/ai/src/detect.rsindex b5875715..07366e0c 100644--- a/crates/ai/src/detect.rs+++ b/crates/ai/src/detect.rs@@ -19,6 +19,10 @@ fn cfg(name: &str, kind: BackendKind, model: &str) -> BackendConfig {BackendConfig { name: name.into(), kind, model: model.into(), base_url: None, ssh_host: None, enabled: true }}+fn cfg_at(name: &str, kind: BackendKind, model: &str, base: &str) -> BackendConfig {+ BackendConfig { base_url: Some(base.into()), ..cfg(name, kind, model) }+}+/// Environment keys that are set.pub fn env_keys(get: impl Fn(&str) -> Option<String>) -> Vec<Detected> {let mut out = Vec::new();@@ -53,6 +57,16 @@ pub fn env_keys(get: impl Fn(&str) -> Option<String>) -> Vec<Detected> {},needs_key: !found,});+ // OpenCode Go: a paid subscription, so it is offered only when its key is already set. Gemini+ // and Kimi are offered keyless because they are general model APIs.+ let go = ["OPENCODEGO_API_KEY", "OPENCODE_GO_API_KEY"].iter().any(|v| get(v).is_some_and(|k| !k.trim().is_empty()));+ if go {+ out.push(Detected {+ suggestion: cfg_at(OPENCODE_GO_NAME, BackendKind::OpenaiCompatible, crate::openai::OPENCODE_GO_DEFAULT_MODEL, crate::openai::OPENCODE_GO_BASE),+ reason: "OpenCode Go, with its key in your environment".into(),+ needs_key: false,+ });+ }out}@@ -61,6 +75,9 @@ pub const KIMI_NAME: &str = "Kimi K3.1 Pro (OpenRouter)";/// Name given to a Google AI Studio (Gemini API key) backend.pub const GEMINI_NAME: &str = "Gemini (Google AI Studio)";+/// The name OpenCode Go is added under.+pub const OPENCODE_GO_NAME: &str = "OpenCode Go (subscription)";+/// Is something listening at this URL's host:port? (bounded TCP connect)pub fn port_open(base_url: &str, timeout: Duration) -> bool {let hostport = base_url.split("://").nth(1).unwrap_or(base_url).split('/').next().unwrap_or_default();@@ -308,18 +325,32 @@ mod tests {#[test]fn env_detection() {let d = env_keys(|v| (v == "OPENROUTER_API_KEY").then(|| "k".to_string()));- assert_eq!(d.len(), 3);- assert_eq!(d[0].suggestion.kind, BackendKind::Openrouter);- assert!(d[0].reason.contains("OPENROUTER_API_KEY"));+ let find = |name: &str| d.iter().find(|x| x.suggestion.name == name).unwrap_or_else(|| panic!("{name} offered"));+ assert!(find("OpenRouter").reason.contains("OPENROUTER_API_KEY"));// Gemini is always offered; without its key it asks for one.- assert!(d[1].suggestion.kind == BackendKind::Gemini && d[1].needs_key);- // Kimi K3.1 Pro rides on the same key, so it needs none of its own.- assert_eq!((d[2].suggestion.model.as_str(), d[2].needs_key), (crate::openai::KIMI_K3_1, false));- // Without a key, Gemini and Kimi K3.1 Pro are still offered, asking for one.+ assert!(find(GEMINI_NAME).needs_key);+ // Kimi K3.1 Pro rides on the OpenRouter key, so it needs none of its own.+ assert!(!find(KIMI_NAME).needs_key);+ // A paid subscription is not advertised to someone who has no key for it.+ assert!(d.iter().all(|x| x.suggestion.name != OPENCODE_GO_NAME));+ // Without any key, everything that can be pasted is still offered.let none = env_keys(|_| Some(" ".into()));- assert_eq!(none.len(), 2);- assert!(none[0].needs_key && none[0].suggestion.name == GEMINI_NAME);- assert!(none[1].needs_key && none[1].suggestion.name == KIMI_NAME);+ assert!(none.iter().all(|x| x.needs_key));+ for name in [GEMINI_NAME, KIMI_NAME] {+ assert!(none.iter().any(|x| x.suggestion.name == name), "{name} offered");+ }+ }++ /// OpenCode Go is offered when its key is set, under either of its environment names.+ #[test]+ fn opencode_go_is_offered_only_with_its_key() {+ for var in ["OPENCODEGO_API_KEY", "OPENCODE_GO_API_KEY"] {+ let d = env_keys(|v| (v == var).then(|| "k".to_string()));+ let go = d.iter().find(|x| x.suggestion.name == OPENCODE_GO_NAME).expect("OpenCode Go offered");+ assert!(!go.needs_key);+ assert_eq!(go.suggestion.base_url.as_deref(), Some(crate::openai::OPENCODE_GO_BASE));+ assert_eq!(go.suggestion.model.as_str(), crate::openai::OPENCODE_GO_DEFAULT_MODEL);+ }}#[test]diff --git a/crates/ai/src/lib.rs b/crates/ai/src/lib.rsindex 4205964e..036f361a 100644--- a/crates/ai/src/lib.rs+++ b/crates/ai/src/lib.rs@@ -106,6 +106,42 @@ fn yes() -> bool {true}+/// A new session id for OpenCode Go: random enough to tell installations apart, with no personal+/// data in it.+fn new_session_id() -> String {+ use std::time::{SystemTime, UNIX_EPOCH};+ let n = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);+ format!("craft-{:x}-{:x}", std::process::id(), n)+}++/// The OpenCode Go key from the environment, when the base URL is its own. A blank value counts as+/// unset, so the other name is still tried.+fn go_env_key(base: &str) -> Option<String> {+ if !openai::is_opencode_go(base) {+ return None;+ }+ ["OPENCODEGO_API_KEY", "OPENCODE_GO_API_KEY"].iter().filter_map(|v| std::env::var(v).ok()).find(|k| !k.trim().is_empty())+}++/// An OpenAI-compatible client, carrying OpenCode Go's session header when the base is its own.+fn compatible_client(name: &str, base: &str, key: Option<String>, model: &str, session: &str) -> openai::OpenAi {+ let mut o = openai::OpenAi::compatible(name, base, key, model);+ if openai::is_opencode_go(base) && !session.is_empty() {+ o.extra_headers.push((openai::OPENCODE_GO_SESSION_HEADER, session.to_string()));+ }+ o+}++/// Where OpenCode Go lists its models: the chat base ends in `/openai/v1`, while the list answers at+/// the same service root with `/v1` (https://opencode.ai/inference/go/v1/models).+fn opencode_go_models_base(base: &str) -> String {+ let base = base.trim_end_matches('/');+ match base.strip_suffix("/openai/v1") {+ Some(root) => format!("{root}/v1"),+ None => base.to_string(),+ }+}+/// The effort an AI thinks at, when it can be chosen (Settings → AI): the Claude API and Claude/// Code, which take every level in [`Effort::ALL`]. `None` for the others, which don't use it.pub fn effort_in_use(config: &BackendConfig, options: Option<&BackendOptions>) -> Option<Effort> {@@ -412,7 +448,9 @@ impl AiHub {.with_remediation("Give the server's address, like http://192.168.1.20:11434/v1."));}let key = key.map(|k| k.trim().to_string()).filter(|k| !k.is_empty());- let models = openai::OpenAi::compatible(name, address, key.clone(), "").list_models(Duration::from_secs(10)).map_err(|e| {+ // OpenCode Go lists its models at /v1, not under the chat path a person would paste.+ let probe = if openai::is_opencode_go(address) { opencode_go_models_base(address) } else { address.to_string() };+ let models = openai::OpenAi::compatible(name, &probe, key.clone(), "").list_models(Duration::from_secs(10)).map_err(|e| {let why = e.message.clone();e.with_remediation(format!("Check the address (it usually ends in /v1), that the server is running and can be reached from this computer, and its key if it needs one. ({why})"@@ -444,6 +482,11 @@ impl AiHub {return Err(ToolError::invalid("A backend needs a name."));}let mut cfg = self.config_to_change()?;+ // The session id is made here, where saving the settings is already the job, rather than on+ // the first model call, which runs under the session lock.+ if cfg.install_id.as_deref().is_none_or(|s| s.trim().is_empty()) && openai::is_opencode_go(entry.config.base_url.as_deref().unwrap_or("")) {+ cfg.install_id = Some(new_session_id());+ }if let Some(k) = key.filter(|k| !k.trim().is_empty()) {self.keys.set(&entry.config.name, k.trim())?;}@@ -590,7 +633,20 @@ impl AiHub {/// True when a key is stored or in the environment (keys themselves are never returned).pub fn has_key(&self, name: &str) -> bool {- self.config().get(name).is_some_and(|b| !b.config.kind.needs_key() || self.keys.resolve(name, b.config.kind).is_some())+ self.config().get(name).is_some_and(|b| {+ let base = b.config.base_url.as_deref().unwrap_or("");+ if b.config.kind == BackendKind::OpenaiCompatible && openai::is_opencode_go(base) {+ return self.keys.resolve(name, b.config.kind).is_some() || go_env_key(base).is_some();+ }+ !b.config.kind.needs_key() || self.keys.resolve(name, b.config.kind).is_some()+ })+ }++ /// This installation's OpenCode Go session id, or empty when the backend was added before one+ /// was made. Reading never writes: `build_model` runs under the session lock, so a save there+ /// would deadlock or freeze the window.+ fn session_id(&self) -> String {+ self.config().install_id.clone().filter(|s| !s.trim().is_empty()).unwrap_or_default()}fn entry(&self, name: &str) -> Result<BackendEntry, ToolError> {@@ -600,8 +656,10 @@ impl AiHub {}fn key_for(&self, e: &BackendEntry) -> Result<String, ToolError> {- self.keys.resolve(&e.config.name, e.config.kind).ok_or_else(|| {- let var = keys::env_var(e.config.kind).unwrap_or("an API key");+ let base = e.config.base_url.as_deref().unwrap_or("");+ self.keys.resolve(&e.config.name, e.config.kind).or_else(|| go_env_key(base)).ok_or_else(|| {+ let var =+ if openai::is_opencode_go(base) { "OPENCODEGO_API_KEY or OPENCODE_GO_API_KEY" } else { keys::env_var(e.config.kind).unwrap_or("an API key") };ToolError::new(ErrorCode::BadSettings, format!("{} has no API key.", e.config.name)).with_remediation(format!("Add the key in Settings → AI, or set {var}."))})@@ -643,7 +701,9 @@ impl AiHub {BackendKind::Openrouter => Box::new(openai::OpenAi::openrouter(base, self.key_for(e)?, &c.model)),BackendKind::Gemini => Box::new(openai::OpenAi::gemini(base, self.key_for(e)?, &c.model)),BackendKind::OpenaiCompatible => {- let mut o = openai::OpenAi::compatible(&c.name, base.unwrap_or("http://127.0.0.1:11434/v1"), self.keys.get(&c.name), &c.model);+ let base = base.unwrap_or("http://127.0.0.1:11434/v1");+ let key = self.keys.get(&c.name).or_else(|| go_env_key(base));+ let mut o = compatible_client(&c.name, base, key, &c.model, &self.session_id());o.react = e.options.react_fallback.unwrap_or(false);Box::new(o)}@@ -768,7 +828,13 @@ impl AiHub {if e.config.ssh_host.as_deref().is_some_and(|h| !h.trim().is_empty()) {return Err(ToolError::unavailable("Listing models on a remote server isn't supported yet.").with_remediation("Type the model name."));}- openai::OpenAi::compatible(&e.config.name, base.unwrap_or("http://127.0.0.1:11434/v1"), self.keys.get(&e.config.name), "").list_models(t)+ let b = base.unwrap_or("http://127.0.0.1:11434/v1");+ let key = self.keys.get(&e.config.name).or_else(|| go_env_key(b));+ if openai::is_opencode_go(b) {+ // The chat base ends in /openai/v1; the model list answers at /v1 instead.+ return compatible_client(&e.config.name, &opencode_go_models_base(b), key, "", "").list_models(t);+ }+ compatible_client(&e.config.name, b, key, "", "").list_models(t)}BackendKind::AgentCli => self.model_choices(name),}@@ -877,11 +943,17 @@ fn reach(e: &BackendEntry, key: Option<String>) -> Result<u64, String> {}BackendKind::OpenaiCompatible => {let b = base.unwrap_or("http://127.0.0.1:11434/v1");- if !detect::port_open(b, Duration::from_millis(500)) {+ let key = key.or_else(|| go_env_key(b));+ if openai::is_opencode_go(b) {+ // The list answers at /v1, not under the chat path's /openai/v1. A key is still+ // required here, so "reachable" never means "callable without one".+ let key = need(key)?;+ compatible_client(&e.config.name, &opencode_go_models_base(b), Some(key), "", "").list_models(t).map(|_| ()).map_err(|x| x.message)+ } else if !b.starts_with("https://") && !detect::port_open(b, Duration::from_millis(500)) {Err(format!("nothing is listening at {b}"))} else {// An open port isn't a model server: another program may hold it (#37).- openai::OpenAi::compatible(&e.config.name, b, key, &e.config.model).list_models(t).map(|_| ()).map_err(|x| x.message)+ compatible_client(&e.config.name, b, key, &e.config.model, "").list_models(t).map(|_| ()).map_err(|x| x.message)}}BackendKind::AgentCli => {diff --git a/crates/ai/src/openai.rs b/crates/ai/src/openai.rsindex 54c59629..8f95ce07 100644--- a/crates/ai/src/openai.rs+++ b/crates/ai/src/openai.rs@@ -24,6 +24,26 @@ pub const GEMINI_MODELS: &[&str] = &[GEMINI_DEFAULT_MODEL, "gemini-4-argon"];/// Generic app identification for OpenRouter (no personal data).pub const APP_REFERER: &str = "https://github.com/storytold/craft-anything";pub const APP_TITLE: &str = "Craft Anything";+/// OpenCode Go (a subscription): an OpenAI-compatible base, the key from its console, and a session+/// header the service asks every client to send so routing and prompt caching follow a conversation.+pub const OPENCODE_GO_BASE: &str = "https://opencode.ai/inference/go/openai/v1";+/// The header OpenCode Go asks every client to send.+pub const OPENCODE_GO_SESSION_HEADER: &str = "x-opencode-session";+/// The model a new OpenCode Go backend starts on, before its own list is fetched.+pub const OPENCODE_GO_DEFAULT_MODEL: &str = "kimi-k3.1-pro";++/// Whether this base URL is OpenCode Go's: https, host opencode.ai, path under /inference/go/.+/// A substring test would also match a look-alike host or a proxy path.+pub fn is_opencode_go(base: &str) -> bool {+ let base = base.trim().trim_end_matches('/');+ let Some((scheme, rest)) = base.split_once("://") else { return false };+ if !scheme.eq_ignore_ascii_case("https") {+ return false;+ }+ let (host, path) = rest.split_once('/').unwrap_or((rest, ""));+ let host = host.rsplit('@').next().unwrap_or(host).split(':').next().unwrap_or(host);+ host.eq_ignore_ascii_case("opencode.ai") && (path == "inference/go" || path.starts_with("inference/go/"))+}/// Well-known local servers: (name, base URL).pub const LOCAL_SERVERS: &[(&str, &str)] = &[@@ -132,7 +152,20 @@ impl OpenAi {let agent = http::quick_agent(timeout);let v = http::get_json(&agent, &self.label, &self.url("models"), &self.headers())?;let arr = v.get("data").or_else(|| v.get("models")).and_then(Value::as_array).cloned().unwrap_or_default();- Ok(arr.iter().filter_map(|m| m.get("id").or_else(|| m.get("name")).and_then(Value::as_str).map(str::to_string)).collect())+ // A catalogue may list a model only for another API (Responses, Messages): such an entry+ // would fail on a chat-completions client, so skip it when the entry says which APIs it+ // serves. Empty and repeated ids are dropped too.+ let mut out: Vec<String> = Vec::new();+ for m in arr {+ if m.get("api").is_some_and(|a| a.get("chat-completions").is_none()) {+ continue;+ }+ let Some(id) = m.get("id").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) else { continue };+ if !out.iter().any(|seen| seen == id) {+ out.push(id.to_string());+ }+ }+ Ok(out)}fn stream_once(&self, req: &TurnRequest<'_>, on_delta: &mut dyn FnMut(Delta), stop: &Stop) -> Result<TurnResult, ToolError> {@@ -517,6 +550,20 @@ mod tests {use super::*;use crate::model::Effort;+ /// Only the real OpenCode Go base gets its session header: not a look-alike host, path or scheme.+ #[test]+ fn opencode_go_base_is_recognised_exactly() {+ assert!(is_opencode_go(OPENCODE_GO_BASE));+ assert!(is_opencode_go("https://opencode.ai/inference/go/openai/v1/models"));+ assert!(is_opencode_go("https://OpenCode.AI/inference/go/openai/v1"));+ assert!(!is_opencode_go("https://opencode.ai.evil.test/inference/go/v1"));+ assert!(!is_opencode_go("http://127.0.0.1:4000/opencode.ai/inference/go/v1"));+ assert!(!is_opencode_go("https://opencode.ai/inference/gopher/v1"));+ assert!(!is_opencode_go("https://opencode.ai/inference/go-v2/v1"));+ assert!(!is_opencode_go("http://opencode.ai/inference/go/v1"));+ assert!(!is_opencode_go("https://openrouter.ai/api/v1"));+ }+#[test]fn json_text_calls_and_non_calls() {for text in [diff --git a/crates/ai/src/tests.rs b/crates/ai/src/tests.rsindex 81228310..573e0876 100644--- a/crates/ai/src/tests.rs+++ b/crates/ai/src/tests.rs@@ -7,6 +7,14 @@ use serde_json::{Value, json};use std::io::{BufRead, BufReader, Read, Write};use std::net::TcpListener;+/// The model list lives at /v1 on the service root, not under the chat path's /openai/v1.+#[test]+fn opencode_go_lists_models_at_the_documented_url() {+ assert_eq!(format!("{}/models", opencode_go_models_base(openai::OPENCODE_GO_BASE)), "https://opencode.ai/inference/go/v1/models");+ assert_eq!(opencode_go_models_base("https://opencode.ai/inference/go/openai/v1/"), "https://opencode.ai/inference/go/v1");+ assert_eq!(opencode_go_models_base("http://127.0.0.1:11434/v1"), "http://127.0.0.1:11434/v1");+}+#[derive(Debug, Clone)]struct Seen {path: String,diff --git a/crates/ui-egui/src/first_run.rs b/crates/ui-egui/src/first_run.rsindex 6ad37120..abbd3617 100644--- a/crates/ui-egui/src/first_run.rs+++ b/crates/ui-egui/src/first_run.rs@@ -207,7 +207,10 @@ fn brain_card(app: &mut CraftApp, ui: &mut Ui, d: &Detected) {}});});- if d.needs_key && !configured {+ // A subscription key is worth pasting even when the environment already has one, so a+ // different key can be used without restarting the app.+ let pastable = d.needs_key || d.suggestion.base_url.as_deref().is_some_and(craft_anything_ai::openai::is_opencode_go);+ if pastable && !configured {ui.add_space(6.0);ui.horizontal(|ui| {let key = app.key_inputs.entry(name.clone()).or_default();diff --git a/crates/ui-egui/src/settings_ui.rs b/crates/ui-egui/src/settings_ui.rsindex b160376d..2d372c3e 100644--- a/crates/ui-egui/src/settings_ui.rs+++ b/crates/ui-egui/src/settings_ui.rs@@ -577,7 +577,10 @@ fn ai(app: &mut CraftApp, ui: &mut Ui) {}});});- if d.needs_key && !configured {+ // A subscription key is worth pasting even when the environment already has one, so a+ // different key can be used without restarting the app.+ let pastable = d.needs_key || d.suggestion.base_url.as_deref().is_some_and(craft_anything_ai::openai::is_opencode_go);+ if pastable && !configured {ui.horizontal(|ui| {let key = app.key_inputs.entry(d.suggestion.name.clone()).or_default();ui.add(diff --git a/docs/pitfalls.md b/docs/pitfalls.mdindex 981d70ba..73f9df14 100644--- a/docs/pitfalls.md+++ b/docs/pitfalls.md@@ -625,3 +625,9 @@ malformed suffixes and non-call JSON examples whose strings contain protocol marthe selected row each frame, so the wheel's scroll was pulled back to it at once and the listkept jumping to the top (#584). Scroll something into view on the frame it changed (a key, a newquery), never as a standing request.++**A test wrote into the real config folder.** A helper that keeps one id per installation created+opencode-session under settings::config_dir() when the first request was made, so running the+tests left a file on the developer's machine and two runs could collide. Anything we persist goes+through the hub's stores (AiHub::with_stores, Session::isolated), which tests point at a temp+folder; production code never writes under the real config folder by hand.