Skip to main content

Overview

The TokenManager is the core component responsible for managing AI service accounts, including token lifecycle, account selection, quota tracking, and rate limiting. Location: src-tauri/src/proxy/token_manager.rs

Core Structure

ProxyToken Structure

Initialization

Creating TokenManager

Loading Accounts

Location: token_manager.rs:116

Account Filtering

Location: token_manager.rs:295 Accounts are skipped if:
  1. Manually disabled - disabled: true or proxy_disabled: true
  2. Validation blocked - Temporary block for CAPTCHA/verification
  3. Expired validation block - Auto-clear and reload

Token Selection Algorithm

Entry Point: get_token()

Location: token_manager.rs:969
Returns: (account_id, access_token, email, project_id, max_output_tokens)

Selection Strategy (Multi-Phase)

Phase 1: Capability Filtering

Location: token_manager.rs:1031 Only keep accounts that have the target model in their quota data:

Phase 2: Multi-Criteria Sorting

Location: token_manager.rs:1055

Phase 3: Special Modes

Preferred Account Mode (Fixed Account) Location: token_manager.rs:1131

Phase 4: P2C Load Balancing

Location: token_manager.rs:869 Power of 2 Choices (P2C):
  • Select 2 random accounts from top 5 candidates
  • Choose the one with higher quota
  • Reduces hotspotting compared to round-robin

Token Refresh

Automatic Refresh

Location: token_manager.rs:1196 Tokens are refreshed 5 minutes before expiry:

Quota Protection

Overview

Quota protection prevents low-quota accounts from being selected for protected models. Location: token_manager.rs:544

Protection Logic

Triggering Protection

Rate Limiting

Rate Limit Tracker

Checking Rate Limits

Setting Rate Limits

Auto-Cleanup

Location: token_manager.rs:79 Background task cleans up expired rate limits every 15 seconds:

Health Scoring

Tracking Health

Updating Health

  • Success: Increase health score (max 1.0)
  • Failure: Decrease health score (min 0.0)
  • Decay: Gradually recover over time

Session Binding (Sticky Sessions)

Purpose

Maintain account consistency across multiple requests in the same session (e.g., Claude Code multi-turn conversations).

Implementation

Checking for existing binding:

Graceful Shutdown

Summary

The TokenManager is a sophisticated account orchestration system that:
  • Loads accounts from disk with filtering
  • Selects optimal accounts using multi-phase algorithm
  • Refreshes tokens automatically before expiry
  • Protects quotas with model-level granularity
  • Handles rate limits with auto-cleanup
  • Maintains sessions for conversational continuity
  • Tracks health for reliability scoring
Next: Model Router Architecture