From 166dde09346a3a9190285ab110532b82fcf8d91d Mon Sep 17 00:00:00 2001 From: fkDead Date: Wed, 11 Nov 2026 20:20:47 +0100 Subject: [PATCH] capri-core: add persona module --- crates/capri-core/src/persona.rs | 174 +++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 crates/capri-core/src/persona.rs diff --git a/crates/capri-core/src/persona.rs b/crates/capri-core/src/persona.rs new file mode 100644 index 0000000..6628ed7 --- /dev/null +++ b/crates/capri-core/src/persona.rs @@ -0,0 +1,174 @@ +//! Personality (PERSONALITY.md), communication style and conversation language. +use std::collections::BTreeMap; +use std::path::Path; +use std::sync::OnceLock; + +use anyhow::{bail, Result}; +use serde::Deserialize; + +use crate::settings::LanguageSettings; +use crate::{fsutil, utf16_len}; + +pub const DEFAULT_PERSONALITY: &str = include_str!("../../../assets/prompts/PERSONALITY.md"); +const MAX_PERSONALITY: usize = 24000; +const STYLES_JSON: &str = include_str!("../../../assets/prompts/communication-styles.json"); +const STYLE_SUFFIX: &str = include_str!("../../../assets/prompts/communication-suffix.txt"); +const LANGUAGES_JSON: &str = include_str!("../../../assets/i18n/languages.json"); + +fn validate_personality(text: &str) -> Result<&str> { + let text = text.strip_prefix('\u{feff}').unwrap_or(text).trim(); + if text.contains('\0') || utf16_len(text) > MAX_PERSONALITY { + bail!("Personality must be at most {MAX_PERSONALITY} characters without NUL."); + } + Ok(text) +} + +/// Current personality: `/PERSONALITY.md`, or the factory text when missing or empty. +pub fn read_personality(workspace: &Path) -> Result { + let bytes = fsutil::read_regular(&workspace.join("PERSONALITY.md"), (MAX_PERSONALITY * 4 + 3) as u64)?; + let text = match bytes { + Some(bytes) => String::from_utf8(bytes)?, + None => String::new(), + }; + let text = validate_personality(&text)?; + Ok(if text.is_empty() { validate_personality(DEFAULT_PERSONALITY)?.to_string() } else { text.to_string() }) +} + +/// Saves the personality; an empty text restores the factory text. +pub fn save_personality(workspace: &Path, text: &str) -> Result<()> { + let text = validate_personality(text)?; + let text = if text.is_empty() { DEFAULT_PERSONALITY.trim() } else { text }; + fsutil::write_atomic(&workspace.join("PERSONALITY.md"), text.as_bytes()) +} + +fn styles() -> &'static BTreeMap { + static STYLES: OnceLock> = OnceLock::new(); + STYLES.get_or_init(|| serde_json::from_str(STYLES_JSON).expect("bundled communication styles")) +} + +pub fn communication_styles() -> impl Iterator { + styles().keys().map(String::as_str) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct StyleFile { + schema_version: u32, + style: String, +} + +fn style_file(workspace: &Path) -> Result { + let folder = workspace.join(".capri"); + if let Ok(meta) = std::fs::symlink_metadata(&folder) + && !meta.is_dir() { + bail!("Communication settings folder must not be linked."); + } + Ok(folder.join("communication.json")) +} + +/// Selected style; any problem with the file means `neutral`. +pub fn read_style(workspace: &Path) -> String { + let read = || -> Result { + let bytes = fsutil::read_regular(&style_file(workspace)?, 4096)?.unwrap_or_default(); + let file: StyleFile = serde_json::from_slice(&bytes)?; + if file.schema_version != 1 || !styles().contains_key(&file.style) { + bail!("invalid"); + } + Ok(file.style) + }; + read().unwrap_or_else(|_| "neutral".into()) +} + +pub fn save_style(workspace: &Path, style: &str) -> Result<()> { + if !styles().contains_key(style) { + bail!("Unknown communication style."); + } + let file = style_file(workspace)?; + std::fs::create_dir_all(file.parent().unwrap())?; + fsutil::write_json_atomic(&file, &serde_json::json!({"schemaVersion": 1, "style": style})) +} + +pub fn communication_instruction(style: &str) -> String { + let style = if styles().contains_key(style) { style } else { "neutral" }; + format!("COMMUNICATION STYLE: {style}\n{}\n{STYLE_SUFFIX}", styles()[style]) +} + +#[derive(Deserialize, Clone, Debug)] +pub struct Language { + pub id: String, + pub name: String, + pub label: String, +} + +pub fn languages() -> &'static [Language] { + static LANGS: OnceLock> = OnceLock::new(); + LANGS.get_or_init(|| serde_json::from_str(LANGUAGES_JSON).expect("bundled languages")) +} + +fn delivery(code: &str) -> Option<&'static str> { + Some(match code { + "en" => "Reply only in English. Speech recognition language controls input transcription, not reply or voice language. Translate the meaning of non-English input into a natural English reply; never copy a whole foreign-language answer into the English voice.", + "ru" => "Отвечай только на русском языке.", + "ja" => "必ず日本語だけで答えてください。", + "zh" => "请只用中文回答。", + "de" => "Antworte ausschließlich auf Deutsch.", + "fr" => "Réponds uniquement en français.", + "es" => "Responde únicamente en español.", + "pt" => "Responda apenas em português.", + "it" => "Rispondi soltanto in italiano.", + "ko" => "반드시 한국어로만 대답하세요.", + "ar" => "أجب باللغة العربية فقط.", + "hi" => "केवल हिन्दी में उत्तर दें।", + "he" => "עני רק בעברית.", + _ => return None, + }) +} + +/// `CURRENT CONVERSATION LANGUAGE: ...` block (Capri `language-context.mjs`). +pub fn conversation_instruction(lang: &LanguageSettings) -> String { + let code = lang.conversation.as_str(); + let entry = languages().iter().find(|l| l.id == code); + let name = if code == "custom" { + lang.custom_conversation.clone() + } else { + entry.map(|l| l.name.clone()).unwrap_or_else(|| code.to_string()) + }; + let native = entry.map(|l| l.label.clone()).unwrap_or_else(|| name.clone()); + let delivery = delivery(code).map(str::to_string).unwrap_or_else(|| format!("Respond only in {name}.")); + format!( + "CURRENT CONVERSATION LANGUAGE: {} ({native}, {code}). Write your entire user-facing reply in this language, even if the user's message or older conversation uses another language. Keep Capri's personality, shared memories, warmth and wit; adapt slang naturally instead of forcing English catchphrases. Do not add an English translation unless requested. A tool's confirmation is factual data: translate it into this language in one short sentence without adding claims. Proper names, song titles, file paths and code may keep their original spelling. Use plain text and punctuation only, with no emoji, asterisks or Markdown. This language choice applies to this interface and overrides older delivery instructions. Final answer language: {name}. {delivery}", + serde_json::to_string(&name).unwrap() + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn personality_falls_back_to_default() { + let dir = tempfile::tempdir().unwrap(); + assert!(read_personality(dir.path()).unwrap().len() > 100); + save_personality(dir.path(), " Be kind. ").unwrap(); + assert_eq!(read_personality(dir.path()).unwrap(), "Be kind."); + assert!(save_personality(dir.path(), "a\0b").is_err()); + } + + #[test] + fn style_roundtrip_and_fallback() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(read_style(dir.path()), "neutral"); + save_style(dir.path(), "wild").unwrap(); + assert_eq!(read_style(dir.path()), "wild"); + assert!(save_style(dir.path(), "nope").is_err()); + assert!(communication_instruction("wild").starts_with("COMMUNICATION STYLE: wild\nWild:")); + } + + #[test] + fn language_instruction() { + let fr = LanguageSettings { conversation: "fr".into(), ..Default::default() }; + let text = conversation_instruction(&fr); + assert!(text.starts_with("CURRENT CONVERSATION LANGUAGE: \"French\" (Français, fr)."), "{text}"); + assert!(text.ends_with("Réponds uniquement en français.")); + } +}