#![warn(missing_docs)]
#![warn(clippy::all)]
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use infernum_core::Result;
use serde::{Deserialize, Serialize};
pub const GRIMOIRE_PATH_ENV: &str = "INFERNUM_GRIMOIRE_PATH";
#[must_use]
pub fn default_grimoire_path() -> PathBuf {
if let Ok(path) = std::env::var(GRIMOIRE_PATH_ENV) {
return PathBuf::from(path);
}
dirs::data_local_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("infernum")
.join("personas")
}
#[deprecated(since = "0.2.0", note = "Use default_grimoire_path() instead")]
pub const DEFAULT_GRIMOIRE_PATH: &str = "~/.local/share/infernum/personas/";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GrimoirePersona {
pub id: String,
pub name: String,
pub system_prompt: String,
pub variants: HashMap<String, String>,
pub metadata: HashMap<String, String>,
}
pub struct GrimoireLoader {
base_path: PathBuf,
cache: dashmap::DashMap<String, GrimoirePersona>,
}
impl GrimoireLoader {
#[must_use]
pub fn new() -> Self {
Self::with_path(default_grimoire_path())
}
#[must_use]
pub fn with_path(path: impl Into<PathBuf>) -> Self {
Self {
base_path: path.into(),
cache: dashmap::DashMap::new(),
}
}
pub async fn load(&self, persona_id: &str) -> Result<GrimoirePersona> {
if let Some(cached) = self.cache.get(persona_id) {
return Ok(cached.clone());
}
let path = self.base_path.join(persona_id);
let prompt_path = if path.is_dir() {
path.join("prompt.md")
} else {
path.with_extension("md")
};
let content = tokio::fs::read_to_string(&prompt_path)
.await
.map_err(|e| infernum_core::Error::Io(e))?;
let persona = self.parse_persona(persona_id, &content)?;
self.cache.insert(persona_id.to_string(), persona.clone());
Ok(persona)
}
fn parse_persona(&self, id: &str, content: &str) -> Result<GrimoirePersona> {
Ok(GrimoirePersona {
id: id.to_string(),
name: id.to_string(),
system_prompt: content.to_string(),
variants: HashMap::new(),
metadata: HashMap::new(),
})
}
pub async fn list(&self) -> Result<Vec<String>> {
let mut personas = Vec::new();
if !self.base_path.exists() {
return Ok(personas);
}
let mut entries = tokio::fs::read_dir(&self.base_path).await?;
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
if path.is_dir() || path.extension().map_or(false, |e| e == "md") {
if let Some(name) = path.file_stem().and_then(|s| s.to_str()) {
personas.push(name.to_string());
}
}
}
Ok(personas)
}
pub fn clear_cache(&self) {
self.cache.clear();
}
#[must_use]
pub fn base_path(&self) -> &Path {
&self.base_path
}
}
impl Default for GrimoireLoader {
fn default() -> Self {
Self::new()
}
}