Telegram-бот Boltun AI на grammY + Mastra
- Отвечает только администраторам из ADMIN_IDS - Личности на чат: встроенные и пользовательские (/personas, /persona, /persona_add, /persona_del) - Вопросы через /ask, упоминание, ответ боту или личку - Сохраняет сообщения чата в SQLite; агент по просьбе читает их инструментом read_chat_messages - Модели через OpenRouter (по умолчанию DeepSeek) - Слои: libs, repositories, services, bot/handlers - Dockerfile для деплоя в Dokploy Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
73
src/services/persona-service.ts
Normal file
73
src/services/persona-service.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { BUILTIN_PERSONAS, DEFAULT_PERSONA_ID, PERSONA_ID_PATTERN } from "../constants/personas.js";
|
||||
import type { ChatSettingsRepository } from "../repositories/chat-settings-repository.js";
|
||||
import type { PersonaRepository } from "../repositories/persona-repository.js";
|
||||
import type { Persona } from "../types.js";
|
||||
|
||||
interface PersonaServiceDeps {
|
||||
personaRepository: PersonaRepository;
|
||||
chatSettingsRepository: ChatSettingsRepository;
|
||||
}
|
||||
|
||||
export type SaveCustomResult =
|
||||
| { ok: true; id: string; updated: boolean }
|
||||
| { ok: false; id: string; reason: "invalid" | "builtin" };
|
||||
|
||||
export type RemoveCustomResult = { ok: true; id: string } | { ok: false; id: string; reason: "not_found" | "builtin" };
|
||||
|
||||
export const createPersonaService = ({ personaRepository, chatSettingsRepository }: PersonaServiceDeps) => {
|
||||
/** Добавляет встроенные личности и обновляет их текст, не трогая пользовательские. */
|
||||
const seedBuiltins = () => personaRepository.upsertBuiltin(BUILTIN_PERSONAS);
|
||||
|
||||
const list = (): Persona[] => personaRepository.list();
|
||||
|
||||
/** id личностей регистронезависимы: храним и ищем в нижнем регистре. */
|
||||
const normalizeId = (id: string): string => id.trim().toLowerCase();
|
||||
|
||||
const find = (id: string): Persona | undefined => personaRepository.findById(normalizeId(id));
|
||||
|
||||
const getActive = (chatId: number): Persona =>
|
||||
personaRepository.findById(chatSettingsRepository.findPersonaId(chatId) ?? DEFAULT_PERSONA_ID) ??
|
||||
personaRepository.findById(DEFAULT_PERSONA_ID)!;
|
||||
|
||||
/** Делает личность активной в чате; undefined — если такой личности нет. */
|
||||
const select = (chatId: number, id: string): Persona | undefined => {
|
||||
const persona = find(id);
|
||||
|
||||
if (persona) chatSettingsRepository.setPersonaId(chatId, persona.id);
|
||||
|
||||
return persona;
|
||||
};
|
||||
|
||||
const saveCustom = (rawId: string, prompt: string): SaveCustomResult => {
|
||||
const id = normalizeId(rawId);
|
||||
|
||||
if (!PERSONA_ID_PATTERN.test(id) || !prompt.trim()) return { ok: false, id, reason: "invalid" };
|
||||
|
||||
const existing = personaRepository.findById(id);
|
||||
|
||||
if (existing?.builtin) return { ok: false, id, reason: "builtin" };
|
||||
|
||||
personaRepository.upsertCustom({ id, name: id, prompt: prompt.trim() });
|
||||
|
||||
return { ok: true, id, updated: existing !== undefined };
|
||||
};
|
||||
|
||||
/** Удаляет пользовательскую личность; чаты, где она была выбрана, вернутся к личности по умолчанию. */
|
||||
const removeCustom = (rawId: string): RemoveCustomResult => {
|
||||
const id = normalizeId(rawId);
|
||||
const persona = personaRepository.findById(id);
|
||||
|
||||
if (!persona) return { ok: false, id, reason: "not_found" };
|
||||
if (persona.builtin) return { ok: false, id, reason: "builtin" };
|
||||
|
||||
// Сначала сбрасываем выбор в чатах: если процесс упадёт между шагами, ссылок на удалённую личность не останется.
|
||||
chatSettingsRepository.resetPersona(id);
|
||||
personaRepository.deleteCustom(id);
|
||||
|
||||
return { ok: true, id };
|
||||
};
|
||||
|
||||
return { seedBuiltins, list, find, getActive, select, saveCustom, removeCustom };
|
||||
};
|
||||
|
||||
export type PersonaService = ReturnType<typeof createPersonaService>;
|
||||
Reference in New Issue
Block a user