use std::collections::HashMap;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use crate::ai::{Api, CompleteOptions, Model, Reasoning, Tool};
use crate::types::{ExitCode, Param, Type};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EntityKind {
Provider,
Model,
Tool,
Specialist,
}
impl std::fmt::Display for EntityKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
EntityKind::Provider => "provider",
EntityKind::Model => "model",
EntityKind::Tool => "tool",
EntityKind::Specialist => "specialist",
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MissingRef {
pub kind: EntityKind,
pub name: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Referrer {
pub kind: EntityKind,
pub name: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProviderDef {
pub name: String,
pub api: Api,
pub base_url: String,
#[serde(default)]
pub api_key_env: Option<String>,
#[serde(default)]
pub constrained_decoding: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModelDef {
pub id: String,
pub name: String,
pub provider: String,
pub max_tokens: u32,
pub context_window: u32,
}
impl ModelDef {
pub fn resolve(&self, provider: &ProviderDef) -> Model {
Model {
id: self.id.clone(),
name: self.name.clone(),
api: provider.api,
provider: provider.name.clone(),
base_url: provider.base_url.clone(),
max_tokens: self.max_tokens,
context_window: self.context_window,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Specialist {
pub name: String,
pub provider: String,
pub model: String,
pub system_prompt: String,
#[serde(default)]
pub tools: Vec<String>,
#[serde(default)]
pub constraint: Option<String>,
#[serde(default)]
pub reasoning: Reasoning,
#[serde(default)]
pub stream: bool,
}
impl Specialist {
pub fn complete_options(&self) -> CompleteOptions {
CompleteOptions {
reasoning: self.reasoning,
tool_choice: self.constraint.clone(),
..Default::default()
}
}
pub fn validate(&self) -> Result<(), String> {
if self.constraint.is_some() && !self.tools.is_empty() {
return Err(format!(
"specialist '{}' sets both tools and a constraint; use one or the other",
self.name
));
}
if self.constraint.is_some() && self.reasoning != Reasoning::Off {
return Err(format!(
"specialist '{}' forces a tool call with reasoning enabled; a forced tool call is incompatible with reasoning, so set --reasoning off",
self.name
));
}
Ok(())
}
pub fn tool_names(&self) -> &[String] {
match &self.constraint {
Some(constraint) => std::slice::from_ref(constraint),
None => &self.tools,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ToolDef {
pub name: String,
pub script: PathBuf,
pub description: String,
pub params: Vec<Param>,
pub output: Option<Type>,
#[serde(default)]
pub exits: Vec<ExitCode>,
}
impl ToolDef {
pub fn to_tool(&self) -> Tool {
let properties: serde_json::Map<String, serde_json::Value> = self
.params
.iter()
.map(|p| (p.name.clone(), p.ty.to_schema()))
.collect();
let required: Vec<&String> = self.params.iter().map(|p| &p.name).collect();
Tool {
name: self.name.clone(),
description: self.describe_with_exits(),
parameters: serde_json::json!({
"type": "object",
"properties": properties,
"required": required,
}),
}
}
fn describe_with_exits(&self) -> String {
if self.exits.is_empty() {
return self.description.clone();
}
let mut out = self.description.clone();
if !out.is_empty() {
out.push_str("\n\n");
}
out.push_str("Exit codes:");
for exit in &self.exits {
match &exit.desc {
Some(desc) => out.push_str(&format!("\n- {} ({}): {desc}", exit.code, exit.name)),
None => out.push_str(&format!("\n- {} ({})", exit.code, exit.name)),
}
}
out
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Registry {
#[serde(default)]
pub providers: HashMap<String, ProviderDef>,
#[serde(default)]
pub models: HashMap<String, ModelDef>,
#[serde(default)]
pub specialists: HashMap<String, Specialist>,
}
impl Registry {
pub fn resolve_model(&self, specialist: &Specialist) -> Result<Model, String> {
let provider = self
.providers
.get(&specialist.provider)
.ok_or_else(|| format!("unknown provider: {}", specialist.provider))?;
let model = self
.models
.get(&specialist.model)
.ok_or_else(|| format!("unknown model: {}", specialist.model))?;
Ok(model.resolve(provider))
}
pub fn missing_model_ref(&self, model: &ModelDef) -> Option<MissingRef> {
if !self.providers.contains_key(&model.provider) {
return Some(MissingRef {
kind: EntityKind::Provider,
name: model.provider.clone(),
});
}
None
}
pub fn missing_specialist_ref(
&self,
specialist: &Specialist,
tool_exists: impl Fn(&str) -> bool,
) -> Option<MissingRef> {
if !self.providers.contains_key(&specialist.provider) {
return Some(MissingRef {
kind: EntityKind::Provider,
name: specialist.provider.clone(),
});
}
if !self.models.contains_key(&specialist.model) {
return Some(MissingRef {
kind: EntityKind::Model,
name: specialist.model.clone(),
});
}
for tool in specialist.tool_names() {
if !tool_exists(tool) {
return Some(MissingRef {
kind: EntityKind::Tool,
name: tool.clone(),
});
}
}
None
}
pub fn referrers(&self, target: EntityKind, name: &str) -> Vec<Referrer> {
match target {
EntityKind::Provider => {
let mut refs = self.referrer_specialists(|s| s.provider == name);
let mut models: Vec<Referrer> = self
.models
.values()
.filter(|m| m.provider == name)
.map(|m| Referrer {
kind: EntityKind::Model,
name: m.id.clone(),
})
.collect();
models.sort_by(|a, b| a.name.cmp(&b.name));
refs.extend(models);
refs
}
EntityKind::Model => self.referrer_specialists(|s| s.model == name),
EntityKind::Tool => {
self.referrer_specialists(|s| s.tool_names().iter().any(|t| t == name))
}
EntityKind::Specialist => Vec::new(),
}
}
fn referrer_specialists(&self, pred: impl Fn(&Specialist) -> bool) -> Vec<Referrer> {
let mut refs: Vec<Referrer> = self
.specialists
.values()
.filter(|s| pred(s))
.map(|s| Referrer {
kind: EntityKind::Specialist,
name: s.name.clone(),
})
.collect();
refs.sort_by(|a, b| a.name.cmp(&b.name));
refs
}
}
#[cfg(test)]
#[path = "domain_tests.rs"]
mod tests;