// PEP-110: the analyst answers in the project's discussion. The watchdog calls // `analystChatTick`; a person's message that nobody answered yet goes to the model (on the // project's own subscription, like the intake roles) together with the project's context and // the last messages, and the answer is posted into the same discussion. Stories the person // asked for are filed into the backlog, already formulated (the intake roles skip them). import { addChatMessage, analystChatContext, analystChatPrompt, analystCursor, ANALYST_NAME, createTask, deliverToUser, discussionHistory, getUserLocale, notify, parseAnalystReply, projectAudience, setAnalystCursor, setIntakeState, type Project, } from "@peppa/core"; import { chatMessages, chats, projects, type Db } from "@peppa/db"; import { and, desc, eq, gt, isNull } from "drizzle-orm"; import { localizeRoleMessage, m as tr, t } from "@peppa/shared/i18n"; import { claudePrint } from "./claude-print.ts"; const inFlight = new Set(); const esc = (s: string) => s.replace(/&/g, "&").replace(//g, ">"); const ask = (db: Db, project: Project, prompt: string) => claudePrint(db, project, { bin: process.env.PEPPA_INTAKE_BIN ?? "claude", model: process.env.PEPPA_ANALYST_CHAT_MODEL ?? process.env.PEPPA_INTAKE_MODEL ?? "sonnet", timeoutMs: Number(process.env.PEPPA_INTAKE_TIMEOUT_MS ?? 180_000), prompt, who: "аналитик", }); export interface AnalystChatOptions { log?: (m: string) => void; now?: Date; /** Wait for the model calls (tests); the watchdog lets them run in the background. */ wait?: boolean; } /** People's messages in project discussions that the analyst has not answered yet. */ export async function analystChatTick(db: Db, opts: AnalystChatOptions = {}): Promise { if (process.env.PEPPA_ANALYST_CHAT === "off") return; const log = opts.log ?? (() => {}); const now = (opts.now ?? new Date()).getTime(); const maxAgeMs = Math.max(1, Number(process.env.PEPPA_ANALYST_CHAT_MAX_AGE_MIN ?? 60) || 60) * 60_000; const jobs: Promise[] = []; const rows = await db.select({ chat: chats, project: projects }).from(chats).innerJoin(projects, eq(chats.projectId, projects.id)).where(eq(chats.kind, "project")); for (const { chat, project } of rows) { if (inFlight.has(chat.id)) continue; const cursor = await analystCursor(db, chat.id); const [last] = await db .select({ id: chatMessages.id, kind: chatMessages.authorKind, text: chatMessages.text, at: chatMessages.createdAt }) .from(chatMessages) .where(and(eq(chatMessages.chatId, chat.id), isNull(chatMessages.threadKey), eq(chatMessages.kind, "user"), gt(chatMessages.id, cursor))) .orderBy(desc(chatMessages.id)) .limit(1); if (!last) continue; // The analyst's own message or a command on top: nothing to answer, move on. So is a message // that waited too long (written before the analyst existed, or during an outage): a late // answer to a stale question only confuses — the person asks again. const stale = now - last.at.getTime() > maxAgeMs; if (last.kind !== "user" || last.text.startsWith("/") || stale) { await setAnalystCursor(db, chat.id, last.id); continue; } inFlight.add(chat.id); jobs.push( answer(db, project, chat.id, last.id, log) .catch((e) => log(`analyst chat ${project.key}: ${(e as Error).message}`)) .finally(() => inFlight.delete(chat.id)), ); } if (opts.wait) await Promise.all(jobs); } /** * A message in the project's discussion from an AI role (`author`: «Аналитик», «Продакт», an * agent's name) or, without an author, a system note. An agent's message also reaches the * project's people in their own Telegram bot / browser. */ export async function sayInDiscussion(db: Db, project: Project, chatId: number, text: string, author: string | null = ANALYST_NAME) { const m = await addChatMessage(db, author ? { chatId, kind: "user", authorKind: "agent", authorLogin: author, text } : { chatId, kind: "user", authorKind: "system", text }); await notify(db, { type: "chat_message", messageId: m?.id ?? 0 }); if (author && m) { const cut = (s: string) => (s.length > 800 ? `${s.slice(0, 800)}…` : s); for (const u of await projectAudience(db, project.id)) { // In the reader's language here: only the fixed lines are translated, the model's own // words stay as written (the general translation on delivery would rewrite them). const locale = await getUserLocale(db, u.id); const short = cut(localizeRoleMessage(locale, text)); const who = localizeRoleMessage(locale, author); await deliverToUser(db, u, { event: "chat", localized: true, projectId: project.id, dedupeKey: `chat:m${m.id}:${u.telegramChatId}`, pushKey: `chat:m${m.id}:u${u.id}`, telegram: { params: { text: `💬 ${esc(project.name)} · ${esc(who)}:\n${esc(short)}\n\n${t(locale, "Ответить: {url}", { url: `${process.env.PEPPA_WEB_URL ?? ""}/chats/${project.key}` })}`, parse_mode: "HTML", link_preview_options: { is_disabled: true } } }, push: { title: `${project.name}: ${who}`, body: short.slice(0, 200), url: `/chats/${project.key}`, tag: `chat:${project.id}` }, }).catch(() => null); } } return m; } const say = (db: Db, project: Project, chatId: number, text: string, agent = true) => sayInDiscussion(db, project, chatId, text, agent ? ANALYST_NAME : null); async function answer(db: Db, project: Project, chatId: number, upTo: number, log: (m: string) => void): Promise { const history = await discussionHistory(db, chatId); const out = await ask(db, project, analystChatPrompt(await analystChatContext(db, project), history)); // Whatever happens, this message is dealt with: a failure is said once, not retried forever. await setAnalystCursor(db, chatId, upTo); if (!out.ok) { const noSub = /нет подписки/.test(out.error); await say(db, project, chatId, noSub ? tr("Аналитик отвечает на подписке проекта, а она не подключена. Подключите Claude в «⋯ Настройки проекта → Подписки» — и напишите ещё раз.") : tr("Аналитик сейчас не смог ответить. Напишите ещё раз чуть позже."), false); log(`analyst chat ${project.key}: ${out.error}`); return; } const reply = parseAnalystReply(out.text); if (!reply) { await say(db, project, chatId, tr("Аналитик ответил не по форме — напишите вопрос ещё раз, пожалуйста."), false); log(`analyst chat ${project.key}: unparsable answer`); return; } const filed: string[] = []; for (const s of reply.create) { const ref = await createTask(db, { projectId: project.id, title: s.title, description: s.description }); // Formulated in the conversation already: «продакт» and «аналитик» of the intake skip it. await setIntakeState(db, ref.task.id, { stage: "done", original: { title: s.title, description: s.description }, attempts: 0, note: "сформулирована с аналитиком в чате" }); filed.push(`• ${ref.key} «${s.title}»`); } await say(db, project, chatId, filed.length ? `${reply.reply}\n\n${tr("Завёл в бэклог:")}\n${filed.join("\n")}` : reply.reply); log(`analyst chat ${project.key}: answered${filed.length ? `, filed ${filed.length}` : ""}`); }