Skip to content

Commit 02b67b0

Browse files
authored
Merge pull request #317 from lidge-jun/agent/fix-codex-monthly-window-315
fix(codex): classify monthly WHAM windows
2 parents af973e5 + 4e0d673 commit 02b67b0

4 files changed

Lines changed: 87 additions & 13 deletions

File tree

‎docs-site/src/content/docs/guides/web-dashboard.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,9 @@ The **Codex Auth** page manages the native ChatGPT/Codex route:
7272
and a strictly lower-usage eligible account exists.
7373
- New sessions can choose the lowest-usage eligible account. Paid plans score the hottest known 5h,
7474
weekly, or 30d window; Go/Free plans use the 30d window only.
75+
- When WHAM supplies `limit_window_seconds`, Codex Auth classifies a primary window of at least 28
76+
days as 30d instead of assuming every primary window is weekly. Responses without a duration keep
77+
the legacy weekly interpretation.
7578
- **Refresh quotas** re-reads account usage immediately so routing and the account cards use the same
7679
values.
7780
- Pool request logs use opaque labels such as `p3fa91c`, never account emails.

‎docs-site/src/content/docs/ko/guides/web-dashboard.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ Dashboard의 **Sub-agent delegation** 선택기는 `injectionModel`과 선택적
7171
정상 계정이 있으면 그 계정으로 다시 묶일 수 있습니다.
7272
- 새 세션은 사용량이 가장 낮은 정상 계정을 고를 수 있습니다. 유료 플랜은 알려진 5시간, 주간, 30일
7373
창 중 가장 높은 사용률로 점수를 매기고, Go/Free 플랜은 30일 창만 사용합니다.
74+
- WHAM이 `limit_window_seconds`를 제공하면 Codex Auth는 28일 이상인 primary window를 주간이 아닌
75+
30일 창으로 분류합니다. 기간이 없는 기존 응답은 이전과 동일하게 주간 창으로 해석합니다.
7476
- **Refresh quotas**는 계정 사용량을 즉시 다시 읽어 라우팅과 화면의 계정 카드가 같은 값을 보게 합니다.
7577
- 풀 요청 로그에는 이메일 대신 `p3fa91c` 같은 불투명한 라벨을 사용합니다.
7678

‎src/codex/quota.ts‎

Lines changed: 42 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,23 @@ export type WhamUsageResponse = {
1111
email?: string | null;
1212
plan_type?: string | null;
1313
rate_limit?: {
14-
primary_window?: { used_percent?: number; reset_at?: number };
15-
secondary_window?: { used_percent?: number; reset_at?: number };
16-
tertiary_window?: { used_percent?: number; reset_at?: number };
14+
primary_window?: WhamUsageWindow;
15+
secondary_window?: WhamUsageWindow;
16+
tertiary_window?: WhamUsageWindow;
1717
};
1818
rate_limit_reset_credits?: {
1919
available_count: number;
2020
} | null;
2121
};
2222

23+
type WhamUsageWindow = {
24+
used_percent?: number;
25+
reset_at?: number;
26+
limit_window_seconds?: number;
27+
};
28+
29+
const MONTHLY_WINDOW_MIN_SECONDS = 28 * 24 * 60 * 60;
30+
2331
const accountQuota = new Map<string, StoredAccountQuota>();
2432

2533
export const CODEX_UNKNOWN_USAGE_SCORE = 100;
@@ -49,6 +57,13 @@ function hasKnownQuotaValue(quota: Omit<StoredAccountQuota, "updatedAt">): boole
4957
.some(value => typeof value === "number" && Number.isFinite(value));
5058
}
5159

