peppa/apps/bot/src/bot.ts
Асель 824ba56b74 PEP-2: Telegram per user — pairing from Settings, delivery by project access
- users.telegram_* replace the single global binding; one-time /start code
  per user (web Settings → Telegram, or peppa telegram pair <login>);
  a chat belongs to one user
- agent questions go to the project's owner and members who paired; an
  answer (button or reply) is accepted only from someone with access to
  the project; messages are closed for every recipient; /status is scoped
- CLI: telegram pair|status|unpair <login>, user ensure mock-<name>;
  dev stand pairs its test PM per user
- tests: several-users journey (bob without access, then as a member);
  70 e2e total, green
- BREAKING: the old global binding is removed; users pair again in Settings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 03:44:30 +05:00

334 lines
14 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.

// Peppa Telegram bot: forwards PM questions (approvals, questions, permissions, session
// alerts) to the paired chat and turns button presses / replies into answers delivered
// back into the agent session. Telegram is an adapter over the DB, not a remote shell:
// it can only answer a specific pending question or resume/stop the session it is about.
import {
acceptPairing,
claimUpdate,
dueOutbox,
enqueueTelegram,
EVENTS_CHANNEL,
finishUpdate,
answeredQuestionMessages,
projectForUser,
questionRecipients,
telegramUser,
userProjectIds,
type User,
getOffset,
getQuestion,
getSession,
listSessions,
markOutboxRetry,
markOutboxSent,
pendingQuestions,
questionByTelegramMessage,
setOffset,
setSetting,
type OutboxRow,
type Question,
type SessionView,
} from "@peppa/core";
import { projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { acceptTask, answerAndDeliver, resumeSession, stopSession } from "@peppa/runner";
import { eq } from "drizzle-orm";
import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts";
import { TelegramApi, TelegramError, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts";
export interface BotOptions {
db: Db;
api: TelegramApi;
/** Server-side secret for hashing pairing codes (the bot token). */
secret: string;
webUrl: string;
pollTimeoutSec?: number;
outboxIntervalMs?: number;
reconcileIntervalMs?: number;
log?: (msg: string) => void;
}
const HELP = `Я бот Пеппы. Присылаю вопросы от агентов: одобрения proposal, вопросы, разрешения и сигналы, что сессия ждёт тебя.
• Кнопки под сообщением — быстрый ответ.
• Ответ <b>реплаем</b> на сообщение — свой текст, он уйдёт прямо в сессию.
• /status — активные сессии и открытые вопросы.`;
export function createBot(o: BotOptions) {
const { db, api } = o;
const log = o.log ?? (() => {});
const abort = new AbortController();
let reconcileQueued = false;
let wakeOutbox: (() => void) | null = null;
// ── questions → outbox ─────────────────────────────────────────────────────────
async function context(q: Question) {
let session: SessionView | null = null;
if (q.sessionId) session = await getSession(db, q.sessionId).catch(() => null);
const [st] = q.taskId ? await db.select({ status: tasks.status }).from(tasks).where(eq(tasks.id, q.taskId)) : [];
const taskStatus = st?.status ?? null;
if (session) return { taskKey: session.taskKey, taskTitle: session.taskTitle, taskStatus, session, webUrl: o.webUrl };
if (q.taskId) {
const [t] = await db
.select({ key: projects.key, number: tasks.number, title: tasks.title })
.from(tasks)
.innerJoin(projects, eq(tasks.projectId, projects.id))
.where(eq(tasks.id, q.taskId));
if (t) return { taskKey: formatTaskKey(t.key, t.number), taskTitle: t.title, taskStatus, session: null, webUrl: o.webUrl };
}
return { taskKey: null, taskTitle: null, session: null, webUrl: o.webUrl };
}
/** Makes sure every open question has a message and every closed one an edit. */
/** Makes sure every open question has a message for each recipient, and every closed one an edit. */
async function reconcile(): Promise<void> {
for (const q of await pendingQuestions(db)) {
const recipients = await questionRecipients(db, q.projectId);
if (!recipients.length) continue;
const r = renderQuestion(q, await context(q));
for (const u of recipients) {
await enqueueTelegram(db, {
dedupeKey: `q:${q.id}:${u.telegramChatId}`,
method: "sendMessage",
questionId: q.id,
params: { chat_id: u.telegramChatId, text: r.text, parse_mode: "HTML", reply_markup: { inline_keyboard: r.buttons } },
});
}
}
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}`,
method: "editMessageText",
questionId: q.id,
params: {
chat_id: sent.params.chat_id,
message_id: sent.telegramMessageId,
text: renderAnswered(String(sent.params.text), q),
parse_mode: "HTML",
reply_markup: { inline_keyboard: [] },
},
});
}
wakeOutbox?.();
}
function scheduleReconcile() {
if (reconcileQueued) return;
reconcileQueued = true;
setTimeout(() => {
reconcileQueued = false;
reconcile().catch((e) => log(`reconcile: ${(e as Error).message}`));
}, 150);
}
// ── outbox → Telegram ──────────────────────────────────────────────────────────
async function deliver(row: OutboxRow): Promise<void> {
if (row.method === "sendMessage" && row.questionId) {
// Answered before we got to it (e.g. in the terminal): no point in asking.
const q = await getQuestion(db, row.questionId).catch(() => null);
if (q?.answeredAt) return markOutboxSent(db, { ...row, questionId: null }, null);
}
try {
const res = await api.call<TgMessage | boolean>(row.method, row.params);
await markOutboxSent(db, row, typeof res === "object" ? res.message_id : null);
} catch (e) {
if (!(e instanceof TelegramError)) throw e;
if (e.code === 400 && /not modified/i.test(e.description)) return markOutboxSent(db, row, null);
log(`outbox #${row.id} ${row.method}: ${e.message}`);
// 400/403 won't get better by retrying.
if (e.code === 400 || e.code === 403) return markOutboxRetry(db, { ...row, attempts: 99 }, e.message);
await markOutboxRetry(db, row, e.message, e.retryAfter);
}
}
async function flushOutbox(): Promise<void> {
for (const row of await dueOutbox(db)) await deliver(row);
}
// ── Telegram → answers ─────────────────────────────────────────────────────────
async function reply(chatId: number, text: string, replyTo?: number) {
await api.sendMessage(chatId, text, replyTo ? { reply_parameters: { message_id: replyTo } } : {}).catch((e) => log(`reply: ${e.message}`));
}
async function answer(q: Question, text: string): Promise<string> {
const fresh = await getQuestion(db, q.id);
if (fresh.answeredAt) return `Уже отвечено${fresh.answeredVia === "system" ? "" : ` (${fresh.answeredVia})`}: ${fresh.answer}`;
const { delivered } = await answerAndDeliver(db, q.id, text, "telegram");
scheduleReconcile();
return delivered ? "Отправлено в сессию ✅" : "Ответ сохранён, но сессия сейчас не запущена — агент увидит его в истории задачи.";
}
const canAccess = (user: User, projectId: number) =>
projectForUser(db, user.id, projectId).then(
() => true,
() => false,
);
async function status(user: User): Promise<string> {
const ids = new Set(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 = [`<b>Активные сессии: ${sessions.length}</b>`];
for (const s of sessions) lines.push(`• ${esc(s.taskKey ?? `#${s.id}`)} — ${s.status} (${s.provider})`);
lines.push("", `<b>Открытых вопросов: ${open.length}</b>`);
return lines.join("\n");
}
async function onMessage(m: TgMessage): Promise<"done" | "ignored"> {
const text = m.text?.trim() ?? "";
const start = /^\/start(?:@\w+)?(?:\s+(\S+))?$/.exec(text);
if (start?.[1] && m.from) {
const b = await acceptPairing(db, o.secret, start[1], { chatId: m.chat.id, userId: m.from.id, username: m.from.username });
if (b) {
await reply(m.chat.id, `Привязано ✅\n\n${HELP}`);
scheduleReconcile();
return "done";
}
await reply(m.chat.id, `Код привязки неверный или истёк. Получи новый: ${esc(o.webUrl)}/settings → Telegram`);
return "done";
}
const user = m.from ? await telegramUser(db, m.chat.id, m.from.id) : null;
if (!user) return "ignored";
if (/^\/(start|help)\b/.test(text)) return reply(m.chat.id, HELP).then(() => "done");
if (/^\/status\b/.test(text)) return reply(m.chat.id, await status(user)).then(() => "done");
if (m.reply_to_message) {
const q = await questionByTelegramMessage(db, m.chat.id, m.reply_to_message.message_id);
if (!q || !(await canAccess(user, q.projectId))) {
await reply(m.chat.id, "Не нашёл вопрос для этого сообщения.", m.message_id);
return "done";
}
await reply(m.chat.id, esc(await answer(q, text)), m.message_id);
return "done";
}
await reply(m.chat.id, "Чтобы ответить агенту, ответь <b>реплаем</b> на его сообщение. /status — что сейчас происходит.");
return "done";
}
async function onCallback(c: TgCallbackQuery): Promise<"done" | "ignored"> {
const user = c.message ? await telegramUser(db, c.message.chat.id, c.from.id) : null;
if (!user) {
await api.answerCallbackQuery(c.id, "Нет доступа").catch(() => {});
return "ignored";
}
const [kind, idStr, choice] = (c.data ?? "").split(":");
const id = Number(idStr);
let toast = "Неизвестная кнопка";
const q0 = kind === "q" ? await getQuestion(db, id).catch(() => null) : null;
const s0 = kind === "s" ? await getSession(db, id).catch(() => null) : null;
const projectId = q0?.projectId ?? s0?.projectId;
if (projectId == null || !(await canAccess(user, projectId))) {
// Unknown or someone else's question/session: don't reveal which.
await api.answerCallbackQuery(c.id, kind === "s" ? "Сессия не найдена" : "Вопрос не найден").catch(() => {});
return "done";
}
if (kind === "q" && choice === "accept") {
try {
const ref = await acceptTask(db, id, "telegram");
toast = `${ref.key} принята ✅`;
} catch (e) {
toast = (e as Error).message;
}
scheduleReconcile();
} else if (kind === "q") {
const q = await getQuestion(db, id).catch(() => null);
const text = q && choice ? choiceToAnswer(q, choice) : null;
toast = q && text ? await answer(q, text) : "Вопрос не найден";
} else if (kind === "s") {
const s = await getSession(db, id).catch(() => null);
if (!s) toast = "Сессия не найдена";
else if (choice === "resume") {
try {
const r = await resumeSession(db, s.id);
toast = `Перезапущено (поколение ${r.generation}) 🔁`;
} catch (e) {
toast = (e as Error).message;
}
} else if (choice === "stop") {
await stopSession(db, s.id);
toast = "Сессия остановлена ⏹";
}
scheduleReconcile();
}
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
return "done";
}
async function handleUpdate(u: TgUpdate): Promise<void> {
if (!(await claimUpdate(db, u.update_id))) return;
try {
const r = u.message ? await onMessage(u.message) : u.callback_query ? await onCallback(u.callback_query) : "ignored";
await finishUpdate(db, u.update_id, r);
} catch (e) {
log(`update ${u.update_id}: ${(e as Error).stack ?? e}`);
await finishUpdate(db, u.update_id, "failed");
}
}
// ── loops ──────────────────────────────────────────────────────────────────────
const sleep = (ms: number) =>
new Promise<void>((r) => {
const t = setTimeout(r, ms);
abort.signal.addEventListener("abort", () => (clearTimeout(t), r()), { once: true });
});
async function pollLoop() {
while (!abort.signal.aborted) {
try {
let offset = await getOffset(db);
const updates = await api.getUpdates(offset, o.pollTimeoutSec ?? 25, abort.signal);
for (const u of updates) {
await handleUpdate(u);
offset = u.update_id + 1;
await setOffset(db, offset);
}
} catch (e) {
log(`poll: ${(e as Error).message}`);
await sleep(3000);
}
}
}
async function outboxLoop() {
while (!abort.signal.aborted) {
await flushOutbox().catch((e) => log(`outbox: ${(e as Error).message}`));
await Promise.race([sleep(o.outboxIntervalMs ?? 1000), new Promise<void>((r) => (wakeOutbox = r))]);
wakeOutbox = null;
}
}
async function reconcileLoop() {
while (!abort.signal.aborted) {
await reconcile().catch((e) => log(`reconcile: ${(e as Error).message}`));
await sleep(o.reconcileIntervalMs ?? 10_000);
}
}
let loops: Promise<unknown> | null = null;
let unlisten: (() => Promise<void>) | null = null;
return {
reconcile,
flushOutbox,
handleUpdate,
async start() {
const me = await api.getMe();
await setSetting(db, "telegram.bot", { id: me.id, username: me.username });
log(`bot @${me.username} started`);
const l = await db.$client.listen(EVENTS_CHANNEL, () => scheduleReconcile());
unlisten = () => l.unlisten();
loops = Promise.all([pollLoop(), outboxLoop(), reconcileLoop()]);
return me;
},
async stop() {
abort.abort();
wakeOutbox?.();
await unlisten?.().catch(() => {});
await loops;
},
};
}
export type Bot = ReturnType<typeof createBot>;