backup current stable ejclaw state

This commit is contained in:
Codex
2026-05-27 10:53:05 +09:00
parent 646bc34372
commit 1509108e04
57 changed files with 7127 additions and 154 deletions

View File

@@ -112,12 +112,15 @@ export function getUsageCacheReadKeys(
return keys;
}
// Rate limit: at most one API call per token per 5 minutes
const MIN_FETCH_INTERVAL_MS = 300_000;
// Rate limit: at most one API call per token per 1 minute.
// We poll usage every minute (was 5) so the 95% exhaustion gate has tight
// resolution — at worst the gate fires ~60s after a window crosses 95%.
const MIN_FETCH_INTERVAL_MS = 60_000;
async function fetchUsageForToken(
token: string,
accountIndex?: number,
refreshAttempted = false,
): Promise<ClaudeUsageData | null> {
loadUsageDiskCache();
@@ -148,7 +151,11 @@ async function fetchUsageForToken(
saveUsageDiskCache();
}
const lastAttempt = cached?.lastAttemptAt ?? cached?.fetchedAt ?? 0;
if (cached && Date.now() - lastAttempt < MIN_FETCH_INTERVAL_MS) {
if (
!refreshAttempted &&
cached &&
Date.now() - lastAttempt < MIN_FETCH_INTERVAL_MS
) {
return cached.usage;
}
const controller = new AbortController();
@@ -165,16 +172,47 @@ async function fetchUsageForToken(
signal: controller.signal,
});
if (res.status === 401) {
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 (accountIndex != null && !refreshAttempted) {
try {
const { forceRefreshToken } = await import('./token-refresh.js');
const newToken = await forceRefreshToken(accountIndex);
if (newToken && newToken !== token) {
logger.info(
{
account: accountIndex + 1,
status: res.status,
cacheKey: writeKey,
},
`Claude usage API: ${res.status} → refreshed access token, retrying`,
);
return fetchUsageForToken(newToken, accountIndex, true);
}
} catch (err) {
logger.warn(
{ err, account: accountIndex + 1 },
'Claude usage API: force-refresh failed',
);
}
}
logger.warn(
{
account: accountIndex != null ? accountIndex + 1 : '?',
tokenKey: legacyTokenCacheKey(token),
cacheKey: writeKey,
},
'Claude usage API: token expired or invalid (401)',
res.status === 401
? 'Claude usage API: token expired or invalid (401)'
: 'Claude usage API: forbidden — token missing required scope (403)',
);
return null;
if (cached) {
cached.lastAttemptAt = Date.now();
saveUsageDiskCache();
}
return cached?.usage ?? null;
}
if (res.status === 429) {
const staleMs = cached ? Date.now() - cached.fetchedAt : 0;
@@ -278,7 +316,15 @@ async function fetchUsageForToken(
* Uses the current active token from rotation.
*/
export async function fetchClaudeUsage(): Promise<ClaudeUsageData | null> {
const token = getCurrentToken() || getConfiguredClaudeTokens()[0];
// Prefer the access token in ~/.claude/.credentials.json when present.
// The static .env token (CLAUDE_CODE_OAUTH_TOKEN) was issued before the
// `user:profile` scope was required for /api/oauth/usage and so always 403s.
// The credentials file is the canonical source written by `claude auth
// login` and kept fresh by token-refresh.ts — its accessToken carries the
// full scope set including user:profile.
const credsToken = readCredentialsAccessToken(0);
const token =
credsToken || getCurrentToken() || getConfiguredClaudeTokens()[0];
if (!token) {
logger.debug('No Claude OAuth token available for usage check');
return null;
@@ -435,7 +481,8 @@ export async function fetchAllClaudeUsage(): Promise<ClaudeAccountUsage[]> {
const allTokens = getAllTokens();
logger.debug({ tokenCount: allTokens.length }, 'fetchAllClaudeUsage called');
if (allTokens.length === 0) {
const token = getConfiguredClaudeTokens()[0];
const credsToken = readCredentialsAccessToken(0);
const token = credsToken || getConfiguredClaudeTokens()[0];
if (!token) return [];
const usage = await fetchUsageForToken(token, 0);
return [
@@ -451,7 +498,14 @@ export async function fetchAllClaudeUsage(): Promise<ClaudeAccountUsage[]> {
const results: ClaudeAccountUsage[] = [];
for (const t of allTokens) {
const usage = await fetchUsageForToken(t.token, t.index);
// Prefer the per-account credentials.json access token when present.
// The static .env CLAUDE_CODE_OAUTH_TOKEN(S) values were issued without
// the `user:profile` scope and so are rejected by /api/oauth/usage.
// The credentials file is rewritten by `claude auth login` and refreshed
// by token-refresh.ts, so it always carries the full scope set.
const credsToken = readCredentialsAccessToken(t.index);
const tokenForFetch = credsToken || t.token;
const usage = await fetchUsageForToken(tokenForFetch, t.index);
results.push({
index: t.index,
masked: t.masked,
@@ -465,3 +519,103 @@ export async function fetchAllClaudeUsage(): Promise<ClaudeAccountUsage[]> {
// Legacy alias
export const fetchClaudeUsageViaCli = fetchClaudeUsage;
// ── Exhaustion gate ───────────────────────────────────────────────────────
//
// Threshold above which a Claude account is considered "out of budget" for
// the purpose of admitting new turns. A turn is blocked only when *every*
// Claude account is either at/over this threshold on either window or
// already in a rate-limit cooldown.
export const CLAUDE_EXHAUSTION_THRESHOLD_PCT = 95;
export interface UsageExhaustionInfo {
exhausted: boolean;
/** ISO timestamp of the soonest reset that would relieve exhaustion. */
nextResetAt: string | null;
}
/** Normalise the API's utilization field (which can be fractional or percent). */
function normaliseUtilization(u: number | undefined): number {
if (u == null || !Number.isFinite(u)) return 0;
return u >= 0 && u < 1 ? u * 100 : u;
}
function parseResetMs(s: string | undefined | null): number | null {
if (!s) return null;
const t = Date.parse(s);
return Number.isFinite(t) ? t : null;
}
/**
* Reports whether every configured Claude account is either ≥ 95% on a
* window or in a rate-limit cooldown, and — when so — the soonest moment at
* which any one account is expected to recover.
*
* Reads the on-disk usage cache (refreshed every minute by the dashboard
* renderer); performs no network I/O. Returns `exhausted: false` when there
* are no configured tokens, or when usage data is missing for any account
* (err on letting work through).
*/
export function getClaudeUsageExhaustion(): UsageExhaustionInfo {
loadUsageDiskCache();
const allTokens = getAllTokens();
if (allTokens.length === 0) return { exhausted: false, nextResetAt: null };
let earliestRecoveryMs = Infinity;
for (const t of allTokens) {
if (t.isRateLimited) {
// Rate-limit recovery time is not exposed on the token snapshot here;
// we treat it as "unknown but eventually". Skip from the min calc.
continue;
}
const credsToken = readCredentialsAccessToken(t.index);
const readKeys = getUsageCacheReadKeys(t.token, t.index, credsToken);
let entry: UsageCacheEntry | undefined;
for (const key of readKeys) {
if (usageDiskCache[key]) {
entry = usageDiskCache[key];
break;
}
}
if (!entry) return { exhausted: false, nextResetAt: null };
const h5 = normaliseUtilization(entry.usage.five_hour?.utilization);
const d7 = normaliseUtilization(entry.usage.seven_day?.utilization);
if (Math.max(h5, d7) < CLAUDE_EXHAUSTION_THRESHOLD_PCT) {
return { exhausted: false, nextResetAt: null };
}
// This account is exhausted. It becomes available again when whichever
// window(s) are over the threshold drop back below it. We approximate
// that as max(reset of each window currently ≥ threshold).
const h5ResetMs =
h5 >= CLAUDE_EXHAUSTION_THRESHOLD_PCT
? parseResetMs(entry.usage.five_hour?.resets_at)
: null;
const d7ResetMs =
d7 >= CLAUDE_EXHAUSTION_THRESHOLD_PCT
? parseResetMs(entry.usage.seven_day?.resets_at)
: null;
const candidates = [h5ResetMs, d7ResetMs].filter(
(v): v is number => v != null,
);
if (candidates.length > 0) {
const accountRecovery = Math.max(...candidates);
if (accountRecovery < earliestRecoveryMs) {
earliestRecoveryMs = accountRecovery;
}
}
}
const nextResetAt = Number.isFinite(earliestRecoveryMs)
? new Date(earliestRecoveryMs).toISOString()
: null;
return { exhausted: true, nextResetAt };
}
/** Backwards-compat boolean wrapper. */
export function isClaudeUsageExhausted(): boolean {
return getClaudeUsageExhaustion().exhausted;
}