brendmanager/src/agent.js
Peppa 4cd1d9bf02
All checks were successful
peppa/lint lint: success за 1с
peppa/test test: success за 1с
ci / checks (pull_request) Successful in 6s
deploy / deploy (pull_request) Successful in 15s
BRM-54: очередь задач с повторами, защита от дублей, дневной и недельный отчёты
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 01:54:47 +05:00

33 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { permanent, retryAt } from "./jobs.js";
import { buildDailyReport, buildWeeklyReport } from "./reports.js";
// Обработчики задач агента: внешнее действие — только через общий публикатор (правила, лимиты, защита от дублей).
export function createHandlers({ pub }) {
return {
async publish({ payload, key }) {
const e = await pub.publish({ channel: payload.channel, text: payload.text, approvedBy: payload.approvedBy, scheduled: true, key: key ?? undefined });
if (e.result === "published") return { ref: e.ref ?? e.url ?? "без номера" };
if (e.reason === "duplicate") return { ref: e.ref ?? e.url ?? `уже опубликовано ${e.duplicateOf}` };
if (e.reason === "limit" && e.retryAt) throw retryAt("достигнут лимит публикаций", e.retryAt);
if (e.result === "error") throw new Error(e.reason); // сбой отправки — повтор с растущей паузой
throw permanent(`отправка не разрешена (${e.reason})`);
},
};
}
// Расписание отчётов превращается в задачи: ключ report:<вид>:<дата> не даёт завести отчёт дважды.
export function enqueueReport({ jobs, pub, metrics, opps, kind, date, now }) {
const text = kind === "week"
? buildWeeklyReport({ date, log: pub.log(), jobs: jobs.list(), queue: pub.queue(), metrics: metrics.list(), opportunities: opps.list(date), tzOffsetHours: metrics.settings().tzOffsetHours })
: buildDailyReport({ date, log: pub.log(), jobs: jobs.list(), queue: pub.queue(), tzOffsetHours: metrics.settings().tzOffsetHours });
return { text, ...jobs.add({ kind: "publish", key: `report:${kind}:${date}`, payload: { channel: "telegram", text, approvedBy: "pm" }, dueAt: now, priority: 2 }) };
}
// Уведомление Татьяне о задаче, которая не удалась: напрямую в канал, мимо дневного лимита публикаций.
export function failureNotifier(telegram) {
return async (job) => {
if (!telegram.connected()) throw new Error("нет доступа к Telegram");
await telegram.send(`Агент не смог выполнить задачу №${job.id} (${job.kind}): ${job.lastError}. Попыток: ${job.attempts}. Задача в списке ошибок.`);
};
}