Files
EJClaw/src/claude-usage-pause.ts
Codex f944f97e54 feat: usage-alignment hold (04-08 KST daily + one-off hold until a set time)
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>
2026-10-16 05:54:39 +09:00

157 lines
5.3 KiB
TypeScript

/**
* 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>;
/**
* 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<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);
}