peppa/packages/runner/src/limits.ts
Асель 685810eb80 PEP-56: runner continues on its own after the usage limit resets
- parseResetTime: 'resets 5pm', 'resets at 3:10 AM', 'resets in 2h 15m',
  'try again at 23:30'; nearest future time, local clock
- recordLimit (hook StopFailure and the watchdog's banner path): status
  rate_limited, resume_at = reset + 60 s, or probes 30 → 60 → 120 min when
  unknown or the limit came back right after a resume; cap 6/day;
  PEPPA_LIMIT_AUTORESUME=off; PM is told 'continues at HH:MM'
- watchdog: at resume_at nudges the live agent or relaunches it with
  resume (vanished/dead rate-limited runners wait instead of failing); the
  limit message is closed as resolved; tick(db, { now }) for tests
- mocks: limit with resetInSec / unknown reset (claude and codex)
- tests: one per spec scenario + Codex (82 e2e total, green)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 03:50:58 +05:00

74 lines
3.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Usage limits (PEP-56): when does the agent's limit reset, and what to tell the PM.
import { updateSession, type SessionView } from "@peppa/core";
import type { Db } from "@peppa/db";
export const LIMIT_RESUME_GRACE_MS = 60_000;
export const MAX_LIMIT_RESUMES_PER_DAY = 6;
const PROBE_STEPS_MIN = [30, 60, 120];
const REPEAT_WINDOW_MS = 5 * 60_000;
export const limitAutoResumeEnabled = () => process.env.PEPPA_LIMIT_AUTORESUME !== "off";
/**
* Reset time from a limit message: "resets 5pm", "resets at 3:10 AM", "reset at 15:00",
* "try again at 5:00 PM", "resets in 2h 15m". A clock time without a date is the nearest
* future one (local time of this machine). Null when there is no time in the text.
*/
export function parseResetTime(text: string, now: Date): Date | null {
const rel = /reset[s]?\s+in\s+(?:(\d+)\s*h(?:ours?)?)?\s*(?:(\d+)\s*m(?:in(?:utes?)?)?)?/i.exec(text);
if (rel && (rel[1] || rel[2])) return new Date(now.getTime() + (Number(rel[1] ?? 0) * 60 + Number(rel[2] ?? 0)) * 60_000);
const abs = /(?:reset[s]?|try again)(?:\s+at)?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/i.exec(text);
if (!abs) return null;
let h = Number(abs[1]);
const m = Number(abs[2] ?? 0);
const ampm = abs[3]?.toLowerCase();
if (!ampm && !abs[2]) return null; // a bare number isn't a time
if (ampm === "pm" && h < 12) h += 12;
if (ampm === "am" && h === 12) h = 0;
if (h > 23 || m > 59) return null;
const t = new Date(now);
t.setHours(h, m, 0, 0);
if (t.getTime() <= now.getTime()) t.setDate(t.getDate() + 1);
return t;
}
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
const today = (now: Date) => now.toLocaleDateString("sv-SE"); // YYYY-MM-DD, local
/**
* The runner hit a usage limit: store when to continue (reset time, or a probe if
* unknown / the limit came back right after an auto-resume). Returns the PM's message.
*/
export async function recordLimit(db: Db, s: SessionView, text: string, now = new Date()): Promise<string> {
const who = s.taskKey ?? `Раннер ${s.id}`;
const day = today(now);
const resumesToday = s.limitResumesDay === day ? s.limitResumes : 0;
const repeated = !!s.limitResumedAt && now.getTime() - s.limitResumedAt.getTime() < REPEAT_WINDOW_MS;
const reset = repeated ? null : parseResetTime(text, now);
let resumeAt: Date | null = null;
let probe: number | null = null;
if (reset) resumeAt = new Date(reset.getTime() + LIMIT_RESUME_GRACE_MS);
else {
const prev = s.limitProbeMin;
probe = repeated && prev ? PROBE_STEPS_MIN.find((p) => p > prev) ?? PROBE_STEPS_MIN.at(-1)! : PROBE_STEPS_MIN[0]!;
resumeAt = new Date(now.getTime() + probe * 60_000);
}
const capped = resumesToday >= MAX_LIMIT_RESUMES_PER_DAY;
const auto = limitAutoResumeEnabled() && !capped;
await updateSession(db, s.id, {
status: "rate_limited",
resumeAt: auto ? resumeAt : null,
limitProbeMin: auto ? probe : null,
limitResumes: resumesToday,
limitResumesDay: day,
});
if (!auto) {
return capped
? `${who}: снова лимит, автопродолжений сегодня уже ${MAX_LIMIT_RESUMES_PER_DAY} — нужен ты. Нажми «Перезапустить», когда лимит сбросится.`
: `${who} упёрлась в лимит.${text ? `\n${text.slice(0, 400)}` : ""}`;
}
return reset
? `${who}: остановлен по лимиту, продолжит в ${hhmm(resumeAt!)} сам.`
: `${who}: остановлен по лимиту, время сброса неизвестно — попробую продолжить в ${hhmm(resumeAt!)}.`;
}