refactor: run Claude and Codex on one fixed account each

The deployment has a single Claude OAuth credential and a single Codex
ChatGPT account, so the N-account rotation machinery only added state
files, cooldown bookkeeping and code paths that never ran.

Removed:
- Claude token rotation (token-rotation.ts, token-rotation-base.ts):
  rotate-on-limit, per-token cooldowns, token-rotation-state.json.
  CLAUDE_CODE_OAUTH_TOKENS is still read, but only its first entry.
- Codex account rotation (codex-token-rotation.ts): account pool,
  rotate-on-429/auth, dead-auth/cooldown tracking, round-robin advance,
  d7 auto-rotate, codex-rotation-state.json, manual account switch.
- Account index plumbing in token-refresh, claude-credentials-path
  (CLAUDE_ACCOUNTS_DIR / ~/.claude-accounts/<n>), Claude/Codex usage
  collectors, the dashboard rows and the Codex warm-up.
- provider-retry.ts rotation loops and the Codex retry path.

Kept:
- Codex exclusive auth lease (one Codex run at a time), the 15-minute
  waitForCodexAuthLease, and a usage-poll lease that skips while a run
  holds the account (codex-auth.ts).
- Session auth copy and write-back of refreshed tokens
  (syncCodexSessionAuthBack, syncClaudeSessionAuthBack).
- Codex auth path: ~/.codex-accounts/0/auth.json, else ~/.codex/auth.json
  (now resolved per run, so a re-login needs no restart).
- Claude token refresh loop, CLAUDE_CREDENTIALS_PATH and the
  CLAUDE_TOKEN_REFRESH_* / CLAUDE_USAGE_USE_HOME_CREDENTIALS flags; an
  auth-expired run still force-refreshes the token and retries once.
- Error classification (classifyClaudeTrigger, classifyCodexTrigger).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Codex
2026-10-01 20:00:46 +09:00
parent f127ac7a2b
commit a9eab5cb94
58 changed files with 1691 additions and 5547 deletions

View File

@@ -163,7 +163,7 @@ vi.mock('./agent-error-detection.js', async (importOriginal) => {
await importOriginal<typeof import('./agent-error-detection.js')>();
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(['새 계정으로 재시도 성공']);
});
});