«Peppa FACTORY» → «FORGE» в экранах, сообщениях, словарях en/kk, шаблоне и тестах; «Пеппа» → «FORGE» в подсказках агентам и правилах; логотип, значок, версия кэша service worker; в словаре старые названия — в «Нельзя». Внутренние имена (CLI peppa, PEPPA_*, MCP-сервер peppa, ключи PEP-N) не меняются. Второй адрес — в mac-route.sh. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1213 lines
65 KiB
TypeScript
1213 lines
65 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 { acceptDigestHold, duringPause, heldForDigest, isProjectPaused, LOCALIZED_PARAM, localizeMessage, messageDetails, 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,
|
||
agentSignature,
|
||
getQuestion,
|
||
questionAuthor,
|
||
getSession,
|
||
listSessions,
|
||
markOutboxRetry,
|
||
markOutboxSent,
|
||
pendingQuestions,
|
||
getUiMode,
|
||
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 { delayAction, resolveTaskById } from "@peppa/runner";
|
||
import { parseDelayCallback } from "@peppa/core";
|
||
import { acceptTask, answerAndDeliver, classifyMessage, decideIncident, decideProposals, moveTask, postToChat, REQUEST_SENT_TEXT, requestSubscription, resumeSession, stopSession } from "@peppa/runner";
|
||
import { INTENT_TEXT, statusAnswer } from "@peppa/core";
|
||
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 { getUserLocale, transcribe, transcribeConfig, transcribeLanguage, 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("Я бот FORGE. Присылаю вопросы от агентов и сообщения о том, что задача готова или агент ждёт вас."),
|
||
"",
|
||
tr("• Кнопки под сообщением — быстрый ответ."),
|
||
tr("• Ответ <b>реплаем</b> на сообщение — свой текст, он уйдёт агенту."),
|
||
voice
|
||
? tr("• Просто напишите (или наговорите голосом) задачу — я её заведу: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу.")
|
||
: tr("• Просто напишите задачу — я её заведу: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу."),
|
||
tr("• Спросите, что сейчас происходит («какие задачи у агентов?», «что с PAY-3?») — отвечу сразу, задачу из вопроса не заведу."),
|
||
tr("• /status — кто из агентов работает и какие вопросы открыты."),
|
||
tr("• /problem — сообщить о проблеме в FORGE: напишите, что случилось, и приложите фото экрана."),
|
||
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("Обновления FORGE"),
|
||
};
|
||
|
||
/** 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) {
|
||
// PEP-152: technical details stay on the site — Telegram gets a «Подробнее» button.
|
||
return { ...(await taskContext(q)), details: (await messageDetails(db, [q.id])).has(q.id) };
|
||
}
|
||
async function taskContext(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;
|
||
const author = await questionAuthor(db, q).catch(() => null);
|
||
const agent = author?.kind === "agent" ? author.name : null;
|
||
if (session) return { taskKey: session.taskKey, taskTitle: session.taskTitle, taskStatus, session, webUrl: o.webUrl, agent };
|
||
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> {
|
||
// PEP-174: a project on pause gets nothing; what came up during a pause is not sent afterwards.
|
||
const open: Question[] = [];
|
||
for (const q of await pendingQuestions(db)) if (!(await duringPause(db, q.projectId, q.createdAt))) open.push(q);
|
||
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 });
|
||
// 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)}`;
|
||
// PEP-198: a finished story nobody waits for comes in the evening digest, not one by one.
|
||
if (await heldForDigest(db, q, ctx.taskStatus ?? null)) continue;
|
||
// PEP-209: more than two ready within an hour — one summary with «Приёмка» instead (acceptDigestTick).
|
||
if ((await acceptDigestHold(db, q)) !== "send") continue;
|
||
for (const u of audience) {
|
||
// PEP-154: the terminal command is for the «Инженер» view only.
|
||
const r = renderQuestion(q, { ...ctx, engineer: (await getUiMode(db, u.id)) === "engineer" });
|
||
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;
|
||
const r = renderQuestion(q, ctx);
|
||
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) {
|
||
if (await isProjectPaused(db, q.projectId)) continue;
|
||
// 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.
|
||
// PEP-156: an agent or an AI role signs with its nickname or name: «🤖 Шустрик: …».
|
||
const bot = m.authorKind === "agent";
|
||
const inRole = bot ? 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 = bot || (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 = bot ? `<b>${asIs(esc(agentSignature(m.authorLogin ? login : null)))}</b>` : m.kind === "user" ? `<b>${asIs(esc(login))}</b>` : "";
|
||
const body = bot ? `: ${said}` : 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 task in words (or a pressed «Завести как задачу») → a draft and the next question. */
|
||
async function startStory(user: User, chatId: number, text: string, voice: boolean, editId?: number) {
|
||
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, editId);
|
||
else await askProject(d, projects, editId);
|
||
}
|
||
|
||
const asTaskRow = (d: Draft): InlineButton[] => [{ text: INTENT_TEXT.asTask, callback_data: `d:${d.id}:t` }];
|
||
|
||
/**
|
||
* PEP-153: a plain message (or a transcribed voice note) is a question or a task. A question is
|
||
* answered at once, with «Завести как задачу» under the answer; a task becomes a draft (PEP-45);
|
||
* when it is not clear — or the classifier is not at hand — the person picks by a button.
|
||
*/
|
||
async function onPlainText(user: User, chatId: number, text: string, voice: boolean) {
|
||
const projects = await listUserProjects(db, user.id);
|
||
if (!projects.length) return startStory(user, chatId, text, voice);
|
||
const parsed = parseStoryText(text, projects);
|
||
void api.call("sendChatAction", { chat_id: chatId, action: "typing" }).catch(() => {});
|
||
const r = await classifyMessage(db, user, parsed.body || text, { explicit: !!parsed.project, project: parsed.project, log });
|
||
if (r.kind === "task") return startStory(user, chatId, text, voice);
|
||
const answered = r.kind === "question" && !!r.answer;
|
||
const d = await saveDraft(db, { userId: user.id, chatId, text, projectId: null, voice, offer: true, asked: !answered, answer: r.answer });
|
||
if (answered) return show(chatId, esc(r.answer!), [asTaskRow(d)]);
|
||
await show(chatId, [`«${esc(splitStory(parsed.body || text).title)}»`, r.failed ? INTENT_TEXT.failed : INTENT_TEXT.unsure].join("\n"), [
|
||
[{ text: INTENT_TEXT.answer, callback_data: `d:${d.id}:a` }, { text: INTENT_TEXT.file, callback_data: `d:${d.id}:t` }],
|
||
]);
|
||
}
|
||
|
||
/** Text of a voice note; null — it could not be heard, and the user has been told. */
|
||
async function voiceText(user: User, 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);
|
||
// PEP-131: in the speaker's own language (in a group too — theirs, not the group's).
|
||
const language = transcribeLanguage(cfg, await getUserLocale(db, user.id));
|
||
text = await transcribe(cfg, audio, file.file_path.split("/").pop() || "voice.ogg", f.mime_type ?? "audio/ogg", language);
|
||
} 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(user, m);
|
||
if (text) await onPlainText(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(user, 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";
|
||
}
|
||
|
||
/** PEP-197: the owner decides on stories the factory suggested. */
|
||
async function onProposalButton(user: User, c: TgCallbackQuery, parts: string[]): Promise<string> {
|
||
const ids = (parts[1] ?? "").split(",").map(Number).filter((n) => Number.isInteger(n) && n > 0);
|
||
const choice = parts[2];
|
||
if (choice !== "do" && choice !== "no" && choice !== "important" && choice !== "none") return tr("Неизвестная кнопка");
|
||
const n = await decideProposals(db, user, ids, choice);
|
||
return choice === "do" || choice === "important" ? tr("Принято, задач: {n}", { n }) : tr("Отклонено: {n}", { n });
|
||
}
|
||
|
||
/** 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("Черновик устарел");
|
||
}
|
||
// PEP-153: «Ответить» — the answer at hand, else the state of things from the platform's data.
|
||
if (parts[2] === "a" && d.offer) {
|
||
const text = d.answer ?? (await statusAnswer(db, user, { text: d.text, webUrl: o.webUrl }));
|
||
await updateDraft(db, { ...d, asked: false });
|
||
await show(chatId, esc(text), [asTaskRow(d)], msgId);
|
||
return tr("Ответил");
|
||
}
|
||
// PEP-153: «Завести как задачу» — the message becomes a draft; an answer above stays as it is.
|
||
if (parts[2] === "t" && d.offer) {
|
||
await dropDraft(db, d.id);
|
||
const answered = !d.asked;
|
||
if (answered && msgId) await api.call("editMessageReplyMarkup", { chat_id: chatId, message_id: msgId, reply_markup: { inline_keyboard: [] } }).catch(() => {});
|
||
await startStory(user, chatId, d.text, d.voice, answered ? undefined : msgId);
|
||
return tr("Завожу задачу");
|
||
}
|
||
if (d.offer) 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 в FORGE и имеет доступ к проекту. /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("Не нашёл вас в FORGE — привяжите 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("Мы передадим это тем, кто делает FORGE.")].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("Чтобы сообщить о проблеме в FORGE, сначала отправьте /problem, а потом фото."), m.message_id);
|
||
return "done";
|
||
}
|
||
if (!text || text.startsWith("/")) {
|
||
await reply(m.chat.id, tr("Чтобы ответить агенту, ответьте <b>реплаем</b> на его сообщение. Чтобы завести задачу — просто напишите её. /help — что я умею."));
|
||
return "done";
|
||
}
|
||
// PEP-153: a question is answered, a task becomes a draft (PEP-45: created only after a button press).
|
||
await onPlainText(user, m.chat.id, text, false);
|
||
return "done";
|
||
}
|
||
|
||
async function onDelayButton(user: User, data: string): Promise<string> {
|
||
const b = parseDelayCallback(data);
|
||
if (!b || !(await isSuperadmin(db, user))) return tr("Неизвестная кнопка");
|
||
const projectId = b.scope.projectId ?? (b.scope.taskId != null ? (await resolveTaskById(db, b.scope.taskId).catch(() => null))?.project.id : null);
|
||
if (projectId == null) return tr("Задача не найдена");
|
||
return delayAction(db, { projectId, taskId: b.scope.taskId }, b.reason, b.action);
|
||
}
|
||
|
||
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";
|
||
}
|
||
// PEP-197: «Делать» / «Не надо» under the acceptance agent's message: `p:<ids>:do|no|important|none`.
|
||
if (parts[0] === "p") {
|
||
const toast = await onProposalButton(user, c, parts).catch((e) => (e instanceof PeppaError ? e.message : (log(`proposal: ${(e as Error).stack ?? e}`), tr("Ошибка"))));
|
||
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||
return "done";
|
||
}
|
||
// PEP-209: the superadmin's buttons on a delay message: `pd:<t|p><id>:<reason>:r|v|x`.
|
||
if (parts[0] === "pd") {
|
||
const toast = await onDelayButton(user, c.data ?? "").catch((e) => (e instanceof PeppaError ? e.message : (log(`delay: ${(e as Error).stack ?? e}`), tr("Ошибка"))));
|
||
wakeOutbox?.();
|
||
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("Агент остановлен ⏹");
|
||
} else if (choice === "ask") {
|
||
// PEP-186: «Попросить подписку у администратора» under a limit message.
|
||
try {
|
||
await requestSubscription(db, user, await projectForUser(db, user.id, s.projectId));
|
||
toast = REQUEST_SENT_TEXT;
|
||
} catch (e) {
|
||
toast = (e as Error).message;
|
||
}
|
||
wakeOutbox?.();
|
||
}
|
||
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>;
|