use std::rc::Rc;
use bunsen::{
data::{
builds::BuildSummary,
catalog::{
BunsenCatalogStack,
CatalogErrorExt,
builtin_stack,
select::state::SelectRun,
},
},
errors::{
BunsenError,
BunsenResult,
},
};
use bunsen_app::catalog::{
SelectionFlags,
SelectionStageArgs,
};
use clap::ArgMatches;
use serde_json::{
Map,
Value,
};
pub fn builtin_catalog() -> BunsenResult<Rc<BunsenCatalogStack>> {
thread_local! {
static STACK: Result<Rc<BunsenCatalogStack>, String> =
builtin_stack().map(Rc::new).map_err(|e| e.problem_message());
}
STACK.with(|s| s.clone().map_err(BunsenError::policy))
}
pub fn log_choice(
chosen: &str,
run: &SelectRun,
) {
let why: Vec<String> = run
.trace
.stages
.iter()
.filter(|s| s.dropped > 0)
.map(|s| format!("`{}` ({}) dropped {}", s.op, s.origin, s.dropped))
.collect();
if why.is_empty() {
log::info!("chose {chosen}");
} else {
log::info!("chose {chosen}: {}", why.join("; "));
}
}
pub fn log_build(
intent: &str,
build: &BuildSummary,
) {
log::info!("model {intent}: {build}");
}
#[derive(clap::Args, Debug, Clone, Default)]
pub struct ChooseArgs {
#[arg(long = "model", value_name = "NAME")]
pub model: Vec<String>,
#[command(flatten)]
pub stages: SelectionStageArgs,
#[arg(long = "patch", value_name = "{..}")]
pub patch: Vec<String>,
}
impl ChooseArgs {
pub fn flags(
&self,
matches: &ArgMatches,
) -> BunsenResult<SelectionFlags> {
SelectionFlags::read(&*builtin_catalog()?, matches)
}
pub fn patch(&self) -> BunsenResult<Option<Value>> {
if self.patch.is_empty() {
return Ok(None);
}
let mut merged = Value::Object(Map::new());
for text in &self.patch {
let value: Value = serde_saphyr::from_str(text)
.map_err(|e| BunsenError::policy(format!("`--patch {text}` is not YAML: {e}")))?;
if !value.is_object() {
return Err(BunsenError::policy(format!(
"`--patch {text}` is not a mapping"
)));
}
bunsen::support::merge_patch::apply(&mut merged, &value);
}
Ok(Some(merged))
}
}
#[cfg(test)]
mod tests {
use clap::{
CommandFactory,
FromArgMatches,
};
use serde_json::json;
use super::*;
#[derive(clap::Parser, Debug)]
struct Args {
#[command(flatten)]
choose: ChooseArgs,
}
#[test]
fn test_flags() {
let matches = Args::command()
.try_get_matches_from([
"x",
"--model",
"qwen",
"--limit",
"2",
"--patch",
"{beam_size: 1, vad: {keep: true}}",
"--patch",
"{vad: {keep: null}}",
"--off",
"thinking",
])
.unwrap();
let args = Args::from_arg_matches(&matches).unwrap();
assert_eq!(args.choose.model, ["qwen"]);
assert_eq!(
args.choose.patch().unwrap(),
Some(json!({"beam_size": 1, "vad": {}}))
);
let flags = args.choose.flags(&matches).unwrap();
assert_eq!(flags.stages.len(), 1);
assert_eq!(flags.presets.presets, ["no-thinking"]);
assert_eq!(ChooseArgs::default().patch().unwrap(), None);
let bad = ChooseArgs {
patch: vec!["[1]".to_string()],
..ChooseArgs::default()
};
assert!(bad.patch().is_err());
}
}