304 lines
16 KiB
TypeScript
304 lines
16 KiB
TypeScript
// PEP-28: watchdog 2.0 — the watchdog fixes what it can by itself (restarts a crashed or
|
||
// stalled runner within a limit), reminds about unanswered questions and escalates them,
|
||
// and stops runners that wait for nobody. Thresholds: `platform.watchdog` over env.
|
||
import { m } from "@peppa/shared/i18n";
|
||
import { and, eq, gte, inArray, isNull, sql } from "drizzle-orm";
|
||
import {
|
||
alertAdmins,
|
||
deleteSetting,
|
||
deliverToUser,
|
||
getBudgetState,
|
||
getSession,
|
||
getSetting,
|
||
listSessions,
|
||
logSessionEvent,
|
||
pendingSessionQuestions,
|
||
PeppaError,
|
||
projectAudience,
|
||
raiseSessionQuestion,
|
||
touchQuestion,
|
||
sendProjectMessage,
|
||
setSetting,
|
||
updateSession,
|
||
type SessionView,
|
||
getIntakeState,
|
||
} from "@peppa/core";
|
||
import { projects, questions, sessions, tasks, type Db, type WatchState } from "@peppa/db";
|
||
import { formatTaskKey } from "@peppa/shared";
|
||
import { killRunner, resumeSession, stopSession } from "./sessions.ts";
|
||
import * as tmux from "./tmux.ts";
|
||
|
||
export interface WatchdogSettings {
|
||
/** Automatic restarts of one runner within the window; 0 = off. */
|
||
restartMax: number;
|
||
restartWindowMin: number;
|
||
/** Pause before restart attempt 1, 2, 3… (the last one repeats). */
|
||
restartDelaysMin: number[];
|
||
/** A stalled runner whose alert got no answer this long is restarted; 0 = never. */
|
||
stallRestartMin: number;
|
||
/** Reminders about an unanswered question (after 1× and 2× this); 0 = off. */
|
||
remindMin: number;
|
||
/** Then the platform admins hear about it; 0 = off. */
|
||
escalateMin: number;
|
||
/** A story runner in waiting_input with nothing asked is stopped after this; 0 = never. */
|
||
idleStopHours: number;
|
||
}
|
||
|
||
export const WATCHDOG_DEFAULTS: WatchdogSettings = {
|
||
restartMax: 3,
|
||
restartWindowMin: 24 * 60,
|
||
restartDelaysMin: [1, 5, 15],
|
||
stallRestartMin: 60,
|
||
remindMin: 30,
|
||
escalateMin: 120,
|
||
idleStopHours: 24,
|
||
};
|
||
|
||
const KEY = "platform.watchdog";
|
||
const envName = (k: string) => `PEPPA_WATCHDOG_${k.replace(/[A-Z]/g, (c) => `_${c}`).toUpperCase()}`;
|
||
|
||
function parseValue(k: keyof WatchdogSettings, v: string): number | number[] {
|
||
if (k === "restartDelaysMin") {
|
||
const list = v.split(",").map((x) => Number(x.trim()));
|
||
if (!list.length || list.some((n) => !Number.isFinite(n) || n < 0)) throw new PeppaError(m("{key}: список минут через запятую, напр. 1,5,15", { key: k }));
|
||
return list;
|
||
}
|
||
const n = Number(v);
|
||
if (!Number.isFinite(n) || n < 0) throw new PeppaError(m("{key}: нужно число ≥ 0", { key: k }));
|
||
return n;
|
||
}
|
||
|
||
/** Defaults ← env `PEPPA_WATCHDOG_*` ← `platform.watchdog`. */
|
||
export async function getWatchdogSettings(db: Db): Promise<WatchdogSettings> {
|
||
const out: WatchdogSettings = { ...WATCHDOG_DEFAULTS, restartDelaysMin: [...WATCHDOG_DEFAULTS.restartDelaysMin] };
|
||
for (const k of Object.keys(out) as (keyof WatchdogSettings)[]) {
|
||
const v = process.env[envName(k)];
|
||
if (v) (out as any)[k] = parseValue(k, v);
|
||
}
|
||
return { ...out, ...((await getSetting<Partial<WatchdogSettings>>(db, KEY)) ?? {}) };
|
||
}
|
||
|
||
/** `peppa platform watchdog key=value…` / `reset`. */
|
||
export async function setWatchdogSettings(db: Db, pairs: string[]): Promise<WatchdogSettings> {
|
||
if (pairs.length === 1 && pairs[0] === "reset") {
|
||
await deleteSetting(db, KEY);
|
||
return getWatchdogSettings(db);
|
||
}
|
||
const cur = (await getSetting<Partial<WatchdogSettings>>(db, KEY)) ?? {};
|
||
for (const p of pairs) {
|
||
const [k, v] = p.split("=");
|
||
if (!k || v === undefined || !(k in WATCHDOG_DEFAULTS)) throw new PeppaError(m("неизвестная настройка «{name}»; есть: {keys}", { name: p, keys: Object.keys(WATCHDOG_DEFAULTS).join(", ") }));
|
||
if (v === "-") delete (cur as any)[k];
|
||
else (cur as any)[k] = parseValue(k as keyof WatchdogSettings, v);
|
||
}
|
||
await setSetting(db, KEY, cur);
|
||
return getWatchdogSettings(db);
|
||
}
|
||
|
||
// ── runner state ──────────────────────────────────────────────────────────────────
|
||
|
||
/** Merges into `sessions.watch_state` (and into the view in hand). */
|
||
export async function patchWatch(db: Db, s: SessionView, patch: Partial<WatchState>, extra: Parameters<typeof updateSession>[2] = {}): Promise<void> {
|
||
const next: WatchState = { ...(s.watchState ?? {}), ...patch };
|
||
for (const k of Object.keys(next) as (keyof WatchState)[]) if (next[k] === undefined) delete next[k];
|
||
s.watchState = next;
|
||
await updateSession(db, s.id, { ...extra, watchState: next });
|
||
}
|
||
|
||
// ── automatic restarts ────────────────────────────────────────────────────────────
|
||
|
||
const RESTARTABLE_TASK = ["proposing", "in_progress"];
|
||
|
||
/** Why the runner may not be restarted automatically (null = it may). */
|
||
async function restartBlocker(db: Db, s: SessionView, cfg: WatchdogSettings, now: number): Promise<string | null> {
|
||
if (cfg.restartMax <= 0) return m("выключен");
|
||
if (!s.taskId || !s.taskStatus || !RESTARTABLE_TASK.includes(s.taskStatus)) return m("задача не в работе");
|
||
if (s.status === "rate_limited" || s.resumeAt) return m("лимит");
|
||
if (await getBudgetState(db, s.taskId)) return m("бюджет");
|
||
const recent = restartsInWindow(s, cfg, now);
|
||
if (recent.length >= cfg.restartMax) return cfg.restartWindowMin % 60 === 0
|
||
? m("авто-перезапуски исчерпаны ({max} за {n} ч)", { max: cfg.restartMax, n: cfg.restartWindowMin / 60 })
|
||
: m("авто-перезапуски исчерпаны ({max} за {n} мин)", { max: cfg.restartMax, n: cfg.restartWindowMin });
|
||
return null;
|
||
}
|
||
|
||
const restartsInWindow = (s: SessionView, cfg: WatchdogSettings, now: number) => (s.watchState?.restarts ?? []).filter((t) => now - t < cfg.restartWindowMin * 60_000);
|
||
|
||
/**
|
||
* The agent process died (non-zero exit) or its tmux session is gone. A story at work gets
|
||
* a planned restart after a pause instead of a question; otherwise the PM is asked as before.
|
||
* Returns true when a restart was planned.
|
||
*/
|
||
export async function onRunnerCrash(
|
||
db: Db,
|
||
s: SessionView,
|
||
reason: "crash" | "gone",
|
||
alert: string,
|
||
o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void },
|
||
): Promise<boolean> {
|
||
const now = o.now.getTime();
|
||
const blocker = await restartBlocker(db, s, o.cfg, now);
|
||
if (!blocker) {
|
||
const n = restartsInWindow(s, o.cfg, now).length;
|
||
const delays = o.cfg.restartDelaysMin.length ? o.cfg.restartDelaysMin : [0];
|
||
const at = now + delays[Math.min(n, delays.length - 1)]! * 60_000;
|
||
await patchWatch(db, s, { restartAt: at, restartReason: reason }, { status: "failed", endedAt: o.now });
|
||
await logSessionEvent(db, s, "restart_planned", { reason, attempt: n + 1, of: o.cfg.restartMax, at: new Date(at).toISOString() });
|
||
o.log(`#${s.id} ${s.taskKey ?? ""}: ${reason}, restart ${n + 1}/${o.cfg.restartMax} at ${new Date(at).toISOString()}`);
|
||
return true;
|
||
}
|
||
await updateSession(db, s.id, { status: "failed", endedAt: o.now });
|
||
const tail = restartsInWindow(s, o.cfg, now).length && blocker.startsWith("авто-перезапуски") ? `\n\n${blocker}.` : "";
|
||
await raiseSessionQuestion(db, s, "attention", `${alert}${tail}`);
|
||
return false;
|
||
}
|
||
|
||
/** Planned restarts that are due (`failed` runners with `watch_state.restartAt`). */
|
||
export async function restartTick(db: Db, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise<void> {
|
||
const rows = await db
|
||
.select({ id: sessions.id })
|
||
.from(sessions)
|
||
.where(and(eq(sessions.status, "failed"), sql`json_extract(${sessions.watchState}, '$.restartAt') is not null`));
|
||
for (const { id } of rows) {
|
||
const s = await getSession(db, id);
|
||
const ws = s.watchState ?? {};
|
||
if (ws.restartAt == null || ws.restartAt > o.now.getTime()) continue;
|
||
const clear = { restartAt: undefined, restartReason: undefined };
|
||
// The PM may have started another runner for the story, or moved it on.
|
||
const other = s.taskId ? (await listSessions(db, { active: true, taskId: s.taskId })).length : 0;
|
||
const blocker = other ? m("задачу уже ведёт другой агент") : await restartBlocker(db, s, o.cfg, o.now.getTime());
|
||
if (blocker) {
|
||
await patchWatch(db, s, clear);
|
||
await logSessionEvent(db, s, "restart_skipped", { why: blocker });
|
||
if (!other && s.taskStatus && RESTARTABLE_TASK.includes(s.taskStatus))
|
||
await raiseSessionQuestion(db, s, "attention", m("{who}: агент остановился с ошибкой, сам не перезапустился: {reason}.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), reason: blocker }));
|
||
continue;
|
||
}
|
||
const restarts = [...restartsInWindow(s, o.cfg, o.now.getTime()), o.now.getTime()];
|
||
await patchWatch(db, s, { ...clear, restarts, screen: undefined, stallAlertAt: undefined });
|
||
try {
|
||
await resumeSession(db, s.id, {
|
||
prompt: `Раннер ${ws.restartReason === "stall" ? "завис" : "упал"} и перезапущен вачдогом автоматически (попытка ${restarts.length} из ${o.cfg.restartMax}).`,
|
||
});
|
||
await logSessionEvent(db, s, "auto_restarted", { reason: ws.restartReason, attempt: restarts.length, of: o.cfg.restartMax });
|
||
o.log(`#${s.id} ${s.taskKey ?? ""}: restarted automatically (${restarts.length}/${o.cfg.restartMax})`);
|
||
} catch (e) {
|
||
await logSessionEvent(db, s, "restart_failed", { error: (e as Error).message });
|
||
await raiseSessionQuestion(db, s, "attention", m("{who}: не удалось перезапустить автоматически — {error}", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), error: (e as Error).message }));
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* The PM did not react to a stall alert for `stallRestartMin`: kill the stuck agent and
|
||
* restart it now (counts against the restart limit). Returns true when it did.
|
||
*/
|
||
export async function restartStalled(db: Db, s: SessionView, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise<boolean> {
|
||
const at = s.watchState?.stallAlertAt;
|
||
if (!at || o.cfg.stallRestartMin <= 0 || o.now.getTime() - at < o.cfg.stallRestartMin * 60_000) return false;
|
||
const blocker = await restartBlocker(db, s, o.cfg, o.now.getTime());
|
||
if (blocker) {
|
||
await patchWatch(db, s, { stallAlertAt: undefined });
|
||
await logSessionEvent(db, s, "restart_skipped", { reason: "stall", why: blocker });
|
||
return false;
|
||
}
|
||
await killRunner(s).catch(() => {});
|
||
await patchWatch(db, s, { stallAlertAt: undefined, restartAt: o.now.getTime(), restartReason: "stall" }, { status: "failed", endedAt: o.now });
|
||
await logSessionEvent(db, s, "restart_planned", { reason: "stall", attempt: restartsInWindow(s, o.cfg, o.now.getTime()).length + 1, of: o.cfg.restartMax });
|
||
await restartTick(db, o);
|
||
return true;
|
||
}
|
||
|
||
// ── reminders and escalation ──────────────────────────────────────────────────────
|
||
|
||
const REMIND_KINDS = ["question", "permission", "approval"] as const;
|
||
const KIND_RU: Record<string, string> = { question: m("Вопрос"), permission: m("Разрешение"), approval: m("Одобрение плана") };
|
||
|
||
/**
|
||
* Unanswered questions: reminders to the project's people after `remindMin` and 2×, then the
|
||
* platform admins after `escalateMin`. `questions.reminders` is claimed atomically, so every
|
||
* message goes out once whoever ticks. Only questions of the last day (no flood of old ones).
|
||
*/
|
||
export async function remindTick(db: Db, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise<number> {
|
||
const { remindMin, escalateMin } = o.cfg;
|
||
if (remindMin <= 0 && escalateMin <= 0) return 0;
|
||
const now = o.now.getTime();
|
||
const rows = await db
|
||
.select({ q: questions, projectKey: projects.key, taskNumber: tasks.number })
|
||
.from(questions)
|
||
.innerJoin(projects, eq(questions.projectId, projects.id))
|
||
.leftJoin(tasks, eq(questions.taskId, tasks.id))
|
||
.where(and(isNull(questions.answeredAt), inArray(questions.kind, [...REMIND_KINDS]), gestDay(now)));
|
||
let sent = 0;
|
||
for (const { q, projectKey, taskNumber } of rows) {
|
||
// PEP-87: the analyst's questions close themselves at their deadline (PEP-84) — no nagging.
|
||
if (q.taskId && (await getIntakeState(db, q.taskId))?.questionId === q.id) continue;
|
||
const age = now - q.createdAt.getTime();
|
||
const ageMin = Math.round(age / 60_000);
|
||
const n = q.reminders;
|
||
const escalate = escalateMin > 0 && n < 3 && age >= escalateMin * 60_000;
|
||
const remind = !escalate && remindMin > 0 && n < 2 && age >= (n + 1) * remindMin * 60_000;
|
||
if (!escalate && !remind) continue;
|
||
const next = escalate ? 3 : n + 1;
|
||
const [claimed] = await db
|
||
.update(questions)
|
||
.set({ reminders: next })
|
||
.where(and(eq(questions.id, q.id), eq(questions.reminders, n), isNull(questions.answeredAt)))
|
||
.returning({ id: questions.id });
|
||
if (!claimed) continue;
|
||
const where = taskNumber != null ? formatTaskKey(projectKey, taskNumber) : projectKey;
|
||
const url = taskNumber != null ? `/t/${where}` : "/";
|
||
const body = q.text.length > 300 ? `${q.text.slice(0, 300)}…` : q.text;
|
||
if (escalate) {
|
||
await alertAdmins(db, `esc:q${q.id}`, `${m("🚨 {where}: {kind} #{id} без ответа {min} мин — агент ждёт.", { where, kind: KIND_RU[q.kind]?.toLowerCase() ?? "вопрос", id: q.id, min: ageMin })}\n\n${body}`, o.log);
|
||
} else {
|
||
// PEP-151: in the chat a reminder refreshes the question's message, it is not a new one.
|
||
await touchQuestion(db, q.id, now);
|
||
for (const u of await projectAudience(db, q.projectId)) {
|
||
const text = `${m("⏰ {where}: {kind} #{id} ждёт ответа {min} мин.", { where, kind: KIND_RU[q.kind] ?? "Вопрос", id: q.id, min: ageMin })}\n\n${body}`;
|
||
const r = await deliverToUser(db, u, {
|
||
event: "questions",
|
||
projectId: q.projectId,
|
||
dedupeKey: `remind:q${q.id}:${next}:${u.telegramChatId}`,
|
||
pushKey: `remind:q${q.id}:${next}:u${u.id}`,
|
||
telegram: { params: { text } },
|
||
push: { title: m("Ждёт ответа: {where}", { where }), body: body.slice(0, 200), url, tag: `remind:q${q.id}` },
|
||
now: o.now,
|
||
});
|
||
if (r.telegram || r.push) sent++;
|
||
}
|
||
}
|
||
o.log(`question #${q.id}: ${escalate ? "escalated to admins" : `reminder ${next}`} (${ageMin} min)`);
|
||
}
|
||
return sent;
|
||
}
|
||
|
||
const gestDay = (now: number) => gte(questions.createdAt, new Date(now - 24 * 60 * 60_000));
|
||
|
||
// ── idle runners ──────────────────────────────────────────────────────────────────
|
||
|
||
/** A story runner in waiting_input with nothing asked for `idleStopHours` is stopped (resumable). */
|
||
export async function idleStopTick(db: Db, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise<number> {
|
||
if (o.cfg.idleStopHours <= 0) return 0;
|
||
let stopped = 0;
|
||
for (const s of await listSessions(db, { active: true })) {
|
||
if (s.status !== "waiting_input" || !s.taskId || !s.lastActivityAt) continue;
|
||
const idleMs = o.now.getTime() - s.lastActivityAt.getTime();
|
||
if (idleMs < o.cfg.idleStopHours * 3600_000) continue;
|
||
if ((await pendingSessionQuestions(db, s.id)).some((q) => q.kind !== "attention")) continue;
|
||
await stopSession(db, s.id);
|
||
await logSessionEvent(db, s, "idle_stopped", { idleHours: Math.round(idleMs / 3600_000) });
|
||
const who = s.taskKey ?? m("Агент №{id}", { id: s.id });
|
||
await sendProjectMessage(
|
||
db,
|
||
s.projectId,
|
||
m("💤 {who}: агент ждал {n} ч без вопросов — остановлен. Чтобы он продолжил, нажмите «Продолжить» на странице задачи.", { who, n: Math.round(idleMs / 3600_000) }),
|
||
`idle-stop:s${s.id}:${s.generation}`,
|
||
{ title: m("Агент остановлен: {who}", { who }), url: s.taskKey ? `/t/${s.taskKey}` : `/runners?id=${s.id}` },
|
||
);
|
||
o.log(`#${s.id} ${s.taskKey ?? ""}: idle ${Math.round(idleMs / 3600_000)}h in waiting_input, stopped`);
|
||
stopped++;
|
||
}
|
||
return stopped;
|
||
}
|