PEP-224: статус функций из мониторинга — ядро, вход, настройки, MCP, observability

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-20 20:59:30 +05:00
parent 8e01419e14
commit 80d66d2b83
26 changed files with 719 additions and 52 deletions

View File

@ -3,7 +3,8 @@
// 30 s it writes its heartbeat (the watchdog watches it like the bot and the web), every hour it
// deletes checks older than the retention (7 days). Monitors are rows in observe.db: the web and
// MCP change them, the service picks the change up on its next pass — no restart.
import { beat, observeTick, pruneObserve, seedMonitors, type ObserveProbes } from "@peppa/core";
import { beat, featureTick, observeTick, pruneObserve, seedFeatureMonitors, seedMonitors, type ObserveProbes } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import type { Db } from "@peppa/db";
export interface ObserverOptions {
@ -16,6 +17,10 @@ export async function runObserver(db: Db, o: ObserverOptions = {}, signal?: Abor
const log = o.log ?? (() => {});
const made = seedMonitors();
if (made.length) log(`observer: built-in monitors created: ${made.map((m) => m.name).join(", ")}`);
// PEP-224: MCP monitors switch the «mcp» feature off; created once, when the web has a public address.
const mcp = seedFeatureMonitors(loadEnv().PEPPA_WEB_URL);
if (mcp.length) log(`observer: built-in monitors created: ${mcp.map((m) => m.name).join(", ")}`);
let featuresBusy = false;
log("observer started");
let lastBeat = 0;
let lastPrune = 0;
@ -36,6 +41,13 @@ export async function runObserver(db: Db, o: ObserverOptions = {}, signal?: Abor
}
// Not awaited: a slow check must not hold the others or the heartbeat.
void observeTick(db, { log, probes: o.probes }).catch((e: Error) => log(`observer: tick failed: ${e.message}`));
// PEP-224: features follow their monitors — announce a change (journal, channel, live pages).
if (!featuresBusy) {
featuresBusy = true;
void featureTick(db, { log })
.catch((e: Error) => log(`observer: features failed: ${e.message}`))
.finally(() => (featuresBusy = false));
}
await new Promise((r) => setTimeout(r, o.tickMs ?? 1_000));
}
}

View File

