1use 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
26pub const ROLE_MAIN: &str = "main";
28pub const ROLE_SUBAGENTS: &str = "subagents";
31pub const ROLE_VISION: &str = "vision";
33pub const ROLE_UTILITY: &str = "utility";
35pub const ROLES: [&str; 4] = [ROLE_MAIN, ROLE_SUBAGENTS, ROLE_VISION, ROLE_UTILITY];
38
39pub const MAX_ID_CHARS: usize = 64;
41pub const MAX_NAME_CHARS: usize = 80;
43pub const MAX_DESCRIPTION_CHARS: usize = 1000;
45pub const MAX_EXTRA_BYTES: usize = 16 * 1024;
47pub const MAX_PROFILES: usize = 200;
49pub const MAX_ROLE_CHARS: usize = 64;
51
52fn 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
58fn 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
68pub const PROTECTED_FIELDS: [&str; 7] = ["model", "messages", "tools", "stream", "stream_options", "id_slot", "system"];
71
72#[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 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#[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 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
108 pub max_tokens: Option<u32>,
109 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
111 pub effort: Option<Effort>,
112 #[serde(default, deserialize_with = "lenient_or_default", skip_serializing_if = "Map::is_empty")]
116 pub extra: Map<String, Value>,
117 #[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#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
130pub struct Profile {
131 #[serde(default, deserialize_with = "lenient_or_default")]
134 pub id: String,
135 #[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 #[serde(default, deserialize_with = "lenient_or_default", skip_serializing_if = "String::is_empty")]
144 pub description: String,
145 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
147 pub api: Option<ApiKind>,
148 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
150 pub tool_mode: Option<ToolMode>,
151 #[serde(default, deserialize_with = "lenient_or_default", skip_serializing_if = "is_false")]
153 pub subagents: bool,
154 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
157 pub max_parallel: Option<u16>,
158 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
160 pub context: Option<u32>,
161 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
164 pub compact_percent: Option<u8>,
165 #[serde(default, deserialize_with = "lenient_or_default", skip_serializing_if = "Params::is_empty")]
167 pub params: Params,
168 #[serde(flatten)]
170 pub extra: Map<String, Value>,
171}
172
173pub fn id_ok(id: &str) -> bool {
175 let b = id.as_bytes();
176 let ok = |c: u8| c.is_ascii_lowercase() || c.is_ascii_digit();
177 !b.is_empty() && b.len() <= MAX_ID_CHARS && ok(b[0]) && b.iter().all(|&c| ok(c) || matches!(c, b'-' | b'_' | b'.'))
178}
179
180pub fn role_ok(role: &str) -> bool {
182 !role.trim().is_empty() && role.chars().count() <= MAX_ROLE_CHARS && !role.chars().any(char::is_control)
183}
184
185pub fn new_id(name: &str, taken: impl Fn(&str) -> bool) -> String {
187 let mut slug = String::new();
188 for c in name.trim().chars() {
189 if c.is_ascii_alphanumeric() {
190 slug.push(c.to_ascii_lowercase());
191 } else if matches!(c, '.' | '_') && !slug.is_empty() {
192 slug.push(c);
193 } else if !slug.is_empty() && !slug.ends_with('-') {
194 slug.push('-');
195 }
196 }
197 let slug: String = slug.trim_end_matches(['-', '.', '_']).chars().take(48).collect();
198 let slug = if slug.is_empty() { "model".to_owned() } else { slug };
199 if !taken(&slug) {
200 return slug;
201 }
202 (2..u32::MAX).map(|n| format!("{slug}-{n}")).find(|c| !taken(c)).unwrap_or(slug)
203}
204
205pub fn same_url(a: &str, b: &str) -> bool {
208 a.trim().trim_end_matches('/').eq_ignore_ascii_case(b.trim().trim_end_matches('/'))
209}
210
211impl Profile {
212 pub fn usable(&self) -> bool {
214 !self.base_url.trim().is_empty() && !self.model.trim().is_empty()
215 }
216
217 pub fn config(&self, key: Option<String>) -> InferenceConfig {
219 InferenceConfig {
220 base_url: self.base_url.trim().to_owned(),
221 model: self.model.trim().to_owned(),
222 api_key: key.filter(|k| !k.is_empty()),
223 api: self.api,
224 params: Params { rest: Map::new(), ..self.params.clone() },
225 context: self.context,
226 }
227 }
228
229 pub fn anthropic(&self) -> bool {
231 self.config(None).api_kind() == ApiKind::Anthropic
232 }
233
234 pub fn points_at(&self, base_url: &str, model: &str) -> bool {
236 same_url(&self.base_url, base_url) && self.model.trim() == model.trim()
237 }
238
239 pub fn label(&self) -> &str {
241 if self.name.trim().is_empty() { self.model.trim() } else { self.name.trim() }
242 }
243
244 pub fn validated(mut self) -> Result<Self, String> {
247 self.name = self.name.trim().to_owned();
248 self.base_url = self.base_url.trim().to_owned();
249 self.model = self.model.trim().to_owned();
250 self.description = self.description.trim().to_owned();
251 if self.name.is_empty() {
252 self.name.clone_from(&self.model);
253 }
254 if self.name.chars().count() > MAX_NAME_CHARS {
255 return Err(format!("names are limited to {MAX_NAME_CHARS} characters"));
256 }
257 if self.base_url.chars().count() > MAX_URL_CHARS {
258 return Err("the URL is too long".into());
259 }
260 if !crate::endpoint_url_ok(&self.base_url) {
261 return Err(format!("{:?} isn't an http://, https:// or cli:// URL", self.base_url));
262 }
263 if self.model.is_empty() {
264 return Err("a model needs a model id (as the server names it)".into());
265 }
266 if self.model.chars().count() > MAX_MODEL_CHARS {
267 return Err("the model name is too long".into());
268 }
269 if self.description.chars().count() > MAX_DESCRIPTION_CHARS {
270 return Err(format!("descriptions are limited to {MAX_DESCRIPTION_CHARS} characters"));
271 }
272 let finite = |v: Option<f64>, max: f64| v.is_none_or(|v| v.is_finite() && (0.0..=max).contains(&v));
273 if !finite(self.params.temperature, 5.0) {
274 return Err("temperature must be between 0 and 5".into());
275 }
276 if !finite(self.params.top_p, 1.0) {
277 return Err("top_p must be between 0 and 1".into());
278 }
279 if self.params.max_tokens == Some(0) {
280 return Err("max_tokens must be at least 1".into());
281 }
282 if let Some(k) = PROTECTED_FIELDS.iter().find(|k| self.params.extra.contains_key(**k)) {
283 return Err(format!("the extra request JSON can't set {k:?}: byob sets it"));
284 }
285 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());
286 if size > MAX_EXTRA_BYTES {
287 return Err(format!("extra request fields are limited to {MAX_EXTRA_BYTES} bytes"));
288 }
289 self.max_parallel = self.max_parallel.filter(|n| *n > 0);
290 self.context = self.context.filter(|n| *n > 0);
291 if self.compact_percent.is_some_and(|p| !(10..=95).contains(&p)) {
292 return Err("compact at must be between 10 and 95 (% of the context window)".into());
293 }
294 Ok(self)
295 }
296}
297
298pub fn profiles_from(v: Value, warnings: &mut Vec<String>) -> BTreeMap<String, Profile> {
301 let Value::Object(map) = v else {
302 if !v.is_null() {
303 warnings.push("ignored settings.json profiles: not an object".into());
304 }
305 return BTreeMap::new();
306 };
307 let mut out = BTreeMap::new();
308 for (id, entry) in map {
309 if !id_ok(&id) {
310 warnings.push(format!("ignored profile {id:?}: ids are lowercase letters, digits, '-', '_' and '.'"));
311 continue;
312 }
313 match serde_json::from_value::<Profile>(entry) {
314 Ok(mut p) if out.len() < MAX_PROFILES => {
315 p.id.clone_from(&id);
316 out.insert(id, p);
317 }
318 Ok(_) => warnings.push(format!("ignored profile {id:?}: at most {MAX_PROFILES} profiles")),
319 Err(e) => warnings.push(format!("ignored profile {id:?}: {e}")),
320 }
321 }
322 out
323}
324
325pub fn find<'a>(profiles: &'a BTreeMap<String, Profile>, wanted: Option<&str>) -> Option<&'a Profile> {
327 wanted.and_then(|id| profiles.get(id)).filter(|p| p.usable())
328}
329
330pub fn apply<'a>(layer: &Layer, profiles: &'a BTreeMap<String, Profile>) -> (Layer, Result<Option<&'a Profile>, String>) {
334 let Some(id) = layer.profile.as_deref() else { return (layer.clone(), Ok(None)) };
335 match find(profiles, Some(id)) {
336 Some(p) => (Layer { base_url: Some(p.base_url.trim().to_owned()), model: Some(p.model.trim().to_owned()), ..layer.clone() }, Ok(Some(p))),
337 None => (Layer { profile: None, base_url: None, model: None, ..layer.clone() }, Err(id.to_owned())),
338 }
339}
340
341#[derive(Debug)]
343pub struct Resolved<'a> {
344 pub effective: Effective,
345 pub profile: Option<(Level, &'a Profile)>,
347 pub missing: Vec<String>,
349}
350
351pub fn resolve_with<'a>(
355 levels: Levels<'_>,
356 keys: Keys,
357 forced: Forced,
358 profiles: &'a BTreeMap<String, Profile>,
359 has_key: impl Fn(&str) -> bool,
360) -> Resolved<'a> {
361 let mut missing = Vec::new();
362 let mut picked: [(Option<Layer>, Option<&'a Profile>, bool); 3] = [(None, None, false), (None, None, false), (None, None, false)];
364 for (slot, layer) in picked.iter_mut().zip([levels.global, levels.workspace, levels.chat]) {
365 if let Some(l) = layer {
366 let (applied, p) = apply(l, profiles);
367 match p {
368 Ok(p) => slot.1 = p,
369 Err(id) => {
370 missing.push(id);
371 slot.2 = true;
372 }
373 }
374 slot.0 = Some(applied);
375 }
376 }
377 let [(g, gp, g_gone), (w, wp, w_gone), (c, cp, c_gone)] = &picked;
378 let applied = Levels { global: g.as_ref(), workspace: w.as_ref(), chat: c.as_ref() };
379 let own = |p: &Option<&Profile>, gone: bool, stored: bool| match p {
382 Some(p) => has_key(&p.id),
383 None => stored && !gone,
384 };
385 let keys = Keys {
386 global: own(gp, *g_gone, keys.global) || (gp.is_some() && keys.global),
387 workspace: own(wp, *w_gone, keys.workspace),
388 chat: own(cp, *c_gone, keys.chat),
389 };
390 let mut effective = resolve(applied, keys, forced);
391 effective.subagent_profile = None;
393 for (from, layer) in [(Level::Chat, levels.chat), (Level::Workspace, levels.workspace), (Level::Global, levels.global)] {
394 let Some(id) = layer.and_then(|l| l.subagent_profile.as_deref()) else { continue };
395 if find(profiles, Some(id)).is_some() {
396 effective.subagent_profile = Some(Sourced { value: id.to_owned(), from });
397 break;
398 }
399 missing.push(id.to_owned());
400 }
401 let from = effective.base_url.from;
402 let profile = match from {
403 Level::Global => *gp,
404 Level::Workspace => *wp,
405 Level::Chat => *cp,
406 Level::Default | Level::Flag => None,
407 }
408 .filter(|p| p.points_at(&effective.base_url.value, &effective.model.value))
409 .map(|p| (from, p));
410 if let Some((level, p)) = profile {
411 effective.key_from = (has_key(&p.id) || (level == Level::Global && keys.global)).then_some(level);
412 if let Some(m) = p.tool_mode
413 && effective.tool_mode.from != Level::Flag
414 {
415 effective.tool_mode = Sourced { value: m, from: level };
416 }
417 if let Some(pc) = p.compact_percent
420 && matches!(effective.compact_percent.from, Level::Default | Level::Global)
421 {
422 effective.compact_percent = Sourced { value: pc.clamp(10, 95), from: level };
423 }
424 }
425 Resolved { effective, profile, missing }
426}
427
428#[cfg(test)]
429mod tests {
430 use super::*;
431
432 fn profile(id: &str, url: &str, model: &str) -> Profile {
433 Profile { id: id.into(), name: id.into(), base_url: url.into(), model: model.into(), ..Profile::default() }
434 }
435
436 #[test]
437 fn a_levels_profile_beats_its_own_endpoint_and_the_most_specific_level_wins() {
438 let mut ps = BTreeMap::new();
439 ps.insert("big".to_owned(), Profile { tool_mode: Some(ToolMode::Prompt), ..profile("big", "http://big/v1", "large") });
440 ps.insert("small".to_owned(), profile("small", "http://small/v1", "tiny"));
441 let g = Layer { base_url: Some("http://g/v1".into()), model: Some("gm".into()), tool_mode: Some(ToolMode::Native), ..Layer::default() };
442 let w = Layer { profile: Some("big".into()), base_url: Some("http://stale/v1".into()), model: Some("stale".into()), ..Layer::default() };
444 let has = |id: &str| id == "big";
445 let r =
446 resolve_with(Levels { global: Some(&g), workspace: Some(&w), chat: None }, Keys { global: true, ..Keys::default() }, Forced::default(), &ps, has);
447 assert_eq!(r.effective.base_url, Sourced { value: "http://big/v1".into(), from: Level::Workspace });
448 assert_eq!(r.effective.model.value, "large");
449 assert_eq!(r.effective.key_from, Some(Level::Workspace));
450 assert_eq!(r.effective.tool_mode, Sourced { value: ToolMode::Prompt, from: Level::Workspace }, "the profile's tool mode beats the levels'");
451 assert_eq!(r.profile.map(|(l, p)| (l, p.id.as_str())), Some((Level::Workspace, "big")));
452 let c = Layer { profile: Some("small".into()), ..Layer::default() };
454 let r = resolve_with(
455 Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c) },
456 Keys { global: true, workspace: true, chat: true },
457 Forced::default(),
458 &ps,
459 has,
460 );
461 assert_eq!((r.effective.base_url.value.as_str(), r.effective.model.from), ("http://small/v1", Level::Chat));
462 assert_eq!(r.effective.key_from, None, "a profile without a key uses none, even if the level stored one");
463 assert_eq!(r.effective.tool_mode, Sourced { value: ToolMode::Native, from: Level::Global });
464 let forced = Forced { tool_mode: Some(ToolMode::Native), ..Forced::default() };
466 let r = resolve_with(Levels { global: Some(&g), workspace: Some(&w), chat: None }, Keys::default(), forced, &ps, has);
467 assert_eq!(r.effective.tool_mode.from, Level::Flag);
468 }
469
470 #[test]
473 fn a_models_compaction_threshold_overrides_the_default() {
474 let mut ps = BTreeMap::new();
475 ps.insert("big".to_owned(), Profile { compact_percent: Some(60), ..profile("big", "http://big/v1", "large") });
476 let has = |_: &str| false;
477 let at = |g: Layer, w: Layer| {
478 resolve_with(Levels { global: Some(&g), workspace: Some(&w), chat: None }, Keys::default(), Forced::default(), &ps, has).effective.compact_percent
479 };
480 let pick = Layer { profile: Some("big".into()), ..Layer::default() };
481 assert_eq!(at(Layer::default(), pick.clone()), Sourced { value: 60, from: Level::Workspace }, "over the default");
482 assert_eq!(at(Layer { compact_percent: Some(85), ..Layer::default() }, pick.clone()).value, 60, "over the global setting");
483 assert_eq!(at(Layer::default(), Layer { compact_percent: Some(40), ..pick }).value, 40, "the workspace's own wins");
484 assert_eq!(at(Layer::default(), Layer::default()).value, crate::config::DEFAULT_COMPACT_PERCENT);
486 assert!(Profile { compact_percent: Some(99), ..profile("x", "http://x/v1", "m") }.validated().is_err());
487 }
488
489 #[test]
490 fn a_deleted_profile_falls_back_to_inheriting() {
491 let ps = BTreeMap::new();
492 let g = Layer { base_url: Some("http://g/v1".into()), model: Some("gm".into()), ..Layer::default() };
493 let w = Layer { profile: Some("gone".into()), base_url: Some("http://copy/v1".into()), model: Some("copy".into()), ..Layer::default() };
494 let r = resolve_with(
495 Levels { global: Some(&g), workspace: Some(&w), chat: None },
496 Keys { global: true, workspace: true, chat: false },
497 Forced::default(),
498 &ps,
499 |_| true,
500 );
501 assert_eq!(r.effective.base_url, Sourced { value: "http://g/v1".into(), from: Level::Global });
502 assert_eq!(r.effective.key_from, Some(Level::Global));
503 assert_eq!(r.missing, ["gone"]);
504 assert!(r.profile.is_none());
505 let ps = [("x".to_owned(), profile("x", "", "m"))].into();
507 let c = Layer { profile: Some("x".into()), ..Layer::default() };
508 let r = resolve_with(Levels { global: Some(&g), workspace: None, chat: Some(&c) }, Keys::default(), Forced::default(), &ps, |_| false);
509 assert_eq!((r.effective.base_url.from, r.missing.len()), (Level::Global, 1));
510 }
511
512 #[test]
513 fn profiles_round_trip_and_keep_unknown_fields() {
514 let json = serde_json::json!({
515 "id": "qwen",
516 "name": "Qwen",
517 "base_url": "http://h/v1",
518 "model": "qwen3",
519 "description": "fast, good at code",
520 "tool_mode": "native",
521 "subagents": true,
522 "max_parallel": 2,
523 "context": 32768,
524 "params": {"temperature": 0.7, "top_p": 0.9, "max_tokens": 4096, "effort": "xhigh", "extra": {"chat_template_kwargs": {"enable_thinking": false}}, "min_p": 0.05},
525 "api": "anthropic",
526 "effort_hint": "low",
527 });
528 let p: Profile = serde_json::from_value(json.clone()).unwrap();
529 assert_eq!(p.tool_mode, Some(ToolMode::Native));
530 assert_eq!((p.subagents, p.max_parallel, p.context), (true, Some(2), Some(32768)));
531 assert_eq!(p.params.temperature, Some(0.7));
532 assert_eq!(p.params.rest.get("min_p"), Some(&serde_json::json!(0.05)));
533 assert_eq!(p.api, Some(ApiKind::Anthropic));
534 assert_eq!(p.extra.get("effort_hint"), Some(&serde_json::json!("low")));
535 assert_eq!(serde_json::to_value(&p).unwrap(), json);
536 let c = p.config(None);
538 assert_eq!((c.params.effort, c.params.max_tokens, c.context), (Some(Effort::Xhigh), Some(4096), Some(32768)));
539 assert!(c.params.rest.is_empty() && c.params.extra.contains_key("chat_template_kwargs"));
540 let odd: Params = serde_json::from_value(serde_json::json!({"effort": "ludicrous", "top_p": 0.5})).unwrap();
542 assert_eq!((odd.effort, odd.top_p), (None, Some(0.5)));
543 let small = Profile { id: "a".into(), name: "A".into(), base_url: "http://h/v1".into(), model: "m".into(), ..Profile::default() };
545 assert_eq!(serde_json::to_string(&small).unwrap(), r#"{"id":"a","name":"A","base_url":"http://h/v1","model":"m"}"#);
546 }
547
548 #[test]
549 fn bad_values_fall_back_one_by_one() {
550 let mut warnings = Vec::new();
551 let v = serde_json::json!({
552 "ok": {"base_url": "http://h/v1", "model": "m", "tool_mode": "sometimes", "max_parallel": -3, "params": "hot"},
553 "Bad Id": {"base_url": "http://h/v1", "model": "m"},
554 "worse": 5,
555 });
556 let ps = profiles_from(v, &mut warnings);
557 assert_eq!(ps.len(), 1, "{warnings:?}");
558 let p = &ps["ok"];
559 assert_eq!((p.id.as_str(), p.tool_mode, p.max_parallel, p.params.is_empty()), ("ok", None, None, true));
560 assert_eq!(warnings.len(), 2);
561 assert!(profiles_from(Value::Null, &mut warnings).is_empty());
562 }
563
564 #[test]
565 fn untrusted_profiles_are_checked() {
566 let p = Profile { name: " ".into(), base_url: " http://h/v1 ".into(), model: " m ".into(), ..Profile::default() };
567 let ok = p.clone().validated().unwrap();
568 assert_eq!((ok.name.as_str(), ok.base_url.as_str(), ok.model.as_str()), ("m", "http://h/v1", "m"));
569 assert!(Profile { base_url: "file:///etc".into(), ..p.clone() }.validated().is_err());
570 assert!(Profile { model: String::new(), ..p.clone() }.validated().is_err());
571 let hot = Profile { params: Params { temperature: Some(f64::NAN), ..Params::default() }, ..p.clone() };
572 assert!(hot.validated().is_err());
573 let mut big = p;
574 big.params.extra.insert("x".into(), Value::String("y".repeat(MAX_EXTRA_BYTES)));
575 assert!(big.validated().is_err());
576 let base = Profile { base_url: "http://h/v1".into(), model: "m".into(), ..Profile::default() };
578 for k in PROTECTED_FIELDS {
579 let mut p = base.clone();
580 p.params.extra.insert(k.into(), Value::Bool(true));
581 let err = p.validated().unwrap_err();
582 assert!(err.contains(k), "{err}");
583 }
584 let mut ok = base.clone();
585 ok.params.extra.insert("chat_template_kwargs".into(), serde_json::json!({"enable_thinking": false}));
586 assert!(ok.validated().is_ok());
587 assert!(Profile { params: Params { max_tokens: Some(0), ..Params::default() }, ..base }.validated().is_err());
588 }
589
590 #[test]
591 fn ids_are_slugs_and_unique() {
592 assert_eq!(new_id("Qwen 3 (fast)", |_| false), "qwen-3-fast");
593 assert_eq!(new_id("gpt-4.1", |_| false), "gpt-4.1");
594 assert_eq!(new_id(" ", |_| false), "model");
595 assert_eq!(new_id("x", |id| id == "x" || id == "x-2"), "x-3");
596 assert!(id_ok("qwen-3_b.1") && !id_ok("Qwen") && !id_ok("-a") && !id_ok(""));
597 assert!(same_url("HTTP://h:1/v1/", "http://h:1/v1"));
598 }
599
600 #[test]
601 fn the_subagent_model_is_the_most_specific_levels_that_exists() {
602 let ps: BTreeMap<String, Profile> =
603 [("role".to_owned(), profile("role", "http://r/v1", "r")), ("ws".to_owned(), profile("ws", "http://w/v1", "w"))].into();
604 let g = Layer { subagent_profile: Some("role".into()), ..Layer::default() };
605 let w = Layer { subagent_profile: Some("ws".into()), ..Layer::default() };
606 let c = Layer { subagent_profile: Some("gone".into()), ..Layer::default() };
607 let at = |levels: Levels<'_>| {
608 let r = resolve_with(levels, Keys::default(), Forced::default(), &ps, |_| false);
609 (r.effective.subagent_profile.map(|s| (s.value, s.from)), r.missing)
610 };
611 let some = |id: &str, l: Level| Some((id.to_owned(), l));
612 assert_eq!(at(Levels { global: Some(&g), workspace: None, chat: None }), (some("role", Level::Global), vec![]));
613 assert_eq!(at(Levels { global: Some(&g), workspace: Some(&w), chat: None }), (some("ws", Level::Workspace), vec![]));
614 assert_eq!(at(Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c) }), (some("ws", Level::Workspace), vec!["gone".to_owned()]));
616 assert_eq!(at(Levels { global: None, workspace: None, chat: Some(&c) }), (None, vec!["gone".to_owned()]));
617 assert_eq!(at(Levels::default()), (None, vec![]));
618 assert!(Layer { subagent_profile: Some("Not An Id".into()), ..Layer::default() }.validated(Level::Chat).is_err());
620 assert_eq!(Layer { subagent_profile: Some(" ".into()), ..Layer::default() }.validated(Level::Chat).unwrap().subagent_profile, None);
621 }
622}