OpenSelect multi-account proxy architecture cover
OpenSelect multi-account proxy architecture cover

Engineering Bottom Line: Running an AI coding loop where Claude (5x) handles architecture, Codex (Pro $200) handles edge-case review, and DeepSeek 1017 executes 80%+ of implementation work at 5x the generation speed burns through a $10 opencode-go weekly quota in roughly one day. To eliminate constant session exits on 429 rate limits, I built and open-sourced **OpenSelect** (MIT License) — a single-process Bun + TypeScript local daemon with 0 runtime npm dependencies (backed by bun:sqlite and covered by 277 automated tests) that exposes a unified Anthropic + OpenAI proxy on :8788 and a live telemetry dashboard on :8789.

  • Pre-First-Byte Failover Without Dropping Sessions: Background usage polling every 45 seconds proactively shifts new sessions at a configurable 97% quota threshold, while in-flight requests hitting 429, 401, 403, 5xx, or mid-header stream drops fail over across accounts before the first byte reaches Claude Code or opencode.
  • Local Anthropic-to-OpenAI Protocol Translation: Pointing ANTHROPIC_BASE_URL=http://127.0.0.1:8788 lets Claude Code drive deepseek-v4.1-flash, glm-5.1, and 37+ catalog models natively — including [1m] context detection that returns a local prompt is too long signal at 1,048,576 tokens to trigger /compact cleanly.
  • Cross-Provider Fallback Chain: Aggregates opencode-go pools with Z.ai (GLM), MiniMax, Command Code, Ollama Cloud, and DeepSeek Official (fallbackOnly=true) under an automated coding-auto routing ladder and free-first zero-cost overflow mode.

Why Single-Account Subscriptions Break Multi-Model Coding Loops

Over the past few months, my daily development workflow settled into a strict three-tier division of labor:

  • Leader (Architecture & Final Sign-Off): Claude (5x) handles system design, cross-module decomposition, and final decisions.
  • Assister (Co-Review & Edge Cases): Codex (Pro $200) handles boundary checks and targeted review.
  • Editor (High-Volume Implementation): DeepSeek 1017 handles over 80% of hands-on code generation because its coding feel and >5x faster generation speed keep iteration tight.

The bottleneck wasn't model quality — it was quota throughput. At peak intensity, I ran 17 concurrent $10 opencode-go subscriptions, burning an entire account's weekly allowance roughly once per day, alongside Z.ai (GLM), MiniMax, Command Code (Kimi), and DeepSeek's pay-as-you-go API.

Because Claude Code (alongside opencode) is my daily terminal entrypoint, two recurring failures broke flow multiple times a day:

  1. Forced Session Restarts on 429 Limits: Whenever an active account hit its 5-hour rolling cap or weekly cap — or when switching to GLM or MiniMax — I had to exit the active Claude Code session, swap configs, and lose conversational momentum.
  2. Brittle Existing Proxies: The 2–3 open-source rotation tools I tested required heavy manual config mapping across providers and offered zero real-time visibility into per-window pressure.

**OpenSelect** collapses quota polling, pre-first-byte failover, protocol translation, and time-of-day route pricing into one local daemon.

opencode / Claude Code (37+ models & multi-provider aliases)
   │  baseURL = http://127.0.0.1:8788
   ▼
OpenSelect Proxy :8788                   ┌────────────── Usage Poller (45s parallel poll)
   ├─ /chat/completions /responses ────► │  https://opencode.ai/inference/go
   │                     /openai/v1/...  │    + direct provider pool (Z.ai/MiniMax/CC/DS/Ollama)
   ├─ /messages ─────────────────────►   │    Selection: sticky -> least-pressure -> fallback
   │                     /anthropic/v1/… │  429/5xx -> cooldown + pre-first-byte ms retry
   └─ /models/<m>:streamGenerateC. ────► └─ 401 -> invalid · 403 -> (account x model) neg-cache

Core Architecture: Pool Failover, Protocol Translation & Multi-Provider Routing

1. Pre-First-Byte Failover Across 17+ Accounts

