715 lines
35 KiB
TypeScript
715 lines
35 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 {
|
||
accountUsageForUser,
|
||
describeUsage,
|
||
usageTotals,
|
||
describeAccount,
|
||
enterActor,
|
||
acceptPairing,
|
||
beat,
|
||
checkServices,
|
||
claimUpdate,
|
||
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,
|
||
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 { 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;
|
||
log?: (msg: string) => void;
|
||
}
|
||
|
||
const HELP = `Я бот Пеппы. Присылаю вопросы от агентов: одобрения proposal, вопросы, разрешения и сигналы, что сессия ждёт тебя.
|
||
|
||
• Кнопки под сообщением — быстрый ответ.
|
||
• Ответ <b>реплаем</b> на сообщение — свой текст, он уйдёт прямо в сессию.
|
||
• Просто напиши (или наговори голосом) задачу — я заведу стори: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу.
|
||
• /status — активные сессии и открытые вопросы.
|
||
• /digest — сводка за сутки по твоим проектам (каждый день приходит сама; время и что присылать — в Настройках → Уведомления).`;
|
||
|
||
const PUSH_MAX_AGE_MS = 30 * 60_000;
|
||
|
||
const PUSH_TITLE: Record<NotifyEvent, string> = {
|
||
questions: "Агент ждёт ответа",
|
||
review: "Готово к ревью",
|
||
failures: "Раннер остановился",
|
||
releases: "Релиз",
|
||
incidents: "Ошибка в проде",
|
||
monitoring: "Мониторинг",
|
||
digest: "Сводка",
|
||
platform: "Обновления Пеппы",
|
||
};
|
||
|
||
/** 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, 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 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>`];
|
||
for (const s of sessions) lines.push(`• ${esc(s.taskKey ?? `#${s.id}`)} — ${s.status} (${s.provider})${usageTotals(s.usage).hasData ? ` · ${esc(describeUsage(s.usage))}` : ""}`);
|
||
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, `Не получилось расшифровать голосовое (${esc((e as Error).message)}). Напиши текстом.`, 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 "Неизвестная кнопка";
|
||
}
|
||
|
||
/** 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) {
|
||
if (!isChatLinkCode(link[1]!)) return reply(m.chat.id, "Это не код связки чата. Получи код в вебе: Чаты → «Связать с Telegram».").then(() => "done");
|
||
const chat = await acceptChatLink(db, o.secret, link[1]!, { tgChatId: m.chat.id, title: m.chat.title ?? null });
|
||
if (!chat) return reply(m.chat.id, "Код связки неверный или истёк — получи новый в вебе: Чаты → «Связать с Telegram».").then(() => "done");
|
||
const name = chat.projectId ? `чатом проекта ${esc(await projectKey(chat.projectId))}` : "мастер-чатом";
|
||
await reply(m.chat.id, `Группа связана с ${name} ✅\n\nСюда будут приходить события и вопросы агентов, треды — цепочками ответов. Ответь <b>реплаем</b> — сообщение уйдёт в тред (в треде стори — агенту). Отвечать могут те, кто привязал Telegram в Пеппе и имеет доступ к проекту. /help — команды.`);
|
||
return "done";
|
||
}
|
||
const chat = await chatByTelegram(db, m.chat.id);
|
||
if (!chat || !m.from || !text) 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 ? "У тебя нет доступа к этому чату." : `Не знаю тебя в Пеппе — привяжи 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);
|
||
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 });
|
||
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";
|
||
// 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 chat = await chatByTelegram(db, c.message.chat.id);
|
||
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");
|
||
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>;
|