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:
@@ -29,7 +29,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') ||
|
||||
@@ -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<typeof import('./agent-runner.js')>(
|
||||
@@ -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<string, unknown>) => Promise<void>,
|
||||
) => {
|
||||
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<string, unknown>) => Promise<void>,
|
||||
) => {
|
||||
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<string, unknown>) => Promise<void>,
|
||||
) => {
|
||||
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<void>) => {
|
||||
@@ -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<string, unknown>) => Promise<void>,
|
||||
) => {
|
||||
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<string, unknown>) => Promise<void>,
|
||||
) => {
|
||||
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<string, unknown>) => Promise<void>,
|
||||
) => {
|
||||
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<void>) => {
|
||||
@@ -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<string, unknown>) => Promise<void>,
|
||||
) => {
|
||||
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<string, unknown>) => Promise<void>,
|
||||
) => {
|
||||
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>) => {
|
||||
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'),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user