// PEP-62: chats — a channel per project with threads (story / incident / release) and a master // chat per user. Messages are a short-lived projection (PEPPA_CHAT_TTL_DAYS) of events, // questions, releases and incidents, which stay in their own tables; people's messages are // stored here too. Telegram groups linked to chats are the bot's business (apps/bot). import { asIs, hasAsIs, m as tr, PRODUCT_NAME } from "@peppa/shared/i18n"; import { createHmac, randomBytes } from "node:crypto"; import { chatMessages, chats, events, incidents, projects, questions, releases, tasks, telegramOutbox, users, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, lt, lte, or, sql, type SQL } from "drizzle-orm"; import { PeppaError } from "./errors.ts"; import { getNotifyPrefs, projectAudience } from "./notifications.ts"; import { notify } from "./notify.ts"; import { IS_QUESTION } from "./questions.ts"; import { messageDetails } from "./message-details.ts"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; import { questionIsFreeText } from "./tasks.ts"; import { projectForUser, userProjectIds, type User } from "./users.ts"; import type { OutboxRow } from "./telegram.ts"; import { chatOffers, type ChatOffer } from "./message-intent.ts"; import { ACCEPTANCE_AGENT_NAME } from "./intake.ts"; import { ANALYST_NAME, questionAuthor, sessionAgentName, taskLiveAgent, taskLiveAgentName } from "./authors.ts"; import { pruneQuestionDetails, userText } from "./user-text.ts"; import { chatRepeatKey, chatRepeats, normalizeMessage, pruneMessageStates, questionStates, type ChatRepeat } from "./message-state.ts"; import { duringPause } from "./project-pause.ts"; export type Chat = typeof chats.$inferSelect; export type ChatMessage = typeof chatMessages.$inferSelect; export type NewChatMessage = typeof chatMessages.$inferInsert; const DAY = 24 * 3600_000; export const chatTtlMs = () => Math.max(1, Number(process.env.PEPPA_CHAT_TTL_DAYS ?? 14) || 14) * DAY; // ── chats ────────────────────────────────────────────────────────────────────────── export async function ensureProjectChat(db: Db, projectId: number): Promise { await db.insert(chats).values({ kind: "project", projectId }).onConflictDoNothing(); const [c] = await db.select().from(chats).where(eq(chats.projectId, projectId)); return c!; } export async function ensureMasterChat(db: Db, userId: number): Promise { await db.insert(chats).values({ kind: "master", userId }).onConflictDoNothing(); const [c] = await db.select().from(chats).where(eq(chats.userId, userId)); return c!; } export async function getChat(db: Db, id: number): Promise { const [c] = await db.select().from(chats).where(eq(chats.id, id)); if (!c) throw new PeppaError(tr("Чат не найден")); return c; } /** The chat if this user may read and write it: project chat — owner/members, master — its owner. */ export async function chatForUser(db: Db, user: Pick, chatId: number): Promise { const c = await getChat(db, chatId); if (c.kind === "master") { if (c.userId !== user.id) throw new PeppaError(tr("Чат не найден")); } else await projectForUser(db, user.id, c.projectId!).catch(() => { throw new PeppaError(tr("Чат не найден")); }); return c; } export async function chatByTelegram(db: Db, tgChatId: number): Promise { const [c] = await db.select().from(chats).where(eq(chats.tgChatId, tgChatId)); return c ?? null; } export interface ChatListItem { id: number; kind: Chat["kind"]; /** "master" or the project key — the URL segment of /chats/. */ slug: string; title: string; projectId: number | null; tgTitle: string | null; lastAt: Date | null; /** Open agent questions of the project (the master chat: all of the user's). */ open: number; } /** The master chat and the chats of the user's projects (created on first look). */ export async function listChats(db: Db, user: Pick): Promise { const master = await ensureMasterChat(db, user.id); const ids = await userProjectIds(db, user.id); const ps = ids.length ? await db.select().from(projects).where(inArray(projects.id, ids)).orderBy(asc(projects.key)) : []; const projectChats = new Map(); for (const p of ps) projectChats.set(p.id, await ensureProjectChat(db, p.id)); const chatIds = [master.id, ...[...projectChats.values()].map((c) => c.id)]; const last = new Map( (await db.select({ chatId: chatMessages.chatId, at: sql`max(${chatMessages.createdAt})` }).from(chatMessages).where(inArray(chatMessages.chatId, chatIds)).groupBy(chatMessages.chatId)).map((r) => [r.chatId, r.at ? new Date(Number(r.at)) : null]), ); const open = new Map( ids.length ? (await db.select({ p: questions.projectId, n: sql`count(*)` }).from(questions).where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt), IS_QUESTION)).groupBy(questions.projectId)).map((r) => [r.p, Number(r.n)]) : [], ); const masterAt = [...last.values()].reduce((a, b) => (b && (!a || b > a) ? b : a), null); return [ { id: master.id, kind: "master", slug: "master", title: tr("Мастер-чат"), projectId: null, tgTitle: master.tgTitle, lastAt: masterAt, open: [...open.values()].reduce((a, b) => a + b, 0) }, ...ps.map((p) => { const c = projectChats.get(p.id)!; return { id: c.id, kind: "project" as const, slug: p.key, title: `${p.key} · ${p.name}`, projectId: p.id, tgTitle: c.tgTitle, lastAt: last.get(c.id) ?? null, open: open.get(p.id) ?? 0 }; }), ]; } // ── messages ─────────────────────────────────────────────────────────────────────── /** Adds a message; with a `dedupeKey` seen before it is a no-op and returns null. */ export async function addChatMessage(db: Db, m: NewChatMessage): Promise { // PEP-154: what an agent or Peppa says goes through the service-text filter; nothing left — no message. // A question's text was filtered when it was asked (a permission request keeps its command). if (m.authorKind !== "user" && !m.questionId) { const text = userText(m.text); if (!text) return null; m = { ...m, text }; } if (m.threadKey && m.threadTitle == null) { const [prev] = await db .select({ t: chatMessages.threadTitle }) .from(chatMessages) .where(and(eq(chatMessages.chatId, m.chatId), eq(chatMessages.threadKey, m.threadKey), isNotNull(chatMessages.threadTitle))) .orderBy(desc(chatMessages.id)) .limit(1); m = { ...m, threadTitle: prev?.t ?? (await threadTitle(db, m.threadKey)) }; } const [row] = await db.insert(chatMessages).values(m).onConflictDoNothing().returning(); return row ?? null; } /** A message in the user's master chat (monitoring, digest, command replies). */ export async function addMasterMessage(db: Db, userId: number, m: Omit): Promise { const chat = await ensureMasterChat(db, userId); const row = await addChatMessage(db, { ...m, chatId: chat.id }); if (row) await notify(db, { type: "chat_message", messageId: row.id }); return row; } /** Current title of a thread: "PAY-7 · Экспорт", "Ошибка: …", "Версия для проверки · 15.11, 16:20". */ export async function threadTitle(db: Db, key: string): Promise { const [kind, raw] = key.split(":"); const id = Number(raw); if (kind === "task") { const [t] = await db.select({ key: projects.key, n: tasks.number, title: tasks.title }).from(tasks).innerJoin(projects, eq(tasks.projectId, projects.id)).where(eq(tasks.id, id)); return t ? `${formatTaskKey(t.key, t.n)} · ${asIs(t.title)}` : null; } if (kind === "incident") { const [i] = await db.select({ title: incidents.title }).from(incidents).where(eq(incidents.id, id)); return i ? tr("Ошибка: {title}", { title: asIs(i.title) }) : null; } if (kind === "release") { const [r] = await db.select({ env: releases.env, createdAt: releases.createdAt }).from(releases).where(eq(releases.id, id)); // PEP-123: in the words of a product manager — which version and when, not the environment and the commit. return r ? `${ENV_RU[r.env] ?? r.env} · ${r.createdAt.toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })}` : null; } return null; } export const THREAD_KEY = /^(task|incident|release):[1-9]\d{0,9}$/; export interface ChatMessageView { id: number; chatId: number; /** Project of the chat the message lives in (master feed mixes projects). */ projectKey: string | null; threadKey: string | null; threadTitle: string | null; kind: ChatMessage["kind"]; important: boolean; authorKind: ChatMessage["authorKind"]; authorUserId: number | null; authorLogin: string | null; via: ChatMessage["via"]; text: string; url: string | null; createdAt: Date; /** PEP-151: how many more times the same thing came (a repeated state, the same event in a row). */ repeats: number; /** When it last came again or was reminded about; null — never. */ updatedAt: Date | null; /** PEP-152: technical details of the message — the screens show them under «Подробнее» only. */ details: string | null; /** PEP-153: what the message offers to do next (buttons under it); null — nothing. */ offer: ChatOffer | null; /** A question message: its live state (answered elsewhere shows here too). */ question: { id: number; kind: string; options: string[] | null; answer: string | null; answeredVia: string | null; answeredAt: Date | null } | null; } async function views(db: Db, where: SQL, limit: number, before?: number): Promise { const rows = await db .select({ m: chatMessages, projectKey: projects.key, q: questions }) .from(chatMessages) .innerJoin(chats, eq(chatMessages.chatId, chats.id)) .leftJoin(projects, eq(chats.projectId, projects.id)) .leftJoin(questions, eq(chatMessages.questionId, questions.id)) .where(before ? and(where, lt(chatMessages.id, before)) : where) .orderBy(desc(chatMessages.id)) .limit(Math.min(limit, 500)); const qStates = await questionStates(db, rows.map((r) => r.q?.id).filter((x): x is number => x != null)); const eRepeats = await chatRepeats(db, rows.filter((r) => r.m.kind === "event").map((r) => r.m.id)); // PEP-152: details of a message — of its question (settings) or of its event (payload). const qDetails = await messageDetails(db, rows.map((r) => r.q?.id).filter((x): x is number => x != null)); const eventOf = (m: ChatMessage) => (m.kind === "event" ? Number(/^event:(\d+)$/.exec(m.dedupeKey ?? "")?.[1]) || null : null); const eventIds = rows.map((r) => eventOf(r.m)).filter((x): x is number => x != null); const eDetails = new Map( (eventIds.length ? await db.select({ id: events.id, payload: events.payload }).from(events).where(and(inArray(events.id, eventIds), inArray(events.type, ["progress", "blocker"]))) : []).map((e) => { const p = (e.payload ?? {}) as P; return [e.id, [s(p.tried) ? tr("Что уже пробовал: {tried}", { tried: asIs(s(p.tried)) }) : "", asIs(s(p.details))].filter(Boolean).join("\n\n") || null] as const; }), ); const offers = await chatOffers(db, rows.filter((r) => r.m.kind === "user" && r.m.authorKind !== "user").map((r) => r.m.id)); const again = (m: ChatMessage, q: { id: number } | null) => { const st = q ? qStates.get(q.id) : undefined; if (st) return { repeats: st.repeats, updatedAt: st.updatedAt ? new Date(st.updatedAt) : null }; const r = eRepeats.get(m.id); return r ? { repeats: r.n - 1, updatedAt: new Date(r.at) } : { repeats: 0, updatedAt: null }; }; return rows.reverse().map(({ m, projectKey, q }) => ({ ...again(m, q), id: m.id, chatId: m.chatId, projectKey, threadKey: m.threadKey, threadTitle: m.threadTitle, kind: m.kind, important: m.important, authorKind: m.authorKind, authorUserId: m.authorUserId, authorLogin: m.authorLogin, via: m.via, text: m.text, url: m.url, createdAt: m.createdAt, details: (q ? qDetails.get(q.id) : eDetails.get(eventOf(m) ?? 0)) ?? null, offer: offers.get(m.id) ?? null, question: q ? { id: q.id, kind: q.kind, options: q.options ?? null, answer: q.answer, answeredVia: q.answeredVia, answeredAt: q.answeredAt } : null, })); } /** Messages of a chat: the whole stream, or one thread (`threadKey`), or the channel only (null). */ export async function chatMessagesView(db: Db, chatId: number, o: { threadKey?: string | null; limit?: number; before?: number } = {}): Promise { const w: SQL[] = [eq(chatMessages.chatId, chatId)]; if (o.threadKey === null) w.push(isNull(chatMessages.threadKey)); else if (o.threadKey) w.push(eq(chatMessages.threadKey, o.threadKey)); return views(db, and(...w)!, o.limit ?? 100, o.before); } /** PEP-228: messages of a chat newer than `after`, oldest first; `more` — there were more than `limit` (the page re-renders). */ export async function newChatMessagesView(db: Db, chatId: number, after: number, limit = 30): Promise<{ messages: ChatMessageView[]; more: boolean }> { const rows = await views(db, and(eq(chatMessages.chatId, chatId), gt(chatMessages.id, after))!, limit + 1); return rows.length > limit ? { messages: [], more: true } : { messages: rows, more: false }; } // ── discussion (PEP-106) ──────────────────────────────────────────────────── /** People's messages in a project chat's channel: no agents, no events, no commands. */ const DISCUSSION = and(isNull(chatMessages.threadKey), eq(chatMessages.kind, "user"), sql`${chatMessages.text} NOT LIKE '/%'`)!; /** PEP-106: the project's discussion — a plain chat of its people, oldest first. */ export async function discussionMessages(db: Db, chatId: number, o: { limit?: number } = {}): Promise { return views(db, and(eq(chatMessages.chatId, chatId), DISCUSSION)!, o.limit ?? 200); } const readKey = (userId: number, chatId: number) => `chat.read:${userId}:${chatId}`; /** The user has seen the discussion up to its last message. */ export async function markDiscussionRead(db: Db, userId: number, chatId: number): Promise { const [last] = await db.select({ id: sql`max(${chatMessages.id})` }).from(chatMessages).where(and(eq(chatMessages.chatId, chatId), DISCUSSION)); const id = Number(last?.id ?? 0); if (id > ((await getSetting(db, readKey(userId, chatId))) ?? 0)) await setSetting(db, readKey(userId, chatId), id); } /** Messages of other people the user has not seen yet, per project chat (chatId → count). */ export async function discussionUnread(db: Db, userId: number): Promise> { const ids = await userProjectIds(db, userId); const out = new Map(); if (!ids.length) return out; const cs = await db.select({ id: chats.id }).from(chats).where(inArray(chats.projectId, ids)); for (const c of cs) { const seen = (await getSetting(db, readKey(userId, c.id))) ?? 0; const [r] = await db .select({ n: sql`count(*)` }) .from(chatMessages) .where(and(eq(chatMessages.chatId, c.id), DISCUSSION, gt(chatMessages.id, seen), or(isNull(chatMessages.authorUserId), sql`${chatMessages.authorUserId} <> ${userId}`))); if (Number(r?.n)) out.set(c.id, Number(r!.n)); } return out; } export interface ProjectChatCard { chatId: number; key: string; name: string; /** Messages of other people and the analyst the user has not read. */ unread: number; /** Agent questions of the project waiting for a person. */ open: number; /** The last message of the chat with the analyst. */ last: { who: string; mine: boolean; text: string; at: Date; /** Written by the factory itself (translatable text). */ system: boolean; /** PEP-156: said by an AI agent or role (`who` — its nickname or role name). */ agent: boolean } | null; } /** PEP-117: the user's project chats at a glance — what is new and what was said last. */ export async function chatOverview(db: Db, user: Pick): Promise { const list = (await listChats(db, user)).filter((c) => c.kind === "project"); const unread = await discussionUnread(db, user.id); const out: ProjectChatCard[] = []; for (const c of list) { const [m] = await db.select().from(chatMessages).where(and(eq(chatMessages.chatId, c.id), DISCUSSION)).orderBy(desc(chatMessages.id)).limit(1); out.push({ chatId: c.id, key: c.slug, name: c.title.includes(" · ") ? c.title.split(" · ").slice(1).join(" · ") : c.title, unread: unread.get(c.id) ?? 0, open: c.open, last: m ? { who: m.authorKind === "agent" ? (m.authorLogin ?? ANALYST_NAME) : (m.authorLogin ?? PRODUCT_NAME), mine: m.authorUserId === user.id, text: m.text, at: m.createdAt, system: m.authorKind === "system", agent: m.authorKind === "agent" } : null, }); } // What needs the person first: open questions, then unread, then the most recent talk. return out.sort((a, b) => b.open - a.open || b.unread - a.unread || (b.last?.at.getTime() ?? 0) - (a.last?.at.getTime() ?? 0)); } /** Where to write to the analyst of a project, and how much there is unread (PEP-161). */ export interface AnalystLink { href: string; unread: number; } /** * «Написать аналитику» on the project cards of «Проекты» (PEP-161): projectId → link, only for * the projects the user owns or is a member of — a superadmin gets none for other people's. */ export async function analystLinks(db: Db, user: Pick): Promise> { const unread = await discussionUnread(db, user.id); const out = new Map(); for (const c of await listChats(db, user)) if (c.kind === "project" && c.projectId != null) out.set(c.projectId, { href: `/chats/${c.slug}`, unread: unread.get(c.id) ?? 0 }); return out; } /** * The master feed: the user's own master messages and the important messages of the chats * of their projects (muted projects left out). `threadKey` narrows it to one project thread. */ export async function masterFeed(db: Db, user: Pick, o: { limit?: number; threadKey?: string; before?: number } = {}): Promise { const master = await ensureMasterChat(db, user.id); const muted = new Set((await getNotifyPrefs(db, user.id)).mutedProjects); const ids = (await userProjectIds(db, user.id)).filter((id) => !muted.has(id)); const projectChats = ids.length ? (await db.select({ id: chats.id }).from(chats).where(inArray(chats.projectId, ids))).map((c) => c.id) : []; const fromProjects = projectChats.length ? and(inArray(chatMessages.chatId, projectChats), eq(chatMessages.important, true)) : undefined; let where: SQL = fromProjects ? or(eq(chatMessages.chatId, master.id), fromProjects)! : eq(chatMessages.chatId, master.id); if (o.threadKey) where = and(where, eq(chatMessages.threadKey, o.threadKey))!; return views(db, where, o.limit ?? 100, o.before); } export interface ThreadView { key: string; title: string; count: number; lastAt: Date; /** Unanswered questions in the thread. */ open: number; } /** Threads of a project chat, most recently active first. */ export async function chatThreads(db: Db, chatId: number, limit = 50): Promise { const rows = await db .select({ key: chatMessages.threadKey, title: sql`max(${chatMessages.threadTitle})`, count: sql`count(*)`, lastId: sql`max(${chatMessages.id})`, lastAt: sql`max(${chatMessages.createdAt})`, open: sql`sum(CASE WHEN ${questions.id} IS NOT NULL AND ${questions.answeredAt} IS NULL AND ${IS_QUESTION} THEN 1 ELSE 0 END)`, }) .from(chatMessages) .leftJoin(questions, eq(chatMessages.questionId, questions.id)) .where(and(eq(chatMessages.chatId, chatId), isNotNull(chatMessages.threadKey))) .groupBy(chatMessages.threadKey) .orderBy(desc(sql`max(${chatMessages.id})`)) .limit(limit); return rows.map((r) => ({ key: r.key!, title: r.title ?? r.key!, count: Number(r.count), lastAt: new Date(Number(r.lastAt)), open: Number(r.open) || 0 })); } // ── projection ───────────────────────────────────────────────────────────────────── const CURSOR_EVENTS = "chat.cursor.events"; const CURSOR_QUESTIONS = "chat.cursor.questions"; const CURSOR_OBJECTS = "chat.cursor.objects"; const BATCH = 500; const STATUS_RU: Record = { backlog: tr("бэклог"), proposing: tr("составляет план"), awaiting_approval: tr("ждёт одобрения"), in_progress: tr("в работе"), review: tr("ревью"), done: tr("готово"), blocked: tr("заблокирована"), }; export const statusRu = (s: string) => STATUS_RU[s] ?? s; type P = Record; const s = (v: unknown) => (v == null ? "" : String(v)); const cut = (t: string, n = 600) => (t.length > n ? `${t.slice(0, n - 1)}…` : t); const TOOK_TEXT = tr("▶️ Агент взял задачу в работу"); const tookKey = (taskId: number) => `chat.took:${taskId}`; /** * PEP-156: «Агент Шустрик взял задачу в работу». The status changes before the agent starts, so * unless the agent was already at work by then the line is put off (`chat.took:`) and * said by the agent's `started` event — once, whenever the chats are synced. Returns the text to say, "" — the event's own text, null — say nothing now. */ async function tookLine(db: Db, type: string, taskId: number, sessionId: number | null, eventId: number, took: boolean): Promise { if (type === "task_updated") { if (!took) return ""; const live = await taskLiveAgent(db, taskId); const [ran] = live ? await db.select({ id: events.id }).from(events).where(and(eq(events.sessionId, live.sessionId), inArray(events.type, ["started", "resumed"]), lt(events.id, eventId))).limit(1) : []; if (live && ran) return tr("▶️ Агент {name} взял задачу в работу", { name: live.name }); await setSetting(db, tookKey(taskId), eventId); return null; } const name = await sessionAgentName(db, sessionId); if (!name) return ""; if ((await getSetting(db, tookKey(taskId))) == null) return tr("▶️ Агент {name} начал работу", { name }); await deleteSetting(db, tookKey(taskId)); return tr("▶️ Агент {name} взял задачу в работу", { name }); } /** Event types that become chat messages: text, and whether the master chat shows it. */ const EVENT_TEXT: Record { text: string; important?: boolean; author?: "agent"; /** The AI role that says it (else — the agent of the runner). */ role?: string } | null> = { task_updated: (p) => { const from = (p.from as P | undefined)?.status; const to = (p.to as P | undefined)?.status; if (!to || from === to) return null; // PEP-117: what happened to the story, in words — not «статус X → Y». const said: Record = { proposing: tr("📝 Агент составляет план задачи"), awaiting_approval: tr("⏸ План готов и ждёт вашего одобрения"), in_progress: from === "review" ? tr("🔧 Задача вернулась агенту на доработку") : TOOK_TEXT, review: tr("👀 Задача готова — посмотрите результат и примите"), // PEP-278: accepted, but the version with the changes is not running yet. done: p.rollout ? tr("✅ Задача принята — изменения заработают после обновления версии") : tr("✅ Задача принята и закрыта"), blocked: tr("⛔ Задача заблокирована — агент не может продолжать"), backlog: tr("↩️ Задача вернулась в бэклог"), }; return { text: said[String(to)] ?? tr("• Статус: {to}", { to: statusRu(String(to)) }), important: ["review", "done", "blocked", "awaiting_approval"].includes(String(to)) }; }, // PEP-139: the agent's and the roles' own words are marked free text — never translated. // PEP-152: a note in the format carries its own marks — the lines of the factory in it are translated. progress: (p) => ({ text: `📈 ${hasAsIs(s(p.text)) ? cut(s(p.text), 1500) : asIs(cut(s(p.text), 1500))}`, author: "agent" }), // PEP-149: the agent cannot go on (not a product decision) — a record, not a question. // PEP-152: «что уже пробовал» and the details are technical — the view shows them under «Подробнее». blocker: (p) => ({ text: `⛔ ${tr("Агент не может продолжить: {what}", { what: p.neutral ? s(p.what) : asIs(cut(s(p.what), 1000)) })}`, author: "agent" }), pm_comment: () => null, // handled separately: a person's message // PEP-4: the project's repo moved to another Gitea namespace. repo_transferred: (p) => ({ text: tr("📦 Код проекта переехал: {from} → {to}", { from: s(p.from), to: s(p.to) }) }), // PEP-84 / PEP-198: the analyst talks to the PM in the story's thread (the acceptance agent's remark — by its name). // PEP-156: the role is the author of the line, not a prefix of its text (free text, PEP-139). intake_note: (p) => ({ text: asIs(cut(s(p.text), 3000)), important: true, author: "agent", role: p.role === "acceptance" ? ACCEPTANCE_AGENT_NAME : ANALYST_NAME }), // PEP-278: the version with the story's changes runs — the story is done for real. task_rolled_out: () => ({ text: tr("🚀 Изменения задачи уже работают — задача готова"), important: true }), pr_merged_in_gitea: (p) => ({ text: p.by ? tr("🔀 Изменения задачи приняты в код проекта ({by})", { by: s(p.by) }) : tr("🔀 Изменения задачи приняты в код проекта") }), // PEP-174: the project's pause — one line each; what happened inside it is not sent later. project_paused: () => ({ text: tr("⏸ Проект поставлен на паузу: агенты остановлены, уведомлений нет"), important: true }), project_resumed: (p) => ({ text: tr("▶️ Пауза: с {from} по {to}. Агенты продолжают работу", { from: s(p.fromText), to: s(p.toText) }), important: true }), started: () => ({ text: tr("▶️ Агент начал работу") }), resumed: () => ({ text: tr("🔁 Агент продолжает работу") }), stopped: () => ({ text: tr("⏹ Агент остановлен") }), // Hiccups Peppa handles by itself are told calmly and are not «важное» for a product manager. stalled: (p) => ({ text: p.idleMinutes ? tr("⚠️ Агент давно молчит ({n} мин) — FORGE перезапустит его сама", { n: s(p.idleMinutes) }) : tr("⚠️ Агент давно молчит — FORGE перезапустит его сама") }), stop_failure: (p) => ({ text: tr("⚠️ Агент споткнулся ({error}) — FORGE продолжит сама", { error: s(p.error) || tr("ошибка") }) }), exited: () => ({ text: tr("⚠️ Агент остановился раньше времени — FORGE перезапустит его сама") }), usage_limit: () => ({ text: tr("⏳ Подписка упёрлась в лимит — агент продолжит после сброса или на другой подписке"), important: true }), auto_restarted: (p) => ({ text: p.attempt ? tr("🔁 Агент перезапущен после сбоя (попытка {attempt} из {of})", { attempt: s(p.attempt), of: s(p.of) }) : tr("🔁 Агент перезапущен после сбоя") }), restart_failed: () => ({ text: tr("❌ Агента не удалось перезапустить — нужна ваша помощь: откройте задачу"), important: true }), budget_paused: () => ({ text: tr("💸 Бюджет задачи исчерпан — агент на паузе, нужен ваш ответ"), important: true }), subscription_switched: (p) => ({ text: p.to ? tr("🔀 Агент перешёл на другую подписку ({to}) и продолжает", { to: s(p.to) }) : tr("🔀 Агент перешёл на другую подписку и продолжает") }), model_escalated: () => ({ text: tr("⬆️ Задача оказалась сложнее — агент перешёл на усиленный режим") }), }; const RELEASE_ICON: Record = { deploying: "⏳", healthy: "🚀", rolled_back: "↩️", failed: "❌", removed: "🧹" }; // " : [ · задачи: ]" — each piece is a dictionary entry, so the line translates. const RELEASE_RU: Record = { deploying: tr("обновляется"), healthy: tr("работает"), rolled_back: tr("не прошла проверку — возвращена прежняя"), failed: tr("не обновилась"), removed: tr("убрана"), }; // PEP-111: what a release is, in words for a product manager. const ENV_RU: Record = { preview: tr("Версия для проверки задачи"), staging: tr("Версия для проверки"), prod: tr("Рабочая версия продукта") }; const INCIDENT_RU: Record = { new: tr("новая"), open: tr("открыта"), pending: tr("ждёт решения"), task: tr("заведена задача"), ignored: tr("игнорируем"), resolved: tr("исправлена"), regressed: tr("вернулась"), }; /** "🐞 : [\n<culprit>][ · <env>][ · N раз]". */ function incidentText(i: { status: string; title: string; culprit: string | null; environment: string | null; events: number }): string { const base = `${tr("🐞 {status}: {title}", { status: INCIDENT_RU[i.status] ?? i.status, title: asIs(cut(i.title, 300)) })}${i.culprit ? `\n${asIs(cut(i.culprit, 200))}` : ""}${i.environment ? ` · ${i.environment}` : ""}`; return i.events > 1 ? tr("{text} · {n} раз", { text: base, n: i.events }) : base; } /** First id of rows newer than a day (a fresh install doesn't import the whole history). */ async function initialCursor(db: Db, table: typeof events | typeof questions, now: Date): Promise<number> { const since = new Date(now.getTime() - DAY); const [r] = await db.select({ min: sql<number | null>`min(${table.id})`, max: sql<number | null>`max(${table.id})` }).from(table).where(gt(table.createdAt, since)); if (r?.min != null) return Number(r.min) - 1; const [all] = await db.select({ max: sql<number | null>`max(${table.id})` }).from(table); return Number(all?.max ?? 0); } /** * PEP-151: is this event the same as the last line of its story thread? Then it is counted on * that line (settings `chat.repeat:<messageId>`) and not added — neither here nor in the linked * Telegram group. */ async function repeatsLastEvent(db: Db, m: NewChatMessage): Promise<boolean> { const eventId = Number(/^event:(\d+)$/.exec(m.dedupeKey ?? "")?.[1]); if (m.kind !== "event" || !m.threadKey?.startsWith("task:") || !eventId) return false; const [last] = await db.select().from(chatMessages).where(and(eq(chatMessages.chatId, m.chatId), eq(chatMessages.threadKey, m.threadKey))).orderBy(desc(chatMessages.id)).limit(1); if (!last || last.kind !== "event" || last.dedupeKey === m.dedupeKey || (last.authorKind ?? "system") !== (m.authorKind ?? "system")) return false; if (normalizeMessage(last.text) !== normalizeMessage(m.text)) return false; const st = await getSetting<ChatRepeat>(db, chatRepeatKey(last.id)); if (st && eventId <= st.last) return true; await setSetting(db, chatRepeatKey(last.id), { n: (st?.n ?? 1) + 1, at: (m.createdAt ?? new Date()).getTime(), last: eventId } satisfies ChatRepeat); return true; } /** * Moves new events, questions, releases and incidents into the project chats. Idempotent * (every message has a dedupe key), so the bot, the watchdog and the web may all call it. * Returns the number of new messages. */ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise<number> { const now = o.now ?? new Date(); const chatOf = new Map<number, number>(); const chatId = async (projectId: number) => { if (!chatOf.has(projectId)) chatOf.set(projectId, (await ensureProjectChat(db, projectId)).id); return chatOf.get(projectId)!; }; const titles = new Map<string, string | null>(); const titleOf = async (key: string) => { if (!titles.has(key)) titles.set(key, await threadTitle(db, key)); return titles.get(key) ?? null; }; let added = 0; let repeated = 0; const add = async (m: NewChatMessage) => { // PEP-151: the same event of a story again in a row is a counter on the line already there. if (m.authorKind !== "user" && !m.questionId) m.text = userText(m.text); // PEP-154: compared and stored without service text if (!m.text) return; if (await repeatsLastEvent(db, m)) return void repeated++; if (m.threadKey) m.threadTitle = await titleOf(m.threadKey); if (await addChatMessage(db, m)) added++; }; // events // Cursors are written only when they move: a no-op sync doesn't wake the other processes. const savedEvents = await getSetting<number>(db, CURSOR_EVENTS); let cursor = savedEvents ?? (await initialCursor(db, events, now)); for (;;) { // Read the newest id first: a row committed after it is picked up by the next call. const [top] = await db.select({ max: sql<number | null>`max(${events.id})` }).from(events); const upTo = Number(top?.max ?? cursor); const rows = await db .select({ e: events, login: users.login }) .from(events) .leftJoin(users, eq(events.actorUserId, users.id)) .where(and(gt(events.id, cursor), lte(events.id, upTo), inArray(events.type, Object.keys(EVENT_TEXT)))) .orderBy(asc(events.id)) .limit(BATCH); for (const { e, login } of rows) { const p = (e.payload ?? {}) as P; const base = { chatId: await chatId(e.projectId), threadKey: e.taskId ? `task:${e.taskId}` : null, taskId: e.taskId, dedupeKey: `event:${e.id}`, createdAt: e.createdAt }; if (e.type === "pm_comment") { if (p.chatMessageId) continue; // written in a chat: already there await add({ ...base, kind: "user", authorKind: "user", authorUserId: (p.userId as number) ?? e.actorUserId, authorLogin: s(p.login) || login, via: e.actorChannel === "telegram" ? "telegram" : "web", text: s(p.text) }); continue; } const t = EVENT_TEXT[e.type]?.(p); if (!t) continue; // PEP-156: «агент взял задачу» names the agent — and waits for it to start when nobody has yet. if (e.taskId && (e.type === "task_updated" || e.type === "started")) { const took = await tookLine(db, e.type, e.taskId, e.sessionId, e.id, t.text === TOOK_TEXT); if (took === null) continue; if (took) t.text = took; } // PEP-156: what the factory or an agent did is never signed with the login of the person // whose click caused it; an agent's own words carry its nickname (a role — its name). const author = t.author === "agent" ? (t.role ?? (await sessionAgentName(db, e.sessionId)) ?? (e.taskId ? await taskLiveAgentName(db, e.taskId) : null)) : null; await add({ ...base, kind: "event", important: !!t.important, authorKind: t.author ?? "system", authorLogin: author, text: t.text }); } // The cursor moves past filtered-out events too. cursor = rows.length === BATCH ? rows.at(-1)!.e.id : Math.max(cursor, upTo); if (rows.length < BATCH) break; } if (cursor !== savedEvents) await setSetting(db, CURSOR_EVENTS, cursor); // questions const savedQuestions = await getSetting<number>(db, CURSOR_QUESTIONS); let qCursor = savedQuestions ?? (await initialCursor(db, questions, now)); for (;;) { const rows = await db.select().from(questions).where(gt(questions.id, qCursor)).orderBy(asc(questions.id)).limit(BATCH); for (const q of rows) { const head = q.kind === "approval" ? tr("🟡 Нужно одобрение") : q.kind === "permission" ? tr("🔐 Нужно разрешение") : q.kind === "question" ? tr("❓ Вопрос агента") : "🔔"; // PEP-156: the agent's own words carry its nickname; «готово», failures and the like — the factory's. const author = await questionAuthor(db, q); await add({ chatId: await chatId(q.projectId), threadKey: q.taskId ? `task:${q.taskId}` : null, taskId: q.taskId, kind: "question", important: true, authorKind: author.kind, authorLogin: author.kind === "agent" ? author.name : null, text: `${head}\n${questionIsFreeText(q) ? asIs(cut(q.text, 3000)) : cut(q.text, 3000)}`, questionId: q.id, dedupeKey: `question:${q.id}`, createdAt: q.createdAt, }); qCursor = q.id; } if (rows.length < BATCH) break; } if (qCursor !== savedQuestions) await setSetting(db, CURSOR_QUESTIONS, qCursor); // releases and incidents: one message per (id, status); the window overlaps a little. const savedObjects = await getSetting<number>(db, CURSOR_OBJECTS); const since = new Date((savedObjects ?? now.getTime() - DAY) - 60_000); for (const r of await db.select().from(releases).where(gt(releases.updatedAt, since)).orderBy(asc(releases.id))) { // A story's draft stand coming and going is plumbing: only its failure is worth a message. if (r.env === "preview" && r.status !== "failed" && r.status !== "rolled_back") continue; const tasksIn = r.tasks.length ? ` · ${tr("задачи: {tasks}", { tasks: r.tasks.slice(0, 8).join(", ") })}` : ""; await add({ chatId: await chatId(r.projectId), threadKey: `release:${r.id}`, kind: "event", important: r.env !== "preview" || r.status === "failed" || r.status === "rolled_back", text: `${RELEASE_ICON[r.status] ?? "•"} ${ENV_RU[r.env] ?? r.env}: ${RELEASE_RU[r.status] ?? r.status}${tasksIn}${r.reason ? `\n${asIs(cut(r.reason, 300))}` : ""}`, url: r.host ? `https://${r.host}` : r.runUrl, dedupeKey: `release:${r.id}:${r.status}`, }); } for (const i of await db.select().from(incidents).where(gt(incidents.updatedAt, since)).orderBy(asc(incidents.id))) { await add({ chatId: await chatId(i.projectId), threadKey: `incident:${i.id}`, taskId: i.taskId, kind: "event", important: i.status === "new" || i.status === "regressed" || i.status === "pending", text: incidentText(i), url: i.url, dedupeKey: `incident:${i.id}:${i.status}`, }); } // Moved at most every 30 s (the window overlaps by a minute, so nothing is lost). if (savedObjects == null || now.getTime() - savedObjects >= 30_000) await setSetting(db, CURSOR_OBJECTS, now.getTime()); if (added || repeated) await notify(db, { type: "chat_message", messageId: 0 }); return added; } /** Deletes chat messages older than the TTL (the stories, questions and events stay). */ export async function pruneChats(db: Db, o: { now?: Date } = {}): Promise<number> { const before = new Date((o.now ?? new Date()).getTime() - chatTtlMs()); // PEP-106: what people wrote to each other in the discussion is kept; the projection is not. const stale = and(lt(chatMessages.createdAt, before), sql`NOT (${DISCUSSION})`)!; const old = db.select({ id: chatMessages.id }).from(chatMessages).where(stale); await db.update(telegramOutbox).set({ chatMessageId: null }).where(inArray(telegramOutbox.chatMessageId, old)); const rows = await db.delete(chatMessages).where(stale).returning({ id: chatMessages.id }); await pruneMessageStates(db, before); await pruneQuestionDetails(db, before); return rows.length; } // ── Telegram groups ──────────────────────────────────────────────────────────────── const LINK_TTL_MS = 10 * 60_000; const linkKey = (code: string, secret: string) => `chat.link:${createHmac("sha256", secret).update(`chat:${code}`).digest("hex")}`; const UNLINKED = { tgChatId: null, tgTitle: null, tgLinkedAt: null, tgLinkedBy: null, tgBotUserId: null }; /** * One-time code (10 minutes) that links a Telegram group to this chat. PEP-109: the group is * linked through the user's own bot — the code is bound to it and only that bot accepts it. * `sharedBot` (the superadmin without an own bot) binds the code to the platform's bot instead. */ export async function createChatLinkCode(db: Db, secret: string, user: Pick<User, "id">, chatId: number, o: { sharedBot?: boolean } = {}): Promise<string> { await chatForUser(db, user, chatId); const [u] = await db.select({ own: users.telegramBotTokenEnc }).from(users).where(eq(users.id, user.id)); if (!u?.own && !o.sharedBot) throw new PeppaError(tr("Чтобы связать чат с группой, подключите своего бота: Настройки → Telegram")); const code = `c${randomBytes(12).toString("base64url")}`; await setSetting(db, linkKey(code, secret), { chatId, userId: user.id, botUserId: u?.own ? user.id : null, expiresAt: Date.now() + LINK_TTL_MS }); return code; } /** Codes of chat links start with "c"; the personal pairing codes of PEP-2 never collide with them. */ export const isChatLinkCode = (code: string) => /^c[\w-]{16}$/.test(code); /** * Links the group the code was sent from. A group linked to another chat moves to this one. * `botUserId` — the owner of the bot the code came to (absent = the shared bot): a code is * accepted only by the bot it was issued for; another bot leaves it intact (a command without * @bot reaches every bot of the group). */ export async function acceptChatLink(db: Db, secret: string, code: string, group: { tgChatId: number; title: string | null; botUserId?: number }, now = Date.now()): Promise<Chat | null> { const key = linkKey(code, secret); const saved = await getSetting<{ chatId: number; userId: number; botUserId?: number | null; expiresAt: number }>(db, key); if (!saved) return null; const botUserId = saved.botUserId ?? null; if (botUserId !== (group.botUserId ?? null)) return null; await deleteSetting(db, key); if (now >= saved.expiresAt) return null; return db.transaction((tx) => { tx.update(chats).set(UNLINKED).where(eq(chats.tgChatId, group.tgChatId)).run(); return tx.update(chats).set({ tgChatId: group.tgChatId, tgTitle: group.title, tgLinkedAt: new Date(now), tgLinkedBy: saved.userId, tgBotUserId: botUserId }).where(eq(chats.id, saved.chatId)).returning().get() ?? null; }); } export async function unlinkChat(db: Db, user: Pick<User, "id">, chatId: number): Promise<void> { await chatForUser(db, user, chatId); await db.update(chats).set(UNLINKED).where(eq(chats.id, chatId)); } /** Whose bot a pending link code is for: a user id, null — the shared bot, undefined — no such code. */ export async function chatLinkCodeBot(db: Db, secret: string, code: string): Promise<number | null | undefined> { const saved = await getSetting<{ botUserId?: number | null }>(db, linkKey(code, secret)); return saved ? (saved.botUserId ?? null) : undefined; } /** The @username of the own bot the chat's group is linked through (null — the shared bot). */ export async function chatGroupBotName(db: Db, chatId: number): Promise<string | null> { const [u] = await db.select({ username: users.telegramBotUsername }).from(chats).innerJoin(users, eq(chats.tgBotUserId, users.id)).where(eq(chats.id, chatId)); return u?.username ?? null; } /** PEP-109: groups linked through users' own bots (the bot process routes their messages). */ export async function chatGroupBots(db: Db): Promise<Array<{ tgChatId: number; botUserId: number }>> { const rows = await db.select({ tgChatId: chats.tgChatId, botUserId: chats.tgBotUserId }).from(chats).where(and(isNotNull(chats.tgChatId), isNotNull(chats.tgBotUserId))); return rows.map((r) => ({ tgChatId: r.tgChatId!, botUserId: r.botUserId! })); } /** A group became a supergroup: Telegram gives it a new id. */ export async function migrateChatGroup(db: Db, from: number, to: number): Promise<void> { await db.update(chats).set({ tgChatId: to }).where(eq(chats.tgChatId, from)); } /** The person writing in a linked group: a Peppa user with this personal Telegram account (PEP-2). */ export async function telegramAccountUser(db: Db, fromId: number): Promise<User | null> { const rows = await db.select().from(users).where(eq(users.telegramUserId, fromId)); return rows.find((u) => !u.disabledAt) ?? null; } /** May this user write into the chat from Telegram (project access / the master chat's owner)? */ export async function mayWriteChat(db: Db, user: Pick<User, "id">, chat: Chat): Promise<boolean> { return chatForUser(db, user, chat.id).then( () => true, () => false, ); } export interface MirrorTarget { tgChatId: number; /** The group of a master chat (a project's message reached it as an important one). */ master: boolean; } /** Messages after `afterId` with the chat they belong to (the bot mirrors them). */ export async function chatMessagesAfter(db: Db, afterId: number, limit = 100) { return db.select({ m: chatMessages, chat: chats }).from(chatMessages).innerJoin(chats, eq(chatMessages.chatId, chats.id)).where(gt(chatMessages.id, afterId)).orderBy(asc(chatMessages.id)).limit(limit); } export async function lastChatMessageId(db: Db): Promise<number> { const [r] = await db.select({ max: sql<number | null>`max(${chatMessages.id})` }).from(chatMessages); return Number(r?.max ?? 0); } /** Linked groups a message goes to: its chat's group, and for an important project message the master groups of the project's people. */ export async function mirrorTargets(db: Db, m: ChatMessage, chat: Chat): Promise<MirrorTarget[]> { // PEP-174: a project on pause sends nothing to Telegram — not even afterwards. if (chat.projectId != null && (await duringPause(db, chat.projectId, m.createdAt))) return []; const out: MirrorTarget[] = []; if (chat.tgChatId && chat.tgChatId !== m.tgChatId) out.push({ tgChatId: chat.tgChatId, master: chat.kind === "master" }); if (chat.kind === "project" && m.important) { for (const u of await projectAudience(db, chat.projectId!)) { const [mc] = await db.select().from(chats).where(and(eq(chats.userId, u.id), isNotNull(chats.tgChatId))); if (!mc?.tgChatId || mc.tgChatId === m.tgChatId || out.some((t) => t.tgChatId === mc.tgChatId)) continue; if ((await getNotifyPrefs(db, u.id)).mutedProjects.includes(chat.projectId!)) continue; out.push({ tgChatId: mc.tgChatId, master: true }); } } return out; } /** The chat message a Telegram message in this group stands for (sent by the bot, or written there). */ export async function chatMessageByTelegram(db: Db, tgChatId: number, tgMessageId: number): Promise<ChatMessage | null> { const [sent] = await db .select({ m: chatMessages }) .from(telegramOutbox) .innerJoin(chatMessages, eq(telegramOutbox.chatMessageId, chatMessages.id)) .where(and(eq(telegramOutbox.telegramMessageId, tgMessageId), sql`cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(tgChatId)}`)); if (sent) return sent.m; const [own] = await db.select().from(chatMessages).where(and(eq(chatMessages.tgChatId, tgChatId), eq(chatMessages.tgMessageId, tgMessageId))); return own ?? null; } /** * The Telegram message a thread hangs on in this group: the first message of the thread * that reached the group (sent by the bot or written there). Null — this is the thread's first. */ export async function threadAnchor(db: Db, row: Pick<OutboxRow, "id" | "chatMessageId" | "params">): Promise<number | null> { if (!row.chatMessageId) return null; const [m] = await db.select({ threadKey: chatMessages.threadKey }).from(chatMessages).where(eq(chatMessages.id, row.chatMessageId)); if (!m?.threadKey) return null; const group = String(row.params.chat_id); const [sent] = await db .select({ id: telegramOutbox.telegramMessageId }) .from(telegramOutbox) .innerJoin(chatMessages, eq(telegramOutbox.chatMessageId, chatMessages.id)) .where(and(eq(chatMessages.threadKey, m.threadKey), eq(telegramOutbox.status, "sent"), isNotNull(telegramOutbox.telegramMessageId), sql`cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${group}`)) .orderBy(asc(telegramOutbox.id)) .limit(1); if (sent?.id) return sent.id; const [own] = await db .select({ id: chatMessages.tgMessageId }) .from(chatMessages) .where(and(eq(chatMessages.threadKey, m.threadKey), eq(chatMessages.tgChatId, Number(group)), isNotNull(chatMessages.tgMessageId))) .orderBy(asc(chatMessages.id)) .limit(1); return own?.id ?? null; }