Skip to main content

byob_types/
profile.rs

1//! Model profiles: a saved model (endpoint, model id, what it is good at) that the global
2//! level, a workspace, a chat or a model role can pick by id.
3//!
4//! A profile lives in `settings.json` `profiles.<id>`; its API key in `secrets.json`
5//! `profile_keys.<id>` (never here, never sent to clients). Roles (`settings.json`
6//! `roles.<role>` → profile id) say which profile does what: [`ROLE_MAIN`] is the default
7//! model of every chat, [`ROLE_VISION`] looks at images for a model that can't.
8//!
9//! [`ROLE_UTILITY`] writes chat titles and compaction summaries.
10//!
11//! A profile's [`Profile::params`] go with every chat request made with it, and its
12//! [`Profile::context`] replaces the probed window (both through [`Profile::config`]).
13//! Unknown fields are kept in [`Profile::extra`] so a newer byob's additions survive.
14//!
15//! This module is pure (no I/O): the store, the engine and the UI share it.
16
17use std::collections::BTreeMap;
18
19use serde::de::DeserializeOwned;
20use serde::{Deserialize, Deserializer, Serialize};
21use serde_json::{Map, Value};
22
23use crate::config::{Effective, Forced, Keys, Layer, Level, Levels, MAX_MODEL_CHARS, MAX_URL_CHARS, Sourced, ToolMode, resolve};
24use crate::{ApiKind, InferenceConfig};
25
26/// The default model of every chat (the "Connection" of older builds).
27pub const ROLE_MAIN: &str = "main";
28/// The model subagents use unless the `delegate` call, their agent or a workspace or chat
29/// names another (the global level's subagent model).
30pub const ROLE_SUBAGENTS: &str = "subagents";
31/// Looks at images for a chat whose model can't.
32pub const ROLE_VISION: &str = "vision";
33/// Writes chat titles and compaction summaries (unset: the chat's own model).
34pub const ROLE_UTILITY: &str = "utility";
35/// The roles byob knows, in the order the UI lists them. Other role names (from
36/// `settings.json` `models.<name>` of older builds) are kept and work as agents' `model:`.
37pub const ROLES: [&str; 4] = [ROLE_MAIN, ROLE_SUBAGENTS, ROLE_VISION, ROLE_UTILITY];
38
39/// Longest profile id.
40pub const MAX_ID_CHARS: usize = 64;
41/// Longest profile name.
42pub const MAX_NAME_CHARS: usize = 80;
43/// Longest description.
44pub const MAX_DESCRIPTION_CHARS: usize = 1000;
45/// Largest `params.extra`, as JSON.
46pub const MAX_EXTRA_BYTES: usize = 16 * 1024;
47/// Most profiles one settings file may hold.
48pub const MAX_PROFILES: usize = 200;
49/// Longest role name.
50pub const MAX_ROLE_CHARS: usize = 64;
51
52/// A field that falls back to `None` when the stored value has the wrong shape.
53fn lenient<'de, D: Deserializer<'de>, T: DeserializeOwned>(d: D) -> Result<Option<T>, D::Error> {
54    let v = Value::deserialize(d)?;
55    Ok(serde_json::from_value(v).ok())
56}
57
58/// A field that falls back to its default when the stored value has the wrong shape.
59fn lenient_or_default<'de, D: Deserializer<'de>, T: DeserializeOwned + Default>(d: D) -> Result<T, D::Error> {
60    let v = Value::deserialize(d)?;
61    Ok(serde_json::from_value(v).unwrap_or_default())
62}
63
64fn is_false(b: &bool) -> bool {
65    !*b
66}
67
68/// Request body fields byob sets itself: [`Params::extra`] can't set them (the engine
69/// refuses a profile that tries, and byob-llm skips them).
70pub const PROTECTED_FIELDS: [&str; 7] = ["model", "messages", "tools", "stream", "stream_options", "id_slot", "system"];
71
72/// How hard a Claude model thinks (Anthropic `output_config.effort`).
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
74#[serde(rename_all = "lowercase")]
75pub enum Effort {
76    Low,
77    Medium,
78    High,
79    Xhigh,
80    Max,
81}
82
83impl Effort {
84    pub const ALL: [Effort; 5] = [Effort::Low, Effort::Medium, Effort::High, Effort::Xhigh, Effort::Max];
85
86    /// The API's name for it.
87    pub fn as_str(self) -> &'static str {
88        match self {
89            Effort::Low => "low",
90            Effort::Medium => "medium",
91            Effort::High => "high",
92            Effort::Xhigh => "xhigh",
93            Effort::Max => "max",
94        }
95    }
96}
97
98/// Request parameters for a profile's model, sent with every chat request made with it
99/// (see `byob_llm::params`). Unset ones are left to the server.
100#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
101pub struct Params {
102    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
103    pub temperature: Option<f64>,
104    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
105    pub top_p: Option<f64>,
106    /// Most tokens of one reply (Anthropic: replaces byob's 64000, thinking included).
107    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
108    pub max_tokens: Option<u32>,
109    /// Anthropic only: `output_config.effort`; unset is the API's default.
110    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
111    pub effort: Option<Effort>,
112    /// A JSON object merged into the request body last (e.g. `{"chat_template_kwargs": {…}}`):
113    /// objects merge key by key, anything else replaces. It may override the fields above,
114    /// never the [`PROTECTED_FIELDS`].
115    #[serde(default, deserialize_with = "lenient_or_default", skip_serializing_if = "Map::is_empty")]
116    pub extra: Map<String, Value>,
117    /// Fields this build doesn't know; preserved.
118    #[serde(flatten)]
119    pub rest: Map<String, Value>,
120}
121
122impl Params {
123    pub fn is_empty(&self) -> bool {
124        *self == Self::default()
125    }
126}
127
128/// A saved model. Its key is in `secrets.json` `profile_keys.<id>`.
129#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
130pub struct Profile {
131    /// Stable id (`[a-z0-9][a-z0-9._-]*`); levels and roles point at it. In settings.json
132    /// the map key is authoritative.
133    #[serde(default, deserialize_with = "lenient_or_default")]
134    pub id: String,
135    /// What the user calls it.
136    #[serde(default, deserialize_with = "lenient_or_default")]
137    pub name: String,
138    #[serde(default, deserialize_with = "lenient_or_default")]
139    pub base_url: String,
140    #[serde(default, deserialize_with = "lenient_or_default")]
141    pub model: String,
142    /// Free text: what it is good at ("fast, good at code").
143    #[serde(default, deserialize_with = "lenient_or_default", skip_serializing_if = "String::is_empty")]
144    pub description: String,
145    /// The API it speaks; `None` decides from the URL (see `InferenceConfig::api_kind`).
146    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
147    pub api: Option<ApiKind>,
148    /// How tools are passed to this model; when set it beats the levels' tool mode.
149    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
150    pub tool_mode: Option<ToolMode>,
151    /// Offered to the main model as a `delegate` `model` choice (its description says when).
152    #[serde(default, deserialize_with = "lenient_or_default", skip_serializing_if = "is_false")]
153    pub subagents: bool,
154    /// Most subagents running on this model at once (besides the global cap and the
155    /// server's free slots).
156    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
157    pub max_parallel: Option<u16>,
158    /// Context window, overriding what the probe found (budgeting and compaction).
159    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
160    pub context: Option<u32>,
161    /// Request parameters, sent with every chat request made with it.
162    #[serde(default, deserialize_with = "lenient_or_default", skip_serializing_if = "Params::is_empty")]
163    pub params: Params,
164    /// Fields this build doesn't know (a newer byob's, or hand edits); preserved.
165    #[serde(flatten)]
166    pub extra: Map<String, Value>,
167}
168
169/// A profile id as byob makes them: `[a-z0-9][a-z0-9._-]{0,63}`.
170pub fn id_ok(id: &str) -> bool {
171    let b = id.as_bytes();
172    let ok = |c: u8| c.is_ascii_lowercase() || c.is_ascii_digit();
173    !b.is_empty() && b.len() <= MAX_ID_CHARS && ok(b[0]) && b.iter().all(|&c| ok(c) || matches!(c, b'-' | b'_' | b'.'))
174}
175
176/// A role name: like an id, a little more lenient (older `models.<name>` keys).
177pub fn role_ok(role: &str) -> bool {
178    !role.trim().is_empty() && role.chars().count() <= MAX_ROLE_CHARS && !role.chars().any(char::is_control)
179}
180
181/// A fresh id for a profile called `name`, not in `taken`: its slug, then slug-2, slug-3, …
182pub fn new_id(name: &str, taken: impl Fn(&str) -> bool) -> String {
183    let mut slug = String::new();
184    for c in name.trim().chars() {
185        if c.is_ascii_alphanumeric() {
186            slug.push(c.to_ascii_lowercase());
187        } else if matches!(c, '.' | '_') && !slug.is_empty() {
188            slug.push(c);
189        } else if !slug.is_empty() && !slug.ends_with('-') {
190            slug.push('-');
191        }
192    }
193    let slug: String = slug.trim_end_matches(['-', '.', '_']).chars().take(48).collect();
194    let slug = if slug.is_empty() { "model".to_owned() } else { slug };
195    if !taken(&slug) {
196        return slug;
197    }
198    (2..u32::MAX).map(|n| format!("{slug}-{n}")).find(|c| !taken(c)).unwrap_or(slug)
199}
200
201/// Scheme, host and port of a URL, then the rest without a trailing slash: two URLs that
202/// mean the same endpoint compare equal.
203pub fn same_url(a: &str, b: &str) -> bool {
204    a.trim().trim_end_matches('/').eq_ignore_ascii_case(b.trim().trim_end_matches('/'))
205}
206
207impl Profile {
208    /// Is it usable (a URL and a model)?
209    pub fn usable(&self) -> bool {
210        !self.base_url.trim().is_empty() && !self.model.trim().is_empty()
211    }
212
213    /// The endpoint, with `key`.
214    pub fn config(&self, key: Option<String>) -> InferenceConfig {
215        InferenceConfig {
216            base_url: self.base_url.trim().to_owned(),
217            model: self.model.trim().to_owned(),
218            api_key: key.filter(|k| !k.is_empty()),
219            api: self.api,
220            params: Params { rest: Map::new(), ..self.params.clone() },
221            context: self.context,
222        }
223    }
224
225    /// Does it speak Anthropic's Messages API (set, or decided from the URL)?
226    pub fn anthropic(&self) -> bool {
227        self.config(None).api_kind() == ApiKind::Anthropic
228    }
229
230    /// Does it point at this endpoint (same URL and model)?
231    pub fn points_at(&self, base_url: &str, model: &str) -> bool {
232        same_url(&self.base_url, base_url) && self.model.trim() == model.trim()
233    }
234
235    /// The name, or the model when it has none.
236    pub fn label(&self) -> &str {
237        if self.name.trim().is_empty() { self.model.trim() } else { self.name.trim() }
238    }
239
240    /// Check an untrusted profile: trims text, refuses what doesn't fit. The id is the
241    /// caller's business (the engine makes new ones).
242    pub fn validated(mut self) -> Result<Self, String> {
243        self.name = self.name.trim().to_owned();
244        self.base_url = self.base_url.trim().to_owned();
245        self.model = self.model.trim().to_owned();
246        self.description = self.description.trim().to_owned();
247        if self.name.is_empty() {
248            self.name.clone_from(&self.model);
249        }
250        if self.name.chars().count() > MAX_NAME_CHARS {
251            return Err(format!("names are limited to {MAX_NAME_CHARS} characters"));
252        }
253        if self.base_url.chars().count() > MAX_URL_CHARS {
254            return Err("the URL is too long".into());
255        }
256        if !(self.base_url.starts_with("http://") || self.base_url.starts_with("https://")) {
257            return Err(format!("{:?} isn't an http:// or https:// URL", self.base_url));
258        }
259        if self.model.is_empty() {
260            return Err("a model needs a model id (as the server names it)".into());
261        }
262        if self.model.chars().count() > MAX_MODEL_CHARS {
263            return Err("the model name is too long".into());
264        }
265        if self.description.chars().count() > MAX_DESCRIPTION_CHARS {
266            return Err(format!("descriptions are limited to {MAX_DESCRIPTION_CHARS} characters"));
267        }
268        let finite = |v: Option<f64>, max: f64| v.is_none_or(|v| v.is_finite() && (0.0..=max).contains(&v));
269        if !finite(self.params.temperature, 5.0) {
270            return Err("temperature must be between 0 and 5".into());
271        }
272        if !finite(self.params.top_p, 1.0) {
273            return Err("top_p must be between 0 and 1".into());
274        }
275        if self.params.max_tokens == Some(0) {
276            return Err("max_tokens must be at least 1".into());
277        }
278        if let Some(k) = PROTECTED_FIELDS.iter().find(|k| self.params.extra.contains_key(**k)) {
279            return Err(format!("the extra request JSON can't set {k:?}: byob sets it"));
280        }
281        let size = serde_json::to_string(&self.params).map_or(usize::MAX, |s| s.len()) + serde_json::to_string(&self.extra).map_or(usize::MAX, |s| s.len());
282        if size > MAX_EXTRA_BYTES {
283            return Err(format!("extra request fields are limited to {MAX_EXTRA_BYTES} bytes"));
284        }
285        self.max_parallel = self.max_parallel.filter(|n| *n > 0);
286        self.context = self.context.filter(|n| *n > 0);
287        Ok(self)
288    }
289}
290
291/// Read a `profiles` map leniently: an entry that isn't an object is dropped (with a
292/// warning), every other one keeps what it can; the map key becomes the id.
293pub fn profiles_from(v: Value, warnings: &mut Vec<String>) -> BTreeMap<String, Profile> {
294    let Value::Object(map) = v else {
295        if !v.is_null() {
296            warnings.push("ignored settings.json profiles: not an object".into());
297        }
298        return BTreeMap::new();
299    };
300    let mut out = BTreeMap::new();
301    for (id, entry) in map {
302        if !id_ok(&id) {
303            warnings.push(format!("ignored profile {id:?}: ids are lowercase letters, digits, '-', '_' and '.'"));
304            continue;
305        }
306        match serde_json::from_value::<Profile>(entry) {
307            Ok(mut p) if out.len() < MAX_PROFILES => {
308                p.id.clone_from(&id);
309                out.insert(id, p);
310            }
311            Ok(_) => warnings.push(format!("ignored profile {id:?}: at most {MAX_PROFILES} profiles")),
312            Err(e) => warnings.push(format!("ignored profile {id:?}: {e}")),
313        }
314    }
315    out
316}
317
318/// Pick `wanted` (a profile id) among `profiles`, if it exists and is usable.
319pub fn find<'a>(profiles: &'a BTreeMap<String, Profile>, wanted: Option<&str>) -> Option<&'a Profile> {
320    wanted.and_then(|id| profiles.get(id)).filter(|p| p.usable())
321}
322
323/// A level as the resolver sees it: the endpoint of its profile in place of its own
324/// `base_url`/`model`. A profile that doesn't exist (deleted) or can't be used leaves the
325/// level without an endpoint, so it inherits one; its id comes back as the error.
326pub fn apply<'a>(layer: &Layer, profiles: &'a BTreeMap<String, Profile>) -> (Layer, Result<Option<&'a Profile>, String>) {
327    let Some(id) = layer.profile.as_deref() else { return (layer.clone(), Ok(None)) };
328    match find(profiles, Some(id)) {
329        Some(p) => (Layer { base_url: Some(p.base_url.trim().to_owned()), model: Some(p.model.trim().to_owned()), ..layer.clone() }, Ok(Some(p))),
330        None => (Layer { profile: None, base_url: None, model: None, ..layer.clone() }, Err(id.to_owned())),
331    }
332}
333
334/// What [`resolve_with`] found besides the settings.
335#[derive(Debug)]
336pub struct Resolved<'a> {
337    pub effective: Effective,
338    /// The profile whose endpoint is used, and the level that picked it.
339    pub profile: Option<(Level, &'a Profile)>,
340    /// Profiles levels point at that don't exist (they inherit instead).
341    pub missing: Vec<String>,
342}
343
344/// [`resolve`] with profiles: each level's profile stands in for its endpoint; the key of
345/// the level whose profile is used is that profile's (`has_key`); a profile's tool mode,
346/// when it sets one, beats every level's (not a command-line flag).
347pub fn resolve_with<'a>(
348    levels: Levels<'_>,
349    keys: Keys,
350    forced: Forced,
351    profiles: &'a BTreeMap<String, Profile>,
352    has_key: impl Fn(&str) -> bool,
353) -> Resolved<'a> {
354    let mut missing = Vec::new();
355    // Per level: the layer as resolved, its profile, and whether its profile is gone.
356    let mut picked: [(Option<Layer>, Option<&'a Profile>, bool); 3] = [(None, None, false), (None, None, false), (None, None, false)];
357    for (slot, layer) in picked.iter_mut().zip([levels.global, levels.workspace, levels.chat]) {
358        if let Some(l) = layer {
359            let (applied, p) = apply(l, profiles);
360            match p {
361                Ok(p) => slot.1 = p,
362                Err(id) => {
363                    missing.push(id);
364                    slot.2 = true;
365                }
366            }
367            slot.0 = Some(applied);
368        }
369    }
370    let [(g, gp, g_gone), (w, wp, w_gone), (c, cp, c_gone)] = &picked;
371    let applied = Levels { global: g.as_ref(), workspace: w.as_ref(), chat: c.as_ref() };
372    // A level with a profile has the key its profile has (none: none), whatever it stored;
373    // the key a level kept for a profile that is gone isn't used.
374    let own = |p: &Option<&Profile>, gone: bool, stored: bool| match p {
375        Some(p) => has_key(&p.id),
376        None => stored && !gone,
377    };
378    let keys = Keys {
379        global: own(gp, *g_gone, keys.global) || (gp.is_some() && keys.global),
380        workspace: own(wp, *w_gone, keys.workspace),
381        chat: own(cp, *c_gone, keys.chat),
382    };
383    let mut effective = resolve(applied, keys, forced);
384    // The subagent model: the most specific level's that still exists.
385    effective.subagent_profile = None;
386    for (from, layer) in [(Level::Chat, levels.chat), (Level::Workspace, levels.workspace), (Level::Global, levels.global)] {
387        let Some(id) = layer.and_then(|l| l.subagent_profile.as_deref()) else { continue };
388        if find(profiles, Some(id)).is_some() {
389            effective.subagent_profile = Some(Sourced { value: id.to_owned(), from });
390            break;
391        }
392        missing.push(id.to_owned());
393    }
394    let from = effective.base_url.from;
395    let profile = match from {
396        Level::Global => *gp,
397        Level::Workspace => *wp,
398        Level::Chat => *cp,
399        Level::Default | Level::Flag => None,
400    }
401    .filter(|p| p.points_at(&effective.base_url.value, &effective.model.value))
402    .map(|p| (from, p));
403    if let Some((level, p)) = profile {
404        effective.key_from = (has_key(&p.id) || (level == Level::Global && keys.global)).then_some(level);
405        if let Some(m) = p.tool_mode
406            && effective.tool_mode.from != Level::Flag
407        {
408            effective.tool_mode = Sourced { value: m, from: level };
409        }
410    }
411    Resolved { effective, profile, missing }
412}
413
414#[cfg(test)]
415mod tests {
416    use super::*;
417
418    fn profile(id: &str, url: &str, model: &str) -> Profile {
419        Profile { id: id.into(), name: id.into(), base_url: url.into(), model: model.into(), ..Profile::default() }
420    }
421
422    #[test]
423    fn a_levels_profile_beats_its_own_endpoint_and_the_most_specific_level_wins() {
424        let mut ps = BTreeMap::new();
425        ps.insert("big".to_owned(), Profile { tool_mode: Some(ToolMode::Prompt), ..profile("big", "http://big/v1", "large") });
426        ps.insert("small".to_owned(), profile("small", "http://small/v1", "tiny"));
427        let g = Layer { base_url: Some("http://g/v1".into()), model: Some("gm".into()), tool_mode: Some(ToolMode::Native), ..Layer::default() };
428        // The workspace picked "big" and still carries an old copy of another endpoint.
429        let w = Layer { profile: Some("big".into()), base_url: Some("http://stale/v1".into()), model: Some("stale".into()), ..Layer::default() };
430        let has = |id: &str| id == "big";
431        let r =
432            resolve_with(Levels { global: Some(&g), workspace: Some(&w), chat: None }, Keys { global: true, ..Keys::default() }, Forced::default(), &ps, has);
433        assert_eq!(r.effective.base_url, Sourced { value: "http://big/v1".into(), from: Level::Workspace });
434        assert_eq!(r.effective.model.value, "large");
435        assert_eq!(r.effective.key_from, Some(Level::Workspace));
436        assert_eq!(r.effective.tool_mode, Sourced { value: ToolMode::Prompt, from: Level::Workspace }, "the profile's tool mode beats the levels'");
437        assert_eq!(r.profile.map(|(l, p)| (l, p.id.as_str())), Some((Level::Workspace, "big")));
438        // A chat's profile beats the workspace's; it has no key, so none is used.
439        let c = Layer { profile: Some("small".into()), ..Layer::default() };
440        let r = resolve_with(
441            Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c) },
442            Keys { global: true, workspace: true, chat: true },
443            Forced::default(),
444            &ps,
445            has,
446        );
447        assert_eq!((r.effective.base_url.value.as_str(), r.effective.model.from), ("http://small/v1", Level::Chat));
448        assert_eq!(r.effective.key_from, None, "a profile without a key uses none, even if the level stored one");
449        assert_eq!(r.effective.tool_mode, Sourced { value: ToolMode::Native, from: Level::Global });
450        // A command-line tool mode still wins.
451        let forced = Forced { tool_mode: Some(ToolMode::Native), ..Forced::default() };
452        let r = resolve_with(Levels { global: Some(&g), workspace: Some(&w), chat: None }, Keys::default(), forced, &ps, has);
453        assert_eq!(r.effective.tool_mode.from, Level::Flag);
454    }
455
456    #[test]
457    fn a_deleted_profile_falls_back_to_inheriting() {
458        let ps = BTreeMap::new();
459        let g = Layer { base_url: Some("http://g/v1".into()), model: Some("gm".into()), ..Layer::default() };
460        let w = Layer { profile: Some("gone".into()), base_url: Some("http://copy/v1".into()), model: Some("copy".into()), ..Layer::default() };
461        let r = resolve_with(
462            Levels { global: Some(&g), workspace: Some(&w), chat: None },
463            Keys { global: true, workspace: true, chat: false },
464            Forced::default(),
465            &ps,
466            |_| true,
467        );
468        assert_eq!(r.effective.base_url, Sourced { value: "http://g/v1".into(), from: Level::Global });
469        assert_eq!(r.effective.key_from, Some(Level::Global));
470        assert_eq!(r.missing, ["gone"]);
471        assert!(r.profile.is_none());
472        // An unusable profile (no URL) counts as missing too.
473        let ps = [("x".to_owned(), profile("x", "", "m"))].into();
474        let c = Layer { profile: Some("x".into()), ..Layer::default() };
475        let r = resolve_with(Levels { global: Some(&g), workspace: None, chat: Some(&c) }, Keys::default(), Forced::default(), &ps, |_| false);
476        assert_eq!((r.effective.base_url.from, r.missing.len()), (Level::Global, 1));
477    }
478
479    #[test]
480    fn profiles_round_trip_and_keep_unknown_fields() {
481        let json = serde_json::json!({
482            "id": "qwen",
483            "name": "Qwen",
484            "base_url": "http://h/v1",
485            "model": "qwen3",
486            "description": "fast, good at code",
487            "tool_mode": "native",
488            "subagents": true,
489            "max_parallel": 2,
490            "context": 32768,
491            "params": {"temperature": 0.7, "top_p": 0.9, "max_tokens": 4096, "effort": "xhigh", "extra": {"chat_template_kwargs": {"enable_thinking": false}}, "min_p": 0.05},
492            "api": "anthropic",
493            "effort_hint": "low",
494        });
495        let p: Profile = serde_json::from_value(json.clone()).unwrap();
496        assert_eq!(p.tool_mode, Some(ToolMode::Native));
497        assert_eq!((p.subagents, p.max_parallel, p.context), (true, Some(2), Some(32768)));
498        assert_eq!(p.params.temperature, Some(0.7));
499        assert_eq!(p.params.rest.get("min_p"), Some(&serde_json::json!(0.05)));
500        assert_eq!(p.api, Some(ApiKind::Anthropic));
501        assert_eq!(p.extra.get("effort_hint"), Some(&serde_json::json!("low")));
502        assert_eq!(serde_json::to_value(&p).unwrap(), json);
503        // Its endpoint carries its request options and context, not the fields it doesn't know.
504        let c = p.config(None);
505        assert_eq!((c.params.effort, c.params.max_tokens, c.context), (Some(Effort::Xhigh), Some(4096), Some(32768)));
506        assert!(c.params.rest.is_empty() && c.params.extra.contains_key("chat_template_kwargs"));
507        // An effort this build doesn't know reads as unset.
508        let odd: Params = serde_json::from_value(serde_json::json!({"effort": "ludicrous", "top_p": 0.5})).unwrap();
509        assert_eq!((odd.effort, odd.top_p), (None, Some(0.5)));
510        // A minimal profile writes only what it has.
511        let small = Profile { id: "a".into(), name: "A".into(), base_url: "http://h/v1".into(), model: "m".into(), ..Profile::default() };
512        assert_eq!(serde_json::to_string(&small).unwrap(), r#"{"id":"a","name":"A","base_url":"http://h/v1","model":"m"}"#);
513    }
514
515    #[test]
516    fn bad_values_fall_back_one_by_one() {
517        let mut warnings = Vec::new();
518        let v = serde_json::json!({
519            "ok": {"base_url": "http://h/v1", "model": "m", "tool_mode": "sometimes", "max_parallel": -3, "params": "hot"},
520            "Bad Id": {"base_url": "http://h/v1", "model": "m"},
521            "worse": 5,
522        });
523        let ps = profiles_from(v, &mut warnings);
524        assert_eq!(ps.len(), 1, "{warnings:?}");
525        let p = &ps["ok"];
526        assert_eq!((p.id.as_str(), p.tool_mode, p.max_parallel, p.params.is_empty()), ("ok", None, None, true));
527        assert_eq!(warnings.len(), 2);
528        assert!(profiles_from(Value::Null, &mut warnings).is_empty());
529    }
530
531    #[test]
532    fn untrusted_profiles_are_checked() {
533        let p = Profile { name: " ".into(), base_url: " http://h/v1 ".into(), model: " m ".into(), ..Profile::default() };
534        let ok = p.clone().validated().unwrap();
535        assert_eq!((ok.name.as_str(), ok.base_url.as_str(), ok.model.as_str()), ("m", "http://h/v1", "m"));
536        assert!(Profile { base_url: "file:///etc".into(), ..p.clone() }.validated().is_err());
537        assert!(Profile { model: String::new(), ..p.clone() }.validated().is_err());
538        let hot = Profile { params: Params { temperature: Some(f64::NAN), ..Params::default() }, ..p.clone() };
539        assert!(hot.validated().is_err());
540        let mut big = p;
541        big.params.extra.insert("x".into(), Value::String("y".repeat(MAX_EXTRA_BYTES)));
542        assert!(big.validated().is_err());
543        // The extra request JSON can't set the fields byob sets; anything else goes.
544        let base = Profile { base_url: "http://h/v1".into(), model: "m".into(), ..Profile::default() };
545        for k in PROTECTED_FIELDS {
546            let mut p = base.clone();
547            p.params.extra.insert(k.into(), Value::Bool(true));
548            let err = p.validated().unwrap_err();
549            assert!(err.contains(k), "{err}");
550        }
551        let mut ok = base.clone();
552        ok.params.extra.insert("chat_template_kwargs".into(), serde_json::json!({"enable_thinking": false}));
553        assert!(ok.validated().is_ok());
554        assert!(Profile { params: Params { max_tokens: Some(0), ..Params::default() }, ..base }.validated().is_err());
555    }
556
557    #[test]
558    fn ids_are_slugs_and_unique() {
559        assert_eq!(new_id("Qwen 3 (fast)", |_| false), "qwen-3-fast");
560        assert_eq!(new_id("gpt-4.1", |_| false), "gpt-4.1");
561        assert_eq!(new_id("  ", |_| false), "model");
562        assert_eq!(new_id("x", |id| id == "x" || id == "x-2"), "x-3");
563        assert!(id_ok("qwen-3_b.1") && !id_ok("Qwen") && !id_ok("-a") && !id_ok(""));
564        assert!(same_url("HTTP://h:1/v1/", "http://h:1/v1"));
565    }
566
567    #[test]
568    fn the_subagent_model_is_the_most_specific_levels_that_exists() {
569        let ps: BTreeMap<String, Profile> =
570            [("role".to_owned(), profile("role", "http://r/v1", "r")), ("ws".to_owned(), profile("ws", "http://w/v1", "w"))].into();
571        let g = Layer { subagent_profile: Some("role".into()), ..Layer::default() };
572        let w = Layer { subagent_profile: Some("ws".into()), ..Layer::default() };
573        let c = Layer { subagent_profile: Some("gone".into()), ..Layer::default() };
574        let at = |levels: Levels<'_>| {
575            let r = resolve_with(levels, Keys::default(), Forced::default(), &ps, |_| false);
576            (r.effective.subagent_profile.map(|s| (s.value, s.from)), r.missing)
577        };
578        let some = |id: &str, l: Level| Some((id.to_owned(), l));
579        assert_eq!(at(Levels { global: Some(&g), workspace: None, chat: None }), (some("role", Level::Global), vec![]));
580        assert_eq!(at(Levels { global: Some(&g), workspace: Some(&w), chat: None }), (some("ws", Level::Workspace), vec![]));
581        // The chat's is deleted: the workspace's applies, and the chat's is reported.
582        assert_eq!(at(Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c) }), (some("ws", Level::Workspace), vec!["gone".to_owned()]));
583        assert_eq!(at(Levels { global: None, workspace: None, chat: Some(&c) }), (None, vec!["gone".to_owned()]));
584        assert_eq!(at(Levels::default()), (None, vec![]));
585        // Checked like a level's own profile.
586        assert!(Layer { subagent_profile: Some("Not An Id".into()), ..Layer::default() }.validated(Level::Chat).is_err());
587        assert_eq!(Layer { subagent_profile: Some(" ".into()), ..Layer::default() }.validated(Level::Chat).unwrap().subagent_profile, None);
588    }
589}