Files
EJClaw/src/claude-usage.ts
Codex 8c68577a24 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>
2026-10-01 20:14:48 +09:00

488 lines
16 KiB
TypeScript

/**
* Claude Usage API
*
* Fetches usage data for the service's Claude account directly from the
* Anthropic OAuth API.
*/
import fs from 'fs';
import path from 'path';
import {
getClaudeCredentialsPath,
hasExplicitClaudeCredentialsPath,
} from './claude-credentials-path.js';
import { DATA_DIR } from './config.js';
import { logger } from './logger.js';
import { getCurrentClaudeToken } from './claude-oauth-token.js';
import { readJsonFile, writeJsonFile } from './utils.js';
const USAGE_CACHE_FILE = path.join(DATA_DIR, 'claude-usage-cache.json');
const PROFILE_ENDPOINT = 'https://api.anthropic.com/api/oauth/profile';
export interface ClaudeUsageData {
five_hour?: { utilization: number; resets_at: string };
seven_day?: { utilization: number; resets_at: string };
seven_day_sonnet?: { utilization: number; resets_at: string };
seven_day_opus?: { utilization: number; resets_at: string };
}
const USAGE_ENDPOINT = 'https://api.anthropic.com/api/oauth/usage';
const FETCH_TIMEOUT_MS = 10_000;
// Master gate for credentials-backed usage queries. When false, the module
// uses only the env-supplied token and skips all credentials-file reads and
// on-401 refresh attempts. Enabled when either an
// explicit CLAUDE_CREDENTIALS_PATH is set or the home fallback is allowed.
const USE_CLAUDE_CREDENTIALS_FOR_USAGE =
hasExplicitClaudeCredentialsPath() ||
process.env.CLAUDE_USAGE_USE_HOME_CREDENTIALS !== 'false';
interface UsageApiResponse {
five_hour?: { utilization: number; resets_at?: string };
seven_day?: { utilization: number; resets_at?: string };
seven_day_sonnet?: { utilization: number; resets_at?: string };
seven_day_opus?: { utilization: number; resets_at?: string };
}
function mapWindow(w?: {
utilization: number;
resets_at?: string;
}): { utilization: number; resets_at: string } | undefined {
if (!w) return undefined;
return { utilization: w.utilization, resets_at: w.resets_at || '' };
}
// ── Disk cache for usage data (survives restarts, 429s) ──
interface UsageCacheEntry {
usage: ClaudeUsageData;
/** Timestamp of last *successful* API fetch (use for stale detection). */
fetchedAt: number;
/** Timestamp of last API *attempt* including failures (use for throttling). */
lastAttemptAt?: number;
/**
* HTTP status of the most recent *failed* attempt (e.g. 429), cleared on a
* successful fetch. Used so the dashboard can render a live error indicator
* instead of a stale value.
*/
lastErrorStatus?: number;
/**
* Epoch-ms before which we MUST NOT retry, derived from a 429 `Retry-After`
* header (or a default backoff when the header is absent). Cleared on a
* successful fetch. Without this we re-poll every MIN_FETCH_INTERVAL_MS (60s)
* even though the endpoint's rate-limit window is longer (~90s+), so the
* cooldown never clears and the 429s become self-sustaining.
*/
cooldownUntil?: number;
}
/**
* Outcome of a usage fetch. `rateLimited` is true when the most recent attempt
* hit a 429 — callers use it to surface an error in the UI rather than the
* last cached value.
*/
export interface UsageFetchResult {
usage: ClaudeUsageData | null;
rateLimited: boolean;
}
// The cache file is a keyed record; one fixed key holds the single account
// (the key matches what earlier versions wrote, so the cache survives).
const USAGE_CACHE_KEY = 'account-0';
let usageDiskCache: Record<string, UsageCacheEntry> = {};
let diskCacheLoaded = false;
function loadUsageDiskCache(): void {
if (diskCacheLoaded) return;
diskCacheLoaded = true;
usageDiskCache =
readJsonFile<Record<string, UsageCacheEntry>>(USAGE_CACHE_FILE) ?? {};
}
function saveUsageDiskCache(): void {
try {
writeJsonFile(USAGE_CACHE_FILE, usageDiskCache);
} catch {
/* best effort */
}
}
function tokenSuffix(token: string): string {
// Use last 8 chars — prefix is always "sk-ant-oat01-" for all tokens
return token.slice(-8);
}
function utilizationPct(utilization: number): number {
return utilization > 1 ? utilization : utilization * 100;
}
/**
* Reset time of the exhausted usage window (5h or 7d, whichever ends later)
* from the last successful usage fetch, or null when no cached window is at
* 100% with a future reset.
*/
export function getCachedClaudeUsageLimitResetAt(
now: number = Date.now(),
): Date | null {
loadUsageDiskCache();
const usage = usageDiskCache[USAGE_CACHE_KEY]?.usage;
let latest: number | null = null;
for (const window of [usage?.five_hour, usage?.seven_day]) {
if (!window || utilizationPct(window.utilization) < 100) continue;
const resetMs = Date.parse(window.resets_at);
if (!Number.isFinite(resetMs) || resetMs <= now) continue;
if (latest == null || resetMs > latest) latest = resetMs;
}
return latest == null ? null : new Date(latest);
}
// Rate limit: at most one API call per 5 minutes.
// The 1-minute cadence existed for the 95% auto-paired-mode gate, which is no
// longer wired into the runtime. The dashboard only needs coarse numbers, and
// polling every minute drew ~32 HTTP 429s a day from the usage endpoint.
const MIN_FETCH_INTERVAL_MS = 300_000;
// Small margin added on top of a server-provided Retry-After so we wait until
// just *after* the cooldown window closes rather than racing its edge.
const RATE_LIMIT_MARGIN_MS = 5_000;
// Fallback cooldown when a 429 carries no usable Retry-After header.
const DEFAULT_RATE_LIMIT_COOLDOWN_MS = 5 * 60_000;
/**
* Parse an HTTP `Retry-After` header into milliseconds from now.
* Accepts either a delta-seconds integer ("93") or an HTTP-date.
* Returns null when the header is missing or unparseable.
*/
export function parseRetryAfterMs(header: string | null): number | null {
if (!header) return null;
const trimmed = header.trim();
if (/^\d+$/.test(trimmed)) {
return Number(trimmed) * 1000;
}
const dateMs = Date.parse(trimmed);
if (Number.isFinite(dateMs)) {
return Math.max(0, dateMs - Date.now());
}
return null;
}
async function fetchUsageForToken(
token: string,
refreshAttempted = false,
): Promise<UsageFetchResult> {
loadUsageDiskCache();
// Return cached data if attempted recently (avoid API rate-limit)
const cached: UsageCacheEntry | undefined = usageDiskCache[USAGE_CACHE_KEY];
/**
* Record this attempt's timestamp (and error status) at the write key,
* creating the entry if it does not exist yet. Recording even when there is
* no prior cached usage is what makes the MIN_FETCH_INTERVAL_MS throttle
* apply to *failures* too — without it an empty cache means every dashboard
* refresh hits the API, which itself sustains the very 429s we then report.
*/
const recordAttempt = (
errorStatus?: number,
cooldownUntil?: number,
): void => {
const now = Date.now();
const entry: UsageCacheEntry = usageDiskCache[USAGE_CACHE_KEY] ?? {
usage: {},
fetchedAt: 0,
};
entry.lastAttemptAt = now;
entry.lastErrorStatus = errorStatus;
entry.cooldownUntil = cooldownUntil;
usageDiskCache[USAGE_CACHE_KEY] = entry;
saveUsageDiskCache();
};
// Honour an active rate-limit cooldown from a prior 429's Retry-After. This
// is what actually breaks the self-sustaining 429 loop: the endpoint hands
// back a ~90s+ window, so retrying on the 60s MIN_FETCH_INTERVAL would keep
// hitting it mid-cooldown and never recover.
if (
!refreshAttempted &&
cached?.cooldownUntil &&
Date.now() < cached.cooldownUntil
) {
return { usage: null, rateLimited: true };
}
const lastAttempt = cached?.lastAttemptAt ?? cached?.fetchedAt ?? 0;
if (
!refreshAttempted &&
cached &&
Date.now() - lastAttempt < MIN_FETCH_INTERVAL_MS
) {
// Within the throttle window: replay the last outcome without an API call.
// On a 429 we report rateLimited and DO NOT serve the stale value.
if (cached.lastErrorStatus === 429) {
return { usage: null, rateLimited: true };
}
return { usage: cached.usage ?? null, rateLimited: false };
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
try {
const res = await fetch(USAGE_ENDPOINT, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
'anthropic-beta': 'oauth-2025-04-20',
'User-Agent': 'ejclaw/1.0',
},
signal: controller.signal,
});
if (res.status === 401 || res.status === 403) {
// 401 = token expired; 403 = token lacks `user:profile` scope.
// Both are recoverable by exchanging refresh_token for a fresh access
// token (mint includes current default scope set). Retry once.
if (USE_CLAUDE_CREDENTIALS_FOR_USAGE && !refreshAttempted) {
try {
const { forceRefreshToken } = await import('./token-refresh.js');
const newToken = await forceRefreshToken();
if (newToken && newToken !== token) {
logger.info(
{ status: res.status },
`Claude usage API: ${res.status} → refreshed access token, retrying`,
);
return fetchUsageForToken(newToken, true);
}
} catch (err) {
logger.warn({ err }, 'Claude usage API: force-refresh failed');
}
}
logger.warn(
{ tokenKey: tokenSuffix(token) },
res.status === 401
? 'Claude usage API: token expired or invalid (401)'
: 'Claude usage API: forbidden — token missing required scope (403)',
);
recordAttempt(res.status);
return { usage: cached?.usage ?? null, rateLimited: false };
}
if (res.status === 429) {
const staleMs = cached ? Date.now() - cached.fetchedAt : 0;
const retryAfterMs = parseRetryAfterMs(res.headers.get('retry-after'));
// A `Retry-After` of 0 (or a past HTTP-date that parses to 0) must NOT
// disable the backoff — honoring it literally makes the poller retry on
// the next 60s tick and re-trip the 429 indefinitely. Treat any
// non-positive value as "no usable hint" and fall back to the default.
const cooldownMs =
retryAfterMs != null && retryAfterMs > 0
? retryAfterMs
: DEFAULT_RATE_LIMIT_COOLDOWN_MS;
const cooldownUntil = Date.now() + cooldownMs + RATE_LIMIT_MARGIN_MS;
logger.warn(
{
tokenKey: tokenSuffix(token),
staleMinutes: Math.round(staleMs / 60_000),
retryAfterSec:
retryAfterMs != null ? Math.round(retryAfterMs / 1000) : null,
cooldownSec: Math.round(cooldownMs / 1000),
},
'Claude usage API: rate limited (429)',
);
// Back off until the server-provided Retry-After window closes (plus a
// margin) so we stop re-tripping the limit. Surfaces a 429 indicator and
// does NOT serve the stale value.
recordAttempt(429, cooldownUntil);
return { usage: null, rateLimited: true };
}
if (!res.ok) {
logger.warn(
{ status: res.status, tokenKey: tokenSuffix(token) },
`Claude usage API: unexpected status ${res.status}`,
);
recordAttempt(res.status);
return { usage: cached?.usage ?? null, rateLimited: false };
}
const data = (await res.json()) as UsageApiResponse;
const result: ClaudeUsageData = {
five_hour: mapWindow(data.five_hour),
seven_day: mapWindow(data.seven_day),
seven_day_sonnet: mapWindow(data.seven_day_sonnet),
seven_day_opus: mapWindow(data.seven_day_opus),
};
// Persist to disk cache — success: update fetchedAt + lastAttemptAt and
// clear any prior error status.
const now = Date.now();
usageDiskCache[USAGE_CACHE_KEY] = {
usage: result,
fetchedAt: now,
lastAttemptAt: now,
lastErrorStatus: undefined,
};
saveUsageDiskCache();
logger.debug(
{
tokenKey: tokenSuffix(token),
h5: result.five_hour?.utilization,
d7: result.seven_day?.utilization,
},
'Claude usage API: fetched successfully',
);
return { usage: result, rateLimited: false };
} catch (err) {
if ((err as Error).name === 'AbortError') {
logger.warn(
{ tokenKey: tokenSuffix(token) },
'Claude usage API: request timed out',
);
} else {
logger.warn(
{ err, tokenKey: tokenSuffix(token) },
'Claude usage API: fetch failed',
);
}
// Record attempt time so we back off on persistent failures
recordAttempt();
return { usage: cached?.usage ?? null, rateLimited: false };
} finally {
clearTimeout(timer);
}
}
export interface ClaudeAccountProfile {
email: string;
planType: string; // "max", "pro", "free"
}
let cachedProfile: ClaudeAccountProfile | undefined;
function readCredentialsOAuthField(
field: 'accessToken' | 'subscriptionType',
): string | null {
if (!USE_CLAUDE_CREDENTIALS_FOR_USAGE) return null;
try {
const credsPath = getClaudeCredentialsPath({
allowHomeFallback:
process.env.CLAUDE_USAGE_USE_HOME_CREDENTIALS !== 'false',
});
if (!credsPath || !fs.existsSync(credsPath)) return null;
const data = readJsonFile<{
claudeAiOauth?: { accessToken?: string; subscriptionType?: string };
}>(credsPath);
return data?.claudeAiOauth?.[field] || null;
} catch {
return null;
}
}
/**
* Token for the usage/profile APIs. Prefer the credentials-file access token:
* the static .env CLAUDE_CODE_OAUTH_TOKEN was issued without the
* `user:profile` scope and is rejected by /api/oauth/usage, while the
* credentials file is rewritten by `claude auth login` and refreshed by
* token-refresh.ts, so it carries the full scope set.
*/
function resolveUsageToken(): string | null {
return (
readCredentialsOAuthField('accessToken') || getCurrentClaudeToken() || null
);
}
async function fetchProfileForToken(
token: string,
): Promise<ClaudeAccountProfile | null> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
try {
const res = await fetch(PROFILE_ENDPOINT, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
'anthropic-beta': 'oauth-2025-04-20',
},
signal: controller.signal,
});
if (!res.ok) return null;
const data = (await res.json()) as {
account?: {
email?: string;
has_claude_max?: boolean;
has_claude_pro?: boolean;
};
organization?: { organization_type?: string };
};
const orgType = data.organization?.organization_type || '';
const planType = data.account?.has_claude_max
? 'max'
: data.account?.has_claude_pro
? 'pro'
: orgType.replace('claude_', '') || '?';
return {
email: data.account?.email || '?',
planType,
};
} catch {
return null;
} finally {
clearTimeout(timer);
}
}
/**
* Fetch the account profile (cached, called once on startup).
*/
export async function fetchClaudeProfile(): Promise<void> {
const token = resolveUsageToken();
if (!token) return;
let profile = await fetchProfileForToken(token);
// Fallback: if profile API failed or returned unknown plan, use credentials file
if (!profile || profile.planType === '?') {
const credsPlan = readCredentialsOAuthField('subscriptionType');
if (credsPlan) {
profile = { email: profile?.email || '?', planType: credsPlan };
logger.info(
{ plan: credsPlan, source: 'credentials' },
`Claude account: ${credsPlan} (from credentials)`,
);
}
}
if (profile) {
cachedProfile = profile;
logger.info(
{ plan: profile.planType, email: profile.email },
`Claude account: ${profile.planType}`,
);
}
}
export function getClaudeProfile(): ClaudeAccountProfile | undefined {
return cachedProfile;
}
export interface ClaudeUsageSnapshot {
usage: ClaudeUsageData | null;
/**
* True when the most recent usage-API attempt hit a 429. The dashboard
* renders a "429" indicator instead of a stale value.
*/
usageRateLimited?: boolean;
}
/**
* Fetch usage for the dashboard. Returns null when no token is configured.
*/
export async function fetchClaudeUsage(): Promise<ClaudeUsageSnapshot | null> {
const token = resolveUsageToken();
if (!token) return null;
const { usage, rateLimited } = await fetchUsageForToken(token);
return { usage, usageRateLimited: rateLimited };
}