// 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"; const REL_RE = /reset[s]?\s+in\s+(?:(\d+)\s*h(?:ours?)?)?\s*(?:(\d+)\s*m(?:in(?:utes?)?)?)?/i; // PEP-205: Codex names the day when the reset is not today — «try again at Nov 18th, 2026 9:13 PM». const DATED_RE = /(?: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; const CLOCK_RE = /(?:reset[s]?|try again|continu(?:e|es|ing)(?:\s+automatically)?)(?:\s+at)?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/i; /** «try again at Nov 18th, 2026 9:13 PM» — the full date and time (local), or null. */ function datedTime(text: string): Date | null { const dated = DATED_RE.exec(text); if (!dated) return null; 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; return month >= 0 && h <= 23 ? new Date(Number(dated[3]), month, Number(dated[2]), h, Number(dated[5]), 0, 0) : null; } /** A clock time without a date: «resets 5pm», «try again at 8:47 PM», «continuing automatically at 6pm». */ function clockTime(text: string): { h: number; m: number } | null { const abs = CLOCK_RE.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; return h > 23 || m > 59 ? null : { h, m }; } /** * 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. * For a banner read off a screen ask `passedReset` first: an old banner's time has passed, and here * it would come out as tomorrow's (PEP-300). */ export function parseResetTime(text: string, now: Date): Date | null { const rel = REL_RE.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 dated = datedTime(text); if (dated && dated.getTime() > now.getTime()) return dated; const clock = clockTime(text); if (!clock) return null; const t = new Date(now); t.setHours(clock.h, clock.m, 0, 0); if (t.getTime() <= now.getTime()) t.setDate(t.getDate() + 1); return t; } /** PEP-300: how long after its reset time a limit banner may still be on an agent's screen and count as old. */ export const PASSED_RESET_WINDOW_MS = 4 * 60 * 60_000; /** * PEP-300: the reset time a banner names when that time has already passed — the limit behind the * banner is over, the line only stays on the screen. Claude Code waits for the reset itself («set to * continue automatically at 6:50pm»), goes on, and the watchdog reads the banner when the turn has * ended: at 18:51 «6:50pm» is not tomorrow's reset (25.11.2026: three working subscriptions were * marked «лимит» for a day). Null when the time is still ahead or the text has none. * A clock time without a date counts as passed for PASSED_RESET_WINDOW_MS after it — today or, just * after midnight, yesterday; read later than that it is the next day's reset, as `parseResetTime` reads it. */ export function passedReset(text: string, now: Date): Date | null { const rel = REL_RE.exec(text); if (rel && (rel[1] || rel[2])) return null; const dated = datedTime(text); if (dated) return dated.getTime() <= now.getTime() ? dated : null; const clock = clockTime(text); if (!clock) return null; const prev = new Date(now); prev.setHours(clock.h, clock.m, 0, 0); if (prev.getTime() > now.getTime()) prev.setDate(prev.getDate() - 1); return now.getTime() - prev.getTime() <= PASSED_RESET_WINDOW_MS ? prev : null; } // PEP-300: people read the time in the platform's zone (PEPPA_TZ), not in the server's (UTC in the containers). const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined }); 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 { 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; }