peppa/apps/bot/src/bot.ts
2026-11-16 13:30:48 +05:00

1111 lines
58 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 { LOCALIZED_PARAM, localizeMessage, questionIsFreeText, reportPlatformError, telegramChatLocale } from "@peppa/core";
import { asIs, localizeRoleMessage, m as tr, stripAsIs } from "@peppa/shared/i18n";
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,
needsPerson,
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,
isRepeatEdit,
getOutbox,
lastRepeatEdit,
questionStates,
repeatEditKey,
sentQuestionMessages,
telegramAccountUser,
threadAnchor,
type Chat,
type ChatMessage,
} from "@peppa/core";
import { projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey, voiceStoriesEnabled } 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 "@peppa/core";
import { addFeedbackScreenshot, FEEDBACK_MAX_SHOTS, fixFeedback, isSuperadmin, linkFeedback, PeppaError, rejectFeedback, submitFeedback } from "@peppa/core";
import { readFileSync } from "node:fs";
import { basename } from "node:path";
import { askRejectReason, clearReject, closeFeedbackMode, feedbackMode, keepFeedbackMode, openFeedbackMode, pendingReject } from "./feedback.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;
/** PEP-151: a delivered message is refreshed for a repeated state at most this often (5 min). */
repeatEditMs?: 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;
}
// One key per line: localizeMessage translates a multi-line message line by line.
const helpText = (voice: boolean) => [
tr("Я бот Peppa FACTORY. Присылаю вопросы от агентов и сообщения о том, что задача готова или агент ждёт вас."),
"",
tr("• Кнопки под сообщением — быстрый ответ."),
tr("• Ответ <b>реплаем</b> на сообщение — свой текст, он уйдёт агенту."),
voice
? tr("• Просто напишите (или наговорите голосом) задачу — я её заведу: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу.")
: tr("• Просто напишите задачу — я её заведу: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу."),
tr("• /status — кто из агентов работает и какие вопросы открыты."),
tr("• /problem — сообщить о проблеме в Peppa FACTORY: напишите, что случилось, и приложите фото экрана."),
tr("• /digest — сводка за сутки по вашим проектам (каждый день приходит сама; время и что присылать — в Настройках → Уведомления)."),
].join("\n");
/** What an agent is doing, in plain words (the same wording as in the web). */
const STATUS_RU: Record<string, string> = {
starting: tr("запускается"),
running: tr("работает"),
waiting_input: tr("ждёт вашего ответа"),
idle: tr("свободен"),
stalled: tr("остановился — нужна помощь"),
rate_limited: tr("ждёт сброса лимита"),
};
const PUSH_MAX_AGE_MS = 30 * 60_000;
const PUSH_TITLE: Record<NotifyEvent, string> = {
questions: tr("Агент ждёт ответа"),
review: tr("Готово к ревью"),
failures: tr("Агент остановился"),
releases: tr("Обновление продукта"),
incidents: tr("Ошибка в продукте"),
chat: tr("Сообщение в обсуждении"),
monitoring: tr("Мониторинг"),
users: tr("Новый пользователь"),
feedback: tr("Обращение пользователя"),
digest: tr("Сводка"),
platform: tr("Обновления 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 what = q.kind === "approval" ? tr("нужно одобрение") : q.kind === "permission" ? tr("нужно разрешение") : PUSH_TITLE[event];
const title = ctx.taskKey ? `${ctx.taskKey}: ${what}` : what;
const short = q.text.length > 200 ? `${q.text.slice(0, 199)}…` : q.text;
return { title, body: questionIsFreeText(q) ? asIs(short) : short };
}
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;
// ── PEP-98: messages go out in the reader's language ─────────────────────────────
// Texts are rendered in Russian everywhere (core, runner, this file); right before the Bot API
// call the text, caption and button labels are translated for the chat's user.
const readerChat = new AsyncLocalStorage<number>();
/** PEP-139: the marks around free text never reach Telegram (the translation takes them off itself). */
const unmarked = (params: Record<string, unknown>): Record<string, unknown> => {
const raw = JSON.stringify(params);
return raw.includes("\u2068") || raw.includes("\u2069") ? (JSON.parse(stripAsIs(raw)) as Record<string, unknown>) : params;
};
const localizeParams = async (params: Record<string, unknown>): Promise<Record<string, unknown>> => {
if (LOCALIZED_PARAM in params) {
// PEP-138: written for this reader already (an AI role's message with free text inside).
const { [LOCALIZED_PARAM]: _done, ...rest } = params;
return unmarked(rest);
}
const chatId = typeof params.chat_id === "number" ? params.chat_id : readerChat.getStore();
if (chatId == null) return unmarked(params);
const locale = await telegramChatLocale(db, chatId).catch(() => "ru" as const);
if (locale === "ru") return unmarked(params);
const loc = (v: unknown) => (typeof v === "string" ? localizeMessage(locale, v) : v);
const out: Record<string, unknown> = { ...params, text: loc(params.text), caption: loc(params.caption) };
if (params.text === undefined) delete out.text;
if (params.caption === undefined) delete out.caption;
const markup = params.reply_markup as { inline_keyboard?: { text: string }[][]; keyboard?: ({ text: string } | string)[][] } | undefined;
if (markup && typeof markup === "object") {
const btn = <B,>(b: B): B => (typeof b === "string" ? (loc(b) as B) : b && typeof b === "object" && "text" in b ? ({ ...b, text: loc((b as { text: string }).text) } as B) : b);
out.reply_markup = {
...markup,
...(markup.inline_keyboard ? { inline_keyboard: markup.inline_keyboard.map((row) => row.map(btn)) } : {}),
...(markup.keyboard ? { keyboard: markup.keyboard.map((row) => row.map(btn)) } : {}),
};
}
return out;
};
/** The same surface as TelegramApi, routed to the right bot per call. */
const api = {
call: async <T,>(method: string, params: Record<string, unknown> = {}, timeoutMs?: number) => pick(params.chat_id).call<T>(method, await localizeParams(params), timeoutMs),
sendMessage: async (chatId: number, text: string, extra: Record<string, unknown> = {}) => {
const p = await localizeParams({ ...extra, chat_id: chatId, text });
return pick(chatId).sendMessage(chatId, p.text as string, p);
},
answerCallbackQuery: async (id: string, text?: string) => pick().answerCallbackQuery(id, text === undefined ? undefined : ((await localizeParams({ text })).text as string)),
sendPhoto: async (chatId: number, photo: { data: Uint8Array; filename: string; mime: string }, extra: Record<string, unknown> = {}) => {
const p = await localizeParams({ ...extra, chat_id: chatId });
return pick(chatId).sendPhoto(chatId, photo, p);
},
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 states = await questionStates(db, open.map((q) => q.id));
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) && waits.has(x.id)).length;
};
// PEP-149: what waits for a person — questions and finished stories; only these push and count.
const ctxOf = new Map<number, Awaited<ReturnType<typeof context>>>();
const waits = new Set<number>();
for (const q of open) {
const c = await context(q);
ctxOf.set(q.id, c);
if (needsPerson(q, c.taskStatus)) waits.add(q.id);
}
for (const q of open) {
const audience = await projectAudience(db, q.projectId);
if (!audience.length) continue;
const ctx = ctxOf.get(q.id)!;
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 && waits.has(q.id) ? { ...pushFor(q, event, ctx), url, tag: `q:${q.id}`, count: await waitingFor(u.id) } : undefined,
urgency: event === "questions" || event === "failures" ? "high" : "normal",
});
}
// PEP-151: the same state came again — no new message; the one already delivered gets the
// fresh text and its buttons back, at most once in `repeatEditMs`.
const repeats = states.get(q.id)?.repeats ?? 0;
if (!repeats) continue;
for (const sent of await sentQuestionMessages(db, q.id)) {
const key = repeatEditKey(sent.id, repeats);
if (await getOutbox(db, key)) continue;
const last = await lastRepeatEdit(db, sent.id);
if (last && Date.now() - last.getTime() < (o.repeatEditMs ?? 5 * 60_000)) continue;
await enqueueTelegram(db, {
dedupeKey: key,
method: "editMessageText",
questionId: q.id,
params: { chat_id: sent.params.chat_id, message_id: sent.telegramMessageId, text: r.text, parse_mode: "HTML", link_preview_options: { is_disabled: true }, reply_markup: { inline_keyboard: r.buttons } },
});
}
}
await mirrorChats().catch((e) => log(`chats: ${(e as Error).message}`));
const answered = await answeredQuestionMessages(db, new Date(Date.now() - 24 * 3600_000));
const answeredStates = await questionStates(db, answered.map((a) => a.q.id));
for (const { sent, q } of answered) {
// PEP-151: a question that came again is answered again — each round closes the message anew.
const round = answeredStates.get(q.id)?.repeats ?? 0;
await enqueueTelegram(db, {
dedupeKey: round ? `qa:${q.id}:r${round}:${sent.params.chat_id}` : `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(round ? renderQuestion(q, await context(q)).text : 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 {
// PEP-139: a person's words go as written; an AI role's message gets its fixed lines in the
// group's language and is then free text too. Events are factory phrases (free parts are
// marked where the event text is built) and are translated when sent.
const role = m.kind === "user" && m.authorKind === "agent";
const inRole = role ? await telegramChatLocale(db, tgChatId).catch(() => "ru" as const) : null;
const own = (s: string) => (inRole ? localizeRoleMessage(inRole, s) : s);
// A note the factory itself writes into a discussion (authorKind system) is a phrase, not free text.
const free = m.kind === "user" && m.authorKind !== "system";
const said = free ? asIs(esc(own(m.text).slice(0, 3500))) : esc(m.text.slice(0, 3500));
const login = own(m.authorLogin ?? "?");
const who = m.kind === "user" ? `<b>${asIs(esc(login))}</b>` : m.authorKind === "agent" ? "🤖 " : "";
const body = m.kind === "user" ? (m.via === "telegram" ? `: ${said}` : tr(" (веб): {text}", { text: said })) : said;
text = `${where ? `${where}\n` : ""}${who}${body}${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);
}
if (isRepeatEdit(row) && row.questionId) {
// PEP-151: answered while the refresh waited — the buttons must not come back.
const q = await getQuestion(db, row.questionId).catch(() => null);
if (!q || q.answeredAt) return markOutboxSent(db, row, 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 {
if (row.method === "sendPhoto") {
// PEP-143: a local file (a report's screenshot) uploaded as a photo.
const { photo_path: path, chat_id: chatId, ...extra } = params as { photo_path?: string; chat_id: number };
let data: Buffer;
try {
data = readFileSync(String(path));
} catch {
return markOutboxRetry(db, { ...row, attempts: 99 }, "file is gone");
}
const ext = basename(String(path)).split(".").pop() ?? "png";
const sent = await api.sendPhoto(chatId, { data, filename: `screenshot.${ext}`, mime: ext === "jpg" ? "image/jpeg" : `image/${ext}` }, extra);
return markOutboxSent(db, row, sent.message_id);
}
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" ? tr("Уже отвечено: {answer}", { answer: fresh.answer }) : tr("Уже отвечено ({via}): {answer}", { via: fresh.answeredVia, answer: fresh.answer });
const { delivered } = await answerAndDeliver(db, q.id, text, "telegram");
scheduleReconcile();
return delivered ? tr("Отправлено агенту ✅") : tr("Ответ сохранён. Агент сейчас не работает — он увидит ответ, когда вернётся к задаче.");
}
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>" + tr("Агентов за работой: {n}", { n: sessions.length }) + "</b>"];
// PEP-123: in plain words — no provider and no spend.
for (const s of sessions) {
const who = s.taskKey ?? tr("агент №{id}", { id: s.id });
lines.push(`• ${esc(who)} — ${STATUS_RU[s.status] ?? s.status}`);
}
lines.push("", "<b>" + tr("Открытых вопросов: {n}", { n: open.length }) + "</b>");
// PEP-5: subscription limit windows.
const accounts = await accountUsageForUser(db, user);
lines.push("", "<b>" + tr("Лимиты") + "</b>", ...(accounts.length ? accounts.map((a) => `• ${esc(describeAccount(a))}`) : [tr("нет данных о лимитах")]));
return lines.join("\n");
}
// ── stories from messages (PEP-45) ─────────────────────────────────────────────
const cancelRow = (d: Draft): InlineButton[] => [{ text: tr("✖️ Отмена"), 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) => `«${asIs(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 text = [tr("📝 Новая задача {title}", { title: storyLine(d) }), tr("В какой проект?"), projects.length > 12 ? tr("Нет нужного — напишите заново с ключом: «KEY: …».") : null];
await show(d.chatId, text.filter((l) => l != null).join("\n"), [...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: asIs(g.title.slice(0, 40)), callback_data: `d:${d.id}:g:${g.id}` })), { text: tr("Без эпика"), callback_data: `d:${d.id}:g:0` }]
: [{ text: tr("✅ Создать в {key}", { key: project.key }), callback_data: `d:${d.id}:g:0` }];
const text = tr("📝 Новая задача в <b>{key}</b>: {title}", { key: esc(project.key), title: storyLine(d) }) + (epics.length ? "\n" + tr("Эпик?") : "");
await show(d.chatId, text, [...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, tr("У вас пока нет проектов — создайте первый: {url}/projects/new", { url: esc(o.webUrl) }));
const parsed = parseStoryText(text, projects);
if (!parsed.body) return reply(chatId, tr("Задача пустая. Напишите, что нужно сделать."));
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);
}
/** Text of a voice note; null — it could not be heard, and the user has been told. */
async function voiceText(m: TgMessage): Promise<string | null> {
const f = m.voice ?? m.audio!;
const cfg = transcribeConfig();
if (!cfg) return reply(m.chat.id, tr("Голосовые сообщения пока не работают. Напишите задачу текстом."), m.message_id).then(() => null);
if ((f.duration ?? 0) > VOICE_MAX_SEC) return reply(m.chat.id, tr("Слишком длинное голосовое (больше {n} минут) . Запишите короче или напишите текстом.", { n: VOICE_MAX_SEC / 60 }), m.message_id).then(() => null);
let text: string;
try {
const file = await api.getFile(f.file_id);
if (!file.file_path) throw new TranscribeError(tr("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, tr("Не получилось расшифровать голосовое. Напишите задачу текстом."), m.message_id).then(() => null);
}
if (!text) return reply(m.chat.id, tr("Не разобрал ни слова. Попробуйте ещё раз или напишите текстом."), m.message_id).then(() => null);
await reply(m.chat.id, tr("🎙 Расслышал: «{text}»", { text: asIs(esc(text)) }), m.message_id);
return text;
}
async function onVoice(user: User, m: TgMessage) {
const text = await voiceText(m);
if (text) await startStory(user, m.chat.id, text, true);
}
// ── «Сообщить о проблеме» (PEP-143) ────────────────────────────────────────────
/** The picture of a message: the largest size of a photo, or an image sent as a file. */
const pictureOf = (m: TgMessage) => m.photo?.at(-1) ?? (m.document?.mime_type?.startsWith("image/") ? m.document : undefined);
async function downloadPicture(m: TgMessage): Promise<Buffer | null> {
const ref = pictureOf(m);
if (!ref) return null;
const file = await api.getFile(ref.file_id);
if (!file.file_path) throw new PeppaError(tr("Telegram не отдал файл"));
return api.downloadFile(file.file_path);
}
/**
* A message while «Сообщить о проблеме» is on: the first one becomes the report, photos
* right after it join it. "pass" — not about the report, handle the message as usual.
*/
async function onFeedbackMessage(user: User, m: TgMessage, text: string): Promise<"done" | "pass"> {
const mode = await feedbackMode(db, user.id);
if (!mode) return "pass";
const picture = pictureOf(m);
try {
if (mode.feedbackId) {
// The report exists: only more pictures belong to it.
if (!picture || text) return closeFeedbackMode(db, user.id).then(() => "pass" as const);
const added = await addFeedbackScreenshot(db, user, mode.feedbackId, (await downloadPicture(m))!);
if (!added) await reply(m.chat.id, tr("К этому обращению скриншот уже не приложить (не больше {n}). Чтобы начать новое, отправьте /problem.", { n: FEEDBACK_MAX_SHOTS }), m.message_id);
else await keepFeedbackMode(db, user.id, mode.feedbackId);
return "done";
}
if (text.startsWith("/")) return closeFeedbackMode(db, user.id).then(() => "pass" as const);
let said = text || m.caption?.trim() || "";
if (!said && (m.voice || m.audio)) {
const heard = await voiceText(m);
if (!heard) return "done";
said = heard;
}
if (!said && !picture) {
await reply(m.chat.id, tr("Напишите, что случилось, или приложите скриншот."), m.message_id);
return "done";
}
const data = picture ? await downloadPicture(m) : null;
const f = await submitFeedback(db, user, { text: said, via: "telegram", files: data ? [data] : [], context: { locale: await telegramChatLocale(db, m.chat.id).catch(() => undefined) } });
await keepFeedbackMode(db, user.id, f.id);
await reply(
m.chat.id,
// glossary-ignore: «команда» here is the team of people, not a terminal command
[tr("Спасибо, передали команде. Обращение №{id}.", { id: f.id }), tr("Можно прислать ещё скриншоты — до {n} на обращение.", { n: FEEDBACK_MAX_SHOTS }), tr("Ваши обращения: {url}/feedback", { url: esc(o.webUrl) })].join("\n"),
m.message_id,
);
} catch (e) {
if (!(e instanceof PeppaError)) throw e;
await reply(m.chat.id, esc(e.message), m.message_id);
}
return "done";
}
/** A superadmin's buttons under a report: `f:<id>:o<N>` (a story from option N), `dup`, `no`. */
async function onFeedbackButton(user: User, c: TgCallbackQuery, parts: string[]): Promise<string> {
const id = Number(parts[1]);
const chatId = c.message!.chat.id;
const settle = async (line: string) => {
await api.call("editMessageReplyMarkup", { chat_id: chatId, message_id: c.message!.message_id, reply_markup: { inline_keyboard: [] } }).catch(() => {});
await reply(chatId, line, c.message!.message_id);
};
try {
const option = /^o(\d)$/.exec(parts[2] ?? "");
if (option) {
const ref = await fixFeedback(db, user, id, Number(option[1]));
await settle([tr("✅ Обращение №{id}: заведена задача <b>{key}</b>", { id, key: esc(ref.key) }), `${esc(o.webUrl)}/t/${esc(ref.key)}`].join("\n"));
return tr("Заведена задача {key}", { key: ref.key });
}
if (parts[2] === "dup") {
const ref = await linkFeedback(db, user, id);
await settle(tr("🔗 Обращение №{id} связано с задачей <b>{key}</b>", { id, key: esc(ref.key) }));
return tr("Связано с {key}", { key: ref.key });
}
if (parts[2] === "no") {
if (!(await isSuperadmin(db, user))) return tr("Обращение не найдено");
await askRejectReason(db, user.id, id);
await reply(chatId, tr("Напишите причину одним сообщением — её увидит автор обращения №{id}. Чтобы отклонить без причины, отправьте «-».", { id }), c.message!.message_id);
return tr("Жду причину");
}
} catch (e) {
if (!(e instanceof PeppaError)) throw e;
return e.message;
}
return tr("Неизвестная кнопка");
}
/** 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 tr("Задача не найдена");
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)}: ${asIs(esc(t.title))}\n${esc(o.webUrl)}/t/${esc(ref.key)}`;
if (parts[2] === "keep") {
await show(chatId, head + "\n" + tr("В бэклоге."), [], msgId);
return tr("Оставил в бэклоге");
}
if (parts[2] !== "start") return tr("Неизвестная кнопка");
if (t.status !== "backlog") {
await show(chatId, head + "\n" + tr("Уже не в бэклоге ({status}).", { status: esc(t.status) }), [], msgId);
return tr("{key} уже {status}", { key: ref.key, status: t.status });
}
try {
await moveTask(db, ref, "in_progress");
} catch (e) {
return (e as Error).message;
}
await show(chatId, head + "\n" + tr("▶️ В работе — агент взялся."), [], msgId);
return tr("{key}: агент взялся ▶️", { key: ref.key });
}
const d = await loadDraft(db, Number(parts[1]), user.id);
if (!d) {
await show(chatId, tr("Черновик устарел. Напишите задачу заново."), [], msgId);
return tr("Черновик устарел");
}
if (parts[2] === "x") {
await dropDraft(db, d.id);
await show(chatId, tr("✖️ Отменено: {title}", { title: storyLine(d) }), [], msgId);
return tr("Отменено");
}
if (parts[2] === "p") {
const projectId = Number(parts[3]);
const project = await projectForUser(db, user.id, projectId).catch(() => null);
if (!project) return tr("Проект не найден");
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 tr("Проект не найден");
const goalId = Number(parts[3]) || undefined;
if (goalId && !(await getGoal(db, project.id, goalId).catch(() => null))) return tr("Эпик не найден");
const { title, rest } = splitStory(d.text);
const from = d.voice ? tr("Создано из Telegram ({login}, расшифровка голосового).", { login: user.login }) : tr("Создано из Telegram ({login}).", { login: user.login });
const ref = await createTask(db, { projectId: project.id, goalId, title, description: `${rest ? `${rest}\n\n` : ""}${from}` });
await dropDraft(db, d.id);
await show(
chatId,
[tr("📥 Создал <b>{key}</b>: {title}", { key: esc(ref.key), title: asIs(esc(title)) }), `${esc(o.webUrl)}/t/${esc(ref.key)}`, tr("Взять в работу сейчас?")].join("\n"),
[[{ text: tr("▶️ Взять в работу"), callback_data: `t:${ref.task.id}:start` }, { text: tr("Оставить в бэклоге"), callback_data: `t:${ref.task.id}:keep` }]],
msgId,
);
return tr("Создал {key}", { key: ref.key });
}
return tr("Неизвестная кнопка");
}
/** 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, tr("Это не код связки чата. Получи код в вебе: Чаты → «Связать с 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, tr("Код связки неверный или истёк — получи новый в вебе: Чаты → «Связать с Telegram».")).then(() => "done");
await syncOwnBots().catch(() => {}); // the group now belongs to this bot
const name = chat.projectId ? tr("чатом проекта {key}", { key: esc(await projectKey(chat.projectId)) }) : tr("мастер-чатом");
await reply(
m.chat.id,
[
tr("Группа связана с {name} ✅", { name }),
"",
tr("Сюда будут приходить события и вопросы агентов, треды — цепочками ответов. Ответьте <b>реплаем</b> — сообщение уйдёт в тред (в переписке по задаче — агенту). Отвечать могут те, кто привязал Telegram в Peppa FACTORY и имеет доступ к проекту. /help — команды."),
].join("\n"),
);
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 ? tr("У вас нет доступа к этому чату.") : tr("Не нашёл вас в Peppa FACTORY — привяжите Telegram: {url}/settings → Telegram.", { url: esc(o.webUrl) }), 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, tr("Привязано ✅") + "\n\n" + helpText(voiceStoriesEnabled()));
scheduleReconcile();
return "done";
}
await reply(m.chat.id, tr("Код привязки неверный или истёк. Получи новый: {url}/settings → Telegram", { url: esc(o.webUrl) }));
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, helpText(voiceStoriesEnabled())).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: tr("Сводка за сутки") }), { link_preview_options: { is_disabled: true } }).catch((e) => log(`digest: ${e.message}`));
return "done";
}
// PEP-143: «Сообщить о проблеме».
if (/^\/(problem|feedback)\b/.test(text)) {
await openFeedbackMode(db, user.id);
await reply(m.chat.id, [tr("Опишите, что случилось, одним сообщением — текстом, фото экрана с подписью или голосом."), tr("Мы передадим это тем, кто делает Peppa FACTORY.")].join("\n"));
return "done";
}
// A superadmin pressed «Не исправлять»: this message is the reason.
const rejecting = text && !text.startsWith("/") ? await pendingReject(db, user.id) : null;
if (rejecting != null) {
await clearReject(db, user.id);
try {
await rejectFeedback(db, user, rejecting, text === "-" ? null : text);
await reply(m.chat.id, tr("Обращение №{id} отклонено, автор получит ответ.", { id: rejecting }), m.message_id);
} catch (e) {
await reply(m.chat.id, esc((e as Error).message), m.message_id);
}
wakeOutbox?.();
return "done";
}
if (!m.reply_to_message && (await onFeedbackMessage(user, m, text)) === "done") 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, tr("Не нашёл вопрос для этого сообщения."), 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 (pictureOf(m)) {
await reply(m.chat.id, tr("Чтобы сообщить о проблеме в Peppa FACTORY, сначала отправьте /problem, а потом фото."), m.message_id);
return "done";
}
if (!text || text.startsWith("/")) {
await reply(m.chat.id, tr("Чтобы ответить агенту, ответьте <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, tr("Нет доступа")).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}`), tr("Ошибка")));
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
return "done";
}
if (parts[0] === "f") {
const toast = await onFeedbackButton(user, c, parts).catch((e) => (log(`feedback: ${(e as Error).stack ?? e}`), tr("Ошибка")));
wakeOutbox?.();
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 = tr("Неизвестная кнопка");
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" ? tr("Агент не найден") : kind === "i" ? tr("Ошибка не найдена") : tr("Вопрос не найден")).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 ? tr("{key}: принято ✅ Изменения обновляются, задача закроется сама", { key: ref.key }) : tr("{key} принята ✅", { 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;
// PEP-149: the «continue» button of an earlier message answers nothing.
toast = q && text ? await answer(q, text) : q && choice === "cont" ? tr("Кнопка устарела — ответьте на сообщение текстом.") : tr("Вопрос не найден");
} 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 ? (choice === "start" ? tr("{key}: агент взялся ▶️", { key: r.task.key }) : tr("{key}: в бэклоге 📥", { key: r.task.key })) : tr("Игнорируем 🙈");
} catch (e) {
toast = (e as Error).message;
}
wakeOutbox?.();
} else if (kind === "s") {
const s = await getSession(db, id).catch(() => null);
if (!s) toast = tr("Агент не найден");
else if (choice === "resume") {
try {
const r = await resumeSession(db, s.id);
toast = tr("Агент продолжил работу 🔁");
void r;
} catch (e) {
toast = (e as Error).message;
}
} else if (choice === "stop") {
await stopSession(db, s.id);
toast = tr("Агент остановлен ⏹");
}
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> {
// PEP-98: the person who sent the update reads the toasts and replies without a chat_id.
const reader = u.callback_query?.from?.id ?? u.message?.from?.id ?? u.message?.chat?.id;
if (reader != null) return readerChat.run(reader, () => handleUpdateIn(u));
return handleUpdateIn(u);
}
async function handleUpdateIn(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>;