peppa/packages/runner/src/chats.ts

206 lines
13 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-62: a person's message in a chat (web or a linked Telegram group). In a story thread it
// answers the story's open question or becomes a PM comment typed into the live runner; in
// other threads and the channel it is a note; a text starting with "/" is a command.
import { asIs, m, m as tr } from "@peppa/shared/i18n";
import { addChatMessage, addStoryComment, attachmentLabel, linkAttachments, parseAttachmentIds, refinePending, chatForUser, deliverToUser, projectAudience, listSessions, notify, pendingQuestions, projectForUser, resolveTask, statusRu, THREAD_KEY, userProjectIds, type Chat, type ChatMessage, type User, PeppaError, MESSAGE_MAX } from "@peppa/core";
import { attachments, projects, questions, tasks, type Db } from "@peppa/db";
import { and, desc, eq, isNull, ne } from "drizzle-orm";
import { moveTask, type BoardColumn } from "./flow.ts";
import { answerAndDeliver, sendToSession, syncSessionAttachments } from "./sessions.ts";
export interface ChatPost {
chatId: number;
/** null = the channel. */
threadKey: string | null;
text: string;
via: "web" | "telegram";
/** A reply to this question's message (Telegram): answer exactly it. */
questionId?: number | null;
/** Where it was written in Telegram (a reply to it finds the thread). */
tg?: { chatId: number; messageId: number };
/** PEP-159: ids of the files uploaded for this message (core/attachments.ts). */
attachmentIds?: number[];
}
export interface ChatPostResult {
message: ChatMessage;
/** Peppa's reply in the same thread (what happened), if any. */
reply: ChatMessage | null;
}
const MAX_TEXT = MESSAGE_MAX;
export const CHAT_HELP = [
// glossary-ignore: команды чата (/status, /move) — не команды терминала; названия колонок — часть команды
m("Команды:"),
m("/status — активные агенты и открытые вопросы"),
m("/task KEY-N — где задача и чего она ждёт"),
// glossary-ignore: команды чата (/status, /move) — не команды терминала; названия колонок — часть команды
m("/move KEY-N <backlog|in_progress|review|done> — передвинуть задачу (in_progress запускает агента)"),
m("/help — эта справка"),
"",
m("В переписке по задаче обычный текст — ответ агенту: на открытый вопрос, иначе комментарий, который агент увидит сразу."),
].join("\n");
const COLUMNS: Record<string, BoardColumn> = {
backlog: "backlog",
бэклог: "backlog",
in_progress: "in_progress",
work: "in_progress",
работа: "in_progress",
"в работу": "in_progress",
review: "review",
ревью: "review",
done: "done",
готово: "done",
};
const COLUMN_MOVED: Record<BoardColumn, string> = { backlog: m("{key} → Бэклог"), in_progress: m("{key} → В работе (агент взялся)"), review: m("{key} → Ревью"), done: m("{key} → Готово") };
/** Posts a person's message and does what it means. Access: chatForUser (project people / master owner). */
export async function postToChat(db: Db, user: User, p: ChatPost): Promise<ChatPostResult> {
const chat = await chatForUser(db, user, p.chatId);
const ids = parseAttachmentIds(p.attachmentIds ?? []);
const text = p.text.trim() || (await attachmentLabel(db, ids));
if (!text) throw new PeppaError(m("Пустое сообщение"));
if (text.length > MAX_TEXT) throw new PeppaError(m("Текст слишком длинный (больше {n} символов) — приложите его файлом", { n: MAX_TEXT }));
if (p.threadKey && !THREAD_KEY.test(p.threadKey)) throw new PeppaError(m("Неизвестный тред"));
if (chat.kind === "master" && p.threadKey) throw new PeppaError(m("В мастер-чате нет своих тредов — ответь в чате проекта"));
const taskId = p.threadKey?.startsWith("task:") ? Number(p.threadKey.slice(5)) : null;
if (taskId) await assertTaskInChat(db, chat, taskId);
const message = (await addChatMessage(db, {
chatId: chat.id,
threadKey: p.threadKey,
taskId,
kind: "user",
authorKind: "user",
authorUserId: user.id,
authorLogin: user.login,
via: p.via,
text,
tgChatId: p.tg?.chatId ?? null,
tgMessageId: p.tg?.messageId ?? null,
}))!;
if (ids.length && chat.projectId) await linkAttachments(db, user, chat.projectId, ids, { chatMessageId: message.id, taskId });
const say = async (t: string) => {
const r = await addChatMessage(db, { chatId: chat.id, threadKey: p.threadKey, taskId, kind: "system", text: t });
return r;
};
let replyText: string | null;
try {
if (text.startsWith("/")) replyText = await runCommand(db, user, chat, text);
else if (taskId) replyText = await toAgent(db, user, message, taskId, text, p);
// glossary-ignore: команды чата (/status, /move) — не команды терминала; названия колонок — часть команды
else replyText = chat.kind === "master" ? `${m("Здесь работают команды.")}\n${CHAT_HELP}` : null;
} catch (e) {
replyText = `⚠️ ${(e as Error).message}`;
}
const reply = replyText ? await say(replyText) : null;
// PEP-106: a message in the project's discussion reaches its other people (by their preferences).
if (chat.kind === "project" && chat.projectId && !p.threadKey && !text.startsWith("/")) {
await notifyDiscussion(db, user, chat.projectId, message).catch(() => {});
}
await notify(db, { type: "chat_message", messageId: message.id });
return { message, reply };
}
const esc = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
/** Tells the project's other people about a new message in its discussion. */
async function notifyDiscussion(db: Db, author: User, projectId: number, m: ChatMessage): Promise<void> {
const [project] = await db.select({ key: projects.key, name: projects.name }).from(projects).where(eq(projects.id, projectId));
if (!project) return;
const url = `/chats/${project.key}`;
const short = m.text.length > 500 ? `${m.text.slice(0, 500)}…` : m.text;
for (const u of await projectAudience(db, projectId)) {
if (u.id === author.id) continue;
await deliverToUser(db, u, {
event: "chat",
projectId,
dedupeKey: `chat:m${m.id}:${u.telegramChatId}`,
pushKey: `chat:m${m.id}:u${u.id}`,
telegram: { params: { text: `💬 <b>${asIs(esc(project.name))}</b> · ${asIs(esc(author.login))}:\n${asIs(esc(short))}\n\n${tr("Ответить: {url}", { url: `${process.env.PEPPA_WEB_URL ?? ""}${url}` })}`, parse_mode: "HTML", link_preview_options: { is_disabled: true } } },
push: { title: asIs(`${project.name}: ${author.login}`), body: asIs(short.slice(0, 200)), url, tag: `chat:${projectId}` },
});
}
}
async function assertTaskInChat(db: Db, chat: Chat, taskId: number) {
const ref = await resolveTaskById(db, taskId);
if (chat.kind !== "project" || ref.project.id !== chat.projectId) throw new PeppaError(m("Тред не из этого чата"));
return ref;
}
async function resolveTaskById(db: Db, taskId: number) {
const [row] = await db.select({ key: projects.key, number: tasks.number }).from(tasks).innerJoin(projects, eq(tasks.projectId, projects.id)).where(eq(tasks.id, taskId));
if (!row) throw new PeppaError(m("Задача не найдена. Проверьте её номер."));
return resolveTask(db, `${row.key}-${row.number}`);
}
/** Story thread: answer its open question, or comment and type into the live runner. */
async function toAgent(db: Db, user: User, message: ChatMessage, taskId: number, text: string, p: ChatPost): Promise<string> {
let q = p.questionId ? (await db.select().from(questions).where(and(eq(questions.id, p.questionId), eq(questions.taskId, taskId))))[0] : undefined;
if (q?.answeredAt) return q.answeredVia && q.answeredVia !== "system" ? m("Этот вопрос уже закрыт ({via}): {answer}", { via: q.answeredVia, answer: q.answer ?? "" }) : m("Этот вопрос уже закрыт: {answer}", { answer: q.answer ?? "" });
// The latest open real question first; «ждёт тебя» (attention) only when nothing else is open.
q ??=
(await db.select().from(questions).where(and(eq(questions.taskId, taskId), isNull(questions.answeredAt), ne(questions.kind, "attention"))).orderBy(desc(questions.id)).limit(1))[0] ??
(await db.select().from(questions).where(and(eq(questions.taskId, taskId), isNull(questions.answeredAt))).orderBy(desc(questions.id)).limit(1))[0];
if (q) {
const { delivered } = await answerAndDeliver(db, q.id, text, p.via);
return delivered ? m("Ответ ушёл агенту ✅") : m("Ответ сохранён. Агент сейчас не работает — он увидит ответ, когда вернётся к задаче.");
}
const ref = await resolveTaskById(db, taskId);
// The comment event carries this message's id: the projection doesn't repeat it in the thread.
const c = await addStoryComment(db, ref, user, text, { chatMessageId: message.id });
// PEP-159: the files of the message belong to the comment too (the story page shows them there).
await db.update(attachments).set({ eventId: c.id }).where(eq(attachments.chatMessageId, message.id));
const [live] = await listSessions(db, { active: true, taskId });
if (!live) return (await refinePending(db, ref.task)) ? m("Комментарий сохранён — агент ещё не начал, аналитик уточнит постановку и ответит в обсуждении задачи.") : m("Комментарий сохранён — агент увидит его, когда возьмётся за задачу.");
await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}${await syncSessionAttachments(db, live.id)}`, { person: true });
return m("Комментарий ушёл агенту ✅");
}
/** /status, /task, /move, /help — no LLM (PM's decision). */
export async function runCommand(db: Db, user: User, chat: Chat, text: string): Promise<string> {
const [cmd0, ...args] = text.trim().split(/\s+/);
const cmd = cmd0!.toLowerCase().replace(/@\w+$/, "");
if (cmd === "/help" || cmd === "/start") return CHAT_HELP;
if (cmd === "/status") return status(db, user, chat);
if (cmd === "/task" || cmd === "/move") {
if (!args[0]) throw new PeppaError(m("Укажите задачу: {usage}", { usage: `${cmd} KEY-N${cmd === "/move" ? " in_progress" : ""}` }));
const defaultKey = chat.kind === "project" ? await projectKey(db, chat.projectId!) : undefined;
const ref = await resolveTask(db, args[0], defaultKey);
await projectForUser(db, user.id, ref.project.id).catch(() => {
throw new PeppaError(m("Задача {key} не найдена. Проверьте её номер.", { key: args[0] }));
});
if (cmd === "/task") {
const open = (await pendingQuestions(db)).filter((q) => q.taskId === ref.task.id);
const [live] = await listSessions(db, { active: true, taskId: ref.task.id });
return [`${ref.key}: ${asIs(ref.task.title)}`, m("Статус: {status}", { status: statusRu(ref.task.status) }), live ? m("Агент: {status}", { status: live.status }) : m("Агент не запущен"), open.length ? m("Ждёт ответа: {n}", { n: open.length }) : m("Открытых вопросов нет")].join("\n");
}
const col = COLUMNS[args.slice(1).join(" ").toLowerCase()];
// glossary-ignore: команды чата (/status, /move) — не команды терминала; названия колонок — часть команды
if (!col) throw new PeppaError(m("Колонка: backlog, in_progress, review или done"));
await moveTask(db, ref, col);
return m(COLUMN_MOVED[col], { key: ref.key });
}
// glossary-ignore: команды чата (/status, /move) — не команды терминала; названия колонок — часть команды
throw new PeppaError(`${m("Не знаю такую команду: {cmd}", { cmd })}\n${CHAT_HELP}`);
}
async function projectKey(db: Db, projectId: number) {
const [p] = await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId));
return p?.key;
}
async function status(db: Db, user: User, chat: Chat): Promise<string> {
const ids = new Set(chat.kind === "project" ? [chat.projectId!] : await userProjectIds(db, user.id));
const sessions = (await listSessions(db, { active: true })).filter((s) => ids.has(s.projectId));
const open = (await pendingQuestions(db)).filter((q) => ids.has(q.projectId));
const lines = [m("Активные агенты: {n}", { n: sessions.length })];
for (const s of sessions.slice(0, 20)) lines.push(`• ${s.taskKey ?? s.name ?? `#${s.id}`} — ${s.status}`);
lines.push(m("Открытых вопросов: {n}", { n: open.length }));
return lines.join("\n");
}