// 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,
beat,
checkServices,
claimUpdate,
dueOutbox,
enqueueTelegram,
finishUpdate,
listenEvents,
answeredQuestionMessages,
projectForUser,
questionRecipients,
telegramUser,
userProjectIds,
type User,
getOffset,
getIncident,
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, decideIncident, 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;
/** Heartbeat + check on the watchdog and the web (PEP-20). */
heartbeatIntervalMs?: number;
// How often to check PRAGMA data_version for writes the notify() poke missed.
changesIntervalMs?: number;
log?: (msg: string) => void;
}
const HELP = `Я бот Пеппы. Присылаю вопросы от агентов: одобрения proposal, вопросы, разрешения и сигналы, что сессия ждёт тебя.
• Кнопки под сообщением — быстрый ответ.
• Ответ реплаем на сообщение — свой текст, он уйдёт прямо в сессию.
• /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 {
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 {
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(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 {
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 {
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 {
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 = [`Активные сессии: ${sessions.length}`];
for (const s of sessions) lines.push(`• ${esc(s.taskKey ?? `#${s.id}`)} — ${s.status} (${s.provider})`);
lines.push("", `Открытых вопросов: ${open.length}`);
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, "Чтобы ответить агенту, ответь реплаем на его сообщение. /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 i0 = kind === "i" ? await getIncident(db, id).catch(() => null) : null;
const projectId = q0?.projectId ?? s0?.projectId ?? i0?.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" ? "Сессия не найдена" : kind === "i" ? "Ошибка не найдена" : "Вопрос не найден").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 === "i" && (choice === "backlog" || choice === "start" || choice === "ignore")) {
// Decision on a new production error (PEP-58).
try {
const r = await decideIncident(db, id, choice, user.login);
toast = r.task ? `${r.task.key}: ${choice === "start" ? "агент взялся ▶️" : "в бэклоге 📥"}` : "Игнорируем 🙈";
} catch (e) {
toast = (e as Error).message;
}
wakeOutbox?.();
} 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 {
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((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((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);
}
}
// Writes by other processes the poke missed (PRAGMA data_version moves on every commit
// from another connection): at most a second late instead of waiting for reconcileLoop.
async function changesLoop() {
let seen = db.$client.dataVersion();
while (!abort.signal.aborted) {
await sleep(o.changesIntervalMs ?? 1000);
const v = db.$client.dataVersion();
if (v !== seen) {
seen = v;
scheduleReconcile();
}
}
}
async function monitorLoop() {
while (!abort.signal.aborted) {
try {
await beat(db, "bot");
if (await checkServices(db, { self: "bot", log })) wakeOutbox?.();
} catch (e) {
log(`monitor: ${(e as Error).message}`);
}
await sleep(o.heartbeatIntervalMs ?? 30_000);
}
}
let loops: Promise | null = null;
let unlisten: (() => Promise) | 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`);
unlisten = await listenEvents("bot", () => scheduleReconcile());
loops = Promise.all([pollLoop(), outboxLoop(), reconcileLoop(), changesLoop(), monitorLoop()]);
return me;
},
async stop() {
abort.abort();
wakeOutbox?.();
await unlisten?.().catch(() => {});
await loops;
},
};
}
export type Bot = ReturnType;