From a9eab5cb942dbd52ca2fafbaccc85f0d562344fc Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 1 Oct 2026 20:00:46 +0900 Subject: [PATCH] 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/), 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 --- .claude/skills/setup/SKILL.md | 1 - .env.example | 3 +- CHANGELOG.md | 1 + README.md | 3 +- codex_relogin.sh | 20 +- docs/configuration.md | 11 +- src/agent-attempt-orchestration.ts | 298 +++--- src/agent-attempt-retry.test.ts | 29 - src/agent-attempt-retry.ts | 88 +- src/agent-error-detection.test.ts | 10 - src/agent-error-detection.ts | 76 +- src/agent-runner-environment.test.ts | 130 +-- src/agent-runner-environment.ts | 82 +- src/agent-runner.test.ts | 2 - src/agent-runner.ts | 12 +- src/claude-credentials-path.ts | 28 +- src/claude-oauth-token.test.ts | 30 + src/claude-oauth-token.ts | 36 + src/claude-usage-backoff.test.ts | 48 +- src/claude-usage.test.ts | 25 +- src/claude-usage.ts | 298 ++---- src/codex-auth.test.ts | 243 +++++ src/codex-auth.ts | 342 ++++++ src/codex-token-rotation.test.ts | 523 --------- src/codex-token-rotation.ts | 999 ------------------ src/codex-usage-collector.test.ts | 28 +- src/codex-usage-collector.ts | 158 +-- src/codex-warmup.test.ts | 489 +++------ src/codex-warmup.ts | 175 ++- src/dashboard-usage-rows.test.ts | 175 +-- src/dashboard-usage-rows.ts | 74 +- src/data-state-files.ts | 2 + src/index.ts | 10 +- src/message-agent-compact-refresh.test.ts | 4 - ...sage-agent-executor-attempt-runner.test.ts | 4 - src/message-agent-executor-attempt-runner.ts | 11 +- src/message-agent-executor-lifecycle.ts | 104 +- src/message-agent-executor-rules.test.ts | 84 +- src/message-agent-executor-rules.ts | 3 - src/message-agent-executor-target.ts | 4 +- src/message-agent-executor.test.ts | 396 +------ src/message-agent-executor.ts | 2 +- src/provider-retry.test.ts | 284 ----- src/provider-retry.ts | 418 -------- src/silent-owner-retry.test.ts | 8 +- src/streamed-output-evaluator.test.ts | 39 +- src/streamed-output-evaluator.ts | 14 +- src/task-scheduler.test.ts | 308 ++---- src/task-scheduler.ts | 114 +- src/token-refresh.test.ts | 29 +- src/token-refresh.ts | 292 ++--- src/token-rotation-base.ts | 71 -- src/token-rotation.test.ts | 116 -- src/token-rotation.ts | 317 ------ src/unified-dashboard.test.ts | 57 +- src/unified-dashboard.ts | 47 +- src/usage-primer.test.ts | 23 +- src/usage-primer.ts | 40 +- 58 files changed, 1691 insertions(+), 5547 deletions(-) delete mode 100644 src/agent-attempt-retry.test.ts create mode 100644 src/claude-oauth-token.test.ts create mode 100644 src/claude-oauth-token.ts create mode 100644 src/codex-auth.test.ts create mode 100644 src/codex-auth.ts delete mode 100644 src/codex-token-rotation.test.ts delete mode 100644 src/codex-token-rotation.ts delete mode 100644 src/provider-retry.test.ts delete mode 100644 src/provider-retry.ts delete mode 100644 src/token-rotation-base.ts delete mode 100644 src/token-rotation.test.ts delete mode 100644 src/token-rotation.ts diff --git a/.claude/skills/setup/SKILL.md b/.claude/skills/setup/SKILL.md index d1004e9..ed6a933 100644 --- a/.claude/skills/setup/SKILL.md +++ b/.claude/skills/setup/SKILL.md @@ -51,7 +51,6 @@ ASSISTANT_NAME=claude # 트리거 이름 (@claude) 권장: ```bash -CLAUDE_CODE_OAUTH_TOKENS=token1,token2 # 다중 계정 자동 로테이션 GROQ_API_KEY=... # Discord 음성 전사 (Groq Whisper) ``` diff --git a/.env.example b/.env.example index 12a3d14..cea8b9d 100644 --- a/.env.example +++ b/.env.example @@ -16,8 +16,7 @@ REVIEWER_AGENT_TYPE=claude-code # claude-code | codex # ARBITER_AGENT_TYPE=codex # optional: codex | claude-code # --- API keys --- -CLAUDE_CODE_OAUTH_TOKENS= # Canonical comma-separated Claude Code OAuth tokens (use one value for single-account too) -CLAUDE_CODE_OAUTH_TOKEN= # Legacy single-token fallback +CLAUDE_CODE_OAUTH_TOKEN= # Claude Code OAuth token (single account) GROQ_API_KEY= # Voice transcription (Groq Whisper, free: console.groq.com) # --- Bot identity --- diff --git a/CHANGELOG.md b/CHANGELOG.md index e7fc692..5ad0432 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ - `/compact`·`/clear`·`/stop` 세션 명령(main 방·관리자 전용이라 실제로 쓰이지 않음)과 `SESSION_COMMAND_ALLOWED_SENDERS` 설정, agent-runner의 `/compact` 처리. `.env`에 남아 있는 `SESSION_COMMAND_*` 값은 더 이상 시작을 막지 않고 무시됨 - main(관리) 방 개념과 그것이 열어 주던 방 간 기능. 모든 방의 `is_main`이 0이라 실제로 쓰이지 않았음. 이제 각 방의 에이전트는 자기 방만 다룸: 다른 방 예약 작업 생성/수정/일시정지/취소(`target_group_jid`), 다른 방으로 메시지 전송·inbound 주입, 전체 방 범위의 DB 증거 조회, IPC `assign_room`/`refresh_groups`와 에이전트용 `assign_room` 도구, `available_groups.json` 스냅샷, main 방 전용 global memory 제외, `EJCLAW_IS_MAIN` 환경 변수, main 방으로 보내던 추론 재시작 알림, `setup --step register`의 `--is-main`, `scripts/deregister-room.ts`의 main 방 보호(`--force`), `groups/main/` 템플릿 제거. `room_settings.is_main` 컬럼은 스키마에 남아 있으나 더 이상 읽거나 쓰지 않음 - 기본 비활성이던 주기적 Codex warm-up 루프와 `CODEX_WARMUP_ENABLED`/`CODEX_WARMUP_INTERVAL_MS`. 고정 슬롯 usage primer는 그대로 동작 +- 다중 계정 로테이션. Claude·Codex 모두 계정 1개 고정으로 동작: 한도·인증 오류 시 다음 계정으로 넘어가기, 계정별 쿨다운·상태 파일(`token-rotation-state.json`, `codex-rotation-state.json`), Codex 1시간 전체 계정 사용량 스캔, `CLAUDE_ACCOUNTS_DIR`(`~/.claude-accounts/`) 제거. Codex는 `~/.codex-accounts/0/auth.json`(없으면 `~/.codex/auth.json`)을 매 실행마다 확인하므로 재로그인 후 재시작이 필요 없음. 계정 잠금(동시 실행 1개, 최대 15분 대기)과 세션 토큰 write-back, Claude 토큰 자동 갱신(만료 시 1회 강제 갱신 후 재시도)은 유지. `CLAUDE_CODE_OAUTH_TOKENS`는 첫 번째 값만 사용 ### Fixed diff --git a/README.md b/README.md index d978d91..f05db3c 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,6 @@ EJClaw는 Discord 위에서 동작하는 Tribunal 멀티에이전트 개발 보 - reviewer host runtime + read-only guard - 승인 후 변경 감지와 재리뷰 - Claude 장애 시 Codex로 넘기는 global failover -- Claude OAuth 멀티 토큰 로테이션 - `room_settings` 기반 명시적 room assignment - 자연어 중단: 작업 중인 방에 "그만", "멈춰", "중단해", "취소", "stop" 같은 짧은 메시지만 보내면 실행 중인 에이전트를 끝내고 열린 paired task를 닫음 - Bun + SQLite 기반 빠른 런타임 @@ -155,7 +154,7 @@ bun run build:all DISCORD_OWNER_BOT_TOKEN= DISCORD_REVIEWER_BOT_TOKEN= DISCORD_ARBITER_BOT_TOKEN= -CLAUDE_CODE_OAUTH_TOKENS= +CLAUDE_CODE_OAUTH_TOKEN= OWNER_AGENT_TYPE=codex REVIEWER_AGENT_TYPE=claude-code ``` diff --git a/codex_relogin.sh b/codex_relogin.sh index e08ed12..ba37a21 100755 --- a/codex_relogin.sh +++ b/codex_relogin.sh @@ -3,12 +3,11 @@ # codex_relogin.sh — Codex(ChatGPT) 계정을 device-code OAuth 로 재로그인한다. # # 사용법: -# ./codex_relogin.sh # 기본 슬롯(0) 재로그인 -# ./codex_relogin.sh 1 # ~/.codex-accounts/1 슬롯 재로그인 +# ./codex_relogin.sh # # 참고: # * Codex 로그인은 이 호스트에서 두 봇(EJClaw / KAClaw)이 "공유"한다. -# 계정 저장 위치가 폴더별이 아니라 ~/.codex-accounts/{n} 이기 때문. +# 계정 저장 위치가 폴더별이 아니라 ~/.codex-accounts/0 이기 때문. # → 한 번만 재로그인하면 두 봇 모두에 반영된다. # * codex CLI 가 URL + 일회용 코드를 출력한다(15분 유효). 브라우저에서 # 로그인/코드입력을 마치면 codex 가 auth.json 을 자동 저장한다. @@ -31,18 +30,11 @@ if [ -z "$CODEX" ]; then exit 1 fi -# --- 대상 슬롯 결정 -------------------------------------------------------- -# 앱은 ~/.codex-accounts/{n}/auth.json 를 읽는다. 없으면 ~/.codex 로 폴백. -SLOT="${1:-0}" -ACCOUNTS_DIR="$HOME/.codex-accounts" -if [ -d "$ACCOUNTS_DIR/$SLOT" ]; then - CODEX_TARGET="$ACCOUNTS_DIR/$SLOT" -elif [ -d "$ACCOUNTS_DIR" ] && ls -d "$ACCOUNTS_DIR"/[0-9]* >/dev/null 2>&1; then - echo "❌ 슬롯 '$SLOT' 이(가) 없습니다. 사용 가능한 슬롯:" >&2 - ls -d "$ACCOUNTS_DIR"/[0-9]* 2>/dev/null | sed 's#.*/# - #' >&2 - exit 1 +# --- 대상 위치 결정 -------------------------------------------------------- +# 앱은 ~/.codex-accounts/0/auth.json 를 읽는다. 없으면 ~/.codex 로 폴백. +if [ -d "$HOME/.codex-accounts/0" ]; then + CODEX_TARGET="$HOME/.codex-accounts/0" else - # accounts 디렉터리가 비어있으면 기본 codex home 사용 CODEX_TARGET="$HOME/.codex" fi export CODEX_HOME="$CODEX_TARGET" diff --git a/docs/configuration.md b/docs/configuration.md index 2b36343..0bef733 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -9,7 +9,7 @@ EJClaw의 설정 기준은 `.env` 하나입니다. - reviewer 기본 provider는 `claude-code` - owner 기본 provider는 `codex` - room-level override는 provider 단위(`claudeModel`, `codexModel`)만 지원합니다 -- `CLAUDE_CODE_OAUTH_TOKENS`가 canonical이고, `CLAUDE_CODE_OAUTH_TOKEN`은 legacy fallback입니다 +- Claude와 Codex는 각각 계정 1개로 동작합니다 (계정 로테이션 없음) ## Discord 봇 @@ -64,8 +64,8 @@ ARBITER_FALLBACK_ENABLED=true ```bash # Claude Code OAuth -CLAUDE_CODE_OAUTH_TOKENS= CLAUDE_CODE_OAUTH_TOKEN= +CLAUDE_CREDENTIALS_PATH= # Claude host env (선택) ANTHROPIC_API_KEY= @@ -75,11 +75,10 @@ ANTHROPIC_BASE_URL= 설명: -- `CLAUDE_CODE_OAUTH_TOKENS`: canonical, 쉼표 구분 -- `CLAUDE_CODE_OAUTH_TOKEN`: 단일 토큰 legacy fallback -- 실제 runner에는 현재 선택된 Claude 토큰 하나만 주입됩니다 +- `CLAUDE_CODE_OAUTH_TOKEN`: runner에 주입하는 Claude 토큰. 예전 `CLAUDE_CODE_OAUTH_TOKENS`(쉼표 구분)가 남아 있으면 첫 번째 값만 씁니다 +- `CLAUDE_CREDENTIALS_PATH`: 이 서비스의 Claude OAuth credentials 파일. `CLAUDE_TOKEN_REFRESH_USE_CREDENTIALS=true`면 만료 전에 자동 갱신하고 새 토큰을 `.env`에도 기록합니다 -Codex 쪽은 현재 **OAuth 세션 파일** 기준으로 동작합니다. `OPENAI_API_KEY`를 Codex child process에 넘겨서 빌링하는 구조는 사용하지 않습니다. +Codex 쪽은 **OAuth 세션 파일** 기준으로 동작합니다. `~/.codex-accounts/0/auth.json`을 쓰고, 없으면 `~/.codex/auth.json`을 씁니다. Codex 실행은 계정 잠금으로 한 번에 하나만 돌고, 잠겨 있으면 최대 15분 기다립니다. `OPENAI_API_KEY`를 Codex child process에 넘겨서 빌링하는 구조는 사용하지 않습니다. ## 음성 전사 diff --git a/src/agent-attempt-orchestration.ts b/src/agent-attempt-orchestration.ts index acf56b6..d5ac4ab 100644 --- a/src/agent-attempt-orchestration.ts +++ b/src/agent-attempt-orchestration.ts @@ -1,19 +1,23 @@ import type { AgentOutput } from './agent-runner.js'; import { - resolveAttemptRetryAction, - type AttemptRetryAction, + resolveClaudeRetryTrigger, type AttemptRetryState, } from './agent-attempt-retry.js'; -import type { - AgentTriggerReason, - CodexRotationReason, -} from './agent-error-detection.js'; import { - runClaudeRotationLoop, - runCodexRotationLoop, -} from './provider-retry.js'; + classifyClaudeTrigger, + type AgentTriggerReason, +} from './agent-error-detection.js'; +import { logger } from './logger.js'; +import { clearGlobalFailover } from './service-routing.js'; +import { forceRefreshToken } from './token-refresh.js'; +import { getErrorMessage } from './utils.js'; -type RotationLogContext = Record; +type LogContext = Record; + +export interface ClaudeTrigger { + reason: AgentTriggerReason; + retryAfterMs?: number; +} type ClaudeRetryAttemptState = Pick< AttemptRetryState, @@ -24,159 +28,169 @@ type ClaudeRetryAttemptState = Pick< sawSuccessNullResultWithoutOutput?: boolean; }; -type CodexRetryAttemptState = Pick< - AttemptRetryState, - 'sawOutput' | 'streamedTriggerReason' -> & { - output?: Pick; - error?: unknown; -}; +type AttemptOutcome = + | { type: 'success'; sawOutput: boolean } + | { type: 'error'; trigger?: ClaudeTrigger }; -export type ExecutedAttemptRetryAction = - | { kind: 'none' } - | { - kind: 'claude'; - trigger: { reason: AgentTriggerReason; retryAfterMs?: number }; - rotationMessage?: string; - result: 'success' | 'error'; - } - | { - kind: 'codex'; - trigger: { reason: CodexRotationReason }; - rotationMessage?: string; - result: 'success' | 'error'; +function retryTriggerFromAttempt( + attempt: ClaudeRetryAttemptState, + errorText: string | null | undefined, +): ClaudeTrigger | null { + if (attempt.sawOutput) return null; + if (attempt.streamedTriggerReason) { + return { + reason: attempt.streamedTriggerReason.reason, + retryAfterMs: attempt.streamedTriggerReason.retryAfterMs, }; + } + const trigger = classifyClaudeTrigger(errorText); + return trigger.shouldRetry + ? { reason: trigger.reason, retryAfterMs: trigger.retryAfterMs } + : null; +} -export async function runClaudeAttemptWithRotation< +/** Judge the attempt made after a forced token refresh. */ +function evaluateRetriedClaudeAttempt( + attempt: ClaudeRetryAttemptState, + logContext: LogContext, +): AttemptOutcome { + if (attempt.error) { + const trigger = retryTriggerFromAttempt( + attempt, + getErrorMessage(attempt.error), + ); + logger.error( + { ...logContext, provider: 'claude', err: attempt.error }, + 'Claude retry after token refresh threw', + ); + return { type: 'error', ...(trigger ? { trigger } : {}) }; + } + + const output = attempt.output; + if (!output) { + logger.error( + { ...logContext, provider: 'claude' }, + 'Claude retry after token refresh produced no output object', + ); + return { type: 'error' }; + } + + if ( + !attempt.sawOutput && + attempt.streamedTriggerReason && + output.status !== 'error' + ) { + return { + type: 'error', + trigger: { + reason: attempt.streamedTriggerReason.reason, + retryAfterMs: attempt.streamedTriggerReason.retryAfterMs, + }, + }; + } + + if (!attempt.sawOutput && attempt.sawSuccessNullResultWithoutOutput) { + logger.warn( + { ...logContext, provider: 'claude' }, + 'Claude retry after token refresh returned success with null result', + ); + return { type: 'error', trigger: { reason: 'success-null-result' } }; + } + + if (output.status === 'error') { + const trigger = retryTriggerFromAttempt(attempt, output.error); + logger.error( + { ...logContext, provider: 'claude', error: output.error }, + 'Claude retry after token refresh failed', + ); + return { type: 'error', ...(trigger ? { trigger } : {}) }; + } + + clearGlobalFailover(); + return { type: 'success', sawOutput: attempt.sawOutput }; +} + +/** + * Recover a Claude attempt that failed before visible output. + * + * Only an expired OAuth token is recoverable: force-refresh it and run the + * attempt once more. Every other trigger (usage limit, 429, org access + * denied, ...) is returned as an error so the caller can report it. + */ +export async function runClaudeAttemptWithAuthRefresh< TAttempt extends ClaudeRetryAttemptState, >(args: { - initialTrigger: { - reason: AgentTriggerReason; - retryAfterMs?: number; - }; + initialTrigger: ClaudeTrigger; runAttempt: () => Promise; - logContext: RotationLogContext; - rotationMessage?: string; + logContext: LogContext; afterAttempt?: (attempt: TAttempt) => Promise | void; onSuccess?: (outcome: { sawOutput: boolean }) => Promise | void; }): Promise<'success' | 'error'> { - const outcome = await runClaudeRotationLoop( - args.initialTrigger, - async () => { + const { initialTrigger, logContext } = args; + if (initialTrigger.reason === 'auth-expired') { + const refreshedToken = await forceRefreshToken(); + if (refreshedToken) { + logger.info( + logContext, + 'Claude auth-expired: force-refreshed the token, retrying once', + ); const attempt = await args.runAttempt(); await args.afterAttempt?.(attempt); - return { - output: attempt.output, - thrownError: attempt.error, - sawOutput: attempt.sawOutput, - sawSuccessNullResult: attempt.sawSuccessNullResultWithoutOutput, - streamedTriggerReason: attempt.streamedTriggerReason, - }; - }, - args.logContext, - args.rotationMessage, - ); - - if (outcome.type === 'success') { - await args.onSuccess?.({ sawOutput: outcome.sawOutput }); - return 'success'; + const outcome = evaluateRetriedClaudeAttempt(attempt, logContext); + if (outcome.type === 'success') { + await args.onSuccess?.({ sawOutput: outcome.sawOutput }); + return 'success'; + } + logger.warn( + { ...logContext, reason: outcome.trigger?.reason ?? null }, + 'Claude retry after token refresh did not recover', + ); + return 'error'; + } } + logger.warn( + { ...logContext, reason: initialTrigger.reason }, + `Claude unavailable (${initialTrigger.reason})`, + ); return 'error'; } -export async function runCodexAttemptWithRotation< - TAttempt extends CodexRetryAttemptState, ->(args: { - initialTrigger: { reason: CodexRotationReason }; - runAttempt: () => Promise; - logContext: RotationLogContext; - rotationMessage?: string; - afterAttempt?: (attempt: TAttempt) => Promise | void; -}): Promise<'success' | 'error'> { - const outcome = await runCodexRotationLoop( - args.initialTrigger, - async () => { - const attempt = await args.runAttempt(); - await args.afterAttempt?.(attempt); - return { - output: attempt.output, - thrownError: attempt.error, - sawOutput: attempt.sawOutput, - streamedTriggerReason: attempt.streamedTriggerReason, - }; - }, - args.logContext, - args.rotationMessage, - ); +export type ExecutedClaudeRetry = + | { kind: 'none' } + | { + kind: 'claude'; + trigger: ClaudeTrigger; + errorMessage?: string; + result: 'success' | 'error'; + }; - return outcome.type === 'success' ? 'success' : 'error'; -} - -export async function executeAttemptRetryAction(args: { +/** + * When a Claude attempt failed with a recognised trigger before any visible + * output, run the recovery path (runClaude) and report what happened. + */ +export async function retryClaudeAttemptOnTrigger(args: { provider: 'claude' | 'codex'; canRetryClaudeCredentials: boolean; - canRetryCodex: boolean; attempt: Pick; - rotationMessage?: string | null; - runClaude: ( - trigger: { reason: AgentTriggerReason; retryAfterMs?: number }, - rotationMessage?: string, - ) => Promise<'success' | 'error'>; - runCodex: ( - trigger: { reason: CodexRotationReason }, - rotationMessage?: string, - ) => Promise<'success' | 'error'>; -}): Promise { - const retryAction = resolveAttemptRetryAction({ - provider: args.provider, + errorMessage?: string | null; + runClaude: (trigger: ClaudeTrigger) => Promise<'success' | 'error'>; +}): Promise { + const errorMessage = + args.errorMessage ?? + args.attempt.streamedTriggerReason?.message ?? + undefined; + const trigger = resolveClaudeRetryTrigger({ canRetryClaudeCredentials: args.canRetryClaudeCredentials, - canRetryCodex: args.canRetryCodex, + provider: args.provider, attempt: args.attempt, - rotationMessage: args.rotationMessage, - }); - - return executeResolvedAttemptRetryAction({ - retryAction, - runClaude: args.runClaude, - runCodex: args.runCodex, + fallbackMessage: errorMessage, }); -} - -async function executeResolvedAttemptRetryAction(args: { - retryAction: AttemptRetryAction; - runClaude: ( - trigger: { reason: AgentTriggerReason; retryAfterMs?: number }, - rotationMessage?: string, - ) => Promise<'success' | 'error'>; - runCodex: ( - trigger: { reason: CodexRotationReason }, - rotationMessage?: string, - ) => Promise<'success' | 'error'>; -}): Promise { - if (args.retryAction.kind === 'claude') { - return { - kind: 'claude', - trigger: args.retryAction.trigger, - rotationMessage: args.retryAction.rotationMessage, - result: await args.runClaude( - args.retryAction.trigger, - args.retryAction.rotationMessage, - ), - }; - } - - if (args.retryAction.kind === 'codex') { - return { - kind: 'codex', - trigger: args.retryAction.trigger, - rotationMessage: args.retryAction.rotationMessage, - result: await args.runCodex( - args.retryAction.trigger, - args.retryAction.rotationMessage, - ), - }; - } - - return { kind: 'none' }; + if (!trigger) return { kind: 'none' }; + return { + kind: 'claude', + trigger, + errorMessage, + result: await args.runClaude(trigger), + }; } diff --git a/src/agent-attempt-retry.test.ts b/src/agent-attempt-retry.test.ts deleted file mode 100644 index 816d05e..0000000 --- a/src/agent-attempt-retry.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { resolveAttemptRetryAction } from './agent-attempt-retry.js'; - -describe('resolveAttemptRetryAction', () => { - it('uses the streamed Codex trigger message as the rotation message', () => { - const errorMessage = - 'unexpected status 401 Unauthorized: Missing bearer or basic authentication in header'; - - const action = resolveAttemptRetryAction({ - provider: 'codex', - canRetryClaudeCredentials: false, - canRetryCodex: true, - attempt: { - sawOutput: false, - streamedTriggerReason: { - reason: 'auth-expired', - message: errorMessage, - } as any, - }, - }); - - expect(action).toEqual({ - kind: 'codex', - trigger: { reason: 'auth-expired' }, - rotationMessage: errorMessage, - }); - }); -}); diff --git a/src/agent-attempt-retry.ts b/src/agent-attempt-retry.ts index bafca9c..2e54672 100644 --- a/src/agent-attempt-retry.ts +++ b/src/agent-attempt-retry.ts @@ -1,10 +1,7 @@ import { - classifyRotationTrigger, + classifyClaudeTrigger, type AgentTriggerReason, - type CodexRotationReason, - isCodexRotationReason, } from './agent-error-detection.js'; -import { detectCodexRotationTrigger } from './codex-token-rotation.js'; import { getErrorMessage } from './utils.js'; export interface AttemptStreamedTrigger { @@ -75,7 +72,7 @@ export function resolveClaudeRetryTrigger(args: { }; } - const trigger = classifyRotationTrigger(args.fallbackMessage); + const trigger = classifyClaudeTrigger(args.fallbackMessage); if (!trigger.shouldRetry) { return null; } @@ -85,84 +82,3 @@ export function resolveClaudeRetryTrigger(args: { retryAfterMs: trigger.retryAfterMs, }; } - -export function resolveCodexRetryTrigger(args: { - canRetryCodex: boolean; - attempt: Pick; - rotationMessage?: string | null; -}): { reason: CodexRotationReason } | null { - if (!args.canRetryCodex) { - return null; - } - - if (args.attempt.streamedTriggerReason) { - if (!isCodexRotationReason(args.attempt.streamedTriggerReason.reason)) { - return null; - } - return { - reason: args.attempt.streamedTriggerReason.reason, - }; - } - - const trigger = detectCodexRotationTrigger(args.rotationMessage); - if (!trigger.shouldRotate) { - return null; - } - - return { reason: trigger.reason }; -} - -export type AttemptRetryAction = - | { - kind: 'claude'; - trigger: { reason: AgentTriggerReason; retryAfterMs?: number }; - rotationMessage?: string; - } - | { - kind: 'codex'; - trigger: { reason: CodexRotationReason }; - rotationMessage?: string; - } - | { kind: 'none' }; - -export function resolveAttemptRetryAction(args: { - provider: 'claude' | 'codex'; - canRetryClaudeCredentials: boolean; - canRetryCodex: boolean; - attempt: Pick; - rotationMessage?: string | null; -}): AttemptRetryAction { - const normalizedRotationMessage = - args.rotationMessage ?? - args.attempt.streamedTriggerReason?.message ?? - undefined; - - const claudeTrigger = resolveClaudeRetryTrigger({ - canRetryClaudeCredentials: args.canRetryClaudeCredentials, - provider: args.provider, - attempt: args.attempt, - fallbackMessage: normalizedRotationMessage, - }); - if (claudeTrigger) { - return { - kind: 'claude', - trigger: claudeTrigger, - rotationMessage: normalizedRotationMessage, - }; - } - - const codexTrigger = resolveCodexRetryTrigger({ - canRetryCodex: args.canRetryCodex, - attempt: args.attempt, - rotationMessage: normalizedRotationMessage, - }); - if (codexTrigger) { - return { - kind: 'codex', - trigger: codexTrigger, - rotationMessage: normalizedRotationMessage, - }; - } - - return { kind: 'none' }; -} diff --git a/src/agent-error-detection.test.ts b/src/agent-error-detection.test.ts index 53a3e2c..e85d31a 100644 --- a/src/agent-error-detection.test.ts +++ b/src/agent-error-detection.test.ts @@ -6,7 +6,6 @@ import { classifyCodexAuthError, detectClaudeProviderFailureMessage, isClaudeOrgAccessDeniedMessage, - shouldRotateClaudeToken, } from './agent-error-detection.js'; describe('agent-error-detection', () => { @@ -105,13 +104,4 @@ describe('agent-error-detection', () => { retryAfterMs: undefined, }); }); - - it('marks only Claude quota/auth reasons as Claude rotation reasons', () => { - expect(shouldRotateClaudeToken('429')).toBe(true); - expect(shouldRotateClaudeToken('usage-exhausted')).toBe(true); - expect(shouldRotateClaudeToken('auth-expired')).toBe(true); - expect(shouldRotateClaudeToken('org-access-denied')).toBe(true); - expect(shouldRotateClaudeToken('overloaded')).toBe(false); - expect(shouldRotateClaudeToken('success-null-result')).toBe(false); - }); }); diff --git a/src/agent-error-detection.ts b/src/agent-error-detection.ts index 60e913f..996e559 100644 --- a/src/agent-error-detection.ts +++ b/src/agent-error-detection.ts @@ -92,7 +92,7 @@ export function isClaudeOrgAccessDeniedMessage(text: string): boolean { return hasOrgAccessDeniedMarker && hasRecoveryHint; } -// ── Rotation decision ─────────────────────────────────────────── +// ── Trigger reasons ───────────────────────────────────────────── export type AgentTriggerReason = | '429' @@ -105,42 +105,14 @@ export type AgentTriggerReason = | 'success-null-result' | 'session-failure'; -export type ClaudeRotationReason = Extract< - AgentTriggerReason, - '429' | 'usage-exhausted' | 'auth-expired' | 'org-access-denied' ->; - -export type CodexRotationReason = Extract< +export type CodexTriggerReason = Extract< AgentTriggerReason, '429' | 'auth-expired' | 'org-access-denied' | 'overloaded' | 'network-error' >; -export function shouldRotateClaudeToken( - reason: AgentTriggerReason, -): reason is ClaudeRotationReason { - return ( - reason === '429' || - reason === 'usage-exhausted' || - reason === 'auth-expired' || - reason === 'org-access-denied' - ); -} +// ── Claude trigger classification ─────────────────────────────── -export function isCodexRotationReason( - reason: AgentTriggerReason, -): reason is CodexRotationReason { - return ( - reason === '429' || - reason === 'auth-expired' || - reason === 'org-access-denied' || - reason === 'overloaded' || - reason === 'network-error' - ); -} - -// ── Rotation trigger classification ───────────────────────────── - -export type RotationTriggerResult = +export type ClaudeTriggerResult = | { shouldRetry: false; reason: '' } | { shouldRetry: true; @@ -149,14 +121,14 @@ export type RotationTriggerResult = }; /** - * Classify an error string to determine if Claude token rotation - * should be attempted. + * Classify a Claude error string into a trigger (rate limit, auth, 5xx, + * network) so the caller can recover or report it. * * Priority: 429 > auth/org errors > 503/network. */ -export function classifyRotationTrigger( +export function classifyClaudeTrigger( error?: string | null, -): RotationTriggerResult { +): ClaudeTriggerResult { if (!error) return { shouldRetry: false, reason: '' }; const common = classifyAgentError(error); @@ -184,6 +156,36 @@ export function classifyRotationTrigger( return { shouldRetry: false, reason: '' }; } +export type CodexTriggerResult = + | { triggered: false; reason: '' } + | { triggered: true; reason: CodexTriggerReason }; + +/** + * Classify a Codex error string (429, 5xx, network, auth). The internal + * account-unavailable sentinel is not a trigger. + */ +export function classifyCodexTrigger( + error?: string | null, +): CodexTriggerResult { + if (!error || isCodexPoolUnavailableError(error)) { + return { triggered: false, reason: '' }; + } + + // Common patterns (429, 503, network) + const common = classifyAgentError(error); + if (common.category !== 'none') { + return { triggered: true, reason: common.reason }; + } + + // Codex-specific loose auth check + const auth = classifyCodexAuthError(error); + if (auth.category !== 'none') { + return { triggered: true, reason: auth.reason }; + } + + return { triggered: false, reason: '' }; +} + // ── Unified error classification ──────────────────────────────── export type AgentErrorClassification = @@ -230,7 +232,7 @@ export function isCodexPoolUnavailableError( return ( /all\s+codex(?:\s+rotation)?\s+accounts(?:\s+are)?\s+unavailable/i.test( error, - ) || /codex\s+rotation\s+pool\s+unavailable/i.test(error) + ) || /codex\s+(?:rotation\s+pool|account)\s+unavailable/i.test(error) ); } diff --git a/src/agent-runner-environment.test.ts b/src/agent-runner-environment.test.ts index 4b447d9..8eec343 100644 --- a/src/agent-runner-environment.test.ts +++ b/src/agent-runner-environment.test.ts @@ -5,25 +5,17 @@ import path from 'path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { EJCLAW_ENV } from 'ejclaw-runners-shared'; -const { - mockReadEnvFile, - mockGetActiveCodexAuthPath, - mockGetCodexAccountCount, - mockClaimCodexAuthLease, - mockFindCodexAccountIndexByAuthPath, -} = vi.hoisted(() => ({ - mockReadEnvFile: vi.fn<() => Record>(), - mockGetActiveCodexAuthPath: vi.fn<() => string | null>(), - mockGetCodexAccountCount: vi.fn<() => number>(), - mockClaimCodexAuthLease: vi.fn< - () => { - authPath: string; - accountIndex: number; - release: () => void; - } | null - >(), - mockFindCodexAccountIndexByAuthPath: vi.fn<() => number | null>(), -})); +const { mockReadEnvFile, mockGetCodexAuthPath, mockClaimCodexAuthLease } = + vi.hoisted(() => ({ + mockReadEnvFile: vi.fn<() => Record>(), + mockGetCodexAuthPath: vi.fn<() => string | null>(), + mockClaimCodexAuthLease: vi.fn< + () => { + authPath: string; + release: () => void; + } | null + >(), + })); vi.mock('./config.js', () => ({ ASSISTANT_NAME: 'Andy', @@ -42,25 +34,16 @@ vi.mock('./env.js', () => ({ getEnv: vi.fn((_key: string) => undefined), })); -vi.mock('./codex-token-rotation.js', () => ({ - getActiveCodexAuthPath: mockGetActiveCodexAuthPath, - getCodexAccountCount: mockGetCodexAccountCount, +vi.mock('./codex-auth.js', () => ({ + getCodexAuthPath: mockGetCodexAuthPath, claimCodexAuthLease: mockClaimCodexAuthLease, - findCodexAccountIndexByAuthPath: mockFindCodexAccountIndexByAuthPath, })); -vi.mock('./token-rotation.js', () => ({ - getCurrentToken: vi.fn(() => undefined), - getConfiguredClaudeTokens: vi.fn( - (options?: { multi?: string | undefined; single?: string | undefined }) => { - if (options?.multi) { - return options.multi - .split(',') - .map((token) => token.trim()) - .filter(Boolean); - } - return options?.single ? [options.single] : []; - }, +vi.mock('./claude-oauth-token.js', () => ({ + getCurrentClaudeToken: vi.fn(() => undefined), + getConfiguredClaudeToken: vi.fn( + (options?: { list?: string | undefined; single?: string | undefined }) => + options?.list?.split(',')[0]?.trim() || options?.single || undefined, ), })); @@ -178,13 +161,10 @@ describe('prepareGroupEnvironment codex auth handling', () => { }); mockReadEnvFile.mockReset(); - mockGetActiveCodexAuthPath.mockReset(); - mockGetCodexAccountCount.mockReset(); - mockGetCodexAccountCount.mockReturnValue(0); + mockGetCodexAuthPath.mockReset(); + mockGetCodexAuthPath.mockReturnValue(null); mockClaimCodexAuthLease.mockReset(); mockClaimCodexAuthLease.mockReturnValue(null); - mockFindCodexAccountIndexByAuthPath.mockReset(); - mockFindCodexAccountIndexByAuthPath.mockReturnValue(null); }); afterEach(() => { @@ -208,7 +188,11 @@ describe('prepareGroupEnvironment codex auth handling', () => { tokens: { access_token: 'x' }, }; fs.writeFileSync(rotatedAuthPath, JSON.stringify(rotatedAuth)); - mockGetActiveCodexAuthPath.mockReturnValue(rotatedAuthPath); + mockGetCodexAuthPath.mockReturnValue(rotatedAuthPath); + mockClaimCodexAuthLease.mockReturnValue({ + authPath: rotatedAuthPath, + release: vi.fn(), + }); mockReadEnvFile.mockReturnValue({ OPENAI_API_KEY: 'sk-test-api-key', CODEX_MODEL: 'gpt-5.4', @@ -247,7 +231,11 @@ describe('prepareGroupEnvironment codex auth handling', () => { }, }; fs.writeFileSync(rotatedAuthPath, JSON.stringify(rotatedAuth)); - mockGetActiveCodexAuthPath.mockReturnValue(rotatedAuthPath); + mockGetCodexAuthPath.mockReturnValue(rotatedAuthPath); + mockClaimCodexAuthLease.mockReturnValue({ + authPath: rotatedAuthPath, + release: vi.fn(), + }); mockReadEnvFile.mockReturnValue({}); prepareGroupEnvironment(group, 'dc:test'); @@ -266,7 +254,7 @@ describe('prepareGroupEnvironment codex auth handling', () => { expect(auth).toEqual(rotatedAuth); }); - it('fails fast instead of launching Codex without OAuth when rotation accounts exist but no lease is available', () => { + it('fails fast instead of launching Codex without OAuth when the account lease is unavailable', () => { const rotatedAuthPath = path.join(tempRoot, 'rotated-auth.json'); fs.writeFileSync( rotatedAuthPath, @@ -275,13 +263,12 @@ describe('prepareGroupEnvironment codex auth handling', () => { tokens: { access_token: 'locked-token' }, }), ); - mockGetCodexAccountCount.mockReturnValue(1); + mockGetCodexAuthPath.mockReturnValue(rotatedAuthPath); mockClaimCodexAuthLease.mockReturnValue(null); - mockGetActiveCodexAuthPath.mockReturnValue(rotatedAuthPath); mockReadEnvFile.mockReturnValue({}); expect(() => prepareGroupEnvironment(group, 'dc:test')).toThrow( - /Codex rotation pool unavailable/, + /Codex account unavailable/, ); const authPath = path.join( @@ -321,13 +308,10 @@ describe('prepareGroupEnvironment prompt stacks', () => { }); mockReadEnvFile.mockReset(); - mockGetActiveCodexAuthPath.mockReset(); - mockGetCodexAccountCount.mockReset(); - mockGetCodexAccountCount.mockReturnValue(0); + mockGetCodexAuthPath.mockReset(); + mockGetCodexAuthPath.mockReturnValue(null); mockClaimCodexAuthLease.mockReset(); mockClaimCodexAuthLease.mockReturnValue(null); - mockFindCodexAccountIndexByAuthPath.mockReset(); - mockFindCodexAccountIndexByAuthPath.mockReturnValue(null); }); afterEach(() => { @@ -543,13 +527,10 @@ describe('prepareGroupEnvironment Codex MCP room role env', () => { fs.mkdirSync(process.env.EJ_TEST_HOME, { recursive: true }); mockReadEnvFile.mockReset(); - mockGetActiveCodexAuthPath.mockReset(); - mockGetCodexAccountCount.mockReset(); - mockGetCodexAccountCount.mockReturnValue(0); + mockGetCodexAuthPath.mockReset(); + mockGetCodexAuthPath.mockReturnValue(null); mockClaimCodexAuthLease.mockReset(); mockClaimCodexAuthLease.mockReturnValue(null); - mockFindCodexAccountIndexByAuthPath.mockReset(); - mockFindCodexAccountIndexByAuthPath.mockReturnValue(null); resetRoutingMocks(); }); @@ -622,13 +603,10 @@ describe('prepareGroupEnvironment room skill overrides', () => { recursive: true, }); mockReadEnvFile.mockReset(); - mockGetActiveCodexAuthPath.mockReset(); - mockGetCodexAccountCount.mockReset(); - mockGetCodexAccountCount.mockReturnValue(0); + mockGetCodexAuthPath.mockReset(); + mockGetCodexAuthPath.mockReturnValue(null); mockClaimCodexAuthLease.mockReset(); mockClaimCodexAuthLease.mockReturnValue(null); - mockFindCodexAccountIndexByAuthPath.mockReset(); - mockFindCodexAccountIndexByAuthPath.mockReturnValue(null); }); afterEach(() => { @@ -759,13 +737,10 @@ describe('prepareGroupEnvironment Codex goals handling', () => { }); mockReadEnvFile.mockReset(); - mockGetActiveCodexAuthPath.mockReset(); - mockGetCodexAccountCount.mockReset(); - mockGetCodexAccountCount.mockReturnValue(0); + mockGetCodexAuthPath.mockReset(); + mockGetCodexAuthPath.mockReturnValue(null); mockClaimCodexAuthLease.mockReset(); mockClaimCodexAuthLease.mockReturnValue(null); - mockFindCodexAccountIndexByAuthPath.mockReset(); - mockFindCodexAccountIndexByAuthPath.mockReturnValue(null); vi.mocked(config.isReviewService).mockReturnValue(false); vi.mocked(serviceRouting.hasReviewerLease).mockReturnValue(false); vi.mocked(serviceRouting.getEffectiveChannelLease).mockReturnValue({ @@ -854,13 +829,10 @@ describe('prepareReadonlySessionEnvironment codex compatibility', () => { }); mockReadEnvFile.mockReset(); - mockGetActiveCodexAuthPath.mockReset(); - mockGetCodexAccountCount.mockReset(); - mockGetCodexAccountCount.mockReturnValue(0); + mockGetCodexAuthPath.mockReset(); + mockGetCodexAuthPath.mockReturnValue(null); mockClaimCodexAuthLease.mockReset(); mockClaimCodexAuthLease.mockReturnValue(null); - mockFindCodexAccountIndexByAuthPath.mockReset(); - mockFindCodexAccountIndexByAuthPath.mockReturnValue(null); }); afterEach(() => { @@ -872,13 +844,12 @@ describe('prepareReadonlySessionEnvironment codex compatibility', () => { it('does not claim a Codex auth lease for Claude read-only sessions', () => { vi.mocked(serviceRouting.hasReviewerLease).mockReturnValue(true); - mockGetCodexAccountCount.mockReturnValue(1); const rotatedAuthPath = path.join(tempRoot, 'rotated-auth.json'); fs.writeFileSync(rotatedAuthPath, '{"auth_mode":"chatgpt"}\n'); + mockGetCodexAuthPath.mockReturnValue(rotatedAuthPath); const release = vi.fn(); mockClaimCodexAuthLease.mockReturnValue({ authPath: rotatedAuthPath, - accountIndex: 0, release, }); @@ -914,10 +885,17 @@ describe('prepareReadonlySessionEnvironment codex compatibility', () => { ); fs.mkdirSync(path.dirname(mcpServerPath), { recursive: true }); fs.writeFileSync(mcpServerPath, '// test mcp server\n'); - fs.writeFileSync( - path.join(process.env.EJ_TEST_HOME!, '.codex', 'auth.json'), - '{"auth_mode":"chatgpt"}\n', + const hostAuthPath = path.join( + process.env.EJ_TEST_HOME!, + '.codex', + 'auth.json', ); + fs.writeFileSync(hostAuthPath, '{"auth_mode":"chatgpt"}\n'); + mockGetCodexAuthPath.mockReturnValue(hostAuthPath); + mockClaimCodexAuthLease.mockReturnValue({ + authPath: hostAuthPath, + release: vi.fn(), + }); fs.writeFileSync( path.join(process.env.EJ_TEST_HOME!, '.codex', 'config.toml'), `model = "gpt-5.4" diff --git a/src/agent-runner-environment.ts b/src/agent-runner-environment.ts index d3e52b6..2728d82 100644 --- a/src/agent-runner-environment.ts +++ b/src/agent-runner-environment.ts @@ -14,18 +14,16 @@ import { logger } from './logger.js'; import { readEnvFile } from './env.js'; import { claimCodexAuthLease, - findCodexAccountIndexByAuthPath, - getActiveCodexAuthPath, - getCodexAccountCount, + getCodexAuthPath, type CodexAuthLease, -} from './codex-token-rotation.js'; +} from './codex-auth.js'; import { readCodexFeatureFromFile } from './codex-config-features.js'; import { ensureClaudeSessionSettings } from './claude-session-settings.js'; import { getClaudeCredentialsPath } from './claude-credentials-path.js'; import { - getConfiguredClaudeTokens, - getCurrentToken, -} from './token-rotation.js'; + getConfiguredClaudeToken, + getCurrentClaudeToken, +} from './claude-oauth-token.js'; import { resolveGroupFolderPath, resolveGroupIpcPath, @@ -69,7 +67,7 @@ function syncClaudeCredentialsToSessionDir(sessionClaudeDir: string): void { // pre-sync, a freshly created session dir has no credentials.json and the // child Claude process fails to authenticate on its first run. token- // refresh.ts's syncToSessionDirs only kicks in on the next refresh cycle. - const srcPath = getClaudeCredentialsPath(0, { allowHomeFallback: true }); + const srcPath = getClaudeCredentialsPath({ allowHomeFallback: true }); if (!srcPath || !fs.existsSync(srcPath)) return; const dest = path.join(sessionClaudeDir, '.credentials.json'); try { @@ -169,8 +167,7 @@ function ensureClaudeGlobalSettingsFile(sessionDir: string): void { export interface PreparedCodexSessionAuth { canonicalAuthPath: string; sessionAuthPath: string; - accountIndex: number | null; - lease?: CodexAuthLease; + lease: CodexAuthLease; } function syncHostCodexSessionFiles( @@ -179,24 +176,6 @@ function syncHostCodexSessionFiles( const hostCodexDir = path.join(os.homedir(), '.codex'); fs.mkdirSync(sessionCodexDir, { recursive: true }); - const authDst = path.join(sessionCodexDir, 'auth.json'); - const hasRotationAccounts = getCodexAccountCount() > 0; - const lease = claimCodexAuthLease(); - const rotatedAuthSrc = - lease?.authPath ?? (!hasRotationAccounts ? getActiveCodexAuthPath() : null); - const fallbackAuthSrc = path.join(hostCodexDir, 'auth.json'); - const authSrc = - rotatedAuthSrc && fs.existsSync(rotatedAuthSrc) - ? rotatedAuthSrc - : !hasRotationAccounts && fs.existsSync(fallbackAuthSrc) - ? fallbackAuthSrc - : null; - if (authSrc) { - fs.copyFileSync(authSrc, authDst); - } else if (fs.existsSync(authDst)) { - fs.unlinkSync(authDst); - } - for (const file of ['config.toml', 'config.json']) { const src = path.join(hostCodexDir, file); const dst = path.join(sessionCodexDir, file); @@ -205,27 +184,28 @@ function syncHostCodexSessionFiles( } } - if ( - !rotatedAuthSrc || - authSrc !== rotatedAuthSrc || - !fs.existsSync(authDst) - ) { - lease?.release(); - if (hasRotationAccounts) { - throw new Error( - 'Codex rotation pool unavailable: all rotation accounts are currently dead, rate-limited, or locked; re-auth or clear stale state before launching Codex', - ); - } + const authDst = path.join(sessionCodexDir, 'auth.json'); + const canonicalAuthPath = getCodexAuthPath(); + if (!canonicalAuthPath) { + if (fs.existsSync(authDst)) fs.unlinkSync(authDst); return null; } - return { - canonicalAuthPath: rotatedAuthSrc, - sessionAuthPath: authDst, - accountIndex: - lease?.accountIndex ?? findCodexAccountIndexByAuthPath(rotatedAuthSrc), - ...(lease ? { lease } : {}), - }; + const lease = claimCodexAuthLease(); + if (!lease) { + if (fs.existsSync(authDst)) fs.unlinkSync(authDst); + throw new Error( + 'Codex account unavailable: the account is locked by another Codex run or its weekly quota is exhausted', + ); + } + try { + fs.copyFileSync(canonicalAuthPath, authDst); + } catch (err) { + lease.release(); + throw err; + } + + return { canonicalAuthPath, sessionAuthPath: authDst, lease }; } function upsertEjclawMcpServerSection(args: { @@ -361,17 +341,17 @@ function prepareClaudeEnvironment(args: { args.envVars.ANTHROPIC_BASE_URL || process.env.ANTHROPIC_BASE_URL || ''; } { - // Token rotation takes priority over static .env value + // The refreshed in-memory token takes priority over the static .env value const oauthToken = - getCurrentToken() || - getConfiguredClaudeTokens({ - multi: + getCurrentClaudeToken() || + getConfiguredClaudeToken({ + list: args.envVars.CLAUDE_CODE_OAUTH_TOKENS || process.env.CLAUDE_CODE_OAUTH_TOKENS, single: args.envVars.CLAUDE_CODE_OAUTH_TOKEN || process.env.CLAUDE_CODE_OAUTH_TOKEN, - })[0]; + }); if (oauthToken) { args.env.CLAUDE_CODE_OAUTH_TOKEN = oauthToken; } diff --git a/src/agent-runner.test.ts b/src/agent-runner.test.ts index d391cff..a7d7d11 100644 --- a/src/agent-runner.test.ts +++ b/src/agent-runner.test.ts @@ -148,9 +148,7 @@ function mockCodexLeaseEnvironment(releaseLease: () => void) { codexSessionAuth: { canonicalAuthPath: '/tmp/codex-account/auth.json', sessionAuthPath: '/tmp/codex-session/auth.json', - accountIndex: 0, lease: { - accountIndex: 0, authPath: '/tmp/codex-account/auth.json', release: releaseLease, }, diff --git a/src/agent-runner.ts b/src/agent-runner.ts index 0fa456f..7d1fe2e 100644 --- a/src/agent-runner.ts +++ b/src/agent-runner.ts @@ -21,7 +21,7 @@ import { isCodexAuthLeaseAvailable, syncCodexSessionAuthBack, waitForCodexAuthLease, -} from './codex-token-rotation.js'; +} from './codex-auth.js'; import { syncClaudeSessionAuthBack } from './token-refresh.js'; import { runSpawnedAgentProcess } from './agent-runner-process.js'; import { getStoredRoomSkillOverrides } from './db.js'; @@ -82,7 +82,7 @@ function readRoomSkillOverridesForRunner( function releaseCodexAuthSession( auth: PreparedCodexSessionAuth | null | undefined, ): void { - auth?.lease?.release(); + auth?.lease.release(); } function finalizeCodexAuthSession( @@ -93,19 +93,17 @@ function finalizeCodexAuthSession( syncCodexSessionAuthBack({ canonicalAuthPath: auth.canonicalAuthPath, sessionAuthPath: auth.sessionAuthPath, - accountIndex: auth.accountIndex, }); } catch (err) { logger.warn( { err, canonicalAuthPath: auth.canonicalAuthPath, - accountIndex: auth.accountIndex, }, 'Failed to sync Codex session auth back to canonical slot', ); } finally { - auth.lease?.release(); + auth.lease.release(); } } @@ -166,8 +164,8 @@ export async function runAgentProcess( !isCodexAuthLeaseAvailable() ) { // A concurrent Codex run in another room may hold the account lease. - // Wait for it instead of failing the turn outright; if the pool is dead or - // rate-limited this returns at once and the prepare step below fails fast. + // Wait for it instead of failing the turn outright; if the weekly quota is + // exhausted this returns at once and the prepare step below fails fast. await waitForCodexAuthLease(); } const prepared = prepareGroupEnvironment(group, input.chatJid, { diff --git a/src/claude-credentials-path.ts b/src/claude-credentials-path.ts index fa21e91..1fded97 100644 --- a/src/claude-credentials-path.ts +++ b/src/claude-credentials-path.ts @@ -6,33 +6,17 @@ function readPathEnv(key: string): string | null { return value ? path.resolve(value) : null; } +/** + * Claude OAuth credentials file of this service: CLAUDE_CREDENTIALS_PATH, else + * ~/.claude/.credentials.json when the home fallback is allowed. + */ export function getClaudeCredentialsPath( - accountIndex: number, options: { allowHomeFallback?: boolean } = {}, ): string | null { const explicitPath = readPathEnv('CLAUDE_CREDENTIALS_PATH'); - if (accountIndex === 0 && explicitPath) return explicitPath; - - const explicitAccountsDir = readPathEnv('CLAUDE_ACCOUNTS_DIR'); - if (accountIndex > 0 && explicitAccountsDir) { - return path.join( - explicitAccountsDir, - String(accountIndex), - '.credentials.json', - ); - } - + if (explicitPath) return explicitPath; if (options.allowHomeFallback === false) return null; - - if (accountIndex === 0) { - return path.join(os.homedir(), '.claude', '.credentials.json'); - } - return path.join( - os.homedir(), - '.claude-accounts', - String(accountIndex), - '.credentials.json', - ); + return path.join(os.homedir(), '.claude', '.credentials.json'); } export function hasExplicitClaudeCredentialsPath(): boolean { diff --git a/src/claude-oauth-token.test.ts b/src/claude-oauth-token.test.ts new file mode 100644 index 0000000..1de87cf --- /dev/null +++ b/src/claude-oauth-token.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it, vi } from 'vitest'; + +vi.mock('./env.js', () => ({ getEnv: vi.fn(() => undefined) })); + +import { + getConfiguredClaudeToken, + getCurrentClaudeToken, + setCurrentClaudeToken, +} from './claude-oauth-token.js'; + +describe('claude-oauth-token', () => { + it('uses the first entry of a legacy comma-separated token list', () => { + expect( + getConfiguredClaudeToken({ list: ' tok-a , tok-b', single: 'tok-c' }), + ).toBe('tok-a'); + }); + + it('falls back to the single token', () => { + expect(getConfiguredClaudeToken({ list: ' , ', single: 'tok-c' })).toBe( + 'tok-c', + ); + expect(getConfiguredClaudeToken({})).toBeUndefined(); + }); + + it('prefers a refreshed token over the configured one', () => { + expect(getCurrentClaudeToken()).toBeUndefined(); + setCurrentClaudeToken('refreshed'); + expect(getCurrentClaudeToken()).toBe('refreshed'); + }); +}); diff --git a/src/claude-oauth-token.ts b/src/claude-oauth-token.ts new file mode 100644 index 0000000..55cd298 --- /dev/null +++ b/src/claude-oauth-token.ts @@ -0,0 +1,36 @@ +/** + * The Claude Code OAuth token passed to spawned agents. + * + * Read from CLAUDE_CODE_OAUTH_TOKEN, or from CLAUDE_CODE_OAUTH_TOKENS (legacy + * comma-separated list; only the first entry is used). token-refresh.ts + * replaces the in-memory value after an OAuth refresh so new runs pick up the + * fresh token without a restart. + */ + +import { getEnv } from './env.js'; + +let refreshedToken: string | undefined; + +export function getConfiguredClaudeToken(options?: { + list?: string | undefined; + single?: string | undefined; +}): string | undefined { + const list = options?.list ?? getEnv('CLAUDE_CODE_OAUTH_TOKENS'); + const fromList = list + ?.split(',') + .map((token) => token.trim()) + .find(Boolean); + if (fromList) return fromList; + const single = (options?.single ?? getEnv('CLAUDE_CODE_OAUTH_TOKEN'))?.trim(); + return single || undefined; +} + +/** The current token: the last refreshed value, else the configured one. */ +export function getCurrentClaudeToken(): string | undefined { + return refreshedToken ?? getConfiguredClaudeToken(); +} + +/** Replace the in-memory token after an OAuth refresh. */ +export function setCurrentClaudeToken(token: string): void { + refreshedToken = token; +} diff --git a/src/claude-usage-backoff.test.ts b/src/claude-usage-backoff.test.ts index 5866d8d..de22456 100644 --- a/src/claude-usage-backoff.test.ts +++ b/src/claude-usage-backoff.test.ts @@ -15,11 +15,8 @@ vi.mock('./logger.js', () => ({ vi.mock('./config.js', () => ({ DATA_DIR: '/tmp/ejclaw-usage-backoff-data' })); -const { getAllTokensMock } = vi.hoisted(() => ({ getAllTokensMock: vi.fn() })); -vi.mock('./token-rotation.js', () => ({ - getAllTokens: getAllTokensMock, - getCurrentToken: () => null, - getConfiguredClaudeTokens: () => [], +vi.mock('./claude-oauth-token.js', () => ({ + getCurrentClaudeToken: () => 'sk-ant-oat01-testTokenAAAAAAAA', })); const { readJsonFileMock } = vi.hoisted(() => ({ readJsonFileMock: vi.fn() })); @@ -72,15 +69,6 @@ describe('parseRetryAfterMs', () => { describe('Claude usage 429 Retry-After backoff', () => { beforeEach(() => { readJsonFileMock.mockReturnValue({}); // start from an empty disk cache - getAllTokensMock.mockReturnValue([ - { - index: 0, - token: 'sk-ant-oat01-testTokenAAAAAAAA', - masked: 'sk-ant-oat01-test...AAAA', - isActive: true, - isRateLimited: false, - }, - ]); }); it('records a cooldown on 429 and skips the next fetch within the window', async () => { @@ -89,17 +77,17 @@ describe('Claude usage 429 Retry-After backoff', () => { ); vi.stubGlobal('fetch', fetchMock); - const { fetchAllClaudeUsage } = await import('./claude-usage.js'); + const { fetchClaudeUsage } = await import('./claude-usage.js'); - const first = await fetchAllClaudeUsage(); + const first = await fetchClaudeUsage(); expect(fetchMock).toHaveBeenCalledTimes(1); - expect(first[0].usageRateLimited).toBe(true); - expect(first[0].usage).toBeNull(); + expect(first!.usageRateLimited).toBe(true); + expect(first!.usage).toBeNull(); // Immediate re-call: cooldown gate must hold, no second network call. - const second = await fetchAllClaudeUsage(); + const second = await fetchClaudeUsage(); expect(fetchMock).toHaveBeenCalledTimes(1); - expect(second[0].usageRateLimited).toBe(true); + expect(second!.usageRateLimited).toBe(true); }); it('falls back to the default cooldown when Retry-After is 0 (does not disable backoff)', async () => { @@ -115,17 +103,17 @@ describe('Claude usage 429 Retry-After backoff', () => { ); vi.stubGlobal('fetch', fetchMock); - const { fetchAllClaudeUsage } = await import('./claude-usage.js'); + const { fetchClaudeUsage } = await import('./claude-usage.js'); - await fetchAllClaudeUsage(); + await fetchClaudeUsage(); expect(fetchMock).toHaveBeenCalledTimes(1); // +70s: past the 60s throttle. With the bug (0 cooldown) this would refetch; // with the default 5-min cooldown it must still be held. vi.setSystemTime(Date.now() + 70_000); - const held = await fetchAllClaudeUsage(); + const held = await fetchClaudeUsage(); expect(fetchMock).toHaveBeenCalledTimes(1); - expect(held[0].usageRateLimited).toBe(true); + expect(held!.usageRateLimited).toBe(true); }); it('keeps backing off after the 5-minute throttle elapses but before the cooldown closes', async () => { @@ -142,21 +130,21 @@ describe('Claude usage 429 Retry-After backoff', () => { .mockResolvedValueOnce(makeResponse(200)); vi.stubGlobal('fetch', fetchMock); - const { fetchAllClaudeUsage } = await import('./claude-usage.js'); + const { fetchClaudeUsage } = await import('./claude-usage.js'); - await fetchAllClaudeUsage(); + await fetchClaudeUsage(); expect(fetchMock).toHaveBeenCalledTimes(1); // +370s: past the 300s throttle, still inside the ~398s cooldown → no refetch. vi.setSystemTime(Date.now() + 370_000); - const held = await fetchAllClaudeUsage(); + const held = await fetchClaudeUsage(); expect(fetchMock).toHaveBeenCalledTimes(1); - expect(held[0].usageRateLimited).toBe(true); + expect(held!.usageRateLimited).toBe(true); // +400s total: cooldown window closed → poller is allowed to fetch again. vi.setSystemTime(Date.now() + 30_000); - const resumed = await fetchAllClaudeUsage(); + const resumed = await fetchClaudeUsage(); expect(fetchMock).toHaveBeenCalledTimes(2); - expect(resumed[0].usageRateLimited).toBe(false); + expect(resumed!.usageRateLimited).toBe(false); }); }); diff --git a/src/claude-usage.test.ts b/src/claude-usage.test.ts index 2639d63..3b7b874 100644 --- a/src/claude-usage.test.ts +++ b/src/claude-usage.test.ts @@ -1,10 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { - getUsageCacheReadKeys, - getUsageCacheWriteKey, - type ClaudeUsageData, -} from './claude-usage.js'; +import { type ClaudeUsageData } from './claude-usage.js'; describe('ClaudeUsageData', () => { it('represents the API response structure correctly', () => { @@ -32,23 +28,4 @@ describe('ClaudeUsageData', () => { expect(data.five_hour?.utilization).toBe(10); expect(data.seven_day).toBeUndefined(); }); - - it('prefers account-based cache keys and falls back to token suffixes', () => { - expect( - getUsageCacheReadKeys( - 'sk-ant-oat01-currentHNCJmAAA', - 0, - 'sk-ant-oat01-credsEqnOPAAA', - ), - ).toEqual(['account-0', 'EqnOPAAA', 'HNCJmAAA']); - }); - - it('writes cache under account key when account index is known', () => { - expect(getUsageCacheWriteKey('sk-ant-oat01-currentHNCJmAAA', 0)).toBe( - 'account-0', - ); - expect(getUsageCacheWriteKey('sk-ant-oat01-currentHNCJmAAA')).toBe( - 'HNCJmAAA', - ); - }); }); diff --git a/src/claude-usage.ts b/src/claude-usage.ts index abcda9e..ff24365 100644 --- a/src/claude-usage.ts +++ b/src/claude-usage.ts @@ -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 = {}; 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 { 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(); +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 { - 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 { + 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 { - 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 { + const token = resolveUsageToken(); + if (!token) return null; + const { usage, rateLimited } = await fetchUsageForToken(token); + return { usage, usageRateLimited: rateLimited }; } diff --git a/src/codex-auth.test.ts b/src/codex-auth.test.ts new file mode 100644 index 0000000..e0b88fc --- /dev/null +++ b/src/codex-auth.test.ts @@ -0,0 +1,243 @@ +import fs from 'fs'; +import path from 'path'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('./logger.js', () => ({ + logger: { + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + debug: vi.fn(), + }, +})); + +vi.mock('os', async () => { + const actual = await vi.importActual('os'); + return { + ...actual, + default: { + ...actual, + homedir: () => process.env.CODEX_AUTH_TEST_HOME || '/tmp', + }, + homedir: () => process.env.CODEX_AUTH_TEST_HOME || '/tmp', + }; +}); + +function createAccountAuth(homeDir: string): string { + const authPath = path.join(homeDir, '.codex-accounts', '0', 'auth.json'); + fs.mkdirSync(path.dirname(authPath), { recursive: true }); + fs.writeFileSync( + authPath, + JSON.stringify({ + auth_mode: 'chatgpt', + tokens: { account_id: 'acct-0', access_token: 'token-0' }, + }), + ); + return authPath; +} + +function createDefaultCodexAuth(homeDir: string): string { + const authPath = path.join(homeDir, '.codex', 'auth.json'); + fs.mkdirSync(path.dirname(authPath), { recursive: true }); + fs.writeFileSync( + authPath, + JSON.stringify({ + auth_mode: 'chatgpt', + tokens: { account_id: 'default-acct', access_token: 'default-token' }, + }), + ); + return authPath; +} + +function useTempHome(prefix: string): () => string { + let tempHome = ''; + beforeEach(() => { + vi.resetModules(); + tempHome = fs.mkdtempSync(path.join('/tmp', prefix)); + process.env.CODEX_AUTH_TEST_HOME = tempHome; + }); + afterEach(() => { + delete process.env.CODEX_AUTH_TEST_HOME; + fs.rmSync(tempHome, { recursive: true, force: true }); + }); + return () => tempHome; +} + +describe('codex-auth path resolution', () => { + const home = useTempHome('ejclaw-codex-auth-path-'); + + it('prefers ~/.codex-accounts/0/auth.json over ~/.codex/auth.json', async () => { + createDefaultCodexAuth(home()); + const accountAuthPath = createAccountAuth(home()); + const mod = await import('./codex-auth.js'); + expect(mod.getCodexAuthPath()).toBe(accountAuthPath); + }); + + it('falls back to ~/.codex/auth.json when the account dir has no auth.json', async () => { + const fallbackAuthPath = createDefaultCodexAuth(home()); + const mod = await import('./codex-auth.js'); + expect(mod.getCodexAuthPath()).toBe(fallbackAuthPath); + expect(mod.getCodexAccountStatus()).not.toBeNull(); + }); + + it('returns null without any auth.json', async () => { + const mod = await import('./codex-auth.js'); + expect(mod.getCodexAuthPath()).toBeNull(); + expect(mod.getCodexAccountStatus()).toBeNull(); + expect(mod.claimCodexAuthLease()).toBeNull(); + }); +}); + +describe('codex-auth session auth write-back', () => { + const home = useTempHome('ejclaw-codex-auth-sync-'); + + it('syncs a refreshed session auth.json back to the canonical file atomically', async () => { + const canonicalAuthPath = createAccountAuth(home()); + const mod = await import('./codex-auth.js'); + + const sessionAuthPath = path.join(home(), 'session', '.codex', 'auth.json'); + fs.mkdirSync(path.dirname(sessionAuthPath), { recursive: true }); + fs.writeFileSync( + sessionAuthPath, + JSON.stringify({ + auth_mode: 'chatgpt', + tokens: { + account_id: 'acct-0', + access_token: 'new-access', + refresh_token: 'new-refresh', + }, + }), + ); + + expect( + mod.syncCodexSessionAuthBack({ canonicalAuthPath, sessionAuthPath }), + ).toBe(true); + const canonical = JSON.parse(fs.readFileSync(canonicalAuthPath, 'utf-8')); + expect(canonical.tokens).toEqual( + expect.objectContaining({ + account_id: 'acct-0', + access_token: 'new-access', + refresh_token: 'new-refresh', + }), + ); + }); + + it('refuses to sync a session auth.json that belongs to another Codex account', async () => { + const canonicalAuthPath = createAccountAuth(home()); + const mod = await import('./codex-auth.js'); + const before = fs.readFileSync(canonicalAuthPath, 'utf-8'); + const sessionAuthPath = path.join( + home(), + 'wrong-account', + '.codex', + 'auth.json', + ); + fs.mkdirSync(path.dirname(sessionAuthPath), { recursive: true }); + fs.writeFileSync( + sessionAuthPath, + JSON.stringify({ + auth_mode: 'chatgpt', + tokens: { + account_id: 'acct-other', + access_token: 'other-access', + refresh_token: 'other-refresh', + }, + }), + ); + + expect( + mod.syncCodexSessionAuthBack({ canonicalAuthPath, sessionAuthPath }), + ).toBe(false); + expect(fs.readFileSync(canonicalAuthPath, 'utf-8')).toBe(before); + }); +}); + +describe('codex-auth lease', () => { + const home = useTempHome('ejclaw-codex-auth-lease-'); + beforeEach(() => { + createAccountAuth(home()); + }); + + it('reports lease availability synchronously', async () => { + const mod = await import('./codex-auth.js'); + expect(mod.isCodexAuthLeaseAvailable()).toBe(true); + const held = mod.claimCodexAuthLease(); + expect(mod.isCodexAuthLeaseAvailable()).toBe(false); + held?.release(); + expect(mod.isCodexAuthLeaseAvailable()).toBe(true); + }); + + it('makes a usage poll skip while a run holds the lease', async () => { + const mod = await import('./codex-auth.js'); + const held = mod.claimCodexAuthLease(); + expect(held).not.toBeNull(); + expect(mod.claimCodexUsagePollLease()).toBeNull(); + held?.release(); + const poll = mod.claimCodexUsagePollLease(); + expect(poll).not.toBeNull(); + poll?.release(); + }); + + it('returns immediately when the account is free', async () => { + const mod = await import('./codex-auth.js'); + const sleep = vi.fn(async () => {}); + + await expect(mod.waitForCodexAuthLease({ sleep })).resolves.toBe(true); + expect(sleep).not.toHaveBeenCalled(); + }); + + it('waits for a concurrent run to release the lease instead of failing', async () => { + const mod = await import('./codex-auth.js'); + + // Another room's Codex run holds the account. Before the wait, a second + // claim fails outright — that was the skipped-review bug. + const held = mod.claimCodexAuthLease(); + expect(held).not.toBeNull(); + expect(mod.claimCodexAuthLease()).toBeNull(); + + let polls = 0; + const sleep = vi.fn(async () => { + polls += 1; + if (polls === 3) held?.release(); + }); + + await expect(mod.waitForCodexAuthLease({ sleep, pollMs: 1 })).resolves.toBe( + true, + ); + expect(polls).toBe(3); + + const next = mod.claimCodexAuthLease(); + expect(next).not.toBeNull(); + next?.release(); + }); + + it('gives up after the timeout while the lease stays held', async () => { + const mod = await import('./codex-auth.js'); + const held = mod.claimCodexAuthLease(); + try { + await expect( + mod.waitForCodexAuthLease({ + timeoutMs: 0, + sleep: async () => {}, + }), + ).resolves.toBe(false); + } finally { + held?.release(); + } + }); + + it('does not wait when the weekly quota is exhausted rather than leased', async () => { + const mod = await import('./codex-auth.js'); + mod.updateCodexUsage({ usagePct: 80, d7Pct: 100 }); + const sleep = vi.fn(async () => {}); + + await expect(mod.waitForCodexAuthLease({ sleep })).resolves.toBe(false); + expect(sleep).not.toHaveBeenCalled(); + expect(mod.claimCodexAuthLease()).toBeNull(); + // A usage poll still gets the lease so the reset can be observed. + const poll = mod.claimCodexUsagePollLease(); + expect(poll).not.toBeNull(); + poll?.release(); + }); +}); diff --git a/src/codex-auth.ts b/src/codex-auth.ts new file mode 100644 index 0000000..2c1f6e7 --- /dev/null +++ b/src/codex-auth.ts @@ -0,0 +1,342 @@ +/** + * Codex (ChatGPT OAuth) auth for the single Codex account. + * + * The account lives at ~/.codex-accounts/0/auth.json, falling back to + * ~/.codex/auth.json when that file does not exist. Before each Codex run the + * canonical auth.json is copied into the session directory; afterwards any + * refreshed token is written back (syncCodexSessionAuthBack). + * + * Exclusive lease: two Codex processes must never refresh the same refresh + * token at once (the second one gets "refresh token was already used" and the + * account dies). A lock file next to auth.json serialises every Codex run and + * every usage poll on the account. + */ + +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { logger } from './logger.js'; +import { readJsonFile } from './utils.js'; + +export interface CodexAuthLease { + authPath: string; + release: () => void; +} + +export interface CodexAccountStatus { + cachedUsagePct?: number; + cachedUsageD7Pct?: number; + resetAt?: string; + resetD7At?: string; +} + +interface CodexUsageState { + lastUsagePct?: number; + lastUsageD7Pct?: number; + resetAt?: string; + resetD7At?: string; +} + +const CODEX_AUTH_LEASE_MS = 2 * 60 * 60_000; + +const usageState: CodexUsageState = {}; +let leasedUntil: number | null = null; +let leaseId: string | null = null; + +function codexAuthCandidates(): string[] { + const home = os.homedir(); + return [ + path.join(home, '.codex-accounts', '0', 'auth.json'), + path.join(home, '.codex', 'auth.json'), + ]; +} + +/** + * Canonical auth.json of the Codex account, or null when neither + * ~/.codex-accounts/0/auth.json nor ~/.codex/auth.json exists. + */ +export function getCodexAuthPath(): string | null { + for (const candidate of codexAuthCandidates()) { + if (fs.existsSync(candidate)) return candidate; + } + return null; +} + +function codexLockPath(authPath: string): string { + return path.join(path.dirname(authPath), '.ejclaw-auth.lock'); +} + +function isPidAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +function readExistingLease(lockPath: string): { + leaseId?: string; + pid?: number; + expiresAt?: number; +} | null { + return ( + readJsonFile<{ + leaseId?: string; + pid?: number; + expiresAt?: number; + }>(lockPath) ?? null + ); +} + +function tryAcquireDiskLease( + authPath: string, + id: string, + now: number, +): boolean { + const lockPath = codexLockPath(authPath); + const payload = JSON.stringify( + { + leaseId: id, + pid: process.pid, + createdAt: now, + expiresAt: now + CODEX_AUTH_LEASE_MS, + }, + null, + 2, + ); + + try { + fs.writeFileSync(lockPath, payload, { flag: 'wx', mode: 0o600 }); + return true; + } catch (err) { + if ((err as NodeJS.ErrnoException).code !== 'EEXIST') return false; + } + + const existing = readExistingLease(lockPath); + const expired = Boolean(existing?.expiresAt && existing.expiresAt <= now); + const deadPid = Boolean(existing?.pid && !isPidAlive(existing.pid)); + if (!expired && !deadPid) return false; + + try { + fs.unlinkSync(lockPath); + } catch { + return false; + } + + try { + fs.writeFileSync(lockPath, payload, { flag: 'wx', mode: 0o600 }); + return true; + } catch { + return false; + } +} + +function releaseDiskLease(authPath: string, id: string): void { + const lockPath = codexLockPath(authPath); + const existing = readExistingLease(lockPath); + if (existing?.leaseId && existing.leaseId !== id) return; + try { + fs.unlinkSync(lockPath); + } catch { + // Best effort only. Expired/stale locks are cleared by the next claimant. + } +} + +function isLeasedByLiveRun(authPath: string, now: number): boolean { + if (leasedUntil && leasedUntil > now) return true; + const existing = readExistingLease(codexLockPath(authPath)); + if (!existing) return false; + if (existing.expiresAt && existing.expiresAt <= now) return false; + if (existing.pid && !isPidAlive(existing.pid)) return false; + return true; +} + +/** Weekly (7d) quota used up: launching Codex would only fail. */ +function isWeeklyUsageExhausted(): boolean { + return usageState.lastUsageD7Pct != null && usageState.lastUsageD7Pct >= 100; +} + +function acquireLease(authPath: string, tag: string): CodexAuthLease | null { + const now = Date.now(); + if (isLeasedByLiveRun(authPath, now)) return null; + const id = `${process.pid}-${now}-${tag}-${Math.random() + .toString(36) + .slice(2)}`; + if (!tryAcquireDiskLease(authPath, id, now)) return null; + leasedUntil = now + CODEX_AUTH_LEASE_MS; + leaseId = id; + return { + authPath, + release: () => { + if (leaseId === id) { + leasedUntil = null; + leaseId = null; + } + releaseDiskLease(authPath, id); + }, + }; +} + +/** Synchronous check: can a Codex run lease the account right now? */ +export function isCodexAuthLeaseAvailable(): boolean { + const authPath = getCodexAuthPath(); + if (!authPath) return true; + return !isWeeklyUsageExhausted() && !isLeasedByLiveRun(authPath, Date.now()); +} + +const CODEX_AUTH_LEASE_WAIT_MAX_MS = 15 * 60_000; +const CODEX_AUTH_LEASE_WAIT_POLL_MS = 2_000; + +/** + * Wait until the Codex account can be leased. + * + * The lease serialises every Codex run, so a run that starts while another + * room's Codex run holds it would fail immediately — which silently skipped + * reviews (task closed as reviewer_codex_unavailable) whenever two rooms + * needed Codex at the same time. + * + * Only waits while the sole obstacle is a lease held by a live run. An + * exhausted weekly quota returns false right away so the caller fails fast. + */ +export async function waitForCodexAuthLease(opts?: { + timeoutMs?: number; + pollMs?: number; + sleep?: (ms: number) => Promise; +}): Promise { + const authPath = getCodexAuthPath(); + if (!authPath) return true; + const timeoutMs = opts?.timeoutMs ?? CODEX_AUTH_LEASE_WAIT_MAX_MS; + const pollMs = opts?.pollMs ?? CODEX_AUTH_LEASE_WAIT_POLL_MS; + const sleep = + opts?.sleep ?? + ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + const startedAt = Date.now(); + let logged = false; + + for (;;) { + const now = Date.now(); + if (isWeeklyUsageExhausted()) return false; + if (!isLeasedByLiveRun(authPath, now)) { + if (logged) { + logger.info( + { waitedMs: now - startedAt }, + 'Codex account lease became available after waiting', + ); + } + return true; + } + if (now - startedAt >= timeoutMs) { + if (logged) { + logger.warn( + { waitedMs: now - startedAt, timeoutMs }, + 'Gave up waiting for the Codex account lease', + ); + } + return false; + } + if (!logged) { + logger.info( + { timeoutMs }, + 'Codex account is leased by another run; waiting before launching Codex', + ); + logged = true; + } + await sleep(pollMs); + } +} + +/** + * Lease the account for a Codex run. Returns null when there is no auth.json, + * the weekly quota is exhausted, or another live run holds the lease. + */ +export function claimCodexAuthLease(): CodexAuthLease | null { + const authPath = getCodexAuthPath(); + if (!authPath || isWeeklyUsageExhausted()) return null; + return acquireLease(authPath, 'run'); +} + +/** + * Lease the account for a usage poll. Unlike claimCodexAuthLease() this ignores + * the exhausted weekly quota (polling is how its reset is learned). Returns + * null when a live run holds the lease, so the caller can simply skip. + */ +export function claimCodexUsagePollLease(): CodexAuthLease | null { + const authPath = getCodexAuthPath(); + if (!authPath) return null; + return acquireLease(authPath, 'poll'); +} + +export function syncCodexSessionAuthBack(args: { + canonicalAuthPath: string; + sessionAuthPath: string; +}): boolean { + if (!fs.existsSync(args.sessionAuthPath)) return false; + if (!fs.existsSync(args.canonicalAuthPath)) return false; + + const canonical = readJsonFile<{ + auth_mode?: string; + tokens?: { account_id?: string }; + }>(args.canonicalAuthPath); + const session = readJsonFile<{ + auth_mode?: string; + tokens?: { account_id?: string }; + }>(args.sessionAuthPath); + if (!canonical || !session?.tokens) return false; + + const canonicalAccount = canonical.tokens?.account_id; + const sessionAccount = session.tokens.account_id; + if ( + canonicalAccount && + sessionAccount && + canonicalAccount !== sessionAccount + ) { + logger.warn( + { + canonicalAuthPath: args.canonicalAuthPath, + sessionAuthPath: args.sessionAuthPath, + }, + 'Refusing to sync Codex session auth back: account mismatch', + ); + return false; + } + + const sessionRaw = fs.readFileSync(args.sessionAuthPath, 'utf-8'); + const canonicalRaw = fs.readFileSync(args.canonicalAuthPath, 'utf-8'); + if (sessionRaw === canonicalRaw) return false; + + const tmpPath = `${args.canonicalAuthPath}.tmp-${process.pid}-${Date.now()}`; + fs.writeFileSync(tmpPath, sessionRaw, { mode: 0o600 }); + fs.renameSync(tmpPath, args.canonicalAuthPath); + + logger.info( + { canonicalAuthPath: args.canonicalAuthPath }, + 'Synced refreshed Codex session auth back to canonical auth.json', + ); + return true; +} + +/** Cache the latest usage numbers (from the usage collector). */ +export function updateCodexUsage(usage: { + usagePct: number; + resetAt?: string; + d7Pct?: number; + resetD7At?: string; +}): void { + usageState.lastUsagePct = usage.usagePct; + if (usage.d7Pct != null) usageState.lastUsageD7Pct = usage.d7Pct; + if (usage.resetAt) usageState.resetAt = usage.resetAt; + if (usage.resetD7At) usageState.resetD7At = usage.resetD7At; +} + +/** Account status for the dashboard and the warm-up primer. */ +export function getCodexAccountStatus(): CodexAccountStatus | null { + if (!getCodexAuthPath()) return null; + return { + cachedUsagePct: usageState.lastUsagePct, + cachedUsageD7Pct: usageState.lastUsageD7Pct, + resetAt: usageState.resetAt, + resetD7At: usageState.resetD7At, + }; +} diff --git a/src/codex-token-rotation.test.ts b/src/codex-token-rotation.test.ts deleted file mode 100644 index e6c1e8b..0000000 --- a/src/codex-token-rotation.test.ts +++ /dev/null @@ -1,523 +0,0 @@ -import fs from 'fs'; -import path from 'path'; - -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; - -vi.mock('./agent-error-detection.js', () => ({ - classifyAgentError: vi.fn(() => ({ category: 'none', reason: '' })), - classifyCodexAuthError: vi.fn(() => ({ category: 'none', reason: '' })), - isCodexPoolUnavailableError: vi.fn( - (error: string | null | undefined) => - /all\s+codex(?:\s+rotation)?\s+accounts(?:\s+are)?\s+unavailable/i.test( - error ?? '', - ) || /codex\s+rotation\s+pool\s+unavailable/i.test(error ?? ''), - ), -})); - -vi.mock('./config.js', () => ({ - DATA_DIR: '/tmp/ejclaw-codex-rot-data', -})); - -vi.mock('./logger.js', () => ({ - logger: { - info: vi.fn(), - warn: vi.fn(), - error: vi.fn(), - debug: vi.fn(), - }, -})); - -vi.mock('./utils.js', async () => { - const actual = - await vi.importActual('./utils.js'); - return { - ...actual, - writeJsonFile: vi.fn(), // no-op to prevent state file writes - }; -}); - -vi.mock('os', async () => { - const actual = await vi.importActual('os'); - return { - ...actual, - default: { - ...actual, - homedir: () => process.env.CODEX_ROT_TEST_HOME || '/tmp', - }, - homedir: () => process.env.CODEX_ROT_TEST_HOME || '/tmp', - }; -}); - -function createFakeAccounts(homeDir: string, count: number): void { - for (let i = 0; i < count; i++) { - const dir = path.join(homeDir, '.codex-accounts', String(i)); - fs.mkdirSync(dir, { recursive: true }); - fs.writeFileSync( - path.join(dir, 'auth.json'), - JSON.stringify({ - auth_mode: 'chatgpt', - tokens: { account_id: `acct-${i}`, access_token: `token-${i}` }, - }), - ); - } -} - -function createDefaultCodexAuth(homeDir: string): string { - const authPath = path.join(homeDir, '.codex', 'auth.json'); - fs.mkdirSync(path.dirname(authPath), { recursive: true }); - fs.writeFileSync( - authPath, - JSON.stringify({ - auth_mode: 'chatgpt', - tokens: { account_id: 'default-acct', access_token: 'default-token' }, - }), - ); - return authPath; -} - -describe('codex-token-rotation d7 ≥ 100% auto-skip', () => { - let tempHome: string; - - beforeEach(() => { - vi.resetModules(); - tempHome = fs.mkdtempSync(path.join('/tmp', 'ejclaw-codex-rot-')); - process.env.CODEX_ROT_TEST_HOME = tempHome; - createFakeAccounts(tempHome, 4); - }); - - afterEach(() => { - delete process.env.CODEX_ROT_TEST_HOME; - fs.rmSync(tempHome, { recursive: true, force: true }); - }); - - it('advanceCodexAccount skips accounts with d7 ≥ 100%', async () => { - const mod = await import('./codex-token-rotation.js'); - mod.initCodexTokenRotation(); - expect(mod.getCodexAccountCount()).toBe(4); - - // Mark account #1 (next after #0) as 7d-exhausted - mod.updateCodexAccountUsage(80, undefined, 1, 100, undefined); - - // Current is #0, advance should skip #1 (d7=100%) → land on #2 - mod.advanceCodexAccount(); - - const accounts = mod.getAllCodexAccounts(); - expect(accounts[0].isActive).toBe(false); - expect(accounts[1].isActive).toBe(false); - expect(accounts[2].isActive).toBe(true); - }); - - it('updateCodexAccountUsage auto-rotates when current account hits d7 ≥ 100%', async () => { - const mod = await import('./codex-token-rotation.js'); - mod.initCodexTokenRotation(); - expect(mod.getCodexAccountCount()).toBe(4); - - // Current is #0 — report d7=100% for the current account - mod.updateCodexAccountUsage(80, undefined, 0, 100, undefined); - - // Should have auto-rotated away from #0 to #1 - const accounts = mod.getAllCodexAccounts(); - expect(accounts[0].isActive).toBe(false); - expect(accounts[1].isActive).toBe(true); - }); - - it('advanceCodexAccount falls back when all accounts are d7-exhausted', async () => { - const mod = await import('./codex-token-rotation.js'); - mod.initCodexTokenRotation(); - expect(mod.getCodexAccountCount()).toBe(4); - - // Exhaust d7 on all accounts except current (#0) - mod.updateCodexAccountUsage(80, undefined, 1, 100, undefined); - mod.updateCodexAccountUsage(80, undefined, 2, 100, undefined); - mod.updateCodexAccountUsage(80, undefined, 3, 100, undefined); - - // Advance — all others d7-exhausted, falls back to rate-limit-only check - // findNextAvailable (base) should still find #1 since it's not rate-limited - mod.advanceCodexAccount(); - - const accounts = mod.getAllCodexAccounts(); - const active = accounts.find((a) => a.isActive); - expect(active).toBeDefined(); - expect(active!.index).toBe(1); // fallback picks next non-rate-limited - }); - - it('warns when Codex rotation state cannot be persisted', async () => { - const mod = await import('./codex-token-rotation.js'); - const utils = await import('./utils.js'); - const { logger } = await import('./logger.js'); - - vi.mocked(utils.writeJsonFile).mockImplementation(() => { - throw new Error('disk full'); - }); - - mod.initCodexTokenRotation(); - expect(mod.rotateCodexToken('rate limit')).toBe(true); - - expect(logger.warn).toHaveBeenCalledWith( - expect.objectContaining({ - stateFile: '/tmp/ejclaw-codex-rot-data/codex-rotation-state.json', - err: expect.any(Error), - }), - 'Failed to persist Codex rotation state', - ); - }); - - it('does not append ~/.codex/auth.json fallback when numbered accounts exist', async () => { - const fallbackAuthPath = createDefaultCodexAuth(tempHome); - - const mod = await import('./codex-token-rotation.js'); - mod.initCodexTokenRotation(); - - expect(mod.getCodexAccountCount()).toBe(4); - expect(mod.getActiveCodexAuthPath()).not.toBe(fallbackAuthPath); - }); - - it('does not mutate account health for the internal all-accounts-unavailable sentinel', async () => { - const agentErrors = await import('./agent-error-detection.js'); - vi.mocked(agentErrors.classifyCodexAuthError).mockReturnValueOnce({ - category: 'auth-expired', - reason: 'auth-expired', - }); - - const mod = await import('./codex-token-rotation.js'); - mod.initCodexTokenRotation(); - - expect( - mod.rotateCodexToken( - 'auth-expired: All Codex rotation accounts unavailable; re-auth required before launching Codex', - ), - ).toBe(false); - - const accounts = mod.getAllCodexAccounts(); - expect(accounts[0]).toEqual( - expect.objectContaining({ - isActive: true, - isAuthDead: false, - authStatus: 'healthy', - isRateLimited: false, - }), - ); - expect(accounts[1].isActive).toBe(false); - }); - - it('marks refresh-token reuse as dead auth instead of a recoverable cooldown', async () => { - const agentErrors = await import('./agent-error-detection.js'); - vi.mocked(agentErrors.classifyCodexAuthError).mockReturnValueOnce({ - category: 'auth-expired', - reason: 'auth-expired', - }); - - const mod = await import('./codex-token-rotation.js'); - mod.initCodexTokenRotation(); - - expect(mod.rotateCodexToken('refresh token was already used')).toBe(true); - - const accounts = mod.getAllCodexAccounts(); - expect(accounts[0]).toEqual( - expect.objectContaining({ - isAuthDead: true, - authStatus: 'dead_auth', - }), - ); - expect(accounts[0].isRateLimited).toBe(false); - expect(accounts[1].isActive).toBe(true); - }); -}); - -describe('codex-token-rotation auth synchronization', () => { - let tempHome: string; - - beforeEach(() => { - vi.resetModules(); - tempHome = fs.mkdtempSync(path.join('/tmp', 'ejclaw-codex-rot-')); - process.env.CODEX_ROT_TEST_HOME = tempHome; - createFakeAccounts(tempHome, 4); - }); - - afterEach(() => { - delete process.env.CODEX_ROT_TEST_HOME; - fs.rmSync(tempHome, { recursive: true, force: true }); - }); - - it('recovers a dead_auth account when canonical auth.json is refreshed before lease claim', async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z')); - try { - const agentErrors = await import('./agent-error-detection.js'); - vi.mocked(agentErrors.classifyCodexAuthError).mockReturnValueOnce({ - category: 'auth-expired', - reason: 'auth-expired', - }); - - const mod = await import('./codex-token-rotation.js'); - const utils = await import('./utils.js'); - mod.initCodexTokenRotation(); - - expect(mod.rotateCodexToken('refresh token was already used')).toBe(true); - expect(mod.getAllCodexAccounts()[0].isAuthDead).toBe(true); - - const refreshedAt = new Date('2026-01-01T00:00:10.000Z'); - const authPath = path.join(tempHome, '.codex-accounts', '0', 'auth.json'); - fs.writeFileSync( - authPath, - JSON.stringify({ - auth_mode: 'chatgpt', - tokens: { account_id: 'acct-0', access_token: 'refreshed-token' }, - }), - ); - fs.utimesSync(authPath, refreshedAt, refreshedAt); - - mod.setCurrentCodexAccountIndex(0); - const lease = mod.claimCodexAuthLease(); - try { - expect(lease).toEqual( - expect.objectContaining({ accountIndex: 0, authPath }), - ); - expect(mod.getAllCodexAccounts()[0]).toEqual( - expect.objectContaining({ - authStatus: 'healthy', - isAuthDead: false, - isActive: true, - }), - ); - expect(vi.mocked(utils.writeJsonFile)).toHaveBeenCalled(); - } finally { - lease?.release(); - } - } finally { - vi.useRealTimers(); - } - }); - - it('leases different accounts for concurrent Codex runs', async () => { - const mod = await import('./codex-token-rotation.js'); - mod.initCodexTokenRotation(); - - const first = mod.claimCodexAuthLease(); - const second = mod.claimCodexAuthLease(); - - try { - expect(first).toEqual( - expect.objectContaining({ - accountIndex: 0, - authPath: expect.any(String), - }), - ); - expect(second).toEqual( - expect.objectContaining({ - accountIndex: 1, - authPath: expect.any(String), - }), - ); - expect(second?.authPath).not.toBe(first?.authPath); - } finally { - second?.release(); - first?.release(); - } - }); - - it('syncs a refreshed session auth.json back to the canonical slot atomically', async () => { - const mod = await import('./codex-token-rotation.js'); - mod.initCodexTokenRotation(); - - const canonicalAuthPath = path.join( - tempHome, - '.codex-accounts', - '0', - 'auth.json', - ); - const sessionAuthPath = path.join( - tempHome, - 'session', - '.codex', - 'auth.json', - ); - fs.mkdirSync(path.dirname(sessionAuthPath), { recursive: true }); - fs.writeFileSync( - sessionAuthPath, - JSON.stringify({ - auth_mode: 'chatgpt', - tokens: { - account_id: 'acct-0', - access_token: 'new-access', - refresh_token: 'new-refresh', - }, - }), - ); - - const synced = mod.syncCodexSessionAuthBack({ - canonicalAuthPath, - sessionAuthPath, - accountIndex: 0, - }); - - expect(synced).toBe(true); - const canonical = JSON.parse(fs.readFileSync(canonicalAuthPath, 'utf-8')); - expect(canonical.tokens).toEqual( - expect.objectContaining({ - account_id: 'acct-0', - access_token: 'new-access', - refresh_token: 'new-refresh', - }), - ); - }); - - it('refuses to sync a session auth.json that belongs to another Codex account', async () => { - const mod = await import('./codex-token-rotation.js'); - mod.initCodexTokenRotation(); - - const canonicalAuthPath = path.join( - tempHome, - '.codex-accounts', - '0', - 'auth.json', - ); - const before = fs.readFileSync(canonicalAuthPath, 'utf-8'); - const sessionAuthPath = path.join( - tempHome, - 'wrong-account', - '.codex', - 'auth.json', - ); - fs.mkdirSync(path.dirname(sessionAuthPath), { recursive: true }); - fs.writeFileSync( - sessionAuthPath, - JSON.stringify({ - auth_mode: 'chatgpt', - tokens: { - account_id: 'acct-other', - access_token: 'other-access', - refresh_token: 'other-refresh', - }, - }), - ); - - expect( - mod.syncCodexSessionAuthBack({ - canonicalAuthPath, - sessionAuthPath, - accountIndex: 0, - }), - ).toBe(false); - expect(fs.readFileSync(canonicalAuthPath, 'utf-8')).toBe(before); - }); -}); - -describe('codex-token-rotation single-account fallback', () => { - let tempHome: string; - - beforeEach(() => { - vi.resetModules(); - tempHome = fs.mkdtempSync(path.join('/tmp', 'ejclaw-codex-fallback-')); - process.env.CODEX_ROT_TEST_HOME = tempHome; - }); - - afterEach(() => { - delete process.env.CODEX_ROT_TEST_HOME; - fs.rmSync(tempHome, { recursive: true, force: true }); - }); - - it('uses ~/.codex/auth.json fallback when ~/.codex-accounts is absent', async () => { - const fallbackAuthPath = createDefaultCodexAuth(tempHome); - - const mod = await import('./codex-token-rotation.js'); - mod.initCodexTokenRotation(); - - expect(mod.getCodexAccountCount()).toBe(1); - expect(mod.getActiveCodexAuthPath()).toBe(fallbackAuthPath); - expect(mod.getAllCodexAccounts()).toEqual([ - expect.objectContaining({ - index: 0, - accountId: 'default-acct', - isActive: true, - }), - ]); - }); -}); - -describe('codex-token-rotation waitForCodexAuthLease (single account)', () => { - let tempHome: string; - - beforeEach(() => { - vi.resetModules(); - tempHome = fs.mkdtempSync(path.join('/tmp', 'ejclaw-codex-rot-')); - process.env.CODEX_ROT_TEST_HOME = tempHome; - createFakeAccounts(tempHome, 1); - }); - - afterEach(() => { - delete process.env.CODEX_ROT_TEST_HOME; - fs.rmSync(tempHome, { recursive: true, force: true }); - }); - - it('reports lease availability synchronously', async () => { - const mod = await import('./codex-token-rotation.js'); - mod.initCodexTokenRotation(); - expect(mod.isCodexAuthLeaseAvailable()).toBe(true); - const held = mod.claimCodexAuthLease(); - expect(mod.isCodexAuthLeaseAvailable()).toBe(false); - held?.release(); - expect(mod.isCodexAuthLeaseAvailable()).toBe(true); - }); - - it('returns immediately when the account is free', async () => { - const mod = await import('./codex-token-rotation.js'); - mod.initCodexTokenRotation(); - const sleep = vi.fn(async () => {}); - - await expect(mod.waitForCodexAuthLease({ sleep })).resolves.toBe(true); - expect(sleep).not.toHaveBeenCalled(); - }); - - it('waits for a concurrent run to release the lease instead of failing', async () => { - const mod = await import('./codex-token-rotation.js'); - mod.initCodexTokenRotation(); - - // Another room's Codex run holds the only account. Before the wait, a - // second claim fails outright — that was the skipped-review bug. - const held = mod.claimCodexAuthLease(); - expect(held).not.toBeNull(); - expect(mod.claimCodexAuthLease()).toBeNull(); - - let polls = 0; - const sleep = vi.fn(async () => { - polls += 1; - if (polls === 3) held?.release(); - }); - - await expect(mod.waitForCodexAuthLease({ sleep, pollMs: 1 })).resolves.toBe( - true, - ); - expect(polls).toBe(3); - - const next = mod.claimCodexAuthLease(); - expect(next).not.toBeNull(); - next?.release(); - }); - - it('gives up after the timeout while the lease stays held', async () => { - const mod = await import('./codex-token-rotation.js'); - mod.initCodexTokenRotation(); - const held = mod.claimCodexAuthLease(); - try { - await expect( - mod.waitForCodexAuthLease({ - timeoutMs: 0, - sleep: async () => {}, - }), - ).resolves.toBe(false); - } finally { - held?.release(); - } - }); - - it('does not wait when the account is exhausted rather than leased', async () => { - const mod = await import('./codex-token-rotation.js'); - mod.initCodexTokenRotation(); - mod.updateCodexAccountUsage(80, undefined, 0, 100, undefined); - const sleep = vi.fn(async () => {}); - - await expect(mod.waitForCodexAuthLease({ sleep })).resolves.toBe(false); - expect(sleep).not.toHaveBeenCalled(); - }); -}); diff --git a/src/codex-token-rotation.ts b/src/codex-token-rotation.ts deleted file mode 100644 index 639d35f..0000000 --- a/src/codex-token-rotation.ts +++ /dev/null @@ -1,999 +0,0 @@ -/** - * Codex OAuth Token Rotation - * - * Rotates between multiple Codex (ChatGPT) OAuth accounts when - * rate-limited. Each account is stored as a separate auth.json in - * ~/.codex-accounts/{n}/auth.json. - * - * The active account's auth.json is copied to the session directory - * before each agent spawn (existing behavior in agent-runner-environment). - * On rate-limit, we rotate to the next account. - */ - -import fs from 'fs'; -import os from 'os'; -import path from 'path'; - -import { - classifyAgentError, - classifyCodexAuthError, - isCodexPoolUnavailableError, - type CodexRotationReason, -} from './agent-error-detection.js'; -import { DATA_DIR } from './config.js'; -import { logger } from './logger.js'; -import { - computeCooldownUntil, - parseRetryAfterFromError, -} from './token-rotation-base.js'; -import { readJsonFile, writeJsonFile } from './utils.js'; - -const STATE_FILE = path.join(DATA_DIR, 'codex-rotation-state.json'); - -interface CodexAccount { - index: number; - authPath: string; - accountId: string; - authFileMtimeMs: number; - planType: string; - subscriptionUntil: string | null; - rateLimitedUntil: number | null; - authStatus: 'healthy' | 'dead_auth'; - authDeadAt: number | null; - authDeadReason: string | null; - leasedUntil: number | null; - leaseId: string | null; - lastUsagePct?: number; - lastUsageD7Pct?: number; - resetAt?: string; - resetD7At?: string; -} - -export interface CodexAuthLease { - accountIndex: number; - authPath: string; - release: () => void; -} - -export type CodexRotationTriggerResult = - | { - shouldRotate: false; - reason: ''; - } - | { - shouldRotate: true; - reason: CodexRotationReason; - }; - -function parseJwtAuth(idToken: string): { - planType: string; - expiresAt: string | null; -} { - try { - const parts = idToken.split('.'); - if (parts.length < 2) return { planType: '?', expiresAt: null }; - const payload = JSON.parse( - Buffer.from(parts[1], 'base64url').toString('utf-8'), - ); - const auth = payload?.['https://api.openai.com/auth'] || {}; - return { - planType: auth.chatgpt_plan_type || '?', - expiresAt: auth.chatgpt_subscription_active_until || null, - }; - } catch { - return { planType: '?', expiresAt: null }; - } -} - -const accounts: CodexAccount[] = []; -let currentIndex = 0; -let initialized = false; - -const CODEX_AUTH_LEASE_MS = 2 * 60 * 60_000; - -const ACCOUNTS_DIR = path.join(os.homedir(), '.codex-accounts'); -const DEFAULT_CODEX_DIR = path.join(os.homedir(), '.codex'); -const DEFAULT_AUTH_PATH = path.join(DEFAULT_CODEX_DIR, 'auth.json'); - -function readAuthFileMtimeMs(authPath: string): number { - try { - return fs.statSync(authPath).mtimeMs; - } catch { - return 0; - } -} - -function loadCodexAccount( - authPath: string, - fallbackAccountId: string, -): boolean { - const data = readJsonFile<{ - tokens?: { account_id?: string; id_token?: string }; - }>(authPath); - if (!data) { - logger.warn({ authPath }, 'Failed to parse codex account auth.json'); - return false; - } - - const accountId = data?.tokens?.account_id || fallbackAccountId; - const jwt = parseJwtAuth(data?.tokens?.id_token || ''); - accounts.push({ - index: accounts.length, - authPath, - accountId, - authFileMtimeMs: readAuthFileMtimeMs(authPath), - planType: jwt.planType, - subscriptionUntil: jwt.expiresAt, - rateLimitedUntil: null, - authStatus: 'healthy', - authDeadAt: null, - authDeadReason: null, - leasedUntil: null, - leaseId: null, - }); - return true; -} - -export function initCodexTokenRotation(): void { - if (initialized) return; - initialized = true; - - const hasAccountsDir = fs.existsSync(ACCOUNTS_DIR); - const dirs = hasAccountsDir - ? fs - .readdirSync(ACCOUNTS_DIR) - .filter((d) => /^\d+$/.test(d)) - .sort((a, b) => parseInt(a) - parseInt(b)) - : []; - - if (!hasAccountsDir) { - logger.info({ dir: ACCOUNTS_DIR }, 'Codex accounts dir not found'); - } - - for (const dir of dirs) { - const authPath = path.join(ACCOUNTS_DIR, dir, 'auth.json'); - if (!fs.existsSync(authPath)) continue; - loadCodexAccount(authPath, `account-${dir}`); - } - - if (dirs.length === 0 && fs.existsSync(DEFAULT_AUTH_PATH)) { - if (loadCodexAccount(DEFAULT_AUTH_PATH, 'default-account')) { - logger.info( - { authPath: DEFAULT_AUTH_PATH }, - 'Codex accounts dir absent/empty; using ~/.codex/auth.json fallback', - ); - } - } - - if (accounts.length > 1) loadCodexState(); - logger.info( - { count: accounts.length, dir: ACCOUNTS_DIR, activeIndex: currentIndex }, - `Codex token rotation: ${accounts.length} account(s) found`, - ); -} - -function saveCodexState(): void { - try { - const state = { - currentIndex, - rateLimits: accounts.map((a) => a.rateLimitedUntil), - authDeadAts: accounts.map((a) => a.authDeadAt), - authDeadReasons: accounts.map((a) => a.authDeadReason), - usagePcts: accounts.map((a) => a.lastUsagePct ?? null), - usageD7Pcts: accounts.map((a) => a.lastUsageD7Pct ?? null), - resetAts: accounts.map((a) => a.resetAt ?? null), - resetD7Ats: accounts.map((a) => a.resetD7At ?? null), - }; - writeJsonFile(STATE_FILE, state); - } catch (err) { - logger.warn( - { stateFile: STATE_FILE, err }, - 'Failed to persist Codex rotation state', - ); - } -} - -function loadCodexState(quiet = false): void { - const state = readJsonFile<{ - currentIndex?: number; - rateLimits?: (number | null)[]; - authDeadAts?: (number | null)[]; - authDeadReasons?: (string | null)[]; - usagePcts?: (number | null)[]; - usageD7Pcts?: (number | null)[]; - resetAts?: (string | null)[]; - resetD7Ats?: (string | null)[]; - }>(STATE_FILE); - if (!state) return; - - const now = Date.now(); - let restoredDeadAuth = false; - if ( - typeof state.currentIndex === 'number' && - state.currentIndex < accounts.length - ) { - currentIndex = state.currentIndex; - } - if (Array.isArray(state.rateLimits)) { - for ( - let i = 0; - i < Math.min(state.rateLimits.length, accounts.length); - i++ - ) { - const until = state.rateLimits[i]; - if (typeof until === 'number' && until > now) { - accounts[i].rateLimitedUntil = until; - } else { - accounts[i].rateLimitedUntil = null; - } - } - } - if (Array.isArray(state.authDeadAts)) { - for ( - let i = 0; - i < Math.min(state.authDeadAts.length, accounts.length); - i++ - ) { - const deadAt = state.authDeadAts[i]; - const acct = accounts[i]; - if (typeof deadAt === 'number' && deadAt > 0) { - const currentMtime = readAuthFileMtimeMs(acct.authPath); - acct.authFileMtimeMs = currentMtime; - if (currentMtime > deadAt) { - acct.authStatus = 'dead_auth'; - acct.authDeadAt = deadAt; - acct.authDeadReason = state.authDeadReasons?.[i] ?? 'auth-expired'; - restoredDeadAuth = - restoreDeadAuthIfAuthFileChanged(acct) || restoredDeadAuth; - } else { - acct.authStatus = 'dead_auth'; - acct.authDeadAt = deadAt; - acct.authDeadReason = state.authDeadReasons?.[i] ?? 'auth-expired'; - acct.rateLimitedUntil = null; - } - } - } - } - if ( - currentIndex < accounts.length && - accounts[currentIndex]?.authStatus === 'dead_auth' - ) { - const nextIdx = findNextCodexAvailable(currentIndex); - if (nextIdx !== null) currentIndex = nextIdx; - } - if (Array.isArray(state.usagePcts)) { - for ( - let i = 0; - i < Math.min(state.usagePcts.length, accounts.length); - i++ - ) { - accounts[i].lastUsagePct = - typeof state.usagePcts[i] === 'number' - ? state.usagePcts[i]! - : undefined; - } - } - if (Array.isArray(state.usageD7Pcts)) { - for ( - let i = 0; - i < Math.min(state.usageD7Pcts.length, accounts.length); - i++ - ) { - accounts[i].lastUsageD7Pct = - typeof state.usageD7Pcts[i] === 'number' - ? state.usageD7Pcts[i]! - : undefined; - } - } - if (Array.isArray(state.resetAts)) { - for (let i = 0; i < Math.min(state.resetAts.length, accounts.length); i++) { - accounts[i].resetAt = state.resetAts[i] ?? undefined; - } - } - if (Array.isArray(state.resetD7Ats)) { - for ( - let i = 0; - i < Math.min(state.resetD7Ats.length, accounts.length); - i++ - ) { - accounts[i].resetD7At = state.resetD7Ats[i] ?? undefined; - } - } - if (!quiet) { - logger.info( - { currentIndex, accountCount: accounts.length }, - 'Codex rotation state restored', - ); - } - if (restoredDeadAuth) saveCodexState(); -} - -/** Get the auth.json path for the current active account. */ -export function getActiveCodexAuthPath(): string | null { - return getCodexAuthPath(); -} - -/** Find the rotation-array index that owns the given auth.json path. */ -export function findCodexAccountIndexByAuthPath( - authPath: string, -): number | null { - for (let i = 0; i < accounts.length; i += 1) { - if (accounts[i]?.authPath === authPath) return i; - } - return null; -} - -/** Manually switch the active codex account. Clears its rate-limit cooldown. */ -export function setCurrentCodexAccountIndex(targetIndex: number): void { - if (accounts.length === 0) { - throw new Error('codex token rotation: no accounts loaded'); - } - if ( - !Number.isInteger(targetIndex) || - targetIndex < 0 || - targetIndex >= accounts.length - ) { - throw new Error( - `codex switch: index ${targetIndex} out of range [0..${accounts.length - 1}]`, - ); - } - if (targetIndex === currentIndex) return; - const previous = currentIndex; - currentIndex = targetIndex; - // Clear rate-limit on the chosen account so rotation logic doesn't bounce it. - accounts[targetIndex].rateLimitedUntil = null; - saveCodexState(); - logger.info( - { - transition: 'rotation:manual-switch', - fromIndex: previous, - toIndex: currentIndex, - totalAccounts: accounts.length, - }, - `Codex switched manually to account #${currentIndex + 1}/${accounts.length}`, - ); -} - -export function getCodexAuthPath( - accountIndex: number = currentIndex, -): string | null { - if (accounts.length === 0) return null; - return accounts[accountIndex]?.authPath ?? null; -} - -function codexLockPath(authPath: string): string { - return path.join(path.dirname(authPath), '.ejclaw-auth.lock'); -} - -function isPidAlive(pid: number): boolean { - try { - process.kill(pid, 0); - return true; - } catch { - return false; - } -} - -function readExistingLease(lockPath: string): { - leaseId?: string; - pid?: number; - expiresAt?: number; -} | null { - const data = readJsonFile<{ - leaseId?: string; - pid?: number; - expiresAt?: number; - }>(lockPath); - return data ?? null; -} - -function tryAcquireDiskLease( - acct: CodexAccount, - leaseId: string, - now: number, -): boolean { - const lockPath = codexLockPath(acct.authPath); - const payload = JSON.stringify( - { - leaseId, - pid: process.pid, - accountIndex: acct.index, - createdAt: now, - expiresAt: now + CODEX_AUTH_LEASE_MS, - }, - null, - 2, - ); - - try { - fs.writeFileSync(lockPath, payload, { flag: 'wx', mode: 0o600 }); - return true; - } catch (err) { - if ((err as NodeJS.ErrnoException).code !== 'EEXIST') return false; - } - - const existing = readExistingLease(lockPath); - const expired = Boolean(existing?.expiresAt && existing.expiresAt <= now); - const deadPid = Boolean(existing?.pid && !isPidAlive(existing.pid)); - if (!expired && !deadPid) return false; - - try { - fs.unlinkSync(lockPath); - } catch { - return false; - } - - try { - fs.writeFileSync(lockPath, payload, { flag: 'wx', mode: 0o600 }); - return true; - } catch { - return false; - } -} - -function releaseDiskLease(authPath: string, leaseId: string): void { - const lockPath = codexLockPath(authPath); - const existing = readExistingLease(lockPath); - if (existing?.leaseId && existing.leaseId !== leaseId) return; - try { - fs.unlinkSync(lockPath); - } catch { - // Best effort only. Expired/stale locks are cleared by the next claimant. - } -} - -function isCodexAccountUsable( - acct: CodexAccount, - now = Date.now(), - opts?: { ignoreRateLimits?: boolean; ignoreD7?: boolean }, -): boolean { - if (restoreDeadAuthIfAuthFileChanged(acct)) saveCodexState(); - if (acct.authStatus === 'dead_auth') return false; - if ( - !opts?.ignoreRateLimits && - acct.rateLimitedUntil && - acct.rateLimitedUntil > now - ) { - return false; - } - if ( - !opts?.ignoreD7 && - acct.lastUsageD7Pct != null && - acct.lastUsageD7Pct >= 100 - ) { - return false; - } - if (acct.leasedUntil && acct.leasedUntil > now) return false; - - const existing = readExistingLease(codexLockPath(acct.authPath)); - if (!existing) return true; - if (existing.expiresAt && existing.expiresAt <= now) return true; - if (existing.pid && !isPidAlive(existing.pid)) return true; - return false; -} - -function restoreDeadAuthIfAuthFileChanged(acct: CodexAccount): boolean { - if (acct.authStatus !== 'dead_auth' || !acct.authDeadAt) return false; - const currentMtime = readAuthFileMtimeMs(acct.authPath); - acct.authFileMtimeMs = currentMtime; - if (currentMtime <= acct.authDeadAt) return false; - - const previousDeadAt = acct.authDeadAt; - acct.authStatus = 'healthy'; - acct.authDeadAt = null; - acct.authDeadReason = null; - acct.rateLimitedUntil = null; - logger.info( - { - transition: 'rotation:auth-file-refreshed', - accountIndex: acct.index, - previousDeadAt: new Date(previousDeadAt).toISOString(), - authFileMtime: new Date(currentMtime).toISOString(), - }, - `Codex account #${acct.index + 1}/${accounts.length} marked healthy after auth.json refresh`, - ); - return true; -} - -function markCodexAccountDeadAuth(acct: CodexAccount, reason?: string): void { - acct.authStatus = 'dead_auth'; - acct.authDeadAt = Date.now(); - acct.authDeadReason = reason || 'auth-expired'; - acct.rateLimitedUntil = null; - acct.leasedUntil = null; - acct.leaseId = null; - logger.warn( - { - transition: 'rotation:dead-auth', - accountIndex: acct.index, - accountId: acct.accountId, - reason: acct.authDeadReason, - }, - `Codex account #${acct.index + 1}/${accounts.length} marked dead; re-auth required`, - ); -} - -function updateAccountMetadataFromAuthFile(acct: CodexAccount): void { - const data = readJsonFile<{ - tokens?: { account_id?: string; id_token?: string }; - }>(acct.authPath); - if (data?.tokens?.account_id) acct.accountId = data.tokens.account_id; - const jwt = parseJwtAuth(data?.tokens?.id_token || ''); - acct.planType = jwt.planType; - acct.subscriptionUntil = jwt.expiresAt; - acct.authFileMtimeMs = readAuthFileMtimeMs(acct.authPath); -} - -function isCodexAccountLeasedByLiveRun( - acct: CodexAccount, - now: number, -): boolean { - if (acct.leasedUntil && acct.leasedUntil > now) return true; - const existing = readExistingLease(codexLockPath(acct.authPath)); - if (!existing) return false; - if (existing.expiresAt && existing.expiresAt <= now) return false; - if (existing.pid && !isPidAlive(existing.pid)) return false; - return true; -} - -/** Synchronous check: can a Codex lease be claimed right now? */ -export function isCodexAuthLeaseAvailable(): boolean { - if (accounts.length === 0) return true; - const now = Date.now(); - return accounts.some((acct) => isCodexAccountUsable(acct, now)); -} - -export const CODEX_AUTH_LEASE_WAIT_MAX_MS = 15 * 60_000; -const CODEX_AUTH_LEASE_WAIT_POLL_MS = 2_000; - -/** - * Wait until a Codex account can be leased. - * - * The lease is exclusive per account so two Codex processes never rotate the - * same refresh token at once. With a single account that also serializes every - * Codex run, and claimCodexAuthLease() fails immediately while another room's - * Codex run holds it — which silently skipped reviews (task closed as - * reviewer_codex_unavailable) whenever two rooms needed Codex at the same time. - * - * Only waits when the sole obstacle is a lease held by a live run. A dead or - * rate-limited pool returns false right away so the caller fails fast as before. - */ -export async function waitForCodexAuthLease(opts?: { - timeoutMs?: number; - pollMs?: number; - sleep?: (ms: number) => Promise; -}): Promise { - if (accounts.length === 0) return true; - const timeoutMs = opts?.timeoutMs ?? CODEX_AUTH_LEASE_WAIT_MAX_MS; - const pollMs = opts?.pollMs ?? CODEX_AUTH_LEASE_WAIT_POLL_MS; - const sleep = - opts?.sleep ?? - ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); - const startedAt = Date.now(); - let logged = false; - - for (;;) { - const now = Date.now(); - if (accounts.some((acct) => isCodexAccountUsable(acct, now))) { - if (logged) { - logger.info( - { waitedMs: now - startedAt }, - 'Codex account lease became available after waiting', - ); - } - return true; - } - const blockedOnlyByLease = accounts.some( - (acct) => - isCodexAccountLeasedByLiveRun(acct, now) && - acct.authStatus !== 'dead_auth' && - !(acct.rateLimitedUntil && acct.rateLimitedUntil > now) && - !(acct.lastUsageD7Pct != null && acct.lastUsageD7Pct >= 100), - ); - if (!blockedOnlyByLease || now - startedAt >= timeoutMs) { - if (logged) { - logger.warn( - { waitedMs: now - startedAt, timeoutMs, blockedOnlyByLease }, - 'Gave up waiting for a Codex account lease', - ); - } - return false; - } - if (!logged) { - logger.info( - { timeoutMs }, - 'Codex account is leased by another run; waiting before launching Codex', - ); - logged = true; - } - await sleep(pollMs); - } -} - -/** - * Lease one specific account for a short side task (usage polling). - * - * Unlike claimCodexAuthLease() this ignores rate limits (polling a limited - * account is how its reset time is learned) and never rotates to another - * account. Returns null when that account is already leased by a live run, so - * the caller can simply skip — the lease exists so two Codex processes never - * refresh the same token concurrently. - */ -export function claimCodexAuthLeaseForAccount( - accountIndex: number, -): CodexAuthLease | null { - const acct = accounts.find((a) => a.index === accountIndex); - if (!acct) return null; - const now = Date.now(); - if (isCodexAccountLeasedByLiveRun(acct, now)) return null; - const leaseId = `${process.pid}-${now}-${acct.index}-poll-${Math.random() - .toString(36) - .slice(2)}`; - if (!tryAcquireDiskLease(acct, leaseId, now)) return null; - acct.leasedUntil = now + CODEX_AUTH_LEASE_MS; - acct.leaseId = leaseId; - return { - accountIndex: acct.index, - authPath: acct.authPath, - release: () => { - if (acct.leaseId === leaseId) { - acct.leasedUntil = null; - acct.leaseId = null; - } - releaseDiskLease(acct.authPath, leaseId); - }, - }; -} - -export function claimCodexAuthLease(): CodexAuthLease | null { - if (accounts.length === 0) return null; - const now = Date.now(); - const attempts = accounts.length; - for (let offset = 0; offset < attempts; offset += 1) { - const idx = (currentIndex + offset) % accounts.length; - const acct = accounts[idx]; - if (!isCodexAccountUsable(acct, now)) continue; - const leaseId = `${process.pid}-${now}-${idx}-${Math.random() - .toString(36) - .slice(2)}`; - if (!tryAcquireDiskLease(acct, leaseId, now)) continue; - currentIndex = idx; - acct.leasedUntil = now + CODEX_AUTH_LEASE_MS; - acct.leaseId = leaseId; - return { - accountIndex: idx, - authPath: acct.authPath, - release: () => { - if (acct.leaseId === leaseId) { - acct.leasedUntil = null; - acct.leaseId = null; - } - releaseDiskLease(acct.authPath, leaseId); - }, - }; - } - return null; -} - -export function syncCodexSessionAuthBack(args: { - canonicalAuthPath: string; - sessionAuthPath: string; - accountIndex?: number | null; -}): boolean { - if (!fs.existsSync(args.sessionAuthPath)) return false; - if (!fs.existsSync(args.canonicalAuthPath)) return false; - - const canonical = readJsonFile<{ - auth_mode?: string; - tokens?: { account_id?: string }; - }>(args.canonicalAuthPath); - const session = readJsonFile<{ - auth_mode?: string; - tokens?: { account_id?: string }; - }>(args.sessionAuthPath); - if (!canonical || !session?.tokens) return false; - - const canonicalAccount = canonical.tokens?.account_id; - const sessionAccount = session.tokens.account_id; - if ( - canonicalAccount && - sessionAccount && - canonicalAccount !== sessionAccount - ) { - logger.warn( - { - canonicalAuthPath: args.canonicalAuthPath, - sessionAuthPath: args.sessionAuthPath, - accountIndex: args.accountIndex ?? null, - }, - 'Refusing to sync Codex session auth back: account mismatch', - ); - return false; - } - - const sessionRaw = fs.readFileSync(args.sessionAuthPath, 'utf-8'); - const canonicalRaw = fs.readFileSync(args.canonicalAuthPath, 'utf-8'); - if (sessionRaw === canonicalRaw) return false; - - const tmpPath = `${args.canonicalAuthPath}.tmp-${process.pid}-${Date.now()}`; - fs.writeFileSync(tmpPath, sessionRaw, { mode: 0o600 }); - fs.renameSync(tmpPath, args.canonicalAuthPath); - - const idx = - args.accountIndex ?? - findCodexAccountIndexByAuthPath(args.canonicalAuthPath); - if (idx != null && accounts[idx]) { - const acct = accounts[idx]; - acct.authStatus = 'healthy'; - acct.authDeadAt = null; - acct.authDeadReason = null; - updateAccountMetadataFromAuthFile(acct); - saveCodexState(); - } - - logger.info( - { - accountIndex: idx, - canonicalAuthPath: args.canonicalAuthPath, - }, - 'Synced refreshed Codex session auth back to canonical account slot', - ); - return true; -} - -export function detectCodexRotationTrigger( - error?: string | null, -): CodexRotationTriggerResult { - if (!error) return { shouldRotate: false, reason: '' }; - if (isCodexPoolUnavailableError(error)) { - return { shouldRotate: false, reason: '' }; - } - - // Common patterns (429, 503, network) — delegated to SSOT - const common = classifyAgentError(error); - if (common.category !== 'none') { - return { shouldRotate: true, reason: common.reason }; - } - - // Codex-specific loose auth check - const auth = classifyCodexAuthError(error); - if (auth.category !== 'none') { - return { shouldRotate: true, reason: auth.reason }; - } - - return { shouldRotate: false, reason: '' }; -} - -/** - * Try to rotate to the next available Codex account. - * Returns true if a fresh account was found. - */ -export function rotateCodexToken( - errorMessage?: string, - opts?: { ignoreRateLimits?: boolean }, -): boolean { - if (accounts.length <= 1) return false; - - if (isCodexPoolUnavailableError(errorMessage)) { - logger.warn( - { - transition: 'rotation:skip-pool-unavailable-sentinel', - currentIndex, - totalAccounts: accounts.length, - reason: errorMessage ?? null, - }, - 'Refusing to mark Codex accounts unhealthy from internal pool-unavailable sentinel', - ); - return false; - } - - const previousIndex = currentIndex; - const acct = accounts[currentIndex]; - const authFailure = classifyCodexAuthError(errorMessage); - let cooldownUntil: number | null = null; - - if (authFailure.category === 'auth-expired') { - markCodexAccountDeadAuth(acct, errorMessage || authFailure.reason); - } else { - cooldownUntil = computeCooldownUntil(errorMessage); - acct.rateLimitedUntil = cooldownUntil; - acct.lastUsagePct = 100; - // Extract reset time string from error for display - const retryAt = parseRetryAfterFromError(errorMessage); - if (retryAt) { - acct.resetAt = new Date(retryAt).toISOString(); - } - } - - const nextIdx = findNextCodexAvailable(currentIndex, opts); - if (nextIdx !== null) { - accounts[nextIdx].rateLimitedUntil = null; - currentIndex = nextIdx; - logger.info( - { - transition: 'rotation:execute', - fromIndex: previousIndex, - toIndex: currentIndex, - totalAccounts: accounts.length, - accountId: accounts[nextIdx].accountId, - ignoreRL: opts?.ignoreRateLimits ?? false, - cooldownUntil: - cooldownUntil != null ? new Date(cooldownUntil).toISOString() : null, - authDead: authFailure.category === 'auth-expired', - reason: errorMessage ?? null, - }, - `Codex rotated to account #${currentIndex + 1}/${accounts.length}`, - ); - saveCodexState(); - return true; - } - - logger.warn( - { - transition: 'rotation:skip', - fromIndex: previousIndex, - totalAccounts: accounts.length, - ignoreRL: opts?.ignoreRateLimits ?? false, - cooldownUntil: - cooldownUntil != null ? new Date(cooldownUntil).toISOString() : null, - authDead: authFailure.category === 'auth-expired', - reason: errorMessage ?? null, - }, - authFailure.category === 'auth-expired' - ? 'All Codex accounts unavailable after auth failure; re-auth required' - : 'All Codex accounts are rate-limited', - ); - saveCodexState(); - return false; -} - -/** - * Find the next Codex account that is neither rate-limited nor 7d-exhausted. - */ -function findNextCodexAvailable( - fromIndex?: number, - opts?: { ignoreRateLimits?: boolean }, -): number | null { - const now = Date.now(); - const start = fromIndex ?? currentIndex; - for (let i = 1; i < accounts.length; i++) { - const idx = (start + i) % accounts.length; - const acct = accounts[idx]; - if (isCodexAccountUsable(acct, now, opts)) return idx; - } - // All d7-exhausted — fall back to rate-limit/dead/lease checks only. - for (let i = 1; i < accounts.length; i++) { - const idx = (start + i) % accounts.length; - const acct = accounts[idx]; - if (isCodexAccountUsable(acct, now, { ...opts, ignoreD7: true })) { - return idx; - } - } - return null; -} - -/** - * Advance to the next healthy account (round-robin). - * Called after each successful request to spread load evenly - * and keep usage data fresh for all accounts. - * Skips accounts with 7d usage ≥ 100% to avoid API billing. - */ -export function advanceCodexAccount(): void { - if (accounts.length <= 1) return; - const nextIdx = findNextCodexAvailable(); - if (nextIdx !== null) { - currentIndex = nextIdx; - saveCodexState(); - } - // All others rate-limited/exhausted, stay on current -} - -/** - * Update cached usage info for a specific account (or current if index omitted). - */ -export function updateCodexAccountUsage( - usagePct: number, - resetAt?: string, - accountIndex?: number, - d7Pct?: number, - resetD7At?: string, -): void { - if (accounts.length === 0) return; - const idx = accountIndex ?? currentIndex; - const acct = accounts[idx]; - if (acct) { - acct.lastUsagePct = usagePct; - if (d7Pct != null) acct.lastUsageD7Pct = d7Pct; - if (resetAt) acct.resetAt = resetAt; - if (resetD7At) acct.resetD7At = resetD7At; - saveCodexState(); - - // Auto-rotate away from 7d-exhausted current account to avoid API billing - if ( - idx === currentIndex && - d7Pct != null && - d7Pct >= 100 && - accounts.length > 1 - ) { - const nextIdx = findNextCodexAvailable(idx); - if (nextIdx !== null && nextIdx !== idx) { - logger.info( - { - transition: 'rotation:auto', - fromIndex: idx, - toIndex: nextIdx, - d7Pct, - accountId: acct.accountId, - }, - `Codex auto-rotating: account #${idx + 1} at ${d7Pct}% 7d → #${nextIdx + 1}`, - ); - currentIndex = nextIdx; - saveCodexState(); - } - } - } -} - -export function markCodexTokenHealthy(): void { - if (accounts.length === 0) return; - const acct = accounts[currentIndex]; - let changed = false; - if (acct?.authStatus === 'dead_auth') { - acct.authStatus = 'healthy'; - acct.authDeadAt = null; - acct.authDeadReason = null; - changed = true; - } - if (acct?.rateLimitedUntil) { - const previousCooldownUntil = acct.rateLimitedUntil; - acct.rateLimitedUntil = null; - changed = true; - logger.info( - { - transition: 'rotation:clear-rate-limit', - accountIndex: currentIndex, - accountId: acct.accountId, - cooldownUntil: new Date(previousCooldownUntil).toISOString(), - }, - 'Cleared Codex account rate-limit state after successful response', - ); - } - if (changed) saveCodexState(); -} - -export function getCodexAccountCount(): number { - return accounts.length; -} - -export function getAllCodexAccounts(): { - index: number; - accountId: string; - planType: string; - isActive: boolean; - isRateLimited: boolean; - isAuthDead?: boolean; - authStatus?: 'healthy' | 'dead_auth'; - authDeadAt?: string; - isLeased?: boolean; - cachedUsagePct?: number; - cachedUsageD7Pct?: number; - resetAt?: string; - resetD7At?: string; -}[] { - const now = Date.now(); - return accounts.map((a, i) => ({ - index: i, - accountId: a.accountId, - planType: a.planType, - isActive: i === currentIndex, - isRateLimited: Boolean(a.rateLimitedUntil && a.rateLimitedUntil > now), - isAuthDead: a.authStatus === 'dead_auth', - authStatus: a.authStatus, - authDeadAt: a.authDeadAt ? new Date(a.authDeadAt).toISOString() : undefined, - isLeased: Boolean(a.leasedUntil && a.leasedUntil > now), - cachedUsagePct: a.lastUsagePct, - cachedUsageD7Pct: a.lastUsageD7Pct, - resetAt: a.resetAt, - resetD7At: a.resetD7At, - })); -} diff --git a/src/codex-usage-collector.test.ts b/src/codex-usage-collector.test.ts index 87f4a32..00debf7 100644 --- a/src/codex-usage-collector.test.ts +++ b/src/codex-usage-collector.test.ts @@ -139,13 +139,14 @@ describe('codex-usage-collector fallback account usage', () => { }) as never; }) as unknown as typeof childProcess.spawn); - const rotation = await import('./codex-token-rotation.js'); + const codexAuth = await import('./codex-auth.js'); const usage = await import('./codex-usage-collector.js'); - rotation.initCodexTokenRotation(); - const result = await usage.refreshActiveCodexUsage(); + const result = await usage.refreshCodexUsage(); - expect(rotation.getCodexAccountCount()).toBe(1); + expect(codexAuth.getCodexAuthPath()).toBe( + path.join(fallbackCodexHome, 'auth.json'), + ); expect(capturedCodexHome).toBe(fallbackCodexHome); expect(result.fetchedAt).toEqual(expect.any(String)); expect(result.rows).toEqual([ @@ -176,10 +177,8 @@ describe('codex-usage-collector fallback account usage', () => { }) as never; }) as unknown as typeof childProcess.spawn); - const rotation = await import('./codex-token-rotation.js'); const usage = await import('./codex-usage-collector.js'); - rotation.initCodexTokenRotation(); - await usage.refreshActiveCodexUsage(); + await usage.refreshCodexUsage(); expect(captured).not.toBeNull(); expect(captured!.cmd).toBe(process.execPath); @@ -203,13 +202,12 @@ describe('codex-usage-collector fallback account usage', () => { throw new Error('must not spawn while the account is leased'); }) as unknown as typeof childProcess.spawn); - const rotation = await import('./codex-token-rotation.js'); + const codexAuth = await import('./codex-auth.js'); const usage = await import('./codex-usage-collector.js'); - rotation.initCodexTokenRotation(); - const held = rotation.claimCodexAuthLease(); + const held = codexAuth.claimCodexAuthLease(); expect(held).not.toBeNull(); try { - const result = await usage.refreshActiveCodexUsage(); + const result = await usage.refreshCodexUsage(); expect(result.fetchedAt).toBeNull(); expect(childProcess.spawn).not.toHaveBeenCalled(); } finally { @@ -241,11 +239,9 @@ describe('codex-usage-collector fallback account usage', () => { }) as never; }) as unknown as typeof childProcess.spawn); - const rotation = await import('./codex-token-rotation.js'); const usage = await import('./codex-usage-collector.js'); - rotation.initCodexTokenRotation(); - const result = await usage.refreshActiveCodexUsage(); + const result = await usage.refreshCodexUsage(); // Usage must be applied (not swallowed by a TypeError), and the lone weekly // window is shown as 7d while the missing 5h window renders as unknown. @@ -317,11 +313,9 @@ describe('codex-usage-collector fallback account usage', () => { }) as unknown as typeof childProcess.spawn); try { - const rotation = await import('./codex-token-rotation.js'); const usage = await import('./codex-usage-collector.js'); - rotation.initCodexTokenRotation(); - const result = await usage.refreshActiveCodexUsage(); + const result = await usage.refreshCodexUsage(); expect(result.fetchedAt).toEqual(expect.any(String)); expect(result.rows).toEqual([ diff --git a/src/codex-usage-collector.ts b/src/codex-usage-collector.ts index 0032204..02a7d8e 100644 --- a/src/codex-usage-collector.ts +++ b/src/codex-usage-collector.ts @@ -4,11 +4,11 @@ import os from 'os'; import path from 'path'; import { - claimCodexAuthLeaseForAccount, - getAllCodexAccounts, + claimCodexUsagePollLease, + getCodexAccountStatus, getCodexAuthPath, - updateCodexAccountUsage, -} from './codex-token-rotation.js'; + updateCodexUsage, +} from './codex-auth.js'; import { formatResetRemaining, type UsageRow } from './dashboard-usage-rows.js'; import { logger } from './logger.js'; @@ -33,13 +33,10 @@ export interface CodexRateLimit { */ export interface CodexUsageRefreshResult { rows: UsageRow[]; - /** Non-null only when at least one account was successfully fetched. */ + /** Non-null only when usage was successfully fetched. */ fetchedAt: string | null; } -/** Full scan interval — exported so the orchestrator can schedule it. */ -export const CODEX_FULL_SCAN_INTERVAL = 3_600_000; // 1 hour - /** Coerce a string-or-number resetsAt (numeric epoch in seconds) to ISO. */ function toIsoMaybe(value: string | number | undefined): string | undefined { if (value == null) return undefined; @@ -121,12 +118,6 @@ function resolveCodexAppServerCommand(): { command: string; args: string[] } { return { command: findCodexBinary(), args: ['app-server'] }; } -function getCodexHomeForAccount(accountIndex?: number): string | null { - const authPath = getCodexAuthPath(accountIndex); - if (!authPath || !fs.existsSync(authPath)) return null; - return path.dirname(authPath); -} - export async function fetchCodexUsage( codexHomeOverride?: string, ): Promise { @@ -228,32 +219,26 @@ export async function fetchCodexUsage( /** * Extract usage percentages from the primary 'codex' rate-limit bucket - * and update the rotation state for a given account. + * and cache them for the account. * * Bucket selection: * 1. limitId === 'codex' → use it * 2. No 'codex' bucket + single bucket → use it * 3. No 'codex' bucket + multiple buckets → unknown (show —) - * - * All buckets are logged at info level for observability. */ -export function applyCodexUsageToAccount( - usage: CodexRateLimit[], - accountIndex: number, -): void { +export function applyCodexUsage(usage: CodexRateLimit[]): void { if (usage.length === 0) return; // Per-bucket detail; the one-line usage summary below stays at info. logger.debug( { - account: accountIndex + 1, buckets: usage.map((l) => ({ id: l.limitId, h5: l.primary?.usedPercent ?? null, d7: l.secondary?.usedPercent ?? null, })), }, - `Codex account #${accountIndex + 1}: ${usage.length} rate-limit bucket(s)`, + `Codex: ${usage.length} rate-limit bucket(s)`, ); // Select the effective bucket @@ -263,10 +248,9 @@ export function applyCodexUsageToAccount( if (!effective) { // Multiple unknown buckets — cannot determine which is authoritative logger.warn( - { account: accountIndex + 1 }, - `Codex account #${accountIndex + 1}: no 'codex' bucket found among ${usage.length} buckets, showing unknown`, + `Codex: no 'codex' bucket found among ${usage.length} buckets, showing unknown`, ); - updateCodexAccountUsage(-1, undefined, accountIndex, -1, undefined); + updateCodexUsage({ usagePct: -1, d7Pct: -1 }); return; } @@ -274,9 +258,8 @@ export function applyCodexUsageToAccount( // (e.g. Plus) return only ONE window in `primary` (a weekly/7d window) with // `secondary: null`. Guard the null so we don't throw, and route a lone // weekly window into the 7d slot so usage still renders. - // Store raw ISO timestamps (not pre-formatted strings) so the exhaustion - // gate can compute "minutes until reset" later. The dashboard render path - // formats these at display time via `formatResetRemaining`. + // Store raw ISO timestamps (not pre-formatted strings); the dashboard render + // path formats these at display time via `formatResetRemaining`. let pct = Math.round(effective.primary.usedPercent); let resetIso = toIsoMaybe(effective.primary.resetsAt); let d7Pct = effective.secondary @@ -295,49 +278,35 @@ export function applyCodexUsageToAccount( pct = -1; resetIso = undefined; } - updateCodexAccountUsage(pct, resetIso, accountIndex, d7Pct, resetD7Iso); + updateCodexUsage({ + usagePct: pct, + resetAt: resetIso, + d7Pct, + resetD7At: resetD7Iso, + }); logger.info( - { - account: accountIndex + 1, - bucket: effective.limitId, - h5: pct, - d7: d7Pct, - reset: resetIso, - }, - `Codex account #${accountIndex + 1} usage: 5h=${pct}% 7d=${d7Pct}%`, + { bucket: effective.limitId, h5: pct, d7: d7Pct, reset: resetIso }, + `Codex usage: 5h=${pct}% 7d=${d7Pct}%`, ); } -/** - * Build display-ready usage rows from Codex rotation state. - * Called after refreshing usage data. - */ +/** Build display-ready usage rows from the cached Codex usage. */ export function buildCodexUsageRowsFromState(): UsageRow[] { - const codexAccounts = getAllCodexAccounts(); - if (codexAccounts.length === 0) return []; - - const isMulti = codexAccounts.length > 1; - return codexAccounts.map((acct) => { - const icon = acct.isActive ? '*' : acct.isRateLimited ? '!' : ' '; - const label = isMulti - ? `Codex${acct.index + 1}${icon} ${acct.planType}` - : 'Codex'; - return { - name: label, + const acct = getCodexAccountStatus(); + if (!acct) return []; + return [ + { + name: 'Codex', h5pct: acct.cachedUsagePct != null ? acct.cachedUsagePct : -1, h5reset: acct.resetAt ? formatResetRemaining(acct.resetAt) : '', d7pct: acct.cachedUsageD7Pct != null ? acct.cachedUsageD7Pct : -1, d7reset: acct.resetD7At ? formatResetRemaining(acct.resetD7At) : '', - }; - }); + }, + ]; } /** - * Scan ALL Codex accounts by spawning app-server with each auth. - * Returns refresh result — caller owns cache state. - */ -/** - * Poll one account's usage while holding that account's auth lease. + * Poll the account's usage while holding its auth lease. * * The usage app-server runs with CODEX_HOME pointed at the account's canonical * auth dir, so it may refresh the token there. Holding the lease keeps it from @@ -345,90 +314,39 @@ export function buildCodexUsageRowsFromState(): UsageRow[] { * (which would leave the reviewer with an already-used refresh token). If a * run holds the lease, skip this poll; the next one will catch up. */ -async function fetchCodexUsageWithLease( - accountIndex: number, - accountDir: string, -): Promise { - const lease = claimCodexAuthLeaseForAccount(accountIndex); +async function fetchCodexUsageWithLease(): Promise { + const lease = claimCodexUsagePollLease(); if (!lease) { logger.debug( - { account: accountIndex + 1 }, 'Skipped Codex usage poll: account is leased by a running Codex turn', ); return null; } try { - return await fetchCodexUsage(accountDir); + return await fetchCodexUsage(path.dirname(lease.authPath)); } finally { lease.release(); } } -export async function refreshAllCodexAccountUsage(): Promise { - const codexAccounts = getAllCodexAccounts(); - if (codexAccounts.length <= 1) { - return { rows: buildCodexUsageRowsFromState(), fetchedAt: null }; - } - - logger.info( - { accountCount: codexAccounts.length }, - 'Scanning all Codex accounts for usage data', - ); - - let anySuccess = false; - for (const acct of codexAccounts) { - const accountDir = getCodexHomeForAccount(acct.index); - if (!accountDir) continue; - - try { - const usage = await fetchCodexUsageWithLease(acct.index, accountDir); - if (usage && Array.isArray(usage) && usage.length > 0) { - applyCodexUsageToAccount(usage, acct.index); - anySuccess = true; - } - } catch (err) { - logger.debug( - { err, account: acct.index + 1 }, - 'Failed to fetch usage for Codex account', - ); - } - } - - return { - rows: buildCodexUsageRowsFromState(), - fetchedAt: anySuccess ? new Date().toISOString() : null, - }; -} - /** - * Quick-refresh the active Codex account's usage. + * Refresh the Codex account's usage. * Returns refresh result — caller owns cache state. */ -export async function refreshActiveCodexUsage(): Promise { - const codexAccounts = getAllCodexAccounts(); - if (codexAccounts.length === 0) { +export async function refreshCodexUsage(): Promise { + if (!getCodexAuthPath()) { return { rows: [], fetchedAt: null }; } - const active = codexAccounts.find((a) => a.isActive); - if (!active) { - return { rows: buildCodexUsageRowsFromState(), fetchedAt: null }; - } - - const accountDir = getCodexHomeForAccount(active.index); - if (!accountDir) { - return { rows: buildCodexUsageRowsFromState(), fetchedAt: null }; - } - let fetchedAt: string | null = null; try { - const usage = await fetchCodexUsageWithLease(active.index, accountDir); + const usage = await fetchCodexUsageWithLease(); if (usage && Array.isArray(usage) && usage.length > 0) { - applyCodexUsageToAccount(usage, active.index); + applyCodexUsage(usage); fetchedAt = new Date().toISOString(); } } catch (err) { - logger.debug({ err }, 'Failed to fetch active Codex account usage'); + logger.debug({ err }, 'Failed to fetch Codex usage'); } return { rows: buildCodexUsageRowsFromState(), fetchedAt }; diff --git a/src/codex-warmup.test.ts b/src/codex-warmup.test.ts index 16a1e42..f2b3a36 100644 --- a/src/codex-warmup.test.ts +++ b/src/codex-warmup.test.ts @@ -8,8 +8,8 @@ vi.mock('child_process', () => ({ spawn: vi.fn(), })); -vi.mock('./codex-token-rotation.js', () => ({ - getAllCodexAccounts: vi.fn(), +vi.mock('./codex-auth.js', () => ({ + getCodexAccountStatus: vi.fn(), getCodexAuthPath: vi.fn(), })); @@ -42,105 +42,84 @@ function createFakeCodexProcess(exitCode = 0): FakeProcess { return proc; } -function authPathFor(tempHome: string, accountIndex: number): string { - return path.join( - tempHome, - '.codex-accounts', - String(accountIndex + 1), - 'auth.json', - ); -} +const baseConfig = { + prompt: 'Reply exactly OK. Do not run tools.', + model: 'gpt-5.5', + minIntervalMs: 18_300_000, + staggerMs: 1_800_000, + maxUsagePct: 0, + maxD7UsagePct: 0, + commandTimeoutMs: 120_000, + failureCooldownMs: 21_600_000, + maxConsecutiveFailures: 2, +}; -describe('Codex warm-up scheduler', () => { +describe('Codex warm-up', () => { let tempHome: string; let statePath: string; + let authPath: string; beforeEach(() => { vi.resetModules(); vi.clearAllMocks(); tempHome = fs.mkdtempSync(path.join('/tmp', 'ejclaw-codex-warmup-')); statePath = path.join(tempHome, 'codex-warmup-state.json'); - for (let i = 0; i < 3; i++) { - const p = authPathFor(tempHome, i); - fs.mkdirSync(path.dirname(p), { recursive: true }); - fs.writeFileSync(p, '{}'); - } + authPath = path.join(tempHome, '.codex-accounts', '0', 'auth.json'); + fs.mkdirSync(path.dirname(authPath), { recursive: true }); + fs.writeFileSync(authPath, '{}'); }); afterEach(() => { fs.rmSync(tempHome, { recursive: true, force: true }); }); - it('warms one eligible zero-usage account with a real codex exec and persists account cooldown state', async () => { + async function setup( + usage: { + cachedUsagePct?: number; + cachedUsageD7Pct?: number; + resetD7At?: string; + }, + exitCode = 0, + ) { const childProcess = await import('child_process'); - const rotation = await import('./codex-token-rotation.js'); + const codexAuth = await import('./codex-auth.js'); const { runCodexWarmupCycle } = await import('./codex-warmup.js'); - const now = new Date('2026-04-24T09:00:00Z').getTime(); - let capturedEnv: Record | undefined; - let capturedArgs: readonly string[] | undefined; - - vi.mocked(rotation.getAllCodexAccounts).mockReturnValue([ - { - index: 0, - accountId: 'busy-account', - planType: 'pro', - isActive: true, - isRateLimited: false, - cachedUsagePct: 14, - cachedUsageD7Pct: 30, - }, - { - index: 1, - accountId: 'rate-limited-account', - planType: 'pro', - isActive: false, - isRateLimited: true, - cachedUsagePct: 0, - cachedUsageD7Pct: 0, - }, - { - index: 2, - accountId: 'fresh-account', - planType: 'team', - isActive: false, - isRateLimited: false, - cachedUsagePct: 0, - cachedUsageD7Pct: 0, - resetAt: '2026-04-24T14:00:00.000Z', - resetD7At: '2026-05-01T09:00:00.000Z', - }, - ]); - vi.mocked(rotation.getCodexAuthPath).mockImplementation( - (accountIndex = 0) => authPathFor(tempHome, accountIndex), - ); + vi.mocked(codexAuth.getCodexAccountStatus).mockReturnValue(usage); + vi.mocked(codexAuth.getCodexAuthPath).mockReturnValue(authPath); + const captured: { + cmd?: string; + args?: readonly string[]; + env?: Record; + } = {}; vi.mocked(childProcess.spawn).mockImplementation((( - _cmd: string, + cmd: string, args?: readonly string[], opts?: { env?: Record }, ) => { - capturedArgs = args; - capturedEnv = opts?.env; - return createFakeCodexProcess(0) as never; + captured.cmd = cmd; + captured.args = args; + captured.env = opts?.env; + return createFakeCodexProcess(exitCode) as never; }) as unknown as typeof childProcess.spawn); + return { childProcess, runCodexWarmupCycle, captured }; + } - const result = await runCodexWarmupCycle( - { - prompt: 'Reply exactly OK. Do not run tools.', - model: 'gpt-5.5', - minIntervalMs: 18_300_000, - staggerMs: 1_800_000, - maxUsagePct: 0, - maxD7UsagePct: 0, - commandTimeoutMs: 120_000, - failureCooldownMs: 21_600_000, - maxConsecutiveFailures: 2, - }, - { nowMs: now, statePath }, - ); + it('warms a zero-usage account with a real codex exec and persists the quota window', async () => { + const { childProcess, runCodexWarmupCycle, captured } = await setup({ + cachedUsagePct: 0, + cachedUsageD7Pct: 0, + resetD7At: '2026-05-01T09:00:00.000Z', + }); + const now = new Date('2026-04-24T09:00:00Z').getTime(); - expect(result).toEqual({ status: 'warmed', accountIndex: 2 }); + const result = await runCodexWarmupCycle(baseConfig, { + nowMs: now, + statePath, + }); + + expect(result).toEqual({ status: 'warmed' }); expect(childProcess.spawn).toHaveBeenCalledTimes(1); - expect(capturedArgs).toEqual( + expect(captured.args).toEqual( expect.arrayContaining([ 'exec', '--ephemeral', @@ -153,124 +132,54 @@ describe('Codex warm-up scheduler', () => { 'Reply exactly OK. Do not run tools.', ]), ); - expect(capturedEnv?.CODEX_HOME).toBe( - path.dirname(authPathFor(tempHome, 2)), - ); + expect(captured.env?.CODEX_HOME).toBe(path.dirname(authPath)); const state = JSON.parse(fs.readFileSync(statePath, 'utf8')); expect(state.lastWarmupAt).toBe('2026-04-24T09:00:00.000Z'); - expect(state.accounts['2'].lastWarmupAt).toBe('2026-04-24T09:00:00.000Z'); - expect(state.accounts['2'].zeroUsageWarmupUntil).toBe( - '2026-05-01T09:00:00.000Z', - ); + expect(state.zeroUsageWarmupUntil).toBe('2026-05-01T09:00:00.000Z'); expect(state.consecutiveFailures).toBe(0); + + // The same zero-usage window is not warmed again. + const again = await runCodexWarmupCycle( + { ...baseConfig, staggerMs: 0, minIntervalMs: 0 }, + { nowMs: now + 60_000, statePath }, + ); + expect(again).toEqual({ + status: 'skipped', + reason: 'no_eligible_accounts', + }); + expect(childProcess.spawn).toHaveBeenCalledTimes(1); }); it('spawns the bundled codex JS launcher via the JS runtime instead of a bare "codex" PATH lookup', async () => { // Regression: under bun/systemd there is usually no global `codex` on PATH, // so spawning bare `codex` failed with ENOENT and the primer never fired. - const childProcess = await import('child_process'); - const rotation = await import('./codex-token-rotation.js'); - const { runCodexWarmupCycle } = await import('./codex-warmup.js'); - const now = new Date('2026-04-24T09:00:00Z').getTime(); - let capturedCmd: string | undefined; - let capturedArgs: readonly string[] | undefined; + const { runCodexWarmupCycle, captured } = await setup({ + cachedUsagePct: 0, + cachedUsageD7Pct: 0, + }); - vi.mocked(rotation.getAllCodexAccounts).mockReturnValue([ - { - index: 0, - accountId: 'fresh-account', - planType: 'pro', - isActive: false, - isRateLimited: false, - cachedUsagePct: 0, - cachedUsageD7Pct: 0, - }, - ]); - vi.mocked(rotation.getCodexAuthPath).mockImplementation( - (accountIndex = 0) => authPathFor(tempHome, accountIndex), - ); - vi.mocked(childProcess.spawn).mockImplementation((( - cmd: string, - args?: readonly string[], - ) => { - capturedCmd = cmd; - capturedArgs = args; - return createFakeCodexProcess(0) as never; - }) as unknown as typeof childProcess.spawn); + await runCodexWarmupCycle(baseConfig, { + nowMs: new Date('2026-04-24T09:00:00Z').getTime(), + statePath, + }); - await runCodexWarmupCycle( - { - prompt: 'Reply exactly OK. Do not run tools.', - model: 'gpt-5.5', - minIntervalMs: 18_300_000, - staggerMs: 1_800_000, - maxUsagePct: 0, - maxD7UsagePct: 0, - commandTimeoutMs: 120_000, - failureCooldownMs: 21_600_000, - maxConsecutiveFailures: 2, - }, - { nowMs: now, statePath }, - ); - - expect(childProcess.spawn).toHaveBeenCalledTimes(1); - // Command is the JS runtime (bun/node), never a bare "codex" PATH lookup. - expect(capturedCmd).toBe(process.execPath); - expect(capturedCmd).not.toBe('codex'); - // First arg is the resolvable codex JS launcher; 'exec' follows after it. - expect(capturedArgs?.[0]).toMatch(/codex\.js$/); - expect(fs.existsSync(capturedArgs?.[0] as string)).toBe(true); - expect(capturedArgs?.[1]).toBe('exec'); + expect(captured.cmd).toBe(process.execPath); + expect(captured.args?.[0]).toMatch(/codex\.js$/); + expect(fs.existsSync(captured.args?.[0] as string)).toBe(true); + expect(captured.args?.[1]).toBe('exec'); }); - it('does not repeat warm-up while the same zero-usage quota window is already marked warmed', async () => { - const childProcess = await import('child_process'); - const rotation = await import('./codex-token-rotation.js'); - const { runCodexWarmupCycle } = await import('./codex-warmup.js'); - const now = new Date('2026-04-24T15:00:00Z').getTime(); + it('skips an account whose usage is above the warm-up limit', async () => { + const { childProcess, runCodexWarmupCycle } = await setup({ + cachedUsagePct: 14, + cachedUsageD7Pct: 30, + }); - fs.writeFileSync( + const result = await runCodexWarmupCycle(baseConfig, { + nowMs: Date.now(), statePath, - JSON.stringify({ - lastWarmupAt: '2026-04-24T09:00:00.000Z', - consecutiveFailures: 0, - accounts: { - '0': { - lastWarmupAt: '2026-04-24T09:00:00.000Z', - zeroUsageWarmupUntil: '2026-05-01T09:00:00.000Z', - }, - }, - }), - ); - vi.mocked(rotation.getAllCodexAccounts).mockReturnValue([ - { - index: 0, - accountId: 'fresh-account-still-rounded-zero', - planType: 'pro', - isActive: false, - isRateLimited: false, - cachedUsagePct: 0, - cachedUsageD7Pct: 0, - resetAt: '2026-04-24T14:00:00.000Z', - resetD7At: '2026-05-01T09:00:00.000Z', - }, - ]); - - const result = await runCodexWarmupCycle( - { - prompt: 'Reply exactly OK. Do not run tools.', - model: 'gpt-5.5', - minIntervalMs: 18_300_000, - staggerMs: 0, - maxUsagePct: 0, - maxD7UsagePct: 0, - commandTimeoutMs: 120_000, - failureCooldownMs: 21_600_000, - maxConsecutiveFailures: 2, - }, - { nowMs: now, statePath }, - ); + }); expect(result).toEqual({ status: 'skipped', @@ -279,166 +188,44 @@ describe('Codex warm-up scheduler', () => { expect(childProcess.spawn).not.toHaveBeenCalled(); }); - it('lets the fixed-slot primer warm an account again when 5h usage is fresh but weekly usage is nonzero', async () => { - const childProcess = await import('child_process'); - const rotation = await import('./codex-token-rotation.js'); - const { runCodexWarmupCycle } = await import('./codex-warmup.js'); - const now = new Date('2026-04-24T14:00:00Z').getTime(); - - fs.writeFileSync( - statePath, - JSON.stringify({ - lastWarmupAt: '2026-04-24T09:00:00.000Z', - consecutiveFailures: 0, - accounts: { - '0': { - lastWarmupAt: '2026-04-24T09:00:00.000Z', - zeroUsageWarmupUntil: '2026-05-01T09:00:00.000Z', - }, - }, - }), + it('backs off after repeated codex exec failures', async () => { + const { childProcess, runCodexWarmupCycle } = await setup( + { cachedUsagePct: 0, cachedUsageD7Pct: 0 }, + 1, ); - vi.mocked(rotation.getAllCodexAccounts).mockReturnValue([ - { - index: 0, - accountId: 'same-account-next-slot', - planType: 'pro', - isActive: true, - isRateLimited: false, - cachedUsagePct: 0, - cachedUsageD7Pct: 37, - resetAt: '2026-04-24T19:00:00.000Z', - resetD7At: '2026-05-01T09:00:00.000Z', - }, - ]); - vi.mocked(rotation.getCodexAuthPath).mockImplementation( - (accountIndex = 0) => authPathFor(tempHome, accountIndex), - ); - vi.mocked(childProcess.spawn).mockImplementation( - () => createFakeCodexProcess(0) as never, - ); - - const result = await runCodexWarmupCycle( - { - prompt: 'Reply exactly OK. Do not run tools.', - model: 'gpt-5.5', - minIntervalMs: 18_000_000, - staggerMs: 0, - maxUsagePct: 0, - maxD7UsagePct: 100, - commandTimeoutMs: 120_000, - failureCooldownMs: 21_600_000, - maxConsecutiveFailures: 2, - }, - { nowMs: now, statePath, ignoreZeroUsageWindow: true }, - ); - - expect(result).toEqual({ status: 'warmed', accountIndex: 0 }); - expect(childProcess.spawn).toHaveBeenCalledTimes(1); - const state = JSON.parse(fs.readFileSync(statePath, 'utf8')); - expect(state.accounts['0'].lastWarmupAt).toBe('2026-04-24T14:00:00.000Z'); - expect(state.accounts['0'].zeroUsageWarmupUntil).toBe( - '2026-04-24T14:00:00.000Z', - ); - }); - - it('auto-backs off after repeated codex exec failures so OpenAI-side blocking does not hammer accounts', async () => { - const childProcess = await import('child_process'); - const rotation = await import('./codex-token-rotation.js'); - const { runCodexWarmupCycle } = await import('./codex-warmup.js'); const now = new Date('2026-04-24T09:00:00Z').getTime(); + const config = { ...baseConfig, staggerMs: 0 }; - vi.mocked(rotation.getAllCodexAccounts).mockReturnValue([ - { - index: 0, - accountId: 'fresh-account', - planType: 'pro', - isActive: false, - isRateLimited: false, - cachedUsagePct: 0, - cachedUsageD7Pct: 0, - }, - ]); - vi.mocked(rotation.getCodexAuthPath).mockImplementation( - (accountIndex = 0) => authPathFor(tempHome, accountIndex), - ); - vi.mocked(childProcess.spawn).mockImplementation( - () => createFakeCodexProcess(1) as never, - ); + expect( + await runCodexWarmupCycle(config, { nowMs: now, statePath }), + ).toEqual({ status: 'failed', reason: 'exit_1' }); + expect( + await runCodexWarmupCycle(config, { nowMs: now + 1_000, statePath }), + ).toEqual({ status: 'failed', reason: 'exit_1' }); - const config = { - prompt: 'Reply exactly OK. Do not run tools.', - model: 'gpt-5.5', - minIntervalMs: 18_300_000, - staggerMs: 0, - maxUsagePct: 0, - maxD7UsagePct: 0, - commandTimeoutMs: 120_000, - failureCooldownMs: 21_600_000, - maxConsecutiveFailures: 1, - }; - - const failed = await runCodexWarmupCycle(config, { nowMs: now, statePath }); - expect(failed.status).toBe('failed'); - - const backedOff = await runCodexWarmupCycle(config, { - nowMs: now + 60_000, - statePath, - }); - - expect(backedOff).toEqual({ - status: 'skipped', - reason: 'disabled_cooldown', - }); - expect(childProcess.spawn).toHaveBeenCalledTimes(1); const state = JSON.parse(fs.readFileSync(statePath, 'utf8')); - expect(state.disabledUntil).toBe('2026-04-24T15:00:00.000Z'); - expect(state.consecutiveFailures).toBe(1); + expect(state.consecutiveFailures).toBe(2); + expect(state.disabledUntil).toBe( + new Date(now + 1_000 + config.failureCooldownMs).toISOString(), + ); + + expect( + await runCodexWarmupCycle(config, { nowMs: now + 2_000, statePath }), + ).toEqual({ status: 'skipped', reason: 'disabled_cooldown' }); + expect(childProcess.spawn).toHaveBeenCalledTimes(2); }); - it('respects global stagger and does not warm another account too soon', async () => { - const childProcess = await import('child_process'); - const rotation = await import('./codex-token-rotation.js'); - const { runCodexWarmupCycle } = await import('./codex-warmup.js'); - const now = new Date('2026-04-24T09:20:00Z').getTime(); + it('skips without an auth file', async () => { + const { runCodexWarmupCycle } = await setup({ + cachedUsagePct: 0, + cachedUsageD7Pct: 0, + }); + const codexAuth = await import('./codex-auth.js'); + vi.mocked(codexAuth.getCodexAuthPath).mockReturnValue(null); - fs.writeFileSync( - statePath, - JSON.stringify({ - lastWarmupAt: '2026-04-24T09:00:00.000Z', - consecutiveFailures: 0, - accounts: { '0': { lastWarmupAt: '2026-04-24T09:00:00.000Z' } }, - }), - ); - vi.mocked(rotation.getAllCodexAccounts).mockReturnValue([ - { - index: 1, - accountId: 'another-fresh-account', - planType: 'pro', - isActive: false, - isRateLimited: false, - cachedUsagePct: 0, - cachedUsageD7Pct: 0, - }, - ]); - - const result = await runCodexWarmupCycle( - { - prompt: '.', - model: 'gpt-5.5', - minIntervalMs: 18_300_000, - staggerMs: 1_800_000, - maxUsagePct: 0, - maxD7UsagePct: 0, - commandTimeoutMs: 120_000, - failureCooldownMs: 21_600_000, - maxConsecutiveFailures: 2, - }, - { nowMs: now, statePath }, - ); - - expect(result).toEqual({ status: 'skipped', reason: 'stagger_wait' }); - expect(childProcess.spawn).not.toHaveBeenCalled(); + expect( + await runCodexWarmupCycle(baseConfig, { nowMs: Date.now(), statePath }), + ).toEqual({ status: 'skipped', reason: 'missing_auth' }); }); }); @@ -450,15 +237,10 @@ describe('Codex warm-up fixed-slot forceAttempt', () => { const t13 = new Date('2026-06-09T04:00:00.486Z').getTime(); const t18 = new Date('2026-06-09T09:00:00.000Z').getTime(); const config = { - prompt: 'Reply exactly OK. Do not run tools.', - model: 'gpt-5.5', + ...baseConfig, minIntervalMs: 18_000_000, // 5h - staggerMs: 1_800_000, maxUsagePct: 100, maxD7UsagePct: 100, - commandTimeoutMs: 120_000, - failureCooldownMs: 21_600_000, - maxConsecutiveFailures: 2, }; beforeEach(() => { @@ -466,8 +248,6 @@ describe('Codex warm-up fixed-slot forceAttempt', () => { vi.clearAllMocks(); tempHome = fs.mkdtempSync(path.join('/tmp', 'ejclaw-codex-force-')); statePath = path.join(tempHome, 'codex-warmup-state.json'); - fs.mkdirSync(path.dirname(authPathFor(tempHome, 0)), { recursive: true }); - fs.writeFileSync(authPathFor(tempHome, 0), '{}'); }); afterEach(() => { @@ -475,23 +255,17 @@ describe('Codex warm-up fixed-slot forceAttempt', () => { }); async function setup() { + const authPath = path.join(tempHome, '.codex-accounts', '0', 'auth.json'); + fs.mkdirSync(path.dirname(authPath), { recursive: true }); + fs.writeFileSync(authPath, '{}'); const childProcess = await import('child_process'); - const rotation = await import('./codex-token-rotation.js'); + const codexAuth = await import('./codex-auth.js'); const { runCodexWarmupCycle } = await import('./codex-warmup.js'); - vi.mocked(rotation.getAllCodexAccounts).mockReturnValue([ - { - index: 0, - accountId: 'acct', - planType: 'pro', - isActive: true, - isRateLimited: false, - cachedUsagePct: 0, - cachedUsageD7Pct: 0, - }, - ]); - vi.mocked(rotation.getCodexAuthPath).mockImplementation( - (accountIndex = 0) => authPathFor(tempHome, accountIndex), - ); + vi.mocked(codexAuth.getCodexAccountStatus).mockReturnValue({ + cachedUsagePct: 0, + cachedUsageD7Pct: 0, + }); + vi.mocked(codexAuth.getCodexAuthPath).mockReturnValue(authPath); vi.mocked(childProcess.spawn).mockImplementation( (() => createFakeCodexProcess( @@ -509,14 +283,14 @@ describe('Codex warm-up fixed-slot forceAttempt', () => { ignoreZeroUsageWindow: true, forceAttempt: true, }); - expect(r1).toEqual({ status: 'warmed', accountIndex: 0 }); + expect(r1).toEqual({ status: 'warmed' }); const r2 = await runCodexWarmupCycle(config, { nowMs: t18, statePath, ignoreZeroUsageWindow: true, forceAttempt: true, }); - expect(r2).toEqual({ status: 'warmed', accountIndex: 0 }); + expect(r2).toEqual({ status: 'warmed' }); expect(childProcess.spawn).toHaveBeenCalledTimes(2); }); @@ -542,7 +316,6 @@ describe('Codex warm-up fixed-slot forceAttempt', () => { JSON.stringify({ disabledUntil: new Date(t18 + 3_600_000).toISOString(), lastWarmupAt: new Date(t18 - 1_000).toISOString(), - accounts: {}, }), ); const result = await runCodexWarmupCycle(config, { @@ -551,6 +324,6 @@ describe('Codex warm-up fixed-slot forceAttempt', () => { ignoreZeroUsageWindow: true, forceAttempt: true, }); - expect(result).toEqual({ status: 'warmed', accountIndex: 0 }); + expect(result).toEqual({ status: 'warmed' }); }); }); diff --git a/src/codex-warmup.ts b/src/codex-warmup.ts index 70760f6..3f64acb 100644 --- a/src/codex-warmup.ts +++ b/src/codex-warmup.ts @@ -7,28 +7,18 @@ import { fileURLToPath } from 'url'; import { DATA_DIR } from './config.js'; import type { AppConfig } from './config/schema.js'; -import { - getAllCodexAccounts, - getCodexAuthPath, -} from './codex-token-rotation.js'; +import { getCodexAccountStatus, getCodexAuthPath } from './codex-auth.js'; import { logger } from './logger.js'; export type CodexWarmupConfig = AppConfig['codexWarmup']; -interface CodexWarmupAccountState { +interface CodexWarmupState { lastWarmupAt?: string; lastAttemptAt?: string; lastErrorAt?: string; zeroUsageWarmupUntil?: string; - failures?: number; -} - -interface CodexWarmupState { - lastWarmupAt?: string; - lastAttemptAt?: string; disabledUntil?: string; consecutiveFailures?: number; - accounts?: Record; } interface CodexWarmupRuntimeOptions { @@ -37,8 +27,7 @@ interface CodexWarmupRuntimeOptions { ignoreZeroUsageWindow?: boolean; /** * Fixed-slot primer mode: bypass the opportunistic warm-up skip gates - * (stagger, post-failure cooldown, min-interval, per-account usage/rate-limit - * filters) so a real Codex command is attempted at every 08/13/18/23 slot and + * (stagger, post-failure cooldown, min-interval, usage filters) so a real Codex command is attempted at every 08/13/18/23 slot and * its success/failure recorded. Without this, two slots exactly 5h apart fall * just under minIntervalMs (the primer fires a few hundred ms after the slot) * and the later slot is silently skipped as `no_eligible_accounts`. @@ -48,8 +37,8 @@ interface CodexWarmupRuntimeOptions { export type CodexWarmupCycleResult = | { status: 'skipped'; reason: string } - | { status: 'warmed'; accountIndex: number } - | { status: 'failed'; accountIndex: number; reason: string }; + | { status: 'warmed' } + | { status: 'failed'; reason: string }; const DEFAULT_STATE_FILE = path.join(DATA_DIR, 'codex-warmup-state.json'); const DEFAULT_ZERO_USAGE_WARMUP_WINDOW_MS = 7 * 24 * 60 * 60 * 1000; @@ -62,20 +51,14 @@ function parseTimestamp(value?: string): number | null { function readWarmupState(statePath: string): CodexWarmupState { try { - if (!fs.existsSync(statePath)) return { accounts: {} }; - const parsed = JSON.parse( - fs.readFileSync(statePath, 'utf8'), - ) as CodexWarmupState; - if (!parsed.accounts || typeof parsed.accounts !== 'object') { - parsed.accounts = {}; - } - return parsed; + if (!fs.existsSync(statePath)) return {}; + return JSON.parse(fs.readFileSync(statePath, 'utf8')) as CodexWarmupState; } catch (err) { logger.warn( { err, statePath }, 'Failed to read Codex warm-up state; starting fresh', ); - return { accounts: {} }; + return {}; } } @@ -155,22 +138,12 @@ function resolveCodexLauncher(): CodexLauncher { return { command: 'codex', prefixArgs: [] }; } -function ensureAccountState( - state: CodexWarmupState, - accountIndex: number, -): CodexWarmupAccountState { - state.accounts ??= {}; - const key = String(accountIndex); - state.accounts[key] ??= {}; - return state.accounts[key]; -} - -function selectWarmupCandidate( +function selectWarmup( config: CodexWarmupConfig, state: CodexWarmupState, nowMs: number, options: { ignoreZeroUsageWindow?: boolean; forceAttempt?: boolean } = {}, -): { accountIndex: number; zeroUsageWarmupUntil: string } | { reason: string } { +): { zeroUsageWarmupUntil: string } | { reason: string } { const disabledUntilMs = parseTimestamp(state.disabledUntil); if ( !options.forceAttempt && @@ -180,71 +153,61 @@ function selectWarmupCandidate( return { reason: 'disabled_cooldown' }; } - const lastGlobalWarmupMs = parseTimestamp(state.lastWarmupAt); + const lastWarmupMs = parseTimestamp(state.lastWarmupAt); if ( !options.forceAttempt && - lastGlobalWarmupMs != null && + lastWarmupMs != null && config.staggerMs > 0 && - nowMs - lastGlobalWarmupMs < config.staggerMs + nowMs - lastWarmupMs < config.staggerMs ) { return { reason: 'stagger_wait' }; } - const accounts = getAllCodexAccounts(); - if (accounts.length === 0) return { reason: 'no_accounts' }; + const account = getCodexAccountStatus(); + if (!account) return { reason: 'no_accounts' }; - // Fixed-slot primer: attempt a real command on the active account every slot, - // bypassing the per-account usage/rate-limit/min-interval filters below. + // Fixed-slot primer: attempt a real command every slot, bypassing the + // usage/min-interval filters below. if (options.forceAttempt) { - const active = accounts.find((a) => a.isActive) ?? accounts[0]; - return { - accountIndex: active.index, - zeroUsageWarmupUntil: new Date(nowMs).toISOString(), - }; + return { zeroUsageWarmupUntil: new Date(nowMs).toISOString() }; } - for (const account of accounts) { - if (account.isRateLimited) continue; - if (typeof account.cachedUsagePct !== 'number') continue; - if (typeof account.cachedUsageD7Pct !== 'number') continue; - if (account.cachedUsagePct > config.maxUsagePct) continue; - if (account.cachedUsageD7Pct > config.maxD7UsagePct) continue; - - const accountState = state.accounts?.[String(account.index)]; - const zeroUsageWarmupUntilMs = parseTimestamp( - accountState?.zeroUsageWarmupUntil, - ); - if ( - !options.ignoreZeroUsageWindow && - zeroUsageWarmupUntilMs != null && - zeroUsageWarmupUntilMs > nowMs - ) { - continue; - } - - const lastWarmupMs = parseTimestamp(accountState?.lastWarmupAt); - if (lastWarmupMs != null && nowMs - lastWarmupMs < config.minIntervalMs) { - continue; - } - - const resetD7Ms = parseTimestamp(account.resetD7At); - let zeroUsageWarmupUntilMsForState = nowMs; - if (!options.ignoreZeroUsageWindow) { - zeroUsageWarmupUntilMsForState = - resetD7Ms != null && resetD7Ms > nowMs - ? resetD7Ms - : nowMs + DEFAULT_ZERO_USAGE_WARMUP_WINDOW_MS; - } - - return { - accountIndex: account.index, - zeroUsageWarmupUntil: new Date( - zeroUsageWarmupUntilMsForState, - ).toISOString(), - }; + if ( + typeof account.cachedUsagePct !== 'number' || + typeof account.cachedUsageD7Pct !== 'number' || + account.cachedUsagePct > config.maxUsagePct || + account.cachedUsageD7Pct > config.maxD7UsagePct + ) { + return { reason: 'no_eligible_accounts' }; } - return { reason: 'no_eligible_accounts' }; + const zeroUsageWarmupUntilMs = parseTimestamp(state.zeroUsageWarmupUntil); + if ( + !options.ignoreZeroUsageWindow && + zeroUsageWarmupUntilMs != null && + zeroUsageWarmupUntilMs > nowMs + ) { + return { reason: 'no_eligible_accounts' }; + } + + if (lastWarmupMs != null && nowMs - lastWarmupMs < config.minIntervalMs) { + return { reason: 'no_eligible_accounts' }; + } + + const resetD7Ms = parseTimestamp(account.resetD7At); + let zeroUsageWarmupUntilMsForState = nowMs; + if (!options.ignoreZeroUsageWindow) { + zeroUsageWarmupUntilMsForState = + resetD7Ms != null && resetD7Ms > nowMs + ? resetD7Ms + : nowMs + DEFAULT_ZERO_USAGE_WARMUP_WINDOW_MS; + } + + return { + zeroUsageWarmupUntil: new Date( + zeroUsageWarmupUntilMsForState, + ).toISOString(), + }; } function runCodexWarmupCommand( @@ -338,7 +301,7 @@ export async function runCodexWarmupCycle( const nowIso = new Date(nowMs).toISOString(); const statePath = runtime.statePath ?? DEFAULT_STATE_FILE; const state = readWarmupState(statePath); - const selected = selectWarmupCandidate(config, state, nowMs, { + const selected = selectWarmup(config, state, nowMs, { ignoreZeroUsageWindow: runtime.ignoreZeroUsageWindow, forceAttempt: runtime.forceAttempt, }); @@ -346,39 +309,28 @@ export async function runCodexWarmupCycle( return { status: 'skipped', reason: selected.reason }; } - const authPath = getCodexAuthPath(selected.accountIndex); - if (!authPath || !fs.existsSync(authPath)) { + const authPath = getCodexAuthPath(); + if (!authPath) { return { status: 'skipped', reason: 'missing_auth' }; } const accountDir = path.dirname(authPath); - const accountState = ensureAccountState(state, selected.accountIndex); state.lastAttemptAt = nowIso; - accountState.lastAttemptAt = nowIso; - logger.info( - { account: selected.accountIndex + 1, model: config.model }, - 'Starting Codex warm-up prompt', - ); + logger.info({ model: config.model }, 'Starting Codex warm-up prompt'); const result = await runCodexWarmupCommand(accountDir, config); if (result.ok) { state.lastWarmupAt = nowIso; state.consecutiveFailures = 0; delete state.disabledUntil; - accountState.lastWarmupAt = nowIso; - accountState.zeroUsageWarmupUntil = selected.zeroUsageWarmupUntil; - accountState.failures = 0; + state.zeroUsageWarmupUntil = selected.zeroUsageWarmupUntil; writeWarmupState(statePath, state); - logger.info( - { account: selected.accountIndex + 1 }, - 'Codex warm-up prompt completed', - ); - return { status: 'warmed', accountIndex: selected.accountIndex }; + logger.info('Codex warm-up prompt completed'); + return { status: 'warmed' }; } state.consecutiveFailures = (state.consecutiveFailures ?? 0) + 1; - accountState.lastErrorAt = nowIso; - accountState.failures = (accountState.failures ?? 0) + 1; + state.lastErrorAt = nowIso; if (state.consecutiveFailures >= config.maxConsecutiveFailures) { state.disabledUntil = new Date( nowMs + config.failureCooldownMs, @@ -387,16 +339,11 @@ export async function runCodexWarmupCycle( writeWarmupState(statePath, state); logger.warn( { - account: selected.accountIndex + 1, reason: result.reason, consecutiveFailures: state.consecutiveFailures, disabledUntil: state.disabledUntil, }, 'Codex warm-up prompt failed', ); - return { - status: 'failed', - accountIndex: selected.accountIndex, - reason: result.reason, - }; + return { status: 'failed', reason: result.reason }; } diff --git a/src/dashboard-usage-rows.test.ts b/src/dashboard-usage-rows.test.ts index 969cc97..f09dce6 100644 --- a/src/dashboard-usage-rows.test.ts +++ b/src/dashboard-usage-rows.test.ts @@ -1,18 +1,15 @@ import { describe, expect, it, vi } from 'vitest'; -import type { ClaudeAccountUsage } from './claude-usage.js'; +import type { ClaudeUsageSnapshot } from './claude-usage.js'; vi.mock('./claude-usage.js', () => ({ - getClaudeProfile: (index: number) => - index === 0 - ? { email: 'a@example.com', planType: 'max' } - : { email: 'b@example.com', planType: 'pro' }, + getClaudeProfile: () => ({ email: 'a@example.com', planType: 'max' }), })); import { buildClaudeUsageRows, extractCodexUsageRows, - mergeClaudeDashboardAccounts, + mergeClaudeDashboardUsage, } from './dashboard-usage-rows.js'; import type { StatusSnapshot } from './status-dashboard.js'; @@ -93,157 +90,39 @@ describe('extractCodexUsageRows staleness', () => { }); describe('dashboard Claude usage rows', () => { - it('keeps both Claude accounts visible when one account usage is unavailable', () => { - const rows = buildClaudeUsageRows([ - { - index: 0, - masked: 'tok-a', - isActive: true, - isRateLimited: false, - usage: { - five_hour: { - utilization: 0.4, - resets_at: '2026-03-24T04:00:00+09:00', - }, - seven_day: { - utilization: 0.7, - resets_at: '2026-03-29T04:00:00+09:00', - }, - }, - }, - { - index: 1, - masked: 'tok-b', - isActive: false, - isRateLimited: true, - usage: null, - }, - ]); + const cachedUsage: ClaudeUsageSnapshot = { + usage: { + five_hour: { utilization: 0.4, resets_at: '2026-03-24T04:00:00+09:00' }, + seven_day: { utilization: 0.7, resets_at: '2026-03-29T04:00:00+09:00' }, + }, + }; - expect(rows).toHaveLength(2); - expect(rows[0]).toMatchObject({ - name: 'Claude1* max', - h5pct: 40, - d7pct: 70, - }); - expect(rows[1]).toMatchObject({ - name: 'Claude2! pro', - h5pct: -1, - d7pct: -1, - }); + it('renders one row labelled with the account plan', () => { + const rows = buildClaudeUsageRows(cachedUsage); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ name: 'Claude max', h5pct: 40, d7pct: 70 }); }); - it('marks a rate-limited account with a 429 error and does not fall back to a cached value', () => { - const cachedAccounts: ClaudeAccountUsage[] = [ - { - index: 0, - masked: 'tok-a', - isActive: true, - isRateLimited: false, - usage: { - five_hour: { - utilization: 0.4, - resets_at: '2026-03-24T04:00:00+09:00', - }, - seven_day: { - utilization: 0.7, - resets_at: '2026-03-29T04:00:00+09:00', - }, - }, - }, - ]; - const liveAccounts: ClaudeAccountUsage[] = [ - { - index: 0, - masked: 'tok-a', - isActive: true, - isRateLimited: false, - usage: null, - usageRateLimited: true, - }, - ]; + it('renders nothing without a usage snapshot', () => { + expect(buildClaudeUsageRows(null)).toEqual([]); + }); - const merged = mergeClaudeDashboardAccounts(liveAccounts, cachedAccounts); + it('marks a rate-limited fetch with a 429 error and does not fall back to a cached value', () => { + const merged = mergeClaudeDashboardUsage( + { usage: null, usageRateLimited: true }, + cachedUsage, + ); // The 429 must win over the cached value — no stale fallback. - expect(merged[0].usage).toBeNull(); + expect(merged?.usage).toBeNull(); const rows = buildClaudeUsageRows(merged); expect(rows[0]).toMatchObject({ h5pct: -1, d7pct: -1, error: '429' }); }); - it('preserves the last successful usage per account instead of collapsing to one cache entry', () => { - const cachedAccounts: ClaudeAccountUsage[] = [ - { - index: 0, - masked: 'tok-a', - isActive: false, - isRateLimited: false, - usage: { - five_hour: { - utilization: 0.25, - resets_at: '2026-03-24T04:00:00+09:00', - }, - seven_day: { - utilization: 0.5, - resets_at: '2026-03-29T04:00:00+09:00', - }, - }, - }, - { - index: 1, - masked: 'tok-b', - isActive: true, - isRateLimited: false, - usage: { - five_hour: { - utilization: 0.6, - resets_at: '2026-03-24T06:00:00+09:00', - }, - seven_day: { - utilization: 0.8, - resets_at: '2026-03-30T04:00:00+09:00', - }, - }, - }, - ]; - const liveAccounts: ClaudeAccountUsage[] = [ - { - index: 0, - masked: 'tok-a', - isActive: true, - isRateLimited: false, - usage: null, - }, - { - index: 1, - masked: 'tok-b', - isActive: false, - isRateLimited: true, - usage: { - five_hour: { - utilization: 0.9, - resets_at: '2026-03-24T08:00:00+09:00', - }, - seven_day: { - utilization: 0.95, - resets_at: '2026-03-31T04:00:00+09:00', - }, - }, - }, - ]; - - const merged = mergeClaudeDashboardAccounts(liveAccounts, cachedAccounts); - - expect(merged).toHaveLength(2); - expect(merged[0]).toMatchObject({ - index: 0, - isActive: true, - usage: cachedAccounts[0].usage, - }); - expect(merged[1]).toMatchObject({ - index: 1, - isRateLimited: true, - usage: liveAccounts[1].usage, - }); + it('keeps the last successful usage when the live fetch returned nothing', () => { + expect( + mergeClaudeDashboardUsage({ usage: null }, cachedUsage)?.usage, + ).toEqual(cachedUsage.usage); + expect(mergeClaudeDashboardUsage(null, cachedUsage)).toBe(cachedUsage); }); }); diff --git a/src/dashboard-usage-rows.ts b/src/dashboard-usage-rows.ts index 259384f..f3a746d 100644 --- a/src/dashboard-usage-rows.ts +++ b/src/dashboard-usage-rows.ts @@ -1,4 +1,4 @@ -import { getClaudeProfile, type ClaudeAccountUsage } from './claude-usage.js'; +import { getClaudeProfile, type ClaudeUsageSnapshot } from './claude-usage.js'; import type { StatusSnapshot } from './status-dashboard.js'; export type UsageRow = { @@ -32,58 +32,42 @@ export function formatResetRemaining(value: string | number): string { } } -export function mergeClaudeDashboardAccounts( - liveAccounts: ClaudeAccountUsage[] | null | undefined, - cachedAccounts: ClaudeAccountUsage[], -): ClaudeAccountUsage[] { - if (!liveAccounts) return cachedAccounts; - - const cachedByIndex = new Map( - cachedAccounts.map((account) => [account.index, account]), - ); - - return liveAccounts.map((account) => ({ - ...account, +export function mergeClaudeDashboardUsage( + live: ClaudeUsageSnapshot | null | undefined, + cached: ClaudeUsageSnapshot | null, +): ClaudeUsageSnapshot | null { + if (!live) return cached; + return { + ...live, // On a 429 we deliberately do NOT fall back to the last cached value — // the dashboard surfaces a "429" indicator instead. - usage: account.usageRateLimited - ? null - : account.usage || cachedByIndex.get(account.index)?.usage || null, - })); + usage: live.usageRateLimited ? null : live.usage || cached?.usage || null, + }; +} + +function toPct(utilization: number): number { + return utilization > 1 + ? Math.round(utilization) + : Math.round(utilization * 100); } export function buildClaudeUsageRows( - claudeAccounts: ClaudeAccountUsage[], + snapshot: ClaudeUsageSnapshot | null, ): UsageRow[] { - const isMultiAccount = claudeAccounts.length > 1; - - return claudeAccounts.map((account) => { - const usage = account.usage; - const h5 = usage?.five_hour; - const d7 = usage?.seven_day; - const profile = getClaudeProfile(account.index); - const planSuffix = profile ? ` ${profile.planType}` : ''; - const label = isMultiAccount - ? `Claude${account.index + 1}${account.isActive ? '*' : ''}${account.isRateLimited ? '!' : ''}${planSuffix}` - : `Claude${account.isActive ? '*' : ''}${account.isRateLimited ? '!' : ''}${planSuffix}`; - - return { - name: label, - h5pct: h5 - ? h5.utilization > 1 - ? Math.round(h5.utilization) - : Math.round(h5.utilization * 100) - : -1, + if (!snapshot) return []; + const h5 = snapshot.usage?.five_hour; + const d7 = snapshot.usage?.seven_day; + const profile = getClaudeProfile(); + return [ + { + name: profile ? `Claude ${profile.planType}` : 'Claude', + h5pct: h5 ? toPct(h5.utilization) : -1, h5reset: h5 ? formatResetRemaining(h5.resets_at) : '', - d7pct: d7 - ? d7.utilization > 1 - ? Math.round(d7.utilization) - : Math.round(d7.utilization * 100) - : -1, + d7pct: d7 ? toPct(d7.utilization) : -1, d7reset: d7 ? formatResetRemaining(d7.resets_at) : '', - error: account.usageRateLimited ? '429' : undefined, - }; - }); + error: snapshot.usageRateLimited ? '429' : undefined, + }, + ]; } /** diff --git a/src/data-state-files.ts b/src/data-state-files.ts index 6c0130d..c6164d5 100644 --- a/src/data-state-files.ts +++ b/src/data-state-files.ts @@ -2,6 +2,8 @@ import fs from 'fs'; import path from 'path'; const ALLOWED_DATA_JSON_PATTERNS = [ + // Leftovers from the removed multi-account token rotation. Kept allowed so + // an existing file does not block startup; drop once deployments delete it. /^token-rotation-state\.json$/, /^codex-rotation-state\.json$/, /^codex-warmup-state\.json$/, diff --git a/src/index.ts b/src/index.ts index 8dba72f..569e01a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -55,11 +55,7 @@ import { import { startUsagePrimer } from './usage-primer.js'; import { Channel, NewMessage } from './types.js'; import { logger } from './logger.js'; -import { initCodexTokenRotation } from './codex-token-rotation.js'; -import { - hasAvailableClaudeToken, - initTokenRotation, -} from './token-rotation.js'; +import { getCurrentClaudeToken } from './claude-oauth-token.js'; import { isBotMessageSourceKind, resolveInjectedMessageSourceKind, @@ -260,8 +256,6 @@ async function main(): Promise { const processStartedAtMs = Date.now(); initDatabase(); logger.info('Database initialized'); - initTokenRotation(); - initCodexTokenRotation(); startTokenRefreshLoop(); runtimeState.loadState(); @@ -514,7 +508,7 @@ async function main(): Promise { leaseRecoveryTimer = setInterval(() => { const failover = getGlobalFailoverInfo(); if (!failover.active) return; - if (!hasAvailableClaudeToken()) return; + if (!getCurrentClaudeToken()) return; const activatedMs = failover.activatedAt ? new Date(failover.activatedAt).getTime() : NaN; diff --git a/src/message-agent-compact-refresh.test.ts b/src/message-agent-compact-refresh.test.ts index d9489e8..3d822f3 100644 --- a/src/message-agent-compact-refresh.test.ts +++ b/src/message-agent-compact-refresh.test.ts @@ -9,10 +9,6 @@ vi.mock('./agent-runner.js', () => ({ runAgentProcess: vi.fn(), })); -vi.mock('./codex-token-rotation.js', () => ({ - getCodexAccountCount: vi.fn(() => 1), -})); - vi.mock('./session-recovery.js', () => ({ shouldResetCodexSessionOnAgentFailure: vi.fn(() => false), shouldResetSessionOnAgentFailure: vi.fn(() => false), diff --git a/src/message-agent-executor-attempt-runner.test.ts b/src/message-agent-executor-attempt-runner.test.ts index 3622370..5de52e5 100644 --- a/src/message-agent-executor-attempt-runner.test.ts +++ b/src/message-agent-executor-attempt-runner.test.ts @@ -6,10 +6,6 @@ vi.mock('./agent-runner.js', () => ({ runAgentProcess: mockRunAgentProcess, })); -vi.mock('./codex-token-rotation.js', () => ({ - getCodexAccountCount: vi.fn(() => 2), -})); - import { runMessageAgentAttempt } from './message-agent-executor-attempt-runner.js'; import type { AgentOutput } from './agent-runner.js'; diff --git a/src/message-agent-executor-attempt-runner.ts b/src/message-agent-executor-attempt-runner.ts index 690c899..eec9a7e 100644 --- a/src/message-agent-executor-attempt-runner.ts +++ b/src/message-agent-executor-attempt-runner.ts @@ -8,7 +8,6 @@ import type { AttemptStreamedTrigger } from './agent-attempt-retry.js'; import { getAgentOutputAttachments } from './agent-output.js'; import { runAgentProcess, type AgentOutput } from './agent-runner.js'; import { markCompactRefreshNeeded } from './compact-refresh.js'; -import { getCodexAccountCount } from './codex-token-rotation.js'; import type { PreparedPairedExecutionContext } from './paired-execution-context.js'; import { shouldResetCodexSessionOnAgentFailure, @@ -130,9 +129,7 @@ class MessageAgentAttemptRunner { suppressClaudeAuthErrorOutput: args.provider === 'claude', trackSuccessNullResult: true, shortCircuitTriggeredErrors: - args.provider === 'claude' - ? args.canRetryClaudeCredentials - : getCodexAccountCount() > 1, + args.provider === 'claude' && args.canRetryClaudeCredentials, }, onEvaluatedOutput: (event) => this.handleEvaluatedOutput(event), }); @@ -294,7 +291,7 @@ class MessageAgentAttemptRunner { reason: event.evaluation.newTrigger.reason, resultPreview: event.outputText.slice(0, 120), }, - 'Detected Claude rotation trigger in successful output', + 'Detected Claude failure trigger in successful output', ); return; } @@ -305,8 +302,8 @@ class MessageAgentAttemptRunner { errorPreview: event.output.error.slice(0, 120), }, this.args.provider === 'claude' - ? 'Detected Claude rotation trigger in streamed error output' - : 'Detected Codex rotation trigger in streamed error output', + ? 'Detected Claude failure trigger in streamed error output' + : 'Detected Codex failure trigger in streamed error output', ); } } diff --git a/src/message-agent-executor-lifecycle.ts b/src/message-agent-executor-lifecycle.ts index eebbbfa..a0e82da 100644 --- a/src/message-agent-executor-lifecycle.ts +++ b/src/message-agent-executor-lifecycle.ts @@ -1,15 +1,11 @@ import { getAgentOutputText } from './agent-output.js'; import { - executeAttemptRetryAction, - runClaudeAttemptWithRotation, - runCodexAttemptWithRotation, + retryClaudeAttemptOnTrigger, + runClaudeAttemptWithAuthRefresh, + type ClaudeTrigger, } from './agent-attempt-orchestration.js'; import { isRetryableClaudeSessionFailureAttempt } from './agent-attempt-retry.js'; -import { getCodexAccountCount } from './codex-token-rotation.js'; -import type { - AgentTriggerReason, - CodexRotationReason, -} from './agent-error-detection.js'; +import type { AgentTriggerReason } from './agent-error-detection.js'; import type { PairedExecutionLifecycle } from './message-agent-executor-paired.js'; import type { MessageAgentAttempt } from './message-agent-executor-attempt-runner.js'; import { @@ -59,7 +55,7 @@ interface ExecuteMessageAgentAttemptLifecycleArgs { result: null; error: string; }) => boolean; - rotationLogContext: { + retryLogContext: { chatJid: string; group: string; groupFolder: string; @@ -120,30 +116,13 @@ class MessageAgentAttemptLifecycleRunner { return this.rememberAttempt(await this.args.runAttempt(currentProvider)); } - private async retryCodexWithRotation( - initialTrigger: { reason: CodexRotationReason }, - rotationMessage?: string, + private async retryClaudeWithAuthRefresh( + initialTrigger: ClaudeTrigger, ): Promise { - return runCodexAttemptWithRotation({ - initialTrigger, - runAttempt: () => this.runTrackedAttempt('codex'), - logContext: this.args.rotationLogContext, - rotationMessage, - }); - } - - private async retryClaudeWithRotation( - initialTrigger: { - reason: AgentTriggerReason; - retryAfterMs?: number; - }, - rotationMessage?: string, - ): Promise { - return runClaudeAttemptWithRotation({ + return runClaudeAttemptWithAuthRefresh({ initialTrigger, runAttempt: () => this.runTrackedAttempt('claude'), - logContext: this.args.rotationLogContext, - rotationMessage, + logContext: this.args.retryLogContext, onSuccess: ({ sawOutput }) => { this.args.pairedExecutionLifecycle.markSawOutput(sawOutput); }, @@ -162,54 +141,25 @@ class MessageAgentAttemptLifecycleRunner { private async retryClaudeAttemptIfNeeded( attempt: MessageAgentAttempt, - rotationMessage?: string | null, + errorMessage?: string | null, ): Promise { - const retryAction = await executeAttemptRetryAction({ + const retry = await retryClaudeAttemptOnTrigger({ provider: this.args.provider, canRetryClaudeCredentials: this.args.canRetryClaudeCredentials, - canRetryCodex: false, attempt, - rotationMessage, - runClaude: (trigger, message) => - this.retryClaudeWithRotation(trigger, message), - runCodex: (trigger, message) => - this.retryCodexWithRotation(trigger, message), + errorMessage, + runClaude: (trigger) => this.retryClaudeWithAuthRefresh(trigger), }); - if (retryAction.kind !== 'claude') { + if (retry.kind !== 'claude') { return null; } - if (retryAction.result === 'error') { - return this.maybeHandoffAfterError(retryAction.trigger.reason, attempt); + if (retry.result === 'error') { + return this.maybeHandoffAfterError(retry.trigger.reason, attempt); } this.args.pairedExecutionLifecycle.markStatus('succeeded'); - return retryAction.result; - } - - private async retryCodexAttemptIfNeeded( - attempt: MessageAgentAttempt, - rotationMessage?: string | null, - ): Promise { - const retryAction = await executeAttemptRetryAction({ - provider: this.args.provider, - canRetryClaudeCredentials: false, - canRetryCodex: !this.args.isClaudeCodeAgent && getCodexAccountCount() > 1, - attempt, - rotationMessage, - runClaude: (trigger, message) => - this.retryClaudeWithRotation(trigger, message), - runCodex: (trigger, message) => - this.retryCodexWithRotation(trigger, message), - }); - if (retryAction.kind !== 'codex') { - return null; - } - - if (retryAction.result === 'success') { - this.args.pairedExecutionLifecycle.markStatus('succeeded'); - } - return retryAction.result; + return retry.result; } private isRetryableClaudeSessionFailure( @@ -288,25 +238,17 @@ class MessageAgentAttemptLifecycleRunner { private async handlePrimaryAttemptFailure( attempt: MessageAgentAttempt, - rotationMessage: string, + errorMessage: string, ): Promise { const { log, provider } = this.args; const claudeRetryResult = await this.retryClaudeAttemptIfNeeded( attempt, - rotationMessage, + errorMessage, ); if (claudeRetryResult) { return claudeRetryResult; } - const codexRetryResult = await this.retryCodexAttemptIfNeeded( - attempt, - rotationMessage, - ); - if (codexRetryResult) { - return codexRetryResult; - } - if (attempt.error) { log.error( { @@ -360,14 +302,6 @@ class MessageAgentAttemptLifecycleRunner { ); } - const codexRetryResult = await this.retryCodexAttemptIfNeeded( - attempt, - output.error ?? output.result, - ); - if (codexRetryResult) { - return codexRetryResult; - } - if (attempt.streamedTriggerReason) { if (this.resolveStreamedTriggerHandoff(attempt)) { return 'success'; diff --git a/src/message-agent-executor-rules.test.ts b/src/message-agent-executor-rules.test.ts index c5ceba1..03dbc0a 100644 --- a/src/message-agent-executor-rules.test.ts +++ b/src/message-agent-executor-rules.test.ts @@ -5,27 +5,17 @@ vi.mock('./agent-error-detection.js', async (importOriginal) => { await importOriginal(); return { ...actual, - classifyRotationTrigger: vi.fn(() => ({ + classifyClaudeTrigger: vi.fn(() => ({ shouldRetry: false, reason: '', })), }; }); -vi.mock('./codex-token-rotation.js', () => ({ - detectCodexRotationTrigger: vi.fn(() => ({ - shouldRotate: false, - reason: '', - })), -})); - -import { classifyRotationTrigger } from './agent-error-detection.js'; -import { detectCodexRotationTrigger } from './codex-token-rotation.js'; +import { classifyClaudeTrigger } from './agent-error-detection.js'; import { isRetryableClaudeSessionFailureAttempt, - resolveAttemptRetryAction, resolveClaudeRetryTrigger, - resolveCodexRetryTrigger, resolvePairedFollowUpQueueAction, } from './message-agent-executor-rules.js'; @@ -59,75 +49,7 @@ describe('message-agent-executor-rules', () => { fallbackMessage: '429 rate limit', }), ).toBeNull(); - expect(classifyRotationTrigger).not.toHaveBeenCalled(); - }); - - it('resolves a Codex retry trigger from the codex detector', () => { - vi.mocked(detectCodexRotationTrigger).mockReturnValue({ - shouldRotate: true, - reason: 'auth-expired', - }); - - expect( - resolveCodexRetryTrigger({ - canRetryCodex: true, - attempt: {}, - rotationMessage: '401 oauth token has expired', - }), - ).toEqual({ reason: 'auth-expired' }); - }); - - it('ignores streamed reasons that are not valid Codex rotation triggers', () => { - expect( - resolveCodexRetryTrigger({ - canRetryCodex: true, - attempt: { - streamedTriggerReason: { reason: 'usage-exhausted' }, - }, - }), - ).toBeNull(); - expect(detectCodexRotationTrigger).not.toHaveBeenCalled(); - }); - - it('resolves a shared Claude retry action from fallback output text', () => { - vi.mocked(classifyRotationTrigger).mockReturnValue({ - shouldRetry: true, - reason: '429', - retryAfterMs: 30000, - }); - - expect( - resolveAttemptRetryAction({ - provider: 'claude', - canRetryClaudeCredentials: true, - canRetryCodex: false, - attempt: { sawOutput: false }, - rotationMessage: '429 rate limit', - }), - ).toEqual({ - kind: 'claude', - trigger: { reason: '429', retryAfterMs: 30000 }, - rotationMessage: '429 rate limit', - }); - }); - - it('resolves a shared Codex retry action from streamed state', () => { - expect( - resolveAttemptRetryAction({ - provider: 'codex', - canRetryClaudeCredentials: false, - canRetryCodex: true, - attempt: { - sawOutput: false, - streamedTriggerReason: { reason: 'auth-expired' }, - }, - rotationMessage: 'oauth token expired', - }), - ).toEqual({ - kind: 'codex', - trigger: { reason: 'auth-expired' }, - rotationMessage: 'oauth token expired', - }); + expect(classifyClaudeTrigger).not.toHaveBeenCalled(); }); it('detects retryable Claude session failures from either flag or classifier', () => { diff --git a/src/message-agent-executor-rules.ts b/src/message-agent-executor-rules.ts index 203989f..150acca 100644 --- a/src/message-agent-executor-rules.ts +++ b/src/message-agent-executor-rules.ts @@ -8,10 +8,7 @@ import { parseVisibleVerdict } from './paired-verdict.js'; import type { PairedRoomRole, PairedTaskStatus } from './types.js'; export { isRetryableClaudeSessionFailureAttempt, - resolveAttemptRetryAction, resolveClaudeRetryTrigger, - resolveCodexRetryTrigger, - type AttemptRetryAction, } from './agent-attempt-retry.js'; export type PairedFollowUpQueueAction = 'pending' | 'none'; diff --git a/src/message-agent-executor-target.ts b/src/message-agent-executor-target.ts index 6b94fb3..68fd905 100644 --- a/src/message-agent-executor-target.ts +++ b/src/message-agent-executor-target.ts @@ -25,7 +25,7 @@ import { import { buildRoomRoleContext } from './room-role-context.js'; import { getEffectiveChannelLease } from './service-routing.js'; import { buildRoomMemoryBriefing } from './sqlite-memory-store.js'; -import { getTokenCount } from './token-rotation.js'; +import { getCurrentClaudeToken } from './claude-oauth-token.js'; import type { AgentType, PairedRoomRole, @@ -285,7 +285,7 @@ class MessageAgentExecutionTargetPreparer { } private canRetryClaudeCredentials(isClaudeCodeAgent: boolean): boolean { - return isClaudeCodeAgent && getTokenCount() > 0; + return isClaudeCodeAgent && Boolean(getCurrentClaudeToken()); } private preparePairedContext( diff --git a/src/message-agent-executor.test.ts b/src/message-agent-executor.test.ts index cc271e3..cf3aa0b 100644 --- a/src/message-agent-executor.test.ts +++ b/src/message-agent-executor.test.ts @@ -163,7 +163,7 @@ vi.mock('./agent-error-detection.js', async (importOriginal) => { await importOriginal(); return { ...actual, - classifyRotationTrigger: vi.fn((error?: string | null) => { + classifyClaudeTrigger: vi.fn((error?: string | null) => { const lower = (error || '').toLowerCase(); if ( lower.includes('does not have access to claude') || @@ -192,37 +192,14 @@ vi.mock('./session-recovery.js', () => ({ shouldRetryFreshSessionOnAgentFailure: vi.fn(() => false), })); -vi.mock('./token-rotation.js', () => ({ - rotateToken: vi.fn(() => false), - getTokenCount: vi.fn(() => 1), - getCurrentTokenIndex: vi.fn(() => 0), - markTokenHealthy: vi.fn(), +vi.mock('./claude-oauth-token.js', () => ({ + getCurrentClaudeToken: vi.fn(() => 'test-oauth-token'), })); vi.mock('./token-refresh.js', () => ({ forceRefreshToken: vi.fn(async () => null), })); -vi.mock('./codex-token-rotation.js', () => ({ - detectCodexRotationTrigger: vi.fn((error?: string | null) => { - const lower = (error || '').toLowerCase(); - if ( - lower.includes('429') || - lower.includes('rate limit') || - lower.includes('oauth token has expired') || - lower.includes('authentication_error') || - lower.includes('failed to authenticate') || - lower.includes('401') - ) { - return { shouldRotate: true, reason: 'auth-expired' }; - } - return { shouldRotate: false, reason: '' }; - }), - rotateCodexToken: vi.fn(() => false), - getCodexAccountCount: vi.fn(() => 1), - markCodexTokenHealthy: vi.fn(), -})); - vi.mock('./sqlite-memory-store.js', () => ({ buildRoomMemoryBriefing: vi.fn(), })); @@ -234,7 +211,6 @@ vi.mock('./paired-execution-context.js', () => ({ import * as agentRunner from './agent-runner.js'; import type { AgentOutput } from './agent-runner.js'; -import * as codexTokenRotation from './codex-token-rotation.js'; import * as db from './db.js'; import { logger } from './logger.js'; import { buildRoomMemoryBriefing } from './sqlite-memory-store.js'; @@ -244,7 +220,7 @@ import * as pairedExecutionContext from './paired-execution-context.js'; import * as sessionRecovery from './session-recovery.js'; import * as serviceRouting from './service-routing.js'; import * as tokenRefresh from './token-refresh.js'; -import * as tokenRotation from './token-rotation.js'; +import * as claudeOauthToken from './claude-oauth-token.js'; import type { RegisteredGroup } from './types.js'; function makeGroup(): RegisteredGroup { @@ -2776,121 +2752,18 @@ describe('runAgentForGroup room memory', () => { }); }); -describe('runAgentForGroup Claude rotation', () => { +describe('runAgentForGroup Claude failure recovery', () => { beforeEach(() => { vi.resetAllMocks(); resetPairedFollowUpScheduleState(); vi.mocked(buildRoomMemoryBriefing).mockResolvedValue(undefined); - vi.mocked(tokenRotation.getTokenCount).mockReturnValue(1); - vi.mocked(tokenRotation.getCurrentTokenIndex).mockReturnValue(0); - vi.mocked(tokenRotation.rotateToken).mockReturnValue(false); + vi.mocked(claudeOauthToken.getCurrentClaudeToken).mockReturnValue( + 'test-oauth-token', + ); vi.mocked(tokenRefresh.forceRefreshToken).mockResolvedValue(null); }); - it('rotates to another Claude account on usage exhaustion', async () => { - const outputs: string[] = []; - - vi.mocked(tokenRotation.getTokenCount).mockReturnValue(2); - vi.mocked(tokenRotation.rotateToken).mockReturnValueOnce(true); - - vi.mocked(agentRunner.runAgentProcess) - .mockImplementationOnce(async (_group, _input, _onProcess, onOutput) => { - await onOutput?.({ - status: 'success', - phase: 'final', - result: "You're out of extra usage · resets 4am (Asia/Seoul)", - }); - return { - status: 'success', - result: null, - }; - }) - .mockImplementationOnce(async (_group, _input, _onProcess, onOutput) => { - await onOutput?.({ - status: 'success', - phase: 'final', - result: '회전된 Claude 응답입니다.', - }); - return { - status: 'success', - result: null, - }; - }); - - const result = await runAgentForGroup(makeDeps(), { - group: makeGroup(), - prompt: 'hello', - chatJid: 'group@test', - runId: 'run-rotate-claude', - onOutput: async (output) => { - if (typeof output.result === 'string') outputs.push(output.result); - }, - }); - - expect(result).toBe('success'); - expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(2); - expect(tokenRotation.rotateToken).toHaveBeenCalledTimes(1); - expect(tokenRotation.markTokenHealthy).toHaveBeenCalledTimes(1); - // No fallback provider — rotation is the only recovery mechanism - expect(outputs).toEqual(['회전된 Claude 응답입니다.']); - }); - - it('rotates to another Claude account when Claude streams an OAuth expiry banner', async () => { - const outputs: string[] = []; - - vi.mocked(tokenRotation.getTokenCount).mockReturnValue(2); - vi.mocked(tokenRotation.rotateToken).mockReturnValueOnce(true); - - vi.mocked(agentRunner.runAgentProcess) - .mockImplementationOnce(async (_group, _input, _onProcess, onOutput) => { - await onOutput?.({ - status: 'success', - phase: 'intermediate', - result: - 'Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"Invalid authentication credentials"}}', - }); - await onOutput?.({ - status: 'success', - phase: 'final', - result: - 'Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"Invalid authentication credentials"}}', - }); - return { - status: 'success', - result: null, - }; - }) - .mockImplementationOnce(async (_group, _input, _onProcess, onOutput) => { - await onOutput?.({ - status: 'success', - phase: 'final', - result: '새 Claude 토큰 응답입니다.', - }); - return { - status: 'success', - result: null, - }; - }); - - const result = await runAgentForGroup(makeDeps(), { - group: makeGroup(), - prompt: 'hello', - chatJid: 'group@test', - runId: 'run-auth-expired-claude', - onOutput: async (output) => { - if (typeof output.result === 'string') outputs.push(output.result); - }, - }); - - expect(result).toBe('success'); - expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(2); - expect(tokenRotation.rotateToken).toHaveBeenCalledTimes(1); - expect(tokenRotation.markTokenHealthy).toHaveBeenCalledTimes(1); - // No fallback provider — rotation is the only recovery mechanism - expect(outputs).toEqual(['새 Claude 토큰 응답입니다.']); - }); - - it('force-refreshes the active Claude token before rotating on auth-expired', async () => { + it('force-refreshes the Claude token and retries once on auth-expired', async () => { const outputs: string[] = []; vi.mocked(tokenRefresh.forceRefreshToken).mockResolvedValueOnce( @@ -2940,15 +2813,14 @@ describe('runAgentForGroup Claude rotation', () => { expect(result).toBe('success'); expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(2); - expect(tokenRefresh.forceRefreshToken).toHaveBeenCalledWith(0); - expect(tokenRotation.rotateToken).not.toHaveBeenCalled(); - expect(tokenRotation.markTokenHealthy).toHaveBeenCalledTimes(1); + expect(tokenRefresh.forceRefreshToken).toHaveBeenCalledTimes(1); expect(outputs).toEqual(['force refresh 뒤 Claude 응답입니다.']); }); - it('marks paired execution as succeeded when Claude rotation recovers after a streamed auth-expired trigger', async () => { - vi.mocked(tokenRotation.getTokenCount).mockReturnValue(2); - vi.mocked(tokenRotation.rotateToken).mockReturnValueOnce(true); + it('marks paired execution as succeeded when a token refresh recovers a streamed auth-expired trigger', async () => { + vi.mocked(tokenRefresh.forceRefreshToken).mockResolvedValueOnce( + 'new-access-token', + ); vi.mocked( pairedExecutionContext.preparePairedExecutionContext, ).mockReturnValue({ @@ -3025,7 +2897,7 @@ describe('runAgentForGroup Claude rotation', () => { ); }); - it('suppresses Claude 502 HTML and returns error when no rotation is available', async () => { + it('suppresses Claude 502 HTML and returns error without retrying', async () => { const outputs: string[] = []; vi.mocked(agentRunner.runAgentProcess).mockImplementationOnce( @@ -3182,16 +3054,11 @@ describe('runAgentForGroup Claude rotation', () => { ); }); - it('returns error after all Claude accounts are usage-exhausted', async () => { + it('does not retry when Claude is usage-exhausted', async () => { const outputs: string[] = []; - vi.mocked(tokenRotation.getTokenCount).mockReturnValue(2); - vi.mocked(tokenRotation.rotateToken) - .mockReturnValueOnce(true) - .mockReturnValueOnce(false); - - vi.mocked(agentRunner.runAgentProcess) - .mockImplementationOnce(async (_group, _input, _onProcess, onOutput) => { + vi.mocked(agentRunner.runAgentProcess).mockImplementationOnce( + async (_group, _input, _onProcess, onOutput) => { await onOutput?.({ status: 'success', phase: 'final', @@ -3202,18 +3069,8 @@ describe('runAgentForGroup Claude rotation', () => { status: 'success', result: null, }; - }) - .mockImplementationOnce(async (_group, _input, _onProcess, onOutput) => { - await onOutput?.({ - status: 'success', - phase: 'final', - result: "You're out of extra usage \u00b7 resets 4am (Asia/Seoul)", - }); - return { - status: 'success', - result: null, - }; - }); + }, + ); const result = await runAgentForGroup(makeDeps(), { group: makeGroup(), @@ -3228,8 +3085,7 @@ describe('runAgentForGroup Claude rotation', () => { }); expect(result).toBe('success'); - expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(2); - expect(tokenRotation.rotateToken).toHaveBeenCalledTimes(2); + expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(1); expect(outputs).toEqual([]); expect(serviceRouting.activateCodexFailover).toHaveBeenCalledWith( 'group@test', @@ -3514,8 +3370,6 @@ describe('runAgentForGroup Claude rotation', () => { it('suppresses a usage-exhausted banner even when Claude already emitted progress text', async () => { const outputs: string[] = []; - vi.mocked(tokenRotation.getTokenCount).mockReturnValue(1); - vi.mocked(agentRunner.runAgentProcess).mockImplementationOnce( async (_group, _input, _onProcess, onOutput) => { await onOutput?.({ @@ -3550,20 +3404,11 @@ describe('runAgentForGroup Claude rotation', () => { expect(db.createServiceHandoff).not.toHaveBeenCalled(); }); - it('rotates to another Claude account when Claude streams an org access denied banner', async () => { + it('does not retry when Claude org access is denied', async () => { const outputs: string[] = []; - vi.mocked(tokenRotation.getTokenCount).mockReturnValue(2); - vi.mocked(tokenRotation.rotateToken).mockReturnValueOnce(true); - - vi.mocked(agentRunner.runAgentProcess) - .mockImplementationOnce(async (_group, _input, _onProcess, onOutput) => { - await onOutput?.({ - status: 'success', - phase: 'intermediate', - result: - 'Your organization does not have access to Claude. Please login again or contact your administrator.', - }); + vi.mocked(agentRunner.runAgentProcess).mockImplementationOnce( + async (_group, _input, _onProcess, onOutput) => { await onOutput?.({ status: 'success', phase: 'final', @@ -3574,116 +3419,8 @@ describe('runAgentForGroup Claude rotation', () => { status: 'success', result: null, }; - }) - .mockImplementationOnce(async (_group, _input, _onProcess, onOutput) => { - await onOutput?.({ - status: 'success', - phase: 'final', - result: 'org access denied 회전 성공 응답', - }); - return { - status: 'success', - result: null, - }; - }); - - const result = await runAgentForGroup(makeDeps(), { - group: makeGroup(), - prompt: 'hello', - chatJid: 'group@test', - runId: 'run-org-access-denied-claude', - onOutput: async (output) => { - if (typeof output.result === 'string') outputs.push(output.result); }, - }); - - expect(result).toBe('success'); - expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(2); - expect(tokenRotation.rotateToken).toHaveBeenCalledTimes(1); - expect(tokenRotation.markTokenHealthy).toHaveBeenCalledTimes(1); - // No fallback provider — rotation is the only recovery mechanism - expect(outputs).toEqual(['org access denied 회전 성공 응답']); - }); - - it('rotates when Claude surfaces 403 terminated as a success result', async () => { - const outputs: string[] = []; - - vi.mocked(tokenRotation.getTokenCount).mockReturnValue(2); - vi.mocked(tokenRotation.rotateToken).mockReturnValueOnce(true); - - vi.mocked(agentRunner.runAgentProcess) - .mockImplementationOnce(async (_group, _input, _onProcess, onOutput) => { - await onOutput?.({ - status: 'success', - phase: 'final', - result: 'Failed to authenticate. API Error: 403 terminated', - }); - return { - status: 'success', - result: null, - }; - }) - .mockImplementationOnce(async (_group, _input, _onProcess, onOutput) => { - await onOutput?.({ - status: 'success', - phase: 'final', - result: '403 회전 성공 응답', - }); - return { - status: 'success', - result: null, - }; - }); - - const result = await runAgentForGroup(makeDeps(), { - group: makeGroup(), - prompt: 'hello', - chatJid: 'group@test', - runId: 'run-403-success-rotation', - onOutput: async (output) => { - if (typeof output.result === 'string') outputs.push(output.result); - }, - }); - - expect(result).toBe('success'); - expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(2); - expect(tokenRotation.rotateToken).toHaveBeenCalledTimes(1); - expect(outputs).toEqual(['403 회전 성공 응답']); - }); - - it('returns error after all Claude accounts are org-access-denied', async () => { - const outputs: string[] = []; - - vi.mocked(tokenRotation.getTokenCount).mockReturnValue(2); - vi.mocked(tokenRotation.rotateToken) - .mockReturnValueOnce(true) - .mockReturnValueOnce(false); - - vi.mocked(agentRunner.runAgentProcess) - .mockImplementationOnce(async (_group, _input, _onProcess, onOutput) => { - await onOutput?.({ - status: 'success', - phase: 'final', - result: - 'Your organization does not have access to Claude. Please login again or contact your administrator.', - }); - return { - status: 'success', - result: null, - }; - }) - .mockImplementationOnce(async (_group, _input, _onProcess, onOutput) => { - await onOutput?.({ - status: 'error', - result: null, - error: 'Failed to authenticate. API Error: 403 terminated', - }); - return { - status: 'error', - result: null, - error: 'Failed to authenticate. API Error: 403 terminated', - }; - }); + ); const result = await runAgentForGroup(makeDeps(), { group: makeGroup(), @@ -3696,8 +3433,7 @@ describe('runAgentForGroup Claude rotation', () => { }); expect(result).toBe('success'); - expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(2); - expect(tokenRotation.rotateToken).toHaveBeenCalledTimes(2); + expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(1); expect(outputs).toEqual([]); expect(serviceRouting.activateCodexFailover).toHaveBeenCalledWith( 'group@test', @@ -3719,8 +3455,6 @@ describe('runAgentForGroup Claude rotation', () => { it('does not mistake a normal response quoting the banner text for a usage error', async () => { const outputs: string[] = []; - vi.mocked(tokenRotation.getTokenCount).mockReturnValue(2); - vi.mocked(agentRunner.runAgentProcess).mockImplementationOnce( async (_group, _input, _onProcess, onOutput) => { await onOutput?.({ @@ -3747,86 +3481,8 @@ describe('runAgentForGroup Claude rotation', () => { }); expect(result).toBe('success'); - expect(tokenRotation.rotateToken).not.toHaveBeenCalled(); expect(outputs).toEqual([ "상태 문구 예시: You're out of extra usage · resets 4am (Asia/Seoul) 라는 배너가 뜰 수 있습니다.", ]); }); }); - -describe('runAgentForGroup Codex rotation', () => { - beforeEach(() => { - vi.resetAllMocks(); - resetPairedFollowUpScheduleState(); - vi.mocked(buildRoomMemoryBriefing).mockResolvedValue(undefined); - vi.mocked(codexTokenRotation.getCodexAccountCount).mockReturnValue(2); - vi.mocked(codexTokenRotation.rotateCodexToken).mockReturnValueOnce(true); - }); - - it('retries Codex with a rotated account when OAuth auth expires', async () => { - const codexGroup: RegisteredGroup = { - ...makeGroup(), - folder: 'test-codex', - agentType: 'codex', - }; - const outputs: string[] = []; - - vi.mocked(serviceRouting.getEffectiveChannelLease).mockReturnValue({ - chat_jid: 'group@test', - owner_agent_type: 'codex', - reviewer_agent_type: 'codex', - arbiter_agent_type: null, - owner_service_id: 'codex-main', - reviewer_service_id: 'codex-review', - arbiter_service_id: null, - activated_at: null, - reason: null, - explicit: false, - }); - - vi.mocked(agentRunner.runAgentProcess) - .mockImplementationOnce(async (_group, _input, _onProcess, onOutput) => { - await onOutput?.({ - status: 'error', - result: null, - error: - 'Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"OAuth token has expired. Please obtain a new token or refresh your existing token."}}', - }); - return { - status: 'error', - result: null, - error: - 'Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"OAuth token has expired. Please obtain a new token or refresh your existing token."}}', - }; - }) - .mockImplementationOnce(async (_group, _input, _onProcess, onOutput) => { - await onOutput?.({ - status: 'success', - phase: 'final', - result: '새 계정으로 재시도 성공', - newSessionId: 'codex-thread-2', - }); - return { - status: 'success', - result: null, - newSessionId: 'codex-thread-2', - }; - }); - - const result = await runAgentForGroup(makeDeps(), { - group: codexGroup, - prompt: 'hello codex', - chatJid: 'group@test', - runId: 'run-codex-auth-expired', - onOutput: async (output) => { - if (typeof output.result === 'string') outputs.push(output.result); - }, - }); - - expect(result).toBe('success'); - expect(codexTokenRotation.rotateCodexToken).toHaveBeenCalledTimes(1); - expect(codexTokenRotation.markCodexTokenHealthy).toHaveBeenCalledTimes(1); - expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(2); - expect(outputs).toEqual(['새 계정으로 재시도 성공']); - }); -}); diff --git a/src/message-agent-executor.ts b/src/message-agent-executor.ts index 1aa11cc..00c844f 100644 --- a/src/message-agent-executor.ts +++ b/src/message-agent-executor.ts @@ -246,7 +246,7 @@ export async function runAgentForGroup( hasDirectTerminalDelivery, pairedExecutionLifecycle, shouldRetryFreshSessionOnAgentFailure, - rotationLogContext: { + retryLogContext: { chatJid, group: group.name, groupFolder: group.folder, diff --git a/src/provider-retry.test.ts b/src/provider-retry.test.ts deleted file mode 100644 index fc06628..0000000 --- a/src/provider-retry.test.ts +++ /dev/null @@ -1,284 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest'; - -vi.mock('./logger.js', () => ({ - logger: { - debug: vi.fn(), - info: vi.fn(), - warn: vi.fn(), - error: vi.fn(), - }, -})); - -vi.mock('./codex-token-rotation.js', () => ({ - detectCodexRotationTrigger: vi.fn(() => ({ - shouldRotate: false, - reason: '', - })), - getCodexAccountCount: vi.fn(() => 1), - markCodexTokenHealthy: vi.fn(), - rotateCodexToken: vi.fn(() => false), -})); - -vi.mock('./token-rotation.js', () => ({ - rotateToken: vi.fn(() => false), - getTokenCount: vi.fn(() => 1), - getCurrentTokenIndex: vi.fn(() => 0), - markTokenHealthy: vi.fn(), -})); - -vi.mock('./token-refresh.js', () => ({ - forceRefreshToken: vi.fn(async () => null), -})); - -import { runClaudeRotationLoop } from './provider-retry.js'; -import { runCodexRotationLoop } from './provider-retry.js'; -import { - detectCodexRotationTrigger, - getCodexAccountCount, - markCodexTokenHealthy, - rotateCodexToken, -} from './codex-token-rotation.js'; -import { - getCurrentTokenIndex, - getTokenCount, - markTokenHealthy, - rotateToken, -} from './token-rotation.js'; -import { forceRefreshToken } from './token-refresh.js'; - -describe('runClaudeRotationLoop', () => { - beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(getTokenCount).mockReturnValue(1); - vi.mocked(getCurrentTokenIndex).mockReturnValue(0); - vi.mocked(rotateToken).mockReturnValue(false); - vi.mocked(forceRefreshToken).mockResolvedValue(null); - }); - - it('rotates and succeeds after an org-access-denied trigger', async () => { - vi.mocked(getTokenCount).mockReturnValue(2); - vi.mocked(rotateToken).mockReturnValueOnce(true); - - const outcome = await runClaudeRotationLoop( - { reason: 'org-access-denied' }, - async () => ({ - output: { status: 'success', result: 'ok' }, - sawOutput: true, - }), - { runId: 'rotate-org-access' }, - ); - - expect(outcome).toEqual({ type: 'success', sawOutput: true }); - expect(rotateToken).toHaveBeenCalledTimes(1); - expect(markTokenHealthy).toHaveBeenCalledTimes(1); - }); - - it('returns error when all Claude tokens are exhausted', async () => { - vi.mocked(getTokenCount).mockReturnValue(2); - - const outcome = await runClaudeRotationLoop( - { reason: 'org-access-denied' }, - async () => ({ - output: { status: 'success', result: 'should not run' }, - sawOutput: true, - }), - { runId: 'no-fallback-org-access' }, - ); - - expect(outcome).toEqual({ - type: 'error', - trigger: { reason: 'org-access-denied' }, - }); - }); - - it('returns error with success-null-result trigger after rotation', async () => { - vi.mocked(getTokenCount).mockReturnValue(2); - vi.mocked(rotateToken).mockReturnValueOnce(true); - - const outcome = await runClaudeRotationLoop( - { reason: '429' }, - async () => ({ - output: { status: 'success', result: null }, - sawOutput: false, - sawSuccessNullResult: true, - }), - { runId: 'success-null-result' }, - ); - - expect(outcome).toEqual({ - type: 'error', - trigger: { reason: 'success-null-result' }, - }); - }); - - it('force-refreshes the active token before rotating on auth-expired', async () => { - vi.mocked(forceRefreshToken).mockResolvedValueOnce('new-access-token'); - - const outcome = await runClaudeRotationLoop( - { reason: 'auth-expired' }, - async () => ({ - output: { status: 'success', result: 'ok' }, - sawOutput: true, - }), - { runId: 'force-refresh-auth-expired' }, - ); - - expect(outcome).toEqual({ type: 'success', sawOutput: true }); - expect(forceRefreshToken).toHaveBeenCalledWith(0); - expect(rotateToken).not.toHaveBeenCalled(); - expect(markTokenHealthy).toHaveBeenCalledTimes(1); - }); - - it('falls back to rotation when force refresh does not recover auth-expired', async () => { - vi.mocked(getTokenCount).mockReturnValue(2); - vi.mocked(forceRefreshToken).mockResolvedValueOnce('new-access-token'); - vi.mocked(rotateToken).mockReturnValueOnce(true); - - let attempts = 0; - const outcome = await runClaudeRotationLoop( - { reason: 'auth-expired' }, - async () => { - attempts += 1; - if (attempts === 1) { - return { - output: { - status: 'error', - result: null, - error: - 'Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"Invalid authentication credentials"}}', - }, - sawOutput: false, - }; - } - - return { - output: { status: 'success', result: 'ok' }, - sawOutput: true, - }; - }, - { runId: 'force-refresh-then-rotate' }, - ); - - expect(outcome).toEqual({ type: 'success', sawOutput: true }); - expect(forceRefreshToken).toHaveBeenCalledWith(0); - expect(rotateToken).toHaveBeenCalledTimes(1); - expect(markTokenHealthy).toHaveBeenCalledTimes(1); - }); - - it('uses structured public output text as the next rotation message', async () => { - vi.mocked(getTokenCount).mockReturnValue(2); - vi.mocked(rotateToken).mockReturnValueOnce(true).mockReturnValueOnce(false); - - let attempts = 0; - const outcome = await runClaudeRotationLoop( - { reason: '429' }, - async () => { - attempts += 1; - if (attempts === 1) { - return { - output: { - status: 'success', - result: null, - output: { visibility: 'public', text: 'retry with next token' }, - }, - sawOutput: false, - streamedTriggerReason: { reason: 'usage-exhausted' }, - }; - } - - return { - output: { status: 'success', result: 'ok' }, - sawOutput: true, - }; - }, - { runId: 'structured-rotation-message' }, - ); - - expect(outcome).toEqual({ - type: 'error', - trigger: { reason: 'usage-exhausted' }, - }); - expect(rotateToken).toHaveBeenNthCalledWith(2, 'retry with next token'); - }); -}); - -describe('runCodexRotationLoop', () => { - beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(getCodexAccountCount).mockReturnValue(1); - vi.mocked(rotateCodexToken).mockReturnValue(false); - }); - - it('rotates and succeeds after a Codex auth trigger', async () => { - vi.mocked(getCodexAccountCount).mockReturnValue(2); - vi.mocked(rotateCodexToken).mockReturnValueOnce(true); - - const outcome = await runCodexRotationLoop( - { reason: 'auth-expired' }, - async () => ({ - output: { status: 'success', result: 'ok' }, - sawOutput: true, - }), - { runId: 'rotate-codex-auth' }, - ); - - expect(outcome).toEqual({ type: 'success' }); - expect(rotateCodexToken).toHaveBeenCalledTimes(1); - expect(rotateCodexToken).toHaveBeenCalledWith('auth-expired'); - expect(markCodexTokenHealthy).toHaveBeenCalledTimes(1); - }); - - it('continues rotation when streamed trigger arrives before visible output', async () => { - vi.mocked(getCodexAccountCount).mockReturnValue(2); - vi.mocked(rotateCodexToken) - .mockReturnValueOnce(true) - .mockReturnValueOnce(false); - - let attempts = 0; - const outcome = await runCodexRotationLoop( - { reason: 'auth-expired' }, - async () => { - attempts += 1; - if (attempts === 1) { - return { - output: { status: 'success', result: 'rotate next' }, - sawOutput: false, - streamedTriggerReason: { reason: 'auth-expired' }, - }; - } - - return { - output: { status: 'success', result: 'ok' }, - sawOutput: true, - }; - }, - { runId: 'rotate-codex-streamed' }, - ); - - expect(outcome).toEqual({ type: 'error' }); - expect(rotateCodexToken).toHaveBeenNthCalledWith(2, 'rotate next'); - }); - - it('uses the Codex detector for thrown errors', async () => { - vi.mocked(getCodexAccountCount).mockReturnValue(2); - vi.mocked(rotateCodexToken).mockReturnValueOnce(true); - vi.mocked(detectCodexRotationTrigger).mockReturnValue({ - shouldRotate: true, - reason: 'auth-expired', - }); - - const outcome = await runCodexRotationLoop( - { reason: 'auth-expired' }, - async () => ({ - thrownError: new Error('OAuth token expired'), - sawOutput: false, - }), - { runId: 'rotate-codex-error' }, - ); - - expect(outcome).toEqual({ type: 'error' }); - expect(detectCodexRotationTrigger).toHaveBeenCalledWith( - 'OAuth token expired', - ); - }); -}); diff --git a/src/provider-retry.ts b/src/provider-retry.ts deleted file mode 100644 index d384cdc..0000000 --- a/src/provider-retry.ts +++ /dev/null @@ -1,418 +0,0 @@ -/** - * Shared Claude retry-with-rotation loop (SSOT). - * - * Extracted from message-agent-executor.ts and task-scheduler.ts - * to eliminate the ~255-line structural duplication. - */ - -import type { AgentOutput } from './agent-runner.js'; -import { getAgentOutputText } from './agent-output.js'; -import { - classifyRotationTrigger, - type CodexRotationReason, - isCodexRotationReason, - shouldRotateClaudeToken, - type AgentTriggerReason, -} from './agent-error-detection.js'; -import { - detectCodexRotationTrigger, - getCodexAccountCount, - markCodexTokenHealthy, - rotateCodexToken, -} from './codex-token-rotation.js'; -import { logger } from './logger.js'; -import { getErrorMessage } from './utils.js'; -import { - getCurrentTokenIndex, - rotateToken, - getTokenCount, - markTokenHealthy, -} from './token-rotation.js'; -import { forceRefreshToken } from './token-refresh.js'; -import { clearGlobalFailover } from './service-routing.js'; - -// ── Types ──────────────────────────────────────────────────────── - -export interface TriggerInfo { - reason: AgentTriggerReason; - retryAfterMs?: number; - message?: string; -} - -export interface RotationAttemptResult { - output?: Pick; - thrownError?: unknown; - sawOutput: boolean; - sawSuccessNullResult?: boolean; - streamedTriggerReason?: TriggerInfo; -} - -export type RotationOutcome = - | { type: 'success'; sawOutput: boolean } - | { type: 'error'; trigger?: TriggerInfo }; - -export interface CodexRotationAttemptResult { - output?: Pick; - thrownError?: unknown; - sawOutput: boolean; - streamedTriggerReason?: TriggerInfo; -} - -export type CodexRotationOutcome = { type: 'success' } | { type: 'error' }; - -type AttemptOutcome = - | { type: 'success'; sawOutput: boolean } - | { type: 'error'; trigger?: TriggerInfo } - | { - type: 'continue'; - trigger: TriggerInfo; - rotationMessage?: string; - }; - -type CodexAttemptOutcome = - | { type: 'success' } - | { type: 'error' } - | { - type: 'continue'; - trigger: { reason: CodexRotationReason }; - rotationMessage?: string; - }; - -function evaluateClaudeAttempt( - attempt: RotationAttemptResult, - logContext: Record, -): AttemptOutcome { - if (attempt.thrownError) { - if (!attempt.sawOutput) { - const errMsg = getErrorMessage(attempt.thrownError); - const retryTrigger = attempt.streamedTriggerReason - ? { - shouldRetry: true, - reason: attempt.streamedTriggerReason.reason, - retryAfterMs: attempt.streamedTriggerReason.retryAfterMs, - } - : classifyRotationTrigger(errMsg); - if (retryTrigger.shouldRetry) { - return { - type: 'continue', - trigger: { - reason: retryTrigger.reason, - retryAfterMs: retryTrigger.retryAfterMs, - }, - rotationMessage: errMsg, - }; - } - } - - logger.error( - { ...logContext, provider: 'claude', err: attempt.thrownError }, - 'Rotated Claude account also threw', - ); - return { type: 'error' }; - } - - const output = attempt.output; - if (!output) { - logger.error( - { ...logContext, provider: 'claude' }, - 'Rotated Claude account produced no output object', - ); - return { type: 'error' }; - } - - if ( - !attempt.sawOutput && - attempt.streamedTriggerReason && - output.status !== 'error' - ) { - return { - type: 'continue', - trigger: { - reason: attempt.streamedTriggerReason.reason, - retryAfterMs: attempt.streamedTriggerReason.retryAfterMs, - }, - rotationMessage: getAgentOutputText(output) ?? undefined, - }; - } - - if (!attempt.sawOutput && attempt.sawSuccessNullResult) { - logger.warn( - { ...logContext, provider: 'claude' }, - 'All rotated tokens returned success with null result', - ); - return { type: 'error', trigger: { reason: 'success-null-result' } }; - } - - if (output.status === 'error') { - if (!attempt.sawOutput) { - const retryTrigger = attempt.streamedTriggerReason - ? { - shouldRetry: true, - reason: attempt.streamedTriggerReason.reason, - retryAfterMs: attempt.streamedTriggerReason.retryAfterMs, - } - : classifyRotationTrigger(output.error); - if (retryTrigger.shouldRetry) { - return { - type: 'continue', - trigger: { - reason: retryTrigger.reason, - retryAfterMs: retryTrigger.retryAfterMs, - }, - rotationMessage: output.error ?? undefined, - }; - } - } - - logger.error( - { ...logContext, provider: 'claude', error: output.error }, - 'Rotated Claude account failed', - ); - return { type: 'error' }; - } - - markTokenHealthy(); - clearGlobalFailover(); - return { type: 'success', sawOutput: attempt.sawOutput }; -} - -function evaluateCodexAttempt( - attempt: CodexRotationAttemptResult, - logContext: Record, -): CodexAttemptOutcome { - if (attempt.thrownError) { - const errMsg = getErrorMessage(attempt.thrownError); - const retryTrigger = detectCodexRotationTrigger(errMsg); - if (retryTrigger.shouldRotate) { - return { - type: 'continue', - trigger: { reason: retryTrigger.reason }, - rotationMessage: errMsg, - }; - } - - logger.error( - { ...logContext, provider: 'codex', err: attempt.thrownError }, - 'Rotated Codex account also threw', - ); - return { type: 'error' }; - } - - const output = attempt.output; - if (!output) { - logger.error( - { ...logContext, provider: 'codex' }, - 'Rotated Codex account produced no output object', - ); - return { type: 'error' }; - } - - if ( - !attempt.sawOutput && - typeof output.error === 'string' && - output.error.length > 0 - ) { - const retryTrigger = - attempt.streamedTriggerReason && - isCodexRotationReason(attempt.streamedTriggerReason.reason) - ? { - shouldRotate: true as const, - reason: attempt.streamedTriggerReason.reason, - } - : detectCodexRotationTrigger(output.error); - if (retryTrigger.shouldRotate) { - return { - type: 'continue', - trigger: { reason: retryTrigger.reason }, - rotationMessage: output.error, - }; - } - - logger.error( - { ...logContext, provider: 'codex', error: output.error }, - 'Rotated Codex account returned an error field without visible output', - ); - return { type: 'error' }; - } - - if ( - !attempt.sawOutput && - attempt.streamedTriggerReason && - output.status !== 'error' - ) { - if (!isCodexRotationReason(attempt.streamedTriggerReason.reason)) { - logger.error( - { - ...logContext, - provider: 'codex', - reason: attempt.streamedTriggerReason.reason, - }, - 'Unexpected non-Codex streamed trigger while rotating Codex account', - ); - return { type: 'error' }; - } - return { - type: 'continue', - trigger: { - reason: attempt.streamedTriggerReason.reason, - }, - rotationMessage: getAgentOutputText(output) ?? undefined, - }; - } - - if (output.status === 'error') { - const retryTrigger = - attempt.streamedTriggerReason && - isCodexRotationReason(attempt.streamedTriggerReason.reason) - ? { - shouldRotate: true as const, - reason: attempt.streamedTriggerReason.reason, - } - : detectCodexRotationTrigger(output.error); - if (retryTrigger.shouldRotate) { - return { - type: 'continue', - trigger: { reason: retryTrigger.reason }, - rotationMessage: output.error ?? undefined, - }; - } - - logger.error( - { ...logContext, provider: 'codex', error: output.error }, - 'Rotated Codex account failed', - ); - return { type: 'error' }; - } - - markCodexTokenHealthy(); - return { type: 'success' }; -} - -// ── Shared rotation loop ───────────────────────────────────────── - -/** - * Retry a Claude request by rotating through available tokens. - * - * Returns 'success' if a rotated token worked, or 'error' if all - * tokens are exhausted or the error is non-retryable. - */ -export async function runClaudeRotationLoop( - initialTrigger: TriggerInfo, - runAttempt: () => Promise, - logContext: Record, - rotationMessage?: string, -): Promise { - let trigger = initialTrigger; - let lastRotationMessage = rotationMessage; - const attemptedForcedRefreshIndexes = new Set(); - - while (shouldRotateClaudeToken(trigger.reason)) { - if (trigger.reason === 'auth-expired') { - const tokenIndex = getCurrentTokenIndex(); - if ( - tokenIndex != null && - !attemptedForcedRefreshIndexes.has(tokenIndex) - ) { - attemptedForcedRefreshIndexes.add(tokenIndex); - const refreshedToken = await forceRefreshToken(tokenIndex); - if (refreshedToken) { - logger.info( - { ...logContext, tokenIndex }, - 'Claude auth-expired recovered by force-refreshing current token', - ); - - const refreshAttemptOutcome = evaluateClaudeAttempt( - await runAttempt(), - logContext, - ); - if (refreshAttemptOutcome.type === 'success') { - return refreshAttemptOutcome; - } - if (refreshAttemptOutcome.type === 'error') { - return refreshAttemptOutcome; - } - - trigger = refreshAttemptOutcome.trigger; - lastRotationMessage = refreshAttemptOutcome.rotationMessage; - continue; - } - } - } - - if ( - !( - getTokenCount() > 1 && - // Respect per-token cooldowns so exhausted auth/quota failures can - // terminate instead of cycling forever. - rotateToken(lastRotationMessage) - ) - ) { - break; - } - - logger.info( - { ...logContext, reason: trigger.reason }, - 'Claude account unavailable, retrying with rotated account', - ); - - const rotatedAttemptOutcome = evaluateClaudeAttempt( - await runAttempt(), - logContext, - ); - if (rotatedAttemptOutcome.type === 'success') { - return rotatedAttemptOutcome; - } - if (rotatedAttemptOutcome.type === 'error') { - return rotatedAttemptOutcome; - } - - trigger = rotatedAttemptOutcome.trigger; - lastRotationMessage = rotatedAttemptOutcome.rotationMessage; - } - - // ── All tokens exhausted ── - logger.warn( - { ...logContext, reason: trigger.reason }, - `All Claude tokens exhausted (${trigger.reason})`, - ); - return { type: 'error', trigger }; -} - -export async function runCodexRotationLoop( - initialTrigger: { reason: CodexRotationReason; message?: string }, - runAttempt: () => Promise, - logContext: Record, - rotationMessage?: string, -): Promise { - let trigger = initialTrigger; - let lastRotationMessage = rotationMessage; - - while (getCodexAccountCount() > 1) { - const rotationReasonMessage = - lastRotationMessage ?? trigger.message ?? trigger.reason; - if (!rotateCodexToken(rotationReasonMessage)) { - break; - } - - logger.info( - { ...logContext, reason: trigger.reason }, - 'Codex account unhealthy, retrying with rotated account', - ); - - const rotatedAttemptOutcome = evaluateCodexAttempt( - await runAttempt(), - logContext, - ); - if (rotatedAttemptOutcome.type === 'success') { - return rotatedAttemptOutcome; - } - if (rotatedAttemptOutcome.type === 'error') { - return rotatedAttemptOutcome; - } - - trigger = rotatedAttemptOutcome.trigger; - lastRotationMessage = rotatedAttemptOutcome.rotationMessage; - } - - return { type: 'error' }; -} diff --git a/src/silent-owner-retry.test.ts b/src/silent-owner-retry.test.ts index 273511d..a0fd30d 100644 --- a/src/silent-owner-retry.test.ts +++ b/src/silent-owner-retry.test.ts @@ -5,7 +5,7 @@ import { createPairedTask, getPairedTaskById, } from './db.js'; -import { detectCodexRotationTrigger } from './codex-token-rotation.js'; +import { classifyCodexTrigger } from './agent-error-detection.js'; import { runQueuedGroupTurn } from './message-runtime-queue.js'; import { resolveNextTurnAction, @@ -72,12 +72,12 @@ describe('silent owner retry recovery', () => { resetPairedFollowUpScheduleState(); }); - it('treats Codex selected-model capacity as a rotation trigger', () => { + it('treats Codex selected-model capacity as an overloaded trigger', () => { expect( - detectCodexRotationTrigger( + classifyCodexTrigger( 'Selected model is at capacity. Please try a different model.', ), - ).toEqual({ shouldRotate: true, reason: 'overloaded' }); + ).toEqual({ triggered: true, reason: 'overloaded' }); }); it('maps active tasks with a previous silent owner failure to an owner retry', () => { diff --git a/src/streamed-output-evaluator.test.ts b/src/streamed-output-evaluator.test.ts index 75154df..b989b58 100644 --- a/src/streamed-output-evaluator.test.ts +++ b/src/streamed-output-evaluator.test.ts @@ -5,17 +5,14 @@ import type { AgentOutput } from './agent-runner.js'; // ── Mocks ────────────────────────────────────────────────────── vi.mock('./agent-error-detection.js', () => ({ classifyClaudeAuthError: vi.fn(() => ({ category: 'none', reason: '' })), - classifyRotationTrigger: vi.fn(() => ({ shouldRetry: false, reason: '' })), + classifyClaudeTrigger: vi.fn(() => ({ shouldRetry: false, reason: '' })), detectClaudeProviderFailureMessage: vi.fn(() => ''), isClaudeUsageExhaustedMessage: vi.fn(() => false), isClaudeOrgAccessDeniedMessage: vi.fn(() => false), isClaudeAuthExpiredMessage: vi.fn(() => false), isClaudeAuthError: vi.fn(() => false), -})); - -vi.mock('./codex-token-rotation.js', () => ({ - detectCodexRotationTrigger: vi.fn(() => ({ - shouldRotate: false, + classifyCodexTrigger: vi.fn(() => ({ + triggered: false, reason: '', })), })); @@ -27,14 +24,14 @@ vi.mock('./session-recovery.js', () => ({ import { classifyClaudeAuthError, - classifyRotationTrigger, + classifyClaudeTrigger, detectClaudeProviderFailureMessage, isClaudeUsageExhaustedMessage, isClaudeOrgAccessDeniedMessage, isClaudeAuthExpiredMessage, isClaudeAuthError, + classifyCodexTrigger, } from './agent-error-detection.js'; -import { detectCodexRotationTrigger } from './codex-token-rotation.js'; import { shouldRetryFreshCodexSessionOnAgentFailure, shouldRetryFreshSessionOnAgentFailure, @@ -82,7 +79,7 @@ beforeEach(() => { category: 'none', reason: '', }); - vi.mocked(classifyRotationTrigger).mockReturnValue({ + vi.mocked(classifyClaudeTrigger).mockReturnValue({ shouldRetry: false, reason: '', }); @@ -91,8 +88,8 @@ beforeEach(() => { vi.mocked(isClaudeOrgAccessDeniedMessage).mockReturnValue(false); vi.mocked(isClaudeAuthExpiredMessage).mockReturnValue(false); vi.mocked(isClaudeAuthError).mockReturnValue(false); - vi.mocked(detectCodexRotationTrigger).mockReturnValue({ - shouldRotate: false, + vi.mocked(classifyCodexTrigger).mockReturnValue({ + triggered: false, reason: '', }); vi.mocked(shouldRetryFreshCodexSessionOnAgentFailure).mockReturnValue(false); @@ -443,7 +440,7 @@ describe('evaluateStreamedOutput', () => { describe('evaluateStreamedOutput error handling', () => { describe('error → Claude rotation trigger', () => { it('returns rotation trigger with retryAfterMs', () => { - vi.mocked(classifyRotationTrigger).mockReturnValue({ + vi.mocked(classifyClaudeTrigger).mockReturnValue({ shouldRetry: true, reason: '429', retryAfterMs: 30000, @@ -467,7 +464,7 @@ describe('evaluateStreamedOutput error handling', () => { }); it('suppresses error forward when shortCircuitTriggeredErrors is set', () => { - vi.mocked(classifyRotationTrigger).mockReturnValue({ + vi.mocked(classifyClaudeTrigger).mockReturnValue({ shouldRetry: true, reason: '429', }); @@ -481,7 +478,7 @@ describe('evaluateStreamedOutput error handling', () => { }); it('skips rotation check when output was already seen', () => { - vi.mocked(classifyRotationTrigger).mockReturnValue({ + vi.mocked(classifyClaudeTrigger).mockReturnValue({ shouldRetry: true, reason: '429', }); @@ -496,7 +493,7 @@ describe('evaluateStreamedOutput error handling', () => { }); it('skips rotation check when already triggered', () => { - vi.mocked(classifyRotationTrigger).mockReturnValue({ + vi.mocked(classifyClaudeTrigger).mockReturnValue({ shouldRetry: true, reason: '429', }); @@ -517,8 +514,8 @@ describe('evaluateStreamedOutput error handling', () => { it('returns rotation trigger for Codex primary', () => { const errorMessage = 'unexpected status 401 Unauthorized: Missing bearer or basic authentication in header'; - vi.mocked(detectCodexRotationTrigger).mockReturnValue({ - shouldRotate: true, + vi.mocked(classifyCodexTrigger).mockReturnValue({ + triggered: true, reason: '429', }); @@ -538,14 +535,14 @@ describe('evaluateStreamedOutput error handling', () => { }); it('does not check Codex rotation for Claude agent type', () => { - vi.mocked(detectCodexRotationTrigger).mockReturnValue({ - shouldRotate: true, + vi.mocked(classifyCodexTrigger).mockReturnValue({ + triggered: true, reason: '429', }); evaluateStreamedOutput(errorOutput('429'), freshState(), claudeOpts); - // Claude uses classifyRotationTrigger, not detectCodexRotationTrigger - expect(detectCodexRotationTrigger).not.toHaveBeenCalled(); + // Claude uses classifyClaudeTrigger, not classifyCodexTrigger + expect(classifyCodexTrigger).not.toHaveBeenCalled(); }); }); diff --git a/src/streamed-output-evaluator.ts b/src/streamed-output-evaluator.ts index f60f7a7..caa5027 100644 --- a/src/streamed-output-evaluator.ts +++ b/src/streamed-output-evaluator.ts @@ -1,7 +1,8 @@ import { getAgentOutputText, hasAgentOutputPayload } from './agent-output.js'; import { classifyClaudeAuthError, - classifyRotationTrigger, + classifyCodexTrigger, + classifyClaudeTrigger, detectClaudeProviderFailureMessage, isClaudeAuthError, isClaudeAuthExpiredMessage, @@ -10,7 +11,6 @@ import { type AgentTriggerReason, } from './agent-error-detection.js'; import type { AgentOutput } from './agent-runner.js'; -import { detectCodexRotationTrigger } from './codex-token-rotation.js'; import { shouldRetryFreshCodexSessionOnAgentFailure, shouldRetryFreshSessionOnAgentFailure, @@ -115,8 +115,8 @@ export function evaluateStreamedOutput( !nextState.sawOutput && !nextState.streamedTriggerReason ) { - const trigger = detectCodexRotationTrigger(output.error); - if (trigger.shouldRotate) { + const trigger = classifyCodexTrigger(output.error); + if (trigger.triggered) { const newTrigger: StreamedTriggerReason = { reason: trigger.reason, message: output.error, @@ -138,7 +138,7 @@ export function evaluateStreamedOutput( let newTrigger: StreamedTriggerReason | undefined; if (primaryAgent === 'claude') { - const trigger = classifyRotationTrigger(output.error); + const trigger = classifyClaudeTrigger(output.error); if (trigger.shouldRetry) { newTrigger = { reason: trigger.reason, @@ -146,8 +146,8 @@ export function evaluateStreamedOutput( }; } } else if (primaryAgent === 'codex') { - const trigger = detectCodexRotationTrigger(output.error); - if (trigger.shouldRotate) { + const trigger = classifyCodexTrigger(output.error); + if (trigger.triggered) { newTrigger = { reason: trigger.reason, message: output.error }; } } diff --git a/src/task-scheduler.test.ts b/src/task-scheduler.test.ts index 6514376..357065e 100644 --- a/src/task-scheduler.test.ts +++ b/src/task-scheduler.test.ts @@ -29,7 +29,7 @@ vi.mock('./agent-error-detection.js', async (importOriginal) => { await importOriginal(); return { ...actual, - classifyRotationTrigger: vi.fn((error?: string | null) => { + classifyClaudeTrigger: vi.fn((error?: string | null) => { const lower = (error || '').toLowerCase(); if ( lower.includes('does not have access to claude') || @@ -51,37 +51,14 @@ vi.mock('./agent-error-detection.js', async (importOriginal) => { }; }); -vi.mock('./token-rotation.js', () => ({ - rotateToken: vi.fn(() => false), - getTokenCount: vi.fn(() => 1), - getCurrentTokenIndex: vi.fn(() => 0), - markTokenHealthy: vi.fn(), +vi.mock('./claude-oauth-token.js', () => ({ + getCurrentClaudeToken: vi.fn(() => 'test-oauth-token'), })); vi.mock('./token-refresh.js', () => ({ forceRefreshToken: vi.fn(async () => null), })); -vi.mock('./codex-token-rotation.js', () => ({ - detectCodexRotationTrigger: vi.fn((error?: string | null) => { - const lower = (error || '').toLowerCase(); - if ( - lower.includes('429') || - lower.includes('rate limit') || - lower.includes('oauth token has expired') || - lower.includes('authentication_error') || - lower.includes('failed to authenticate') || - lower.includes('401') - ) { - return { shouldRotate: true, reason: 'auth-expired' }; - } - return { shouldRotate: false, reason: '' }; - }), - rotateCodexToken: vi.fn(() => false), - getCodexAccountCount: vi.fn(() => 1), - markCodexTokenHealthy: vi.fn(), -})); - vi.mock('./agent-runner.js', async () => { const actual = await vi.importActual( @@ -149,13 +126,11 @@ import { createTask, getTaskById, } from './db.js'; -import * as codexTokenRotation from './codex-token-rotation.js'; import { TIMEZONE } from './config.js'; import * as serviceRouting from './service-routing.js'; import * as tokenRefresh from './token-refresh.js'; import { createTaskStatusTracker } from './task-status-tracker.js'; import { TASK_STATUS_MESSAGE_PREFIX } from './task-watch-status.js'; -import * as tokenRotation from './token-rotation.js'; import { _resetSchedulerLoopForTests, computeNextRun, @@ -193,17 +168,8 @@ describe('task scheduler', () => { resultSummary: 'GitHub Actions run 123 is in_progress', }); // No fallback provider setup needed - vi.mocked(tokenRotation.getTokenCount).mockReturnValue(1); - vi.mocked(tokenRotation.getCurrentTokenIndex).mockReturnValue(0); - vi.mocked(tokenRotation.markTokenHealthy).mockClear(); - vi.mocked(tokenRotation.rotateToken).mockClear(); - vi.mocked(tokenRotation.rotateToken).mockReturnValue(false); vi.mocked(tokenRefresh.forceRefreshToken).mockReset(); vi.mocked(tokenRefresh.forceRefreshToken).mockResolvedValue(null); - vi.mocked(codexTokenRotation.rotateCodexToken).mockClear(); - vi.mocked(codexTokenRotation.rotateCodexToken).mockReturnValue(false); - vi.mocked(codexTokenRotation.getCodexAccountCount).mockReturnValue(1); - vi.mocked(codexTokenRotation.markCodexTokenHealthy).mockClear(); vi.mocked(serviceRouting.hasReviewerLease).mockReturnValue(false); vi.useFakeTimers(); }); @@ -671,7 +637,7 @@ Check the run. expect(enqueueTask.mock.calls[0][1]).toBe('task-watch-group'); }); - it('suppresses Claude usage banners for scheduled tasks and retries with a rotated account', async () => { + it('suppresses Claude usage banners for scheduled tasks without retrying', async () => { const dueAt = new Date(Date.now() - 60_000).toISOString(); createTask({ id: 'task-usage-banner', @@ -687,49 +653,28 @@ Check the run. created_at: '2026-02-22T00:00:00.000Z', }); - vi.mocked(tokenRotation.getTokenCount).mockReturnValue(2); - vi.mocked(tokenRotation.rotateToken).mockReturnValueOnce(true); - - (runAgentProcessMock as any) - .mockImplementationOnce( - async ( - _group: unknown, - _input: unknown, - _onProcess: unknown, - onOutput?: (output: Record) => Promise, - ) => { - await onOutput?.({ - status: 'success', - phase: 'intermediate', - result: "You're out of extra usage · resets 4am (Asia/Seoul)", - }); - await onOutput?.({ - status: 'success', - result: "You're out of extra usage · resets 4am (Asia/Seoul)", - }); - return { - status: 'success', - result: null, - }; - }, - ) - .mockImplementationOnce( - async ( - _group: unknown, - _input: unknown, - _onProcess: unknown, - onOutput?: (output: Record) => Promise, - ) => { - await onOutput?.({ - status: 'success', - result: 'rotated scheduled task response', - }); - return { - status: 'success', - result: null, - }; - }, - ); + (runAgentProcessMock as any).mockImplementationOnce( + async ( + _group: unknown, + _input: unknown, + _onProcess: unknown, + onOutput?: (output: Record) => Promise, + ) => { + await onOutput?.({ + status: 'success', + phase: 'intermediate', + result: "You're out of extra usage · resets 4am (Asia/Seoul)", + }); + await onOutput?.({ + status: 'success', + result: "You're out of extra usage · resets 4am (Asia/Seoul)", + }); + return { + status: 'success', + result: null, + }; + }, + ); const enqueueTask = vi.fn( (_groupJid: string, _taskId: string, fn: () => Promise) => { @@ -757,18 +702,15 @@ Check the run. await vi.advanceTimersByTimeAsync(10); - expect(runAgentProcessMock).toHaveBeenCalledTimes(2); - expect(tokenRotation.rotateToken).toHaveBeenCalledTimes(1); - expect(tokenRotation.markTokenHealthy).toHaveBeenCalledTimes(1); - // No fallback cooldown to check - expect(sendMessage).toHaveBeenCalledTimes(1); - expect(sendMessage).toHaveBeenCalledWith( + expect(runAgentProcessMock).toHaveBeenCalledTimes(1); + expect(tokenRefresh.forceRefreshToken).not.toHaveBeenCalled(); + expect(sendMessage).not.toHaveBeenCalledWith( 'shared@g.us', - 'rotated scheduled task response', + expect.stringContaining('out of extra usage'), ); }); - it('suppresses Claude OAuth expiry banners for scheduled tasks and retries with a rotated account', async () => { + it('suppresses Claude OAuth expiry banners for scheduled tasks and retries after a token refresh', async () => { const dueAt = new Date(Date.now() - 60_000).toISOString(); createTask({ id: 'task-auth-expired-banner', @@ -784,8 +726,9 @@ Check the run. created_at: '2026-02-22T00:00:00.000Z', }); - vi.mocked(tokenRotation.getTokenCount).mockReturnValue(2); - vi.mocked(tokenRotation.rotateToken).mockReturnValueOnce(true); + vi.mocked(tokenRefresh.forceRefreshToken).mockResolvedValueOnce( + 'refreshed-token', + ); (runAgentProcessMock as any) .mockImplementationOnce( @@ -857,9 +800,7 @@ Check the run. await vi.advanceTimersByTimeAsync(10); expect(runAgentProcessMock).toHaveBeenCalledTimes(2); - expect(tokenRotation.rotateToken).toHaveBeenCalledTimes(1); - expect(tokenRotation.markTokenHealthy).toHaveBeenCalledTimes(1); - // No fallback cooldown to check + expect(tokenRefresh.forceRefreshToken).toHaveBeenCalledTimes(1); expect(sendMessage).toHaveBeenCalledTimes(1); expect(sendMessage).toHaveBeenCalledWith( 'shared@g.us', @@ -935,11 +876,10 @@ Check the run. await vi.advanceTimersByTimeAsync(10); expect(runAgentProcessMock).toHaveBeenCalledTimes(1); - expect(tokenRotation.rotateToken).not.toHaveBeenCalled(); - // No fallback — 502 results in error without retrying on another provider + // 502 results in an error without a retry }); - it('suppresses Claude org access denied banners for scheduled tasks and retries with a rotated account', async () => { + it('suppresses Claude org access denied banners for scheduled tasks without retrying', async () => { const dueAt = new Date(Date.now() - 60_000).toISOString(); createTask({ id: 'task-org-access-denied-banner', @@ -955,51 +895,30 @@ Check the run. created_at: '2026-02-22T00:00:00.000Z', }); - vi.mocked(tokenRotation.getTokenCount).mockReturnValue(2); - vi.mocked(tokenRotation.rotateToken).mockReturnValueOnce(true); - - (runAgentProcessMock as any) - .mockImplementationOnce( - async ( - _group: unknown, - _input: unknown, - _onProcess: unknown, - onOutput?: (output: Record) => Promise, - ) => { - await onOutput?.({ - status: 'success', - phase: 'intermediate', - result: - 'Your organization does not have access to Claude. Please login again or contact your administrator.', - }); - await onOutput?.({ - status: 'success', - result: - 'Your organization does not have access to Claude. Please login again or contact your administrator.', - }); - return { - status: 'success', - result: null, - }; - }, - ) - .mockImplementationOnce( - async ( - _group: unknown, - _input: unknown, - _onProcess: unknown, - onOutput?: (output: Record) => Promise, - ) => { - await onOutput?.({ - status: 'success', - result: 'rotated scheduled task org-access response', - }); - return { - status: 'success', - result: null, - }; - }, - ); + (runAgentProcessMock as any).mockImplementationOnce( + async ( + _group: unknown, + _input: unknown, + _onProcess: unknown, + onOutput?: (output: Record) => Promise, + ) => { + await onOutput?.({ + status: 'success', + phase: 'intermediate', + result: + 'Your organization does not have access to Claude. Please login again or contact your administrator.', + }); + await onOutput?.({ + status: 'success', + result: + 'Your organization does not have access to Claude. Please login again or contact your administrator.', + }); + return { + status: 'success', + result: null, + }; + }, + ); const enqueueTask = vi.fn( (_groupJid: string, _taskId: string, fn: () => Promise) => { @@ -1027,109 +946,10 @@ Check the run. await vi.advanceTimersByTimeAsync(10); - expect(runAgentProcessMock).toHaveBeenCalledTimes(2); - expect(tokenRotation.rotateToken).toHaveBeenCalledTimes(1); - expect(tokenRotation.markTokenHealthy).toHaveBeenCalledTimes(1); - // No fallback cooldown to check - expect(sendMessage).toHaveBeenCalledTimes(1); - expect(sendMessage).toHaveBeenCalledWith( + expect(runAgentProcessMock).toHaveBeenCalledTimes(1); + expect(sendMessage).not.toHaveBeenCalledWith( 'shared@g.us', - 'rotated scheduled task org-access response', - ); - }); - - it('retries Codex scheduled tasks with a rotated account on streamed auth expiry', async () => { - const dueAt = new Date(Date.now() - 60_000).toISOString(); - createTask({ - id: 'task-codex-auth-expired', - group_folder: 'shared-group', - chat_jid: 'shared@g.us', - agent_type: 'codex', - prompt: 'codex task', - schedule_type: 'once', - schedule_value: dueAt, - context_mode: 'isolated', - next_run: dueAt, - status: 'active', - created_at: '2026-02-22T00:00:00.000Z', - }); - - vi.mocked(codexTokenRotation.getCodexAccountCount).mockReturnValue(2); - vi.mocked(codexTokenRotation.rotateCodexToken).mockReturnValueOnce(true); - - (runAgentProcessMock as any) - .mockImplementationOnce( - async ( - _group: unknown, - _input: unknown, - _onProcess: unknown, - onOutput?: (output: Record) => Promise, - ) => { - await onOutput?.({ - status: 'error', - error: - 'Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"OAuth token has expired. Please obtain a new token or refresh your existing token."}}', - result: null, - }); - return { - status: 'error', - error: - 'Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"OAuth token has expired. Please obtain a new token or refresh your existing token."}}', - result: null, - }; - }, - ) - .mockImplementationOnce( - async ( - _group: unknown, - _input: unknown, - _onProcess: unknown, - onOutput?: (output: Record) => Promise, - ) => { - await onOutput?.({ - status: 'success', - result: 'rotated codex scheduled task response', - }); - return { - status: 'success', - result: null, - }; - }, - ); - - const enqueueTask = vi.fn( - (_groupJid: string, _taskId: string, fn: () => Promise) => { - void fn(); - }, - ); - const sendMessage = vi.fn(async () => {}); - - startSchedulerLoop({ - serviceAgentType: 'codex', - roomBindings: () => ({ - 'shared@g.us': { - name: 'Shared', - folder: 'shared-group', - trigger: '@Codex', - added_at: '2026-02-22T00:00:00.000Z', - agentType: 'codex', - }, - }), - getSessions: () => ({}), - queue: { enqueueTask } as any, - onProcess: () => {}, - sendMessage, - }); - - await vi.advanceTimersByTimeAsync(10); - - expect(runAgentProcessMock).toHaveBeenCalledTimes(2); - expect(codexTokenRotation.rotateCodexToken).toHaveBeenCalledTimes(1); - expect(codexTokenRotation.markCodexTokenHealthy).toHaveBeenCalledTimes(1); - expect(sendMessage).toHaveBeenCalledTimes(1); - expect(sendMessage).toHaveBeenCalledWith( - 'shared@g.us', - 'rotated codex scheduled task response', + expect.stringContaining('does not have access to Claude'), ); }); diff --git a/src/task-scheduler.ts b/src/task-scheduler.ts index 8eb95f9..547d99b 100644 --- a/src/task-scheduler.ts +++ b/src/task-scheduler.ts @@ -2,9 +2,9 @@ import { CronExpressionParser } from 'cron-parser'; import { getAgentOutputText } from './agent-output.js'; import { createEvaluatedOutputHandler } from './agent-attempt.js'; import { - executeAttemptRetryAction, - runClaudeAttemptWithRotation, - runCodexAttemptWithRotation, + retryClaudeAttemptOnTrigger, + runClaudeAttemptWithAuthRefresh, + type ClaudeTrigger, } from './agent-attempt-orchestration.js'; import { getErrorMessage } from './utils.js'; @@ -23,22 +23,8 @@ import { } from './db.js'; import { createScopedLogger, logger } from './logger.js'; import { createTaskStatusTracker } from './task-status-tracker.js'; -import { - detectCodexRotationTrigger, - rotateCodexToken, - getCodexAccountCount, - markCodexTokenHealthy, -} from './codex-token-rotation.js'; -import { - classifyRotationTrigger, - type AgentTriggerReason, - type CodexRotationReason, -} from './agent-error-detection.js'; -import { - getTokenCount, - markTokenHealthy, - rotateToken, -} from './token-rotation.js'; +import type { AgentTriggerReason } from './agent-error-detection.js'; +import { getCurrentClaudeToken } from './claude-oauth-token.js'; import { evaluateTaskSuspension, formatSuspensionNotice, @@ -319,49 +305,17 @@ async function runTask( }; }; - const retryClaudeTaskWithRotation = async ( - initialTrigger: { - reason: AgentTriggerReason; - retryAfterMs?: number; - }, - rotationMessage?: string, + const retryClaudeTaskWithAuthRefresh = async ( + initialTrigger: ClaudeTrigger, ): Promise<'success' | 'error'> => { - const logContext = { - taskId: task.id, - group: context.group.name, - groupFolder: task.group_folder, - }; - - const outcome = await runClaudeAttemptWithRotation({ + const outcome = await runClaudeAttemptWithAuthRefresh({ initialTrigger, runAttempt: () => runTaskAttempt('claude'), - logContext, - rotationMessage, - afterAttempt: (attempt) => { - result = attempt.attemptResult; - error = attempt.attemptError; - }, - }); - - if (outcome === 'success') { - error = null; - } - return outcome; - }; - - const retryCodexTaskWithRotation = async ( - initialTrigger: { reason: CodexRotationReason }, - rotationMessage?: string, - ): Promise<'success' | 'error'> => { - const outcome = await runCodexAttemptWithRotation({ - initialTrigger, - runAttempt: () => runTaskAttempt('codex'), logContext: { taskId: task.id, group: context.group.name, groupFolder: task.group_folder, }, - rotationMessage, afterAttempt: (attempt) => { result = attempt.attemptResult; error = attempt.attemptError; @@ -381,14 +335,13 @@ async function runTask( result = attempt.attemptResult; error = attempt.attemptError; - const retryAction = await executeAttemptRetryAction({ + const retryAction = await retryClaudeAttemptOnTrigger({ provider, - canRetryClaudeCredentials: provider === 'claude' && getTokenCount() > 0, - canRetryCodex: provider === 'codex' && getCodexAccountCount() > 1, + canRetryClaudeCredentials: + provider === 'claude' && Boolean(getCurrentClaudeToken()), attempt, - rotationMessage: error, - runClaude: retryClaudeTaskWithRotation, - runCodex: retryCodexTaskWithRotation, + errorMessage: error, + runClaude: retryClaudeTaskWithAuthRefresh, }); if (retryAction.kind === 'none' && attempt.output.status === 'error') { @@ -423,47 +376,6 @@ async function runTask( updateTask(task.id, { suspended_until: null }); } - // Try token rotation before suspending - if (error) { - const effectiveAgentType = context.taskAgentType; - const isCodex = effectiveAgentType === 'codex'; - if (isCodex) { - const trigger = detectCodexRotationTrigger(error); - if (trigger.shouldRotate) { - const rotated = getCodexAccountCount() > 1 && rotateCodexToken(error); - if (rotated) { - log.info( - { - agent: effectiveAgentType, - reason: trigger.reason, - }, - 'Task rate-limited, rotated token — will retry on next schedule', - ); - markCodexTokenHealthy(); - // Clear the error so suspension doesn't trigger - error = null; - } - } - } else { - const trigger = classifyRotationTrigger(error); - if (trigger.shouldRetry) { - const rotated = getTokenCount() > 1 && rotateToken(error); - if (rotated) { - log.info( - { - agent: effectiveAgentType, - reason: trigger.reason, - }, - 'Task rate-limited, rotated token — will retry on next schedule', - ); - markTokenHealthy(); - // Clear the error so suspension doesn't trigger - error = null; - } - } - } - } - // Check for repeated quota/auth errors → auto-suspend let suspended = false; if (error) { diff --git a/src/token-refresh.test.ts b/src/token-refresh.test.ts index 1c81bcc..a39ee85 100644 --- a/src/token-refresh.test.ts +++ b/src/token-refresh.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; import { - applyUpdatedTokensToEnvContent, + applyUpdatedTokenToEnvContent, collectSessionCredentialPaths, pickFreshestOAuth, shouldAdoptSessionOAuth, @@ -28,31 +28,34 @@ describe('shouldStartTokenRefreshLoop', () => { expect(shouldStartTokenRefreshLoop('codex')).toBe(false); }); - it('updates both multi-token and single-token env vars when present', () => { - const next = applyUpdatedTokensToEnvContent( + it('rewrites both the single-token and legacy list env vars when present', () => { + const next = applyUpdatedTokenToEnvContent( [ 'CLAUDE_CODE_OAUTH_TOKEN=old-primary', - 'CLAUDE_CODE_OAUTH_TOKENS=old-primary,old-secondary', + 'CLAUDE_CODE_OAUTH_TOKENS=old-primary', 'OTHER=value', ].join('\n'), - ['new-primary', 'new-secondary'], + 'new-primary', ); expect(next).toContain('CLAUDE_CODE_OAUTH_TOKEN=new-primary'); - expect(next).toContain( - 'CLAUDE_CODE_OAUTH_TOKENS=new-primary,new-secondary', - ); + expect(next).toContain('CLAUDE_CODE_OAUTH_TOKENS=new-primary'); + expect(next).toContain('OTHER=value'); }); - it('adds the multi-token env var when it is missing', () => { - const next = applyUpdatedTokensToEnvContent( + it('only rewrites the single-token env var when the list is absent', () => { + const next = applyUpdatedTokenToEnvContent( ['CLAUDE_CODE_OAUTH_TOKEN=old-primary', 'OTHER=value'].join('\n'), - ['new-primary', 'new-secondary'], + 'new-primary', ); expect(next).toContain('CLAUDE_CODE_OAUTH_TOKEN=new-primary'); - expect(next).toContain( - 'CLAUDE_CODE_OAUTH_TOKENS=new-primary,new-secondary', + expect(next).not.toContain('CLAUDE_CODE_OAUTH_TOKENS'); + }); + + it('appends CLAUDE_CODE_OAUTH_TOKEN when neither var exists', () => { + expect(applyUpdatedTokenToEnvContent('OTHER=value\n', 'tok')).toBe( + 'OTHER=value\nCLAUDE_CODE_OAUTH_TOKEN=tok\n', ); }); }); diff --git a/src/token-refresh.ts b/src/token-refresh.ts index efb0cd1..6afae28 100644 --- a/src/token-refresh.ts +++ b/src/token-refresh.ts @@ -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(); +// 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(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(sessionPath), - }); - } + for (const sessionPath of listSessionCredentialPaths()) { + candidates.push({ + label: sessionPath, + creds: readJsonFile(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(fn: () => Promise): Promise { } /** - * 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 { - return serializeRefresh(() => doCheckAndRefreshAccount(accountIndex, opts)); +async function checkAndRefreshCredentials(opts?: { + force?: boolean; +}): Promise { + return serializeRefresh(() => doCheckAndRefreshCredentials(opts)); } -async function doCheckAndRefreshAccount( - accountIndex: number, - opts?: { force?: boolean }, -): Promise { - const freshest = loadFreshestCredentials(accountIndex); +async function doCheckAndRefreshCredentials(opts?: { + force?: boolean; +}): Promise { + 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 { - 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 { + const newAccessToken = await checkAndRefreshCredentials(); + if (newAccessToken) applyRefreshedAccessToken(newAccessToken); } let refreshInterval: ReturnType | 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 { - logger.info({ tokenIndex }, 'Force-refreshing token after 401'); +export async function forceRefreshToken(): Promise { + 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; } diff --git a/src/token-rotation-base.ts b/src/token-rotation-base.ts deleted file mode 100644 index 6acaab4..0000000 --- a/src/token-rotation-base.ts +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Token Rotation Base Utilities (SSOT) - * - * Shared algorithms for Claude and Codex token rotation. - * Extracted from token-rotation.ts and codex-token-rotation.ts - * to eliminate duplicate implementations. - */ - -export const BUFFER_MS = 3 * 60_000; // 3 min buffer after reset time -export const DEFAULT_COOLDOWN_MS = 3_600_000; // 1 hour fallback - -/** - * Parse "try again at Mar 26th, 2026 9:00 AM" or "resets at ..." from - * an error message. Returns timestamp in ms, or null if not found. - * - * Uses the wider regex from token-rotation.ts that also matches - * "resets at" patterns (codex-token-rotation only matched "try again at"). - */ -export function parseRetryAfterFromError(error?: string): number | null { - if (!error) return null; - const match = error.match( - /(?:try again at|resets?\s+(?:at\s+)?)\s*(\w+ \d{1,2}(?:st|nd|rd|th)?,?\s+\d{4}\s+\d{1,2}:\d{2}\s*(?:AM|PM)?)/i, - ); - if (!match) return null; - try { - const cleaned = match[1].replace(/(\d+)(?:st|nd|rd|th)/i, '$1'); - const ts = new Date(cleaned).getTime(); - if (Number.isNaN(ts)) return null; - return ts; - } catch { - return null; - } -} - -/** - * Compute when a rate-limited token should become available again. - * Parses retry-after from error message, falling back to DEFAULT_COOLDOWN_MS. - */ -export function computeCooldownUntil(error?: string): number { - const retryAt = parseRetryAfterFromError(error); - if (retryAt) return retryAt + BUFFER_MS; - return Date.now() + DEFAULT_COOLDOWN_MS; -} - -/** - * Find the next available (non-rate-limited) item in a rotation pool. - * Returns the index, or null if all are exhausted. - * - * This is the shared rotation algorithm used by both Claude token rotation - * and Codex account rotation. - */ -export function findNextAvailable< - T extends { rateLimitedUntil: number | null }, ->( - items: T[], - currentIndex: number, - opts?: { ignoreRateLimits?: boolean }, -): number | null { - const now = Date.now(); - const ignoreRL = opts?.ignoreRateLimits ?? false; - - for (let i = 1; i < items.length; i++) { - const idx = (currentIndex + i) % items.length; - const item = items[idx]; - if (ignoreRL || !item.rateLimitedUntil || item.rateLimitedUntil <= now) { - return idx; - } - } - - return null; -} diff --git a/src/token-rotation.test.ts b/src/token-rotation.test.ts deleted file mode 100644 index 139cdfd..0000000 --- a/src/token-rotation.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; - -vi.mock('./config.js', () => ({ - DATA_DIR: '/tmp/ejclaw-claude-rot-data', -})); - -vi.mock('./env.js', () => ({ - getEnv: vi.fn((key: string) => process.env[key]), -})); - -vi.mock('./logger.js', () => ({ - logger: { - info: vi.fn(), - warn: vi.fn(), - error: vi.fn(), - debug: vi.fn(), - }, -})); - -vi.mock('./utils.js', async () => { - const actual = - await vi.importActual('./utils.js'); - return { - ...actual, - readJsonFile: vi.fn(() => null), - writeJsonFile: vi.fn(), - }; -}); - -describe('token-rotation runtime reselection', () => { - beforeEach(() => { - vi.resetModules(); - vi.useFakeTimers(); - vi.setSystemTime(new Date('2026-04-02T12:00:00.000Z')); - process.env.CLAUDE_CODE_OAUTH_TOKENS = 'token-1,token-2'; - delete process.env.CLAUDE_CODE_OAUTH_TOKEN; - }); - - afterEach(() => { - vi.useRealTimers(); - delete process.env.CLAUDE_CODE_OAUTH_TOKENS; - delete process.env.CLAUDE_CODE_OAUTH_TOKEN; - }); - - it('returns to the preferred healthy token after the cooldown expires at runtime', async () => { - const mod = await import('./token-rotation.js'); - - mod.initTokenRotation(); - expect(mod.getCurrentToken()).toBe('token-1'); - - expect(mod.rotateToken('rate limit')).toBe(true); - expect(mod.getCurrentToken()).toBe('token-2'); - expect(mod.getTokenRotationInfo()).toMatchObject({ - total: 2, - currentIndex: 1, - rateLimited: 1, - }); - - vi.advanceTimersByTime(60 * 60 * 1000 + 1); - - expect(mod.getCurrentToken()).toBe('token-1'); - expect(mod.getTokenRotationInfo()).toMatchObject({ - total: 2, - currentIndex: 0, - rateLimited: 0, - }); - }); - - it('reloads Claude rotation state from disk written by another service', async () => { - const mod = await import('./token-rotation.js'); - const utils = await import('./utils.js'); - const readJsonFile = vi.mocked(utils.readJsonFile); - - readJsonFile.mockReturnValueOnce(null); - mod.initTokenRotation(); - expect(mod.getCurrentToken()).toBe('token-1'); - - readJsonFile.mockReturnValueOnce({ - currentIndex: 1, - rateLimits: [Date.now() + 60_000, null], - }); - mod.reloadTokenRotationStateFromDisk(); - - expect(mod.getCurrentTokenIndex()).toBe(1); - expect(mod.getCurrentToken()).toBe('token-2'); - }); - - it('warns when Claude rotation state cannot be persisted', async () => { - const mod = await import('./token-rotation.js'); - const utils = await import('./utils.js'); - const { logger } = await import('./logger.js'); - - vi.mocked(utils.writeJsonFile).mockImplementation(() => { - throw new Error('disk full'); - }); - - mod.initTokenRotation(); - expect(mod.rotateToken('rate limit')).toBe(true); - - expect(logger.warn).toHaveBeenCalledWith( - expect.objectContaining({ - stateFile: '/tmp/ejclaw-claude-rot-data/token-rotation-state.json', - err: expect.any(Error), - }), - 'Failed to persist Claude token rotation state', - ); - }); - - it('treats CLAUDE_CODE_OAUTH_TOKENS as the canonical fallback even before init', async () => { - const mod = await import('./token-rotation.js'); - - expect(mod.getConfiguredClaudeTokens()).toEqual(['token-1', 'token-2']); - expect(mod.getCurrentToken()).toBe('token-1'); - expect(mod.hasAvailableClaudeToken()).toBe(true); - }); -}); diff --git a/src/token-rotation.ts b/src/token-rotation.ts deleted file mode 100644 index eae26dd..0000000 --- a/src/token-rotation.ts +++ /dev/null @@ -1,317 +0,0 @@ -/** - * OAuth Token Rotation - * - * Rotates between multiple Claude Code OAuth tokens when - * rate-limited. Tokens are stored as comma-separated values in the - * canonical CLAUDE_CODE_OAUTH_TOKENS env var and fall through to the - * legacy single-token CLAUDE_CODE_OAUTH_TOKEN when needed. - * - * On rate-limit: rotate to next token - * All exhausted: surface error to caller - */ - -import path from 'path'; - -import { DATA_DIR } from './config.js'; -import { getEnv } from './env.js'; -import { logger } from './logger.js'; -import { - computeCooldownUntil, - findNextAvailable, -} from './token-rotation-base.js'; -import { readJsonFile, writeJsonFile } from './utils.js'; - -const STATE_FILE = path.join(DATA_DIR, 'token-rotation-state.json'); - -interface TokenState { - token: string; - rateLimitedUntil: number | null; -} - -const tokens: TokenState[] = []; -let currentIndex = 0; -let initialized = false; - -export function getConfiguredClaudeTokens(options?: { - multi?: string | undefined; - single?: string | undefined; -}): string[] { - const multi = options?.multi ?? getEnv('CLAUDE_CODE_OAUTH_TOKENS'); - const single = options?.single ?? getEnv('CLAUDE_CODE_OAUTH_TOKEN'); - - if (multi) { - return multi - .split(',') - .map((token) => token.trim()) - .filter(Boolean); - } - - return single ? [single] : []; -} - -export function initTokenRotation(): void { - if (initialized) return; - initialized = true; - - const raw = getConfiguredClaudeTokens(); - - for (const token of raw) { - tokens.push({ token, rateLimitedUntil: null }); - } - - if (tokens.length > 1) { - loadState(); - logger.info( - { count: tokens.length, activeIndex: currentIndex }, - `Token rotation initialized with ${tokens.length} tokens`, - ); - } -} - -function saveState(): void { - try { - const state = { - currentIndex, - rateLimits: tokens.map((t) => t.rateLimitedUntil), - }; - writeJsonFile(STATE_FILE, state); - } catch (err) { - logger.warn( - { stateFile: STATE_FILE, err }, - 'Failed to persist Claude token rotation state', - ); - } -} - -function loadState(quiet = false): void { - const state = readJsonFile<{ - currentIndex?: number; - rateLimits?: (number | null)[]; - }>(STATE_FILE); - if (!state) return; - - const now = Date.now(); - if ( - typeof state.currentIndex === 'number' && - state.currentIndex < tokens.length - ) { - currentIndex = state.currentIndex; - } - if (Array.isArray(state.rateLimits)) { - for (let i = 0; i < Math.min(state.rateLimits.length, tokens.length); i++) { - const until = state.rateLimits[i]; - if (typeof until === 'number' && until > now) { - tokens[i].rateLimitedUntil = until; - } else { - tokens[i].rateLimitedUntil = null; - } - } - } - if (!quiet) { - logger.info( - { currentIndex, tokenCount: tokens.length }, - 'Token rotation state restored', - ); - } -} - -/** - * Re-read the on-disk rotation state (written by any service). - * Call before dashboard renders so the renderer picks up rotations - * performed by another Claude service process. - */ -export function reloadTokenRotationStateFromDisk(): void { - if (tokens.length <= 1) return; - loadState(true); -} - -function refreshRuntimeTokenSelection(): void { - if (tokens.length <= 1) return; - - const now = Date.now(); - const previousIndex = currentIndex; - let expiredCooldowns = 0; - - for (const token of tokens) { - if (token.rateLimitedUntil && token.rateLimitedUntil <= now) { - token.rateLimitedUntil = null; - expiredCooldowns += 1; - } - } - - const preferredIndex = tokens.findIndex( - (token) => !token.rateLimitedUntil || token.rateLimitedUntil <= now, - ); - if (preferredIndex !== -1) { - currentIndex = preferredIndex; - } - - if (expiredCooldowns > 0 || currentIndex !== previousIndex) { - logger.info( - { - previousIndex, - currentIndex, - expiredCooldowns, - }, - 'Refreshed Claude token runtime selection', - ); - saveState(); - } -} - -/** Get the current active token. */ -export function getCurrentToken(): string | undefined { - if (tokens.length === 0) return getConfiguredClaudeTokens()[0]; - refreshRuntimeTokenSelection(); - return tokens[currentIndex % tokens.length]?.token; -} - -/** Get the current active token index. */ -export function getCurrentTokenIndex(): number | null { - if (tokens.length === 0) return null; - refreshRuntimeTokenSelection(); - return currentIndex % tokens.length; -} - -/** - * Try to rotate to the next available (non-rate-limited) token. - * Returns true if a fresh token was found, false if all are exhausted. - */ -export function rotateToken( - errorMessage?: string, - opts?: { ignoreRateLimits?: boolean }, -): boolean { - if (tokens.length <= 1) return false; - - const previousIndex = currentIndex; - const cooldownUntil = computeCooldownUntil(errorMessage); - tokens[currentIndex].rateLimitedUntil = cooldownUntil; - - const nextIdx = findNextAvailable(tokens, currentIndex, opts); - if (nextIdx !== null) { - tokens[nextIdx].rateLimitedUntil = null; - currentIndex = nextIdx; - logger.info( - { - transition: 'rotation:execute', - fromIndex: previousIndex, - toIndex: currentIndex, - totalTokens: tokens.length, - ignoreRL: opts?.ignoreRateLimits ?? false, - cooldownUntil: - cooldownUntil != null ? new Date(cooldownUntil).toISOString() : null, - reason: errorMessage ?? null, - }, - `Rotated to token #${currentIndex + 1}/${tokens.length}`, - ); - saveState(); - return true; - } - - logger.warn( - { - transition: 'rotation:skip', - fromIndex: previousIndex, - totalTokens: tokens.length, - ignoreRL: opts?.ignoreRateLimits ?? false, - cooldownUntil: - cooldownUntil != null ? new Date(cooldownUntil).toISOString() : null, - reason: errorMessage ?? null, - }, - 'All tokens are rate-limited, no available tokens', - ); - return false; -} - -/** Clear rate-limit flag for the current token (on successful response). */ -export function markTokenHealthy(): void { - if (tokens.length === 0) return; - const state = tokens[currentIndex]; - let updated = false; - if (state?.rateLimitedUntil) { - const previousCooldownUntil = state.rateLimitedUntil; - state.rateLimitedUntil = null; - updated = true; - logger.info( - { - transition: 'rotation:clear-rate-limit', - tokenIndex: currentIndex, - cooldownUntil: new Date(previousCooldownUntil).toISOString(), - }, - 'Cleared Claude token rate-limit state after successful response', - ); - } - refreshRuntimeTokenSelection(); - if (updated) saveState(); -} - -/** Number of configured tokens. */ -export function getTokenCount(): number { - return tokens.length; -} - -/** Get all configured tokens (masked for display, raw for API calls). */ -export function getAllTokens(): { - index: number; - token: string; - masked: string; - isActive: boolean; - isRateLimited: boolean; -}[] { - refreshRuntimeTokenSelection(); - const now = Date.now(); - return tokens.map((t, i) => ({ - index: i, - token: t.token, - masked: `${t.token.slice(0, 20)}...${t.token.slice(-4)}`, - isActive: i === currentIndex, - isRateLimited: Boolean(t.rateLimitedUntil && t.rateLimitedUntil > now), - })); -} - -/** Update the access token value for a specific index (after OAuth refresh). */ -export function updateTokenValue(index: number, newAccessToken: string): void { - if (index < 0 || index >= tokens.length) { - logger.warn( - { index, total: tokens.length }, - 'updateTokenValue: index out of range', - ); - return; - } - tokens[index].token = newAccessToken; - logger.info( - { - index, - masked: `${newAccessToken.slice(0, 20)}...${newAccessToken.slice(-4)}`, - }, - 'Token value updated after OAuth refresh', - ); -} - -/** Diagnostic info. */ -export function getTokenRotationInfo(): { - total: number; - currentIndex: number; - rateLimited: number; -} { - refreshRuntimeTokenSelection(); - const now = Date.now(); - return { - total: tokens.length, - currentIndex, - rateLimited: tokens.filter( - (t) => t.rateLimitedUntil && t.rateLimitedUntil > now, - ).length, - }; -} - -export function hasAvailableClaudeToken(): boolean { - if (tokens.length === 0) { - return getConfiguredClaudeTokens().length > 0; - } - refreshRuntimeTokenSelection(); - const now = Date.now(); - return tokens.some( - (token) => !token.rateLimitedUntil || token.rateLimitedUntil <= now, - ); -} diff --git a/src/unified-dashboard.test.ts b/src/unified-dashboard.test.ts index 894cd31..73e1feb 100644 --- a/src/unified-dashboard.test.ts +++ b/src/unified-dashboard.test.ts @@ -172,40 +172,18 @@ describe('buildWebUsageRowsForSnapshot', () => { it('keeps real Claude rows ahead of Codex rows for snapshots', () => { const rows = buildWebUsageRowsForSnapshot({ serviceAgentType: 'claude-code', - claudeAccounts: [ - { - index: 0, - masked: 'claude-1', - isActive: true, - isRateLimited: false, - usage: { - five_hour: { - utilization: 0.2, - resets_at: '2026-04-26T12:00:00.000Z', - }, - seven_day: { - utilization: 0.4, - resets_at: '2026-04-27T12:00:00.000Z', - }, + claudeUsage: { + usage: { + five_hour: { + utilization: 0.2, + resets_at: '2026-04-26T12:00:00.000Z', + }, + seven_day: { + utilization: 0.4, + resets_at: '2026-04-27T12:00:00.000Z', }, }, - { - index: 1, - masked: 'claude-2', - isActive: false, - isRateLimited: false, - usage: { - five_hour: { - utilization: 0.3, - resets_at: '2026-04-26T12:00:00.000Z', - }, - seven_day: { - utilization: 0.5, - resets_at: '2026-04-27T12:00:00.000Z', - }, - }, - }, - ], + }, codexRows: [ { name: 'Codex1', @@ -218,23 +196,14 @@ describe('buildWebUsageRowsForSnapshot', () => { }); const names = rows.map((row) => row.name); - expect(names[0]).toMatch(/^Claude1/); - expect(names[1]).toMatch(/^Claude2/); - expect(names[2]).toBe('Codex1'); + expect(names[0]).toMatch(/^Claude/); + expect(names[1]).toBe('Codex1'); }); it('does not invent Claude rows for codex-only services', () => { const rows = buildWebUsageRowsForSnapshot({ serviceAgentType: 'codex', - claudeAccounts: [ - { - index: 0, - masked: 'claude-1', - isActive: true, - isRateLimited: false, - usage: null, - }, - ], + claudeUsage: { usage: null }, codexRows: [ { name: 'Codex1', diff --git a/src/unified-dashboard.ts b/src/unified-dashboard.ts index 54cc6c6..61ceb41 100644 --- a/src/unified-dashboard.ts +++ b/src/unified-dashboard.ts @@ -17,15 +17,11 @@ import { } from './config.js'; import { getGlobalFailoverInfo } from './service-routing.js'; import { - fetchAllClaudeUsage, - fetchAllClaudeProfiles, - type ClaudeAccountUsage, + fetchClaudeProfile, + fetchClaudeUsage, + type ClaudeUsageSnapshot, } from './claude-usage.js'; -import { - CODEX_FULL_SCAN_INTERVAL, - refreshActiveCodexUsage, - refreshAllCodexAccountUsage, -} from './codex-usage-collector.js'; +import { refreshCodexUsage } from './codex-usage-collector.js'; import { composeDashboardContent, formatElapsed, @@ -40,7 +36,7 @@ import { import { buildClaudeUsageRows, extractCodexUsageRows, - mergeClaudeDashboardAccounts, + mergeClaudeDashboardUsage, type UsageRow, } from './dashboard-usage-rows.js'; import { getAllChats, getAllTasks } from './db.js'; @@ -100,7 +96,7 @@ const DASHBOARD_DUPLICATE_CLEANUP_POLL_MS = 300_000; let statusMessageId: string | null = null; let cachedUsageContent = ''; -let cachedClaudeAccounts: ClaudeAccountUsage[] = []; +let cachedClaudeUsage: ClaudeUsageSnapshot | null = null; let usageUpdateInProgress = false; let channelMetaCache = new Map(); let channelMetaLastRefresh = 0; @@ -269,13 +265,13 @@ export function formatRoomName( export function buildWebUsageRowsForSnapshot(args: { serviceAgentType: AgentType; - claudeAccounts: ClaudeAccountUsage[]; + claudeUsage: ClaudeUsageSnapshot | null; codexRows: UsageRow[]; }): UsageRow[] { const rows: UsageRow[] = []; if (args.serviceAgentType === 'claude-code') { - rows.push(...buildClaudeUsageRows(args.claudeAccounts)); + rows.push(...buildClaudeUsageRows(args.claudeUsage)); } rows.push(...args.codexRows); @@ -288,7 +284,7 @@ function buildUsageSnapshotRows(opts: UnifiedDashboardOptions): { } { const rows = buildWebUsageRowsForSnapshot({ serviceAgentType: opts.serviceAgentType, - claudeAccounts: cachedClaudeAccounts, + claudeUsage: cachedClaudeUsage, codexRows: cachedCodexUsageRows, }); @@ -603,11 +599,11 @@ export function renderUsageTable( async function buildUsageContent(): Promise { const shouldFetchClaudeUsage = USAGE_DASHBOARD_ENABLED; - let liveClaudeAccounts: ClaudeAccountUsage[] | null = null; + let liveClaudeUsage: ClaudeUsageSnapshot | null = null; if (shouldFetchClaudeUsage) { try { - liveClaudeAccounts = await fetchAllClaudeUsage(); + liveClaudeUsage = await fetchClaudeUsage(); } catch (err) { logger.warn({ err }, 'Failed to fetch Claude usage for dashboard'); } @@ -623,11 +619,11 @@ async function buildUsageContent(): Promise { const claudeBotRows: UsageRow[] = []; if (shouldFetchClaudeUsage) { - cachedClaudeAccounts = mergeClaudeDashboardAccounts( - liveClaudeAccounts, - cachedClaudeAccounts, + cachedClaudeUsage = mergeClaudeDashboardUsage( + liveClaudeUsage, + cachedClaudeUsage, ); - claudeBotRows.push(...buildClaudeUsageRows(cachedClaudeAccounts)); + claudeBotRows.push(...buildClaudeUsageRows(cachedClaudeUsage)); } // Group 2: Codex bot — use in-process cache (unified service) @@ -903,7 +899,7 @@ export async function startUnifiedDashboard( } if (isRenderer) { - await fetchAllClaudeProfiles(); + await fetchClaudeProfile(); await refreshUsageCache(); } @@ -1058,20 +1054,13 @@ export async function startUnifiedDashboard( cachedCodexUsageRows = result.rows; if (result.fetchedAt) codexUsageFetchedAt = result.fetchedAt; }; - void refreshAllCodexAccountUsage().then((r) => { - applyCodexRefresh(r); - return refreshActiveCodexUsage().then(applyCodexRefresh); - }); + void refreshCodexUsage().then(applyCodexRefresh); // Each poll spawns a Codex app-server; every 5 minutes is plenty for the // dashboard (it used to run every minute, ~1,440 spawns a day). setInterval( - () => void refreshActiveCodexUsage().then(applyCodexRefresh), + () => void refreshCodexUsage().then(applyCodexRefresh), Math.max(opts.usageUpdateInterval, CODEX_ACTIVE_USAGE_POLL_MS), ); - setInterval( - () => void refreshAllCodexAccountUsage().then(applyCodexRefresh), - CODEX_FULL_SCAN_INTERVAL, - ); logger.info( { diff --git a/src/usage-primer.test.ts b/src/usage-primer.test.ts index 3d4b1a3..c750448 100644 --- a/src/usage-primer.test.ts +++ b/src/usage-primer.test.ts @@ -2,17 +2,13 @@ import { describe, expect, it, vi } from 'vitest'; const callOrder: string[] = []; -const refreshAllCodexAccountUsage = vi.fn(async () => { - callOrder.push('refreshAll'); - return { rows: [], fetchedAt: '2026-06-01T00:00:00.000Z' }; -}); -const refreshActiveCodexUsage = vi.fn(async () => { - callOrder.push('refreshActive'); +const refreshCodexUsage = vi.fn(async () => { + callOrder.push('refresh'); return { rows: [], fetchedAt: '2026-06-01T00:00:01.000Z' }; }); const runCodexWarmupCycle = vi.fn(async () => { callOrder.push('warmup'); - return { status: 'warmed', accountIndex: 0 }; + return { status: 'warmed' }; }); vi.mock('./config.js', () => ({ @@ -38,13 +34,12 @@ vi.mock('./logger.js', () => ({ }, })); -vi.mock('./token-rotation.js', () => ({ - getAllTokens: vi.fn(() => []), +vi.mock('./claude-oauth-token.js', () => ({ + getCurrentClaudeToken: vi.fn(() => undefined), })); vi.mock('./codex-usage-collector.js', () => ({ - refreshAllCodexAccountUsage, - refreshActiveCodexUsage, + refreshCodexUsage, })); vi.mock('./codex-warmup.js', () => ({ @@ -54,8 +49,7 @@ vi.mock('./codex-warmup.js', () => ({ describe('usage-primer', () => { it('fires the Codex primer first with forceAttempt and refreshes usage only afterwards', async () => { callOrder.length = 0; - refreshAllCodexAccountUsage.mockClear(); - refreshActiveCodexUsage.mockClear(); + refreshCodexUsage.mockClear(); runCodexWarmupCycle.mockClear(); const { runCodexPrimerCycle } = await import('./usage-primer.js'); @@ -63,8 +57,7 @@ describe('usage-primer', () => { // No pre-call usage refresh (that was the off-slot latency source); the // command fires immediately, then usage is refreshed for observability. - expect(callOrder).toEqual(['warmup', 'refreshActive']); - expect(refreshAllCodexAccountUsage).not.toHaveBeenCalled(); + expect(callOrder).toEqual(['warmup', 'refresh']); expect(runCodexWarmupCycle).toHaveBeenCalledWith( expect.objectContaining({ minIntervalMs: 18_000_000, diff --git a/src/usage-primer.ts b/src/usage-primer.ts index 156ab29..1d0f43b 100644 --- a/src/usage-primer.ts +++ b/src/usage-primer.ts @@ -3,16 +3,16 @@ import fs from 'fs'; import path from 'path'; import { CODEX_WARMUP_CONFIG } from './config.js'; -import { refreshActiveCodexUsage } from './codex-usage-collector.js'; +import { refreshCodexUsage } from './codex-usage-collector.js'; import { runCodexWarmupCycle } from './codex-warmup.js'; import { logger } from './logger.js'; -import { getAllTokens } from './token-rotation.js'; +import { getCurrentClaudeToken } from './claude-oauth-token.js'; /** * Usage-window warm-up primer. * - * Fires a tiny inference call at fixed KST slots (08, 13, 18, 23) so each - * provider account is kept warm and any usage-window issues surface in the + * Fires a tiny inference call at fixed KST slots (08, 13, 18, 23) so the + * Claude and Codex accounts are kept warm and any usage-window issues surface in the * logs at predictable times. * * IMPORTANT — what this does NOT do: it does not pin the reset to a fixed @@ -29,11 +29,9 @@ const KST_OFFSET_MS = 9 * 60 * 60 * 1000; const CLAUDE_PRIMER_TIMEOUT_MS = 60_000; const CODEX_PRIMER_MIN_INTERVAL_MS = 5 * 60 * 60 * 1000; // Fire the Codex primer unconditionally at every slot, mirroring the Claude -// primer (which always fires unless the account is rate-limited). The 5h usage -// level no longer gates the call (maxUsagePct=100), so a slot is never skipped -// just because Codex happens to be partway through its window. The d7 gate -// stays at 100 so we still skip an account whose weekly quota is exhausted, -// which is the Codex analogue of Claude's rate-limit skip. +// primer. The 5h usage level no longer gates the call (maxUsagePct=100), so a +// slot is never skipped just because Codex happens to be partway through its +// window. const CODEX_PRIMER_MAX_USAGE_PCT = 100; const CODEX_PRIMER_MAX_D7_USAGE_PCT = 100; @@ -126,25 +124,17 @@ function runClaudePrimerOnce( } async function runClaudePrimerCycle(): Promise { - const tokens = getAllTokens(); - const candidates = tokens.filter((t) => !t.isRateLimited); - if (candidates.length === 0) { - logger.info('Claude primer skipped: no eligible tokens'); + const token = getCurrentClaudeToken(); + if (!token) { + logger.info('Claude primer skipped: no Claude OAuth token configured'); return; } - const target = candidates[0]; - logger.info( - { tokenIndex: target.index }, - 'Starting Claude primer (haiku, prompt=ok)', - ); - const result = await runClaudePrimerOnce(target.token); + logger.info('Starting Claude primer (haiku, prompt=ok)'); + const result = await runClaudePrimerOnce(token); if (result.ok) { - logger.info({ tokenIndex: target.index }, 'Claude primer completed'); + logger.info('Claude primer completed'); } else { - logger.warn( - { tokenIndex: target.index, reason: result.reason }, - 'Claude primer failed', - ); + logger.warn({ reason: result.reason }, 'Claude primer failed'); } } @@ -170,7 +160,7 @@ export async function runCodexPrimerCycle(): Promise { logger.info({ result }, 'Codex primer cycle finished'); // Observability only — runs AFTER the call so it never delays it: refresh // so the new reset window shows up in usage data/logs. - await refreshActiveCodexUsage(); + await refreshCodexUsage(); } catch (err) { logger.warn({ err }, 'Codex primer cycle threw'); }