refactor: replace the Claude→Codex failover with a usage-limit notice

When Claude hit a limit the run was handed to a Codex service
(codex-main/codex-review) through service_handoffs and a global owner
failover. That service does not exist in this deployment, so handoffs
stayed pending forever (2 rows since May) and the user got no answer.

Removed:
- handoff creation (message-agent-executor-handoff, paired-turn-fallback)
  and the delegated paired-execution path
- the pending-handoff poll/claim worker (message-runtime-handoffs) and the
  service_handoffs CRUD module (db/service-handoffs, db exports)
- global owner failover in service-routing, its recovery timer in index,
  the dashboard failover line, the codex-review failover prompt pack and
  prompts/codex-review-failover-platform.md
- failoverOwner in RoomRoleContext and the `failover=` ROOM_ROLE field
- OWNER_/REVIEWER_/ARBITER_FALLBACK_ENABLED and FAILOVER_MIN_DURATION_MS
- tests for the removed behaviour

Now, when a Claude run fails with a usage/rate limit (trigger reason
429 or usage-exhausted) the executor closes the open paired task as
completed/claude_usage_limit and sends the room one final notice:
"Claude 사용 한도에 도달했습니다. 21:40에 재개할 수 있습니다." The reset time
comes from the error text (CLI banner "resets 9:40pm (Asia/Seoul)", dated
banners, "try again at ...", ISO timestamps), else from the cached usage
API window at 100%, else "잠시 후 다시 시도해 주세요". Nothing retries
silently; the next user message starts a new task. Other Claude failures
(session failure, org access denied) now end as ordinary run errors.

The service_handoffs table, its columns on paired_turn_attempts and the
migrations stay untouched for the later migration squash; the runtime no
longer reads or writes them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Codex
2026-10-01 20:14:25 +09:00
parent a9eab5cb94
commit 8c68577a24
62 changed files with 719 additions and 3963 deletions

223
src/claude-usage-limit.ts Normal file
View File

@@ -0,0 +1,223 @@
/**
* 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 is
* told when Claude becomes available again instead of the work being handed
* off or retried silently.
*/
import type { AgentTriggerReason } from './agent-error-detection.js';
import { getCachedClaudeUsageLimitResetAt } from './claude-usage.js';
import { TIMEZONE } from './config.js';
const LIMIT_PREFIX = 'Claude 사용 한도에 도달했습니다.';
const RETRY_LATER = '잠시 후 다시 시도해 주세요.';
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;
}
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}`;
}
export function formatClaudeUsageLimitMessage(
resetAt: Date | null,
nowMs: number = Date.now(),
): string {
if (!resetAt || resetAt.getTime() <= nowMs) {
return `${LIMIT_PREFIX} ${RETRY_LATER}`;
}
return `${LIMIT_PREFIX} ${formatResetTime(resetAt, nowMs)}에 재개할 수 있습니다.`;
}
/**
* Notice for the room: the reset time comes from the error text, else from
* the cached usage API data, else the user is asked to retry later.
*/
export function buildClaudeUsageLimitMessage(
errorText: string | null | undefined,
nowMs: number = Date.now(),
): string {
const resetAt =
parseClaudeLimitResetTime(errorText, nowMs) ??
getCachedClaudeUsageLimitResetAt(nowMs);
return formatClaudeUsageLimitMessage(resetAt, nowMs);
}