Managing a double-digit account pool manually is impossible. OpenSelect runs two synchronized relay layers:

  • Proactive 45-Second Usage Polling & 97% Pre-Rotation: A background worker polls GET /inference/go/v1/usage every 45 seconds across all accounts, tracking rolling (5h), weekly, and monthly percentages plus reset countdowns (and restoring snapshots <24h old on restart so hot accounts aren't accidentally re-selected). Once any window crosses the threshold (default 97%, tunable from 95% to 99%), new sessions route via sticky -> least-pressure -> fallback.
  • In-Flight Pre-First-Byte Retry: If an active session hits upstream 429, 401, 403, 5xx, a network drop, or even a 2xx header followed by a mid-stream stall before the first payload chunk, OpenSelect buffers the first chunk check and retries on the next healthy account (up to 4 attempts by default) before a single byte is flushed to the client.
  • Granular Error Isolation (Zero Good-Account Poisoning):
Upstream FailureOpenSelect HandlingClient Impact
Upstream 429 (Rate Limit)Parses retry-after + metadata.limitName, applies targeted cooldown, fails over immediatelySeamless continuation
Upstream 401 (Invalid Key)Marks account invalid out of rotation, retries next account (auto-recovers if later poll succeeds)Seamless continuation
Upstream 403 (Model/Region Block)Never poisons the whole account; sets a 15-minute (account x model) negative cache and retriesSeamless continuation
Upstream 5xx / Pre-First-Byte DropShort cooldown (<= 60s), logs original and failover account in ledger, retriesSeamless continuation
Cloudflare 1010 BlockNormalizes upstream User-Agent: opencode/1.0.0 to avoid WAF script-signature blocksEliminates 1010 errors

2. Zero-Config Claude Code Attachment & Local Protocol Translation

To run OpenAI-compatible coding models (deepseek-v4.1-flash, glm-5.1) directly inside Claude Code, :8788 acts as a dual Anthropic + OpenAI gateway:

  • Native Anthropic Passthrough: Supports POST /v1/messages and /v1/messages/count_tokens across 9 family=anthropic models with zero translation overhead, synthesizing stable x-opencode-session headers from credentials when omitted.
  • Built-In Anthropic-to-OpenAI Chat Translator: Point ANTHROPIC_BASE_URL at http://127.0.0.1:8788:
ANTHROPIC_BASE_URL=http://127.0.0.1:8788 ANTHROPIC_API_KEY=placeholder \
  claude --model glm-5.1

The translator converts requests once locally (so failover retries reuse the translated payload with zero duplicate overhead), mapping mid-conversation system prompts, multi-turn history, image inputs, tools / tool_choice, tool_result, and stop_sequences, while normalizing OpenAI SSE streams — including interleaved or missing tool-call index fields — into valid Anthropic stream events.

  • 1M Context Auto-Compact Trigger ([1m]): Appending [1m] (e.g., deepseek-v4.1-flash[1m]) strips the suffix before forwarding and intercepts requests exceeding 1,048,576 tokens locally with a standard Anthropic prompt is too long response. Claude Code triggers /compact automatically instead of slamming into an upstream 400 wall.

For terminal ergonomics, ./scripts/install-claude-aliases.sh backs up ~/.zshrc and installs three alias launchers with zero embedded secrets (actual credentials remain locked in 0600 ~/.openselect/config.json):

Terminal AliasTarget ModelIntended Workflow
ds-clideepseek-v4.1-flash[1m]Primary fast Editor routed across the 17-account pool
free-clideepseek-v4.1-flash-freeZero-cost execution via free-tier routes
auto-clicoding-auto[1m]Automatic cross-provider ladder (Z.ai -> MiniMax -> opencode-go -> DeepSeek Official)

3. Multi-Provider Survival Ladder & free-first Mode

Beyond opencode-go, OpenSelect natively integrates five direct provider pools:

ProviderProtocol SupportExample Model AliasesDefault Reasoning InjectionQuota / Health Endpoint
OpenCode GoAnthropic / OpenAI / GoogleAll 37 catalog modelsNative passthroughGET /inference/go/v1/usage (5h/weekly/monthly)
Z.ai (GLM)Native Anthropiczai/glm-5.3-flash, zai/glm-5.3thinking.enabled + effort=maxGET /api/monitor/usage/quota/limit
MiniMax (CN/Global)Native Anthropicminimax/MiniMax-M3.1-Flash, M3output_config.effort=maxGET /v1/token_plan/remains
Command CodeAnthropic + OpenAIcc/kimi-k3.1-pro, cc/glm-5.3-flashNative passthroughMulti-key failover per provider
Ollama CloudAnthropic + OpenAIollama/<auto-discovered>Native passthroughAuto-probes /v1/models
DeepSeek OfficialNative Anthropicdeepseek/deepseek-flash, v4-prothinking.enabled + effort=maxGET /user/balance (CNY balance)

Two details matter in production:

  1. fallbackOnly=true on Pay-As-You-Go APIs: In coding-auto, requests traverse Z.ai GLM-5.3-Flash -> MiniMax M3.1-Flash -> opencode-go deepseek-v4.1-flash -> DeepSeek Official deepseek-flash. Marking DeepSeek Official as fallbackOnly=true ensures cash API balances are never touched until every subscription pool is exhausted.
  2. Smart 429 Cooldowns & free-first Isolation: Direct providers only trigger long cooldowns when a retry-after / limitName header is present or quota hits 100% (bare transient 429s pause just 3 seconds). Similarly, free-first tries the 7 opencode zen free models plus verified Go free-tier models (longcat-2.5-preview-free, minimax-m3.1-flash-free) first, caching free-model failures per (account x free_model) for 15 minutes without cooling down the underlying paid account.

One-Command opencode Injection (opensel wire) & Telemetry Console (:8789)

During end-to-end testing, we confirmed a subtle opencode client quirk: opencode only honors model-level settings.baseURL overrides — provider-level settings.baseURL and legacy provider.options.baseURL are silently ignored.

Instead of hand-editing 37 model blocks, setup takes four commands:

git clone https://github.com/Acorne-VJ/OpenSelect.git
cd OpenSelect
./bin/opensel init

./bin/opensel import                              # Batch-import existing local opencode credentials
# or: ./bin/opensel add --key <KEY> --label go-01

./bin/opensel serve                               # Starts :8788 proxy + :8789 UI + 45s poller
./bin/opensel wire                                # Safely injects all 37 model baseURLs (reversible via unwire)

Before writing, opensel wire snapshots the original config to ~/.openselect/backups/ and tracks per-model state in wired.json, so ./bin/opensel unwire restores direct connections cleanly while preserving manual post-wire edits. Adding or removing accounts hot-reloads within one poll cycle, and ./bin/opensel install registers a macOS launchd service plus daily backups.

Opening http://127.0.0.1:8789 exposes the local cockpit:

  • Pool Cockpit (/): Live 5h/weekly/monthly progress bars, local-timezone reset timers, historical usage charts with threshold markers, active session pinning ("Set Preferred"), and a live price-performance table indexed to DeepSeek Official = 100%.
  • Token Analytics (/tokens): Aggregates input, output, and cache tokens across providers, accounts, models, and clients with a 91-day activity heatmap (explicitly tagging translated-stream token counts as estimates).
  • Time-of-Day Route Optimizer (/routes): bun run collect:pricing fetches peak vs. off-peak multipliers (such as opencode-go doubling DeepSeek token weights during peak hours) and scores routes by effective cost x pressure x latency x quality x reliability.
  • Catalog Sync, Diagnostics & Signed Backups: opensel sync-catalog --write unions GET /v1/models across accounts with zero-inference protocol probing, opensel doctor audits the full chain, and opensel backup exports SQLite VACUUM INTO snapshots with Ed25519 signature verification and optional AES-256-CBC encrypted private Git backup.

FAQ

Does OpenSelect require Docker or external npm dependencies?

No. OpenSelect runs as a single Bun + TypeScript process with 0 runtime npm dependencies, using Bun's built-in bun:sqlite for state, telemetry, and snapshots, backed by 277 automated tests.

How does OpenSelect avoid dropping an active Claude Code session on a 429 error?

OpenSelect buffers the initial upstream response check before forwarding the first payload byte to the client. If an account returns 429, 401, 403, 5xx, or drops before the first body chunk, OpenSelect fails over to the next healthy account (up to 4 retries by default) without terminating the client session.

Why didn't setting a provider-level baseURL work in opencode?

End-to-end testing showed that opencode silently ignores provider-level settings.baseURL and legacy provider.options.baseURL, honoring only per-model settings.baseURL overrides. opensel wire automates injecting all 37 model entries reversibly via wired.json and ./bin/opensel unwire.

Will free-first failures lock out my paid opencode-go accounts?

No. When a free candidate model fails with 429, 403, or 5xx, OpenSelect records a 15-minute (account x free_model) negative cache entry and falls back immediately to the paid model without applying cooldowns to the account's paid quota pool.


Repository & Primary References