返回 CodeWhale
opencode_catalog.rs
根目录 / crates / engine / src / client / opencode_catalog.rs
1 use super::{CatalogOffering, CatalogRefreshError, CatalogSource};
2 use codewhale_config::models_dev::ModelsDevLimit;
3 use serde::Deserialize;
4 use serde_json::Value;
5 use std::collections::HashSet;
6
7 #[derive(Deserialize)]
8 struct Inventory {
9 data: Vec<Value>,
10 }
11
12 pub(crate) fn official_listing(base: &str) -> bool {
13 codewhale_config::opencode_go_listing_base_url(base) == "https://opencode.ai/inference/go/v1"
14 }
15
16 fn supported(capability: &Value) -> Option<bool> {
17 capability
18 .as_bool()
19 .or_else(|| capability["supported"].as_bool())
20 }
21
22 fn contains_secret(value: &Value, secret: &str) -> bool {
23 match value {
24 Value::String(text) => text.contains(secret),
25 Value::Array(items) => items.iter().any(|item| contains_secret(item, secret)),
26 Value::Object(fields) => fields
27 .iter()
28 .any(|(key, item)| key.contains(secret) || contains_secret(item, secret)),
29 _ => false,
30 }
31 }
32
33 fn chat_api(connection: &str, api: &Value) -> Option<(&'static str, String)> {
34 let endpoints = api.as_object()?;
35 if endpoints.len() != 1 {
36 return None;
37 }
38 let (name, endpoint) = endpoints.iter().next()?;
39 let key = match name.as_str() {
40 "chat-completions" => "chat",
41 "messages" => "messages",
42 "responses" => "responses",
43 "generate-content" => "generate-content",
44 _ => return None,
45 };
46 let url = codewhale_config::opencode_go_dispatch_base_url(
47 connection,
48 endpoint["base_url"].as_str()?,
49 )?;
50 Some((key, url))
51 }
52
53 pub(super) fn parse(
54 body: &str,
55 provider: &str,
56 base: &str,
57 fingerprint: &str,
58 fetched_at: u64,
59 secrets: &[String],
60 ) -> Result<Option<Vec<CatalogOffering>>, CatalogRefreshError> {
61 let listing: Inventory =
62 serde_json::from_str(body).map_err(|_| CatalogRefreshError::InvalidResponse)?;
63 if listing.data.is_empty() {
64 return Ok(Some(Vec::new()));
65 }
66 if !official_listing(base)
67 && !listing
68 .data
69 .iter()
70 .any(|row| row.get("type").is_some() || row.get("api").is_some())
71 {
72 return Ok(None);
73 }
74 let mut offerings = Vec::new();
75 let mut seen = HashSet::new();
76 for row in listing.data {
77 let Some(id) = row["id"]
78 .as_str()
79 .filter(|id| codewhale_runtime::catalog_cache::valid_catalog_model_id(id))
80 else {
81 continue;
82 };
83 if !seen.insert(id.to_owned()) {
84 return Err(CatalogRefreshError::InvalidResponse);
85 }
86 if secrets.iter().any(|secret| {
87 !secret.is_empty()
88 && (id.contains(secret)
89 || ["type", "name", "api", "modalities"].iter().any(|key| {
90 row.get(*key)
91 .is_some_and(|value| contains_secret(value, secret))
92 }))
93 }) {
94 return Err(CatalogRefreshError::InvalidResponse);
95 }
96 let model_type = row["type"].as_str().unwrap_or("unknown");
97 let active = !matches!(
98 row["status"].as_str(),
99 Some("disabled" | "deprecated" | "retired")
100 ) && row["disabled"].as_bool() != Some(true)
101 && row["enabled"].as_bool() != Some(false);
102 let route = if model_type == "chat" && active {
103 chat_api(base, &row["api"])
104 } else {
105 None
106 };
107 let (endpoint, api) = match route {
108 Some((key, url)) => (key, Some(url)),
109 None => ("unproven", None),
110 };
111 let limit = ModelsDevLimit {
112 context: row["limit"]["context"].as_u64().filter(|n| *n > 0),
113 input: row["limit"]["input"].as_u64().filter(|n| *n > 0),
114 output: row["limit"]["output"].as_u64().filter(|n| *n > 0),
115 };
116 offerings.push(CatalogOffering {
117 provider: provider.to_owned(),
118 wire_model_id: id.to_owned(),
119 name: row["name"].as_str().map(str::to_owned),
120 model_type: Some(model_type.to_owned()),
121 modalities: serde_json::from_value(row["modalities"].clone()).ok(),
122 endpoint_key: endpoint.to_owned(),
123 provider_api: api,
124 status: if active {
125 None
126 } else {
127 Some("disabled".into())
128 },
129 limit: (limit != ModelsDevLimit::default()).then_some(limit),
130 reasoning: supported(&row["capabilities"]["reasoning"]),
131 tool_call: supported(&row["capabilities"]["tools"]),
132 source: CatalogSource::Live {
133 base_url_fingerprint: fingerprint.to_owned(),
134 fetched_at,
135 },
136 ..Default::default()
137 });
138 }
139 if offerings.is_empty() {
140 return Err(CatalogRefreshError::InvalidResponse);
141 }
142 Ok(Some(offerings))
143 }
144
145 #[cfg(test)]
146 mod tests {
147 use super::*;
148
149 #[test]
150 fn official_go_url_uses_normalized_https_authority_and_exact_path() {
151 assert!(official_listing("https://opencode.ai:443/inference/go/v1/"));
152 assert!(official_listing("https://OPENCODE.ai:443/zen/go/v1"));
153 assert!(!official_listing("https://opencode.ai/inference/GO/v1"));
154 assert!(!official_listing("https://opencode.ai:444/inference/go/v1"));
155 assert!(!official_listing(
156 "https://user@opencode.ai/inference/go/v1"
157 ));
158 }
159
160 #[test]
161 fn official_empty_or_untyped_listing_never_falls_back_to_legacy_roster() {
162 let base = "https://opencode.ai/inference/go/v1";
163 let empty = parse(r#"{"data":[]}"#, "opencode-go", base, "fingerprint", 1, &[])
164 .unwrap()
165 .unwrap();
166 assert!(empty.is_empty());
167 let untyped = parse(
168 r#"{"data":[{"id":"step-5","object":"model"}]}"#,
169 "opencode-go",
170 base,
171 "fingerprint",
172 1,
173 &[],
174 )
175 .unwrap()
176 .unwrap();
177 assert_eq!(untyped[0].endpoint_key, "unproven");
178 assert!(untyped[0].provider_api.is_none());
179 }
180 }
181
181 lines RUST