peppa/packages/runner/src/analyst-chat.ts
2026-11-16 09:52:35 +05:00

137 lines
7.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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,
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 { claudePrint } from "./claude-print.ts";
const inFlight = new Set<number>();
const esc = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
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<void> {
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<void>[] = [];
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 short = text.length > 800 ? `${text.slice(0, 800)}…` : text;
for (const u of await projectAudience(db, project.id)) {
await deliverToUser(db, u, {
event: "chat",
projectId: project.id,
dedupeKey: `chat:m${m.id}:${u.telegramChatId}`,
pushKey: `chat:m${m.id}:u${u.id}`,
telegram: { params: { text: `💬 <b>${esc(project.name)}</b> · ${esc(author)}:\n${esc(short)}\n\nОтветить: ${process.env.PEPPA_WEB_URL ?? ""}/chats/${project.key}`, parse_mode: "HTML", link_preview_options: { is_disabled: true } } },
push: { title: `${project.name}: ${author}`, 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<void> {
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);
// glossary-user: ответ «Аналитика» в обсуждение проекта
await say(db, project, chatId, noSub ? "Аналитик отвечает на подписке проекта, а она не подключена. Подключите Claude в «⋯ Настройки проекта → Подписки» — и напишите ещё раз." : `Аналитик сейчас не смог ответить (${out.error.slice(0, 200)}). Напишите ещё раз чуть позже.`, false);
log(`analyst chat ${project.key}: ${out.error}`);
return;
}
const reply = parseAnalystReply(out.text);
if (!reply) {
// glossary-user: ответ «Аналитика» в обсуждение проекта
await say(db, project, chatId, "Аналитик ответил не по форме — напишите вопрос ещё раз, пожалуйста.", 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}»`);
}
// glossary-user: ответ «Аналитика» в обсуждение проекта
await say(db, project, chatId, filed.length ? `${reply.reply}\n\nЗавёл в бэклог:\n${filed.join("\n")}` : reply.reply);
log(`analyst chat ${project.key}: answered${filed.length ? `, filed ${filed.length}` : ""}`);
}