Skip to main content

waratah_api/ai/
config.rs

1//! The `[ai]` configuration document (`{config-dir}/ai.toml`) and its
2//! resolved form ([`AiConfig`]).
3//!
4//! Merge order follows the notebooks precedent (`waratah_notebook::
5//! options.rs`): CLI flag (`--with-ai`) > `ai.toml` value > built-in
6//! default. A missing file or a missing/`false` `[ai]` section leaves the
7//! feature disabled (`None`), which every AI route answers with `501`.
8//! When the feature is enabled and the document declares no upstreams, the
9//! single `zen` upstream is preconfigured so grevillea dev works out of the
10//! box (bring-your-own-key: the engine holds no key unless an upstream
11//! sets `api_key_env`).
12
13use std::time::Duration;
14
15use serde::Deserialize;
16use thiserror::Error;
17
18/// Default whole-request deadline for a proxied upstream call.
19pub const DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 120;
20
21/// Default TCP/TLS connect deadline for an upstream call.
22pub const DEFAULT_CONNECT_TIMEOUT_SECS: u64 = 10;
23
24/// Default request-body maximum on the proxy route (32 MiB).
25pub const DEFAULT_MAX_REQUEST_BODY_BYTES: usize = 33_554_432;
26
27/// Upstream id preconfigured by `--with-ai` when `ai.toml` declares none.
28pub const DEFAULT_UPSTREAM_ID: &str = "zen";
29
30/// Base URL of the preconfigured `zen` upstream.
31pub const DEFAULT_ZEN_BASE_URL: &str = "https://opencode.ai/zen/v1";
32
33/// Errors raised while resolving `ai.toml` into an [`AiConfig`].
34#[derive(Debug, Error)]
35pub enum AiConfigError {
36    /// An upstream id is not usable as a URL path segment.
37    #[error("ai upstream id {id:?} is not a valid path segment")]
38    InvalidUpstreamId {
39        /// The rejected id.
40        id: String,
41    },
42
43    /// A `base_url` is not an acceptable http(s) origin.
44    #[error("ai upstream base_url {url:?} is not a valid http(s) origin")]
45    InvalidBaseUrl {
46        /// The rejected URL.
47        url: String,
48    },
49
50    /// The TOML document could not be parsed.
51    #[error("invalid ai.toml: {0}")]
52    Toml(#[from] toml::de::Error),
53}
54
55/// The `{config-dir}/ai.toml` document.
56///
57/// Mirrors the contract's `[ai]` block verbatim (wrapper section included,
58/// unlike the flat `notebooks.toml` document, because `[ai.upstreams.<id>]`
59/// needs the nesting). Unknown keys are ignored so future knobs don't
60/// break older engines.
61#[derive(Debug, Clone, Default, Deserialize)]
62pub struct AiToml {
63    /// The `[ai]` table; absent ⇒ feature disabled.
64    pub ai: Option<AiTable>,
65}
66
67impl AiToml {
68    /// Parse an `ai.toml` document.
69    pub fn from_toml_str(text: &str) -> Result<Self, AiConfigError> {
70        Ok(toml::from_str(text)?)
71    }
72}
73
74/// The `[ai]` table of `ai.toml`.
75#[derive(Debug, Clone, Default, Deserialize)]
76pub struct AiTable {
77    /// Enable AI features (same as `--with-ai`).
78    pub enabled: Option<bool>,
79    /// Whole-request deadline for proxied calls, seconds.
80    pub request_timeout_secs: Option<u64>,
81    /// Connect deadline for proxied calls, seconds.
82    pub connect_timeout_secs: Option<u64>,
83    /// Request-body maximum on the proxy route, bytes.
84    pub max_request_body_bytes: Option<u64>,
85    /// `[ai.upstreams.<id>]` table; upstream id is the URL path segment.
86    pub upstreams: Option<std::collections::BTreeMap<String, UpstreamToml>>,
87}
88
89/// One `[ai.upstreams.<id>]` table.
90#[derive(Debug, Clone, Deserialize)]
91pub struct UpstreamToml {
92    /// Upstream origin (`http(s)://host[:port][/prefix]`). Trailing `/` is
93    /// trimmed at resolve time; query and fragment are rejected.
94    pub base_url: String,
95    /// Optional server-held key: name of an environment variable whose
96    /// value replaces the client's `Authorization` header verbatim (the
97    /// value is the complete header value — scheme prefix included).
98    pub api_key_env: Option<String>,
99}
100
101/// One resolved egress upstream.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct AiUpstream {
104    /// Path segment identifying this upstream (`/waratah/ai/upstreams/{id}`).
105    pub id: String,
106    /// Validated origin; no trailing `/`, no query, no fragment.
107    pub base_url: String,
108    /// Environment variable holding the complete `Authorization` value, if
109    /// the engine owns the key for this upstream.
110    pub api_key_env: Option<String>,
111}
112
113/// Fully resolved AI configuration (what `AppState` serves from).
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct AiConfig {
116    /// Whole-request deadline for one proxied upstream call.
117    pub request_timeout: Duration,
118    /// Connect deadline for one proxied upstream call.
119    pub connect_timeout: Duration,
120    /// Request-body maximum on the proxy route.
121    pub max_request_body_bytes: usize,
122    /// Upstreams, sorted by id (TOML's BTreeMap order preserved).
123    pub upstreams: Vec<AiUpstream>,
124}
125
126impl AiConfig {
127    /// Resolve the enabled state and all fields.
128    ///
129    /// `flag_enabled` is `--with-ai`; `toml` is the parsed `ai.toml`, when
130    /// found. Returns `None` when neither enables the feature. Upstream
131    /// preconfiguration: an enabled config with no declared upstreams gets
132    /// the single `zen` upstream; declared upstreams are the complete set.
133    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                // An id that cannot survive as a URL path segment would
146                // configure an upstream the proxy route can never resolve
147                // (discovery would advertise a `proxyPath` that does not
148                // round-trip) — fail the config load instead.
149                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            // `--with-ai` with no `[ai.upstreams]` table: grevillea dev
161            // works out of the box against the zen edge (BYOK).
162            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
189/// Validate and normalize a `base_url`:
190/// - must parse as an absolute `http`/`https` URI with a host;
191/// - must carry no query, fragment, or userinfo (this is an origin, and
192///   anything else would silently ride into every proxied request);
193/// - trailing `/` characters are trimmed (the proxy joins
194///   `base_url + "/" + path`).
195fn 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    // `http::Uri` does not model fragments, so a `#` in the raw string is
202    // either a parse error or trailing noise — reject it explicitly.
203    let clean = uri.query().is_none() && !raw.contains('#');
204    // `Uri::authority` keeps userinfo (`user@host`); a configured upstream
205    // must never forward static credentials.
206    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        // e.g. "https:///" — already rejected by the host check above; kept
215        // defensively so normalization can never produce an empty origin.
216        return Err(AiConfigError::InvalidBaseUrl {
217            url: raw.to_owned(),
218        });
219    }
220    Ok(trimmed.to_owned())
221}
222
223/// Upstream ids are single URL path segments: non-empty, not `.`/`..`, and
224/// free of separators and control-ish characters (same rules as the
225/// `/cors_proxy` compute ids).
226pub(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        // A file with no `[ai]` section at all.
251        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        // BTreeMap order (sorted by id) is preserved; trailing `/` trimmed.
295        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://",                        // no host
325            "https://example.com/v1?x=1",     // query
326            "https://example.com/v1#frag",    // fragment
327            "https://user:[email protected]/v1", // userinfo
328        ] {
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        // An id with a separator would advertise a proxyPath that never
354        // round-trips through the route, so config load must fail loudly.
355        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        // A clean id still resolves.
368        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}