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

@@ -0,0 +1,7 @@
---
area: modules
type: added
audience: admins
title: Configure Playerbot Characters from the Modules page
---
Set up an OpenAI, Ollama, Anthropic or OpenAI-compatible connection from Modules, including its API key. Playerbot Characters gives CoA Companions or SQUID Playerbots dialogue and memories.
+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. /// 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<()> { 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 let parent = path
.parent() .parent()
.ok_or_else(|| Error::PathRejected("no parent directory".into()))?; .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() uuid::Uuid::new_v4().simple()
)); ));
let write = || -> std::io::Result<()> { 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.write_all(bytes)?;
f.sync_all()?; f.sync_all()?;
Ok(()) Ok(())
+33
View File
@@ -12,6 +12,8 @@ use crate::config::parser::ConfFile;
use crate::error::{Error, Result}; use crate::error::{Error, Result};
use crate::fsx; use crate::fsx;
pub mod pbc;
static CATALOG: &str = include_str!("../../../modules/catalog.json"); static CATALOG: &str = include_str!("../../../modules/catalog.json");
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
@@ -703,6 +705,37 @@ fn save_settings_in(
mod tests { mod tests {
use super::*; 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] #[test]
fn time_is_time_card_settings_and_backups_match_the_module() { fn time_is_time_card_settings_and_backups_match_the_module() {
let temp = tempfile::tempdir().unwrap(); 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 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] #[test]
fn startup_waits_for_an_update_check_but_not_for_active_maintenance() { fn startup_waits_for_an_update_check_but_not_for_active_maintenance() {
let temp = tempfile::tempdir().unwrap(); let temp = tempfile::tempdir().unwrap();
+18
View File
@@ -1,6 +1,24 @@
{ {
"schema": 1, "schema": 1,
"modules": [ "modules": [
{
"id": "mod-pbc",
"name": "Playerbot Characters",
"description": {
"en": "Gives CoA Companions or SQUID Playerbots dialogue, personalities and memories. Requires a model connection you configure.",
"ru": "Добавляет диалоги, характеры и воспоминания ботам CoA Companions или SQUID Playerbots. Нужно настроить подключение к модели.",
"de": "Gibt CoA Companions oder SQUID Playerbots Dialoge, Persönlichkeiten und Erinnerungen. Die Verbindung zu einem KI-Modell muss eingerichtet werden.",
"fr": "Ajoute des dialogues, des personnalités et des souvenirs aux bots CoA Companions ou SQUID Playerbots. Une connexion à un modèle doit être configurée.",
"es": "Añade diálogos, personalidades y recuerdos a los bots de CoA Companions o SQUID Playerbots. Requiere configurar una conexión con un modelo.",
"zh": "为 CoA Companions 或 SQUID Playerbots 添加对话、个性和记忆。需要自行配置模型连接。"
},
"repo": "https://github.com/deseven/mod-pbc#model-connection-setup",
"conf": "playerbots_characters.conf",
"enable_key": "PBC.Enable",
"default_on": false,
"status": "early",
"icon": "bot"
},
{ {
"id": "dungeon-clear", "id": "dungeon-clear",
"name": "Dungeon Clear", "name": "Dungeon Clear",
+26
View File
@@ -1710,6 +1710,30 @@ async fn module_save_settings(
.await .await
} }
#[tauri::command]
async fn pbc_connection(
state: State<'_, AppState>,
id: String,
) -> std::result::Result<coa_core::modules::pbc::Setup, UiError> {
let root = path_of(&state, &id)?;
blocking(move || coa_core::modules::pbc::load(&root)).await
}
#[tauri::command]
async fn pbc_save_connection(
state: State<'_, AppState>,
id: String,
update: coa_core::modules::pbc::ConnectionUpdate,
) -> std::result::Result<coa_core::modules::pbc::Setup, UiError> {
let root = path_of(&state, &id)?;
let _guard = BusyGuard::acquire(&state, &id)?;
blocking(move || {
let (dir, _) = install_meta(&root)?;
coa_core::modules::pbc::save(&root, &dir, update)
})
.await
}
#[tauri::command] #[tauri::command]
async fn all_settings( async fn all_settings(
state: State<'_, AppState>, state: State<'_, AppState>,
@@ -3217,6 +3241,8 @@ pub fn run() {
repair_server, repair_server,
module_set_enabled, module_set_enabled,
module_settings, module_settings,
pbc_connection,
pbc_save_connection,
module_save_settings, module_save_settings,
all_settings, all_settings,
all_settings_save, all_settings_save,
+12
View File
@@ -845,6 +845,18 @@ const de: Partial<Record<keyof typeof en, string>> = {
"mod.switch": "{name} ein- oder ausschalten", "mod.switch": "{name} ein- oder ausschalten",
"mod.notHere": "Nicht Teil dieses Servers", "mod.notHere": "Nicht Teil dieses Servers",
"mod.github": "GitHub", "mod.github": "GitHub",
"mod.pbc.connection": "Modellverbindung",
"mod.pbc.provider": "Modellanbieter",
"mod.pbc.compatible": "OpenAI-kompatibler Endpunkt",
"mod.pbc.model": "Modellname",
"mod.pbc.endpoint": "API-Basis-URL",
"mod.pbc.key": "API-Schlüssel",
"mod.pbc.savedKey": "Schlüssel gespeichert",
"mod.pbc.removeKey": "Gespeicherten Schlüssel löschen",
"mod.pbc.keyHint": "Lass das Feld leer, um den Schlüssel für denselben Endpunkt zu behalten. Lokales Ollama braucht meist keinen Schlüssel.",
"mod.pbc.save": "Modellverbindung speichern",
"mod.pbc.saved": "Modellverbindung gespeichert.",
"mod.pbc.useConnection": "Beim Speichern wird diese Verbindung als Standard für mod-pbc auf dem Server festgelegt.",
"mod.settings": "Einstellungen", "mod.settings": "Einstellungen",
"mod.default": "Zurück zum Standard ({v})", "mod.default": "Zurück zum Standard ({v})",
"mod.saved": "Gespeichert ({n} geändert).", "mod.saved": "Gespeichert ({n} geändert).",
+12
View File
@@ -891,6 +891,18 @@ const en = {
"mod.switch": "Turn {name} on or off", "mod.switch": "Turn {name} on or off",
"mod.notHere": "Not part of this server", "mod.notHere": "Not part of this server",
"mod.github": "GitHub", "mod.github": "GitHub",
"mod.pbc.connection": "Model connection",
"mod.pbc.provider": "Model provider",
"mod.pbc.compatible": "OpenAI-compatible endpoint",
"mod.pbc.model": "Model name",
"mod.pbc.endpoint": "API base URL",
"mod.pbc.key": "API key",
"mod.pbc.savedKey": "Saved key",
"mod.pbc.removeKey": "Remove saved key",
"mod.pbc.keyHint": "Leave the key blank to keep it for the same endpoint. Local Ollama usually needs no key.",
"mod.pbc.save": "Save model connection",
"mod.pbc.saved": "Model connection saved.",
"mod.pbc.useConnection": "Saving makes this the server’s default mod-pbc connection.",
"mod.settings": "Settings", "mod.settings": "Settings",
"mod.default": "Back to the default ({v})", "mod.default": "Back to the default ({v})",
"mod.saved": "Saved ({n} changed).", "mod.saved": "Saved ({n} changed).",
+12
View File
@@ -845,6 +845,18 @@ const es: Partial<Record<keyof typeof en, string>> = {
"mod.switch": "Activar o desactivar {name}", "mod.switch": "Activar o desactivar {name}",
"mod.notHere": "No forma parte de este servidor", "mod.notHere": "No forma parte de este servidor",
"mod.github": "GitHub", "mod.github": "GitHub",
"mod.pbc.connection": "Conexión con el modelo",
"mod.pbc.provider": "Proveedor del modelo",
"mod.pbc.compatible": "Endpoint compatible con OpenAI",
"mod.pbc.model": "Nombre del modelo",
"mod.pbc.endpoint": "URL base de la API",
"mod.pbc.key": "Clave de API",
"mod.pbc.savedKey": "Clave guardada",
"mod.pbc.removeKey": "Eliminar la clave guardada",
"mod.pbc.keyHint": "Deja el campo vacío para conservar la clave del mismo endpoint. Ollama en local normalmente no necesita clave.",
"mod.pbc.save": "Guardar la conexión",
"mod.pbc.saved": "Conexión con el modelo guardada.",
"mod.pbc.useConnection": "Al guardar, esta será la conexión predeterminada de mod-pbc en el servidor.",
"mod.settings": "Ajustes", "mod.settings": "Ajustes",
"mod.default": "Volver al valor por defecto ({v})", "mod.default": "Volver al valor por defecto ({v})",
"mod.saved": "Guardado ({n} cambiado(s)).", "mod.saved": "Guardado ({n} cambiado(s)).",
+12
View File
@@ -845,6 +845,18 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"mod.switch": "Activer ou désactiver {name}", "mod.switch": "Activer ou désactiver {name}",
"mod.notHere": "Ne fait pas partie de ce serveur", "mod.notHere": "Ne fait pas partie de ce serveur",
"mod.github": "GitHub", "mod.github": "GitHub",
"mod.pbc.connection": "Connexion au modèle",
"mod.pbc.provider": "Fournisseur du modèle",
"mod.pbc.compatible": "Point d’accès compatible OpenAI",
"mod.pbc.model": "Nom du modèle",
"mod.pbc.endpoint": "URL de base de l’API",
"mod.pbc.key": "Clé API",
"mod.pbc.savedKey": "Clé enregistrée",
"mod.pbc.removeKey": "Supprimer la clé enregistrée",
"mod.pbc.keyHint": "Laissez le champ vide pour conserver la clé du même point d’accès. Ollama en local ne demande généralement pas de clé.",
"mod.pbc.save": "Enregistrer la connexion",
"mod.pbc.saved": "Connexion au modèle enregistrée.",
"mod.pbc.useConnection": "Cette connexion deviendra la connexion par défaut de mod-pbc sur le serveur.",
"mod.settings": "Réglages", "mod.settings": "Réglages",
"mod.default": "Revenir à la valeur par défaut ({v})", "mod.default": "Revenir à la valeur par défaut ({v})",
"mod.saved": "Enregistré ({n} modifié(s)).", "mod.saved": "Enregistré ({n} modifié(s)).",
+12
View File
@@ -874,6 +874,18 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"mod.switch": "Включить или выключить {name}", "mod.switch": "Включить или выключить {name}",
"mod.notHere": "Нет в этом сервере", "mod.notHere": "Нет в этом сервере",
"mod.github": "GitHub", "mod.github": "GitHub",
"mod.pbc.connection": "Подключение к модели",
"mod.pbc.provider": "Провайдер модели",
"mod.pbc.compatible": "Эндпоинт, совместимый с OpenAI",
"mod.pbc.model": "Имя модели",
"mod.pbc.endpoint": "Базовый URL API",
"mod.pbc.key": "Ключ API",
"mod.pbc.savedKey": "Ключ сохранён",
"mod.pbc.removeKey": "Удалить сохранённый ключ",
"mod.pbc.keyHint": "Оставьте поле пустым, чтобы сохранить ключ для того же адреса. Локальной Ollama обычно ключ не нужен.",
"mod.pbc.save": "Сохранить подключение",
"mod.pbc.saved": "Подключение к модели сохранено.",
"mod.pbc.useConnection": "После сохранения это подключение станет основным для mod-pbc на сервере.",
"mod.settings": "Настройки", "mod.settings": "Настройки",
"mod.default": "Вернуть по умолчанию ({v})", "mod.default": "Вернуть по умолчанию ({v})",
"mod.saved": "Сохранено (изменено: {n}).", "mod.saved": "Сохранено (изменено: {n}).",
+12
View File
@@ -845,6 +845,18 @@ const zh = {
"mod.switch": "开启或关闭 {name}", "mod.switch": "开启或关闭 {name}",
"mod.notHere": "未包含在当前服务器中", "mod.notHere": "未包含在当前服务器中",
"mod.github": "GitHub 页面", "mod.github": "GitHub 页面",
"mod.pbc.connection": "模型连接",
"mod.pbc.provider": "模型服务商",
"mod.pbc.compatible": "兼容 OpenAI 的端点",
"mod.pbc.model": "模型名称",
"mod.pbc.endpoint": "API 基础网址",
"mod.pbc.key": "API 密钥",
"mod.pbc.savedKey": "已保存密钥",
"mod.pbc.removeKey": "删除已保存的密钥",
"mod.pbc.keyHint": "留空会保留同一端点的密钥。本地 Ollama 通常不需要密钥。",
"mod.pbc.save": "保存模型连接",
"mod.pbc.saved": "模型连接已保存。",
"mod.pbc.useConnection": "保存后,此连接将成为该服务器上 mod-pbc 的默认连接。",
"mod.settings": "模块设置", "mod.settings": "模块设置",
"mod.default": "恢复为默认值 ({v})", "mod.default": "恢复为默认值 ({v})",
"mod.saved": "已保存(修改了 {n} 项)。", "mod.saved": "已保存(修改了 {n} 项)。",
+17
View File
@@ -229,6 +229,21 @@ export interface RealmProfile {
data: string; data: string;
} }
export type PbcApiType = "openai" | "ollama" | "anthropic";
export interface PbcConnection {
apiType: PbcApiType;
baseUrl: string;
model: string;
}
export interface PbcConnectionSetup {
active: boolean;
connection: (PbcConnection & { hasKey: boolean }) | null;
}
export interface PbcConnectionUpdate extends PbcConnection {
apiKey?: string;
removeKey: boolean;
}
export interface ModuleView { export interface ModuleView {
id: string; id: string;
name: string; name: string;
@@ -545,6 +560,8 @@ export const api = {
realmlistDelete: (id: string, profileId: string) => invoke<void>("realmlist_delete", { id, profileId }), realmlistDelete: (id: string, profileId: string) => invoke<void>("realmlist_delete", { id, profileId }),
realmlistActivate: (id: string, profileId: string) => invoke<string[]>("realmlist_activate", { id, profileId }), realmlistActivate: (id: string, profileId: string) => invoke<string[]>("realmlist_activate", { id, profileId }),
modulesList: (id: string) => invoke<ModuleView[]>("modules_list", { id }), modulesList: (id: string) => invoke<ModuleView[]>("modules_list", { id }),
pbcConnection: (id: string) => invoke<PbcConnectionSetup>("pbc_connection", { id }),
pbcSaveConnection: (id: string, update: PbcConnectionUpdate) => invoke<PbcConnectionSetup>("pbc_save_connection", { id, update }),
moduleSetEnabled: (id: string, module: string, enabled: boolean) => invoke<void>("module_set_enabled", { id, module, enabled }), moduleSetEnabled: (id: string, module: string, enabled: boolean) => invoke<void>("module_set_enabled", { id, module, enabled }),
moduleSettings: (id: string, module: string) => invoke<ModuleSetting[]>("module_settings", { id, module }), moduleSettings: (id: string, module: string) => invoke<ModuleSetting[]>("module_settings", { id, module }),
moduleSaveSettings: (id: string, module: string, changes: Record<string, string>) => invoke<string[]>("module_save_settings", { id, module, changes }), moduleSaveSettings: (id: string, module: string, changes: Record<string, string>) => invoke<string[]>("module_save_settings", { id, module, changes }),
+7 -3
View File
@@ -9,6 +9,7 @@ import { useHuman, useI18n, useSchemaText, type Key } from "@/i18n";
import { auctionWeightKey, canonicalModuleValue, moduleEnableKey, moduleField, retiredModuleKeys } from "@/lib/moduleSettings"; import { auctionWeightKey, canonicalModuleValue, moduleEnableKey, moduleField, retiredModuleKeys } from "@/lib/moduleSettings";
import { AuctionTypes } from "@/screens/AuctionTypes"; import { AuctionTypes } from "@/screens/AuctionTypes";
import { RaceAvailabilitySettings } from "@/screens/RaceAvailabilitySettings"; import { RaceAvailabilitySettings } from "@/screens/RaceAvailabilitySettings";
import { PbcConnectionSettings } from "@/screens/PbcConnectionSettings";
import type { UnsavedChangesGuard } from "@/lib/unsavedGuard"; import type { UnsavedChangesGuard } from "@/lib/unsavedGuard";
/** The GitHub mark (lucide dropped its brand icons). */ /** The GitHub mark (lucide dropped its brand icons). */
@@ -111,16 +112,18 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
}, [serverId]); }, [serverId]);
const [guard, setGuard] = useState<UnsavedChangesGuard | null>(null); const [guard, setGuard] = useState<UnsavedChangesGuard | null>(null);
const [racesGuard, setRacesGuard] = useState<UnsavedChangesGuard | null>(null); const [racesGuard, setRacesGuard] = useState<UnsavedChangesGuard | null>(null);
const [pbcGuard, setPbcGuard] = useState<UnsavedChangesGuard | null>(null);
const markChanged = useCallback(() => setChanged(true), []);
useEffect(() => { useEffect(() => {
const guards = [guard, racesGuard].filter((item): item is UnsavedChangesGuard => item !== null); const guards = [guard, racesGuard, pbcGuard].filter((item): item is UnsavedChangesGuard => item !== null);
onRegisterGuard?.(guards.length ? { onRegisterGuard?.(guards.length ? {
isDirty: () => guards.some(item => item.isDirty()), isDirty: () => guards.some(item => item.isDirty()),
save: async () => { for (const item of guards) if (item.isDirty() && !await item.save()) return false; return true; }, save: async () => { for (const item of guards) if (item.isDirty() && !await item.save()) return false; return true; },
discard: () => guards.forEach(item => item.discard()), discard: () => guards.forEach(item => item.discard()),
} : null); } : null);
return () => onRegisterGuard?.(null); return () => onRegisterGuard?.(null);
}, [guard, racesGuard, onRegisterGuard]); }, [guard, racesGuard, pbcGuard, onRegisterGuard]);
const load = useCallback(async () => { const load = useCallback(async () => {
try { try {
@@ -343,6 +346,7 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
{selected?.has_settings && !selected.page && selectedAt >= 0 && Math.floor(selectedAt / 2) === Math.floor(i / 2) && (i % 2 === 1 || i === modules.length - 1) && ( {selected?.has_settings && !selected.page && selectedAt >= 0 && Math.floor(selectedAt / 2) === Math.floor(i / 2) && (i % 2 === 1 || i === modules.length - 1) && (
<SettingsPanel key={selected.id} className="sm:col-span-2"> <SettingsPanel key={selected.id} className="sm:col-span-2">
<h2 className="font-semibold">{t("mod.settingsOf", { name: selected.name })}</h2> <h2 className="font-semibold">{t("mod.settingsOf", { name: selected.name })}</h2>
{selected.id === "mod-pbc" && <PbcConnectionSettings serverId={serverId} onSaved={markChanged} onRegisterGuard={setPbcGuard} />}
<ModuleSettings serverId={serverId} module={selected} onSaved={() => setChanged(true)} onRegisterGuard={setGuard} /> <ModuleSettings serverId={serverId} module={selected} onSaved={() => setChanged(true)} onRegisterGuard={setGuard} />
{selected.id === "custom-races" && <RaceAvailabilitySettings serverId={serverId} {selected.id === "custom-races" && <RaceAvailabilitySettings serverId={serverId}
blocked={racesInstalling || toggling !== null} onSaved={() => setChanged(true)} blocked={racesInstalling || toggling !== null} onSaved={() => setChanged(true)}
@@ -461,7 +465,7 @@ function ModuleSettings({ serverId, module, onSaved, onRegisterGuard }: { server
else next[key] = value; else next[key] = value;
return next; return next;
}); });
const available = items?.filter(s => s.key !== moduleEnableKey(module.id) && !["CoACustomRaces.DisabledRaceIds", "CoACustomRaces.DisabledRaceCatalogSha256"].includes(s.key) && !retiredModuleKeys.has(s.key)) ?? []; const available = items?.filter(s => s.key !== moduleEnableKey(module.id) && !["CoACustomRaces.DisabledRaceIds", "CoACustomRaces.DisabledRaceCatalogSha256", "PBC.DefaultConnection"].includes(s.key) && !retiredModuleKeys.has(s.key)) ?? [];
const advancedCount = available.filter(s => !auctionWeightKey(s.key) && (!moduleField(s.key, locale, s.field) || moduleField(s.key, locale, s.field)?.advanced)).length; const advancedCount = available.filter(s => !auctionWeightKey(s.key) && (!moduleField(s.key, locale, s.field) || moduleField(s.key, locale, s.field)?.advanced)).length;
const visible = available.filter(s => { const visible = available.filter(s => {
if (module.id === "ah-bot" && auctionWeightKey(s.key)) return false; if (module.id === "ah-bot" && auctionWeightKey(s.key)) return false;
+141
View File
@@ -0,0 +1,141 @@
import { useCallback, useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { useHuman, useI18n } from "@/i18n";
import { api, asUiError, type PbcConnection, type PbcConnectionSetup, type UiError } from "@/lib/api";
import type { UnsavedChangesGuard } from "@/lib/unsavedGuard";
type Provider = "openai" | "ollama" | "anthropic" | "compatible";
const presets: Record<Provider, PbcConnection> = {
openai: { apiType: "openai", baseUrl: "https://api.openai.com/v1", model: "gpt-5.4-mini" },
ollama: { apiType: "ollama", baseUrl: "http://127.0.0.1:11434", model: "" },
anthropic: { apiType: "anthropic", baseUrl: "https://api.anthropic.com/v1", model: "" },
compatible: { apiType: "openai", baseUrl: "", model: "" },
};
const providerOf = (connection: PbcConnection): Provider => connection.apiType !== "openai" ? connection.apiType
: connection.baseUrl === presets.openai.baseUrl ? "openai" : "compatible";
const inputClass = "selectable w-full rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold";
export function PbcConnectionSettings({ serverId, onSaved, onRegisterGuard }: {
serverId: string;
onSaved: () => void;
onRegisterGuard: (guard: UnsavedChangesGuard | null) => void;
}) {
const { t } = useI18n();
const human = useHuman();
const [setup, setSetup] = useState<PbcConnectionSetup | null>(null);
const [connection, setConnection] = useState<PbcConnection>(presets.openai);
const [provider, setProvider] = useState<Provider>("openai");
const [apiKey, setApiKey] = useState("");
const [removeKey, setRemoveKey] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<UiError | null>(null);
const [saved, setSaved] = useState(false);
const reset = useCallback((value: PbcConnectionSetup) => {
const current = value.connection ?? presets.openai;
setConnection(current);
setProvider(providerOf(current));
setApiKey("");
setRemoveKey(false);
}, []);
useEffect(() => {
let cancelled = false;
setSetup(null);
setSaved(false);
setError(null);
void api.pbcConnection(serverId).then(value => {
if (cancelled) return;
setSetup(value);
reset(value);
}).catch(e => { if (!cancelled) setError(asUiError(e)); });
return () => { cancelled = true; };
}, [serverId, reset]);
const previous = setup?.connection ?? presets.openai;
const dirty = !!setup && (connection.apiType !== previous.apiType || connection.baseUrl !== previous.baseUrl
|| connection.model !== previous.model || !!apiKey || removeKey);
const sameEndpoint = connection.apiType === previous.apiType
&& connection.baseUrl.trim().replace(/\/+$/, "") === previous.baseUrl;
const hasKey = !!setup?.connection?.hasKey && sameEndpoint;
const valid = !!connection.baseUrl.trim() && !!connection.model.trim();
const save = useCallback(async () => {
if (!setup || !valid || busy) return false;
setBusy(true);
setSaved(false);
setError(null);
try {
const next = await api.pbcSaveConnection(serverId, { ...connection, apiKey: apiKey || undefined, removeKey });
setSetup(next);
reset(next);
setSaved(true);
onSaved();
return true;
} catch (e) {
setError(asUiError(e));
return false;
} finally {
setBusy(false);
}
}, [setup, valid, busy, serverId, connection, apiKey, removeKey, reset, onSaved]);
useEffect(() => {
if (!setup || !dirty) return;
onRegisterGuard({ isDirty: () => true, save, discard: () => reset(setup) });
return () => onRegisterGuard(null);
}, [setup, dirty, save, reset, onRegisterGuard]);
function changeProvider(value: Provider) {
setProvider(value);
setConnection(presets[value]);
setApiKey("");
setRemoveKey(false);
setSaved(false);
}
return (
<section className="mt-4 space-y-3 border-t border-line pt-4" aria-labelledby="pbc-connection-heading">
<h3 id="pbc-connection-heading" className="font-semibold">{t("mod.pbc.connection")}</h3>
{error && <p className="text-sm text-warn" role="alert">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>}
{setup && (
<form className="space-y-3" onSubmit={event => { event.preventDefault(); void save(); }}>
{!setup.active && <p className="text-sm text-muted">{t("mod.pbc.useConnection")}</p>}
<fieldset disabled={busy} className="grid gap-3 sm:grid-cols-2">
<label className="space-y-1 text-sm">
<span>{t("mod.pbc.provider")}</span>
<select className={inputClass} value={provider} onChange={event => changeProvider(event.target.value as Provider)}>
<option value="openai">OpenAI</option>
<option value="ollama">Ollama</option>
<option value="anthropic">Anthropic</option>
<option value="compatible">{t("mod.pbc.compatible")}</option>
</select>
</label>
<label className="space-y-1 text-sm">
<span>{t("mod.pbc.model")}</span>
<input className={inputClass} value={connection.model} required onChange={event => { setConnection({ ...connection, model: event.target.value }); setSaved(false); }} />
</label>
<label className="space-y-1 text-sm sm:col-span-2">
<span>{t("mod.pbc.endpoint")}</span>
<input className={inputClass} value={connection.baseUrl} type="url" required readOnly={provider === "openai"}
onChange={event => { setConnection({ ...connection, baseUrl: event.target.value }); setApiKey(""); setRemoveKey(false); setSaved(false); }} />
</label>
<label className="space-y-1 text-sm sm:col-span-2">
<span>{t("mod.pbc.key")}</span>
<input className={inputClass} value={apiKey} type="password" autoComplete="off" disabled={removeKey}
placeholder={hasKey ? t("mod.pbc.savedKey") : undefined}
onChange={event => { setApiKey(event.target.value); setSaved(false); }} />
</label>
{hasKey && <label className="flex items-center gap-2 text-sm sm:col-span-2">
<input type="checkbox" checked={removeKey} onChange={event => { setRemoveKey(event.target.checked); setApiKey(""); setSaved(false); }} />
{t("mod.pbc.removeKey")}
</label>}
</fieldset>
<p className="text-sm text-muted">{t("mod.pbc.keyHint")}</p>
<Button size="sm" type="submit" disabled={busy || !valid || (setup.active && !dirty)}>{t("mod.pbc.save")}</Button>
{saved && <p className="text-sm text-ok" role="status">{t("mod.pbc.saved")}</p>}
</form>
)}
</section>
);
}