Skip to content

Commit c0aa964

Browse files
committed
feat(anthropic): opt-in Claude OAuth account pool (#294)
Add experimental, default-off routing across stored Anthropic OAuth accounts: sticky session affinity, 429 cooldown failover, and new-session lowest 5h-usage pick. Includes GUI toggle with an explicit not-battle-tested warning, management API, docs, and focused regressions.
1 parent de35caa commit c0aa964

18 files changed

Lines changed: 876 additions & 13 deletions

File tree

‎docs-site/src/content/docs/guides/claude-code.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,17 @@ opencodex serves `POST /v1/messages` (plus `count_tokens`) alongside `/v1/respon
77
Code can use every routed provider — OAuth logins, account pools, key failover and sidecars
88
included — with zero extra auth work.
99

10+
## Claude OAuth account pool (experimental)
11+
12+
You can log in multiple Claude accounts via the Providers dashboard (`ocx login anthropic` /
13+
add-account). By default every request uses the **active** account only.
14+
15+
An **experimental, opt-in** Claude account pool (`anthropicAccountPool.enabled`) adds sticky
16+
session affinity and 429 cooldown failover across those OAuth accounts, with optional
17+
new-session lowest-usage pick from the 5-hour quota bars. It is **off by default**, shows a
18+
GUI warning, and is not battle-tested — Anthropic may restrict accounts that look like
19+
automated rotation. See [Configuration](/reference/configuration/#anthropicaccountpool-experimental).
20+
1021
## Quickstart
1122

1223
```bash

‎docs-site/src/content/docs/reference/configuration.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,25 @@ credential store. Existing thread ids keep account affinity, while new sessions
103103
on quota, cooldown, and health.
104104
:::
105105

106+
### anthropicAccountPool (experimental)
107+
108+
Opt-in routing across **multiple Anthropic OAuth accounts** already stored in `auth.json`
109+
(issue [#294](https://github.com/lidge-jun/opencodex/issues/294)). **Default off.** This is
110+
experimental and not battle-tested — enable only if you accept the risk that Anthropic may
111+
restrict accounts that look like automated multi-account rotation. Accounts under the same
112+
organization can share quota; pooling those will not help.
113+
114+
| Key | Type | Default | Description |
115+
| --- | --- | --- | --- |
116+
| `anthropicAccountPool.enabled?` | `boolean` | `false` | When true, sticky session affinity + 429 cooldown failover across eligible Anthropic OAuth accounts. |
117+
| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | For **new** sessions only: if the active account's cached 5-hour usage is at/above this percent, pick the lowest-usage eligible account. `0` disables quota-based picking (affinity + active only). |
118+
119+
Toggle and warning also appear on **Providers → anthropic → Accounts** in the GUI.
120+
:::caution[Experimental]
121+
Leave this disabled unless you understand Anthropic account policy risk. Prefer manual
122+
`ocx account use anthropic <id>` switching when unsure.
123+
:::
124+
106125
### claudeCode (OcxClaudeCodeConfig)
107126

108127
Claude Code inbound settings consumed by the `/v1/messages` surface, the `ocx claude`
Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
/**
2+
* Opt-in Anthropic OAuth account pool controls (#294).
3+
* Experimental — shows a strong warning because the feature is not battle-tested.
4+
*/
5+
import { useCallback, useEffect, useState } from "react";
6+
import { useT } from "../../i18n/shared";
7+
8+
type PoolState = {
9+
enabled: boolean;
10+
threshold: number;
11+
};
12+
13+
export default function AnthropicAccountPoolSettings({
14+
apiBase,
15+
accountCount,
16+
}: {
17+
apiBase: string;
18+
accountCount: number;
19+
}) {
20+
const t = useT();
21+
const [state, setState] = useState<PoolState | null>(null);
22+
const [draft, setDraft] = useState("80");
23+
const [saving, setSaving] = useState(false);
24+
const [error, setError] = useState<string | null>(null);
25+
const [loadError, setLoadError] = useState(false);
26+
27+
useEffect(() => {
28+
let cancelled = false;
29+
const ac = new AbortController();
30+
void (async () => {
31+
try {
32+
const res = await fetch(`${apiBase}/api/oauth/accounts/pool?provider=anthropic`, {
33+
signal: ac.signal,
34+
});
35+
if (!res.ok) throw new Error("load");
36+
const json = await res.json() as { enabled?: boolean; autoSwitchThreshold?: number };
37+
if (cancelled) return;
38+
const nextEnabled = json.enabled === true;
39+
const nextThreshold = typeof json.autoSwitchThreshold === "number" ? json.autoSwitchThreshold : 80;
40+
setState({ enabled: nextEnabled, threshold: nextThreshold });
41+
setDraft(String(nextThreshold > 0 ? nextThreshold : 80));
42+
setLoadError(false);
43+
} catch {
44+
if (cancelled || ac.signal.aborted) return;
45+
setLoadError(true);
46+
}
47+
})();
48+
return () => {
49+
cancelled = true;
50+
ac.abort();
51+
};
52+
}, [apiBase]);
53+
54+
const save = useCallback(async (nextEnabled: boolean, nextThreshold: number) => {
55+
setSaving(true);
56+
setError(null);
57+
try {
58+
const res = await fetch(`${apiBase}/api/oauth/accounts/pool`, {
59+
method: "PUT",
60+
headers: { "content-type": "application/json" },
61+
body: JSON.stringify({
62+
provider: "anthropic",
63+
enabled: nextEnabled,
64+
autoSwitchThreshold: nextThreshold,
65+
}),
66+
});
67+
if (!res.ok) throw new Error("save");
68+
setState({ enabled: nextEnabled, threshold: nextThreshold });
69+
setDraft(String(nextThreshold > 0 ? nextThreshold : 80));
70+
} catch {
71+
setError(t("anthropicPool.saveFailed"));
72+
} finally {
73+
setSaving(false);
74+
}
75+
}, [apiBase, t]);
76+
77+
const enabled = state?.enabled === true;
78+
const threshold = state?.threshold ?? 80;
79+
const loading = state === null && !loadError;
80+
81+
return (
82+
<div className="card" style={{ marginTop: 12 }} aria-busy={loading || saving}>
83+
<div className="card-row" style={{ alignItems: "flex-start", gap: 12 }}>
84+
<div style={{ flex: 1 }}>
85+
<strong>{t("anthropicPool.title")}</strong>
86+
<div className="card-sub" style={{ marginTop: 4 }}>
87+
{loadError
88+
? t("anthropicPool.loadFailed")
89+
: loading
90+
? t("common.loading")
91+
: enabled
92+
? t("anthropicPool.enabledDesc", { threshold })
93+
: t("anthropicPool.disabledDesc")}
94+
</div>
95+
</div>
96+
<label className="toggle" style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
97+
<input
98+
type="checkbox"
99+
checked={enabled}
100+
disabled={loading || saving || loadError || accountCount < 2}
101+
onChange={(event) => {
102+
const next = event.target.checked;
103+
void save(next, threshold > 0 ? threshold : 80);
104+
}}
105+
/>
106+
<span>{enabled ? t("anthropicPool.on") : t("anthropicPool.off")}</span>
107+
</label>
108+
</div>
109+
110+
<div
111+
role="alert"
112+
className="card-sub"
113+
style={{
114+
marginTop: 10,
115+
padding: "8px 10px",
116+
border: "1px solid var(--border, #c9a227)",
117+
borderRadius: 6,
118+
background: "color-mix(in srgb, var(--warn, #c9a227) 12%, transparent)",
119+
}}
120+
>
121+
{t("anthropicPool.experimentalWarning")}
122+
</div>
123+
124+
{accountCount < 2 && (
125+
<div className="card-sub" style={{ marginTop: 8 }}>{t("anthropicPool.needTwoAccounts")}</div>
126+
)}
127+
128+
{enabled && (
129+
<label className="field" style={{ display: "block", marginTop: 12 }}>
130+
<span className="field-label">{t("anthropicPool.threshold")}</span>
131+
<input
132+
className="input mono"
133+
type="number"
134+
min={0}
135+
max={100}
136+
step={1}
137+
value={draft}
138+
disabled={saving}
139+
aria-label={t("anthropicPool.thresholdAria")}
140+
onChange={(event) => setDraft(event.target.value)}
141+
onBlur={() => {
142+
const parsed = Number.parseInt(draft, 10);
143+
if (!Number.isInteger(parsed) || parsed < 0 || parsed > 100) {
144+
setDraft(String(threshold));
145+
setError(t("anthropicPool.thresholdInvalid"));
146+
return;
147+
}
148+
if (parsed !== threshold) void save(true, parsed);
149+
}}
150+
/>
151+
<div className="card-sub" style={{ marginTop: 4 }}>{t("anthropicPool.thresholdHelp")}</div>
152+
</label>
153+
)}
154+
155+
{error && (
156+
<div role="alert" className="card-sub" style={{ marginTop: 8, color: "var(--danger, #c44)" }}>
157+
{error}
158+
</div>
159+
)}
160+
</div>
161+
);
162+
}

‎gui/src/components/provider-workspace/ProviderAuthPanel.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
oauthHealthShowsReauth,
2020
} from "../../oauth-health-display";
2121
import CodexAccountPool from "../CodexAccountPool";
22+
import AnthropicAccountPoolSettings from "./AnthropicAccountPoolSettings";
2223
import { LoginUrlBlock } from "../login-url-block";
2324
import QuotaBars from "../QuotaBars";
2425
import { useCopyFeedback } from "../use-copy-feedback";
@@ -105,6 +106,9 @@ export default function ProviderAuthPanel({
105106
<div className="pwi-auth-body">
106107
{isOauth && (
107108
<>
109+
{item.name === "anthropic" && (
110+
<AnthropicAccountPoolSettings apiBase={apiBase} accountCount={accounts.length} />
111+
)}
108112
<div className="pwi-auth-status-row">
109113
<span className={`pwi-auth-dot ${activeNeedsReauth ? "pwi-auth-dot--warn" : loggedIn ? "pwi-auth-dot--ok" : "pwi-auth-dot--off"}`} aria-hidden="true" />
110114
<span className="pwi-auth-status-text">

‎gui/src/i18n/de.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -668,6 +668,19 @@ export const de: Record<TKey, string> = {
668668
"codexAuth.autoSwitchThresholdInvalid": "Gib eine ganze Zahl von 1 bis 100 ein",
669669
"codexAuth.autoSwitchUpdated": "Der automatische Kontowechsel wurde aktualisiert",
670670
"codexAuth.autoSwitchUpdateFailed": "Die Aktualisierung konnte nicht bestätigt werden. Der zuletzt bestätigte Wert wird angezeigt.",
671+
"anthropicPool.title": "Claude account pool (experimental)",
672+
"anthropicPool.enabledDesc": "On 429, cools the account and fails over. New sessions prefer usage under {threshold}% (5-hour bar).",
673+
"anthropicPool.disabledDesc": "Uses only the active Claude account. Enable only if you accept experimental routing.",
674+
"anthropicPool.experimentalWarning": "Experimental and not battle-tested. Anthropic may restrict accounts that look like automated multi-account rotation. Same organization can share quota — pooling those accounts will not help. Keep this off unless you understand the risk.",
675+
"anthropicPool.needTwoAccounts": "Add at least two Claude OAuth accounts before enabling the pool.",
676+
"anthropicPool.threshold": "New-session usage threshold",
677+
"anthropicPool.thresholdAria": "New-session usage threshold, percent",
678+
"anthropicPool.thresholdHelp": "0 disables quota-based picking (affinity + active account only). Default 80.",
679+
"anthropicPool.thresholdInvalid": "Enter a whole number from 0 to 100",
680+
"anthropicPool.loadFailed": "Claude pool settings could not be loaded.",
681+
"anthropicPool.saveFailed": "Claude pool settings could not be saved.",
682+
"anthropicPool.on": "On",
683+
"anthropicPool.off": "Off",
671684
"codexAuth.switched": "{email} ist für die nächste Anfrage ausgewählt",
672685
"codexAuth.loadFailed": "Die Codex-Kontoeinstellungen konnten nicht geladen werden.",
673686
"codexAuth.switchFailed": "Das Konto konnte nicht gewechselt werden. Die vorherige Auswahl bleibt erhalten.",

‎gui/src/i18n/en.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1079,6 +1079,21 @@ export const en = {
10791079
"codexAuth.autoSwitchThresholdInvalid": "Enter a whole number from 1 to 100",
10801080
"codexAuth.autoSwitchUpdated": "Automatic account switching updated",
10811081
"codexAuth.autoSwitchUpdateFailed": "The update could not be confirmed. The last confirmed value is shown.",
1082+
1083+
"anthropicPool.title": "Claude account pool (experimental)",
1084+
"anthropicPool.enabledDesc": "On 429, cools the account and fails over. New sessions prefer usage under {threshold}% (5-hour bar).",
1085+
"anthropicPool.disabledDesc": "Uses only the active Claude account. Enable only if you accept experimental routing.",
1086+
"anthropicPool.experimentalWarning": "Experimental and not battle-tested. Anthropic may restrict accounts that look like automated multi-account rotation. Same organization can share quota — pooling those accounts will not help. Keep this off unless you understand the risk.",
1087+
"anthropicPool.needTwoAccounts": "Add at least two Claude OAuth accounts before enabling the pool.",
1088+
"anthropicPool.threshold": "New-session usage threshold",
1089+
"anthropicPool.thresholdAria": "New-session usage threshold, percent",
1090+
"anthropicPool.thresholdHelp": "0 disables quota-based picking (affinity + active account only). Default 80.",
1091+
"anthropicPool.thresholdInvalid": "Enter a whole number from 0 to 100",
1092+
"anthropicPool.loadFailed": "Claude pool settings could not be loaded.",
1093+
"anthropicPool.saveFailed": "Claude pool settings could not be saved.",
1094+
"anthropicPool.on": "On",
1095+
"anthropicPool.off": "Off",
1096+
10821097
"codexAuth.switched": "{email} is selected for the next request",
10831098
"codexAuth.loadFailed": "Codex account settings could not be loaded.",
10841099
"codexAuth.switchFailed": "The account could not be switched. Your previous selection is unchanged.",

‎gui/src/i18n/ja.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1036,6 +1036,19 @@ export const ja: Record<TKey, string> = {
10361036
"codexAuth.autoSwitchThresholdInvalid": "1 から 100 までの整数を入力してください",
10371037
"codexAuth.autoSwitchUpdated": "アカウントの自動切り替え設定を更新しました",
10381038
"codexAuth.autoSwitchUpdateFailed": "更新を確認できませんでした。最後に確認された値を表示しています。",
1039+
"anthropicPool.title": "Claude account pool (experimental)",
1040+
"anthropicPool.enabledDesc": "On 429, cools the account and fails over. New sessions prefer usage under {threshold}% (5-hour bar).",
1041+
"anthropicPool.disabledDesc": "Uses only the active Claude account. Enable only if you accept experimental routing.",
1042+
"anthropicPool.experimentalWarning": "Experimental and not battle-tested. Anthropic may restrict accounts that look like automated multi-account rotation. Same organization can share quota — pooling those accounts will not help. Keep this off unless you understand the risk.",
1043+
"anthropicPool.needTwoAccounts": "Add at least two Claude OAuth accounts before enabling the pool.",
1044+
"anthropicPool.threshold": "New-session usage threshold",
1045+
"anthropicPool.thresholdAria": "New-session usage threshold, percent",
1046+
"anthropicPool.thresholdHelp": "0 disables quota-based picking (affinity + active account only). Default 80.",
1047+
"anthropicPool.thresholdInvalid": "Enter a whole number from 0 to 100",
1048+
"anthropicPool.loadFailed": "Claude pool settings could not be loaded.",
1049+
"anthropicPool.saveFailed": "Claude pool settings could not be saved.",
1050+
"anthropicPool.on": "On",
1051+
"anthropicPool.off": "Off",
10391052
"codexAuth.switched": "次のリクエストでは {email} を使用します",
10401053
"codexAuth.loadFailed": "Codex アカウント設定を読み込めませんでした。",
10411054
"codexAuth.switchFailed": "アカウントを切り替えられませんでした。以前の選択はそのままです。",

‎gui/src/i18n/ko.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -685,6 +685,19 @@ export const ko: Record<TKey, string> = {
685685
"codexAuth.autoSwitchThresholdInvalid": "1~100 사이의 정수를 입력하세요",
686686
"codexAuth.autoSwitchUpdated": "자동 계정 전환 설정을 저장했습니다",
687687
"codexAuth.autoSwitchUpdateFailed": "자동 계정 전환 설정 변경을 확인하지 못했습니다. 마지막으로 확인된 값을 표시합니다.",
688+
"anthropicPool.title": "Claude account pool (experimental)",
689+
"anthropicPool.enabledDesc": "On 429, cools the account and fails over. New sessions prefer usage under {threshold}% (5-hour bar).",
690+
"anthropicPool.disabledDesc": "Uses only the active Claude account. Enable only if you accept experimental routing.",
691+
"anthropicPool.experimentalWarning": "Experimental and not battle-tested. Anthropic may restrict accounts that look like automated multi-account rotation. Same organization can share quota — pooling those accounts will not help. Keep this off unless you understand the risk.",
692+
"anthropicPool.needTwoAccounts": "Add at least two Claude OAuth accounts before enabling the pool.",
693+
"anthropicPool.threshold": "New-session usage threshold",
694+
"anthropicPool.thresholdAria": "New-session usage threshold, percent",
695+
"anthropicPool.thresholdHelp": "0 disables quota-based picking (affinity + active account only). Default 80.",
696+
"anthropicPool.thresholdInvalid": "Enter a whole number from 0 to 100",
697+
"anthropicPool.loadFailed": "Claude pool settings could not be loaded.",
698+
"anthropicPool.saveFailed": "Claude pool settings could not be saved.",
699+
"anthropicPool.on": "On",
700+
"anthropicPool.off": "Off",
688701
"codexAuth.switched": "다음 요청에 {email}을(를) 사용합니다",
689702
"codexAuth.loadFailed": "Codex 계정 설정을 불러오지 못했습니다.",
690703
"codexAuth.switchFailed": "계정을 전환하지 못했습니다. 이전 선택은 그대로 유지됩니다.",

‎gui/src/i18n/ru.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1078,6 +1078,19 @@ export const ru: Record<TKey, string> = {
10781078
"codexAuth.autoSwitchThresholdInvalid": "Введите целое число от 1 до 100",
10791079
"codexAuth.autoSwitchUpdated": "Настройки автоматического переключения обновлены",
10801080
"codexAuth.autoSwitchUpdateFailed": "Не удалось подтвердить обновление. Показано последнее подтверждённое значение.",
1081+
"anthropicPool.title": "Claude account pool (experimental)",
1082+
"anthropicPool.enabledDesc": "On 429, cools the account and fails over. New sessions prefer usage under {threshold}% (5-hour bar).",
1083+
"anthropicPool.disabledDesc": "Uses only the active Claude account. Enable only if you accept experimental routing.",
1084+
"anthropicPool.experimentalWarning": "Experimental and not battle-tested. Anthropic may restrict accounts that look like automated multi-account rotation. Same organization can share quota — pooling those accounts will not help. Keep this off unless you understand the risk.",
1085+
"anthropicPool.needTwoAccounts": "Add at least two Claude OAuth accounts before enabling the pool.",
1086+
"anthropicPool.threshold": "New-session usage threshold",
1087+
"anthropicPool.thresholdAria": "New-session usage threshold, percent",
1088+
"anthropicPool.thresholdHelp": "0 disables quota-based picking (affinity + active account only). Default 80.",
1089+
"anthropicPool.thresholdInvalid": "Enter a whole number from 0 to 100",
1090+
"anthropicPool.loadFailed": "Claude pool settings could not be loaded.",
1091+
"anthropicPool.saveFailed": "Claude pool settings could not be saved.",
1092+
"anthropicPool.on": "On",
1093+
"anthropicPool.off": "Off",
10811094
"codexAuth.switched": "{email} выбран для следующего запроса",
10821095
"codexAuth.loadFailed": "Не удалось загрузить настройки аккаунтов Codex.",
10831096
"codexAuth.switchFailed": "Не удалось переключить аккаунт. Ваш предыдущий выбор не изменён.",

‎gui/src/i18n/zh.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -685,6 +685,19 @@ export const zh: Record<TKey, string> = {
685685
"codexAuth.autoSwitchThresholdInvalid": "请输入 1 到 100 之间的整数",
686686
"codexAuth.autoSwitchUpdated": "自动切换账号设置已更新",
687687
"codexAuth.autoSwitchUpdateFailed": "无法确认更新。当前显示最后一次确认的值。",
688+
"anthropicPool.title": "Claude account pool (experimental)",
689+
"anthropicPool.enabledDesc": "On 429, cools the account and fails over. New sessions prefer usage under {threshold}% (5-hour bar).",
690+
"anthropicPool.disabledDesc": "Uses only the active Claude account. Enable only if you accept experimental routing.",
691+
"anthropicPool.experimentalWarning": "Experimental and not battle-tested. Anthropic may restrict accounts that look like automated multi-account rotation. Same organization can share quota — pooling those accounts will not help. Keep this off unless you understand the risk.",
692+
"anthropicPool.needTwoAccounts": "Add at least two Claude OAuth accounts before enabling the pool.",
693+
"anthropicPool.threshold": "New-session usage threshold",
694+
"anthropicPool.thresholdAria": "New-session usage threshold, percent",
695+
"anthropicPool.thresholdHelp": "0 disables quota-based picking (affinity + active account only). Default 80.",
696+
"anthropicPool.thresholdInvalid": "Enter a whole number from 0 to 100",
697+
"anthropicPool.loadFailed": "Claude pool settings could not be loaded.",
698+
"anthropicPool.saveFailed": "Claude pool settings could not be saved.",
699+
"anthropicPool.on": "On",
700+
"anthropicPool.off": "Off",
688701
"codexAuth.switched": "下一次请求将使用 {email}",
689702
"codexAuth.loadFailed": "无法加载 Codex 账号设置。",
690703
"codexAuth.switchFailed": "无法切换账户。之前的选择保持不变。",

0 commit comments

Comments
 (0)