Bring back the dawn gap that keeps Claude's 5h windows on the primer
slots (08-13, 13-18, 18-23, 23-04): it was dropped by the 2026-06-08
upstream merge (1dd948a).
- usage-alignment-hold.ts: hold during 04:00-08:00 KST, or until the ISO
time in router_state `usage_alignment_hold_until` (ignored once past,
so only the daily gap remains). A one-off end inside the gap runs on to
08:00.
- Claude turns during a hold pause through the existing usage-pause path
(messages kept, room resumed at the hold end) with an alignment notice.
The stored pause is marked alignmentOnly so it does not act as an
account-wide usage limit.
- Due Claude scheduled tasks stay due until the hold ends (Codex and
GitHub CI watchers are not held).
- Urgent bypass like the old gate: a human @-mention lets that room run
until the hold ends.
- Tests stub the wall-clock hold in test/vitest-env.ts so the suite does
not pause when run between 04 and 08 KST.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
247 lines
7.5 KiB
TypeScript
247 lines
7.5 KiB
TypeScript
/**
|
|
* Reset time and user-facing notice for a Claude run that hit the account
|
|
* usage limit.
|
|
*
|
|
* There is a single Claude account and no fallback provider, so the room's
|
|
* work is paused until the limit resets and then resumed (see
|
|
* claude-usage-pause.ts).
|
|
*/
|
|
|
|
import type { AgentTriggerReason } from './agent-error-detection.js';
|
|
import { getCachedClaudeUsageLimitResetAt } from './claude-usage.js';
|
|
import { TIMEZONE } from './config.js';
|
|
|
|
const PAUSE_PREFIX =
|
|
'Claude 사용 한도에 도달해서 이 방의 작업을 일시정지했습니다.';
|
|
|
|
const MONTHS: Record<string, number> = {
|
|
jan: 1,
|
|
feb: 2,
|
|
mar: 3,
|
|
apr: 4,
|
|
may: 5,
|
|
jun: 6,
|
|
jul: 7,
|
|
aug: 8,
|
|
sep: 9,
|
|
oct: 10,
|
|
nov: 11,
|
|
dec: 12,
|
|
};
|
|
|
|
/** Trigger reasons that mean "the Claude account is out of usage". */
|
|
export function isClaudeUsageLimitReason(reason: AgentTriggerReason): boolean {
|
|
return reason === '429' || reason === 'usage-exhausted';
|
|
}
|
|
|
|
function isValidTimeZone(timeZone: string): boolean {
|
|
try {
|
|
new Intl.DateTimeFormat('en-US', { timeZone });
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function zonedParts(
|
|
instantMs: number,
|
|
timeZone: string,
|
|
): { year: number; month: number; day: number; hour: number; minute: number } {
|
|
const parts = new Intl.DateTimeFormat('en-US', {
|
|
timeZone,
|
|
hourCycle: 'h23',
|
|
year: 'numeric',
|
|
month: 'numeric',
|
|
day: 'numeric',
|
|
hour: 'numeric',
|
|
minute: 'numeric',
|
|
}).formatToParts(new Date(instantMs));
|
|
const get = (type: string) =>
|
|
Number(parts.find((part) => part.type === type)?.value ?? 0);
|
|
return {
|
|
year: get('year'),
|
|
month: get('month'),
|
|
day: get('day'),
|
|
hour: get('hour'),
|
|
minute: get('minute'),
|
|
};
|
|
}
|
|
|
|
/** UTC instant of a wall-clock time in `timeZone`. */
|
|
function zonedTimeToUtc(
|
|
wall: {
|
|
year: number;
|
|
month: number;
|
|
day: number;
|
|
hour: number;
|
|
minute: number;
|
|
},
|
|
timeZone: string,
|
|
): number {
|
|
const asUtc = Date.UTC(
|
|
wall.year,
|
|
wall.month - 1,
|
|
wall.day,
|
|
wall.hour,
|
|
wall.minute,
|
|
);
|
|
const shown = zonedParts(asUtc, timeZone);
|
|
const offset =
|
|
Date.UTC(shown.year, shown.month - 1, shown.day, shown.hour, shown.minute) -
|
|
asUtc;
|
|
return asUtc - offset;
|
|
}
|
|
|
|
function addDays(
|
|
wall: { year: number; month: number; day: number },
|
|
days: number,
|
|
): { year: number; month: number; day: number } {
|
|
const date = new Date(Date.UTC(wall.year, wall.month - 1, wall.day + days));
|
|
return {
|
|
year: date.getUTCFullYear(),
|
|
month: date.getUTCMonth() + 1,
|
|
day: date.getUTCDate(),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Claude CLI banner: "You've hit your limit · resets 9:40pm (Asia/Seoul)",
|
|
* optionally with a date ("resets Oct 2, 4am (Asia/Seoul)"). The time is in
|
|
* the named zone (the service timezone when none is given); without a date it
|
|
* is the next occurrence of that clock time.
|
|
*/
|
|
function parseBannerResetTime(text: string, nowMs: number): Date | null {
|
|
const match = text.match(
|
|
/resets?\s+(?:at\s+)?(?:([a-z]{3})[a-z]*\.?\s+(\d{1,2})(?:st|nd|rd|th)?,?\s+(?:at\s+)?)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)\b(?:\s*\(([^)]+)\))?/i,
|
|
);
|
|
if (!match) return null;
|
|
const [, monthName, dayText, hourText, minuteText, meridiem, zoneText] =
|
|
match;
|
|
const timeZone =
|
|
zoneText && isValidTimeZone(zoneText.trim()) ? zoneText.trim() : TIMEZONE;
|
|
|
|
let hour = Number(hourText) % 12;
|
|
if (meridiem.toLowerCase() === 'pm') hour += 12;
|
|
const minute = minuteText ? Number(minuteText) : 0;
|
|
if (hour > 23 || minute > 59) return null;
|
|
|
|
const today = zonedParts(nowMs, timeZone);
|
|
if (monthName && dayText) {
|
|
const month = MONTHS[monthName.toLowerCase()];
|
|
if (!month) return null;
|
|
let resetMs = zonedTimeToUtc(
|
|
{ year: today.year, month, day: Number(dayText), hour, minute },
|
|
timeZone,
|
|
);
|
|
if (resetMs <= nowMs) {
|
|
resetMs = zonedTimeToUtc(
|
|
{ year: today.year + 1, month, day: Number(dayText), hour, minute },
|
|
timeZone,
|
|
);
|
|
}
|
|
return new Date(resetMs);
|
|
}
|
|
|
|
let resetMs = zonedTimeToUtc({ ...today, hour, minute }, timeZone);
|
|
if (resetMs <= nowMs) {
|
|
resetMs = zonedTimeToUtc({ ...addDays(today, 1), hour, minute }, timeZone);
|
|
}
|
|
return new Date(resetMs);
|
|
}
|
|
|
|
/** "try again at Mar 26th, 2026 9:00 AM" / "resets at Mar 26, 2026 9:00 AM". */
|
|
function parseFullDateResetTime(text: string): Date | null {
|
|
const match = text.match(
|
|
/(?:try again at|resets?\s+(?:at\s+)?)\s*(\w+ \d{1,2}(?:st|nd|rd|th)?,?\s+\d{4}\s+\d{1,2}:\d{2}\s*(?:AM|PM)?)/i,
|
|
);
|
|
if (!match) return null;
|
|
const ts = new Date(
|
|
match[1].replace(/(\d+)(?:st|nd|rd|th)/i, '$1'),
|
|
).getTime();
|
|
return Number.isNaN(ts) ? null : new Date(ts);
|
|
}
|
|
|
|
/** An ISO-8601 timestamp in a message that talks about a reset. */
|
|
function parseIsoResetTime(text: string): Date | null {
|
|
if (!/reset/i.test(text)) return null;
|
|
const match = text.match(
|
|
/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})/,
|
|
);
|
|
if (!match) return null;
|
|
const ts = Date.parse(match[0]);
|
|
return Number.isFinite(ts) ? new Date(ts) : null;
|
|
}
|
|
|
|
/** Reset time named in a Claude limit error, or null when none is found. */
|
|
export function parseClaudeLimitResetTime(
|
|
text: string | null | undefined,
|
|
nowMs: number = Date.now(),
|
|
): Date | null {
|
|
if (!text) return null;
|
|
const candidates = [
|
|
parseFullDateResetTime(text),
|
|
parseIsoResetTime(text),
|
|
parseBannerResetTime(text, nowMs),
|
|
];
|
|
return candidates.find((date) => date && date.getTime() > nowMs) ?? null;
|
|
}
|
|
|
|
export function formatResetTime(resetAt: Date, nowMs: number): string {
|
|
const reset = zonedParts(resetAt.getTime(), TIMEZONE);
|
|
const today = zonedParts(nowMs, TIMEZONE);
|
|
const time = `${String(reset.hour).padStart(2, '0')}:${String(
|
|
reset.minute,
|
|
).padStart(2, '0')}`;
|
|
const sameDay =
|
|
reset.year === today.year &&
|
|
reset.month === today.month &&
|
|
reset.day === today.day;
|
|
return sameDay ? time : `${reset.month}월 ${reset.day}일 ${time}`;
|
|
}
|
|
|
|
/** A banner time that passed less than this long ago means "resetting now", not tomorrow. */
|
|
const JUST_PASSED_RESET_GRACE_MS = 15 * 60_000;
|
|
/** Retry delay when the limit error names no usable reset time. */
|
|
export const CLAUDE_USAGE_RETRY_FALLBACK_MS = 10 * 60_000;
|
|
|
|
export interface ClaudeUsageResume {
|
|
resumeAt: Date;
|
|
/** False when no reset time was found and resumeAt is only a retry time. */
|
|
resetKnown: boolean;
|
|
}
|
|
|
|
/**
|
|
* When paused Claude work may resume: the reset time in the error text, else
|
|
* the cached usage API reset, else a short retry delay.
|
|
*
|
|
* A banner such as "resets 9:40pm" read at 21:41 is treated as "now" instead
|
|
* of tomorrow 21:40, so a limit that outlives its reset by a minute is not
|
|
* paused for a whole day.
|
|
*/
|
|
export function resolveClaudeUsageResume(
|
|
errorText: string | null | undefined,
|
|
nowMs: number = Date.now(),
|
|
): ClaudeUsageResume {
|
|
const resetAt =
|
|
parseClaudeLimitResetTime(errorText, nowMs - JUST_PASSED_RESET_GRACE_MS) ??
|
|
getCachedClaudeUsageLimitResetAt(nowMs);
|
|
if (resetAt && resetAt.getTime() > nowMs) {
|
|
return { resumeAt: resetAt, resetKnown: true };
|
|
}
|
|
return {
|
|
resumeAt: new Date(nowMs + CLAUDE_USAGE_RETRY_FALLBACK_MS),
|
|
resetKnown: false,
|
|
};
|
|
}
|
|
|
|
export function formatClaudeUsagePauseMessage(
|
|
resume: ClaudeUsageResume,
|
|
nowMs: number = Date.now(),
|
|
): string {
|
|
const at = formatResetTime(resume.resumeAt, nowMs);
|
|
const when = resume.resetKnown
|
|
? `${at}에 사용량이 초기화되면 자동으로 이어서 진행합니다.`
|
|
: `초기화 시각을 알 수 없어서 ${at}에 다시 시도합니다.`;
|
|
return `${PAUSE_PREFIX} ${when} 그 전에 멈추려면 "중단"이라고 보내 주세요.`;
|
|
}
|