peppa/packages/runner/src/limits.ts

118 lines
6.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 { m } from "@peppa/shared/i18n";
import { markSubscriptionLimited, updateSession, type SessionView } from "@peppa/core";
import type { Db } from "@peppa/db";
import { planRotation } from "./rotation.ts";
/** PEP-107: what to do so agents don't wait for a reset next time. */
export const ADD_SUBSCRIPTION_HINT = m("Чтобы агенты не ждали — добавьте ещё одну подписку Claude или ChatGPT: «Настройки проекта → Подписки».");
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;
/** A usage-limit banner of the agent CLI on its screen (the watchdog's fallback when no hook reports it). */
// PEP-205: Codex prints a typographic apostrophe — «You’ve hit your usage limit … try again at 8:47 PM».
export const LIMIT_SCREEN_RE = /(usage limit reached|limit reached.{0,40}reset|you[’'`]ve hit your (usage )?limit|out of extra usage)/i;
/** Limit banner lines on a captured screen, top to bottom. */
export const limitLines = (screen: string): string[] => screen.split("\n").filter((l) => LIMIT_SCREEN_RE.test(l)).map((l) => l.trim());
/**
* PEP-166: is there a limit banner that was not on the screen when this generation started?
* After a switch to another subscription the resumed conversation shows its history, the old
* account's «Usage limit reached» included — that must not mark the new subscription limited.
* `base` = banners counted at the generation's first look (lowered when they scroll away).
*/
export function freshLimitLine(screen: string, base: number): string | null {
const lines = limitLines(screen);
return lines.length > base ? lines.at(-1)! : null;
}
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", and Claude Code's newer banner
* "Usage limit reached · continuing automatically at 6pm" (PEP-166). 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);
// PEP-205: Codex names the day when the reset is not today — «try again at Nov 18th, 2026 9:13 PM».
const dated = /(?:reset[s]?|try again)(?:\s+(?:at|on))?\s+([A-Z][a-z]{2})[a-z]*\.?\s+(\d{1,2})(?:st|nd|rd|th)?,?\s+(\d{4})(?:,|\s+at)?\s+(\d{1,2}):(\d{2})\s*(am|pm)?/i.exec(text);
if (dated) {
const month = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"].indexOf(dated[1]!.toLowerCase());
let h = Number(dated[4]);
const pm = dated[6]?.toLowerCase();
if (pm === "pm" && h < 12) h += 12;
if (pm === "am" && h === 12) h = 0;
if (month >= 0 && h <= 23) {
const t = new Date(Number(dated[3]), month, Number(dated[2]), h, Number(dated[5]), 0, 0);
if (t.getTime() > now.getTime()) return t;
}
}
const abs = /(?:reset[s]?|try again|continu(?:e|es|ing)(?:\s+automatically)?)(?:\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) and mark its subscription
* «лимит до …» (PEP-39). Returns the PM's message — or null when another subscription of
* the pool is free: the watchdog switches to it (`rotate_reason`) and reports that instead.
*/
export async function recordLimit(db: Db, s: SessionView, text: string, now = new Date()): Promise<string | null> {
const who = s.taskKey ?? m("Агент №{id}", { id: 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;
if (s.subscriptionId != null) await markSubscriptionLimited(db, s.subscriptionId, reset ?? resumeAt!, text);
const rotate = auto && !!(await planRotation(db, s, "limit", now));
await updateSession(db, s.id, {
status: "rate_limited",
resumeAt: auto ? resumeAt : null,
limitProbeMin: auto ? probe : null,
limitResumes: resumesToday,
limitResumesDay: day,
rotateReason: rotate ? "limit" : null,
});
if (rotate) return null;
if (!auto) {
return capped
? m("{who}: снова лимит, автопродолжений сегодня уже {n} — нужны вы. Нажмите «Продолжить», когда лимит сбросится.", { who, n: MAX_LIMIT_RESUMES_PER_DAY })
: `${m("{who}: агент упёрся в лимит.", { who })}${text ? `\n${text.slice(0, 400)}` : ""}`;
}
const hint = s.subscriptionId != null ? `\n${ADD_SUBSCRIPTION_HINT}` : "";
return reset
? m("{who}: остановлен по лимиту, продолжит в {time} сам.", { who, time: hhmm(resumeAt!) }) + hint
: m("{who}: остановлен по лимиту, время сброса неизвестно — попробую продолжить в {time}.", { who, time: hhmm(resumeAt!) }) + hint;
}