peppa/packages/runner/src/limits.ts
Асель c7283063c9 PEP-39: rotate a limited session to a free subscription of the pool at the turn boundary
Limit marks the subscription «лимит до …»; the watchdog relaunches the session on another
usable subscription of the same provider (Claude/OpenCode resume the conversation, Codex
starts afresh), threshold banner switches after the turn, max 3 switches/hour, simple
fairness between projects, subscription_switched events + Telegram message, web shows
subscription and switch history. Migration 0004 (sessions.rotate_reason).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 05:31:22 +05:00

81 lines
4.1 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 { markSubscriptionLimited, updateSession, type SessionView } from "@peppa/core";
import type { Db } from "@peppa/db";
import { planRotation } from "./rotation.ts";
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) 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 ?? `Раннер ${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
? `${who}: снова лимит, автопродолжений сегодня уже ${MAX_LIMIT_RESUMES_PER_DAY} — нужен ты. Нажми «Перезапустить», когда лимит сбросится.`
: `${who} упёрлась в лимит.${text ? `\n${text.slice(0, 400)}` : ""}`;
}
return reset
? `${who}: остановлен по лимиту, продолжит в ${hhmm(resumeAt!)} сам.`
: `${who}: остановлен по лимиту, время сброса неизвестно — попробую продолжить в ${hhmm(resumeAt!)}.`;
}