Add Playerbot Characters model setup

This commit is contained in:
Nightwalker743 committed 2026-11-20 16:14:27 -06:00
1 parent 10cfdcf5a2
commit 206d4844c9
16 files changed
+564 -4

No files matched your search

+16 -1
View File
@@ -154,6 +154,14 @@ pub fn safe_join(root: &Path, rel: &str) -> Result<PathBuf> {
/// Write `bytes` to `path` so readers see either the old or the new content, never a partial file.
pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
atomic_write_inner(path, bytes, false)
}
pub(crate) fn atomic_write_private(path: &Path, bytes: &[u8]) -> Result<()> {
atomic_write_inner(path, bytes, true)
}
fn atomic_write_inner(path: &Path, bytes: &[u8], _private: bool) -> Result<()> {
let parent = path
.parent()
.ok_or_else(|| Error::PathRejected("no parent directory".into()))?;
@@ -166,7 +174,14 @@ pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
uuid::Uuid::new_v4().simple()
));
let write = || -> std::io::Result<()> {
let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?;
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
if _private {
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut f = options.open(&tmp)?;
f.write_all(bytes)?;
f.sync_all()?;
Ok(())
+33
View File
@@ -12,6 +12,8 @@ use crate::config::parser::ConfFile;
use crate::error::{Error, Result};
use crate::fsx;
pub mod pbc;
static CATALOG: &str = include_str!("../../../modules/catalog.json");
#[derive(Debug, Clone, Deserialize)]
@@ -703,6 +705,37 @@ fn save_settings_in(
mod tests {
use super::*;
#[test]
fn playerbot_characters_uses_the_packaged_default_and_keeps_host_settings() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("server");
let meta = temp.path().join("metadata");
let cat = catalog();
let id = "mod-pbc";
let card = || list_in(&cat, &root).into_iter().find(|m| m.id == id).unwrap();
fs::create_dir_all(dir(&root)).unwrap();
fs::create_dir_all(&meta).unwrap();
assert!(!card().installed);
let dist = dir(&root).join("playerbots_characters.conf.dist");
let defaults = "[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = ../Extras/PlayerbotCharacters/my-connection.jsonc\n";
fs::write(&dist, defaults).unwrap();
let installed = card();
assert!(installed.installed && installed.switchable && installed.has_settings);
assert!(!installed.enabled);
let key = "PBC.DefaultConnection";
let path = "C:/Test Server/Model Config/custom.jsonc";
save_settings_in(&cat, &root, &meta, id, &BTreeMap::from([(key.into(), path.into())])).unwrap();
set_enabled_in(&cat, &root, &meta, id, true).unwrap();
assert!(card().enabled);
set_enabled_in(&cat, &root, &meta, id, false).unwrap();
assert!(!card().enabled);
let active = read(&dir(&root).join("playerbots_characters.conf")).unwrap();
assert_eq!(active.get(key), Some(path));
assert_eq!(fs::read_to_string(dist).unwrap(), defaults);
}
#[test]
fn time_is_time_card_settings_and_backups_match_the_module() {
let temp = tempfile::tempdir().unwrap();
+195
View File
@@ -0,0 +1,195 @@
//! Owns the connection file created by the Manager. Handwritten connection files stay with their owners.
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use crate::{Error, Result, fsx};
const MODULE: &str = "mod-pbc";
const PATH_SETTING: &str = "PBC.DefaultConnection";
const CONNECTION_FILE: &str = "Extras/PlayerbotCharacters/manager-connection.jsonc";
const CONNECTION_SETTING: &str = "../Extras/PlayerbotCharacters/manager-connection.jsonc";
#[derive(Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ApiType {
Openai,
Ollama,
Anthropic,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConnectionUpdate {
pub api_type: ApiType,
pub base_url: String,
pub model: String,
pub api_key: Option<String>,
pub remove_key: bool,
}
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct Connection {
api_type: ApiType,
base_url: String,
model: String,
api_key: String,
request_timeout_sec: u32,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConnectionView {
pub api_type: ApiType,
pub base_url: String,
pub model: String,
pub has_key: bool,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Setup {
pub active: bool,
pub connection: Option<ConnectionView>,
}
fn connection_path(root: &Path) -> Result<PathBuf> {
fsx::ensure_within(root, &root.join(CONNECTION_FILE))
}
fn read_connection(path: &Path) -> Result<Option<Vec<u8>>> {
match fs::read(path) {
Ok(bytes) => Ok(Some(bytes)),
Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
Err(error) => Err(error.into()),
}
}
fn parse(bytes: &[u8]) -> Result<Connection> {
serde_json::from_slice(bytes).map_err(|_| Error::Invalid("The Manager model connection file is invalid.".into()))
}
fn view(connection: Connection) -> ConnectionView {
ConnectionView {
api_type: connection.api_type,
base_url: connection.base_url,
model: connection.model,
has_key: !connection.api_key.is_empty(),
}
}
fn module_setting(root: &Path) -> Result<String> {
super::settings(root, MODULE)?
.into_iter()
.find(|setting| setting.key == PATH_SETTING)
.map(|setting| setting.value)
.ok_or_else(|| Error::Invalid("This server package does not provide a model connection setting.".into()))
}
pub fn load(root: &Path) -> Result<Setup> {
let active = module_setting(root)?.trim_matches('"') == CONNECTION_SETTING;
let connection = read_connection(&connection_path(root)?)?
.as_deref()
.map(parse)
.transpose()?
.map(view);
Ok(Setup { active, connection })
}
pub fn save(root: &Path, meta: &Path, update: ConnectionUpdate) -> Result<Setup> {
let active = module_setting(root)?.trim_matches('"') == CONNECTION_SETTING;
let base_url = update.base_url.trim().trim_end_matches('/');
let url = reqwest::Url::parse(base_url).map_err(|_| Error::Invalid("Enter a valid model API base URL.".into()))?;
if !matches!(url.scheme(), "http" | "https") || url.host().is_none()
|| !url.username().is_empty() || url.password().is_some() || url.query().is_some() || url.fragment().is_some()
{
return Err(Error::Invalid("Use an HTTP or HTTPS base URL without credentials, a query, or a fragment.".into()));
}
let base_url = url.as_str().trim_end_matches('/');
let model = update.model.trim();
if model.is_empty() || model.chars().any(char::is_control) {
return Err(Error::Invalid("Enter a model name on a single line.".into()));
}
let submitted_key = update.api_key.as_deref().map(str::trim).filter(|value| !value.is_empty());
if submitted_key.is_some_and(|value| value.chars().any(char::is_control)) {
return Err(Error::Invalid("Enter the API key on a single line.".into()));
}
let path = connection_path(root)?;
let previous = read_connection(&path)?;
let previous_connection = previous.as_deref().map(parse).transpose()?;
let key = if update.remove_key {
String::new()
} else if let Some(key) = submitted_key {
key.to_owned()
} else {
previous_connection
.filter(|old| old.api_type == update.api_type && old.base_url == base_url)
.map(|old| old.api_key)
.unwrap_or_default()
};
let connection = Connection {
api_type: update.api_type,
base_url: base_url.into(),
model: model.into(),
api_key: key,
request_timeout_sec: if matches!(update.api_type, ApiType::Ollama) { 60 } else { 30 },
};
fsx::atomic_write_private(&path, &serde_json::to_vec_pretty(&connection)?)?;
if !active {
let changes = BTreeMap::from([(PATH_SETTING.into(), CONNECTION_SETTING.into())]);
if let Err(error) = super::save_settings(root, meta, MODULE, &changes) {
if let Some(bytes) = previous {
fsx::atomic_write_private(&path, &bytes)?;
} else {
fs::remove_file(&path)?;
}
return Err(error);
}
}
Ok(Setup { active: true, connection: Some(view(connection)) })
}
#[cfg(test)]
mod tests {
use super::*;
fn update(api_type: ApiType, base_url: &str, api_key: Option<&str>) -> ConnectionUpdate {
ConnectionUpdate { api_type, base_url: base_url.into(), model: "example-model".into(),
api_key: api_key.map(str::to_owned), remove_key: false }
}
#[test]
fn model_setup_preserves_manual_files_and_only_reuses_keys_for_the_same_endpoint() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
let meta = root.join("metadata");
let configs = root.join("Core/configs/modules");
fs::create_dir_all(&meta).unwrap();
fs::create_dir_all(&configs).unwrap();
fs::write(configs.join("playerbots_characters.conf.dist"),
"[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = ../my-custom.jsonc\n").unwrap();
fs::write(root.join("my-custom.jsonc"), b"// manual connection").unwrap();
assert!(!load(root).unwrap().active);
let base_url = "https://api.example.com/v1";
let saved = save(root, &meta, update(ApiType::Openai, base_url, Some("fixture-key"))).unwrap();
assert!(saved.active && saved.connection.as_ref().unwrap().has_key);
assert!(!serde_json::to_string(&saved).unwrap().contains("fixture-key"));
assert!(save(root, &meta, update(ApiType::Openai, base_url, None)).unwrap().connection.unwrap().has_key);
let mut clear = update(ApiType::Openai, base_url, None);
clear.remove_key = true;
assert!(!save(root, &meta, clear).unwrap().connection.unwrap().has_key);
save(root, &meta, update(ApiType::Openai, base_url, Some("replacement-key"))).unwrap();
let changed = save(root, &meta, update(ApiType::Ollama, "http://127.0.0.1:11434", None)).unwrap();
assert!(!changed.connection.unwrap().has_key);
assert!(save(root, &meta, update(ApiType::Openai, "https://user:secret@example.com", None)).is_err());
assert_eq!(fs::read(root.join("my-custom.jsonc")).unwrap(), b"// manual connection");
let config = fs::read_to_string(configs.join("playerbots_characters.conf")).unwrap();
assert!(config.contains("PBC.Enable = 0"));
assert!(!config.contains("replacement-key"));
}
}
+32
View File
@@ -2362,6 +2362,38 @@ mod tests {
w
}
#[test]
fn playerbot_characters_release_files_leave_host_connections_and_cards_in_place() {
const DIST: &str = "Core/configs/modules/playerbots_characters.conf.dist";
const CONFIG: &str = "Core/configs/modules/playerbots_characters.conf";
const CONNECTION: &str = "Extras/PlayerbotCharacters/manager-connection.jsonc";
const CARD: &str = "Extras/PlayerbotCharacters/cards/Companion.card.txt";
const PROMPT: &str = "Extras/PlayerbotCharacters/prompts/enUS/CharacterContext.custom.txt";
let defaults = b"[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = ../Extras/PlayerbotCharacters/my-connection.jsonc\n";
for configured in [false, true] {
let w = world(&[(DIST, defaults), ("Extras/PlayerbotCharacters/cards/README.txt", b"Cards")], false);
let host_config = b"[worldserver]\nPBC.Enable = 1\nPBC.DefaultConnection = ../Extras/PlayerbotCharacters/manager-connection.jsonc\n";
if configured {
write(&w.root, CONFIG, host_config);
write(&w.root, CONNECTION, b"{\"apiKey\":\"fixture-only\"}");
write(&w.root, CARD, b"My character card");
write(&w.root, PROMPT, b"My custom prompt");
}
assert_eq!(run(&w, &Fake::ok(), BTreeMap::new(), None).unwrap().txn.state, State::Committed);
assert_eq!(fs::read(w.root.join(DIST)).unwrap(), defaults);
let module = crate::modules::list(&w.root).into_iter().find(|m| m.id == "mod-pbc").unwrap();
assert!(module.installed && module.enabled == configured);
if configured {
assert_eq!(fs::read(w.root.join(CONFIG)).unwrap(), host_config);
assert_eq!(fs::read(w.root.join(CONNECTION)).unwrap(), b"{\"apiKey\":\"fixture-only\"}");
assert_eq!(fs::read(w.root.join(CARD)).unwrap(), b"My character card");
assert_eq!(fs::read(w.root.join(PROMPT)).unwrap(), b"My custom prompt");
} else {
assert!(!w.root.join(CONNECTION).exists());
}
}
}
#[test]
fn startup_waits_for_an_update_check_but_not_for_active_maintenance() {
let temp = tempfile::tempdir().unwrap();