PEP-166: a limit banner replayed by a resumed Claude conversation is history, not a new limit of the subscription it moved to

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-16 15:07:53 +05:00
parent b6220327cf
commit 5a36687f42
4 changed files with 49 additions and 4 deletions

View File

@ -401,6 +401,9 @@ export type WatchState = {
screen?: string;
/** Generation whose limit banner was already handled / threshold warning already seen. */
limitGen?: number;
/** PEP-166: limit banners already on screen when this generation started (a resumed conversation shows its history). */
limitBaseGen?: number;
limitBase?: number;
thresholdGen?: number;
/** Times (ms) of automatic restarts — the limit counts those inside the window. */
restarts?: number[];

View File

@ -12,6 +12,23 @@ 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). */
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";
/**

View File

@ -25,7 +25,7 @@ import {
} from "@peppa/core";
import type { Db } from "@peppa/db";
import * as tmux from "./tmux.ts";
import { ADD_SUBSCRIPTION_HINT, recordLimit } from "./limits.ts";
import { ADD_SUBSCRIPTION_HINT, freshLimitLine, limitLines, recordLimit } from "./limits.ts";
import { killRunner, resumeSession } from "./sessions.ts";
import { hostTick } from "./hosts.ts";
import { getSubscription, isUsable, reportPlatformError } from "@peppa/core";
@ -61,7 +61,6 @@ export interface WatchdogOptions {
}
// Claude Code's limit banners ("…usage limit reached… resets 3pm", "You've hit your limit").
const LIMIT_RE = /(usage limit reached|limit reached.{0,40}reset|you've hit your (usage )?limit|out of extra usage)/i;
/** Last non-empty screen lines — what the PM needs to see in an alert. */
function screenTail(screen: string, lines: number): string {
@ -201,10 +200,27 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg:
});
}
// PEP-166: banners already on screen when this generation started are history (a resumed
// conversation after a switch shows the old account's limit) — count them, don't act on them.
// Only a resumed Claude conversation replays history (a fresh start and Codex — which starts
// over on another subscription — begin with a clean screen, and Codex has no limit hook).
const replays = s.provider !== "codex" && s.generation > 1;
const banners = limitLines(screen).length;
if (!replays) {
if (s.watchState?.limitBase) await patchWatch(db, s, { limitBase: 0 });
s = { ...s, watchState: { ...s.watchState, limitBase: 0 } };
} else if (s.watchState?.limitBaseGen !== s.generation) {
await patchWatch(db, s, { limitBaseGen: s.generation, limitBase: banners });
s = { ...s, watchState: { ...s.watchState, limitBaseGen: s.generation, limitBase: banners } };
} else if (banners < (s.watchState?.limitBase ?? 0)) {
await patchWatch(db, s, { limitBase: banners });
s = { ...s, watchState: { ...s.watchState, limitBase: banners } };
}
const fresh = freshLimitLine(screen, s.watchState?.limitBase ?? 0);
// Fallback for limits that don't come through the StopFailure hook.
if (LIMIT_RE.test(screen) && s.status !== "rate_limited" && s.watchState?.limitGen !== s.generation) {
if (fresh && s.status !== "rate_limited" && s.watchState?.limitGen !== s.generation) {
await patchWatch(db, s, { limitGen: s.generation });
const line = screen.split("\n").find((l) => LIMIT_RE.test(l))?.trim() ?? "";
const line = fresh;
log(`${label}: usage limit`);
await logSessionEvent(db, s, "usage_limit", { line });
const msg = await recordLimit(db, s, line, new Date(now));

View File

@ -32,6 +32,15 @@ describe("Время сброса лимита", () => {
});
}
test("PEP-166: баннер лимита из истории возобновлённого разговора — не новый лимит", () => {
const old = "⏺ Usage limit reached · continuing automatically at 6pm · esc to cancel";
const resumed = `> продолжай\n${old}\n⏺ Продолжаю работу над задачей…`;
assert.equal(runner.freshLimitLine(resumed, 1), null, "the old account's banner was there when the generation started");
assert.equal(runner.freshLimitLine(`${resumed}\n⏺ Usage limit reached · resets 9pm`, 1), "⏺ Usage limit reached · resets 9pm", "a new banner after it counts");
assert.equal(runner.freshLimitLine("⏺ Работаю…", 0), null);
assert.equal(runner.freshLimitLine(old, 0), old, "a generation that started clean sees its first banner");
});
test("Время сброса указано", async () => {
const p = await project({ turns: [[{ limit: { resetInSec: 120 } }], [{ say: "Продолжаю после лимита." }]] });
const sid = await p.start();