Warn the model mid-turn as the 5-hour or 7-day limit nears

Steer the model to wind down before a usage block runs out.
overage (default false): set it on accounts with extra usage so the exhausted-block message warns that further requests spend overage credits.
register.ts reads the rate-limit windows on each session.measure and appends guidance mid-turn when a window crosses a band. Each append is logged through mod-events as an inject event, and a landed append prints a one-line summary to the transcript. Bands re-arm after /clear and /resume.bands.ts holds the thresholds and their guidance. Each band fires once per block and re-arms when the window resets.types/index.d.ts declares the announced-band state.bun scripts/mod-test.ts session-limit
mod/register.ts 65 lines1import type { On, PluginOptions } from "claude-code";
2import { evaluate, summarize } from "./bands";
3
4const MOD = "session-limit";
5const ANNOUNCED = { plugin: "session-limit", key: "announced" } as const;
6
7export function register(on: On, options: PluginOptions): void {
8 const overage = options.overage === true;
9
10 on("session.start", ($, e, next) => {
11 void $.modEvents.emit({ mod: MOD, event: "session.start" });
12 return next(e);
13 });
14
15 // /clear and /resume start a new conversation without a session.start.
16 on("session.end", async ($, e, next) => {
17 if (e.reason === "clear" || e.reason === "resume") await $.state.set(ANNOUNCED, {});
18 return next(e);
19 });
20
21 on("session.measure", async ($, e, next) => {
22 if (!e.changed.includes("rateLimits")) return next(e);
23
24 const { value: prev = {} } = await $.state.get(ANNOUNCED);
25 const { announced, crossings } = evaluate(e.rateLimits, prev, await $.clock.now(), overage);
26
27 if (crossings.length === 0) {
28 await $.state.set(ANNOUNCED, announced);
29 } else {
30 const text = crossings.map((crossing) => crossing.message).join("\n\n");
31 const outcome = await $.session
32 .append({ message: { type: "user", content: [{ type: "text", text }] } })
33 .then(
34 (result) => ({
35 ok: result.deny === undefined,
36 uuid: result.uuid ?? null,
37 error: result.deny ?? null,
38 }),
39 (error: unknown) => ({ ok: false, uuid: null, error: String(error) }),
40 );
41 // A refused append leaves the bands unannounced so the next measurement retries.
42 if (outcome.ok) {
43 await $.state.set(ANNOUNCED, announced);
44 $.ui.log(summarize(crossings));
45 }
46 void $.modEvents.emit({
47 mod: MOD,
48 event: "inject",
49 ok: outcome.ok,
50 detail: {
51 crossings: crossings.map(({ kind, threshold, percentUsed, resetsAt }) => ({
52 kind,
53 threshold,
54 percentUsed,
55 resetsAt: resetsAt ?? null,
56 })),
57 uuid: outcome.uuid,
58 error: outcome.error,
59 },
60 });
61 }
62 return next(e);
63 });
64}
65mod/bands.ts 120 lines1import type { SessionRateLimit } from "claude-code";
2import type { SessionLimitAnnounced } from "../types";
3
4export interface Band {
5 threshold: number;
6 message: (resetsAt: string | undefined, nowMs: number, overage: boolean) => string;
7}
8
9export type Announced = SessionLimitAnnounced;
10
11export interface Crossing {
12 kind: string;
13 threshold: number;
14 percentUsed: number;
15 resetsAt: string | undefined;
16 message: string;
17}
18
19// Auto-scheduling a wake-up caps out around an hour. Past this horizon the model
20// defers to the user.
21const WAKEUP_HORIZON_MS = 55 * 60 * 1000;
22
23export const BANDS: Record<string, Band[]> = {
24 five_hour: [
25 {
26 threshold: 90,
27 message: (resetsAt) =>
28 `You are at 90% of the current 5-hour usage block (resets ${formatResetTime(resetsAt)}). Favor efficient work and avoid starting large non-essential tasks.`,
29 },
30 {
31 threshold: 95,
32 message: (resetsAt) =>
33 `You are at 95% of the current 5-hour usage block (resets ${formatResetTime(resetsAt)}). Prefer finishing in-flight work over starting anything new, and batch tool calls.`,
34 },
35 {
36 threshold: 100,
37 message: (resetsAt, nowMs, overage) => {
38 const reset = formatResetTime(resetsAt);
39 const msUntilReset = resetsAt == null ? Number.NaN : Date.parse(resetsAt) - nowMs;
40 const withinHorizon = msUntilReset > 0 && msUntilReset <= WAKEUP_HORIZON_MS;
41 const resume = withinHorizon
42 ? `then schedule a wake-up for just after ${reset} (no need to ask) so work resumes on a fresh block, and stop`
43 : `then tell the user to return at ${reset} to resume on a fresh block, and stop`;
44 const spend = overage ? " Every further request now spends overage credits." : "";
45 return `The 5-hour usage block is exhausted (resets ${reset}).${spend} Finish only in-flight work, ${resume}. Start no new work.`;
46 },
47 },
48 ],
49 seven_day: [
50 {
51 threshold: 95,
52 message: (resetsAt) =>
53 `You are at 95% of the 7-day usage limit. A 5-hour wait will not restore this. Minimize spend until the weekly reset (${formatResetTime(resetsAt)}).`,
54 },
55 ],
56};
57
58export function formatResetTime(resetsAt: string | undefined): string {
59 if (resetsAt == null) return "at an unknown time";
60 return new Date(resetsAt).toLocaleString([], {
61 weekday: "short",
62 hour: "numeric",
63 minute: "2-digit",
64 });
65}
66
67const LABELS: Record<string, string> = { five_hour: "5-hour", seven_day: "7-day" };
68
69export function summarize(crossings: readonly Crossing[]): string {
70 const parts = crossings.map(({ kind, percentUsed, resetsAt }) => {
71 const reset = resetsAt == null ? "" : ` (resets ${formatResetTime(resetsAt)})`;
72 return `${LABELS[kind] ?? kind} limit at ${percentUsed}%${reset}`;
73 });
74 return `Usage notice sent to Claude: ${parts.join(", ")}`;
75}
76
77export function crossedBand(percentUsed: number, bands: readonly Band[]): Band | undefined {
78 return bands.findLast((band) => percentUsed >= band.threshold);
79}
80
81// A new resetsAt means the block rolled over, so its bands re-arm.
82function announcedBand(prev: Announced, kind: string, resetsAt: string): number {
83 const entry = prev[kind];
84 return entry?.resetsAt === resetsAt ? entry.band : 0;
85}
86
87export function evaluate(
88 limits: readonly SessionRateLimit[],
89 prev: Announced,
90 nowMs: number,
91 overage = false,
92): { announced: Announced; crossings: Crossing[] } {
93 const announced: Announced = { ...prev };
94 const crossings: Crossing[] = [];
95
96 for (const limit of limits) {
97 const bands = BANDS[limit.kind];
98 if (!bands) continue;
99
100 const resetsAt = limit.resetsAt ?? "";
101 const prior = announcedBand(prev, limit.kind, resetsAt);
102 announced[limit.kind] = { band: prior, resetsAt };
103
104 // Announce only the highest band crossed, and only once per block.
105 const crossed = crossedBand(limit.percentUsed, bands);
106 if (!crossed || crossed.threshold <= prior) continue;
107
108 announced[limit.kind] = { band: crossed.threshold, resetsAt };
109 crossings.push({
110 kind: limit.kind,
111 threshold: crossed.threshold,
112 percentUsed: limit.percentUsed,
113 resetsAt: limit.resetsAt,
114 message: crossed.message(limit.resetsAt, nowMs, overage),
115 });
116 }
117
118 return { announced, crossings };
119}
120types/index.d.ts 8 lines1export type SessionLimitAnnounced = Record<string, { band: number; resetsAt: string }>;
2
3declare module "claude-code" {
4 interface PluginState {
5 "session-limit": { announced: SessionLimitAnnounced };
6 }
7}
8