213 lines
11 KiB
TypeScript
213 lines
11 KiB
TypeScript
// 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 {
|
||
addChatMessage,
|
||
addStoryComment,
|
||
refinePending,
|
||
chatForUser,
|
||
deliverToUser,
|
||
projectAudience,
|
||
listSessions,
|
||
notify,
|
||
pendingQuestions,
|
||
projectForUser,
|
||
resolveTask,
|
||
statusRu,
|
||
THREAD_KEY,
|
||
userProjectIds,
|
||
type Chat,
|
||
type ChatMessage,
|
||
type User,
|
||
PeppaError,
|
||
} from "@peppa/core";
|
||
import { 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 } 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 };
|
||
}
|
||
|
||
export interface ChatPostResult {
|
||
message: ChatMessage;
|
||
/** Peppa's reply in the same thread (what happened), if any. */
|
||
reply: ChatMessage | null;
|
||
}
|
||
|
||
const MAX_TEXT = 8000;
|
||
|
||
export const CHAT_HELP = [
|
||
"Команды:",
|
||
"/status — активные агенты и открытые вопросы",
|
||
"/task KEY-N — где стори и что она ждёт",
|
||
"/move KEY-N <backlog|in_progress|review|done> — передвинуть стори (in_progress запускает агента)",
|
||
"/help — эта справка",
|
||
"",
|
||
"В треде стори обычный текст — ответ агенту: на открытый вопрос, иначе комментарий, который агент увидит сразу.",
|
||
].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_RU: Record<BoardColumn, string> = { backlog: "Бэклог", in_progress: "В работе", review: "Ревью", done: "Готово" };
|
||
|
||
/** 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 text = p.text.trim();
|
||
if (!text) throw new PeppaError("Пустое сообщение");
|
||
if (text.length > MAX_TEXT) throw new PeppaError(`Сообщение длиннее ${MAX_TEXT} символов`);
|
||
if (p.threadKey && !THREAD_KEY.test(p.threadKey)) throw new PeppaError("Неизвестный тред");
|
||
if (chat.kind === "master" && p.threadKey) throw new PeppaError("В мастер-чате нет своих тредов — ответь в чате проекта");
|
||
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,
|
||
}))!;
|
||
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);
|
||
else replyText = chat.kind === "master" ? `Здесь работают команды.\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, "&").replace(/</g, "<").replace(/>/g, ">");
|
||
|
||
/** 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>${esc(project.name)}</b> · ${esc(author.login)}:\n${esc(short)}\n\nОтветить: ${process.env.PEPPA_WEB_URL ?? ""}${url}`, parse_mode: "HTML", link_preview_options: { is_disabled: true } } },
|
||
push: { title: `${project.name}: ${author.login}`, body: 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("Тред не из этого чата");
|
||
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("Стори не найдена");
|
||
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" ? ` (${q.answeredVia})` : ""}: ${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 ? "Ответ ушёл агенту ✅" : "Ответ сохранён; сессия не запущена — агент увидит его в истории стори.";
|
||
}
|
||
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 });
|
||
const [live] = await listSessions(db, { active: true, taskId });
|
||
if (!live) return (await refinePending(db, ref.task)) ? "Комментарий сохранён — агент ещё не начал, аналитик уточнит постановку и ответит в обсуждении стори." : "Комментарий сохранён — агент увидит его, когда возьмётся за стори.";
|
||
await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}`);
|
||
return "Комментарий ушёл агенту ✅";
|
||
}
|
||
|
||
/** /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(`Укажи стори: ${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(`Стори ${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}: ${ref.task.title}`, `Статус: ${statusRu(ref.task.status)}`, live ? `Агент: ${live.status}` : "Агент не запущен", open.length ? `Ждёт ответа: ${open.length}` : "Открытых вопросов нет"].join("\n");
|
||
}
|
||
const col = COLUMNS[args.slice(1).join(" ").toLowerCase()];
|
||
if (!col) throw new PeppaError("Колонка: backlog, in_progress, review или done");
|
||
await moveTask(db, ref, col);
|
||
return `${ref.key} → ${COLUMN_RU[col]}${col === "in_progress" ? " (агент взялся)" : ""}`;
|
||
}
|
||
throw new PeppaError(`Не знаю такую команду: ${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 = [`Активные агенты: ${sessions.length}`];
|
||
for (const s of sessions.slice(0, 20)) lines.push(`• ${s.taskKey ?? s.name ?? `#${s.id}`} — ${s.status}`);
|
||
lines.push(`Открытых вопросов: ${open.length}`);
|
||
return lines.join("\n");
|
||
}
|