// 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, asksAboutLook, agentSignature, analystCursor, attachmentsForModel, ANALYST_NAME, isRoleName, deliverToUser, discussionHistory, getUserLocale, notify, INTENT_TEXT, parseAnalystReply, quickIntent, setChatOffer, projectAudience, setAnalystCursor, type Project, pausedProjectIds, } from "@peppa/core"; import { chatMessages, chats, projects, releases, type Db } from "@peppa/db"; import { and, desc, eq, gt, isNull, lte } from "drizzle-orm"; import { asIs, localizeRoleMessage, m as tr, t, type Locale } from "@peppa/shared/i18n"; import { releaseScreenshotFiles } from "./deploy.ts"; 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, files?: Array<{ name: string; path: 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, files, 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")); const paused = await pausedProjectIds(db); for (const { chat, project } of rows) { // PEP-174: the analyst does not answer in a project on pause. if (inFlight.has(chat.id) || paused.has(project.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, cursor, 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`: «Аналитик», «Продакт-агент») * or an agent (its nickname) 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, extra: { buttons?: (locale: Locale) => Array>; /** An agent that has no nickname yet (PEP-156). */ agent?: boolean } = {}) { const fromAgent = !!author || !!extra.agent; const m = await addChatMessage(db, fromAgent ? { 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 (fromAgent && 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)); // PEP-156: a role signs with its name (in the reader's language), an agent — «🤖 кличка». const who = author && isRoleName(author) ? localizeRoleMessage(locale, author) : agentSignature(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 }, ...(extra.buttons ? { reply_markup: { inline_keyboard: extra.buttons(locale) } } : {}) } }, 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, from: number, upTo: number, log: (m: string) => void): Promise { const history = await discussionHistory(db, chatId); // PEP-153: what the person wrote — a question or a task. A question gets «Завести как задачу» // under the answer; when it is unclear or the analyst is not at hand, the person picks by a button. const [asked] = await db.select({ text: chatMessages.text }).from(chatMessages).where(eq(chatMessages.id, upTo)); const text = asked?.text ?? ""; const hint = quickIntent(text); const offer = async (said: { id: number } | null | undefined, o: Parameters[2]) => { if (said) await setChatOffer(db, said.id, o); }; const pick = "\n" + INTENT_TEXT.pick; // PEP-159: files of the messages not answered yet (everything after the cursor). const fresh = await db .select({ id: chatMessages.id }) .from(chatMessages) .where(and(eq(chatMessages.chatId, chatId), isNull(chatMessages.threadKey), gt(chatMessages.id, from), lte(chatMessages.id, upTo))); const attached = await attachmentsForModel(db, { messageIds: fresh.map((r) => r.id) }); // PEP-198 (6.2): «как это сейчас выглядит?» — the last screenshots of the product go along. const shots = asksAboutLook(text) ? await lastScreenshots(db, project.id) : []; const out = await ask(db, project, analystChatPrompt(await analystChatContext(db, project), history, attached.prompt + (shots.length ? `\n\nСнимки экрана продукта (последние): ${shots.map((s) => s.name).join(", ")}` : "")), [...(attached.files ?? []), ...shots]); // 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 offer(await say(db, project, chatId, (noSub ? tr("Аналитик отвечает на подписке проекта, а она не подключена. Подключите Claude в «⋯ Настройки проекта → Подписки» — и напишите ещё раз.") : tr("Аналитик сейчас не смог ответить. Напишите ещё раз чуть позже.")) + pick, false), { kind: "choice", text, answer: null }); log(`analyst chat ${project.key}: ${out.error}`); return; } const reply = parseAnalystReply(out.text); if (!reply) { await offer(await say(db, project, chatId, tr("Аналитик ответил не по форме — напишите вопрос ещё раз, пожалуйста.") + pick, false), { kind: "choice", text, answer: null }); log(`analyst chat ${project.key}: unparsable answer`); return; } // PEP-198 (7.1): the analyst only suggests — the stories are filed by the person's press of // «Завести задачи» (resolveChatOffer), never by the model deciding the person said «yes». const suggested = reply.create; const kind = suggested.length ? "task" : (reply.kind ?? hint); if (kind === "unsure") { await offer(await say(db, project, chatId, INTENT_TEXT.unsure, false), { kind: "choice", text, answer: reply.reply }); log(`analyst chat ${project.key}: unsure, asked`); return; } const said = await say(db, project, chatId, suggested.length ? `${reply.reply}\n\n${tr("Предлагаю завести:")}\n${suggested.map((s) => `• ${asIs(s.title)}`).join("\n")}` : reply.reply); if (suggested.length) await offer(said, { kind: "stories", text, stories: suggested }); else if (kind === "question") await offer(said, { kind: "task", text }); log(`analyst chat ${project.key}: answered${suggested.length ? `, suggested ${suggested.length}` : ""}`); } /** PEP-198 (6.2): the newest screenshots of the project's product (at most two files). */ async function lastScreenshots(db: Db, projectId: number): Promise> { const rels = await db.select().from(releases).where(eq(releases.projectId, projectId)).orderBy(desc(releases.id)).limit(20); const rel = rels.find((r) => r.screenshots.length); return rel ? releaseScreenshotFiles(rel).slice(0, 2).map((path, i) => ({ name: `screen-${i + 1}.png`, path })) : []; }