peppa/packages/runner/src/monitor.ts
peppa-bot f3d10a4c25 PEP-243: платформа называется FORGE — название во всех текстах для людей и подсказках агентам, адрес forge.telecom.quest
«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>
2026-11-23 11:18:49 +05:00

70 lines
4.0 KiB
TypeScript

// Watchdog side of service monitoring (PEP-20): heartbeat, check the bot and the web, and
// deliver monitor alerts straight to the Bot API when the bot itself is the one that's down.
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { beat, checkServices, getPlatformChannel, getSetting, portKey, postToChannel, setSetting, type PortState, markOutboxRetry, markOutboxSent, pendingMonitorMessages, serviceStatus, type MonitorOptions } from "@peppa/core";
import { m as tr } from "@peppa/shared/i18n";
import type { Db } from "@peppa/db";
export interface MonitorTickOptions extends MonitorOptions {
/** Bot API access for direct delivery (defaults: TELEGRAM_BOT_TOKEN, TELEGRAM_API_URL). */
telegram?: { token?: string; apiUrl?: string };
}
export async function monitorTick(db: Db, o: MonitorTickOptions = {}): Promise<void> {
const log = o.log ?? (() => {});
await beat(db, "watchdog", { now: o.now });
await checkServices(db, { ...o, self: "watchdog" });
await webRestartTick(db, o).catch((e) => log(`monitor: web restart: ${(e as Error).message}`));
const bot = (await serviceStatus(db, { now: o.now, staleMs: o.staleMs })).find((s) => s.service === "bot");
if (bot?.heartbeat && !bot.ok) await deliverDirect(db, o.telegram ?? {}, log);
}
const run = promisify(execFile);
/**
* PEP-168: the web process is alive but its port stays closed for `PEPPA_WEB_RESTART_AFTER`
* (default 6) checks in a row → `launchctl kickstart -k`, at most `PEPPA_WEB_RESTART_MAX` (2)
* times per hour; the platform channel hears about it. `PEPPA_WEB_RESTART=off` disables.
*/
export async function webRestartTick(db: Db, o: MonitorTickOptions = {}): Promise<boolean> {
if (process.env.PEPPA_WEB_RESTART === "off") return false;
const port = await getSetting<PortState>(db, portKey("web"));
if (!port || port.fails < Number(process.env.PEPPA_WEB_RESTART_AFTER ?? 6)) return false;
const now = o.now ?? new Date();
const key = "monitor.web-restarts";
const recent = ((await getSetting<string[]>(db, key)) ?? []).filter((t) => now.getTime() - Date.parse(t) < 3600_000);
if (recent.length >= Number(process.env.PEPPA_WEB_RESTART_MAX ?? 2)) return false;
await setSetting(db, key, [...recent, now.toISOString()]);
// The streak starts over: the next verdict is about the restarted process.
await setSetting(db, portKey("web"), { fails: 0, since: port.since, lastAt: now.toISOString() } satisfies PortState);
const bin = process.env.PEPPA_LAUNCHCTL_BIN ?? "launchctl";
await run(bin, ["kickstart", "-k", `gui/${process.getuid?.() ?? 501}/quest.telecom.peppa.web`], { timeout: 30_000 });
o.log?.("monitor: веб не слушал порт — перезапущен (launchctl kickstart -k)");
await postToChannel(db, "services", `mon:ch:web:kick:${now.toISOString()}`, tr("🔄 FORGE: веб не слушал порт — перезапускаю."), await getPlatformChannel(db));
return true;
}
/** Sends pending `mon:` outbox rows itself; marks them sent so the bot won't repeat them. */
async function deliverDirect(db: Db, tg: { token?: string; apiUrl?: string }, log: (m: string) => void) {
const token = tg.token ?? process.env.TELEGRAM_BOT_TOKEN;
if (!token) return;
const base = tg.apiUrl ?? process.env.TELEGRAM_API_URL ?? "https://api.telegram.org";
for (const row of await pendingMonitorMessages(db)) {
try {
const res = await fetch(`${base}/bot${token}/${row.method}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(row.params),
signal: AbortSignal.timeout(15_000),
});
const body = (await res.json().catch(() => ({}))) as { ok?: boolean; result?: { message_id?: number }; description?: string };
if (!body.ok) throw new Error(body.description ?? res.statusText);
await markOutboxSent(db, row, body.result?.message_id ?? null);
} catch (e) {
log(`monitor: direct send #${row.id}: ${(e as Error).message}`);
await markOutboxRetry(db, row, (e as Error).message);
}
}
}