60+
function isExplicitMonthlyWindow(window: WhamUsageWindow | undefined): boolean {
61+
const seconds = window?.limit_window_seconds;
62+
return typeof seconds === "number"
63+
&& Number.isFinite(seconds)
64+
&& seconds >= MONTHLY_WINDOW_MIN_SECONDS;
65+
}
66+
5267
export function updateAccountQuota(
5368
accountId: string,
5469
weekly: unknown,
@@ -110,16 +125,30 @@ export function parseUsageQuota(data: WhamUsageResponse): Omit<StoredAccountQuot
110125

111126
const quota: Omit<StoredAccountQuota, "updatedAt"> = {};
112127
const thirtyDayOnly = data.plan_type?.trim().toLowerCase() === "go" || data.plan_type?.trim().toLowerCase() === "free";
113-
// primary_window was the 5h window; it now carries weekly data for GPT plans.
114-
// secondary_window is the legacy weekly source; prefer primary when present.
115-
const primaryPercent = normalizeUsagePercent(data.rate_limit.primary_window?.used_percent);
116-
const secondaryPercent = normalizeUsagePercent(data.rate_limit.secondary_window?.used_percent);
117-
const weeklyPercent = primaryPercent ?? secondaryPercent;
118-
const monthlyPercent = normalizeUsagePercent(data.rate_limit.tertiary_window?.used_percent);
119-
const primaryResetAt = normalizeResetAt(data.rate_limit.primary_window?.reset_at);
120-
const secondaryResetAt = normalizeResetAt(data.rate_limit.secondary_window?.reset_at);
121-
const weeklyResetAt = primaryPercent !== undefined ? primaryResetAt : secondaryResetAt;
122-
const monthlyResetAt = normalizeResetAt(data.rate_limit.tertiary_window?.reset_at);
128+
const primaryWindow = data.rate_limit.primary_window;
129+
const secondaryWindow = data.rate_limit.secondary_window;
130+
const tertiaryWindow = data.rate_limit.tertiary_window;
131+
const primaryPercent = normalizeUsagePercent(primaryWindow?.used_percent);
132+
const secondaryPercent = normalizeUsagePercent(secondaryWindow?.used_percent);
133+
const tertiaryPercent = normalizeUsagePercent(tertiaryWindow?.used_percent);
134+
const primaryResetAt = normalizeResetAt(primaryWindow?.reset_at);
135+
const secondaryResetAt = normalizeResetAt(secondaryWindow?.reset_at);
136+
const tertiaryResetAt = normalizeResetAt(tertiaryWindow?.reset_at);
137+
const primaryIsMonthly = isExplicitMonthlyWindow(primaryWindow);
138+
139+
// [Decision Log]
140+
// - 목적과 의도: distinguish weekly and roughly monthly WHAM primary windows without plan-name guesses.
141+
// - 기존 구현 및 제약 조건: primary meant weekly, and older responses omit limit_window_seconds.
142+
// - 검토한 주요 대안: exact-duration matching, plan-specific mapping, and a duration lower bound.
143+
// - 선택한 방식: only an explicit primary duration of at least 28 days changes it to monthly.
144+
// - 다른 대안 대신 이 방식을 선택한 이유: it accepts calendar-month variance and preserves legacy payloads.
145+
// - 장점, 단점 및 영향: Team monthly quotas classify correctly; unknown durations remain weekly by design.
146+
const weeklyPercent = primaryIsMonthly ? secondaryPercent : primaryPercent ?? secondaryPercent;
147+
const weeklyResetAt = primaryIsMonthly
148+
? secondaryResetAt
149+
: primaryPercent !== undefined ? primaryResetAt : secondaryResetAt;
150+
const monthlyPercent = primaryIsMonthly ? primaryPercent ?? tertiaryPercent : tertiaryPercent;
151+
const monthlyResetAt = primaryIsMonthly && primaryPercent !== undefined ? primaryResetAt : tertiaryResetAt;
123152
if (thirtyDayOnly) {
124153
if (monthlyPercent !== undefined) {
125154
quota.monthlyPercent = monthlyPercent;

‎tests/codex-routing.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -571,6 +571,46 @@ describe("codex routing", () => {
571571
});
572572
});
573573

574+
test("WHAM primary window uses its explicit duration to distinguish weekly and monthly quotas", () => {
575+
expect(parseUsageQuota({
576+
plan_type: "team",
577+
rate_limit: {
578+
primary_window: { used_percent: 20, reset_at: 2, limit_window_seconds: 604_800 },
579+
},
580+
})).toEqual({ weeklyPercent: 20, weeklyResetAt: 2 });
581+
582+
expect(parseUsageQuota({
583+
plan_type: "team",
584+
rate_limit: {
585+
primary_window: { used_percent: 39, reset_at: 3, limit_window_seconds: 2_628_000 },
586+
},
587+
})).toEqual({ monthlyPercent: 39, monthlyResetAt: 3 });
588+
});
589+
590+
test("WHAM monthly primary preserves a legacy secondary weekly window", () => {
591+
expect(parseUsageQuota({
592+
plan_type: "team",
593+
rate_limit: {
594+
primary_window: { used_percent: 39, reset_at: 30, limit_window_seconds: 2_628_000 },
595+
secondary_window: { used_percent: 12, reset_at: 7, limit_window_seconds: 604_800 },
596+
},
597+
})).toEqual({
598+
weeklyPercent: 12,
599+
weeklyResetAt: 7,
600+
monthlyPercent: 39,
601+
monthlyResetAt: 30,
602+
});
603+
});
604+
605+
test("WHAM primary window without duration keeps the legacy weekly fallback", () => {
606+
expect(parseUsageQuota({
607+
plan_type: "team",
608+
rate_limit: {
609+
primary_window: { used_percent: 6, reset_at: 7 },
610+
},
611+
})).toEqual({ weeklyPercent: 6, weeklyResetAt: 7 });
612+
});
613+
574614
test("WHAM parser returns null when no valid quota window is present", () => {
575615
expect(parseUsageQuota({ rate_limit: {} })).toBeNull();
576616
expect(parseUsageQuota({

0 commit comments

Comments
 (0)