-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpool.go
More file actions
1825 lines (1658 loc) · 54.7 KB
/
pool.go
File metadata and controls
1825 lines (1658 loc) · 54.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
)
// AccountType distinguishes between different API backends.
type AccountType string
const (
AccountTypeCodex AccountType = "codex"
AccountTypeGemini AccountType = "gemini"
AccountTypeClaude AccountType = "claude"
AccountTypeKimi AccountType = "kimi"
AccountTypeMinimax AccountType = "minimax"
AccountTypeZAI AccountType = "zai"
)
type Account struct {
mu sync.Mutex
Type AccountType // codex, gemini, or claude
ID string
File string
Label string
AccessToken string
RefreshToken string
IDToken string
// AccountID corresponds to Codex `auth.json` field `tokens.account_id`.
// Codex uses this value as the `ChatGPT-Account-ID` header.
AccountID string
// IDTokenChatGPTAccountID is the `chatgpt_account_id` claim extracted from the ID token.
// We keep it for debugging/fallback but prefer AccountID when present.
IDTokenChatGPTAccountID string
PlanType string
RateLimitTier string
Disabled bool
Inflight int64
ExpiresAt time.Time
LastRefresh time.Time
Usage UsageSnapshot
Penalty float64
LastPenalty time.Time
Dead bool
LastUsed time.Time
RateLimitUntil time.Time
BackoffLevel int // exponent: cooldown = min(1s * 2^level, 30m)
AllowedSourceIPs []string
// Aggregated token counters (in-memory for now; persist later)
Totals AccountUsage
}
func (a *Account) applyRateLimitObject(rl map[string]any) {
primaryUsed := readUsedPercent(rl, "primary_window")
secondaryUsed := readUsedPercent(rl, "secondary_window")
if primaryUsed == 0 && secondaryUsed == 0 {
return
}
newSnap := UsageSnapshot{
PrimaryUsed: primaryUsed,
SecondaryUsed: secondaryUsed,
PrimaryUsedPercent: primaryUsed,
SecondaryUsedPercent: secondaryUsed,
RetrievedAt: time.Now(),
Source: "body",
}
a.mu.Lock()
a.Usage = mergeUsage(a.Usage, newSnap)
a.mu.Unlock()
}
func readUsedPercent(rl map[string]any, key string) float64 {
v, ok := rl[key]
if !ok {
return 0
}
obj, ok := v.(map[string]any)
if !ok {
return 0
}
if up, ok := obj["used_percent"]; ok {
switch t := up.(type) {
case float64:
return t / 100.0
case int:
return float64(t) / 100.0
}
}
return 0
}
// applyRateLimitsFromTokenCount updates account usage from Codex token_count rate_limits.
// Format: {primary: {used_percent: 26.5, ...}, secondary: {used_percent: 14.5, ...}}
func (a *Account) applyRateLimitsFromTokenCount(rl map[string]any) {
if a == nil || rl == nil {
return
}
var primaryPct, secondaryPct float64
if primary, ok := rl["primary"].(map[string]any); ok {
if up, ok := primary["used_percent"]; ok {
switch t := up.(type) {
case float64:
primaryPct = t / 100.0
case int:
primaryPct = float64(t) / 100.0
}
}
}
if secondary, ok := rl["secondary"].(map[string]any); ok {
if up, ok := secondary["used_percent"]; ok {
switch t := up.(type) {
case float64:
secondaryPct = t / 100.0
case int:
secondaryPct = float64(t) / 100.0
}
}
}
if primaryPct == 0 && secondaryPct == 0 {
return
}
newSnap := UsageSnapshot{
PrimaryUsed: primaryPct,
SecondaryUsed: secondaryPct,
PrimaryUsedPercent: primaryPct,
SecondaryUsedPercent: secondaryPct,
RetrievedAt: time.Now(),
Source: "token_count",
}
a.mu.Lock()
a.Usage = mergeUsage(a.Usage, newSnap)
a.mu.Unlock()
}
// UsageSnapshot captures Codex usage headroom and optional credit info.
// PrimaryUsed/SecondaryUsed are kept for backward compatibility; values are 0-1.
type UsageSnapshot struct {
PrimaryUsed float64
SecondaryUsed float64
PrimaryUsedPercent float64
SecondaryUsedPercent float64
PrimaryWindowMinutes int
SecondaryWindowMinutes int
PrimaryResetAt time.Time
SecondaryResetAt time.Time
CreditsBalance float64
HasCredits bool
CreditsUnlimited bool
RetrievedAt time.Time
Source string
}
// RequestUsage captures per-request token consumption parsed from SSE events.
type RequestUsage struct {
Timestamp time.Time
AccountID string
PlanType string
UserID string
OriginID string
PromptCacheKey string
RequestID string
InputTokens int64
CachedInputTokens int64 // cache_read_input_tokens (cheap reads from cache)
CacheCreationTokens int64 // cache_creation_input_tokens (expensive writes to cache)
OutputTokens int64
ReasoningTokens int64
BillableTokens int64
// Rate limit snapshot after this request
PrimaryUsedPct float64
SecondaryUsedPct float64
// Model and provider info
Model string `json:"model,omitempty"` // e.g., "claude-sonnet-4-5-20250929", "o4-mini"
AccountType AccountType `json:"account_type,omitempty"` // "claude", "codex", "gemini"
}
// AccountUsage stores aggregates for an account with time windows.
type AccountUsage struct {
TotalInputTokens int64 `json:"total_input_tokens"`
TotalCachedTokens int64 `json:"total_cached_tokens"`
TotalOutputTokens int64 `json:"total_output_tokens"`
TotalReasoningTokens int64 `json:"total_reasoning_tokens"`
TotalBillableTokens int64 `json:"total_billable_tokens"`
TotalCostEstimate float64 `json:"total_cost_estimate"`
RequestCount int64 `json:"request_count"`
// For calculating tokens-per-percent
LastPrimaryPct float64 `json:"last_primary_pct"`
LastSecondaryPct float64 `json:"last_secondary_pct"`
LastUpdated time.Time `json:"last_updated"`
}
// TokenCapacity tracks tokens-per-percent for capacity analysis.
type TokenCapacity struct {
PlanType string `json:"plan_type"`
SampleCount int64 `json:"sample_count"`
TotalTokens int64 `json:"total_tokens"`
TotalPrimaryPctDelta float64 `json:"total_primary_pct_delta"`
TotalSecondaryPctDelta float64 `json:"total_secondary_pct_delta"`
// Raw token type totals for weighted estimation
TotalInputTokens int64 `json:"total_input_tokens"`
TotalCachedTokens int64 `json:"total_cached_tokens"`
TotalOutputTokens int64 `json:"total_output_tokens"`
TotalReasoningTokens int64 `json:"total_reasoning_tokens"`
// Derived: raw billable tokens per 1% of quota
TokensPerPrimaryPct float64 `json:"tokens_per_primary_pct,omitempty"`
TokensPerSecondaryPct float64 `json:"tokens_per_secondary_pct,omitempty"`
// Derived: weighted effective tokens per 1% (accounts for token cost differences)
// Formula: effective = input + (cached * 0.1) + (output * OutputMultiplier) + (reasoning * ReasoningMultiplier)
EffectivePerPrimaryPct float64 `json:"effective_per_primary_pct,omitempty"`
EffectivePerSecondaryPct float64 `json:"effective_per_secondary_pct,omitempty"`
// Estimated multipliers (refined over time with more data)
OutputMultiplier float64 `json:"output_multiplier,omitempty"` // How much more output costs vs input (typically 3-5x)
ReasoningMultiplier float64 `json:"reasoning_multiplier,omitempty"` // How much reasoning costs vs input
}
// applyRequestUsage increments aggregate counters for the account.
func (a *Account) applyRequestUsage(u RequestUsage) {
a.mu.Lock()
a.Totals.TotalInputTokens += u.InputTokens
a.Totals.TotalCachedTokens += u.CachedInputTokens
a.Totals.TotalOutputTokens += u.OutputTokens
a.Totals.TotalReasoningTokens += u.ReasoningTokens
a.Totals.TotalBillableTokens += u.BillableTokens
a.Totals.RequestCount++
if u.PrimaryUsedPct > 0 {
a.Totals.LastPrimaryPct = u.PrimaryUsedPct
}
if u.SecondaryUsedPct > 0 {
a.Totals.LastSecondaryPct = u.SecondaryUsedPct
}
a.Totals.LastUpdated = u.Timestamp
a.mu.Unlock()
}
// CodexAuthJSON is the format for Codex auth.json files.
type CodexAuthJSON struct {
OpenAIKey *string `json:"OPENAI_API_KEY"`
Tokens *TokenData `json:"tokens"`
LastRefresh *time.Time `json:"last_refresh"`
Dead bool `json:"dead"`
AllowedIP string `json:"allowed_ip"`
AllowedSourceIPs []string `json:"allowed_source_ips"`
}
type TokenData struct {
IDToken string `json:"id_token"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
AccountID *string `json:"account_id"`
}
// GeminiAuthJSON is the format for Gemini oauth_creds.json files.
// Files should be named gemini_*.json in the pool folder.
type GeminiAuthJSON struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
ExpiryDate int64 `json:"expiry_date"` // Unix timestamp in milliseconds
PlanType string `json:"plan_type"` // e.g., "ultra", "gemini"
LastRefresh string `json:"last_refresh"` // RFC3339 timestamp of last refresh attempt
}
// ClaudeAuthJSON is the format for Claude auth files.
// Files should be named claude_*.json in the pool folder.
// Supports both API key format and OAuth format (from Claude Code).
type ClaudeAuthJSON struct {
// API key format
APIKey string `json:"api_key,omitempty"`
PlanType string `json:"plan_type,omitempty"` // optional: pro, max, etc.
AllowedIP string `json:"allowed_ip,omitempty"`
AllowedSourceIPs []string `json:"allowed_source_ips,omitempty"`
// OAuth format (from Claude Code keychain)
ClaudeAiOauth *ClaudeOAuthData `json:"claudeAiOauth,omitempty"`
}
// ClaudeOAuthData is the OAuth token structure from Claude Code.
type ClaudeOAuthData struct {
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
ExpiresAt int64 `json:"expiresAt"` // Unix timestamp in milliseconds
Scopes []string `json:"scopes"`
SubscriptionType string `json:"subscriptionType"` // pro, max, etc.
RateLimitTier string `json:"rateLimitTier"`
}
func loadPool(dir string, registry *ProviderRegistry) ([]*Account, error) {
var accs []*Account
// Load accounts from provider subdirectories: pool/codex/, pool/claude/, pool/gemini/
providerDirs := map[string]AccountType{
"codex": AccountTypeCodex,
"claude": AccountTypeClaude,
"gemini": AccountTypeGemini,
"kimi": AccountTypeKimi,
"minimax": AccountTypeMinimax,
"zai": AccountTypeZAI,
}
for subdir, accountType := range providerDirs {
providerDir := filepath.Join(dir, subdir)
entries, err := os.ReadDir(providerDir)
if os.IsNotExist(err) {
continue // Skip if provider directory doesn't exist
}
if err != nil {
return nil, fmt.Errorf("read pool dir %s: %w", providerDir, err)
}
provider := registry.ForType(accountType)
if provider == nil {
continue
}
for _, e := range entries {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".json") {
continue
}
path := filepath.Join(providerDir, e.Name())
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read %s: %w", path, err)
}
acc, err := provider.LoadAccount(e.Name(), path, data)
if err != nil {
return nil, err
}
if acc != nil {
accs = append(accs, acc)
}
}
}
return accs, nil
}
// Note: Individual account loading functions are now in the provider files:
// - provider_codex.go: CodexProvider.LoadAccount
// - provider_claude.go: ClaudeProvider.LoadAccount
// - provider_gemini.go: GeminiProvider.LoadAccount
// poolState wraps accounts with a mutex.
type poolState struct {
mu sync.RWMutex
accounts []*Account
convPin map[string]string // conversation_id -> account ID
debug bool
rr uint64
tierThreshold float64 // secondary usage % at which we stop preferring a tier (default 0.50)
}
func newPoolState(accs []*Account, debug bool) *poolState {
return &poolState{accounts: accs, convPin: map[string]string{}, debug: debug, tierThreshold: 0.50}
}
// replace swaps the pool accounts (used on reload).
func (p *poolState) replace(accs []*Account) {
p.mu.Lock()
defer p.mu.Unlock()
p.accounts = accs
p.convPin = map[string]string{}
p.rr = 0
}
func (p *poolState) count() int {
p.mu.RLock()
defer p.mu.RUnlock()
return len(p.accounts)
}
// accountTier returns the preference tier for an account (1 = best, 2 = mid, 3 = last resort).
// Claude: tier 1 = max/team/max_team, tier 2 = unknown/other, tier 3 = pro
// Codex: tier 1 = pro, tier 2 = everything else
// Gemini: tier 1 = ultra, tier 2 = everything else
func accountTier(accType AccountType, planType string) int {
switch accType {
case AccountTypeClaude:
p := strings.ToLower(strings.TrimSpace(planType))
switch p {
case "max", "team", "max_team":
return 1
case "pro":
return 3
default:
return 2
}
case AccountTypeCodex:
if planType == "pro" {
return 1
}
return 2
case AccountTypeGemini:
if planType == "ultra" {
return 1
}
return 2
}
return 2
}
func isCodexProPlan(planType string) bool {
return strings.EqualFold(strings.TrimSpace(planType), "pro")
}
func accountAllowsClientIPLocked(a *Account, clientIP string) bool {
if a == nil || len(a.AllowedSourceIPs) == 0 {
return true
}
clientIP = strings.TrimSpace(clientIP)
if clientIP == "" {
return false
}
for _, allowedIP := range a.AllowedSourceIPs {
if strings.EqualFold(strings.TrimSpace(allowedIP), clientIP) {
return true
}
}
return false
}
// nearestCooldown returns how long until the next rate-limited account of the
// given type becomes available. Returns 0 if no accounts are cooling down.
// This lets the retry loop wait briefly instead of returning 503 immediately.
func (p *poolState) nearestCooldown(accountType AccountType, exclude map[string]bool) time.Duration {
p.mu.RLock()
defer p.mu.RUnlock()
now := time.Now()
var nearest time.Duration
for _, a := range p.accounts {
if exclude != nil && exclude[a.ID] {
continue
}
a.mu.Lock()
if a.Dead || a.Disabled || (accountType != "" && a.Type != accountType) {
a.mu.Unlock()
continue
}
if !a.RateLimitUntil.IsZero() && a.RateLimitUntil.After(now) {
wait := a.RateLimitUntil.Sub(now)
if nearest == 0 || wait < nearest {
nearest = wait
}
}
a.mu.Unlock()
}
return nearest
}
// candidate selects the best account using tiered selection, optionally filtering by type.
// If accountType is empty, all account types are considered.
//
// Selection strategy:
// 1. Conversation pinning (stickiness) — only unpin at hard limits
// 2. Split eligible accounts into Tier 1 and Tier 2
// 3. If any Tier 1 account has secondary < tierThreshold → pick best Tier 1 below threshold
// 4. Else if Tier 1 accounts exist above threshold → still prefer best Tier 1 by score
// (only fall to Tier 2 if it has significantly better score)
// 5. Else pick best Tier 2 by threshold then score
// 6. Within a tier, use score as tiebreaker (headroom, drain urgency, recency, inflight)
// 7. If all non-codex candidates are rate-limited, pick the best rate-limited account as fallback
// to avoid hard 503 failures during transient exhaustion.
func (p *poolState) candidate(conversationID string, exclude map[string]bool, accountType AccountType, requiredPlan string, clientIP string) *Account {
p.mu.Lock()
defer p.mu.Unlock()
now := time.Now()
// Conversation pinning — keep using the same account unless at hard limits
if conversationID != "" {
if id, ok := p.convPin[conversationID]; ok {
if exclude != nil && exclude[id] {
// pinned excluded; fall through to selection
} else if a := p.getLocked(id); a != nil {
a.mu.Lock()
ok := !a.Dead && !a.Disabled && (accountType == "" || a.Type == accountType) && planMatchesRequired(a.PlanType, requiredPlan) && accountAllowsClientIPLocked(a, clientIP)
if ok && a.Type == AccountTypeCodex && !isCodexProPlan(a.PlanType) {
ok = false
if p.debug {
log.Printf("unpinning conversation %s from non-pro codex account %s", conversationID, id)
}
}
if ok && a.Type != AccountTypeCodex && !a.RateLimitUntil.IsZero() && a.RateLimitUntil.After(now) {
ok = false
if p.debug {
log.Printf("unpinning conversation %s from rate-limited account %s (until %s)",
conversationID, id, a.RateLimitUntil.Format(time.RFC3339))
}
} else if ok && a.Type == AccountTypeCodex && !a.RateLimitUntil.IsZero() && a.RateLimitUntil.After(now) {
if p.debug {
log.Printf("ignoring rate limit for codex account %s (until %s)",
id, a.RateLimitUntil.Format(time.RFC3339))
}
}
// Unpin at 95% secondary (raised from 90% for better stickiness)
secondaryUsed := accountSecondaryUsageLocked(a)
if ok && secondaryUsed >= secondaryHardExcludeThreshold {
ok = false
if p.debug {
log.Printf("unpinning conversation %s from exhausted account %s (%.0f%% secondary >= %.0f%%)",
conversationID, id, secondaryUsed*100, secondaryHardExcludeThreshold*100)
}
}
// Also unpin if primary usage is at/above 95% (hard limit)
primaryUsed := accountPrimaryUsageLocked(a)
if ok && primaryUsed >= primaryHardExcludeThreshold {
ok = false
if p.debug {
log.Printf("unpinning conversation %s from account %s (%.0f%% primary >= %.0f%%)",
conversationID, id, primaryUsed*100, primaryHardExcludeThreshold*100)
}
}
// Also unpin if token is expired - don't wait for a failed request
if ok && !a.ExpiresAt.IsZero() && a.ExpiresAt.Before(now) {
ok = false
if p.debug {
log.Printf("unpinning conversation %s from expired account %s",
conversationID, id)
}
}
a.mu.Unlock()
if ok {
return a
}
}
}
}
n := len(p.accounts)
if n == 0 {
return nil
}
// Collect eligible accounts with their tier and score
type scoredAccount struct {
acc *Account
tier int
secondaryPct float64
score float64
}
var eligible []scoredAccount
var rateLimited []scoredAccount
start := int(p.rr % uint64(n))
for i := 0; i < n; i++ {
a := p.accounts[(start+i)%n]
if exclude != nil && exclude[a.ID] {
continue
}
a.mu.Lock()
if a.Dead || a.Disabled || (accountType != "" && a.Type != accountType) || !planMatchesRequired(a.PlanType, requiredPlan) || !accountAllowsClientIPLocked(a, clientIP) {
a.mu.Unlock()
continue
}
if a.Type != AccountTypeCodex && !a.RateLimitUntil.IsZero() && a.RateLimitUntil.After(now) {
secondaryUsed := accountSecondaryUsageLocked(a)
tier := accountTier(a.Type, a.PlanType)
score := scoreAccountLocked(a, now)
a.mu.Unlock()
// Prefer less-loaded accounts
score -= float64(atomic.LoadInt64(&a.Inflight)) * 0.02
rateLimited = append(rateLimited, scoredAccount{acc: a, tier: tier, secondaryPct: secondaryUsed, score: score})
if p.debug {
log.Printf("skipping account %s: rate limited until %s", a.ID, a.RateLimitUntil.Format(time.RFC3339))
}
continue
}
if a.Type == AccountTypeCodex && !a.RateLimitUntil.IsZero() && a.RateLimitUntil.After(now) {
if p.debug {
log.Printf("ignoring rate limit for codex account %s (until %s)", a.ID, a.RateLimitUntil.Format(time.RFC3339))
}
}
// Hard exclusion: >=95% primary usage
primaryUsed := accountPrimaryUsageLocked(a)
if primaryUsed >= primaryHardExcludeThreshold {
a.mu.Unlock()
if p.debug {
log.Printf("excluding account %s: primary usage %.1f%% >= %.0f%%", a.ID, primaryUsed*100, primaryHardExcludeThreshold*100)
}
continue
}
// Hard exclusion: >=99% secondary usage
secondaryUsed := accountSecondaryUsageLocked(a)
if secondaryUsed >= secondaryHardExcludeThreshold {
a.mu.Unlock()
if p.debug {
log.Printf("excluding account %s: secondary usage %.1f%% >= %.0f%%", a.ID, secondaryUsed*100, secondaryHardExcludeThreshold*100)
}
continue
}
tier := accountTier(a.Type, a.PlanType)
score := scoreAccountLocked(a, now)
a.mu.Unlock()
// Prefer less-loaded accounts
score -= float64(atomic.LoadInt64(&a.Inflight)) * 0.02
eligible = append(eligible, scoredAccount{acc: a, tier: tier, secondaryPct: secondaryUsed, score: score})
}
selectCandidate := func(accounts []scoredAccount) *Account {
threshold := p.tierThreshold
// Try Tier 1 accounts below threshold
var bestTier1Below *scoredAccount
var bestTier1Any *scoredAccount
for i := range accounts {
sa := &accounts[i]
if sa.tier == 1 {
if bestTier1Any == nil || sa.score > bestTier1Any.score {
bestTier1Any = sa
}
if sa.secondaryPct < threshold {
if bestTier1Below == nil || sa.score > bestTier1Below.score {
bestTier1Below = sa
}
}
}
}
if bestTier1Below != nil {
p.rr++
return bestTier1Below.acc
}
// Try Tier 2 accounts below threshold
var bestTier2Below *scoredAccount
var bestTier2Any *scoredAccount
for i := range accounts {
sa := &accounts[i]
if sa.tier == 2 {
if bestTier2Any == nil || sa.score > bestTier2Any.score {
bestTier2Any = sa
}
if sa.secondaryPct < threshold {
if bestTier2Below == nil || sa.score > bestTier2Below.score {
bestTier2Below = sa
}
}
}
}
// If tier 1 accounts exist above threshold, prefer them over tier 2 below threshold.
// Only fall to tier 2 if no tier 1 accounts at all.
if bestTier1Any != nil {
// Tier 1 exists but all above threshold. Still prefer tier 1 by score
// unless a tier 2 below threshold has significantly better score.
if accountType != AccountTypeCodex && bestTier2Below != nil && bestTier2Below.score > bestTier1Any.score+0.3 {
p.rr++
return bestTier2Below.acc
}
p.rr++
return bestTier1Any.acc
}
if bestTier2Below != nil {
p.rr++
return bestTier2Below.acc
}
if bestTier2Any != nil {
p.rr++
return bestTier2Any.acc
}
// Tier 3: last resort (e.g. Claude pro accounts)
var bestTier3Below *scoredAccount
var bestTier3Any *scoredAccount
for i := range accounts {
sa := &accounts[i]
if sa.tier == 3 {
if bestTier3Any == nil || sa.score > bestTier3Any.score {
bestTier3Any = sa
}
if sa.secondaryPct < threshold {
if bestTier3Below == nil || sa.score > bestTier3Below.score {
bestTier3Below = sa
}
}
}
}
if bestTier3Below != nil {
p.rr++
return bestTier3Below.acc
}
if bestTier3Any != nil {
p.rr++
return bestTier3Any.acc
}
// Absolute fallback — pick the one with highest score (most headroom)
var bestAll *scoredAccount
for i := range accounts {
sa := &accounts[i]
if bestAll == nil || sa.score > bestAll.score {
bestAll = sa
}
}
if bestAll != nil {
p.rr++
return bestAll.acc
}
return nil
}
if len(eligible) == 0 {
if len(rateLimited) > 0 && p.debug {
log.Printf("no non-rate-limited %s accounts available; refusing to route to rate-limited accounts", accountType)
}
return nil
}
return selectCandidate(eligible)
}
func planMatchesRequired(planType, requiredPlan string) bool {
if requiredPlan == "" {
return true
}
return strings.EqualFold(strings.TrimSpace(planType), strings.TrimSpace(requiredPlan))
}
// countByType returns the number of accounts of a given type (or all if empty).
func (p *poolState) countByType(accountType AccountType) int {
p.mu.RLock()
defer p.mu.RUnlock()
if accountType == "" {
return len(p.accounts)
}
count := 0
for _, a := range p.accounts {
if a.Type == accountType {
count++
}
}
return count
}
func scoreAccount(a *Account, now time.Time) float64 {
if a == nil {
return 0
}
a.mu.Lock()
defer a.mu.Unlock()
return scoreAccountLocked(a, now)
}
type scoreBreakdown struct {
Score float64
PrimaryUsed float64
SecondaryUsed float64
BaseHeadroom float64
DrainMultiplier float64
PrimaryPaceBonus float64
PrimaryPenalty float64
ExpiryPenalty float64
PenaltyRaw float64
PenaltyFactor float64
PenaltyApplied float64
ClampedToFloor bool
RecentUseBonus float64
CreditBonus float64
HeadroomPreCredit float64
}
func scoreAccountBreakdownLocked(a *Account, now time.Time) scoreBreakdown {
var out scoreBreakdown
decayPenaltyLocked(a, now)
primaryUsed := a.Usage.PrimaryUsedPercent
secondaryUsed := a.Usage.SecondaryUsedPercent
if primaryUsed == 0 && a.Usage.PrimaryUsed > 0 {
primaryUsed = a.Usage.PrimaryUsed
}
if secondaryUsed == 0 && a.Usage.SecondaryUsed > 0 {
secondaryUsed = a.Usage.SecondaryUsed
}
out.PrimaryUsed = primaryUsed
out.SecondaryUsed = secondaryUsed
// Start from weekly headroom.
headroom := 1.0 - secondaryUsed
out.BaseHeadroom = headroom
out.DrainMultiplier = 1.0
// Accounts closer to reset can absorb more traffic right now.
if !a.Usage.SecondaryResetAt.IsZero() && a.Usage.SecondaryResetAt.After(now) {
hoursRemaining := a.Usage.SecondaryResetAt.Sub(now).Hours()
totalHours := 168.0
if hoursRemaining > 1 && hoursRemaining < totalHours {
sustainableBurnRate := headroom / hoursRemaining
baselineBurnRate := 1.0 / totalHours
burnRateRatio := sustainableBurnRate / baselineBurnRate
maxMultiplier := 3.0
if hoursRemaining < 6 && headroom > 0.1 {
maxMultiplier = 8.0
}
if burnRateRatio > maxMultiplier {
burnRateRatio = maxMultiplier
} else if burnRateRatio < 0.3 {
burnRateRatio = 0.3
}
out.DrainMultiplier = burnRateRatio
headroom *= burnRateRatio
}
}
// Cap drain multiplier for accounts with no primary window data.
// Pro/Team plans lack a 5hr window; don't let phantom headroom inflate their score.
if a.Usage.PrimaryResetAt.IsZero() && primaryUsed == 0 {
if out.DrainMultiplier > 1.0 {
out.DrainMultiplier = 1.0
headroom = out.BaseHeadroom
}
}
// Bonus for short-term headroom in the 5h window.
// The 5h window controls burst capacity: an account at 0% primary can absorb
// heavy traffic right now regardless of 7d usage. Scale the bonus by how much
// primary headroom exists, up to matching the base headroom itself.
if !a.Usage.PrimaryResetAt.IsZero() && a.Usage.PrimaryResetAt.After(now) {
hoursRemaining := a.Usage.PrimaryResetAt.Sub(now).Hours()
primaryHeadroom := 1.0 - primaryUsed
if hoursRemaining > 0.1 && hoursRemaining <= 5.0 && primaryHeadroom > 0.05 {
// Scale bonus: more primary headroom = bigger boost.
// At 100% primary headroom (0% used), bonus ≈ 0.5 * timeWeight.
// At 50% primary headroom, bonus ≈ 0.25 * timeWeight.
// timeWeight: full bonus when >2h remain, tapers as window shrinks.
timeWeight := hoursRemaining / 3.0
if timeWeight > 1.0 {
timeWeight = 1.0
}
out.PrimaryPaceBonus = primaryHeadroom * 0.5 * timeWeight
}
} else if a.Usage.PrimaryResetAt.IsZero() && primaryUsed == 0 && a.Usage.RetrievedAt.IsZero() {
// No primary data at all (never polled) -- no bonus.
} else if a.Usage.PrimaryResetAt.IsZero() && primaryUsed < 0.5 {
// Have primary usage data but no reset time (some plan types).
// Give a modest bonus based on raw headroom.
out.PrimaryPaceBonus = (1.0 - primaryUsed) * 0.15
}
headroom += out.PrimaryPaceBonus
// Penalize only when 5h usage gets critically high.
if primaryUsed > 0.8 {
out.PrimaryPenalty = (primaryUsed - 0.8) * 2.0
headroom -= out.PrimaryPenalty
}
// Mild expiry penalty.
if !a.ExpiresAt.IsZero() {
ttl := a.ExpiresAt.Sub(now).Minutes()
if ttl < 0 {
out.ExpiryPenalty = 0.3
} else if ttl < 30 {
out.ExpiryPenalty = 0.2
} else if ttl < 60 {
out.ExpiryPenalty = 0.1
}
}
headroom -= out.ExpiryPenalty
out.PenaltyFactor = 1.0
if !a.Usage.SecondaryResetAt.IsZero() {
hoursRemaining := a.Usage.SecondaryResetAt.Sub(now).Hours()
secondaryHeadroom := 1.0 - secondaryUsed
if hoursRemaining > 0 && hoursRemaining < 6 && secondaryHeadroom > 0.1 {
out.PenaltyFactor = 0.3
}
}
out.PenaltyRaw = a.Penalty
out.PenaltyApplied = a.Penalty * out.PenaltyFactor
headroom -= out.PenaltyApplied
if headroom < 0.01 {
headroom = 0.01
out.ClampedToFloor = true
}
if !a.LastUsed.IsZero() && now.Sub(a.LastUsed) < 5*time.Minute {
out.RecentUseBonus = 0.1
headroom += out.RecentUseBonus
}
out.CreditBonus = 1.0
if a.Usage.CreditsUnlimited || a.Usage.HasCredits {
out.CreditBonus = 1.1
}
out.HeadroomPreCredit = headroom
out.Score = headroom * out.CreditBonus
return out
}
func scoreAccountLocked(a *Account, now time.Time) float64 {
return scoreAccountBreakdownLocked(a, now).Score
}
func scoreTooltipFromBreakdownLocked(a *Account, now time.Time, breakdown scoreBreakdown) string {
if a.Disabled {
return "Not scored because this account is disabled."
}
if a.Dead {
return "Not scored because this account is marked dead."
}
lines := make([]string, 0, 12)
lines = append(lines, fmt.Sprintf("Final score: %.2f", breakdown.Score))
lines = append(lines, fmt.Sprintf("7d headroom: %.2f from %.0f%% weekly usage", breakdown.BaseHeadroom, breakdown.SecondaryUsed*100))
if breakdown.DrainMultiplier != 1.0 {
lines = append(lines, fmt.Sprintf("Drain multiplier: x%.2f", breakdown.DrainMultiplier))
}
if breakdown.PrimaryPaceBonus > 0 {
lines = append(lines, fmt.Sprintf("5h pace bonus: +%.2f", breakdown.PrimaryPaceBonus))
}
if breakdown.PrimaryPenalty > 0 {
lines = append(lines, fmt.Sprintf("5h high-usage penalty: -%.2f at %.0f%%", breakdown.PrimaryPenalty, breakdown.PrimaryUsed*100))
}
if breakdown.ExpiryPenalty > 0 {
lines = append(lines, fmt.Sprintf("Expiry penalty: -%.2f", breakdown.ExpiryPenalty))
}
if breakdown.PenaltyApplied > 0 {
lines = append(lines, fmt.Sprintf("Penalty applied: -%.2f (raw %.2f x %.2f)", breakdown.PenaltyApplied, breakdown.PenaltyRaw, breakdown.PenaltyFactor))
}
if breakdown.ClampedToFloor {
lines = append(lines, "Headroom floor applied: 0.01")
}
if breakdown.RecentUseBonus > 0 {
lines = append(lines, fmt.Sprintf("Recent-use bonus: +%.2f", breakdown.RecentUseBonus))
}
if breakdown.CreditBonus > 1.0 {
lines = append(lines, fmt.Sprintf("Credits multiplier: x%.2f", breakdown.CreditBonus))
}
if accountCoolingDownLocked(a, now) {
lines = append(lines, "Cooldown is separate from score; this account is currently cooling down.")
}
lines = append(lines, fmt.Sprintf("Pre-credit headroom: %.2f", breakdown.HeadroomPreCredit))
return strings.Join(lines, "\n")
}
func scoreTooltipLocked(a *Account, now time.Time) string {
return scoreTooltipFromBreakdownLocked(a, now, scoreAccountBreakdownLocked(a, now))
}
func (p *poolState) pin(conversationID, accountID string) {
if conversationID == "" || accountID == "" {
return
}
p.mu.Lock()
p.convPin[conversationID] = accountID
p.mu.Unlock()
}
// allAccounts returns a copy of all accounts for stats/reporting.
func (p *poolState) allAccounts() []*Account {
p.mu.RLock()
defer p.mu.RUnlock()
out := make([]*Account, len(p.accounts))
copy(out, p.accounts)
return out
}
// saveAccount persists the account back to its auth.json file.
func saveAccount(a *Account) error {
if a == nil {
return fmt.Errorf("nil account")
}
if strings.TrimSpace(a.File) == "" {
return fmt.Errorf("account %s has empty file path", a.ID)
}
switch a.Type {
case AccountTypeGemini:
return saveGeminiAccount(a)
case AccountTypeClaude:
return saveClaudeAccount(a)
case AccountTypeKimi:
return saveAPIKeyAccount(a)
case AccountTypeMinimax:
return saveAPIKeyAccount(a)
case AccountTypeZAI:
return saveAPIKeyAccount(a)
default:
return saveCodexAccount(a)
}
}