refactor: run Claude and Codex on one fixed account each
The deployment has a single Claude OAuth credential and a single Codex ChatGPT account, so the N-account rotation machinery only added state files, cooldown bookkeeping and code paths that never ran. Removed: - Claude token rotation (token-rotation.ts, token-rotation-base.ts): rotate-on-limit, per-token cooldowns, token-rotation-state.json. CLAUDE_CODE_OAUTH_TOKENS is still read, but only its first entry. - Codex account rotation (codex-token-rotation.ts): account pool, rotate-on-429/auth, dead-auth/cooldown tracking, round-robin advance, d7 auto-rotate, codex-rotation-state.json, manual account switch. - Account index plumbing in token-refresh, claude-credentials-path (CLAUDE_ACCOUNTS_DIR / ~/.claude-accounts/<n>), Claude/Codex usage collectors, the dashboard rows and the Codex warm-up. - provider-retry.ts rotation loops and the Codex retry path. Kept: - Codex exclusive auth lease (one Codex run at a time), the 15-minute waitForCodexAuthLease, and a usage-poll lease that skips while a run holds the account (codex-auth.ts). - Session auth copy and write-back of refreshed tokens (syncCodexSessionAuthBack, syncClaudeSessionAuthBack). - Codex auth path: ~/.codex-accounts/0/auth.json, else ~/.codex/auth.json (now resolved per run, so a re-login needs no restart). - Claude token refresh loop, CLAUDE_CREDENTIALS_PATH and the CLAUDE_TOKEN_REFRESH_* / CLAUDE_USAGE_USE_HOME_CREDENTIALS flags; an auth-expired run still force-refreshes the token and retries once. - Error classification (classifyClaudeTrigger, classifyCodexTrigger). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* Claude Usage API
|
||||
*
|
||||
* Fetches usage data directly from the Anthropic OAuth API.
|
||||
* Supports multiple tokens for rotation-aware usage checking.
|
||||
* Fetches usage data for the service's Claude account directly from the
|
||||
* Anthropic OAuth API.
|
||||
*/
|
||||
|
||||
import fs from 'fs';
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
} from './claude-credentials-path.js';
|
||||
import { DATA_DIR } from './config.js';
|
||||
import { logger } from './logger.js';
|
||||
import { getAllTokens, getConfiguredClaudeTokens } from './token-rotation.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');
|
||||
@@ -32,8 +32,8 @@ 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 env-supplied tokens and skips all credentials-file reads, per-
|
||||
// account cache keys, and on-401 refresh attempts. Enabled when either an
|
||||
// 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() ||
|
||||
@@ -88,6 +88,10 @@ export interface UsageFetchResult {
|
||||
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;
|
||||
|
||||
@@ -106,46 +110,12 @@ function saveUsageDiskCache(): void {
|
||||
}
|
||||
}
|
||||
|
||||
function legacyTokenCacheKey(token: string): string {
|
||||
function tokenSuffix(token: string): string {
|
||||
// Use last 8 chars — prefix is always "sk-ant-oat01-" for all tokens
|
||||
return token.slice(-8);
|
||||
}
|
||||
|
||||
function accountCacheKey(accountIndex: number): string {
|
||||
return `account-${accountIndex}`;
|
||||
}
|
||||
|
||||
export function getUsageCacheWriteKey(
|
||||
token: string,
|
||||
accountIndex?: number,
|
||||
): string {
|
||||
return USE_CLAUDE_CREDENTIALS_FOR_USAGE && accountIndex != null
|
||||
? accountCacheKey(accountIndex)
|
||||
: legacyTokenCacheKey(token);
|
||||
}
|
||||
|
||||
export function getUsageCacheReadKeys(
|
||||
token: string,
|
||||
accountIndex?: number,
|
||||
credentialsAccessToken?: string | null,
|
||||
): string[] {
|
||||
const keys: string[] = [];
|
||||
if (USE_CLAUDE_CREDENTIALS_FOR_USAGE && accountIndex != null) {
|
||||
keys.push(accountCacheKey(accountIndex));
|
||||
}
|
||||
|
||||
if (USE_CLAUDE_CREDENTIALS_FOR_USAGE && credentialsAccessToken) {
|
||||
const credsKey = legacyTokenCacheKey(credentialsAccessToken);
|
||||
if (!keys.includes(credsKey)) keys.push(credsKey);
|
||||
}
|
||||
|
||||
const tokenKey = legacyTokenCacheKey(token);
|
||||
if (!keys.includes(tokenKey)) keys.push(tokenKey);
|
||||
|
||||
return keys;
|
||||
}
|
||||
|
||||
// Rate limit: at most one API call per token per 5 minutes.
|
||||
// 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.
|
||||
@@ -177,37 +147,12 @@ export function parseRetryAfterMs(header: string | null): number | null {
|
||||
|
||||
async function fetchUsageForToken(
|
||||
token: string,
|
||||
accountIndex?: number,
|
||||
refreshAttempted = false,
|
||||
): Promise<UsageFetchResult> {
|
||||
loadUsageDiskCache();
|
||||
|
||||
// Return cached data if attempted recently (avoid API rate-limit)
|
||||
const writeKey = getUsageCacheWriteKey(token, accountIndex);
|
||||
const readKeys = getUsageCacheReadKeys(
|
||||
token,
|
||||
accountIndex,
|
||||
accountIndex != null ? readCredentialsAccessToken(accountIndex) : null,
|
||||
);
|
||||
let cachedKey: string | null = null;
|
||||
let cached: UsageCacheEntry | undefined;
|
||||
for (const key of readKeys) {
|
||||
const entry = usageDiskCache[key];
|
||||
if (!entry) continue;
|
||||
cachedKey = key;
|
||||
cached = entry;
|
||||
break;
|
||||
}
|
||||
if (
|
||||
cached &&
|
||||
cachedKey &&
|
||||
cachedKey !== writeKey &&
|
||||
!usageDiskCache[writeKey]
|
||||
) {
|
||||
usageDiskCache[writeKey] = { ...cached };
|
||||
cached = usageDiskCache[writeKey];
|
||||
saveUsageDiskCache();
|
||||
}
|
||||
const cached: UsageCacheEntry | undefined = usageDiskCache[USAGE_CACHE_KEY];
|
||||
|
||||
/**
|
||||
* Record this attempt's timestamp (and error status) at the write key,
|
||||
@@ -221,14 +166,14 @@ async function fetchUsageForToken(
|
||||
cooldownUntil?: number,
|
||||
): void => {
|
||||
const now = Date.now();
|
||||
const entry: UsageCacheEntry = usageDiskCache[writeKey] ?? {
|
||||
const entry: UsageCacheEntry = usageDiskCache[USAGE_CACHE_KEY] ?? {
|
||||
usage: {},
|
||||
fetchedAt: 0,
|
||||
};
|
||||
entry.lastAttemptAt = now;
|
||||
entry.lastErrorStatus = errorStatus;
|
||||
entry.cooldownUntil = cooldownUntil;
|
||||
usageDiskCache[writeKey] = entry;
|
||||
usageDiskCache[USAGE_CACHE_KEY] = entry;
|
||||
saveUsageDiskCache();
|
||||
};
|
||||
|
||||
@@ -275,38 +220,23 @@ async function fetchUsageForToken(
|
||||
// 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 &&
|
||||
accountIndex != null &&
|
||||
!refreshAttempted
|
||||
) {
|
||||
if (USE_CLAUDE_CREDENTIALS_FOR_USAGE && !refreshAttempted) {
|
||||
try {
|
||||
const { forceRefreshToken } = await import('./token-refresh.js');
|
||||
const newToken = await forceRefreshToken(accountIndex);
|
||||
const newToken = await forceRefreshToken();
|
||||
if (newToken && newToken !== token) {
|
||||
logger.info(
|
||||
{
|
||||
account: accountIndex + 1,
|
||||
status: res.status,
|
||||
cacheKey: writeKey,
|
||||
},
|
||||
{ status: res.status },
|
||||
`Claude usage API: ${res.status} → refreshed access token, retrying`,
|
||||
);
|
||||
return fetchUsageForToken(newToken, accountIndex, true);
|
||||
return fetchUsageForToken(newToken, true);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ err, account: accountIndex + 1 },
|
||||
'Claude usage API: force-refresh failed',
|
||||
);
|
||||
logger.warn({ err }, 'Claude usage API: force-refresh failed');
|
||||
}
|
||||
}
|
||||
logger.warn(
|
||||
{
|
||||
account: accountIndex != null ? accountIndex + 1 : '?',
|
||||
tokenKey: legacyTokenCacheKey(token),
|
||||
cacheKey: writeKey,
|
||||
},
|
||||
{ tokenKey: tokenSuffix(token) },
|
||||
res.status === 401
|
||||
? 'Claude usage API: token expired or invalid (401)'
|
||||
: 'Claude usage API: forbidden — token missing required scope (403)',
|
||||
@@ -328,9 +258,7 @@ async function fetchUsageForToken(
|
||||
const cooldownUntil = Date.now() + cooldownMs + RATE_LIMIT_MARGIN_MS;
|
||||
logger.warn(
|
||||
{
|
||||
account: accountIndex != null ? accountIndex + 1 : '?',
|
||||
tokenKey: legacyTokenCacheKey(token),
|
||||
cacheKey: writeKey,
|
||||
tokenKey: tokenSuffix(token),
|
||||
staleMinutes: Math.round(staleMs / 60_000),
|
||||
retryAfterSec:
|
||||
retryAfterMs != null ? Math.round(retryAfterMs / 1000) : null,
|
||||
@@ -346,12 +274,7 @@ async function fetchUsageForToken(
|
||||
}
|
||||
if (!res.ok) {
|
||||
logger.warn(
|
||||
{
|
||||
account: accountIndex != null ? accountIndex + 1 : '?',
|
||||
status: res.status,
|
||||
tokenKey: legacyTokenCacheKey(token),
|
||||
cacheKey: writeKey,
|
||||
},
|
||||
{ status: res.status, tokenKey: tokenSuffix(token) },
|
||||
`Claude usage API: unexpected status ${res.status}`,
|
||||
);
|
||||
recordAttempt(res.status);
|
||||
@@ -370,7 +293,7 @@ async function fetchUsageForToken(
|
||||
// Persist to disk cache — success: update fetchedAt + lastAttemptAt and
|
||||
// clear any prior error status.
|
||||
const now = Date.now();
|
||||
usageDiskCache[writeKey] = {
|
||||
usageDiskCache[USAGE_CACHE_KEY] = {
|
||||
usage: result,
|
||||
fetchedAt: now,
|
||||
lastAttemptAt: now,
|
||||
@@ -380,9 +303,7 @@ async function fetchUsageForToken(
|
||||
|
||||
logger.debug(
|
||||
{
|
||||
account: accountIndex != null ? accountIndex + 1 : '?',
|
||||
tokenKey: legacyTokenCacheKey(token),
|
||||
cacheKey: writeKey,
|
||||
tokenKey: tokenSuffix(token),
|
||||
h5: result.five_hour?.utilization,
|
||||
d7: result.seven_day?.utilization,
|
||||
},
|
||||
@@ -393,21 +314,12 @@ async function fetchUsageForToken(
|
||||
} catch (err) {
|
||||
if ((err as Error).name === 'AbortError') {
|
||||
logger.warn(
|
||||
{
|
||||
account: accountIndex != null ? accountIndex + 1 : '?',
|
||||
tokenKey: legacyTokenCacheKey(token),
|
||||
cacheKey: writeKey,
|
||||
},
|
||||
{ tokenKey: tokenSuffix(token) },
|
||||
'Claude usage API: request timed out',
|
||||
);
|
||||
} else {
|
||||
logger.warn(
|
||||
{
|
||||
err,
|
||||
account: accountIndex != null ? accountIndex + 1 : '?',
|
||||
tokenKey: legacyTokenCacheKey(token),
|
||||
cacheKey: writeKey,
|
||||
},
|
||||
{ err, tokenKey: tokenSuffix(token) },
|
||||
'Claude usage API: fetch failed',
|
||||
);
|
||||
}
|
||||
@@ -424,46 +336,38 @@ export interface ClaudeAccountProfile {
|
||||
planType: string; // "max", "pro", "free"
|
||||
}
|
||||
|
||||
const profileCache = new Map<number, ClaudeAccountProfile>();
|
||||
let cachedProfile: ClaudeAccountProfile | undefined;
|
||||
|
||||
/**
|
||||
* Read planType from credentials file as fallback when profile API fails.
|
||||
* Path is resolved by getClaudeCredentialsPath (honours CLAUDE_CREDENTIALS_PATH
|
||||
* / CLAUDE_ACCOUNTS_DIR / home fallback). Returns null when the credentials
|
||||
* gate is off or no file is found.
|
||||
*/
|
||||
function readCredentialsPlanType(accountIndex: number): string | null {
|
||||
function readCredentialsOAuthField(
|
||||
field: 'accessToken' | 'subscriptionType',
|
||||
): string | null {
|
||||
if (!USE_CLAUDE_CREDENTIALS_FOR_USAGE) return null;
|
||||
try {
|
||||
const credsPath = getClaudeCredentialsPath(accountIndex, {
|
||||
const credsPath = getClaudeCredentialsPath({
|
||||
allowHomeFallback:
|
||||
process.env.CLAUDE_USAGE_USE_HOME_CREDENTIALS !== 'false',
|
||||
});
|
||||
if (!credsPath || !fs.existsSync(credsPath)) return null;
|
||||
const data = readJsonFile<{
|
||||
claudeAiOauth?: { subscriptionType?: string };
|
||||
claudeAiOauth?: { accessToken?: string; subscriptionType?: string };
|
||||
}>(credsPath);
|
||||
return data?.claudeAiOauth?.subscriptionType || null;
|
||||
return data?.claudeAiOauth?.[field] || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function readCredentialsAccessToken(accountIndex: number): string | null {
|
||||
if (!USE_CLAUDE_CREDENTIALS_FOR_USAGE) return null;
|
||||
try {
|
||||
const credsPath = getClaudeCredentialsPath(accountIndex, {
|
||||
allowHomeFallback:
|
||||
process.env.CLAUDE_USAGE_USE_HOME_CREDENTIALS !== 'false',
|
||||
});
|
||||
if (!credsPath || !fs.existsSync(credsPath)) return null;
|
||||
const data = readJsonFile<{
|
||||
claudeAiOauth?: { accessToken?: string };
|
||||
}>(credsPath);
|
||||
return data?.claudeAiOauth?.accessToken || 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(
|
||||
@@ -507,105 +411,53 @@ async function fetchProfileForToken(
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch profiles for all Claude tokens (cached, called once on startup).
|
||||
* Fetch the account profile (cached, called once on startup).
|
||||
*/
|
||||
export async function fetchAllClaudeProfiles(): Promise<void> {
|
||||
const allTokens = getAllTokens();
|
||||
for (const t of allTokens) {
|
||||
// Prefer the per-account credentials access token; the static env token
|
||||
// may lack the `user:profile` scope.
|
||||
const credsToken = readCredentialsAccessToken(t.index);
|
||||
let profile = await fetchProfileForToken(credsToken || t.token);
|
||||
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 = readCredentialsPlanType(t.index);
|
||||
if (credsPlan) {
|
||||
profile = {
|
||||
email: profile?.email || '?',
|
||||
planType: credsPlan,
|
||||
};
|
||||
logger.info(
|
||||
{ account: t.index + 1, plan: credsPlan, source: 'credentials' },
|
||||
`Claude account #${t.index + 1}: ${credsPlan} (from credentials)`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (profile) {
|
||||
profileCache.set(t.index, profile);
|
||||
// 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(
|
||||
{ account: t.index + 1, plan: profile.planType, email: profile.email },
|
||||
`Claude account #${t.index + 1}: ${profile.planType}`,
|
||||
{ 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(
|
||||
index: number,
|
||||
): ClaudeAccountProfile | undefined {
|
||||
return profileCache.get(index);
|
||||
export function getClaudeProfile(): ClaudeAccountProfile | undefined {
|
||||
return cachedProfile;
|
||||
}
|
||||
|
||||
export interface ClaudeAccountUsage {
|
||||
index: number;
|
||||
masked: string;
|
||||
isActive: boolean;
|
||||
isRateLimited: boolean;
|
||||
export interface ClaudeUsageSnapshot {
|
||||
usage: ClaudeUsageData | null;
|
||||
/**
|
||||
* True when the most recent usage-API attempt for this account hit a 429.
|
||||
* The dashboard renders a "429" indicator instead of a stale value.
|
||||
* 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 ALL configured tokens.
|
||||
* Returns per-account usage for dashboard display.
|
||||
* Fetch usage for the dashboard. Returns null when no token is configured.
|
||||
*/
|
||||
export async function fetchAllClaudeUsage(): Promise<ClaudeAccountUsage[]> {
|
||||
const allTokens = getAllTokens();
|
||||
logger.debug({ tokenCount: allTokens.length }, 'fetchAllClaudeUsage called');
|
||||
if (allTokens.length === 0) {
|
||||
const credsToken = readCredentialsAccessToken(0);
|
||||
const token = credsToken || getConfiguredClaudeTokens()[0];
|
||||
if (!token) return [];
|
||||
const { usage, rateLimited } = await fetchUsageForToken(token, 0);
|
||||
return [
|
||||
{
|
||||
index: 0,
|
||||
masked: `${token.slice(0, 20)}...${token.slice(-4)}`,
|
||||
isActive: true,
|
||||
isRateLimited: false,
|
||||
usage,
|
||||
usageRateLimited: rateLimited,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const results: ClaudeAccountUsage[] = [];
|
||||
for (const t of allTokens) {
|
||||
// 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, rateLimited } = await fetchUsageForToken(
|
||||
tokenForFetch,
|
||||
t.index,
|
||||
);
|
||||
results.push({
|
||||
index: t.index,
|
||||
masked: t.masked,
|
||||
isActive: t.isActive,
|
||||
isRateLimited: t.isRateLimited,
|
||||
usage,
|
||||
usageRateLimited: rateLimited,
|
||||
});
|
||||
}
|
||||
return results;
|
||||
export async function fetchClaudeUsage(): Promise<ClaudeUsageSnapshot | null> {
|
||||
const token = resolveUsageToken();
|
||||
if (!token) return null;
|
||||
const { usage, rateLimited } = await fetchUsageForToken(token);
|
||||
return { usage, usageRateLimited: rateLimited };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user