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:
Codex
2026-10-01 20:00:46 +09:00
parent f127ac7a2b
commit a9eab5cb94
58 changed files with 1691 additions and 5547 deletions

View File

@@ -1,15 +1,12 @@
/**
* OAuth Token Auto-Refresh for Claude Code (Multi-Account)
* OAuth Token Auto-Refresh for Claude Code
*
* Periodically checks credentials files and refreshes access tokens
* before they expire. Supports multiple accounts via CLAUDE_CODE_OAUTH_TOKENS.
* Periodically checks the service's credentials file (CLAUDE_CREDENTIALS_PATH,
* or ~/.claude/.credentials.json when the home fallback is enabled) and
* refreshes the access token before it expires.
*
* Account credential paths:
* - Account 0 (default): ~/.claude/.credentials.json
* - Account 1+: ~/.claude-accounts/{index}/.credentials.json
*
* After refresh, updates both the in-memory token rotation state and
* the .env file so new tokens survive restarts.
* After refresh, updates both the in-memory token and the .env file so the
* new token survives restarts.
*/
import fs from 'fs';
import { getErrorMessage, readJsonFile } from './utils.js';
@@ -17,7 +14,10 @@ import path from 'path';
import { logger } from './logger.js';
import { DATA_DIR } from './config.js';
import { getAllTokens, updateTokenValue } from './token-rotation.js';
import {
getConfiguredClaudeToken,
setCurrentClaudeToken,
} from './claude-oauth-token.js';
import type { AgentType } from './types.js';
import {
getClaudeCredentialsPath,
@@ -59,27 +59,24 @@ interface AuthFailureState {
firstFailureAt: number;
gaveUp: boolean;
}
// Per-account continuous-refresh-failure tracking. Cleared as soon as a valid
// token appears again (e.g. after a manual re-login rewrites the creds file).
const authFailureByAccount = new Map<number, AuthFailureState>();
// Continuous-refresh-failure tracking. Cleared as soon as a valid token
// appears again (e.g. after a manual re-login rewrites the creds file).
let authFailure: AuthFailureState | null = null;
/**
* True when automatic refresh for this account has been failing for longer than
* True when automatic refresh has been failing for longer than
* GIVE_UP_AFTER_MS and we have stopped retrying. Request handlers use this to
* reply with RELOGIN_REQUIRED_MESSAGE instead of running a doomed agent.
*/
export function isReloginRequired(accountIndex = 0): boolean {
return authFailureByAccount.get(accountIndex)?.gaveUp === true;
export function isReloginRequired(): boolean {
return authFailure?.gaveUp === true;
}
/** Clear failure tracking once a valid token is observed again. */
function recordAuthSuccess(accountIndex: number): void {
if (authFailureByAccount.has(accountIndex)) {
authFailureByAccount.delete(accountIndex);
logger.info(
{ accountIndex },
'Claude OAuth recovered — cleared re-login-required state',
);
function recordAuthSuccess(): void {
if (authFailure) {
authFailure = null;
logger.info('Claude OAuth recovered — cleared re-login-required state');
}
}
@@ -88,21 +85,17 @@ function recordAuthSuccess(accountIndex: number): void {
* failing for >= GIVE_UP_AFTER_MS), at which point the caller should stop
* hitting the network.
*/
function recordAuthFailure(accountIndex: number): boolean {
function recordAuthFailure(): boolean {
const now = Date.now();
const state = authFailureByAccount.get(accountIndex);
const state = authFailure;
if (!state) {
authFailureByAccount.set(accountIndex, {
firstFailureAt: now,
gaveUp: false,
});
authFailure = { firstFailureAt: now, gaveUp: false };
return false;
}
if (!state.gaveUp && now - state.firstFailureAt >= GIVE_UP_AFTER_MS) {
state.gaveUp = true;
logger.error(
{
accountIndex,
failingForMin: Math.round((now - state.firstFailureAt) / 60000),
},
'Claude OAuth refresh has failed for over 30 min — giving up automatic ' +
@@ -138,41 +131,35 @@ interface TokenResponse {
scope?: string;
}
/**
* Get the credentials file path for a given account index.
* - Index 0: ~/.claude/.credentials.json
* - Index 1+: ~/.claude-accounts/{index}/.credentials.json
*/
function getCredentialsPath(accountIndex: number): string {
const credsPath = getClaudeCredentialsPath(accountIndex, {
/** Credentials file path (CLAUDE_CREDENTIALS_PATH or the home fallback). */
function getCredentialsPath(): string {
const credsPath = getClaudeCredentialsPath({
allowHomeFallback:
process.env.CLAUDE_TOKEN_REFRESH_USE_HOME_CREDENTIALS === 'true',
});
if (!credsPath) {
throw new Error(
`No Claude credentials path configured for account ${accountIndex}`,
);
throw new Error('No Claude credentials path configured');
}
return credsPath;
}
function readCredentials(accountIndex: number): CredentialsFile | null {
function readCredentials(): CredentialsFile | null {
let credsPath: string;
try {
credsPath = getCredentialsPath(accountIndex);
credsPath = getCredentialsPath();
} catch {
return null;
}
if (!fs.existsSync(credsPath)) return null;
const data = readJsonFile<CredentialsFile>(credsPath);
if (!data) {
logger.warn({ accountIndex }, 'Failed to read Claude credentials');
logger.warn('Failed to read Claude credentials');
}
return data;
}
function writeCredentials(accountIndex: number, creds: CredentialsFile): void {
const credsPath = getCredentialsPath(accountIndex);
function writeCredentials(creds: CredentialsFile): void {
const credsPath = getCredentialsPath();
const dir = path.dirname(credsPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
@@ -311,10 +298,7 @@ export function shouldAdoptSessionOAuth(
* the whole token family (forcing a manual re-login). Mirrors the Codex
* syncCodexSessionAuthBack write-back. Returns true if canonical was updated.
*/
export function syncClaudeSessionAuthBack(
sessionClaudeDir: string,
accountIndex = 0,
): boolean {
export function syncClaudeSessionAuthBack(sessionClaudeDir: string): boolean {
if (!sessionClaudeDir) return false;
const sessionPath = path.join(sessionClaudeDir, '.credentials.json');
let sessionCreds: CredentialsFile | null = null;
@@ -328,7 +312,7 @@ export function syncClaudeSessionAuthBack(
}
const sOauth = sessionCreds?.claudeAiOauth;
if (!sOauth) return false;
const canonical = readCredentials(accountIndex);
const canonical = readCredentials();
if (!shouldAdoptSessionOAuth(sOauth, canonical?.claudeAiOauth)) {
return false;
}
@@ -336,11 +320,10 @@ export function syncClaudeSessionAuthBack(
// writeCredentials also fans the adopted token out to every session dir, so
// stale copies (old refresh tokens that could trigger family revocation) are
// overwritten with the current one.
writeCredentials(accountIndex, sessionCreds);
recordAuthSuccess(accountIndex);
writeCredentials(sessionCreds);
recordAuthSuccess();
logger.info(
{
accountIndex,
newExpiryMin: Math.round((sOauth.expiresAt - Date.now()) / 60000),
},
'Adopted refreshed Claude session token back into canonical credentials',
@@ -372,15 +355,6 @@ export function pickFreshestOAuth(
return best;
}
/**
* Only the primary account (index 0 / the service's CLAUDE_CREDENTIALS_PATH) is
* mirrored into session dirs. Scanning them for other accounts would adopt the
* wrong token family.
*/
function isPrimarySessionAccount(accountIndex: number): boolean {
return accountIndex === 0;
}
interface FreshestCredentials {
creds: CredentialsFile;
/** True when the freshest copy came from a session dir, not the source file. */
@@ -395,19 +369,15 @@ interface FreshestCredentials {
* re-POSTing our now-stale refresh token is what prevents reuse-detection from
* revoking the entire family.
*/
function loadFreshestCredentials(
accountIndex: number,
): FreshestCredentials | null {
function loadFreshestCredentials(): FreshestCredentials | null {
const candidates: Array<{ label: string; creds: CredentialsFile | null }> = [
{ label: 'source', creds: readCredentials(accountIndex) },
{ label: 'source', creds: readCredentials() },
];
if (isPrimarySessionAccount(accountIndex)) {
for (const sessionPath of listSessionCredentialPaths()) {
candidates.push({
label: sessionPath,
creds: readJsonFile<CredentialsFile>(sessionPath),
});
}
for (const sessionPath of listSessionCredentialPaths()) {
candidates.push({
label: sessionPath,
creds: readJsonFile<CredentialsFile>(sessionPath),
});
}
const best = pickFreshestOAuth(candidates);
if (!best) return null;
@@ -419,44 +389,51 @@ function loadFreshestCredentials(
}
/**
* Update CLAUDE_CODE_OAUTH_TOKENS in .env so refreshed tokens survive restarts.
* Write the refreshed token into .env so it survives restarts. Both the
* CLAUDE_CODE_OAUTH_TOKEN line and the legacy CLAUDE_CODE_OAUTH_TOKENS line are
* rewritten when present; with neither present, CLAUDE_CODE_OAUTH_TOKEN is
* appended.
*/
export function applyUpdatedTokensToEnvContent(
export function applyUpdatedTokenToEnvContent(
content: string,
tokens: string[],
token: string,
): string {
if (tokens.length === 0) return content;
const multiValue = tokens.join(',');
const multiLineRe = /^CLAUDE_CODE_OAUTH_TOKENS=.*/m;
const listLineRe = /^CLAUDE_CODE_OAUTH_TOKENS=.*/m;
const singleLineRe = /^CLAUDE_CODE_OAUTH_TOKEN=.*/m;
let next = content;
if (multiLineRe.test(next)) {
next = next.replace(multiLineRe, `CLAUDE_CODE_OAUTH_TOKENS=${multiValue}`);
} else {
next = `${next.replace(/\s*$/, '')}\nCLAUDE_CODE_OAUTH_TOKENS=${multiValue}\n`;
const hasList = listLineRe.test(next);
const hasSingle = singleLineRe.test(next);
if (hasList) {
next = next.replace(listLineRe, `CLAUDE_CODE_OAUTH_TOKENS=${token}`);
}
if (singleLineRe.test(next)) {
next = next.replace(singleLineRe, `CLAUDE_CODE_OAUTH_TOKEN=${tokens[0]}`);
if (hasSingle) {
next = next.replace(singleLineRe, `CLAUDE_CODE_OAUTH_TOKEN=${token}`);
}
if (!hasList && !hasSingle) {
next = `${next.replace(/\s*$/, '')}\nCLAUDE_CODE_OAUTH_TOKEN=${token}\n`;
}
return next;
}
function updateEnvTokens(): void {
/**
* Adopt a refreshed access token: in memory, in process.env and in .env.
* Skipped when the service passes no OAuth token to agents (credentials-file
* only setups), matching the previous behaviour.
*/
function applyRefreshedAccessToken(accessToken: string): void {
if (!getConfiguredClaudeToken()) return;
setCurrentClaudeToken(accessToken);
process.env.CLAUDE_CODE_OAUTH_TOKEN = accessToken;
updateEnvToken(accessToken);
}
function updateEnvToken(token: string): void {
const envFile = path.join(process.cwd(), '.env');
try {
if (!fs.existsSync(envFile)) return;
const content = fs.readFileSync(envFile, 'utf-8');
const allTokens = getAllTokens();
if (allTokens.length === 0) return;
const nextContent = applyUpdatedTokensToEnvContent(
content,
allTokens.map((t) => t.token),
);
const nextContent = applyUpdatedTokenToEnvContent(content, token);
const tempPath = `${envFile}.tmp`;
fs.writeFileSync(tempPath, nextContent, { mode: 0o600 });
@@ -530,28 +507,26 @@ function serializeRefresh<T>(fn: () => Promise<T>): Promise<T> {
}
/**
* Check and refresh a single account's credentials.
* Check and refresh the credentials.
* Returns the (new or adopted) access token if it changed, null otherwise.
*/
async function checkAndRefreshAccount(
accountIndex: number,
opts?: { force?: boolean },
): Promise<string | null> {
return serializeRefresh(() => doCheckAndRefreshAccount(accountIndex, opts));
async function checkAndRefreshCredentials(opts?: {
force?: boolean;
}): Promise<string | null> {
return serializeRefresh(() => doCheckAndRefreshCredentials(opts));
}
async function doCheckAndRefreshAccount(
accountIndex: number,
opts?: { force?: boolean },
): Promise<string | null> {
const freshest = loadFreshestCredentials(accountIndex);
async function doCheckAndRefreshCredentials(opts?: {
force?: boolean;
}): Promise<string | null> {
const freshest = loadFreshestCredentials();
if (!freshest?.creds.claudeAiOauth) return null;
const creds = freshest.creds;
const oauth = creds.claudeAiOauth;
const rt = oauth.refreshToken;
if (!rt) {
logger.debug({ accountIndex }, 'No refresh token in credentials, skipping');
logger.debug('No refresh token in credentials, skipping');
return null;
}
@@ -559,10 +534,9 @@ async function doCheckAndRefreshAccount(
// the family in its session copy. Converge the source file onto that newer
// token so we never re-POST a superseded refresh token.
if (freshest.adoptedFromSession) {
writeCredentials(accountIndex, creds);
writeCredentials(creds);
logger.info(
{
accountIndex,
remainingMin: Math.round((oauth.expiresAt - Date.now()) / 60000),
},
'Adopted newer Claude token from a concurrent refresher (skipped duplicate refresh)',
@@ -575,10 +549,10 @@ async function doCheckAndRefreshAccount(
if (remaining > REFRESH_BEFORE_EXPIRY_MS) {
// A valid token is present again (typically after a manual re-login rewrote
// the credentials file) — drop any prior "re-login required" state.
recordAuthSuccess(accountIndex);
recordAuthSuccess();
if (!opts?.force && !freshest.adoptedFromSession) {
logger.debug(
{ accountIndex, remainingMin: Math.round(remaining / 60000) },
{ remainingMin: Math.round(remaining / 60000) },
'Token still valid, no refresh needed',
);
}
@@ -592,9 +566,8 @@ async function doCheckAndRefreshAccount(
// Already gave up on this account (refresh token dead). Stop hammering the
// endpoint every 5 min — a manual re-login is required, which the
// healthy-token branch above will detect and clear automatically.
if (isReloginRequired(accountIndex)) {
if (isReloginRequired()) {
logger.debug(
{ accountIndex },
'Skipping refresh — re-login required until a manual re-login is performed',
);
return null;
@@ -603,7 +576,6 @@ async function doCheckAndRefreshAccount(
const isExpired = remaining <= 0;
logger.info(
{
accountIndex,
remainingMin: Math.round(remaining / 60000),
isExpired,
force: opts?.force === true,
@@ -614,7 +586,7 @@ async function doCheckAndRefreshAccount(
try {
const response = await refreshToken(rt, oauth.scopes || DEFAULT_SCOPES);
recordAuthSuccess(accountIndex);
recordAuthSuccess();
oauth.accessToken = response.access_token;
oauth.refreshToken = response.refresh_token || rt;
oauth.expiresAt = Date.now() + response.expires_in * 1000;
@@ -623,11 +595,11 @@ async function doCheckAndRefreshAccount(
oauth.scopes = response.scope.split(' ');
}
writeCredentials(accountIndex, creds);
writeCredentials(creds);
const newExpiryMin = Math.round(response.expires_in / 60);
logger.info(
{ accountIndex, expiresInMin: newExpiryMin },
{ expiresInMin: newExpiryMin },
'Claude OAuth token refreshed successfully',
);
@@ -636,19 +608,18 @@ async function doCheckAndRefreshAccount(
// We may simply have lost the rotation race: another process refreshed the
// family a moment ago, so our token is now "expired". Re-scan every copy —
// if a valid token exists, adopt it instead of reporting a hard failure.
const recovered = loadFreshestCredentials(accountIndex);
const recovered = loadFreshestCredentials();
const recoveredOauth = recovered?.creds.claudeAiOauth;
if (
recoveredOauth &&
recoveredOauth.expiresAt - Date.now() > REFRESH_BEFORE_EXPIRY_MS
) {
if (recovered.adoptedFromSession) {
writeCredentials(accountIndex, recovered.creds);
writeCredentials(recovered.creds);
}
recordAuthSuccess(accountIndex);
recordAuthSuccess();
logger.warn(
{
accountIndex,
remainingMin: Math.round(
(recoveredOauth.expiresAt - Date.now()) / 60000,
),
@@ -657,10 +628,9 @@ async function doCheckAndRefreshAccount(
);
return recoveredOauth.accessToken;
}
const gaveUp = recordAuthFailure(accountIndex);
const gaveUp = recordAuthFailure();
logger.error(
{
accountIndex,
gaveUp,
err: getErrorMessage(err),
},
@@ -672,35 +642,10 @@ async function doCheckAndRefreshAccount(
}
}
/**
* Check and refresh all accounts, updating token rotation and .env.
*/
async function checkAndRefreshAll(): Promise<void> {
const allTokens = getAllTokens();
const accountCount = Math.max(allTokens.length, 1);
let anyRefreshed = false;
for (let i = 0; i < accountCount; i++) {
const newAccessToken = await checkAndRefreshAccount(i);
if (newAccessToken && i < allTokens.length) {
updateTokenValue(i, newAccessToken);
anyRefreshed = true;
}
}
if (anyRefreshed) {
// Sync refreshed tokens to process.env so subsequent turns pick them up
const refreshedTokens = getAllTokens();
if (refreshedTokens.length > 0) {
process.env.CLAUDE_CODE_OAUTH_TOKEN = refreshedTokens[0].token;
if (refreshedTokens.length > 1) {
process.env.CLAUDE_CODE_OAUTH_TOKENS = refreshedTokens
.map((t) => t.token)
.join(',');
}
}
updateEnvTokens();
}
/** Periodic check: refresh when needed and adopt the new token. */
async function checkAndRefresh(): Promise<void> {
const newAccessToken = await checkAndRefreshCredentials();
if (newAccessToken) applyRefreshedAccessToken(newAccessToken);
}
let refreshInterval: ReturnType<typeof setInterval> | null = null;
@@ -723,36 +668,23 @@ export function startTokenRefreshLoop(): void {
return;
}
const allTokens = getAllTokens();
// Check if any credentials files exist (for any configured account)
const accountCount = Math.max(allTokens.length, 1);
let hasAnyCreds = false;
for (let i = 0; i < accountCount; i++) {
const creds = readCredentials(i);
if (creds?.claudeAiOauth) {
hasAnyCreds = true;
break;
}
}
if (!hasAnyCreds) {
if (!readCredentials()?.claudeAiOauth) {
logger.info('No OAuth credentials found, token refresh disabled');
return;
}
logger.info(
{ checkIntervalMin: CHECK_INTERVAL_MS / 60000, accountCount },
{ checkIntervalMin: CHECK_INTERVAL_MS / 60000 },
'Token auto-refresh started',
);
// Check immediately on startup
checkAndRefreshAll().catch((err) =>
checkAndRefresh().catch((err) =>
logger.error({ err }, 'Initial token refresh check failed'),
);
refreshInterval = setInterval(() => {
checkAndRefreshAll().catch((err) =>
checkAndRefresh().catch((err) =>
logger.error({ err }, 'Token refresh check failed'),
);
}, CHECK_INTERVAL_MS);
@@ -766,24 +698,14 @@ export function stopTokenRefreshLoop(): void {
}
/**
* Force an immediate token refresh for a specific account index.
* Force an immediate token refresh.
* Useful when a 401 is detected — attempt refresh before giving up.
* Returns the new access token if refresh succeeded, null otherwise.
*/
export async function forceRefreshToken(
tokenIndex: number,
): Promise<string | null> {
logger.info({ tokenIndex }, 'Force-refreshing token after 401');
export async function forceRefreshToken(): Promise<string | null> {
logger.info('Force-refreshing token after 401');
const newAccessToken = await checkAndRefreshAccount(tokenIndex, {
force: true,
});
if (newAccessToken) {
const allTokens = getAllTokens();
if (tokenIndex < allTokens.length) {
updateTokenValue(tokenIndex, newAccessToken);
updateEnvTokens();
}
}
const newAccessToken = await checkAndRefreshCredentials({ force: true });
if (newAccessToken) applyRefreshedAccessToken(newAccessToken);
return newAccessToken;
}