peppa/apps/bot/src/bot.ts

845 lines
42 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 { reportPlatformError } from "@peppa/core";
import {
accountUsageForUser,
describeUsage,
usageTotals,
describeAccount,
enterActor,
acceptPairing,
beat,
checkServices,
claimUpdate,
userBots,
dueOutbox,
enqueueTelegram,
finishUpdate,
listenEvents,
answeredQuestionMessages,
projectForUser,
buildDigest,
deliverToUser,
flushPushOutbox,
projectAudience,
questionEvent,
renderDigest,
type NotifyEvent,
telegramUser,
userProjectIds,
type User,
getOffset,
getIncident,
getQuestion,
getSession,
listSessions,
markOutboxRetry,
markOutboxSent,
pendingQuestions,
questionByTelegramMessage,
setOffset,
setSetting,
createTask,
getGoal,
listGoals,
listUserProjects,
type Project,
type OutboxRow,
type Question,
type SessionView,
acceptChatLink,
chatGroupBots,
chatLinkCodeBot,
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, postToChat, resumeSession, stopSession } from "@peppa/runner";
import { AsyncLocalStorage } from "node:async_hooks";
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";
import { dropDraft, loadDraft, parseStoryText, saveDraft, splitStory, updateDraft, type Draft } from "./drafts.ts";
import { transcribe, transcribeConfig, TranscribeError } from "./transcribe.ts";
/** Longest voice note the bot transcribes (seconds). */
const VOICE_MAX_SEC = 5 * 60;
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;
/** PEP-85: API client of a user's own bot (tests point it at a second mock). */
userApi?: (token: string) => TelegramApi;
/** How often the list of users' own bots is re-read. */
userBotsIntervalMs?: number;
log?: (msg: string) => void;
}
const HELP = `Я бот Peppa FACTORY. Присылаю вопросы от агентов и сообщения о том, что задача готова или агент ждёт вас.
• Кнопки под сообщением — быстрый ответ.
• Ответ <b>реплаем</b> на сообщение — свой текст, он уйдёт агенту.
• Просто напишите (или наговорите голосом) задачу — я её заведу: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу.
• /status — кто из агентов работает и какие вопросы открыты.
• /digest — сводка за сутки по вашим проектам (каждый день приходит сама; время и что присылать — в Настройках → Уведомления).`;
/** What an agent is doing, in plain words (the same wording as in the web). */
const STATUS_RU: Record<string, string> = {
starting: "запускается",
running: "работает",
waiting_input: "ждёт вашего ответа",
idle: "свободен",
stalled: "остановился — нужна помощь",
rate_limited: "ждёт сброса лимита",
};
const PUSH_MAX_AGE_MS = 30 * 60_000;
const PUSH_TITLE: Record<NotifyEvent, string> = {
questions: "Агент ждёт ответа",
review: "Готово к ревью",
failures: "Агент остановился",
releases: "Обновление продукта",
incidents: "Ошибка в продукте",
chat: "Сообщение в обсуждении",
monitoring: "Мониторинг",
users: "Новый пользователь",
digest: "Сводка",
platform: "Обновления Peppa FACTORY",
};
/** Browser notification text for a question. */
function pushFor(q: Question, event: NotifyEvent, ctx: { taskKey: string | null; taskTitle: string | null }): { title: string; body: string } {
const title = `${ctx.taskKey ? `${ctx.taskKey}: ` : ""}${q.kind === "approval" ? "нужно одобрение" : q.kind === "permission" ? "нужно разрешение" : PUSH_TITLE[event]}`;
const body = q.text.length > 200 ? `${q.text.slice(0, 199)}…` : q.text;
return { title, body };
}
export function createBot(o: BotOptions) {
const { db } = o;
const log = o.log ?? (() => {});
const abort = new AbortController();
// ── PEP-85: users' own bots ────────────────────────────────────────────────────
// Every bot is polled by its own loop; an update is handled inside `via.run(bot)`, so replies
// go out through the bot the message came to. Outside an update (outbox, digests) the bot is
// picked by the chat: the owner's private chat belongs to their bot, everything else — the
// platform's shared bot.
interface OwnBot {
userId: number;
token: string;
api: TelegramApi;
stop: AbortController;
}
const via = new AsyncLocalStorage<OwnBot>();
const ownBots = new Map<number, OwnBot>();
const ownByChat = new Map<number, OwnBot>();
const pick = (chatId?: unknown): TelegramApi => via.getStore()?.api ?? (typeof chatId === "number" ? ownByChat.get(chatId)?.api : undefined) ?? o.api;
/** The same surface as TelegramApi, routed to the right bot per call. */
const api = {
call: <T>(method: string, params: Record<string, unknown> = {}, timeoutMs?: number) => pick(params.chat_id).call<T>(method, params, timeoutMs),
sendMessage: (chatId: number, text: string, extra: Record<string, unknown> = {}) => pick(chatId).sendMessage(chatId, text, extra),
answerCallbackQuery: (id: string, text?: string) => pick().answerCallbackQuery(id, text),
getFile: (fileId: string) => pick().getFile(fileId),
downloadFile: (filePath: string) => pick().downloadFile(filePath),
getMe: () => o.api.getMe(),
getUpdates: (offset: number, timeoutSec: number, signal?: AbortSignal) => o.api.getUpdates(offset, timeoutSec, signal),
};
/** Re-reads the connected bots: starts a poll loop for a new one, stops a removed or re-issued one. */
async function syncOwnBots(): Promise<void> {
const list = await userBots(db);
const seen = new Set<number>();
ownByChat.clear();
for (const b of list) {
seen.add(b.userId);
let bot = ownBots.get(b.userId);
if (bot && bot.token !== b.token) {
bot.stop.abort();
bot = undefined;
}
if (!bot) {
bot = { userId: b.userId, token: b.token, api: (o.userApi ?? ((t) => new TelegramApi(t, process.env.TELEGRAM_API_URL)))(b.token), stop: new AbortController() };
ownBots.set(b.userId, bot);
log(`own bot @${b.username} of user #${b.userId}: polling`);
void ownPollLoop(bot);
}
if (b.chatId != null) ownByChat.set(b.chatId, bot);
}
// PEP-109: a group linked through somebody's own bot is written to by that bot.
for (const g of await chatGroupBots(db)) {
const bot = ownBots.get(g.botUserId);
if (bot && seen.has(g.botUserId)) ownByChat.set(g.tgChatId, bot);
}
for (const [userId, bot] of ownBots) {
if (seen.has(userId)) continue;
bot.stop.abort();
ownBots.delete(userId);
log(`own bot of user #${userId}: stopped`);
}
}
async function ownPollLoop(bot: OwnBot): Promise<void> {
while (!abort.signal.aborted && !bot.stop.signal.aborted) {
try {
let offset = await getOffset(db, bot.userId);
const updates = await bot.api.getUpdates(offset, o.pollTimeoutSec ?? 25, bot.stop.signal);
for (const u of updates) {
await via.run(bot, () => handleUpdate(u));
offset = u.update_id + 1;
await setOffset(db, offset, bot.userId);
}
} catch (e) {
// A revoked token (401) keeps failing: back off instead of hammering Telegram.
log(`own bot #${bot.userId} poll: ${(e as Error).message}`);
await sleep(e instanceof TelegramError && e.code === 401 ? 60_000 : 3000);
}
}
}
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 reaches each person of its project by their notification
* settings (PEP-35): a Telegram message and/or a browser push; every closed one gets an edit.
*/
async function reconcile(): Promise<void> {
const open = await pendingQuestions(db);
const projectsOf = new Map<number, Set<number>>();
const waitingFor = async (userId: number) => {
if (!projectsOf.has(userId)) projectsOf.set(userId, new Set(await userProjectIds(db, userId)));
const ids = projectsOf.get(userId)!;
return open.filter((x) => ids.has(x.projectId)).length;
};
for (const q of open) {
const audience = await projectAudience(db, q.projectId);
if (!audience.length) continue;
const ctx = await context(q);
const event = questionEvent(q, { taskStatus: ctx.taskStatus, sessionStatus: ctx.session?.status });
const r = renderQuestion(q, ctx);
// A push is a "now" signal: questions older than this don't pop up on a fresh subscription.
const fresh = Date.now() - q.createdAt.getTime() < PUSH_MAX_AGE_MS;
const url = ctx.taskKey ? `/t/${ctx.taskKey}` : `/p/${await projectKey(q.projectId)}`;
for (const u of audience) {
await deliverToUser(db, u, {
event,
projectId: q.projectId,
dedupeKey: `q:${q.id}:${u.telegramChatId}`,
pushKey: `q:${q.id}:u${u.id}`,
telegram: { questionId: q.id, params: { text: r.text, parse_mode: "HTML", reply_markup: { inline_keyboard: r.buttons } } },
push: fresh ? { ...pushFor(q, event, ctx), url, tag: `q:${q.id}`, count: await waitingFor(u.id) } : undefined,
urgency: event === "questions" || event === "failures" ? "high" : "normal",
});
}
}
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}`,
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?.();
}
// ── 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<void> {
await syncChats(db);
let cursor = await getSetting<number>(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<void> {
const key = chat.projectId ? await projectKey(chat.projectId) : "";
const where = [master && key ? `[${esc(key)}]` : null, m.threadTitle ? `🧵 <i>${esc(m.threadTitle)}</i>` : 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" ? `<b>${esc(m.authorLogin ?? "?")}</b>${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<string> {
const [p] = await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId));
return p?.key ?? "";
}
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);
}
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<TgMessage | boolean>(row.method, 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);
// Browser pushes (PEP-55) go out of the same loop.
await flushPushOutbox(db, { log });
}
// ── 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>`];
// PEP-123: in plain words — no provider and no spend.
for (const s of sessions) lines.push(`• ${esc(s.taskKey ?? `агент №${s.id}`)} — ${STATUS_RU[s.status] ?? s.status}`);
lines.push("", `<b>Открытых вопросов: ${open.length}</b>`);
// PEP-5: subscription limit windows.
const accounts = await accountUsageForUser(db, user);
lines.push("", "<b>Лимиты</b>", ...(accounts.length ? accounts.map((a) => `• ${esc(describeAccount(a))}`) : ["нет данных о лимитах"]));
return lines.join("\n");
}
// ── stories from messages (PEP-45) ─────────────────────────────────────────────
const cancelRow = (d: Draft): InlineButton[] => [{ text: "✖️ Отмена", callback_data: `d:${d.id}:x` }];
const rows = (buttons: InlineButton[], per = 2) => buttons.reduce<InlineButton[][]>((acc, b, i) => (i % per ? acc[acc.length - 1]!.push(b) : acc.push([b]), acc), []);
const storyLine = (d: Draft) => `«${esc(splitStory(d.text).title)}»`;
/** Send (or, for a button press, edit in place) a bot message with buttons. */
async function show(chatId: number, text: string, buttons: InlineButton[][], editId?: number) {
const params = { chat_id: chatId, text, parse_mode: "HTML", reply_markup: { inline_keyboard: buttons }, link_preview_options: { is_disabled: true } };
if (editId) await api.call("editMessageText", { ...params, message_id: editId }).catch((e) => log(`edit: ${(e as Error).message}`));
else await api.call("sendMessage", params).catch((e) => log(`send: ${(e as Error).message}`));
}
async function askProject(d: Draft, projects: Project[], editId?: number) {
// Most recently active first (the latest story touched), then newest projects.
const touched = new Map<number, number>();
for (const r of await db.select({ projectId: tasks.projectId, at: sql<number>`max(${tasks.updatedAt})` }).from(tasks).groupBy(tasks.projectId)) touched.set(r.projectId, Number(r.at) || 0);
projects = [...projects].sort((a, b) => (touched.get(b.id) ?? 0) - (touched.get(a.id) ?? 0) || b.id - a.id);
const buttons = projects.slice(0, 12).map((p) => ({ text: p.key, callback_data: `d:${d.id}:p:${p.id}` }));
const more = projects.length > 12 ? "\nНет нужного — напишите заново с ключом: «KEY: …»." : "";
await show(d.chatId, `📝 Новая задача ${storyLine(d)}\nВ какой проект?${more}`, [...rows(buttons, 3), cancelRow(d)], editId);
}
async function askEpic(d: Draft, project: Project, editId?: number) {
const epics = (await listGoals(db, project.id)).slice(0, 10);
const buttons = epics.length
? [...epics.map((g) => ({ text: g.title.slice(0, 40), callback_data: `d:${d.id}:g:${g.id}` })), { text: "Без эпика", callback_data: `d:${d.id}:g:0` }]
: [{ text: `✅ Создать в ${project.key}`, callback_data: `d:${d.id}:g:0` }];
await show(d.chatId, `📝 Новая задача в <b>${esc(project.key)}</b>: ${storyLine(d)}${epics.length ? "\nЭпик?" : ""}`, [...rows(buttons), cancelRow(d)], editId);
}
/** A plain message (or a transcribed voice note) → a draft and the next question. */
async function startStory(user: User, chatId: number, text: string, voice: boolean) {
const projects = await listUserProjects(db, user.id);
if (!projects.length) return reply(chatId, `У вас пока нет проектов — создайте первый: ${esc(o.webUrl)}/projects/new`);
const parsed = parseStoryText(text, projects);
if (!parsed.body) return reply(chatId, "Задача пустая. Напишите, что нужно сделать.");
const project = parsed.project ?? (projects.length === 1 ? projects[0]! : null);
const d = await saveDraft(db, { userId: user.id, chatId, text: parsed.body, projectId: project?.id ?? null, voice });
if (project) await askEpic(d, project);
else await askProject(d, projects);
}
async function onVoice(user: User, m: TgMessage) {
const f = m.voice ?? m.audio!;
const cfg = transcribeConfig();
if (!cfg) return reply(m.chat.id, "Голосовые сообщения пока не работают. Напишите задачу текстом.", m.message_id);
if ((f.duration ?? 0) > VOICE_MAX_SEC) return reply(m.chat.id, `Слишком длинное голосовое (больше ${VOICE_MAX_SEC / 60} минут) . Запишите короче или напишите текстом.`, m.message_id);
let text: string;
try {
const file = await api.getFile(f.file_id);
if (!file.file_path) throw new TranscribeError("Telegram не отдал файл");
const audio = await api.downloadFile(file.file_path);
text = await transcribe(cfg, audio, file.file_path.split("/").pop() || "voice.ogg", f.mime_type ?? "audio/ogg");
} catch (e) {
log(`voice: ${(e as Error).message}`);
return reply(m.chat.id, `Не получилось расшифровать голосовое. Напишите задачу текстом.`, m.message_id);
}
if (!text) return reply(m.chat.id, "Не разобрал ни слова. Попробуйте ещё раз или напишите текстом.", m.message_id);
await reply(m.chat.id, `🎙 Расслышал: «${esc(text)}»`, m.message_id);
await startStory(user, m.chat.id, text, true);
}
/** Buttons of a draft (`d:<id>:p:<project>` / `d:<id>:g:<epic|0>` / `d:<id>:x`) and of a new story (`t:<task>:start|keep`). */
async function onStoryButton(user: User, c: TgCallbackQuery, parts: string[]): Promise<string> {
const msgId = c.message?.message_id;
const chatId = c.message!.chat.id;
if (parts[0] === "t") {
const [t] = await db.select().from(tasks).where(eq(tasks.id, Number(parts[1])));
if (!t || !(await canAccess(user, t.projectId))) return "Задача не найдена";
const [project] = await db.select().from(projects).where(eq(projects.id, t.projectId));
const ref = { project: project!, task: t, key: formatTaskKey(project!.key, t.number) };
const head = `📥 ${esc(ref.key)}: ${esc(t.title)}\n${esc(o.webUrl)}/t/${esc(ref.key)}`;
if (parts[2] === "keep") {
await show(chatId, `${head}\nВ бэклоге.`, [], msgId);
return "Оставил в бэклоге";
}
if (parts[2] !== "start") return "Неизвестная кнопка";
if (t.status !== "backlog") {
await show(chatId, `${head}\nУже не в бэклоге (${esc(t.status)}).`, [], msgId);
return `${ref.key} уже ${t.status}`;
}
try {
await moveTask(db, ref, "in_progress");
} catch (e) {
return (e as Error).message;
}
await show(chatId, `${head}\n▶️ В работе — агент взялся.`, [], msgId);
return `${ref.key}: агент взялся ▶️`;
}
const d = await loadDraft(db, Number(parts[1]), user.id);
if (!d) {
await show(chatId, "Черновик устарел. Напишите задачу заново.", [], msgId);
return "Черновик устарел";
}
if (parts[2] === "x") {
await dropDraft(db, d.id);
await show(chatId, `✖️ Отменено: ${storyLine(d)}`, [], msgId);
return "Отменено";
}
if (parts[2] === "p") {
const projectId = Number(parts[3]);
const project = await projectForUser(db, user.id, projectId).catch(() => null);
if (!project) return "Проект не найден";
await updateDraft(db, { ...d, projectId });
await askEpic(d, project, msgId);
return project.key;
}
if (parts[2] === "g" && d.projectId) {
const project = await projectForUser(db, user.id, d.projectId).catch(() => null);
if (!project) return "Проект не найден";
const goalId = Number(parts[3]) || undefined;
if (goalId && !(await getGoal(db, project.id, goalId).catch(() => null))) return "Эпик не найден";
const { title, rest } = splitStory(d.text);
const from = `Создано из Telegram (${user.login}${d.voice ? ", расшифровка голосового" : ""}).`;
const ref = await createTask(db, { projectId: project.id, goalId, title, description: `${rest ? `${rest}\n\n` : ""}${from}` });
await dropDraft(db, d.id);
await show(
chatId,
`📥 Создал <b>${esc(ref.key)}</b>: ${esc(title)}\n${esc(o.webUrl)}/t/${esc(ref.key)}\nВзять в работу сейчас?`,
[[{ text: "▶️ Взять в работу", callback_data: `t:${ref.task.id}:start` }, { text: "Оставить в бэклоге", callback_data: `t:${ref.task.id}:keep` }]],
msgId,
);
return `Создал ${ref.key}`;
}
return "Неизвестная кнопка";
}
/** Is the update being handled by the bot this chat's group is linked through? */
const linkedHere = (chat: Chat) => (chat.tgBotUserId ?? null) === (via.getStore()?.userId ?? null);
/** 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) {
const code = link[2]!;
// PEP-109: a command without @bot reaches every bot of the group — a code issued for
// another bot is that bot's business, this one keeps quiet.
const codeBot = isChatLinkCode(code) ? await chatLinkCodeBot(db, o.secret, code) : undefined;
if (!link[1] && codeBot !== undefined && codeBot !== (via.getStore()?.userId ?? null)) return "ignored";
if (!isChatLinkCode(code)) return reply(m.chat.id, "Это не код связки чата. Получи код в вебе: Чаты → «Связать с Telegram».").then(() => "done");
const chat = await acceptChatLink(db, o.secret, code, { tgChatId: m.chat.id, title: m.chat.title ?? null, botUserId: via.getStore()?.userId });
if (!chat) return reply(m.chat.id, "Код связки неверный или истёк — получи новый в вебе: Чаты → «Связать с Telegram».").then(() => "done");
await syncOwnBots().catch(() => {}); // the group now belongs to this bot
const name = chat.projectId ? `чатом проекта ${esc(await projectKey(chat.projectId))}` : "мастер-чатом";
await reply(m.chat.id, `Группа связана с ${name} ✅\n\nСюда будут приходить события и вопросы агентов, треды — цепочками ответов. Ответьте <b>реплаем</b> — сообщение уйдёт в тред (в переписке по задаче — агенту). Отвечать могут те, кто привязал Telegram в Peppa FACTORY и имеет доступ к проекту. /help — команды.`);
return "done";
}
const chat = await chatByTelegram(db, m.chat.id);
if (!chat || !m.from || !text) return "ignored";
// PEP-109: the group is served by the bot it is linked through; another bot in it stays silent.
if (!linkedHere(chat)) 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 ? "У вас нет доступа к этому чату." : `Не нашёл вас в Peppa FACTORY — привяжите 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);
await syncOwnBots().catch(() => {});
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) {
const b = await acceptPairing(db, o.secret, start[1], { chatId: m.chat.id, userId: m.from.id, username: m.from.username, botUserId: via.getStore()?.userId });
if (b) {
await syncOwnBots().catch(() => {}); // the chat now belongs to this bot
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";
// PEP-85: a user's own bot serves its owner only.
const own = via.getStore();
if (own && own.userId !== user.id) return "ignored";
// PEP-48: what follows is done by this user through Telegram.
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
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 (/^\/digest\b/.test(text)) {
const d = await buildDigest(db, user);
await api.sendMessage(m.chat.id, renderDigest(d, { webUrl: o.webUrl, title: "Сводка за сутки" }), { link_preview_options: { is_disabled: true } }).catch((e) => log(`digest: ${e.message}`));
return "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";
}
if (m.voice || m.audio) {
await onVoice(user, m);
return "done";
}
if (!text || text.startsWith("/")) {
await reply(m.chat.id, "Чтобы ответить агенту, ответьте <b>реплаем</b> на его сообщение. Чтобы завести задачу — просто напишите её. /help — что я умею.");
return "done";
}
// PEP-45: any other text is a new story (created only after a button press).
await startStory(user, m.chat.id, text, false);
return "done";
}
async function onCallback(c: TgCallbackQuery): Promise<"done" | "ignored"> {
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 found = await chatByTelegram(db, c.message.chat.id);
const chat = found && linkedHere(found) ? found : null;
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";
}
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
const parts = (c.data ?? "").split(":");
if (parts[0] === "d" || parts[0] === "t") {
const toast = await onStoryButton(user, c, parts).catch((e) => (log(`story: ${(e as Error).stack ?? e}`), "Ошибка"));
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
return "done";
}
const [kind, idStr, choice] = parts;
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");
// PEP-127: over a conflict the accept is remembered and carried through.
toast = ref.pending ? `${ref.key}: принято ✅ Агент обновляет изменения, задача закроется сама` : `${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 = "Агент продолжил работу 🔁";
void r;
} 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> {
const botUserId = via.getStore()?.userId;
if (!(await claimUpdate(db, u.update_id, botUserId))) 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, botUserId);
} catch (e) {
log(`update ${u.update_id}: ${(e as Error).stack ?? e}`);
void reportPlatformError(db, e, { service: "bot", where: u.message ? "message" : u.callback_query ? `button ${u.callback_query.data ?? ""}`.slice(0, 60) : "update" });
await finishUpdate(db, u.update_id, "failed", botUserId);
}
}
// ── 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 ownBotsLoop() {
while (!abort.signal.aborted) {
await syncOwnBots().catch((e) => log(`own bots: ${(e as Error).message}`));
await sleep(o.userBotsIntervalMs ?? 10_000);
}
}
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,
syncOwnBots,
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());
await syncOwnBots().catch((e) => log(`own bots: ${(e as Error).message}`));
loops = Promise.all([pollLoop(), outboxLoop(), reconcileLoop(), changesLoop(), monitorLoop(), ownBotsLoop()]);
return me;
},
async stop() {
abort.abort();
for (const b of ownBots.values()) b.stop.abort();
wakeOutbox?.();
await unlisten?.().catch(() => {});
await loops;
},
};
}
export type Bot = ReturnType<typeof createBot>;