peppa/packages/runner/src/analyst-chat.ts

172 lines
9.5 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,
attachmentsForModel,
ANALYST_NAME,
createTask,
deliverToUser,
discussionHistory,
getUserLocale,
notify,
INTENT_TEXT,
parseAnalystReply,
quickIntent,
setChatOffer,
projectAudience,
setAnalystCursor,
setIntakeState,
type Project,
pausedProjectIds,
} from "@peppa/core";
import { chatMessages, chats, projects, type Db } from "@peppa/db";
import { and, desc, eq, gt, isNull, lte } from "drizzle-orm";
import { localizeRoleMessage, m as tr, t, type Locale } from "@peppa/shared/i18n";
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, 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<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"));
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`: «Аналитик», «Продакт», 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, extra: { buttons?: (locale: Locale) => Array<Array<{ text: string; callback_data: string }>> } = {}) {
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: `💬 <b>${esc(project.name)}</b> · ${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<void> {
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<typeof setChatOffer>[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) });
const out = await ask(db, project, analystChatPrompt(await analystChatContext(db, project), history, attached.prompt), attached.files);
// 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;
}
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}»`);
}
const kind = filed.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, filed.length ? `${reply.reply}\n\n${tr("Завёл в бэклог:")}\n${filed.join("\n")}` : reply.reply);
if (kind === "question") await offer(said, { kind: "task", text });
log(`analyst chat ${project.key}: answered${filed.length ? `, filed ${filed.length}` : ""}`);
}