590 lines
36 KiB
TypeScript
590 lines
36 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 { asIs, m } from "@peppa/shared/i18n";
|
||
import { and, desc, eq, gt, gte, inArray, isNull, sql } from "drizzle-orm";
|
||
import {
|
||
alertAdmins,
|
||
getSubscription,
|
||
updateSubscription,
|
||
deleteSetting,
|
||
deliverToUser,
|
||
getBudgetState,
|
||
getSession,
|
||
getSetting,
|
||
listSessions,
|
||
logSessionEvent,
|
||
pendingSessionQuestions,
|
||
PeppaError,
|
||
questionIsFreeText,
|
||
projectAudience,
|
||
raiseSessionQuestion,
|
||
platformFailure,
|
||
touchQuestion,
|
||
clearPlatformDelay,
|
||
sessionDelay,
|
||
sendProjectMessage,
|
||
setSetting,
|
||
updateSession,
|
||
type SessionView,
|
||
getIntakeState,
|
||
isProjectPaused,
|
||
pausedProjectIds,
|
||
} from "@peppa/core";
|
||
import { events, projects, questions, sessions, tasks, type Db, type WatchState } from "@peppa/db";
|
||
import { formatTaskKey } from "@peppa/shared";
|
||
import { killRunner, resumeSession, stopSession } from "./sessions.ts";
|
||
import { HostUnreachable } from "./exec.ts";
|
||
import * as tmux from "./tmux.ts";
|
||
import type { StartQuestion } from "./start-screen.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;
|
||
/** A reminder about an unanswered question after this (PEP-173: 4 h); 0 = off. */
|
||
remindMin: number;
|
||
/** How many reminders one question gets (PEP-173: one — no nagging). */
|
||
remindMax: number;
|
||
/** Reminders go only in working time (PEP-173): hours [workFrom, workTo) on workDays (1 = Mon … 7 = Sun), platform time zone. */
|
||
workFrom: number;
|
||
workTo: number;
|
||
workDays: 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;
|
||
/** PEP-299: an agent of a story in review, silent this long, gives its place to a story waiting in the queue; 0 = never. */
|
||
reviewReleaseMin: number;
|
||
/** PEP-150: checks of a result's head commit that have not started for this long are a delay; 0 = off. */
|
||
checksStuckMin: number;
|
||
/** PEP-265: a new agent with no action this long and a question of its CLI on screen is a start hang; 0 = off. */
|
||
startHangSec: number;
|
||
/** PEP-287: the docker build cache is pruned hourly down to this many GB; 0 = off. */
|
||
buildCacheGb: number;
|
||
/** PEP-287: free space of the disk below this percent — one message to the superadmins; 0 = off. */
|
||
diskFreeAlertPct: number;
|
||
}
|
||
|
||
export const WATCHDOG_DEFAULTS: WatchdogSettings = {
|
||
restartMax: 3,
|
||
restartWindowMin: 24 * 60,
|
||
restartDelaysMin: [1, 5, 15],
|
||
stallRestartMin: 60,
|
||
remindMin: 240,
|
||
remindMax: 1,
|
||
workFrom: 9,
|
||
workTo: 19,
|
||
workDays: [1, 2, 3, 4, 5],
|
||
// Stuck questions are on the superadmin's dashboard (PEP-167) — no extra message by default.
|
||
escalateMin: 0,
|
||
idleStopHours: 24,
|
||
reviewReleaseMin: 30,
|
||
checksStuckMin: 30,
|
||
startHangSec: 90,
|
||
buildCacheGb: 40,
|
||
diskFreeAlertPct: 15,
|
||
};
|
||
|
||
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" || k === "workDays") {
|
||
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], workDays: [...WATCHDOG_DEFAULTS.workDays] };
|
||
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, free = false): Promise<string | null> {
|
||
if (cfg.restartMax <= 0 && !free) 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("бюджет");
|
||
// PEP-205: a retry after a sign-in hiccup is not an automatic restart — the count does not apply.
|
||
if (free) return null;
|
||
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; /** PEP-188: a restart cannot help (the launch line itself is wrong) */ noRestart?: string },
|
||
): Promise<boolean> {
|
||
const now = o.now.getTime();
|
||
// PEP-268: the tmux session vanished (an agent that exits leaves a dead pane: remain-on-exit) —
|
||
// someone outside killed it (a tmux server restart, a deploy). Not the story's attempt.
|
||
if (reason === "gone" && !o.noRestart) return planPlatformRetry(db, s, "gone", alert, o);
|
||
const blocker = o.noRestart ?? (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()}`);
|
||
// PEP-150: the story shows the delay line; the superadmin hears only if the restarts run out.
|
||
await sessionDelay(db, s, { reason: "agent", state: "restart", quiet: true, details: alert, now: o.now, log: o.log });
|
||
return true;
|
||
}
|
||
await updateSession(db, s.id, { status: "failed", endedAt: o.now });
|
||
// PEP-150: nothing to the owner — the superadmin gets one message, the story the delay line.
|
||
await sessionDelay(db, s, { reason: "agent", state: "down", exhausted: true, resume: s.id, details: `${alert}\n\n${m("Сам не перезапустится: {reason}.", { reason: blocker })}`, now: o.now, log: o.log });
|
||
return false;
|
||
}
|
||
|
||
/** PEP-268: pauses (minutes) before the retries after a failure of the platform itself (the last one repeats). */
|
||
export const PLATFORM_RETRY_MIN = [1, 5, 15, 30];
|
||
/** PEP-268: the superadmin hears once — on this failure of the platform within the window. */
|
||
export const PLATFORM_ALERT_AT = 3;
|
||
|
||
const platformFailsInWindow = (s: SessionView, cfg: WatchdogSettings, now: number) => (s.watchState?.platformFails ?? []).filter((t) => now - t < cfg.restartWindowMin * 60_000);
|
||
|
||
/** PEP-268: the launch did not happen because of the platform (host unreachable, no tmux server). */
|
||
export function isPlatformError(e: unknown): boolean {
|
||
return e instanceof HostUnreachable || (e instanceof Error && e.message.includes(tmux.TMUX_SERVER_DOWN));
|
||
}
|
||
|
||
/**
|
||
* PEP-268: did this Claude launch never reach its SessionStart hook (the CLI hung while starting —
|
||
* the platform's failure, not the agent's work)? Codex/OpenCode have no such hook — no way to tell.
|
||
*/
|
||
async function hungAtStart(db: Db, s: SessionView): Promise<boolean> {
|
||
if (s.provider !== "claude") return false;
|
||
const [launch] = await db
|
||
.select({ id: events.id })
|
||
.from(events)
|
||
.where(and(eq(events.sessionId, s.id), inArray(events.type, ["started", "resumed"])))
|
||
.orderBy(desc(events.id))
|
||
.limit(1);
|
||
if (!launch) return false;
|
||
const [started] = await db
|
||
.select({ id: events.id })
|
||
.from(events)
|
||
.where(and(eq(events.sessionId, s.id), eq(events.type, "claude_session"), gt(events.id, launch.id)))
|
||
.limit(1);
|
||
return !started;
|
||
}
|
||
|
||
/**
|
||
* PEP-268: a failure of the platform itself (tmux gone, a hang before the first step, host or tmux
|
||
* server down at the restart). Its own count (`platformFails`), a restart that spends none of the
|
||
* story's automatic restarts, pauses 1/5/15/30 min and no «attempts ran out»: the story waits until
|
||
* the platform is fixed and goes on by itself. The superadmin hears once, on the third failure.
|
||
*/
|
||
export async function planPlatformRetry(
|
||
db: Db,
|
||
s: SessionView,
|
||
what: "gone" | "stall" | "launch",
|
||
details: 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, true);
|
||
if (blocker) {
|
||
await updateSession(db, s.id, { status: "failed", endedAt: o.now });
|
||
await sessionDelay(db, s, { reason: "agent", state: "down", exhausted: true, resume: s.id, details: `${details}\n\n${m("Сам не перезапустится: {reason}.", { reason: blocker })}`, now: o.now, log: o.log });
|
||
return false;
|
||
}
|
||
const fails = [...platformFailsInWindow(s, o.cfg, now), now];
|
||
const at = now + PLATFORM_RETRY_MIN[Math.min(fails.length - 1, PLATFORM_RETRY_MIN.length - 1)]! * 60_000;
|
||
await patchWatch(db, s, { platformFails: fails, restartAt: at, restartReason: `platform:${what}`, restartFree: true }, { status: "failed", endedAt: o.now });
|
||
await logSessionEvent(db, s, "platform_retry_planned", { what, failures: fails.length, at: new Date(at).toISOString() });
|
||
o.log(`#${s.id} ${s.taskKey ?? ""}: platform failure (${what}) ${fails.length}, retry at ${new Date(at).toISOString()} — no restart spent`);
|
||
await sessionDelay(db, s, {
|
||
reason: "agent",
|
||
state: "platform",
|
||
quiet: fails.length !== PLATFORM_ALERT_AT,
|
||
retryAt: at,
|
||
resume: s.id,
|
||
details: `${m("{who}: сбой платформы (№{n} подряд) — попытки задачи не тратятся, повторяем сами.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), n: fails.length })}\n\n${details}`,
|
||
now: o.now,
|
||
log: o.log,
|
||
});
|
||
return true;
|
||
}
|
||
|
||
/** PEP-205: pauses (minutes) before the retries after a sign-in failure of the agent CLI. */
|
||
export const LOGIN_RETRY_MIN = [1, 5, 15];
|
||
|
||
/**
|
||
* PEP-205: the agent CLI could not sign in («account/read failed … timed out») and exited. That is a
|
||
* hiccup on the way to the provider, not the agent's failure: retry after 1, 5 and 15 minutes without
|
||
* spending automatic restarts. A fourth failure in a row marks the subscription «проблема со входом»,
|
||
* the superadmin gets one message and the agent moves to another subscription of the pool.
|
||
*/
|
||
export async function onLoginFailure(db: Db, s: SessionView, tail: string, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise<"retry" | "moved" | "down"> {
|
||
const who = s.taskKey ?? m("Агент №{id}", { id: s.id });
|
||
const fails = (s.watchState?.loginFails ?? 0) + 1;
|
||
const atWork = !!s.taskId && !!s.taskStatus && RESTARTABLE_TASK.includes(s.taskStatus);
|
||
const known = s.subscriptionId != null ? await getSubscription(db, s.subscriptionId).catch(() => null) : null;
|
||
// The subscription is already marked (another agent went through the retries): move at once.
|
||
if (fails <= LOGIN_RETRY_MIN.length && atWork && known?.status !== "auth_error") {
|
||
const at = o.now.getTime() + LOGIN_RETRY_MIN[fails - 1]! * 60_000;
|
||
await patchWatch(db, s, { loginFails: fails, restartAt: at, restartReason: "login", restartFree: true }, { status: "failed", endedAt: o.now });
|
||
await logSessionEvent(db, s, "login_retry_planned", { attempt: fails, of: LOGIN_RETRY_MIN.length, at: new Date(at).toISOString() });
|
||
o.log(`#${s.id} ${s.taskKey ?? ""}: sign-in failed, retry ${fails}/${LOGIN_RETRY_MIN.length} at ${new Date(at).toISOString()}`);
|
||
await sessionDelay(db, s, { reason: "agent", state: "login", quiet: true, details: `${m("{who}: агент не смог войти в аккаунт — сбой связи, повторим сами.", { who })}\n\n${asIs(tail)}`, now: o.now, log: o.log });
|
||
return "retry";
|
||
}
|
||
await patchWatch(db, s, { loginFails: undefined, restartAt: undefined, restartReason: undefined, restartFree: undefined }, { status: "failed", endedAt: o.now });
|
||
const sub = known;
|
||
if (sub) {
|
||
await updateSubscription(db, sub.id, { status: "auth_error", lastError: tail.slice(0, 500), checkedAt: o.now });
|
||
// One message per subscription and day, however many agents ran on it.
|
||
await alertAdmins(
|
||
db,
|
||
`delay:login:${sub.id}:${o.now.toISOString().slice(0, 10)}`,
|
||
m("🔑 Подписка «{name}»: проблема со входом — агент {n} раза подряд не смог войти в аккаунт. Агенты переезжают на другую подписку набора; эту проверьте в «Подписках».", { name: asIs(sub.name), n: LOGIN_RETRY_MIN.length + 1 }),
|
||
o.log,
|
||
);
|
||
}
|
||
await logSessionEvent(db, s, "login_failed", { attempts: fails, subscriptionId: sub?.id ?? null });
|
||
if (atWork && sub) {
|
||
const { tryRotate } = await import("./rotation.ts");
|
||
if (await tryRotate(db, s, "login", o.now, o.log).catch(() => false)) {
|
||
if (s.taskId) await clearPlatformDelay(db, { projectId: s.projectId, taskId: s.taskId }, "agent");
|
||
return "moved";
|
||
}
|
||
}
|
||
await sessionDelay(db, s, { reason: "agent", state: "down", exhausted: true, resume: s.id, details: `${m("{who}: агент не может войти в аккаунт, другой подписки в наборе нет.", { who })}\n\n${asIs(tail)}`, now: o.now, log: o.log });
|
||
return "down";
|
||
}
|
||
|
||
/** PEP-265: pauses (minutes) before the restarts after a start hang; one more hang after them — the agent stays stopped. */
|
||
export const HANG_RETRY_MIN = [5, 15];
|
||
|
||
/** PEP-265: what the CLI waits for, in words for the superadmin. */
|
||
export const START_QUESTION_TEXT: Record<StartQuestion, string> = {
|
||
trust: m("доверие к папке"),
|
||
// glossary-ignore: сообщение суперадмину — он настраивает модели агентов
|
||
model: m("выбор модели"),
|
||
login: m("вход в аккаунт"),
|
||
setup: m("первичная настройка"),
|
||
};
|
||
|
||
/**
|
||
* PEP-265: the agent made no action since its start and its CLI waits on a question of its own (trust,
|
||
* model, sign-in, setup). That is the platform's launch failing, not the story: the superadmin hears at
|
||
* once (the delay `hang`, not quiet), the owner sees only the delay line, and the agent is restarted
|
||
* outside the count of automatic restarts; the third hang in a row leaves it stopped.
|
||
*/
|
||
export async function onStartHang(db: Db, s: SessionView, kind: StartQuestion, tail: string, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise<"retry" | "down"> {
|
||
const who = s.taskKey ?? m("Агент №{id}", { id: s.id });
|
||
const hangs = (s.watchState?.hangs ?? 0) + 1;
|
||
const waited = Math.round((o.now.getTime() - (s.watchState?.launchedAt ?? o.now.getTime())) / 1000);
|
||
await logSessionEvent(db, s, "start_hang", { kind, attempt: hangs, waitedSec: waited, tail });
|
||
o.log(`#${s.id} ${s.taskKey ?? ""}: start hang (${kind}), ${hangs}/${HANG_RETRY_MIN.length + 1}`);
|
||
await killRunner(s).catch(() => {});
|
||
const head = m("{who}: агент завис на старте — ждёт ответа на экране ({what}), за {sec} с не сделал ни одного действия.", { who, what: START_QUESTION_TEXT[kind], sec: waited });
|
||
const blocker = hangs > HANG_RETRY_MIN.length ? m("зависает на старте {n} раза подряд", { n: hangs }) : await restartBlocker(db, s, o.cfg, o.now.getTime(), true);
|
||
if (!blocker) {
|
||
const at = o.now.getTime() + HANG_RETRY_MIN[hangs - 1]! * 60_000;
|
||
await patchWatch(db, s, { hangs, hangGen: s.generation, restartAt: at, restartReason: "start_hang", restartFree: true }, { status: "failed", endedAt: o.now });
|
||
await sessionDelay(db, s, { reason: "hang", state: `${kind}:${hangs}`, attempts: hangs, retryAt: at, action: m("агент остановлен, перезапуск в {time}", { time: new Date(at).toISOString().slice(11, 16) }), details: `${head}\n${m("Попытки задачи не тратятся, FORGE перезапустит агента сама.")}\n\n${asIs(tail)}`, now: o.now, log: o.log });
|
||
return "retry";
|
||
}
|
||
await patchWatch(db, s, { hangs, hangGen: s.generation, restartAt: undefined, restartReason: undefined, restartFree: undefined }, { status: "failed", endedAt: o.now });
|
||
await sessionDelay(db, s, { reason: "hang", state: "stopped", exhausted: true, attempts: hangs, resume: s.id, buttons: true, details: `${head}\n${m("Сам не перезапустится: {reason}.", { reason: blocker })}\n\n${asIs(tail)}`, now: o.now, log: o.log });
|
||
return "down";
|
||
}
|
||
|
||
/** PEP-227: what Claude prints when `--resume` names a conversation it no longer has. */
|
||
export const LOST_CONVERSATION_RE = /No conversation found with session ID/i;
|
||
|
||
/**
|
||
* PEP-227: Claude could not resume the saved conversation («No conversation found with session ID»)
|
||
* and exited. Resuming it again fails the same way, so the conversation is forgotten and the agent
|
||
* starts a new one at once (through `restartTick`: same checks, no automatic restart spent).
|
||
*/
|
||
export async function onConversationLost(db: Db, s: SessionView, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise<void> {
|
||
await updateSession(db, s.id, { conversationId: null });
|
||
await logSessionEvent(db, s, "conversation_lost", { conversationId: s.conversationId });
|
||
o.log(`#${s.id} ${s.taskKey ?? ""}: conversation ${s.conversationId} is gone, starting a new one`);
|
||
const blocker = await restartBlocker(db, s, o.cfg, o.now.getTime(), true);
|
||
if (blocker) {
|
||
await updateSession(db, s.id, { status: "failed", endedAt: o.now });
|
||
await sessionDelay(db, s, { reason: "agent", state: "down", exhausted: true, resume: s.id, details: m("{who}: прошлый разговор агента потерян, сам не перезапустится: {reason}.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), reason: blocker }), now: o.now, log: o.log });
|
||
return;
|
||
}
|
||
await patchWatch(db, s, { restartAt: o.now.getTime(), restartReason: "conversation_lost", restartFree: true }, { status: "failed", endedAt: o.now });
|
||
}
|
||
|
||
/** 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;
|
||
// PEP-174: a project on pause keeps its planned restart until «Продолжить».
|
||
if (await isProjectPaused(db, s.projectId)) continue;
|
||
const clear = { restartAt: undefined, restartReason: undefined, restartFree: undefined };
|
||
const free = !!ws.restartFree;
|
||
// 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(), free);
|
||
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 sessionDelay(db, s, { reason: "agent", state: "down", exhausted: true, resume: s.id, details: m("{who}: агент остановился с ошибкой, сам не перезапустился: {reason}.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), reason: blocker }), now: o.now, log: o.log });
|
||
continue;
|
||
}
|
||
const before = restartsInWindow(s, o.cfg, o.now.getTime());
|
||
const restarts = free ? before : [...before, o.now.getTime()];
|
||
const platform = !!ws.restartReason?.startsWith("platform:");
|
||
await patchWatch(db, s, { ...clear, restarts, screen: undefined, stallAlertAt: undefined });
|
||
try {
|
||
await resumeSession(db, s.id, {
|
||
prompt: ws.restartReason === "conversation_lost"
|
||
? "Прошлый разговор потерян (Claude не нашёл его при resume) — это новый разговор. Сверься с peppa.get_task и tasks.md и продолжай с первого невыполненного пункта."
|
||
: ws.restartReason === "start_hang"
|
||
? "Прошлый запуск завис на старте (CLI ждал ответа на экране) — это повтор. Продолжай работу с того места, где остановился."
|
||
: platform
|
||
? "Прошлый запуск оборвался из-за сбоя платформы, не по твоей вине — это повтор. Продолжай работу с того места, где остановился."
|
||
: free
|
||
? "Прошлый запуск не смог войти в аккаунт (сбой связи) — это повтор. Продолжай работу с того места, где остановился."
|
||
: `Раннер ${ws.restartReason === "stall" ? "завис" : "упал"} и перезапущен вачдогом автоматически (попытка ${restarts.length} из ${o.cfg.restartMax}).`,
|
||
});
|
||
if (ws.restartReason === "conversation_lost") await logSessionEvent(db, s, "conversation_restarted", {});
|
||
else if (ws.restartReason === "start_hang") await logSessionEvent(db, s, "start_hang_retried", { attempt: ws.hangs ?? 1 });
|
||
else if (platform) await logSessionEvent(db, s, "platform_retried", { what: ws.restartReason!.slice("platform:".length), failures: platformFailsInWindow(s, o.cfg, o.now.getTime()).length });
|
||
else await logSessionEvent(db, s, free ? "login_retried" : "auto_restarted", { reason: ws.restartReason, attempt: free ? (ws.loginFails ?? 1) : restarts.length, of: free ? LOGIN_RETRY_MIN.length : o.cfg.restartMax });
|
||
o.log(`#${s.id} ${s.taskKey ?? ""}: restarted automatically (${restarts.length}/${o.cfg.restartMax})`);
|
||
if (s.taskId) await clearPlatformDelay(db, { projectId: s.projectId, taskId: s.taskId }, "agent");
|
||
} catch (e) {
|
||
await logSessionEvent(db, s, "restart_failed", { error: (e as Error).message });
|
||
// PEP-268: the host or the tmux server is down — the launch never happened: the attempt is
|
||
// given back and the story waits for the platform on its own schedule.
|
||
if (isPlatformError(e)) {
|
||
await patchWatch(db, s, { restarts: before });
|
||
await planPlatformRetry(db, s, "launch", m("{who}: не удалось запустить агента — {error}", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), error: (e as Error).message }), o);
|
||
continue;
|
||
}
|
||
// PEP-150: a failed restart is an attempt — the next one follows the same schedule; the
|
||
// superadmin is told once the attempts have run out. The error itself goes to Bugsink.
|
||
const fresh = await getSession(db, s.id).catch(() => s);
|
||
const left = fresh.status === "failed" && !(await restartBlocker(db, s, o.cfg, o.now.getTime()));
|
||
if (left) {
|
||
const delays = o.cfg.restartDelaysMin.length ? o.cfg.restartDelaysMin : [0];
|
||
await patchWatch(db, s, { restartAt: o.now.getTime() + delays[Math.min(restarts.length, delays.length - 1)]! * 60_000, restartReason: ws.restartReason });
|
||
}
|
||
await sessionDelay(db, s, {
|
||
reason: "agent",
|
||
state: left ? "restart" : "down",
|
||
quiet: left,
|
||
exhausted: !left,
|
||
resume: s.id,
|
||
details: m("{who}: не удалось перезапустить автоматически — {error}", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), error: (e as Error).message }),
|
||
error: e,
|
||
now: o.now,
|
||
log: o.log,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 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;
|
||
// PEP-268: the agent hung before its first step — the launch is the platform's failure.
|
||
const hung = await hungAtStart(db, s);
|
||
const blocker = await restartBlocker(db, s, o.cfg, o.now.getTime(), hung);
|
||
if (blocker) {
|
||
await patchWatch(db, s, { stallAlertAt: undefined });
|
||
await logSessionEvent(db, s, "restart_skipped", { reason: "stall", why: blocker });
|
||
await sessionDelay(db, s, { reason: "agent", state: "down", exhausted: true, resume: s.id, details: m("{who}: работа зависла, сам не перезапустится: {reason}.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), reason: blocker }), now: o.now, log: o.log });
|
||
return false;
|
||
}
|
||
await killRunner(s).catch(() => {});
|
||
if (hung) {
|
||
await patchWatch(db, s, { stallAlertAt: undefined });
|
||
return planPlatformRetry(db, s, "stall", m("{who}: агент завис на старте — программа агента так и не запустилась.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }) }), o);
|
||
}
|
||
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).
|
||
*/
|
||
/** PEP-173: is it working time in the platform's time zone (PEPPA_TZ, else this machine's)? */
|
||
export function inWorkingTime(now: Date, cfg: Pick<WatchdogSettings, "workFrom" | "workTo" | "workDays">): boolean {
|
||
const parts = new Intl.DateTimeFormat("en-GB", { timeZone: process.env.PEPPA_TZ || undefined, weekday: "short", hour: "numeric", hourCycle: "h23" }).formatToParts(now);
|
||
const hour = Number(parts.find((x) => x.type === "hour")?.value ?? 0);
|
||
const day = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].indexOf(parts.find((x) => x.type === "weekday")?.value ?? "") + 1;
|
||
return cfg.workDays.includes(day) && hour >= cfg.workFrom && hour < cfg.workTo;
|
||
}
|
||
|
||
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;
|
||
const paused = await pausedProjectIds(db);
|
||
for (const { q, projectKey, taskNumber } of rows) {
|
||
// PEP-174: a project on pause sends no reminders (nor escalations).
|
||
if (paused.has(q.projectId)) continue;
|
||
// 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;
|
||
// PEP-173: one reminder (remindMax), not before remindMin, and only in working time — outside
|
||
// it the reminder waits for the morning.
|
||
const remind = !escalate && remindMin > 0 && n < o.cfg.remindMax && age >= (n + 1) * remindMin * 60_000 && inWorkingTime(o.now, o.cfg);
|
||
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 short = q.text.length > 300 ? `${q.text.slice(0, 300)}…` : q.text;
|
||
// PEP-139/140: an agent's own question is free text — the reminder keeps it as written.
|
||
const body = questionIsFreeText(q) ? asIs(short) : short;
|
||
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 })) {
|
||
// PEP-149: an agent that ended its turn without a question is `idle` while its story is in work.
|
||
const turnOver = s.status === "waiting_input" || (s.status === "idle" && ["proposing", "in_progress"].includes(s.taskStatus ?? ""));
|
||
if (!turnOver || !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;
|
||
}
|