1use std::time::Duration;
14
15use serde::Deserialize;
16use thiserror::Error;
17
18pub const DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 120;
20
21pub const DEFAULT_CONNECT_TIMEOUT_SECS: u64 = 10;
23
24pub const DEFAULT_MAX_REQUEST_BODY_BYTES: usize = 33_554_432;
26
27pub const DEFAULT_UPSTREAM_ID: &str = "zen";
29
30pub const DEFAULT_ZEN_BASE_URL: &str = "https://opencode.ai/zen/v1";
32
33#[derive(Debug, Error)]
35pub enum AiConfigError {
36 #[error("ai upstream id {id:?} is not a valid path segment")]
38 InvalidUpstreamId {
39 id: String,
41 },
42
43 #[error("ai upstream base_url {url:?} is not a valid http(s) origin")]
45 InvalidBaseUrl {
46 url: String,
48 },
49
50 #[error("invalid ai.toml: {0}")]
52 Toml(#[from] toml::de::Error),
53}
54
55#[derive(Debug, Clone, Default, Deserialize)]
62pub struct AiToml {
63 pub ai: Option<AiTable>,
65}
66
67impl AiToml {
68 pub fn from_toml_str(text: &str) -> Result<Self, AiConfigError> {
70 Ok(toml::from_str(text)?)
71 }
72}
73
74#[derive(Debug, Clone, Default, Deserialize)]
76pub struct AiTable {
77 pub enabled: Option<bool>,
79 pub request_timeout_secs: Option<u64>,
81 pub connect_timeout_secs: Option<u64>,
83 pub max_request_body_bytes: Option<u64>,
85 pub upstreams: Option<std::collections::BTreeMap<String, UpstreamToml>>,
87}
88
89#[derive(Debug, Clone, Deserialize)]
91pub struct UpstreamToml {
92 pub base_url: String,
95 pub api_key_env: Option<String>,
99}
100
101#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct AiUpstream {
104 pub id: String,
106 pub base_url: String,
108 pub api_key_env: Option<String>,
111}
112
113#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct AiConfig {
116 pub request_timeout: Duration,
118 pub connect_timeout: Duration,
120 pub max_request_body_bytes: usize,
122 pub upstreams: Vec<AiUpstream>,
124}
125
126impl AiConfig {
127 pub fn resolve(
134 flag_enabled: bool,
135 toml: Option<AiToml>,
136 ) -> Result<Option<Self>, AiConfigError> {
137 let table = toml.and_then(|doc| doc.ai).unwrap_or_default();
138 let enabled = flag_enabled || table.enabled.unwrap_or(false);
139 if !enabled {
140 return Ok(None);
141 }
142 let mut upstreams = Vec::new();
143 if let Some(declared) = table.upstreams {
144 for (id, upstream) in declared {
145 if !valid_upstream_id(&id) {
150 return Err(AiConfigError::InvalidUpstreamId { id });
151 }
152 upstreams.push(AiUpstream {
153 id,
154 base_url: validate_base_url(&upstream.base_url)?,
155 api_key_env: upstream.api_key_env,
156 });
157 }
158 }
159 if upstreams.is_empty() {
160 upstreams.push(AiUpstream {
163 id: DEFAULT_UPSTREAM_ID.to_owned(),
164 base_url: validate_base_url(DEFAULT_ZEN_BASE_URL)?,
165 api_key_env: None,
166 });
167 }
168 Ok(Some(Self {
169 request_timeout: Duration::from_secs(
170 table
171 .request_timeout_secs
172 .unwrap_or(DEFAULT_REQUEST_TIMEOUT_SECS),
173 ),
174 connect_timeout: Duration::from_secs(
175 table
176 .connect_timeout_secs
177 .unwrap_or(DEFAULT_CONNECT_TIMEOUT_SECS),
178 ),
179 max_request_body_bytes: table
180 .max_request_body_bytes
181 .map_or(DEFAULT_MAX_REQUEST_BODY_BYTES, |bytes| {
182 bytes.min(usize::MAX as u64) as usize
183 }),
184 upstreams,
185 }))
186 }
187}
188
189fn validate_base_url(raw: &str) -> Result<String, AiConfigError> {
196 let uri: axum::http::Uri = raw.parse().map_err(|_| AiConfigError::InvalidBaseUrl {
197 url: raw.to_owned(),
198 })?;
199 let scheme_ok = matches!(uri.scheme_str(), Some("http") | Some("https"));
200 let host_ok = uri.host().is_some_and(|host| !host.is_empty());
201 let clean = uri.query().is_none() && !raw.contains('#');
204 let userinfo_ok = uri.authority().is_none_or(|a| !a.as_str().contains('@'));
207 if !scheme_ok || !host_ok || !clean || !userinfo_ok {
208 return Err(AiConfigError::InvalidBaseUrl {
209 url: raw.to_owned(),
210 });
211 }
212 let trimmed = raw.trim_end_matches('/');
213 if trimmed.is_empty() {
214 return Err(AiConfigError::InvalidBaseUrl {
217 url: raw.to_owned(),
218 });
219 }
220 Ok(trimmed.to_owned())
221}
222
223pub(crate) fn valid_upstream_id(id: &str) -> bool {
227 !id.is_empty() && id != "." && id != ".." && !id.contains(['/', '\\', '\0', '?', '#', ' '])
228}
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233 use pretty_assertions::assert_eq;
234
235 fn resolve_flag() -> Option<AiConfig> {
236 AiConfig::resolve(true, None).unwrap()
237 }
238
239 #[test]
240 fn disabled_by_default() {
241 assert!(AiConfig::resolve(false, None).unwrap().is_none());
242 assert!(
243 AiConfig::resolve(
244 false,
245 Some(AiToml::from_toml_str("[ai]\nenabled = false\n").unwrap())
246 )
247 .unwrap()
248 .is_none()
249 );
250 assert!(
252 AiConfig::resolve(false, Some(AiToml::from_toml_str("").unwrap()))
253 .unwrap()
254 .is_none()
255 );
256 }
257
258 #[test]
259 fn flag_preconfigures_the_zen_upstream() {
260 let config = resolve_flag().unwrap();
261 assert_eq!(
262 config.upstreams,
263 vec![AiUpstream {
264 id: "zen".to_owned(),
265 base_url: DEFAULT_ZEN_BASE_URL.to_owned(),
266 api_key_env: None,
267 }]
268 );
269 assert_eq!(config.request_timeout, Duration::from_secs(120));
270 assert_eq!(config.connect_timeout, Duration::from_secs(10));
271 assert_eq!(config.max_request_body_bytes, 33_554_432);
272 }
273
274 #[test]
275 fn toml_overrides_defaults_and_declares_the_upstream_set() {
276 let toml = AiToml::from_toml_str(
277 r#"
278 [ai]
279 enabled = true
280 request_timeout_secs = 30
281
282 [ai.upstreams.anthropic]
283 base_url = "https://api.anthropic.com/v1/"
284
285 [ai.upstreams.zen]
286 base_url = "https://opencode.ai/zen/v1"
287 api_key_env = "WARATAH_ZEN_KEY"
288 "#,
289 )
290 .unwrap();
291 let config = AiConfig::resolve(false, Some(toml)).unwrap().unwrap();
292 assert_eq!(config.request_timeout, Duration::from_secs(30));
293 assert_eq!(config.connect_timeout, Duration::from_secs(10));
294 assert_eq!(
296 config.upstreams,
297 vec![
298 AiUpstream {
299 id: "anthropic".to_owned(),
300 base_url: "https://api.anthropic.com/v1".to_owned(),
301 api_key_env: None,
302 },
303 AiUpstream {
304 id: "zen".to_owned(),
305 base_url: "https://opencode.ai/zen/v1".to_owned(),
306 api_key_env: Some("WARATAH_ZEN_KEY".to_owned()),
307 },
308 ]
309 );
310 }
311
312 #[test]
313 fn unknown_keys_are_ignored() {
314 let toml = AiToml::from_toml_str("[ai]\nenabled = true\nfuture_knob = 7\n").unwrap();
315 let config = AiConfig::resolve(false, Some(toml)).unwrap().unwrap();
316 assert_eq!(config.upstreams.len(), 1, "zen preconfigured");
317 }
318
319 #[test]
320 fn invalid_base_urls_are_typed_errors() {
321 for url in [
322 "not a url",
323 "ftp://example.com",
324 "http://", "https://example.com/v1?x=1", "https://example.com/v1#frag", "https://user:[email protected]/v1", ] {
329 let error = validate_base_url(url).unwrap_err();
330 assert!(
331 matches!(error, AiConfigError::InvalidBaseUrl { .. }),
332 "{url} should be rejected"
333 );
334 }
335 assert_eq!(
336 validate_base_url("http://127.0.0.1:9123/base/").unwrap(),
337 "http://127.0.0.1:9123/base"
338 );
339 }
340
341 #[test]
342 fn invalid_upstream_ids_are_rejected() {
343 for id in ["", ".", "..", "a/b", "a\\b", "a?b", "a#b", "a b"] {
344 assert!(!valid_upstream_id(id), "{id:?} should be invalid");
345 }
346 for id in ["zen", "a.b", "up-1"] {
347 assert!(valid_upstream_id(id), "{id:?} should be valid");
348 }
349 }
350
351 #[test]
352 fn resolve_rejects_upstream_ids_that_cannot_be_routed() {
353 let toml = AiToml::from_toml_str(
356 r#"
357 [ai]
358 enabled = true
359
360 [ai.upstreams.'a/b']
361 base_url = "https://opencode.ai/zen/v1"
362 "#,
363 )
364 .unwrap();
365 let error = AiConfig::resolve(false, Some(toml)).unwrap_err();
366 assert!(matches!(error, AiConfigError::InvalidUpstreamId { .. }));
367 let toml = AiToml::from_toml_str(
369 r#"
370 [ai]
371 enabled = true
372
373 [ai.upstreams.zen]
374 base_url = "https://opencode.ai/zen/v1"
375 "#,
376 )
377 .unwrap();
378 assert!(AiConfig::resolve(false, Some(toml)).unwrap().is_some());
379 }
380}