feat: pause room work on the Claude usage limit and resume after reset
Before, a Claude run that hit the account usage limit closed the open paired task as claude_usage_limit, posted the reset time and consumed the user's messages, so the work was lost and had to be re-requested. Now the room is paused instead: - The failed turn is released without touching the paired task (no failure count, no status change, no follow-up) and the queue keeps the human messages unconsumed, so the same turn can run again. - The room is recorded in router_state `claude_usage_pause` with the reset time (error text, else cached usage API reset, else a 10 min retry). A banner time that just passed is read as "now", not tomorrow. - While the limit lasts, paused rooms run nothing and any other room's Claude turn pauses that room without spawning a run (the limit is account-wide). A stop request still goes through and drops the room from the resume list. - The scheduler tick clears the pause 1 min after the reset, posts a resume notice and re-queues the rooms; the pending turn or the kept messages then run again. The state survives restarts. Safety refusals keep closing the task as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
139
src/claude-usage-pause.ts
Normal file
139
src/claude-usage-pause.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* 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<string, string>;
|
||||
}
|
||||
|
||||
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;
|
||||
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 ?? {}) },
|
||||
};
|
||||
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) 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]);
|
||||
}
|
||||
|
||||
/** 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<string>();
|
||||
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);
|
||||
}
|
||||
Reference in New Issue
Block a user