use alloc::{
collections::BTreeMap,
format,
string::{
String,
ToString,
},
vec::Vec,
};
use crate::{
data::{
catalog::{
BunsenCatalog,
BunsenCatalogStack,
CatalogName,
ResolvedBuild,
document::{
CatalogEntry,
EntryKind,
ResourceEntry,
},
error::{
CatalogErrorExt,
CatalogRule,
catalog_error,
},
lookup::LeafMatch,
presets::ResolvedPresetSet,
},
resources::ResourceSet,
},
errors::BunsenResult,
};
fn compiled(feature: &str) -> BunsenResult<bool> {
match feature {
"kits" => Ok(cfg!(feature = "kits")),
"speech" => Ok(cfg!(feature = "speech")),
other => Err(catalog_error(
CatalogRule::Parse,
format!("the built-in catalog names the feature `{other}`, which bunsen doesn't have"),
)),
}
}
pub fn builtin_layers() -> BunsenResult<Vec<(bunsen_catalog::CatalogFile, bool)>> {
bunsen_catalog::files()
.into_iter()
.map(|file| {
let imported = match file.feature {
None => true,
Some(feature) => compiled(feature).map_err(|e| e.in_layer(file.label()))?,
};
Ok((file, imported))
})
.collect()
}
pub fn builtin_stack() -> BunsenResult<BunsenCatalogStack> {
let mut stack = BunsenCatalogStack::new();
for (file, imported) in builtin_layers()? {
if !imported {
continue;
}
let label = file.label();
let document = if file.name.ends_with(".json") {
BunsenCatalog::from_json(file.text)
} else {
BunsenCatalog::from_yaml(file.text)
}
.map_err(|e| e.in_layer(label))?;
stack.push(label, None, document)?;
}
Ok(stack)
}
#[derive(Debug)]
pub struct BuiltinCatalog {
builds: Vec<ResolvedBuild>,
hub_origins: Vec<String>,
names: Vec<(CatalogName, usize)>,
classes: BTreeMap<CatalogName, ResolvedPresetSet>,
contracts: BTreeMap<CatalogName, String>,
resources: BTreeMap<CatalogName, ResourceEntry>,
}
impl BuiltinCatalog {
pub fn get() -> BunsenResult<&'static BuiltinCatalog> {
static BUILTIN: std::sync::OnceLock<Result<BuiltinCatalog, String>> =
std::sync::OnceLock::new();
BUILTIN
.get_or_init(|| {
builtin_stack()
.and_then(|stack| Self::resolve(&stack))
.map_err(|e| e.to_string())
})
.as_ref()
.map_err(|e| catalog_error(CatalogRule::Parse, format!("the built-in catalog: {e}")))
}
fn resolve(stack: &BunsenCatalogStack) -> BunsenResult<Self> {
let mut builds = Vec::new();
let mut names = Vec::new();
for build in stack.of_kind(EntryKind::Build) {
let build = stack.resolve_build(build.name())?;
names.push((build.name.clone(), builds.len()));
names.extend(build.aliases.iter().map(|a| (a.clone(), builds.len())));
builds.push(build);
}
let mut classes = BTreeMap::new();
for class in stack.of_kind(EntryKind::TemplateClass) {
let name = class.name().clone();
classes.insert(name.clone(), stack.resolve_template_class(&name)?.presets);
}
let mut resources = BTreeMap::new();
for resource in stack.of_kind(EntryKind::Resource) {
if let CatalogEntry::Resource(r) = resource.body() {
resources.insert(resource.name().clone(), r.clone());
}
}
let mut contracts = BTreeMap::new();
for contract in stack.of_kind(EntryKind::Contract) {
if let CatalogEntry::Contract(c) = contract.body() {
contracts.insert(contract.name().clone(), c.description.clone());
}
}
Ok(Self {
builds,
hub_origins: stack.hub_origins(),
names,
classes,
contracts,
resources,
})
}
pub fn stack(&self) -> BunsenResult<BunsenCatalogStack> {
builtin_stack()
}
pub fn builds(&self) -> &[ResolvedBuild] {
&self.builds
}
pub fn build(
&self,
name: &str,
) -> BunsenResult<&ResolvedBuild> {
let found = find_spelling(&self.names, name, |i| self.builds[i].name.to_string())?;
found.map(|i| &self.builds[i]).ok_or_else(|| {
catalog_error(
CatalogRule::Lookup,
format!("the built-in catalog has no build `{name}`"),
)
})
}
pub fn resource(
&self,
name: &str,
slot: &str,
) -> BunsenResult<ResourceSet> {
let full = CatalogName::parse(name)?;
let entry = self.resources.get(&full).ok_or_else(|| {
catalog_error(
CatalogRule::Lookup,
format!("the built-in catalog has no resource `{name}`"),
)
})?;
Ok(entry.to_slot_set(&full.to_string(), slot, &self.hub_origins))
}
pub fn template_presets(
&self,
class: &str,
) -> BunsenResult<ResolvedPresetSet> {
let name = CatalogName::parse(class)?;
self.classes.get(&name).cloned().ok_or_else(|| {
catalog_error(
CatalogRule::Lookup,
format!("the built-in catalog has no template class `{class}`"),
)
})
}
pub fn hub_origins(&self) -> &[String] {
&self.hub_origins
}
pub fn contract_description(
&self,
name: &CatalogName,
) -> Option<&str> {
self.contracts.get(name).map(String::as_str)
}
}
pub(crate) fn find_spelling(
names: &[(CatalogName, usize)],
spelling: &str,
label: impl Fn(usize) -> String,
) -> BunsenResult<Option<usize>> {
if let Some((_, i)) = names
.iter()
.find(|(n, _)| n.to_string().eq_ignore_ascii_case(spelling))
{
return Ok(Some(*i));
}
let mut found: Vec<usize> = Vec::new();
for (n, i) in names {
if n.matches_query(spelling, LeafMatch::Exact) && !found.contains(i) {
found.push(*i);
}
}
match found.as_slice() {
[] => Ok(None),
[one] => Ok(Some(*one)),
many => Err(catalog_error(
CatalogRule::Lookup,
format!(
"`{spelling}` is ambiguous: {}",
many.iter()
.map(|&i| label(i))
.collect::<Vec<_>>()
.join(", ")
),
)),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_the_builtin_stack_imports() {
let stack = builtin_stack().unwrap();
let layers = builtin_layers().unwrap();
assert_eq!(
stack.layers().len(),
layers.iter().filter(|(_, imported)| *imported).count()
);
assert_eq!(stack.layers()[0].label(), "prelude");
}
#[cfg(all(feature = "kits", feature = "store"))]
#[test]
fn test_the_builtin_contracts_are_the_kits() {
use crate::{
data::catalog::document::OrderedNode,
kits::support::catalog_contracts::{
contracts_section,
kit_catalog_contracts,
},
};
let stack = builtin_stack().unwrap();
let built = stack.layers()[0].document().contracts.clone().unwrap();
let fragments = BunsenCatalog::from_node(OrderedNode::Map(vec![(
"$contracts".to_string(),
contracts_section(&kit_catalog_contracts()).unwrap(),
)]))
.unwrap()
.contracts
.unwrap();
#[cfg(feature = "speech")]
assert_eq!(built, fragments);
#[cfg(not(feature = "speech"))]
for contract in &fragments {
assert!(built.contains(contract), "{}", contract.name());
}
}
#[cfg(feature = "speech")]
#[test]
fn test_builtin_builds_resolve() {
let stack = builtin_stack().unwrap();
for (name, contract) in [
("qwen3-0.6b", "qwen3-lm"),
("qwen3.5-0.8b", "qwen3.5-lm"),
("gemma-3-1b-it", "gemma-lm"),
("rl-d20", "nanochat-lm"),
("laya", "laya-decision"),
("torchvision/resnet50", "resnet-classifier"),
("large", "whisper-asr"),
("phonon-2", "parakeet-asr"),
("phonon-1", "qwen3-asr/stated"),
("voxtral-mini-4b-realtime", "voxtral-asr/stated"),
("sortformer-v2", "sortformer-diarizer"),
("vad-16k", "silero-vad"),
] {
let found = stack.find_build(name).unwrap();
let build = stack.resolve_build(&found).unwrap();
assert_eq!(
build.tag("contract"),
Some(&serde_json::json!(contract)),
"{name}"
);
}
}
}