- packages/db: schema on sqlite-core (timestamps as epoch ms → Date, JSON as text, booleans 0/1), one baseline migration; node:sqlite client under drizzle's better-sqlite3 session (busy_timeout first, WAL, BEGIN IMMEDIATE, retries on SQLITE_BUSY, lazy open, async transaction callbacks refused); PEPPA_DB (default ~/.peppa/peppa.db) - live updates: notify() pokes the bot over a unix socket; the bot also watches PRAGMA data_version every second (writes by other processes) - Postgres specifics ported: createTask transaction is synchronous, no `for update skip locked`, `count(*)`, json_extract instead of ->>, json_each instead of @> - `peppa db migrate` and `peppa db migrate-to-sqlite <file>` (read-only snapshot of Postgres, FK order from the schema, row count + foreign key checks, file appears only when they pass); old Postgres schema kept in packages/cli/legacy-pg-migrations for the migration and its test - daily VACUUM INTO backup from the watchdog (7 copies, admin alert on failure) - tests: a temp SQLite file per test file; storage.test.ts (20 processes, per-project numbering across processes, socket/data_version, migration from Postgres incl. a dangling foreign key, backups); two test races fixed - CI: no per-run Postgres database; PEPPA_TEST_PG only for the migration test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
376 lines
16 KiB
TypeScript
376 lines
16 KiB
TypeScript
// 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, вопросы, разрешения и сигналы, что сессия ждёт тебя.
|
||
|
||
• Кнопки под сообщением — быстрый ответ.
|
||
• Ответ <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 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<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);
|
||
}
|
||
}
|
||
|
||
// 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<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`);
|
||
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<typeof createBot>;
|