From 46840ffef57cdbda1f8520675360a17d8d3e242f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 19:04:18 +0500 Subject: [PATCH] =?UTF-8?q?PEP-62:=20bot=20=E2=80=94=20link=20groups=20by?= =?UTF-8?q?=20code,=20mirror=20chat=20messages=20with=20reply=20threads,?= =?UTF-8?q?=20replies=20and=20buttons=20from=20groups?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/bot/src/bot.ts | 125 +++++++++++++++++++++++- apps/bot/src/telegram.ts | 4 +- openspec/changes/pep-62-chats/design.md | 5 +- packages/core/src/telegram.ts | 2 +- 4 files changed, 129 insertions(+), 7 deletions(-) diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 435ab96a..50b3a401 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -47,10 +47,25 @@ import { type OutboxRow, type Question, type SessionView, + acceptChatLink, + chatByTelegram, + chatMessageByTelegram, + chatMessagesAfter, + getSetting, + isChatLinkCode, + lastChatMessageId, + mayWriteChat, + migrateChatGroup, + mirrorTargets, + syncChats, + telegramAccountUser, + threadAnchor, + type Chat, + type ChatMessage, } from "@peppa/core"; import { projects, tasks, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; -import { acceptTask, answerAndDeliver, decideIncident, moveTask, resumeSession, stopSession } from "@peppa/runner"; +import { acceptTask, answerAndDeliver, decideIncident, moveTask, postToChat, resumeSession, stopSession } from "@peppa/runner"; import { eq, sql } from "drizzle-orm"; import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts"; import { TelegramApi, TelegramError, type InlineButton, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts"; @@ -161,6 +176,7 @@ export function createBot(o: BotOptions) { }); } } + await mirrorChats().catch((e) => log(`chats: ${(e as Error).message}`)); for (const { sent, q } of await answeredQuestionMessages(db, new Date(Date.now() - 24 * 3600_000))) { await enqueueTelegram(db, { dedupeKey: `qa:${q.id}:${sent.params.chat_id}`, @@ -178,6 +194,52 @@ export function createBot(o: BotOptions) { wakeOutbox?.(); } + // ── chats → linked Telegram groups (PEP-62) ──────────────────────────────────── + const MIRROR_CURSOR = "chat.mirror.cursor"; + + /** Projects new events into chats and queues new chat messages for the linked groups. */ + async function mirrorChats(): Promise { + await syncChats(db); + let cursor = await getSetting(db, MIRROR_CURSOR); + // First start: only what comes from now on (a newly linked group doesn't get the backlog). + if (cursor == null) return setSetting(db, MIRROR_CURSOR, await lastChatMessageId(db)); + for (;;) { + const rows = await chatMessagesAfter(db, cursor); + for (const { m, chat } of rows) { + for (const t of await mirrorTargets(db, m, chat)) await mirrorOne(m, chat, t.tgChatId, t.master); + cursor = m.id; + } + await setSetting(db, MIRROR_CURSOR, cursor); + if (rows.length < 100) break; + } + } + + async function mirrorOne(m: ChatMessage, chat: Chat, tgChatId: number, master: boolean): Promise { + const key = chat.projectId ? await projectKey(chat.projectId) : ""; + const where = [master && key ? `[${esc(key)}]` : null, m.threadTitle ? `🧵 ${esc(m.threadTitle)}` : null].filter(Boolean).join(" "); + let text: string; + let buttons: InlineButton[][] = []; + let questionId: number | undefined; + if (m.kind === "question" && m.questionId) { + const q = await getQuestion(db, m.questionId).catch(() => null); + if (!q || q.answeredAt) return; + const r = renderQuestion(q, await context(q)); + text = r.text; + buttons = r.buttons; + questionId = q.id; + } else { + const who = m.kind === "user" ? `${esc(m.authorLogin ?? "?")}${m.via === "telegram" ? "" : " (веб)"}: ` : m.authorKind === "agent" ? "🤖 " : ""; + text = `${where ? `${where}\n` : ""}${who}${esc(m.text.slice(0, 3500))}${m.url ? `\n${esc(m.url)}` : ""}`; + } + await enqueueTelegram(db, { + dedupeKey: `cm:${m.id}:${tgChatId}`, + method: "sendMessage", + questionId, + chatMessageId: m.id, + params: { chat_id: tgChatId, text, parse_mode: "HTML", link_preview_options: { is_disabled: true }, ...(buttons.length ? { reply_markup: { inline_keyboard: buttons } } : {}) }, + }); + } + async function projectKey(projectId: number): Promise { const [p] = await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId)); return p?.key ?? ""; @@ -199,8 +261,14 @@ export function createBot(o: BotOptions) { const q = await getQuestion(db, row.questionId).catch(() => null); if (q?.answeredAt) return markOutboxSent(db, { ...row, questionId: null }, null); } + let params = row.params; + if (row.method === "sendMessage" && row.chatMessageId && !params.reply_parameters) { + // PEP-62: a thread in a group = a chain of replies to its first message. + const anchor = await threadAnchor(db, row); + if (anchor) params = { ...params, reply_parameters: { message_id: anchor, allow_sending_without_reply: true } }; + } try { - const res = await api.call(row.method, row.params); + const res = await api.call(row.method, params); await markOutboxSent(db, row, typeof res === "object" ? res.message_id : null); } catch (e) { if (!(e instanceof TelegramError)) throw e; @@ -377,7 +445,52 @@ export function createBot(o: BotOptions) { return "Неизвестная кнопка"; } + /** A message in a group (PEP-62): linking by code, then replies and commands of the linked chat. */ + async function onGroupMessage(m: TgMessage): Promise<"done" | "ignored"> { + const text = m.text?.trim() ?? ""; + const link = /^\/(?:start|link)(?:@\w+)?\s+(\S+)$/.exec(text); + if (link) { + if (!isChatLinkCode(link[1]!)) return reply(m.chat.id, "Это не код связки чата. Получи код в вебе: Чаты → «Связать с Telegram».").then(() => "done"); + const chat = await acceptChatLink(db, o.secret, link[1]!, { tgChatId: m.chat.id, title: m.chat.title ?? null }); + if (!chat) return reply(m.chat.id, "Код связки неверный или истёк — получи новый в вебе: Чаты → «Связать с Telegram».").then(() => "done"); + const name = chat.projectId ? `чатом проекта ${esc(await projectKey(chat.projectId))}` : "мастер-чатом"; + await reply(m.chat.id, `Группа связана с ${name} ✅\n\nСюда будут приходить события и вопросы агентов, треды — цепочками ответов. Ответь реплаем — сообщение уйдёт в тред (в треде стори — агенту). Отвечать могут те, кто привязал Telegram в Пеппе и имеет доступ к проекту. /help — команды.`); + return "done"; + } + const chat = await chatByTelegram(db, m.chat.id); + if (!chat || !m.from || !text) return "ignored"; + // Group chatter stays in Telegram: only replies and commands reach the chat. + if (!m.reply_to_message && !text.startsWith("/")) return "ignored"; + const user = await telegramAccountUser(db, m.from.id); + if (!user || !(await mayWriteChat(db, user, chat))) { + await reply(m.chat.id, user ? "У тебя нет доступа к этому чату." : `Не знаю тебя в Пеппе — привяжи Telegram: ${esc(o.webUrl)}/settings → Telegram.`, m.message_id); + return "done"; + } + enterActor({ kind: "user", userId: user.id, channel: "telegram" }); + // A reply finds its thread (and chat: the master group holds project threads too). + const target = m.reply_to_message ? await chatMessageByTelegram(db, m.chat.id, m.reply_to_message.message_id) : null; + try { + await postToChat(db, user, { + chatId: target?.chatId ?? chat.id, + threadKey: target?.threadKey ?? null, + text, + via: "telegram", + questionId: target?.kind === "question" ? target.questionId : null, + tg: { chatId: m.chat.id, messageId: m.message_id }, + }); + } catch (e) { + await reply(m.chat.id, esc((e as Error).message), m.message_id); + } + scheduleReconcile(); + return "done"; + } + async function onMessage(m: TgMessage): Promise<"done" | "ignored"> { + if (m.migrate_to_chat_id) { + await migrateChatGroup(db, m.chat.id, m.migrate_to_chat_id); + return "done"; + } + if (m.chat.type !== "private") return onGroupMessage(m); const text = m.text?.trim() ?? ""; const start = /^\/start(?:@\w+)?(?:\s+(\S+))?$/.exec(text); if (start?.[1] && m.from) { @@ -426,7 +539,13 @@ export function createBot(o: BotOptions) { } async function onCallback(c: TgCallbackQuery): Promise<"done" | "ignored"> { - const user = c.message ? await telegramUser(db, c.message.chat.id, c.from.id) : null; + let user = c.message ? await telegramUser(db, c.message.chat.id, c.from.id) : null; + if (!user && c.message && c.message.chat.type !== "private") { + // PEP-62: buttons in a linked group — the presser's own account and access to the chat. + const chat = await chatByTelegram(db, c.message.chat.id); + const who = chat ? await telegramAccountUser(db, c.from.id) : null; + if (chat && who && (chat.kind === "project" || chat.userId === who.id)) user = who; + } if (!user) { await api.answerCallbackQuery(c.id, "Нет доступа").catch(() => {}); return "ignored"; diff --git a/apps/bot/src/telegram.ts b/apps/bot/src/telegram.ts index b8039146..2e734cff 100644 --- a/apps/bot/src/telegram.ts +++ b/apps/bot/src/telegram.ts @@ -8,9 +8,11 @@ export interface TgUser { } export interface TgMessage { message_id: number; - chat: { id: number; type: string }; + chat: { id: number; type: string; title?: string }; from?: TgUser; text?: string; + /** PEP-62: a group became a supergroup (new chat id). */ + migrate_to_chat_id?: number; reply_to_message?: TgMessage; /** PEP-45: voice notes and audio files become stories after transcription. */ voice?: TgFileRef; diff --git a/openspec/changes/pep-62-chats/design.md b/openspec/changes/pep-62-chats/design.md index eb2c3412..c59eb13e 100644 --- a/openspec/changes/pep-62-chats/design.md +++ b/openspec/changes/pep-62-chats/design.md @@ -65,8 +65,9 @@ PEP-21 сами уходят в раннер-сервис. что существующая правка «отвечено» и `questionByTelegramMessage` работают и в группе). - **Приём**: сообщение в связанной группе → пользователь по `users.telegram_user_id` (личная привязка PEP-2) и не отключён → доступ к проекту / владелец мастер-чата. - Реплай → тред сообщения, на которое ответили (outbox или `tg_message_id`); иначе — общий - канал. Чужие и непривязанные игнорируются, на реплай/команду бот один раз подсказывает + Реплай → тред сообщения, на которое ответили (outbox или `tg_message_id`); команда без + реплая — общий канал. Обычная болтовня в группе (не реплай и не команда) остаётся в Telegram + и в чат не попадает — даже если privacy mode бота выключен. Чужие и непривязанные игнорируются, на реплай/команду бот один раз подсказывает привязать Telegram. Privacy mode бота оставляем: он видит команды и реплаи на свои сообщения — этого достаточно для тредов. - Личные уведомления в личку не меняются (их можно выключить по проекту в «Уведомлениях»). diff --git a/packages/core/src/telegram.ts b/packages/core/src/telegram.ts index 72dbe607..f14ef30e 100644 --- a/packages/core/src/telegram.ts +++ b/packages/core/src/telegram.ts @@ -85,7 +85,7 @@ export async function finishUpdate(db: Db, updateId: number, status: "done" | "i /** Queues a Bot API call; a no-op if `dedupeKey` was queued before. */ export async function enqueueTelegram( db: Db, - m: { dedupeKey: string; method: OutboxRow["method"]; params: Record; questionId?: number }, + m: { dedupeKey: string; method: OutboxRow["method"]; params: Record; questionId?: number; chatMessageId?: number }, ): Promise { const rows = await db.insert(telegramOutbox).values(m).onConflictDoNothing().returning(); return rows.length > 0;