/** * Rooms whose Claude work is paused because the Claude account hit its usage * limit. * * There is one Claude account, so the limit is global: while it lasts, every * Claude run would fail the same way. The first run that hits it (or that * would start while it lasts) pauses its room: the paired task is left as it * was, the human messages stay unconsumed, and the room is recorded here. * Paused rooms run nothing until the reset time; the scheduler tick then * clears the pause and re-queues them, so the interrupted turn runs again. * * Stored in router_state so a restart keeps the pause and still resumes. */ import { getRouterState, setRouterState } from './db.js'; import { logger } from './logger.js'; export const CLAUDE_USAGE_PAUSE_KEY = 'claude_usage_pause'; /** Wait this long past the reset time before resuming, to not race it. */ export const CLAUDE_USAGE_RESUME_MARGIN_MS = 60_000; export const CLAUDE_USAGE_RESUME_NOTICE = 'Claude 사용량이 초기화되어서 일시정지했던 작업을 이어서 진행합니다.'; interface ClaudeUsagePauseState { /** ISO time the limit resets (or the next retry when unknown). */ until: string; resetKnown: boolean; /** chatJid -> ISO time the room was paused. */ rooms: Record; /** * Set while every room was paused only by the usage-alignment hold * (usage-alignment-hold.ts), not by a real limit. Such a pause does not * block other rooms; the hold itself is re-checked on every run. */ alignmentOnly?: boolean; } export interface ActiveClaudeUsagePause { until: Date; resetKnown: boolean; } function readState(): ClaudeUsagePauseState | null { const raw = getRouterState(CLAUDE_USAGE_PAUSE_KEY); if (!raw) return null; try { const parsed = JSON.parse(raw) as ClaudeUsagePauseState | null; if (!parsed || !Number.isFinite(Date.parse(parsed.until))) return null; return { ...parsed, rooms: parsed.rooms ?? {} }; } catch { logger.warn({ raw }, 'Ignoring unreadable Claude usage pause state'); return null; } } function writeState(state: ClaudeUsagePauseState | null): void { setRouterState(CLAUDE_USAGE_PAUSE_KEY, JSON.stringify(state)); } /** * Pause `chatJid` until `resumeAt` (kept if a later pause already exists). * Returns the pause now in effect. */ export function pauseRoomForClaudeUsage(args: { chatJid: string; resumeAt: Date; resetKnown: boolean; /** Paused by the usage-alignment hold, not by a usage limit. */ alignment?: boolean; now?: Date; }): ActiveClaudeUsagePause { const now = args.now ?? new Date(); const state = readState(); const keepExisting = state !== null && Date.parse(state.until) >= args.resumeAt.getTime(); const next: ClaudeUsagePauseState = { until: keepExisting ? state.until : args.resumeAt.toISOString(), resetKnown: keepExisting ? state.resetKnown : args.resetKnown, rooms: { ...(state?.rooms ?? {}) }, alignmentOnly: args.alignment === true && (state === null || state.alignmentOnly === true), }; next.rooms[args.chatJid] ??= now.toISOString(); writeState(next); logger.warn( { chatJid: args.chatJid, until: next.until, resetKnown: next.resetKnown }, 'Paused room work until the Claude usage limit resets', ); return { until: new Date(next.until), resetKnown: next.resetKnown }; } /** The Claude usage limit still in effect, or null. */ export function getActiveClaudeUsagePause( nowMs: number = Date.now(), ): ActiveClaudeUsagePause | null { const state = readState(); if (!state || state.alignmentOnly) return null; const until = new Date(state.until); return until.getTime() > nowMs ? { until, resetKnown: state.resetKnown } : null; } export function isRoomPausedForClaudeUsage(chatJid: string): boolean { return Boolean(readState()?.rooms[chatJid]); } /** True when the room is paused and no usage limit is involved. */ export function isRoomPausedOnlyForAlignment(chatJid: string): boolean { const state = readState(); return Boolean(state?.alignmentOnly && state.rooms[chatJid]); } /** Drop a room from the pause (the user stopped its work). */ export function releaseRoomFromClaudeUsagePause(chatJid: string): boolean { const state = readState(); if (!state?.rooms[chatJid]) return false; const rooms = { ...state.rooms }; delete rooms[chatJid]; writeState({ ...state, rooms }); return true; } /** * Once the reset time (plus a margin) has passed, clear the pause and return * the rooms to resume. Returns [] while the pause still holds. */ export function takeRoomsReadyToResume(nowMs: number = Date.now()): string[] { const state = readState(); if (!state) return []; if (Date.parse(state.until) + CLAUDE_USAGE_RESUME_MARGIN_MS > nowMs) { return []; } writeState(null); return Object.keys(state.rooms); } // Runs that ended paused, so the queue keeps their messages unconsumed. const pausedRunIds = new Set(); const MAX_TRACKED_PAUSED_RUNS = 100; export function markRunPausedForClaudeUsage(runId: string): void { pausedRunIds.add(runId); if (pausedRunIds.size > MAX_TRACKED_PAUSED_RUNS) { const oldest = pausedRunIds.values().next().value; if (oldest !== undefined) pausedRunIds.delete(oldest); } } /** True once for a run that ended paused by the Claude usage limit. */ export function consumeRunPausedForClaudeUsage(runId: string): boolean { return pausedRunIds.delete(runId); }