Участники чата, промпты в файлах, личности только из кода
- Бот запоминает участников (имя, фамилия, ник, активность) и ID автора каждого сообщения - Упоминания в вопросе (@ник и по имени-ссылке) передаются модели с данными участника - Новые инструменты агента: list_chat_members, read_member_messages (поиск по нику/имени) - Бот обращается к людям по имени - Промпты вынесены в prompts/system.md и prompts/personas/<id>.md - Личности больше не редактируются из чата: скрипт seed синхронизирует их с БД при старте - Оставлена одна личность boltun (Dirty D) - Миграция старых баз: колонка messages.user_id Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { BUILTIN_PERSONAS, DEFAULT_PERSONA_ID, PERSONA_ID_PATTERN } from "../constants/personas.js";
|
||||
import { DEFAULT_PERSONA_ID } 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";
|
||||
@@ -8,66 +8,24 @@ interface PersonaServiceDeps {
|
||||
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);
|
||||
const persona = personaRepository.findById(id.trim().toLowerCase());
|
||||
|
||||
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 };
|
||||
return { list, getActive, select };
|
||||
};
|
||||
|
||||
export type PersonaService = ReturnType<typeof createPersonaService>;
|
||||
|
||||
Reference in New Issue
Block a user