@ -1,27 +1,33 @@
import Link from "next/link";
import { CONNECT_HELP } from "@peppa/core";
import { CONNECT_HELP, featureGateView } from "@peppa/core";
import { FeatureGate } from "@/components/FeatureGate";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PageHeader } from "@/components/common";
import { CopyText } from "@/components/CopyText";
import { Workspace } from "@/components/Workspace";
import { publicOrigin } from "@/lib/auth";
import { getLocale } from "@/lib/i18n";
import { getLocale, getT } from "@/lib/i18n";
/** PEP-135: how to connect Peppa FACTORY to one's own Claude or ChatGPT — step by step; texts live in core/connect-texts.ts. */
export default async function ConnectHelp() {
const t = CONNECT_HELP[await getLocale()] ?? CONNECT_HELP.ru;
const address = `${await publicOrigin()}/mcp`;
const tr = await getT();
const card = "flex flex-col gap-2 rounded-lg border bg-card px-4 py-3";
const h2 = "m-0 text-[15px] font-semibold";
return (
<Workspace>
<div className="max-w-2xl text-sm leading-relaxed">
<LiveRefresh scope="features" indicator={false} pollMs={30_000} />
<PageHeader crumbs={<Link href="/help" className="text-muted-foreground hover:text-foreground">{t.back}</Link>} title={t.title}>
{t.lead}
</PageHeader>
<div className="flex flex-col gap-3">
<section className={card}>
<h2 className={h2}>{t.addressTitle}</h2>
<CopyText value={address} label={t.copy} done={t.copied} />
<FeatureGate view={featureGateView("mcp")} title={tr("MCP временно недоступен")}>
<CopyText value={address} label={t.copy} done={t.copied} />
</FeatureGate>
<p className="m-0 text-muted-foreground">{t.addressNote}</p>
</section>
{t.apps.map((app) => (

View File

@ -1,6 +1,8 @@
import Link from "next/link";
import type { ReactNode } from "react";
import { CONNECT_HELP, PRODUCT_HELP } from "@peppa/core";
import { CONNECT_HELP, featureGateView, PRODUCT_HELP } from "@peppa/core";
import { FeatureGate } from "@/components/FeatureGate";
import { LiveRefresh } from "@/components/LiveRefresh";
import { m } from "@peppa/shared/i18n";
import { getLocale, getT } from "@/lib/i18n";
import { publicOrigin, uiMode } from "@/lib/auth";
@ -172,8 +174,11 @@ export default async function Help() {
</Section>
<Section title={t("Подключить MCP")}>
<p className="m-0">{t("Адрес сервера:")}</p>
<code className="block overflow-x-auto rounded-md border bg-muted px-3 py-2 text-sm">{mcp}</code>
<LiveRefresh scope="features" indicator={false} pollMs={30_000} />
<FeatureGate view={featureGateView("mcp")} title={t("MCP временно недоступен")}>
<p className="m-0">{t("Адрес сервера:")}</p>
<code className="block overflow-x-auto rounded-md border bg-muted px-3 py-2 text-sm">{mcp}</code>
</FeatureGate>
<ul>
<li>{rich(t("<b>ChatGPT</b>: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется Peppa FACTORY — войдите через eGov и нажмите «Разрешить». В чате включите коннектор Peppa."))}</li>
<li>{rich(t("<b>Инструкция для ИИ</b>: первым делом ИИ-клиент вызывает инструмент <m>get_started</m> — памятка менеджера: код пишут только агенты, напрямую в код проекта не лезть, «Готово» — только после «Принять». Те же слова — на открытой странице <a href=\"/mcp-guide\">/mcp-guide</a> (кнопка «Скопировать» — для «Инструкций» проекта ChatGPT или системного сообщения другого ИИ). Первый ответ <m>list_projects</m> и <m>get_task</m> напоминает о ней."))}</li>

View File

@ -2,7 +2,7 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Activity, Pause, Play, Trash2 } from "lucide-react";
import { describeTarget, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core";
import { describeTarget, FEATURES, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { AutoRefresh } from "@/components/AutoRefresh";
import { Hidden } from "@/components/cards";
@ -66,6 +66,9 @@ export default async function MonitorPage({ params, searchParams }: { params: Pr
<p className="m-0 text-xs text-muted-foreground">
{t("Раз в {n} с · «не работает» после {f} неудач подряд · «работает» после {r} удач · создал {who}", { n: m.intervalSec, f: m.failThreshold, r: m.recoverThreshold, who: m.createdBy })}
</p>
<p className="m-0 text-xs text-muted-foreground">
{t("Что отключать при сбое:")} {m.features.length ? m.features.map((f) => t(FEATURES[f].label)).join(", ") : t("ничего")}
</p>
<div className="flex flex-wrap gap-2">
<form action={pauseMonitorAction}>
<Hidden fields={{ id: m.id, paused: m.paused ? "0" : "1", back: `/observability/${m.id}` }} />

View File

@ -1,7 +1,7 @@
"use server";
// Observability (PEP-202): every action is superadmin-only (others get "not found").
import { createMonitor, deleteMonitor, getProject, logEvent, MONITOR_KINDS, PeppaError, platformProjectKey, requireSuperadmin, setMonitorPaused, updateMonitor, type MonitorKind, type MonitorTarget } from "@peppa/core";
import { createMonitor, deleteMonitor, resetFeatureCache, setFeatureThreshold, getProject, logEvent, MONITOR_KINDS, PeppaError, platformProjectKey, requireSuperadmin, setMonitorPaused, updateMonitor, type MonitorKind, type MonitorTarget } from "@peppa/core";
import type { Db } from "@peppa/db";
import { m } from "@peppa/shared/i18n";
import { revalidatePath } from "next/cache";
@ -53,6 +53,8 @@ function targetOf(kind: MonitorKind, f: FormData): MonitorTarget {
}
const numbers = (f: FormData) => ({
// PEP-224: «Что отключать при сбое» — the checked features.
features: f.getAll("features").map(String),
intervalSec: str(f, "intervalSec") ? Number(str(f, "intervalSec")) : undefined,
failThreshold: str(f, "failThreshold") ? Number(str(f, "failThreshold")) : undefined,
recoverThreshold: str(f, "recoverThreshold") ? Number(str(f, "recoverThreshold")) : undefined,
@ -95,3 +97,14 @@ export async function deleteMonitorAction(f: FormData) {
return BASE;
});
}
/** PEP-224: how long a linked monitor may be down before the feature turns grey. */
export async function setFeatureThresholdAction(f: FormData) {
await attempt(f, BASE, async (login) => {
const name = str(f, "name");
const minutes = Number(str(f, "disableAfterMin"));
setFeatureThreshold(name, minutes);
resetFeatureCache();
await journal(db, "feature_updated", { feature: name, disableAfterMin: minutes, author: `user:${login}` });
});
}

View File

@ -2,7 +2,7 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Activity, Pause, Play, Plus } from "lucide-react";
import { describeTarget, egovLoginSummary, isSuperadmin, listMonitorViews } from "@peppa/core";
import { describeTarget, egovLoginSummary, FEATURE_NAMES, FEATURES, featureLog, featureStatuses, isSuperadmin, listMonitorViews } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { AutoRefresh } from "@/components/AutoRefresh";
import { Hidden } from "@/components/cards";
@ -14,7 +14,9 @@ import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
import { createMonitorAction, pauseMonitorAction } from "./actions";
import { createMonitorAction, pauseMonitorAction, setFeatureThresholdAction } from "./actions";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
export const dynamic = "force-dynamic";
@ -33,6 +35,10 @@ export default async function Observability({ searchParams }: { searchParams: Pr
const web = loadEnv().PEPPA_WEB_URL;
const down = monitors.filter((m) => !m.paused && m.state === "down").length;
const degraded = monitors.filter((m) => !m.paused && m.state === "degraded").length;
// PEP-224: features follow their monitors.
const features = featureStatuses({ fresh: true });
const flog = featureLog(20);
const FEATURE_STATE = { available: [t("доступна"), "border-ok/40 text-ok"], degraded: [t("с задержками"), "border-warn/40 text-warn"], unavailable: [t("отключена"), "border-destructive/40 text-destructive"] } as const;
return (
<Workspace>
<AutoRefresh everyMs={15_000} />
@ -88,6 +94,63 @@ export default async function Observability({ searchParams }: { searchParams: Pr
</form>
</Disclosure>
</Section>
<Section title={t("Функции")} count={FEATURE_NAMES.length}>
<p className="m-0 text-sm text-muted-foreground">{t("Функция становится серой у пользователей, когда связанный мониторинг не работает дольше порога, и включается сама после восстановления. Связка — «Что отключать при сбое» у мониторинга или поле features в MCP update_monitor.")}</p>
<div className="flex flex-col gap-2">
{FEATURE_NAMES.map((name) => {
const f = features[name];
const [label, cls] = FEATURE_STATE[f.state];
return (
<Card key={name} className="gap-1.5 py-3" data-feature-row={name}>
<div className="flex flex-wrap items-center gap-2">
<Badge variant="outline" className={cls}>{label}</Badge>
<span className="font-semibold">{t(FEATURES[name].label)}</span>
<span className="font-mono text-xs text-muted-foreground">{name}</span>
<form action={setFeatureThresholdAction} className="ml-auto flex items-center gap-1.5 text-xs text-muted-foreground">
<Hidden fields={{ name }} />
{t("отключать через, мин")}
<Input name="disableAfterMin" type="number" min={0} max={1440} defaultValue={f.disableAfterMin} className="h-7 w-16" />
<Button size="sm" variant="ghost">{t("Сохранить")}</Button>
</form>
</div>
<div className="text-xs text-muted-foreground">
{f.monitors.length ? (
<>
{t("Мониторинги:")}{" "}
{f.monitors.map((mm, i) => (
<span key={mm.id}>
{i ? ", " : ""}
<Link href={`/observability/${mm.id}`} className="hover:underline">{mm.name}</Link>
</span>
))}
</>
) : (
t("Не связана ни с одним мониторингом — всегда доступна.")
)}
{f.failing.length ? <span className="text-destructive"> · {f.failing.map((x) => `${x.name}${x.reason ? `: ${x.reason}` : ""}`).join("; ")}</span> : null}
</div>
</Card>
);
})}
</div>
<Disclosure summary={t("Журнал включений и выключений ({n})", { n: flog.length })}>
{flog.length === 0 ? (
<Empty>{t("Функции ещё не отключались.")}</Empty>
) : (
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
{flog.map((e) => (
<li key={e.id} className="flex flex-wrap gap-2">
<span className="text-muted-foreground">{new Date(e.at).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })}</span>
<span className={e.state === "unavailable" ? "text-destructive" : "text-ok"}>{e.state === "unavailable" ? t("отключена") : t("снова включена")}</span>
<span className="font-medium">{t(FEATURES[e.name].label)}</span>
{e.reason && <span className="text-muted-foreground">{e.reason}</span>}
</li>
))}
</ul>
)}
</Disclosure>
</Section>
</div>
</Workspace>
);

View File

@ -1,4 +1,4 @@
import { CONNECT_HELP, googleEnabled, connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
import { CONNECT_HELP, featureGateView, googleEnabled, connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
import { Hidden } from "@/components/cards";
import { ago, Disclosure, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
import { Button } from "@/components/ui/button";
@ -6,6 +6,8 @@ import { Card } from "@/components/ui/card";
import { Input, Label } from "@/components/ui/input";
import { GoogleSignIn } from "@/components/GoogleSignIn";
import { EgovSign } from "@/components/EgovSign";
import { FeatureGate } from "@/components/FeatureGate";
import { LiveRefresh } from "@/components/LiveRefresh";
import { OwnBotSteps } from "@/components/OwnBotSteps";
import { voiceStoriesEnabled } from "@peppa/shared";
import { Workspace } from "@/components/Workspace";
@ -50,10 +52,14 @@ export default async function Settings({ searchParams }: { searchParams: Promise
const vapid = await vapidPublicKey(db);
const t = await getT();
const connect = CONNECT_HELP[await getLocale()] ?? CONNECT_HELP.ru;
// PEP-224: features whose service is down are grey here (eGov binding, connecting AI clients).
const egovGate = featureGateView("egov_login");
const mcpGate = featureGateView("mcp");
const ownBotSteps = <OwnBotSteps botUsername={user.telegramBotUsername} back="/settings" />;
return (
<Workspace>
<div className="max-w-2xl">
<LiveRefresh scope="features" indicator={false} pollMs={30_000} />
<Flash error={error} />
<PageHeader title={t("Настройки")} />
<Section title={t("Язык интерфейса")} id="language">
@ -146,7 +152,9 @@ export default async function Settings({ searchParams }: { searchParams: Promise
<Card>
<p className="m-0 text-sm">{t("Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. Вход в Peppa FACTORY — только через eGov.")}</p>
<div className="max-w-xs">
<EgovSign purpose="link" label={t("Привязать eGov")} />
<FeatureGate view={egovGate} label={t("Привязать eGov")}>
<EgovSign purpose="link" label={t("Привязать eGov")} />
</FeatureGate>
</div>
</Card>
</Section>
@ -309,12 +317,14 @@ export default async function Settings({ searchParams }: { searchParams: Promise
</Section>
<Section title={w.engineer ? t("MCP для ChatGPT и других клиентов") : t("Peppa FACTORY в вашем Claude или ChatGPT")}>
<p className="m-0 text-sm">{w.engineer ? t("Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране Peppa FACTORY.") : t("Подключите Peppa FACTORY к своему чату — и ставьте задачи и отвечайте агентам прямо из него. Понадобится этот адрес; доступ вы подтвердите на экране Peppa FACTORY.")}</p>
<CopyText value={`${origin}/mcp`} label={connect.copy} done={connect.copied} />
<p className="m-0 text-sm">
<a href="/help/connect" className="font-medium text-primary">{connect.linkLabel} →</a>
{" · "}
<a href="/mcp-guide" className="font-medium text-primary">{t("Инструкция для ИИ")} →</a>
</p>
<FeatureGate view={mcpGate} title={t("MCP временно недоступен")}>
<CopyText value={`${origin}/mcp`} label={connect.copy} done={connect.copied} />
<p className="m-0 text-sm">
<a href="/help/connect" className="font-medium text-primary">{connect.linkLabel} →</a>
{" · "}
<a href="/mcp-guide" className="font-medium text-primary">{t("Инструкция для ИИ")} →</a>
</p>
</FeatureGate>
</Section>
<Section title={t("Подключённые приложения")} id="apps">
{apps.length === 0 ? (

View File

@ -12,9 +12,11 @@ const fail = async (status: number, error: string) => Response.json({ error: (aw
export async function GET(req: Request) {
const user = await currentUser();
if (!user) return fail(401, m("Нужен вход"));
try {
return await liveSse(db, user, parseScopes(new URL(req.url).searchParams.get("scope")), req.signal);
const scopes = parseScopes(new URL(req.url).searchParams.get("scope"));
// PEP-224: only `features` (state of platform features, no user data) is open without a sign-in.
if (!user && scopes.some((s) => s !== "features")) return fail(401, m("Нужен вход"));
return await liveSse(db, user, scopes, req.signal);
} catch (e) {
if (e instanceof LiveError) return fail(e.status, e.message);
console.error("live:", e);

View File

@ -1,6 +1,8 @@
import { redirect } from "next/navigation";
import { Check, Laptop, MessageCircle, ShieldCheck, Sparkles } from "lucide-react";
import { googleEnabled } from "@peppa/core";
import { featureGateView, googleEnabled } from "@peppa/core";
import { FeatureGate } from "@/components/FeatureGate";
import { LiveRefresh } from "@/components/LiveRefresh";
import { currentUser, safeNext } from "@/lib/auth";
import { Brand } from "@/components/Brand";
import { GoogleSignIn } from "@/components/GoogleSignIn";
@ -40,6 +42,11 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
const { error, next } = await searchParams;
if (await currentUser()) redirect(safeNext(next));
const t = await getT();
// PEP-224: eGov known to be down — a grey button with a caption; Google (if on) becomes the main way in.
const egov = featureGateView("egov_login");
const egovDown = egov.state === "unavailable";
const google = googleEnabled();
const googleButton = google && <GoogleSignIn purpose="login" next={safeNext(next)} label={t("Войти через Google")} primary={egovDown} />;
return (
<main className="relative mx-auto grid min-h-dvh w-full max-w-6xl content-start items-start gap-x-10 gap-y-8 px-5 py-10 lg:grid-cols-[minmax(0,1fr)_380px] lg:py-16">
<LanguageSwitcher className="absolute top-3 right-5 z-10" />
@ -57,8 +64,13 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
<h2 className="m-0 text-xl font-semibold">{t("Начать — одна минута")}</h2>
<p className="m-0 text-sm text-muted-foreground">{t("Вход через eGov или Google. Первый вход сам создаёт учётку — регистрироваться отдельно не нужно.")}</p>
<Flash error={error ? t.text(error) : undefined} />
<EgovSign purpose="login" next={safeNext(next)} label={t("Войти через eGov")} />
{googleEnabled() && <GoogleSignIn purpose="login" next={safeNext(next)} label={t("Войти через Google")} />}
<LiveRefresh scope="features" indicator={false} pollMs={30_000} />
{egovDown && googleButton}
<FeatureGate view={egov} label={t("Войти через eGov")}>
<EgovSign purpose="login" next={safeNext(next)} label={t("Войти через eGov")} />
</FeatureGate>
{!egovDown && googleButton}
{egovDown && !google && <p className="m-0 text-sm text-muted-foreground">{t("Другого способа входа сейчас нет. Откройте эту страницу позже — кнопка заработает сама, как только eGov снова будет доступен.")}</p>}
<p className="m-0 text-xs text-muted-foreground lg:hidden">{t("Вы с телефона? Войти можно и отсюда, но управлять фабрикой удобнее с ноутбука.")}</p>
</aside>

View File

@ -1,4 +1,6 @@
import { MCP_GUIDE } from "@peppa/core";
import { featureGateView, MCP_GUIDE } from "@peppa/core";
import { FeatureGate } from "@/components/FeatureGate";
import { LiveRefresh } from "@/components/LiveRefresh";
import { Brand } from "@/components/Brand";
import { GuideCopy } from "@/components/GuideCopy";
import { getT } from "@/lib/i18n";
@ -13,7 +15,10 @@ export default async function McpGuide() {
<Brand />
<h1 className="m-0 text-xl font-semibold">{t("Инструкция для ИИ")}</h1>
<p className="m-0 text-muted-foreground">{t("Памятка для ИИ, подключённого к Peppa FACTORY. Вставьте её в «Инструкции» проекта ChatGPT или в системное сообщение другого ИИ.")}</p>
<GuideCopy value={MCP_GUIDE} label={t("Скопировать")} done={t("Скопировано")} />
<LiveRefresh scope="features" indicator={false} pollMs={30_000} />
<FeatureGate view={featureGateView("mcp")} title={t("MCP временно недоступен")}>
<GuideCopy value={MCP_GUIDE} label={t("Скопировать")} done={t("Скопировано")} />
</FeatureGate>
</main>
);
}

View File

@ -1,5 +1,6 @@
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import { enterActor, getUser, isUserAllowed, verifyAccessToken } from "@peppa/core";
import { enterActor, FEATURES, featureStatus, getUser, isUserAllowed, verifyAccessToken } from "@peppa/core";
import { stripAsIs, t as translate } from "@peppa/shared/i18n";
import { createManagerServer } from "@peppa/mcp/manager";
import { publicOrigin } from "@/lib/auth";
import { db } from "@/lib/db";
@ -20,6 +21,15 @@ export async function POST(req: Request) {
const auth = await verifyAccessToken(db, token);
const user = auth && (await getUser(db, auth.userId));
if (!user || !(await isUserAllowed(db, user))) return unauthorized();
// PEP-224: a service MCP depends on is down (Observability) — say so plainly instead of failing midway.
// HTTP 200 with a JSON-RPC error: a 5xx is replaced by Cloudflare's own page (PEP-194).
if (featureStatus("mcp").state === "unavailable") {
const body = (await req.clone().json().catch(() => null)) as { id?: unknown } | Array<{ id?: unknown }> | null;
const id = (Array.isArray(body) ? body[0]?.id : body?.id) ?? null;
const text = FEATURES.mcp.unavailableText;
const message = `${stripAsIs(text)} / ${stripAsIs(translate("en", text))}`;
return json({ jsonrpc: "2.0", id, error: { code: -32001, message } }, 200, { "Access-Control-Allow-Origin": "*", "Retry-After": "300" });
}
// PEP-48: everything this request does is done by the user through this OAuth client.
enterActor({ kind: "user", userId: user.id, channel: "mcp", clientId: auth.clientId });
const server = createManagerServer(db, user, await publicOrigin());

View File

@ -0,0 +1,41 @@
// PEP-224: a feature that depends on a failing service (Observability) — grey, inactive, with a
// plain caption and the time it failed. Available — its children as they are; unstable — the
// children with a note «может работать с задержками». For any new feature: pass `featureGateView`.
import type { ReactNode } from "react";
import { CircleSlash, Clock } from "lucide-react";
import { serverTimezone, type FeatureGateView } from "@peppa/core";
import { getLocale, getT } from "@/lib/i18n";
import { intlLocale } from "@peppa/shared/i18n";
import { cn } from "@/lib/utils";
export async function FeatureGate({ view, label, title, children, className }: { view: FeatureGateView; /** The grey button's text (a button-like control). */ label?: ReactNode; /** A grey status instead (an instruction, a section). */ title?: ReactNode; children: ReactNode; className?: string }) {
if (view.state === "available") return <>{children}</>;
const t = await getT();
if (view.state === "degraded")
return (
<>
{children}
<p className="m-0 flex items-center gap-1.5 text-xs text-warn" data-feature={view.name} data-feature-state="degraded">
<Clock className="size-3.5 shrink-0" /> {t.text(view.text)}
</p>
</>
);
const since = view.since ? new Date(view.since).toLocaleTimeString(intlLocale(await getLocale()), { hour: "2-digit", minute: "2-digit", timeZone: serverTimezone() }) : null;
return (
<div className={cn("flex w-full flex-col gap-1.5", className)} data-feature={view.name} data-feature-state="unavailable">
{label ? (
<button type="button" disabled aria-disabled="true" className="inline-flex h-10 w-full cursor-not-allowed items-center justify-center gap-2 rounded-md border border-dashed bg-muted px-4 text-sm font-medium text-muted-foreground opacity-80">
<CircleSlash className="size-4" /> {label}
</button>
) : (
<div role="status" aria-disabled="true" className="flex items-center gap-2 rounded-lg border border-dashed bg-muted px-4 py-3 text-sm font-medium text-muted-foreground">
<CircleSlash className="size-4 shrink-0" /> {title}
</div>
)}
<p className="m-0 text-xs text-muted-foreground">
{t.text(view.text)}
{since ? ` · ${t("с {time}", { time: since })}` : ""}
</p>
</div>
);
}

View File

@ -1,12 +1,12 @@
import { Button } from "@/components/ui/button";
/** «Войти через Google» / «Привязать Google» (PEP-90): обычная форма, браузер уходит на Google. */
export function GoogleSignIn({ purpose, next, label }: { purpose: "login" | "link"; next?: string; label: string }) {
export function GoogleSignIn({ purpose, next, label, primary = false }: { purpose: "login" | "link"; next?: string; label: string; /** PEP-224: the main way in while eGov is unavailable. */ primary?: boolean }) {
return (
<form method="post" action="/auth/google/start" className="w-full">
<input type="hidden" name="purpose" value={purpose} />
{next && <input type="hidden" name="next" value={next} />}
<Button type="submit" variant="outline" size="lg" className="w-full">
<Button type="submit" variant={primary ? "default" : "outline"} size="lg" className="w-full">
<svg aria-hidden viewBox="0 0 48 48" className="size-4">
<path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9.1 3.6l6.8-6.8C35.8 2.4 30.3 0 24 0 14.6 0 6.5 5.4 2.6 13.2l7.9 6.1C12.4 13.6 17.7 9.5 24 9.5z" />
<path fill="#4285F4" d="M46.5 24.5c0-1.6-.1-3.1-.4-4.5H24v9h12.7c-.6 3-2.3 5.5-4.8 7.2l7.5 5.8c4.4-4.1 7.1-10.1 7.1-17.5z" />

View File

@ -1,6 +1,6 @@
// Observability (PEP-202): shared pieces of the monitors list and the monitor page.
// glossary-ignore-file: the section is for the superadmin only.
import type { MonitorKind, MonitorState, MonitorView } from "@peppa/core";
import { FEATURE_NAMES, FEATURES, type MonitorKind, type MonitorState, type MonitorView } from "@peppa/core";
import type { Translator } from "@peppa/shared/i18n";
import { Badge } from "@/components/ui/badge";
import { Input, Label, NativeSelect } from "@/components/ui/input";
@ -89,6 +89,17 @@ export function MonitorFields({ t, m, kindFixed }: { t: Translator; m?: MonitorV
{t("Запас heartbeat, с")}
<Input name="graceSec" type="number" min={0} defaultValue={tg.graceSec != null ? String(tg.graceSec) : ""} placeholder="60" className="h-8" />
</Label>
<fieldset className="m-0 flex flex-col gap-1 border-0 p-0 sm:col-span-2">
<legend className="mb-1 text-sm font-medium">{t("Что отключать при сбое")}</legend>
<span className="flex flex-wrap gap-x-4 gap-y-1">
{FEATURE_NAMES.map((f) => (
<label key={f} className="flex items-center gap-1.5 text-sm">
<input type="checkbox" name="features" value={f} defaultChecked={m?.features.includes(f)} className="size-4 accent-primary" />
{t(FEATURES[f].label)}
</label>
))}
</span>
</fieldset>
</div>
);
}

View File

@ -0,0 +1,52 @@
# Design: PEP-224
## Где хранить связку
Связка «мониторинг → функции» — колонка `monitors.features` (JSON-массив имён) в
`observe.db`: её меняют вместе с мониторингом («Что отключать при сбое» на странице
мониторинга, `features` в MCP `create_monitor`/`update_monitor`). Порог на функцию и
последнее объявленное состояние — таблица `features (name, disable_after_min, state,
since, reason, changed_at)`; журнал — `feature_log`. Основная БД не меняется: всё, что
касается мониторингов, живёт в `observe.db` (PEP-202).
## Правило (чистая функция `computeFeatures`)
Для каждой функции берутся её мониторинги не на паузе:
- `unavailable` — хотя бы один в `down` дольше `disableAfterMin` (от `state_since`);
тихие сбои (весь интернет) тоже считаются — пользователю всё равно недоступно;
- `degraded` — хотя бы один `degraded` (или `down` моложе порога не считается);
- иначе `available`. Восстановление — по состоянию мониторинга, т.е. после его
`recover_threshold` хороших проверок.
`since` — самое раннее `state_since` упавших мониторингов (время, с которого сбой).
## Чтение
`featureStatus(name)` / `featureStatuses()` считают на лету из `observe.db` (одно чтение
таблицы мониторингов) с кэшем 15 с на процесс. Любая ошибка (файла нет, повреждён,
занят) → функция доступна: сбой мониторинга не блокирует вход. Сервер проверяет сам:
`startEgovFlow` при `unavailable` — `PeppaError` до запроса к relay; `/mcp` — ошибка
JSON-RPC с тем же текстом и 503.
## Объявление и живое обновление
`featureTick` в сервисе мониторингов (каждую секунду, после проверок) сравнивает
посчитанное с `features.state`; смена → `feature_log`, событие `feature_disabled` /
`feature_enabled` в журнале платформенного проекта (запись в основную БД будит
`LiveHub` через `data_version`), сообщение в канал «services» (`postToChannel`, без
канала — `alertAdmins`) и `notify()`. Первое вычисление только запоминает состояние
(«доступна» не объявляется). Новая живая область `features` — отпечаток из
`features.state`; `/api/live?scope=features` открыт без входа (только эта область:
в ней нет данных пользователей), страница входа её слушает.
## Тексты
Пользователю — без «relay», «DNS», «OAuth»: «Временно недоступно — технические
неполадки на стороне eGov. Попробуйте позже», «MCP временно недоступен». Сообщения в
канал «services» и `/observability` — для суперадмина, там названия мониторингов как есть.
## Встроенные мониторинги MCP
`seedFeatureMonitors` (один раз, `observe_meta 'seeded:mcp'`): при `PEPPA_WEB_URL` не на
localhost создаёт «MCP-сервер /mcp» (GET `/mcp`, ожидается 401 — без токена сервер
отвечает «нужен вход») и «MCP — вход OAuth» (`/.well-known/oauth-authorization-server`,
текст `token_endpoint`), оба с `features: ["mcp"]`. Миграция v2 проставляет
`egov_login` встроенным «eGov relay» и «eGov relay — DNS».
## Остальные функции
`google_login`, `bot`, `voice`, `bugsink` есть в списке, но без связанных мониторингов
— доступны, пока суперадмин не свяжет мониторинг. Серой в интерфейсе пока делаются только
eGov и MCP; `FeatureGate` — для следующих.

View File

@ -0,0 +1,31 @@
# PEP-224: статус функций из мониторинга
## Why
Мониторинг (PEP-202) знает, что eGov relay или MCP не работает, а интерфейс — нет: человек
сканирует QR, ждёт пять минут и получает ошибку. Функция, зависящая от упавшего сервиса,
должна сама становиться серой с понятной подписью и сама возвращаться после восстановления.
## What Changes
- `core/feature-status.ts`: список функций платформы (`egov_login`, `mcp`, `google_login`,
`bot`, `voice`, `bugsink`), связка «мониторинг → функции» (поле `features` мониторинга),
порог `disableAfterMin` на функцию (по умолчанию 5), чистое правило `computeFeatures`
и дешёвое чтение `featureStatus(name)` (кэш 15 с, сбой `observe.db` → доступна).
- `observe.db` v2: колонка `monitors.features`, таблицы `features` (порог, объявленное
состояние) и `feature_log` (журнал включений/выключений). Встроенные мониторинги eGov
получают `egov_login`; новые встроенные «MCP-сервер /mcp» и «MCP — вход OAuth» — `mcp`.
- Сервис мониторингов: `featureTick` — смена статуса функции → запись в журнал, событие
платформенного проекта, одно сообщение в канал «services» (иначе админам), `notify()`.
- Сервер: `startEgovFlow` при недоступности отказывает `PeppaError` без запроса к relay;
`/mcp` при недоступности отвечает понятной ошибкой JSON-RPC.
- Интерфейс: компонент `FeatureGate`; вход (eGov серый, Google — основной, нет других
способов — подпись), «Настройки → eGov», «Настройки → Peppa FACTORY в вашем Claude или
ChatGPT», `/mcp-guide`, «Помощь → Подключение» — серый статус. Живая область `features`
(доступна и без входа) — кнопка оживает без перезагрузки.
- `/observability`: «Функции» (статус, порог, журнал), у мониторинга «Что отключать при
сбое»; MCP `create_monitor`/`update_monitor` принимают `features`.
## Impact
- Код: `packages/core` (feature-status, observe), `apps/observer`, `packages/mcp`
(monitors), `packages/runner` (live), `apps/web` (вход, настройки, mcp-guide, помощь,
observability, /mcp, /auth/egov/start, /api/live).
- Данные: миграция `observe.db` (user_version 2), основная БД не меняется.

View File

@ -0,0 +1,63 @@
## ADDED Requirements
### Requirement: Статус функции из мониторингов
Peppa SHALL считать функцию платформы недоступной, если связанный с ней мониторинг находится в состоянии «не работает» дольше порога функции (по умолчанию 5 минут), и SHALL снова считать её доступной после восстановления мониторинга. Состояние «нестабильно» SHALL давать только пометку о возможных задержках. Сбой чтения базы мониторингов SHALL оставлять функцию доступной.
#### Scenario: eGov relay лежит дольше порога
- **GIVEN** мониторинг «eGov relay» связан с функцией «Вход через eGov», порог 5 мин
- **AND** мониторинг в состоянии «не работает» 6 минут
- **WHEN** страница входа читает статус функции
- **THEN** функция «Вход через eGov» недоступна с временем начала сбоя
#### Scenario: Сбой короче порога
- **GIVEN** мониторинг «eGov relay» в состоянии «не работает» 2 минуты
- **WHEN** читается статус функции «Вход через eGov»
- **THEN** функция доступна
#### Scenario: Мониторинг восстановился
- **GIVEN** функция «Вход через eGov» недоступна
- **WHEN** мониторинг «eGov relay» после двух удачных проверок снова «работает»
- **THEN** функция доступна
#### Scenario: База мониторингов недоступна
- **GIVEN** файл базы мониторингов не открывается
- **WHEN** читается статус функции «Вход через eGov»
- **THEN** функция доступна
### Requirement: Сервер не начинает недоступное
Начало входа через eGov SHALL отказывать понятным сообщением, не обращаясь к eGov, когда функция «Вход через eGov» недоступна. Удалённый MCP SHALL отвечать клиенту понятной ошибкой, когда функция «MCP» недоступна.
#### Scenario: Отказ без запроса к eGov
- **GIVEN** функция «Вход через eGov» недоступна
- **WHEN** пользователь нажимает «Войти через eGov»
- **THEN** приходит ответ «Временно недоступно — технические неполадки на стороне eGov. Попробуйте позже»
- **AND** запроса к eGov не было
### Requirement: Недоступное серое в интерфейсе
Кнопка или инструкция недоступной функции SHALL быть серой и неактивной с подписью «временно недоступно» и временем начала сбоя и SHALL оживать без перезагрузки страницы после восстановления. На странице входа при недоступном eGov другой способ входа SHALL оставаться рабочим и выделенным; если других способов нет, страница SHALL говорить об этом.
#### Scenario: Вход при упавшем eGov
- **GIVEN** функция «Вход через eGov» недоступна
- **AND** вход через Google включён
- **WHEN** человек открывает страницу входа
- **THEN** кнопка «Войти через eGov» серая с подписью «Временно недоступно — технические неполадки на стороне eGov. Попробуйте позже»
- **AND** кнопка «Войти через Google» активна и выделена
#### Scenario: MCP недоступен
- **GIVEN** функция «MCP» недоступна
- **WHEN** пользователь открывает «Настройки»
- **THEN** вместо адреса подключения — серый статус «MCP временно недоступен»
### Requirement: Журнал включений и выключений
Смена статуса функции SHALL записываться в журнал на странице Observability и SHALL давать одно сообщение в канал платформы «services». Связку функции с мониторингами SHALL менять суперадмин на странице мониторинга и через MCP.
#### Scenario: Функция отключена и включена
- **GIVEN** канал платформы настроен
- **WHEN** функция «Вход через eGov» становится недоступной, а потом доступной
- **THEN** в канал ушли два сообщения: «отключён для пользователей» и «снова включён»
- **AND** на Observability в журнале функций две записи
#### Scenario: Связка через MCP
- **GIVEN** мониторинг «Bugsink» без связанных функций
- **WHEN** суперадмин вызывает `update_monitor` с `features: ["bugsink"]`
- **THEN** мониторинг связан с функцией «Отслеживание ошибок»

View File

@ -0,0 +1,16 @@
## 1. Ядро
- [ ] 1.1 `observe.db` v2: `monitors.features`, `features`, `feature_log`; eGov-мониторингам `egov_login`; `features` в create/update мониторинга
- [ ] 1.2 `core/feature-status.ts`: список функций, `computeFeatures`, `featureStatus(es)` с кэшем, `setFeatureThreshold`, `featureTick`, тексты
- [ ] 1.3 Встроенные мониторинги MCP (`seedFeatureMonitors`), `featureTick` в сервисе мониторингов
- [ ] 1.4 `startEgovFlow` отказывает при недоступности
## 2. Веб и MCP
- [ ] 2.1 Живая область `features` (без входа)
- [ ] 2.2 `FeatureGate`; вход, «Настройки → eGov», подключение ИИ-клиентов, `/mcp-guide`, помощь
- [ ] 2.3 `/mcp` — понятная ошибка при недоступности
- [ ] 2.4 `/observability`: «Функции», «Что отключать при сбое»; MCP `features`
- [ ] 2.5 Переводы en/kk, словарь
## 3. Проверка
- [ ] 3.1 Тест `feature-status.test.ts`
- [ ] 3.2 Проверки (lint, typecheck, тесты), браузер

View File

@ -2,6 +2,7 @@
// short-lived <auth><challenge/><nonce/></auth>, reads the signed XML from the relay itself and takes
// the signer's IIN from the certificate. The XMLDSig itself is not verified here — the relay is
// trusted (PM decision, see openspec design); the challenge and nonce never leave the server.
import { assertFeatureAvailable } from "./feature-status.ts";
import { m as tr } from "@peppa/shared/i18n";
import { randomBytes, randomInt, randomUUID } from "node:crypto";
import { and, eq, gte, inArray, sql } from "drizzle-orm";
@ -193,6 +194,8 @@ export async function startEgovFlow(db: Db, purpose: EgovPurpose, userId: number
async function startEgovFlowInner(db: Db, purpose: EgovPurpose, userId: number | null): Promise<EgovStart> {
if (purpose === "link" && !userId) throw new PeppaError(tr("Привязать eGov можно только после входа"));
// PEP-224: eGov is known to be down — say so now instead of a QR that never signs.
assertFeatureAvailable("egov_login");
const env = loadEnv();
const nonce = randomUUID();
const challenge = randomBytes(32).toString("base64url");

View File

@ -0,0 +1,5 @@
// PEP-224: the platform features a monitor can switch off (no imports: observe.ts and
// feature-status.ts both use it).
export const FEATURE_NAMES = ["egov_login", "mcp", "google_login", "bot", "voice", "bugsink"] as const;
export type FeatureName = (typeof FEATURE_NAMES)[number];
export const isFeatureName = (v: unknown): v is FeatureName => (FEATURE_NAMES as readonly string[]).includes(String(v));

View File

@ -0,0 +1,227 @@
// PEP-224: platform features follow their monitors (PEP-202). A feature is `unavailable` while one
// of its monitors has been down longer than the feature's threshold (default 5 min), `degraded`
// while one is unstable, `available` otherwise — recovery follows the monitor's own
// recover_threshold. Reading is cheap (one query of observe.db, cached 15 s per process) and never
// blocks: any trouble with observe.db means «available». The observer announces changes
// (`featureTick`): the journal, one message to the «services» channel, a poke for live pages.
import type { Db } from "@peppa/db";
import { m as tr } from "@peppa/shared/i18n";
import { PeppaError } from "./errors.ts";
import { FEATURE_NAMES, isFeatureName, type FeatureName } from "./feature-names.ts";
import { alertAdmins } from "./monitor.ts";
import { notify } from "./notify.ts";
import { listMonitors, observeDb, type Monitor } from "./observe.ts";
import { getPlatformChannel, platformProjectKey, postToChannel } from "./platform-channel.ts";
import { logEvent } from "./audit.ts";
import { getProject } from "./projects.ts";
export { FEATURE_NAMES, isFeatureName, type FeatureName } from "./feature-names.ts";
export type FeatureState = "available" | "degraded" | "unavailable";
export interface FeatureInfo {
/** For people (a key of the translations). */
label: string;
/** What a person sees on a grey button. */
unavailableText: string;
}
const GENERIC = tr("Временно недоступно — технические неполадки. Попробуйте позже");
export const FEATURES: Record<FeatureName, FeatureInfo> = {
egov_login: { label: tr("Вход через eGov"), unavailableText: tr("Временно недоступно — технические неполадки на стороне eGov. Попробуйте позже") },
mcp: { label: tr("Подключение к Claude и ChatGPT"), unavailableText: tr("MCP временно недоступен — технические неполадки. Попробуйте позже") },
google_login: { label: tr("Вход через Google"), unavailableText: tr("Временно недоступно — технические неполадки на стороне Google. Попробуйте позже") },
bot: { label: tr("Telegram-бот"), unavailableText: GENERIC },
voice: { label: tr("Голосовой ввод"), unavailableText: GENERIC },
bugsink: { label: tr("Отслеживание ошибок"), unavailableText: GENERIC },
};
export const DEGRADED_TEXT = tr("Может работать с задержками");
export const DEFAULT_DISABLE_AFTER_MIN = 5;
const CACHE_MS = 15_000;
export interface FeatureStatus {
name: FeatureName;
state: FeatureState;
/** Since when the linked service fails (unavailable / degraded). */
since: string | null;
disableAfterMin: number;
/** Linked monitors (not on pause). */
monitors: Array<Pick<Monitor, "id" | "name" | "state" | "stateSince">>;
/** Monitors that make the state, with their last reason. */
failing: Array<{ id: number; name: string; state: Monitor["state"]; since: string | null; reason: string }>;
}
type MonitorLike = Pick<Monitor, "id" | "name" | "state" | "stateSince" | "paused" | "features" | "lastDetail">;
/** The rule, pure: monitors + thresholds → the state of every feature. */
export function computeFeatures(monitors: MonitorLike[], thresholds: Partial<Record<FeatureName, number>>, now = new Date()): Record<FeatureName, FeatureStatus> {
const out = {} as Record<FeatureName, FeatureStatus>;
for (const name of FEATURE_NAMES) {
const disableAfterMin = thresholds[name] ?? DEFAULT_DISABLE_AFTER_MIN;
const linked = monitors.filter((m) => !m.paused && m.features.includes(name));
const longDown = linked.filter((m) => m.state === "down" && now.getTime() - Date.parse(m.stateSince ?? now.toISOString()) >= disableAfterMin * 60_000);
const shaky = linked.filter((m) => m.state === "degraded");
const state: FeatureState = longDown.length ? "unavailable" : shaky.length ? "degraded" : "available";
const failing = (state === "unavailable" ? longDown : state === "degraded" ? shaky : []).map((m) => ({
id: m.id,
name: m.name,
state: m.state,
since: m.stateSince,
reason: String(m.lastDetail?.reason ?? ""),
}));
const since = failing.map((f) => f.since).filter((s): s is string => !!s).sort()[0] ?? null;
out[name] = { name, state, since, disableAfterMin, monitors: linked.map((m) => ({ id: m.id, name: m.name, state: m.state, stateSince: m.stateSince })), failing };
}
return out;
}
const allAvailable = (): Record<FeatureName, FeatureStatus> => computeFeatures([], {});
/** Per-feature thresholds set by the superadmin (no row = 5 min). */
export function featureThresholds(): Partial<Record<FeatureName, number>> {
const out: Partial<Record<FeatureName, number>> = {};
for (const r of observeDb().prepare("SELECT name, disable_after_min FROM features WHERE disable_after_min IS NOT NULL").all() as Array<{ name: string; disable_after_min: number }>)
if (isFeatureName(r.name)) out[r.name] = Number(r.disable_after_min);
return out;
}
let cache: { at: number; value: Record<FeatureName, FeatureStatus> } | null = null;
/** Tests and the superadmin's changes: read afresh next time. */
export function resetFeatureCache(): void {
cache = null;
}
/** Every feature's state (cached 15 s); trouble with observe.db = everything available. */
export function featureStatuses(o: { now?: Date; fresh?: boolean } = {}): Record<FeatureName, FeatureStatus> {
const now = o.now ?? new Date();
if (!o.fresh && !o.now && cache && Date.now() - cache.at < CACHE_MS) return cache.value;
let value: Record<FeatureName, FeatureStatus>;
try {
value = computeFeatures(listMonitors(), featureThresholds(), now);
} catch (e) {
console.error("feature-status: observe.db unavailable, everything counts as available:", (e as Error).message);
value = allAvailable();
}
if (!o.now) cache = { at: Date.now(), value };
return value;
}
export const featureStatus = (name: FeatureName, o: { now?: Date; fresh?: boolean } = {}): FeatureStatus => featureStatuses(o)[name];
/** Servers check too: refuses (PeppaError with the person's text) when the feature is unavailable. */
export function assertFeatureAvailable(name: FeatureName, o: { now?: Date } = {}): void {
if (featureStatus(name, o).state === "unavailable") throw new PeppaError(FEATURES[name].unavailableText);
}
/** A grey control's data for the web (kept small: it goes to client components). */
export interface FeatureGateView {
name: FeatureName;
state: FeatureState;
since: string | null;
text: string;
}
export function featureGateView(name: FeatureName, o: { now?: Date } = {}): FeatureGateView {
const s = featureStatus(name, o);
return { name, state: s.state, since: s.since, text: s.state === "unavailable" ? FEATURES[name].unavailableText : s.state === "degraded" ? DEGRADED_TEXT : "" };
}
export function setFeatureThreshold(name: string, minutes: number): void {
if (!isFeatureName(name)) throw new PeppaError(tr("Неизвестная функция: {name}. Есть: {list}", { name, list: FEATURE_NAMES.join(", ") }));
if (!Number.isInteger(minutes) || minutes < 0 || minutes > 1440) throw new PeppaError(tr("{field}: целое число от {min} до {max}", { field: "disableAfterMin", min: 0, max: 1440 }));
observeDb().prepare("INSERT INTO features (name, disable_after_min) VALUES (?, ?) ON CONFLICT(name) DO UPDATE SET disable_after_min = excluded.disable_after_min").run(name, minutes);
resetFeatureCache();
}
export interface FeatureLogEntry {
id: number;
name: FeatureName;
state: FeatureState;
reason: string;
at: string;
}
export function featureLog(limit = 50): FeatureLogEntry[] {
return (observeDb().prepare("SELECT * FROM feature_log ORDER BY at DESC, id DESC LIMIT ?").all(limit) as Array<Record<string, unknown>>)
.filter((r) => isFeatureName(r.name))
.map((r) => ({ id: Number(r.id), name: r.name as FeatureName, state: r.state as FeatureState, reason: String(r.reason), at: String(r.at) }));
}
/** Live pages (scope `features`): the announced states; "" when observe.db is unavailable. */
export function featureFingerprint(): string {
try {
return (observeDb().prepare("SELECT coalesce(group_concat(name || ':' || coalesce(state,'') || ':' || coalesce(changed_at,''), ','), '') AS f FROM features").get() as { f: string }).f;
} catch {
return "";
}
}
const esc = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
function why(s: FeatureStatus, now: Date): string {
return s.failing
.map((f) => {
const n = Math.max(1, Math.round((now.getTime() - Date.parse(f.since ?? now.toISOString())) / 60_000));
return f.reason ? `${f.name} — ${f.reason}, ${n} мин` : `${f.name}, ${n} мин`;
})
.join("; ");
}
/** Text of the message to the «services» channel (superadmin's: monitor names as they are). */
export function featureChangeText(s: FeatureStatus, now = new Date()): string {
return s.state === "unavailable"
? tr("⛔ «{feature}» отключено для пользователей: не работает {why}", { feature: FEATURES[s.name].label, why: why(s, now) })
: tr("✅ «{feature}» снова включено для пользователей", { feature: FEATURES[s.name].label });
}
export interface FeatureTickOptions {
now?: Date;
log?: (s: string) => void;
}
/**
* The observer, after its checks: compares the computed states with the announced ones. A change
* to/from «unavailable» goes to the feature journal, the platform project's events and the
* «services» channel (no channel — the superadmins); every change pokes live pages. The first
* computation only remembers. Returns the changed features.
*/
export async function featureTick(db: Db, o: FeatureTickOptions = {}): Promise<FeatureName[]> {
const now = o.now ?? new Date();
const log = o.log ?? (() => {});
const iso = now.toISOString();
const odb = observeDb();
const statuses = computeFeatures(listMonitors(), featureThresholds(), now);
const known = new Map((odb.prepare("SELECT name, state FROM features").all() as Array<{ name: string; state: string | null }>).map((r) => [r.name, r.state]));
const changed: FeatureName[] = [];
for (const name of FEATURE_NAMES) {
const s = statuses[name];
const prev = known.get(name) ?? null;
if (prev === s.state) continue;
const reason = s.state === "available" ? "" : why(s, now);
odb
.prepare("INSERT INTO features (name, state, since, reason, changed_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(name) DO UPDATE SET state = excluded.state, since = excluded.since, reason = excluded.reason, changed_at = excluded.changed_at")
.run(name, s.state, s.since, reason, iso);
changed.push(name);
// The first computation (no state yet) and degraded ↔ available are not announced.
if (prev === null || (prev === "unavailable") === (s.state === "unavailable")) continue;
odb.prepare("INSERT INTO feature_log (name, state, reason, at) VALUES (?, ?, ?, ?)").run(name, s.state === "unavailable" ? "unavailable" : "available", reason, iso);
const text = featureChangeText(s, now);
log(`feature: ${name} ${prev} → ${s.state}${reason ? ` (${reason})` : ""}`);
const p = await getProject(db, platformProjectKey()).catch(() => null);
if (p) await logEvent(db, { projectId: p.id, type: s.state === "unavailable" ? "feature_disabled" : "feature_enabled", payload: { feature: name, reason, since: s.since } }).catch(() => {});
const key = `feature:${name}:${s.state === "unavailable" ? "off" : "on"}:${iso}`;
try {
const channel = await getPlatformChannel(db);
if (!(await postToChannel(db, "services", `mon:ch:${key}`, esc(text), channel))) await alertAdmins(db, `mon:${key}`, text, log);
} catch (e) {
log(`feature: announce failed: ${(e as Error).message}`);
}
}
if (changed.length) {
resetFeatureCache();
for (const name of changed) await notify(db, { type: "feature", name }).catch(() => {});
}
return changed;
}

View File

@ -101,5 +101,6 @@ export * from "./egress.ts";
export * from "./fallback-fetch.ts";
export * from "./observe.ts";
export * from "./observe-checks.ts";
export * from "./feature-status.ts";
export * from "./accept-screen.ts";
export * from "./accept-digest.ts";

View File

@ -11,7 +11,8 @@ export type PeppaNotification =
| { type: "progress"; eventId: number }
| { type: "session_updated"; sessionId: number }
| { type: "incident"; incidentId: number }
| { type: "chat_message"; messageId: number };
| { type: "chat_message"; messageId: number }
| { type: "feature"; name: string };
/** Services that want live updates; each listens on its own unix socket in PEPPA_HOME (web: PEP-37). */
export const SUBSCRIBERS = ["bot", "web"] as const;

View File

@ -14,6 +14,7 @@ import type { Db } from "@peppa/db";
import { PeppaError } from "./errors.ts";
import { alertAdmins } from "./monitor.ts";
import { getPlatformChannel, postToChannel } from "./platform-channel.ts";
import { FEATURE_NAMES, isFeatureName, type FeatureName } from "./feature-names.ts";
import { realObserveProbes, runCheck, type CheckResult, type ObserveProbes } from "./observe-checks.ts";
export type MonitorKind = "http" | "tcp" | "dns" | "internet" | "heartbeat";
@ -71,6 +72,8 @@ export interface Monitor {
lastPingAt: string | null;
lastDetail: Record<string, unknown> | null;
incidentId: number | null;
/** PEP-224: features switched off while this monitor is down. */
features: FeatureName[];
}
export interface MonitorCheck {
@ -102,6 +105,8 @@ export interface MonitorInput {
timeoutMs?: number;
failThreshold?: number;
recoverThreshold?: number;
/** PEP-224: features to switch off while this monitor is down. */
features?: string[];
}
export const MIN_INTERVAL_SEC = 30;
@ -158,7 +163,30 @@ const SCHEMA = [
`CREATE TABLE observe_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
];
/** Each entry upgrades the file by one version (PRAGMA user_version). */
const MIGRATIONS: string[][] = [SCHEMA];
const MIGRATIONS: string[][] = [
SCHEMA,
// PEP-224: monitor → features, per-feature threshold and the announced state, their journal.
[
`ALTER TABLE monitors ADD COLUMN features TEXT NOT NULL DEFAULT '[]'`,
`CREATE TABLE features (
name TEXT PRIMARY KEY,
disable_after_min INTEGER,
state TEXT,
since TEXT,
reason TEXT,
changed_at TEXT
)`,
`CREATE TABLE feature_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
state TEXT NOT NULL,
reason TEXT NOT NULL,
at TEXT NOT NULL
)`,
`CREATE INDEX feature_log_at ON feature_log (at)`,
`UPDATE monitors SET features = '["egov_login"]' WHERE name IN ('eGov relay', 'eGov relay — DNS') AND created_by = 'system'`,
],
];
const opened = new Map<string, DatabaseSync>();
@ -228,6 +256,7 @@ function toMonitor(r: Row): Monitor {
lastPingAt: (r.last_ping_at as string | null) ?? null,
lastDetail: json(r.last_detail, null),
incidentId: r.incident_id == null ? null : Number(r.incident_id),
features: (json(r.features, []) as unknown[]).filter(isFeatureName),
};
}
@ -304,7 +333,14 @@ export function normalizeTarget(kind: MonitorKind, t: Record<string, unknown>):
}
}
function normalize(input: MonitorInput): Required<Omit<MonitorInput, "target">> & { target: MonitorTarget } {
/** PEP-224: known feature names, without repeats; an unknown one is refused. */
export function normalizeFeatures(v: unknown): FeatureName[] {
const list = (Array.isArray(v) ? v : String(v ?? "").split(/[\s,]+/)).map((x) => String(x).trim()).filter(Boolean);
for (const f of list) if (!isFeatureName(f)) bad("Неизвестная функция: {name}. Есть: {list}", { name: f, list: FEATURE_NAMES.join(", ") });
return [...new Set(list)] as FeatureName[];
}
function normalize(input: MonitorInput): Required<Omit<MonitorInput, "target" | "features">> & { target: MonitorTarget; features: FeatureName[] } {
const name = String(input.name ?? "").trim();
if (!name || name.length > 80) bad("Название: от 1 до 80 символов");
if (!MONITOR_KINDS.includes(input.kind)) bad("Неизвестный вид мониторинга: {kind}", { kind: String(input.kind) });
@ -317,6 +353,7 @@ function normalize(input: MonitorInput): Required<Omit<MonitorInput, "target">>
timeoutMs: int(input.timeoutMs ?? 10_000, 1_000, 30_000, "timeoutMs"),
failThreshold: int(input.failThreshold ?? 3, 1, 20, "failThreshold"),
recoverThreshold: int(input.recoverThreshold ?? 2, 1, 20, "recoverThreshold"),
features: normalizeFeatures(input.features ?? []),
};
}
@ -341,10 +378,10 @@ export function createMonitor(input: MonitorInput, author: string, now = new Dat
const token = n.kind === "heartbeat" ? randomBytes(18).toString("base64url") : null;
const r = db
.prepare(
`INSERT INTO monitors (name, kind, target, interval_sec, timeout_ms, fail_threshold, recover_threshold, token, created_by, created_at, updated_at, state_since, last_ping_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`,
`INSERT INTO monitors (name, kind, target, interval_sec, timeout_ms, fail_threshold, recover_threshold, token, created_by, created_at, updated_at, state_since, last_ping_at, features)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`,
)
.get(n.name, n.kind, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, token, author, iso, iso, iso, n.kind === "heartbeat" ? iso : null) as Row;
.get(n.name, n.kind, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, token, author, iso, iso, iso, n.kind === "heartbeat" ? iso : null, JSON.stringify(n.features)) as Row;
return toMonitor(r);
}
@ -360,10 +397,11 @@ export function updateMonitor(id: number, patch: Partial<MonitorInput>, now = ne
timeoutMs: patch.timeoutMs ?? cur.timeoutMs,
failThreshold: patch.failThreshold ?? cur.failThreshold,
recoverThreshold: patch.recoverThreshold ?? cur.recoverThreshold,
features: patch.features ?? cur.features,
});
const r = observeDb()
.prepare(`UPDATE monitors SET name = ?, target = ?, interval_sec = ?, timeout_ms = ?, fail_threshold = ?, recover_threshold = ?, updated_at = ?, last_check_at = NULL WHERE id = ? RETURNING *`)
.get(n.name, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, now.toISOString(), id) as Row;
.prepare(`UPDATE monitors SET name = ?, target = ?, interval_sec = ?, timeout_ms = ?, fail_threshold = ?, recover_threshold = ?, features = ?, updated_at = ?, last_check_at = NULL WHERE id = ? RETURNING *`)
.get(n.name, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, JSON.stringify(n.features), now.toISOString(), id) as Row;
return toMonitor(r);
}
@ -612,10 +650,33 @@ export function seedMonitors(now = new Date()): Monitor[] {
if (db.prepare("SELECT 1 FROM observe_meta WHERE key = 'seeded'").get()) return [];
const made = [
createMonitor({ name: "Интернет", kind: "internet", target: { hosts: DEFAULT_INTERNET_HOSTS }, intervalSec: 60 }, "system", now),
createMonitor({ name: "eGov relay", kind: "http", target: { url: "https://sign.aitu.uz/" }, intervalSec: 60 }, "system", now),
createMonitor({ name: "eGov relay — DNS", kind: "dns", target: { host: "sign.aitu.uz" }, intervalSec: 300 }, "system", now),
createMonitor({ name: "eGov relay", kind: "http", target: { url: "https://sign.aitu.uz/" }, intervalSec: 60, features: ["egov_login"] }, "system", now),
createMonitor({ name: "eGov relay — DNS", kind: "dns", target: { host: "sign.aitu.uz" }, intervalSec: 300, features: ["egov_login"] }, "system", now),
];
db.prepare("INSERT INTO observe_meta (key, value) VALUES ('seeded', ?)").run(now.toISOString());
return made;
}
/**
* PEP-224: «MCP-сервер /mcp» and «MCP — вход OAuth» (they switch off `mcp`), once, when the web has
* a public address. Without a token /mcp answers 401 — that is the sign it is alive.
*/
export function seedFeatureMonitors(webUrl: string | undefined, now = new Date()): Monitor[] {
const db = observeDb();
if (db.prepare("SELECT 1 FROM observe_meta WHERE key = 'seeded:mcp'").get()) return [];
let base: URL;
try {
base = new URL(webUrl ?? "");
} catch {
return [];
}
if (/^(localhost|127\.|\[::1\])/.test(base.hostname)) return [];
const names = new Set(listMonitors().map((m) => m.name));
const made: Monitor[] = [];
if (!names.has("MCP-сервер /mcp")) made.push(createMonitor({ name: "MCP-сервер /mcp", kind: "http", target: { url: new URL("/mcp", base).toString(), expectStatus: [401] }, intervalSec: 60, features: ["mcp"] }, "system", now));
if (!names.has("MCP — вход OAuth"))
made.push(createMonitor({ name: "MCP — вход OAuth", kind: "http", target: { url: new URL("/.well-known/oauth-authorization-server", base).toString(), contains: "token_endpoint" }, intervalSec: 60, features: ["mcp"] }, "system", now));
db.prepare("INSERT INTO observe_meta (key, value) VALUES ('seeded:mcp', ?)").run(now.toISOString());
return made;
}

View File

@ -6,6 +6,8 @@ import {
createMonitor,
deleteMonitor,
describeTarget,
FEATURE_NAMES,
featureStatuses,
getMonitor,
getProject,
logEvent,
@ -51,11 +53,15 @@ const common = {
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)"),
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 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)}`;
`- #${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)}${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);
@ -68,7 +74,9 @@ export function registerMonitorTools(db: Db, define: Define, access: MonitorAcce
define("list_monitors", "Observability (PEP-202): every monitor of the Peppa platform with its state, last reason and uptime for 24 h and 7 days.", {}, true, async () => {
await access.check();
const list = listMonitorViews();
return list.length ? list.map(line).join("\n") : "No monitors.";
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 }) => {
@ -95,7 +103,7 @@ export function registerMonitorTools(db: Db, define: Define, access: MonitorAcce
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 }, who.author);
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, 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.`;
},
@ -104,9 +112,9 @@ export function registerMonitorTools(db: Db, define: Define, access: MonitorAcce
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 });
await journal(db, "monitor_updated", who.sessionId, { id: m.id, name: m.name, author: who.author });
return `Updated #${m.id} ${m.name}.`;
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, 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 }) => {

View File

@ -6,11 +6,11 @@
import { m } from "@peppa/shared/i18n";
import { existsSync, statSync } from "node:fs";
import { join } from "node:path";
import { findChangeDir, listenEvents, projectForUser, STEP_EVENT, stepView, type StepView, type User } from "@peppa/core";
import { featureFingerprint, findChangeDir, resetFeatureCache, listenEvents, projectForUser, STEP_EVENT, stepView, type StepView, type User } from "@peppa/core";
import { events, sessions, tasks, type Db } from "@peppa/db";
import { and, eq, gt } from "drizzle-orm";
export type LiveScope = "home" | "runners" | "chats" | "team" | `project:${number}` | `task:${number}` | `steps:${number}`;
export type LiveScope = "home" | "runners" | "chats" | "team" | "features" | `project:${number}` | `task:${number}` | `steps:${number}`;
export type LiveEvent = { type: "change"; scope: LiveScope } | { type: "step"; scope: LiveScope; step: StepView };
type Listener = (e: LiveEvent) => void;
@ -30,7 +30,7 @@ const WAKE_DEBOUNCE_MS = 250;
export function parseScopes(raw: string | null): LiveScope[] {
const out = new Set<LiveScope>();
for (const part of (raw ?? "").split(",").map((s) => s.trim()).filter(Boolean)) {
if (part === "home" || part === "runners" || part === "chats" || part === "team") out.add(part);
if (part === "home" || part === "runners" || part === "chats" || part === "team" || part === "features") out.add(part);
else if (/^(project|task|steps):[1-9]\d{0,9}$/.test(part)) out.add(part as LiveScope);
else throw new LiveError(m("Неизвестная область: {scope}", { scope: part }), 400);
}
@ -38,8 +38,10 @@ export function parseScopes(raw: string | null): LiveScope[] {
return [...out];
}
/** Access: project/story/runner scopes need the project; home/runners only a user. */
export async function checkScopeAccess(db: Db, user: User, scope: LiveScope): Promise<void> {
/** Access: project/story/runner scopes need the project; home/runners only a user; `features` (PEP-224) nobody. */
export async function checkScopeAccess(db: Db, user: User | null, scope: LiveScope): Promise<void> {
if (scope === "features") return;
if (!user) throw new LiveError(m("Нужен вход"), 401);
const [kind, raw] = scope.split(":") as [string, string?];
const id = Number(raw);
let projectId: number | undefined;
@ -57,6 +59,8 @@ const ACTIVE_SESSIONS = `group_concat(CASE WHEN ended_at IS NULL THEN id || ':'
/** One SQL per scope; frequent fields (last_activity_at, steps, heartbeats) are left out. */
function fingerprint(db: Db, scope: LiveScope): string {
// PEP-224: features follow monitors (observe.db) — no user data, the login page watches it too.
if (scope === "features") return featureFingerprint();
const c = db.$client;
const [kind, raw] = scope.split(":") as [string, string?];
const id = Number(raw);
@ -252,6 +256,8 @@ class LiveHub {
const fp = fingerprint(this.db, scope);
if (fp === this.prints.get(scope)) continue;
this.prints.set(scope, fp);
// PEP-224: the observer announced a feature change — pages must not read the 15 s cache.
if (scope === "features") resetFeatureCache();
for (const fn of set) fn({ type: "change", scope });
} catch (e) {
console.error(`live: ${scope} check failed`, e);
@ -271,7 +277,7 @@ export function liveHub(db: Db): LiveHub {
}
/** SSE response for /api/live: `change` / `step` events, pings for Cloudflare. */
export async function liveSse(db: Db, user: User, scopes: LiveScope[], signal: AbortSignal, opts: { pingMs?: number } = {}): Promise<Response> {
export async function liveSse(db: Db, user: User | null, scopes: LiveScope[], signal: AbortSignal, opts: { pingMs?: number } = {}): Promise<Response> {
for (const s of scopes) await checkScopeAccess(db, user, s);
const enc = new TextEncoder();
let cleanup = () => {};