peppa/packages/mcp/src/monitors.ts
peppa-bot acb6e3fb81
All checks were successful
peppa/lint lint: success за 1с
peppa/typecheck typecheck: success за 46с
peppa/build build: success за 34с
peppa/test test: success за 1325с
peppa-ci / ci (pull_request) Successful in 24m11s
PEP-224: статус функций из мониторинга (сведено с main после PEP-225)
Функция → мониторинги (core/feature-status.ts), серая кнопка входа через eGov и статус MCP,
отказ startEgovFlow, журнал и сообщения в канал. После переезда живых обновлений на
WebSocket (PEP-225): область `features` в LIVE_PLAIN_SCOPES, открыта без входа (SSE и
WebSocket с `anonymous: true` — только открытые области), смотрится по таймеру вместе с
`observe`, смена сбрасывает кэш статусов.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 15:00:03 +00:00

142 lines
9.0 KiB
TypeScript
Raw Permalink 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.

// PEP-202: Observability tools — the same set in the remote MCP (superadmin only) and in the agent
// MCP (sessions of the platform project only). Every change goes to the journal with its author.
import { z } from "zod";
import type { Db } from "@peppa/db";
import {
createMonitor,
deleteMonitor,
describeTarget,
FEATURE_NAMES,
featureStatuses,
getMonitor,
getProject,
logEvent,
monitorChecks,
monitorIncidents,
monitorView,
listMonitorViews,
observeRemindMin,
PeppaError,
platformProjectKey,
setMonitorPaused,
updateMonitor,
type MonitorKind,
type MonitorView,
} from "@peppa/core";
import { loadEnv } from "@peppa/shared";
type Define = <S extends z.ZodRawShape>(name: string, description: string, schema: S, readOnly: boolean, run: (a: z.infer<z.ZodObject<S>>) => Promise<string>) => void;
export interface MonitorAccess {
/** Throws when the caller may not use monitors; returns the author («user:<login>», «agent:s<id>»). */
check(): Promise<{ author: string; sessionId?: number | null }>;
}
export const MONITOR_TOOLS = ["list_monitors", "get_monitor", "create_monitor", "update_monitor", "pause_monitor", "delete_monitor"];
const kind = z.enum(["http", "tcp", "dns", "internet", "heartbeat"]);
const target = z
.object({
url: z.string().optional().describe("http: the address, http:// or https://"),
method: z.enum(["GET", "HEAD"]).optional(),
expectStatus: z.array(z.number().int()).optional().describe("http: accepted codes (default 200–399)"),
contains: z.string().optional().describe("http: text the body must contain"),
maxLatencyMs: z.number().int().optional().describe("http: slower = degraded"),
certDays: z.number().int().optional().describe("http: certificate expiring sooner = degraded (default 14)"),
host: z.string().optional().describe("tcp / dns: host name or IPv4"),
port: z.number().int().optional().describe("tcp: port"),
hosts: z.array(z.string()).optional().describe("internet: up to 10 hosts; down only when none opens"),
graceSec: z.number().int().optional().describe("heartbeat: extra seconds after the interval (default 60)"),
})
.describe("Where to look; fields by kind");
const common = {
interval_sec: z.number().int().min(30).optional().describe("Seconds between checks (≥30, default 60)"),
timeout_ms: z.number().int().optional().describe("Per check, 1000–30000 (default 10000)"),
fail_threshold: z.number().int().optional().describe("Bad checks in a row before «down» (default 3)"),
recover_threshold: z.number().int().optional().describe("Good checks in a row before «up» again (default 2)"),
remind_min: z.number().int().min(0).max(1440).nullable().optional().describe("Minutes between reminders while it is down (PEP-223); 0 — no reminders, null — the common default (PEPPA_OBSERVE_REMIND_MIN, 30)"),
remind_degraded: z.boolean().optional().describe("Remind while «degraded» too (default false)"),
features: z
.array(z.enum(FEATURE_NAMES))
.optional()
.describe(`PEP-224: platform features to switch off for users (grey, «temporarily unavailable») while this monitor is down longer than the feature's threshold (default 5 min): ${FEATURE_NAMES.join(", ")}. [] — none; left out — unchanged`),
};
const pct = (v: number | null) => (v == null ? "—" : `${(v * 100).toFixed(v >= 0.9995 ? 0 : 2)}%`);
const outage = (m: MonitorView) =>
m.outage && (m.state === "down" || m.state === "degraded")
? ` · ${m.state} since ${m.outage.startedAt}, reminders ${m.outage.reminders}${m.outage.nextRemindAt ? `, next ${m.outage.nextRemindAt}` : m.outage.quiet ? " (quiet: with the internet)" : ", no more"}`
: "";
const line = (m: MonitorView) =>
`- #${m.id} ${m.name} [${m.kind}] ${describeTarget(m, loadEnv().PEPPA_WEB_URL)} — ${m.paused ? "paused" : m.state}${m.lastDetail?.reason ? ` (${m.lastDetail.reason})` : ""} · uptime 24h ${pct(m.uptime24h)}, 7d ${pct(m.uptime7d)}${outage(m)}${m.features.length ? ` · switches off: ${m.features.join(", ")}` : ""}`;
async function journal(db: Db, type: string, sessionId: number | null | undefined, payload: Record<string, unknown>) {
const p = await getProject(db, platformProjectKey()).catch(() => null);
if (p) await logEvent(db, { projectId: p.id, sessionId: sessionId ?? null, type, payload }).catch(() => {});
}
export function registerMonitorTools(db: Db, define: Define, access: MonitorAccess): void {
const found = (id: number) => getMonitor(id) ?? (() => { throw new PeppaError("Monitor not found"); })();
define("list_monitors", "Observability (PEP-202): every monitor of the FORGE platform with its state, last reason and uptime for 24 h and 7 days.", {}, true, async () => {
await access.check();
const list = listMonitorViews();
const f = Object.values(featureStatuses({ fresh: true }));
const features = ["", "Features (PEP-224):", ...f.map((x) => `- ${x.name}: ${x.state}${x.since ? ` since ${x.since}` : ""} · off after ${x.disableAfterMin} min down · monitors: ${x.monitors.map((mm) => mm.name).join(", ") || "none"}`)];
return [list.length ? list.map(line).join("\n") : "No monitors.", ...features].join("\n");
});
define("get_monitor", "Observability: one monitor — state, uptime, incidents of the week and the last checks.", { id: z.number().int(), checks: z.number().int().min(1).max(500).optional().describe("How many last checks (default 50)") }, true, async ({ id, checks }) => {
await access.check();
const m = monitorView(found(id));
const inc = monitorIncidents(id, 20);
const cs = monitorChecks(id, { limit: checks ?? 50 });
return [
line(m),
`interval ${m.intervalSec}s, timeout ${m.timeoutMs}ms, down after ${m.failThreshold} bad, up after ${m.recoverThreshold} good; reminders every ${m.remindMin ?? `${observeRemindMin()} (default)`} min${m.remindDegraded ? " (degraded too)" : ""}; created by ${m.createdBy}`,
"",
"Incidents:",
...(inc.length ? inc.map((i) => `- ${i.startedAt} → ${i.endedAt ?? "now"}: ${i.state} — ${i.reason}${i.quiet ? " (with the internet, no message)" : ""}${i.reminders ? `, reminders ${i.reminders}` : ""}`) : ["- none"]),
"",
"Last checks:",
...cs.map((c) => `- ${c.at} ${c.ok ? (c.degraded ? "degraded" : "ok") : "FAIL"}${c.latencyMs != null ? ` ${c.latencyMs}ms` : ""}${c.detail.reason ? ` — ${c.detail.reason}` : ""}`),
].join("\n");
});
define(
"create_monitor",
"Observability: add a monitor. Kinds: http (url, expectStatus, contains, maxLatencyMs, certDays), tcp (host, port), dns (host — system DNS vs 1.1.1.1), internet (hosts), heartbeat (graceSec; returns the ping address the service must call). State changes go to the platform's Telegram channel; while down, a reminder every remind_min minutes (default 30).",
{ name: z.string().min(1).max(80), kind, target, ...common },
false,
async (a) => {
const who = await access.check();
const m = createMonitor({ name: a.name, kind: a.kind as MonitorKind, target: a.target, intervalSec: a.interval_sec, timeoutMs: a.timeout_ms, failThreshold: a.fail_threshold, recoverThreshold: a.recover_threshold, remindMin: a.remind_min, remindDegraded: a.remind_degraded, features: a.features }, who.author);
await journal(db, "monitor_created", who.sessionId, { id: m.id, name: m.name, kind: m.kind, target: m.target, author: who.author });
return `Created #${m.id} ${m.name} [${m.kind}] ${describeTarget(m, loadEnv().PEPPA_WEB_URL)}; first check within a few seconds.`;
},
);
define("update_monitor", "Observability: change a monitor (the kind stays). Fields left out stay.", { id: z.number().int(), name: z.string().min(1).max(80).optional(), target: target.optional(), ...common }, false, async (a) => {
const who = await access.check();
found(a.id);
const m = updateMonitor(a.id, { name: a.name, target: a.target, intervalSec: a.interval_sec, timeoutMs: a.timeout_ms, failThreshold: a.fail_threshold, recoverThreshold: a.recover_threshold, remindMin: a.remind_min, remindDegraded: a.remind_degraded, features: a.features });
await journal(db, "monitor_updated", who.sessionId, { id: m.id, name: m.name, features: m.features, author: who.author });
return `Updated #${m.id} ${m.name}${m.features.length ? `; switches off: ${m.features.join(", ")}` : ""}.`;
});
define("pause_monitor", "Observability: pause (no checks, no messages) or resume a monitor.", { id: z.number().int(), paused: z.boolean() }, false, async ({ id, paused }) => {
const who = await access.check();
found(id);
const m = setMonitorPaused(id, paused);
await journal(db, "monitor_updated", who.sessionId, { id: m.id, name: m.name, paused, author: who.author });
return `#${m.id} ${m.name}: ${paused ? "paused" : "resumed"}.`;
});
define("delete_monitor", "Observability: delete a monitor with its checks and incidents.", { id: z.number().int() }, false, async ({ id }) => {
const who = await access.check();
const m = deleteMonitor(found(id).id);
await journal(db, "monitor_deleted", who.sessionId, { id: m.id, name: m.name, author: who.author });
return `Deleted #${m.id} ${m.name}.`;
});
}