GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - 413x5/underclass: underclass: an OpenAI-compatible pooling proxy that pins sessions to one account (prompt cache stays warm), cools quota-exhausted subscriptions until their window resets, and fails fast with the earliest Retry-After when the whole pool is dry.

BranchesTags
Open more actions menu
 
 

Latest commit

 

History

126 Commits
126 Commits

Folders and files

NameName
Last commit message
Last commit date
.agents/skills
.agents/skills
 
 
.githooks
.githooks
 
 
.github/workflows
.github/workflows
 
 
docs
docs
 
 
nixos
nixos
 
 
scripts
scripts
 
 
src
src
 
 
tests
tests
 
 
.envrc
.envrc
 
 
.gitignore
.gitignore
 
 
AGENTS.md
AGENTS.md
 
 
CONTRACTS
CONTRACTS
 
 
CONTRIBUTING.md
CONTRIBUTING.md
 
 
Cargo.lock
Cargo.lock
 
 
Cargo.toml
Cargo.toml
 
 
LICENSE
LICENSE
 
 
README.md
README.md
 
 
config.example.toml
config.example.toml
 
 
devenv.lock
devenv.lock
 
 
devenv.nix
devenv.nix
 
 
devenv.yaml
devenv.yaml
 
 
flake.lock
flake.lock
 
 
flake.nix
flake.nix
 
 
renovate.json
renovate.json
 
 
skills-lock.json
skills-lock.json
 
 

Repository files navigation

underclass

A local proxy that pools multiple ChatGPT/Codex, GitHub Copilot, Claude Code, ClinePass, OpenCode Go, and Vercel AI Gateway subscriptions behind one endpoint.

Fork features

  • Virtual models (model aliases). Request subscriptions/<model>, credits/<model>, or free/<model>, for routing by billing surface, or to free models, across all configured and enabled accounts. Free models never cool a billing surface.
  • OpenCode Go backend. Pools OpenCode Go subscriptions, x-opencode-session sticky header, per-model 429/402 cooling, client user-agent forwarding, dynamic catalog from models.dev + Go's /v1/models listing.
  • ClinePass + ClineFree + Cline Usage-Billing backend. Chat Completions translation for /v1/responses, models feed discovery, client user-agent forwarding, per-billing-surface quota cooling.

Architecture decision records: docs/adr/fork.


                       ┌────────────────────────────────────┐
                       │            underclass              │
                       │                                    │
 client ──────────────►│  /v1/responses       (OpenAI)      │────► chatgpt.com
 (any OpenAI-compatible│  /v1/chat/completions              │      (Codex subs,
  client)              │  /v1/models                        │       OAuth device flow)
                       │                                    │────► api.githubcopilot.com
 Claude Code ─────────►│  /v1/messages        (Anthropic)   │      (Copilot subs,
 (ANTHROPIC_BASE_URL)  │                                    │       GitHub device flow)
 web UI ◄─────────────►│  sticky sessions · health pool     │────► api.anthropic.com
 (accounts, catalog,   │  fail-fast saturation · tracing    │      (Claude Code subs,
  live request feed)   │  per-surface quota cooling         │       OAuth paste-back)
                       │                                    │────► api.cline.bot
                       │                                    │      (ClinePass subs, Credits,
                       │                                    │       API keys)
                       │                                    │────► opencode.ai/inference/go
                       │                                    │      (OpenCode Go subs,
                       │                                    │       API keys)
                       │                                    │────► ai-gateway.vercel.sh
                       │                                    │      (Credits,
                       └────────────────────────────────────┘       API keys)

One subscription runs out of quota? It leaves rotation until its window resets — and comes back on its own. Sessions stay pinned to one subscription so upstream prompt caches stay warm. When everything is exhausted, the proxy fails fast with the earliest reset time instead of hanging.


Why

Subscription-based model access has a per-account quota. One account is a ceiling; twenty accounts are a pool. underclass turns a pile of personal subscriptions into a single durable endpoint that behaves like one well-provisioned provider:

  • No client changes — the surface is plain /v1/*; point opencode (or anything OpenAI-compatible) at it.
  • No quota whiplash — exhausted accounts cool down and recover automatically; clients never see account churn.
  • No cache waste — sessions are sticky, so the upstream prompt cache keeps working across turns.

Quick start

UNDERCLASS_PROXY_KEY="$(openssl rand -hex 32)" \
UNDERCLASS_UI_TOKEN="$(openssl rand -hex 32)" \
cargo run -- serve
underclass listening on http://127.0.0.1:8080
web ui: http://127.0.0.1:8080/

Keep the generated values in a password manager or runtime secret file; underclass never writes them to diagnostics. Open the web UI and paste the value supplied as UNDERCLASS_UI_TOKEN.

  1. Open the web UI and paste the configured admin token.
  2. Click Add account → pick ChatGPT / Codex, GitHub Copilot, or Claude Code (Anthropic) → follow the flow, or pick Cline (API key) and paste a key from app.cline.bot → Settings → API Keys, or pick OpenCode Go (API key) and paste a key from opencode.ai/console → Account → Personal API keys. Accounts are labeled automatically with the account's email, username, or OpenCode workspace.
  3. Repeat for every subscription you want in the pool.
  4. Point opencode at the pool:
cargo run -- connect
opencode --provider underclass --model underclass/gpt-5.5

underclass connect writes the provider block and credentials into your global opencode config (~/.config/opencode/opencode.json{,c} + auth.json), idempotently and with backups. Re-run it any time; --remove undoes it.

  1. Point Claude Code at the same pool (it speaks the Anthropic surface):
export ANTHROPIC_BASE_URL=http://127.0.0.1:8080
export CLAUDE_CODE_OAUTH_TOKEN=<the underclass proxy key>

CLAUDE_CODE_OAUTH_TOKEN is what the official client uses when an auth-injecting proxy sits in front of it: the client keeps its Claude Code request shape and sends the proxy key as its bearer token, and underclass replaces that with the pooled subscription credential.

How routing works

  • Sticky sessions. Requests carrying prompt_cache_key / promptCacheKey (opencode sends the session ID when configured with setCacheKey: true) always land on the same subscription, and OpenCode Go receives that same value as its required x-opencode-session header. Bindings live for 24h, survive restarts, and rebind preferentially within the same backend when an account cools.

  • Health pool. A quota response moves an account to cooling until the upstream deadline or a per-backend default. When the catalog scopes a model to a billing surface (Cline's credits and cline-pass), the cooldown applies only to that surface, so an exhausted credit balance does not take the ClinePass subscription out of rotation. Claude Code adds a per-model dimension: a limit that names one model family cools only that model on that account. Codex uses the later valid deadline from its usage-limit error and retry-after, and its account usage poll can extend cooldown to a later exhausted-window reset or readmit an account when upstream reports it allowed. 401s trigger one token refresh + retry, then the account needs re-login. Cooling accounts stay configured and return to rotation automatically.

  • Codex usage and banked resets. The admin page shows per-account usage windows and available reset credits. When a live request finds every enabled ChatGPT/Codex account unavailable, underclass can redeem one banked reset, choosing the account that would otherwise wait longest for natural quota recovery. This is enabled by default; set auto_codex_resets = false in ~/.config/underclass/config.toml or UNDERCLASS_AUTO_CODEX_RESETS=false to disable automatic redemption. To spend a credit by hand, click Use reset on the account row in the admin page or run underclass reset <email-or-id> against the running server (it uses the same admin token resolution as underclass top; pass --url plus UNDERCLASS_UI_TOKEN for a remote server). The manual path redeems exactly one credit for that account, refuses when upstream reports the account is not rate limited or a reset already redeemed for this outage has not restored usage, and --force overrides both refusals. To refresh credentials on demand (for example after an outage), click Refresh token on the account row or run underclass refresh <email-or-id> (or underclass refresh --all). A successful refresh returns an auth_error account to rotation; a failed one changes nothing, so the account still needs Re-login (see ADR 0026). Claude Code accounts have banked credits too; redeeming one is always manual, because it spends your own subscription.

  • Token accounting. Each upstream attempt is recorded in SQLite with its model, account, prompt cache key, and reported input/output tokens. Missing counts remain marked unknown. The admin page shows current-month totals and filters; historical rows remain queryable after account removal.

  • Stream outcomes and statistics. A 2xx stream can still fail upstream (e.g. response.failed with server_is_overloaded, which Codex shows as "Selected model is at capacity"). underclass records how every body ended (completed, failed, incomplete, truncated, upstream_error, client_closed), the sanitized error code, and the attempt duration. It logs stream.finished at warn for failures, and records capacity, policy (cyber_policy), quota, and saturation events. underclass stats and the admin page's Statistics panel report requests, sessions, tokens, peak and mean concurrency, outcomes, and events over up to two years. See ADR 0021.

  • Fail fast. If every account eligible for the requested model is cooling, the proxy answers 429 + Retry-After = earliest reset. No queuing. Eligibility follows the model's quota scope, so saturation is reported only when the surface that model bills against is exhausted.

  • Flat pool. Codex, Copilot, Claude Code, Cline, and OpenCode Go accounts compete by least-in-flight, filtered by per-backend model catalogs. Unknown model IDs pass through to the surface's default backend so new models work without proxy changes.

  • Two surfaces, one pool. /v1/responses and /v1/chat/completions speak OpenAI; /v1/messages speaks the Anthropic Messages API. A request is only ever routed to a backend that serves its surface, so an Anthropic request never lands on a Codex account and the other way round. See ADR 0024.

  • Claude Code subscriptions. The Anthropic surface serves the official Claude Code client only: the request must carry x-app: cli, a claude-cli/ user agent, the claude-code-20250219 beta, and a Claude Code identity block, and underclass forwards the client's headers and body verbatim, swapping only the credential. Anthropic's subscription quota is window-based (5-hour session, 7-day weekly, and a weekly window scoped to one model family), and underclass reads all of them from the account's own usage API, so an exhausted account leaves rotation exactly when its window resets — and a limit that only affects one model family leaves that account serving its other models. The admin page shows the plan, the three windows, and the banked reset credits; Use reset redeems exactly one of those credits when you ask for it (never automatically, because a credit is your own subscription). See ADR 0023.

  • Cline and ClinePass. Cline models are namespaced cline/…: credit-based models keep their upstream ID after the prefix (cline/anthropic/claude-sonnet-4-6, cline/openai/gpt-5.4), and ClinePass subscription models appear as cline/cline-pass/… (cline/cline-pass/kimi-k3, cline/cline-pass/deepseek-v4.1-flash-1017). GET /api/v1/models lists neither the ClinePass nor the free models, so a refresh also reads Cline's public recommended-models feed and takes both its clinePass and free buckets; a model Cline publishes becomes routable at the next refresh without a release, and that refresh happens when you press the Cline catalog button (or onboard a Cline account), not at boot. Free models bill credits at $0, not the subscription quota. Cline only speaks Chat Completions, so /v1/responses requests routed to it are translated to /api/v1/chat/completions and the reply is translated back to the Responses format. 402 Payment Required cools only the billing surface the model draws from (credits or cline-pass), so the other surface on the same key stays routable; 403 (model outside the plan) leaves the account in rotation. See the Cline backend ADR and per-surface quota cooling.

  • OpenCode Go. OpenCode Go models are namespaced opencode-go/… (opencode-go/kimi-k3, opencode-go/gpt-6-luna) and always travel over its OpenAI surface: the model decides the upstream path, so opencode-go/kimi-k3 is posted to /openai/v1/chat/completions and opencode-go/gpt-6-luna to /openai/v1/responses, and a /v1/responses request for a chat-family model is translated. The proxy's sticky key is sent as x-opencode-session, which OpenCode Go requires on every request. OpenCode Go meters usage per model, so a 429 — and a 402 naming an unavailable endpoint — cools that model on that account and leaves the rest of its catalog servable. Models it serves only over its Anthropic or Gemini APIs are not pooled at all. Cline and OpenCode Go present the client's own User-Agent upstream when the client sent one, so a real client is not identified as a proxy, and the built-in default otherwise; set user_agent (or cline_user_agent / opencode_go_user_agent) to present an identity of your own instead. The upstream backends — Codex, Copilot, and Claude — keep their own user-agent behaviour. See the OpenCode Go backend ADR and client user agent forwarding.

  • Failover only before output. A stream that fails with an upstream capacity error before any output is retried on another account. Once output starts — or, on the Anthropic surface, once the upstream has accepted the request — upstream errors pass through, so half-finished turns are never re-sent silently.

Design decisions and their trade-offs live in docs/adr/ — start with ADR 0010 for the routing model.

Configuration

Optional ~/.config/underclass/config.toml. config.example.toml lists every key with its built-in default and what it does; copy it there and edit the copy to change anything. Nothing in it is required — deleting a key restores the default shown.

key default meaning
bind 127.0.0.1:8080 listen address
proxy_key empty: minted on first run bearer key clients must send to /v1/*
ui_token empty: minted on first run admin token for the web UI + /admin/api/*
codex_cooldown_secs / codex_cooldown_ms 1800 / unset cooling window when upstream omits retry-after; the _ms key wins when set
copilot_cooldown_secs / copilot_cooldown_ms 1800 / unset same, for Copilot
claude_cooldown_secs / claude_cooldown_ms 1800 / unset same, for Claude Code accounts
cline_cooldown_secs / cline_cooldown_ms 1800 / unset same, for Cline (applied on 402, scoped to the model's billing surface)
opencode_go_cooldown_secs / opencode_go_cooldown_ms 1800 / unset same, for OpenCode Go (applied on 429, scoped to the requested model)
vercel_cooldown_secs / vercel_cooldown_ms 1800 / unset same, for Vercel AI Gateway
auto_codex_resets true redeem one banked Codex reset when every Codex account is unavailable
upstream_connect_timeout_secs 10 TCP/TLS connect budget per attempt; bounds only startup
pre_output_hold_secs 60 how long first output is held back so a capacity failure can fail over; expiry only stops holding
pre_output_hold_bytes 1048576 bytes buffered during that hold
stream_idle_timeout_secs 0 (off) end a streamed response that sends nothing for this long, with a terminal error event; 0 never ends a stream for being quiet
stats_retention_days 730 how long usage rows, upstream events, and daily stats rollups are kept
user_agent empty: the client's own outbound user agent for Cline, OpenCode Go, and Vercel
cline_user_agent empty: falls back to user_agent per-backend override for Cline
opencode_go_user_agent empty: falls back to user_agent per-backend override for OpenCode Go
vercel_user_agent empty: falls back to user_agent per-backend override for Vercel
[model_aliases] subscriptions / credits / default_kind = "subscriptions" billing-kind prefixes behind the derived subscriptions/ and credits/ aliases

Environment overrides: UNDERCLASS_BIND, UNDERCLASS_PROXY_KEY, UNDERCLASS_UI_TOKEN, UNDERCLASS_MONITOR_SOCKET (local socket path), UNDERCLASS_STATS_RETENTION_DAYS, UNDERCLASS_STREAM_IDLE_TIMEOUT_SECS, UNDERCLASS_UPSTREAM_CONNECT_TIMEOUT_SECS, UNDERCLASS_PRE_OUTPUT_HOLD_SECS, UNDERCLASS_PRE_OUTPUT_HOLD_BYTES, UNDERCLASS_USER_AGENT, UNDERCLASS_CLINE_USER_AGENT, UNDERCLASS_OPENCODE_GO_USER_AGENT. UNDERCLASS_OPENCODE_GO_COOLDOWN_SECS overrides the OpenCode Go cooldown. For testing against a mock upstream: UNDERCLASS_CODEX_UPSTREAM, UNDERCLASS_COPILOT_UPSTREAM, UNDERCLASS_CLINE_UPSTREAM, UNDERCLASS_MODELS_DEV_URL (the models.dev corpus, default https://models.dev/api.json), UNDERCLASS_GO_UPSTREAM (default to the real endpoints; the Cline base URL is https://api.cline.bot, without /api/v1, and the OpenCode Go base is https://opencode.ai/inference/go). Set UNDERCLASS_GO_UPSTREAM=https://opencode.ai/inference to pool a pay-as-you-go Console key instead of a Go subscription; UNDERCLASS_GO_CONSOLE points key verification at a different Console.

State (credentials, sticky bindings, model catalog, minted keys) lives in ~/.local/share/underclass/pool.db. Delete it to start fresh.

CLI

underclass serve [--bind ADDR]
underclass top [--url HTTP_OR_HTTPS_ORIGIN]
underclass stats [--since 24h|7d|90d|2y] [--bucket minute|hour|day] [--by total|model|account] [--json] [--url ORIGIN]
underclass stats import-codex [--dir DIR]... [--dry-run] [--url ORIGIN]
underclass connect [--base-url URL] [--api-key KEY] [--model MODEL]
                   [--project] [--no-default-model] [--dry-run] [--remove]

stats prints a UTC table with these columns: requests, sessions, tokens in/out, peak/mean concurrency, failed streams, and overloaded / policy / quota / cooling / saturated events. It uses the same admin token resolution as top. stats import-codex backfills capacity, quota, retry-exhaustion, and policy errors (such as cyber_policy) from $CODEX_HOME/sessions rollout logs. It sends only timestamps, kinds, codes, models, and dedupe keys, and is safe to re-run.

connect targets the global opencode config by default; --project writes ./.opencode/opencode.json instead. --dry-run prints the merged documents without writing.

Run underclass top (or utop from the Nix package) in a second terminal while underclass serve is running for a continuously updating pool monitor. It shows live in-flight requests, a 60-minute attempt chart, current UTC month token accounting, account status and sticky sessions, quota windows and banked resets, and recent outcomes. Each account has a PLAN column showing the plan the upstream reports (the ChatGPT plan for Codex accounts, pro/max/team/enterprise for Claude Code accounts); missing plan metadata shows unknown and Copilot shows —. Plan metadata updates with token rotation. Account states and quota levels are color coded and also labeled in text. Press q to quit; use arrow keys, j/k, or Page Up/Down to scroll accounts. d disables the selected account and e re-enables a disabled or auth error account; both ask for y first, and the write goes through the running server's admin API rather than the read-only monitor socket, so it needs the admin token. The dashboard reconnects if the server becomes unavailable. Locally it uses a Unix socket without a token; the NixOS service exposes /run/underclass/monitor.sock to local users. The socket serves only the monitor snapshot, which includes account labels and usage. If no socket is available, top can use the local admin token from UNDERCLASS_UI_TOKEN, config, or the existing database. For another server, pass --url and set UNDERCLASS_UI_TOKEN in the environment. The browser UI still requires its admin token. Copilot quota availability is shown as unknown because underclass has no Copilot quota snapshot. Counts are upstream attempts; token totals omit unknown usage.

utop showing a five-account Codex pool: live inference counts, a 60-minute attempts chart, per-account state, quota left and resets, and recent request outcomes

Endpoints

route auth purpose
POST /v1/responses proxy key Responses API, streamed through to the pool (translated for Cline, and for OpenCode Go's chat-family models)
POST /v1/chat/completions proxy key Chat Completions, same
POST /v1/messages proxy key Anthropic Messages API (Claude Code clients)
POST /v1/messages/count_tokens proxy key Anthropic token counting, same
POST /messages proxy key Messages API alias, for clients whose base URL already ends in /v1
GET /v1/models proxy key union catalog of account-backed backends: merged limits, scope, capability metadata, and derived aliases
GET / none web UI
GET /admin/api/state admin token accounts, catalog, last 200 requests
GET /admin/api/usage admin token token totals grouped by group_by=model,account_id,cache_key (any subset)
GET /admin/api/usage/requests admin token paginated per-attempt accounting rows
GET /admin/api/monitor admin token compact read-only live monitor snapshot
GET /admin/api/stats admin token bucketed requests, sessions, tokens, concurrency, outcomes, events (since, bucket, by)
POST /admin/api/events/import admin token idempotent upstream-event backfill (used by stats import-codex)
POST /admin/api/flows admin token start onboarding (device flow, or a Cline / OpenCode Go API key via api_key)
GET /admin/api/flows/{id} admin token poll an onboarding flow
POST /admin/api/flows/{id}/code admin token finish a Claude Code paste-back flow
POST /admin/api/accounts/{id}/enable [disable][relogin] admin token account controls
DELETE /admin/api/accounts/{id} admin token remove from pool
GET[PUT] /admin/api/catalog/{backend} admin token inspect/edit model catalog (codex, copilot, claude, cline, go)
GET /admin/api/client-key admin token retrieve the proxy key for connect

Every response carries x-request-id; logs are JSON (RUST_LOG filters, --log-format json|pretty) and each request logs the account (label) that served it.

Accounting queries accept from_ms (inclusive), to_ms (exclusive), and exact model, account_id, or cache_key filters. Use missing_key=true to select requests without a key. Grouped summaries and request details accept limit (1–1000, default 100) and offset; summary responses also include unpaginated totals. With no time bounds, queries default to the current UTC month; provide from_ms=0 to query all history. Each summary includes measured and unknown request counts. Token totals sum reported values only; they are lower bounds when unknown requests exist. See ADR 0014.

A blank cache key means the client sent no prompt_cache_key, not that prompt caching is off — the proxy does not invent a key. Cline's prompt cache is content-addressed and shared across its API keys, so a session that moves between Cline subscriptions still hits cache; stickiness keeps a session on one billing surface rather than protecting cache warmth. See Prompt Cache Scope Across Subscriptions.

Long requests, timeouts, and stream failures

There is no total request deadline. A long review runs for as long as the upstream keeps producing: no request deadline, no read deadline, and no inference request carries a per-request HTTP timeout. Three bounds cover the edges of one attempt, and each one is 0 to turn off:

bound default what it bounds on expiry
upstream connect (upstream_connect_timeout_secs) 10s TCP/TLS connect only the attempt fails over
response headers (upstream_response_header_timeout_secs) 1800s the wait for the upstream's response head, never the body the attempt ends as upstream_response_timeout and fails over
mid-body silence (stream_idle_timeout_secs) 60s the gap before the next chunk, reset on every chunk — not the body's total time the body ends with one terminal error event
pre-output hold (pre_output_hold_secs / pre_output_hold_bytes) 60s / 1 MiB how long output is held back so a capacity failure can still fail over holding stops and streaming continues — never a failure
shutdown drain 5s graceful restart only remaining requests abort, recorded client_closed

The two defaults are deliberate and nest above a client's own patience rather than inside it:

  • Mid-body silence, 60s. A healthy stream emits deltas continuously — reasoning deltas included — so a minute of complete silence mid-body means the upstream has stopped talking rather than being slow. The timer wraps one next() call, so a long but active response is never cut.

  • Response headers, 1800s. This sits above a client's own wait (the review bundle uses ai_timeout=1500), so it never races the client's decision: it is a leak backstop for a request nobody is waiting for any more, not a policy on how long generation may take. Lowering it toward the client's timeout turns it into one. It is applied with tokio::time::timeout around the send, never as a reqwest client timeout — that would bound the body too and re-create the premature cut fixed in #30. If no account can produce an upstream response at all, the request answers 504 carrying the same upstream_response_timeout code its usage row does:

    {"error":{"message":"upstream sent no response headers within the configured bound; retry the request","type":"upstream_response_timeout"}}
    

A non-streaming completion is not covered by the mid-body bound, because it has no body to observe until the head arrives; the header bound is what covers that wait.

If the upstream fails after the response has started, the client's body is never truncated. The proxy emits exactly one terminal error event in the protocol the client is speaking, using the stable code upstream_stream_error and a message naming the backend, and then ends the body completely, so a chunked terminator (or Content-Length) always arrives:

event: error
data: {"type":"error","code":"upstream_stream_error","message":"upstream codex stream ended early: the connection failed before the response completed"}

Chat Completions receives the same data: frame with an OpenAI-shaped error object, and the Anthropic surface receives {"type":"error","error":{"type":"upstream_stream_error",...}}. A translated /v1/responses stream keeps its single response.failed terminal event instead. The usage row for the attempt records the same code, so a client's report and the server's accounting agree. See Stream Failures and Timeouts.

Watching an attempt that never gets upstream headers

An attempt logs request.selected, then request.awaiting_headers when it begins waiting for the upstream's response head (fields: request_id, attempt, cache_key, model, upstream_model, endpoint, backend, account, account_id). attempt is the attempt's 1-based position in this request's failover chain, and cache_key is the client's own session key — the identity that joins separate requests belonging to one logical call, since transport-level retries arrive as new requests.

Everything after the head arrives is already covered by request.completed, upstream.network_error, usage.recorded, and stream.finished. The one case that used to be silent is an attempt that never reaches the head and is abandoned — the client goes away, the request is cancelled, or the server shuts down. That case now logs exactly one terminal line, emitted from a Drop guard so it fires however the attempt ends:

{"level":"WARN","message":"request.abandoned","request_id":"…","attempt":1,"cache_key":"…","stage":"awaiting_headers","reason":"upstream_silent","elapsed_ms":857004,…}
  • stage says where the attempt was: token (the upstream was never contacted) or awaiting_headers.
  • reason distinguishes the causes: upstream_silent (still waiting for headers — the case that used to vanish), client_aborted (the future was dropped before the upstream was contacted), or header_timeout (the configured bound expired; that path also logs upstream.headers_timeout with the limit).
  • The line is not emitted when the attempt completed normally or failed for a reason it already logged, so an attempt is never reported twice.

No timeout was added by this instrumentation: it observes and names what happens, it does not decide it. See Watching Abandoned Requests.

Correlation with preflight

When preflight, the secret-inspection proxy, fronts underclass, it generates a UUIDv4 and forwards it as x-request-id. (The preflight-code review bundle is a separate tool and plays no part in this path.) Underclass preserves that ID in its response, routing/retry logs, and request history. Search the same request_id in both services to trace inspection through pool routing.

Underclass accepts one hyphenated RFC4122 UUIDv4 and normalizes it to lowercase. Missing, duplicate, invalid, nil, and other-version IDs are replaced before authentication or logging. Every handled response receives the resulting ID, including 401s, 429s, model discovery, and unmatched routes. Provider responses cannot replace it. Correlation IDs convey no authorization or proof that preflight inspected a request. See ADR 0012.

Models

The catalog is data, not code: seeded with the Codex families (gpt-5.4, gpt-5.4-mini, gpt-5.3-codex-spark, gpt-5.5, gpt-5.6-sol, gpt-5.6-terra, gpt-5.6-luna, gpt-6-astra, gpt-6-sol), Copilot's live /models list, Cline's cline/ + cline/cline-pass/ IDs (refreshed from Cline's recommended-models feed), and OpenCode Go's opencode-go/ IDs. Edit it in the UI or via the admin API; routing eligibility and the opencode model block follow it. A restart never changes the Copilot, Cline, or OpenCode Go catalogs: they are fetched only when you press Refresh Copilot catalog, Refresh Cline catalog, or Refresh OpenCode Go catalog (or call the matching POST /admin/api/catalog/refresh-* endpoint), and on account onboarding. Claude is the exception - it has no refresh button, so its catalog refreshes at boot. See ADR 0007 and Catalog Refresh Is Operator-Driven.

GET /v1/models, the UI's opencode snippet, and underclass connect list only the catalogs of backends that have an account, so every advertised id is one the pool can route. Stored rows are never pruned when an account is removed - re-adding it advertises its models again - and the catalog editor still shows every stored row, marking a backend with no account. See Only Account-Backed Models Are Advertised.

Each entry carries the original seven keys plus two additive ones:

key meaning
id, object, name, owned_by unchanged
context_window, max_input_tokens, max_output_tokens the published limit, or JSON null when no source published one - the key is always present, and 0 never reaches the wire
scope credits or cline-pass for a model that bills against a surface; absent when the whole account shares one quota
metadata reasoning (supported plus the per-model effort ladder), tools, structured_output, modalities, cost, prompt_cache, knowledge, wire, reasoning_field, status

A capability a backend did not publish stays null in metadata, never a guess: an empty effort ladder means toggle-only reasoning, and a model that reports no effort array is not given invented levels. A model recorded as deprecated is stored but never advertised, so picking from /v1/models cannot hit a 404. OpenCode Go's /v1/models supplies its own specs; Cline's ClinePass set comes from its recommended-models feed and its specs from models.dev cline-pass, which is advisory only - a failed models.dev read leaves the catalog exactly as it was. See Model Metadata: Sources, Precedence, and What We Refuse to Copy.

Installing on macOS

The Nix path below is the supported install on Linux. On macOS, scripts/deploy_macos.sh installs underclass from source and updates it afterwards, in either case through a launch agent:

scripts/deploy_macos.sh                 # fresh install, or update the installed copy
scripts/deploy_macos.sh --dry-run       # fetch and report what it would do
scripts/deploy_macos.sh --list          # list rollback points
scripts/deploy_macos.sh --rollback      # restore the newest one
scripts/deploy_macos.sh --rollback REV  # restore the point recorded for that revision

It detects a fresh install rather than being told: no binary or no launch agent means build, install, write the agent in ~/Library/LaunchAgents, load it and verify health; anything else is an update, which records a rollback point (previous binary, a consistent pool.db snapshot and a manifest under ~/.local/share/underclass/releases/) before installing, builds before touching the service, and restarts with a proven pid change plus a 200 from /v1/models. Every run also installs config.example.toml beside your live config so you can diff the reference against your own ~/.config/underclass/config.toml; that file is created only when it is missing or empty and is never overwritten.

scripts/migrate_db.sh is the companion migration runner, and it is OS-neutral: it needs sqlite3, plus lsof for the guard that refuses to rewrite a database a daemon still holds (on a host without lsof, stop the underclass service and set MIGRATE_ASSUME_NO_WRITER=1). It never invokes a service manager, so it works the same on macOS and Linux. It applies the one-shot data rewrites a pool.db needs across a rename, registered in order and all inside one transaction, with an online-backup safety copy first. No migration is registered today; it exists so the next data rewrite is an entry in its registry rather than a new script and a new procedure:

scripts/migrate_db.sh --list            # registered migrations and which are pending
scripts/migrate_db.sh --check           # exit 0 when nothing is pending, 1 when something is
scripts/migrate_db.sh --dry-run         # report what would change; write nothing
scripts/migrate_db.sh --restore         # restore the newest backup it made

deploy_macos.sh runs it automatically when --check reports pending work, with the daemon stopped. No migration is registered today. Adding one is three edits inside scripts/migrate_db.sh: an entry in MIGRATIONS, a describe case, and a pending_<slug> / sql_<slug> pair; its header lists them.

Nix flake

The repository is a Nix flake: it exposes the CLI as a package/app and the devenv development shell as devShells.default.

Run the proxy without installing:

nix run github:ghuntley/underclass -- serve

Install it into your profile:

nix profile install github:ghuntley/underclass
utop

The installed package puts both underclass and utop on your PATH. utop runs underclass top and accepts the same --url option. You can also run it without installing with nix run github:ghuntley/underclass#utop. Enabling the NixOS service with its default package also adds both commands to the host PATH. utop connects to the service's local monitor socket without a token.

Use the devenv shell (Rust toolchain, cargo) for development:

nix develop --no-pure-eval
cargo test

--no-pure-eval is required for the devenv shell (devenv inspects the working directory; this matches devenv's own flake template). The package and app outputs are pure — nix run and nix profile install need no flags.

Long-term devenv users can keep using devenv shell / devenv test directly — nix develop and devenv shell activate the same devenv.nix.

NixOS module

Add underclass to your flake inputs and import its module:

{
  inputs.underclass.url = "github:ghuntley/underclass";

  outputs =
    { nixpkgs, underclass, ... }:
    {
      nixosConfigurations.my-host = nixpkgs.lib.nixosSystem {
        system = "x86_64-linux";
        modules = [
          underclass.nixosModules.default
          {
            services.underclass = {
              enable = true;
              bindAddress = "127.0.0.1:8080";
              environmentFile = "/run/secrets/underclass.env";
              settings = {
                codex_cooldown_secs = 1800;
                copilot_cooldown_secs = 1800;
              };
            };
          }
        ];
      };
    };
}

The runtime environment file can provide credentials without placing them in the Nix store:

UNDERCLASS_PROXY_KEY=sk-underclass-...
UNDERCLASS_UI_TOKEN=...

The service uses a dynamic user, persists its database in /var/lib/underclass, binds to localhost by default, and leaves the firewall closed. Set services.underclass.openFirewall = true only when intentionally binding beyond localhost.

The flake also exports overlays.default. Validate the module and its QEMU machine test with:

nix build .#checks.x86_64-linux.underclass-module
nix build .#checks.x86_64-linux.underclass-vm

Notes:

  • The package builds from the committed Cargo.lock; dependency versions are pinned there.
  • nix build skips cargo test because the property tests compile the Hegel engine as a build step, which needs network access that the Nix sandbox denies. CI runs the full suite via devenv (see .github/workflows/ci.yml).

Security

  • Access/refresh tokens, authorization headers, and prompt bodies are never logged.
  • Account labels (email/username) appear in logs and the UI by design; raw UUID account IDs are truncated.
  • auth.json written by connect uses 0600. Never commit pool.db or *.bak.
  • The proxy binds to localhost by default; put it behind a tunnel only if you understand the exposure.
  • OAuth tokens rotate: every Codex refresh persists the new refresh token immediately, and so does every Claude Code refresh.
  • Anthropic's terms restrict subscription OAuth. As of February 2026 Anthropic states that subscription OAuth is intended exclusively for Claude Code and Claude.ai, that third parties may not collect, store, or intermediate those credentials, and that using them in any other product or service violates the Consumer Terms of Service. Anthropic enforces this server-side and can invalidate a credential without notice. underclass's Claude Code support is therefore local-only, serves the official client exclusively, and stores the credential in the pool database. See ADR 0023 for the measured behaviour and the full risk statement.

Development

cargo build
cargo test        # unit tests, Hegel property tests, and the e2e suite

Testing is two-tier: plain unit tests for exact behavior (headers, merges, redaction), and Hegel property tests over the pure pool core — stickiness stability, health-state invariants, saturation minimums, TTL/cap bounds. The core (src/pool.rs, src/health.rs) is synchronous with an injected clock; async lives only at the edges. New backends implement the provider::Backend trait and register — nothing else changes.

Setup, the checks a change must pass, and the review loop are in CONTRIBUTING.md. Agent conventions and the ADR policy are in AGENTS.md. Architecture decision records: docs/adr/.

License

MIT

Project layout

src/
  main.rs        bootstrap, router, background tasks
  lib.rs         library root: module list for the binary and the tests
  config.rs      TOML + env config
  models.rs      domain types (Account, status, catalog, log entries)
  store.rs       SQLite persistence (accounts, bindings, catalog, config)
  pool.rs        pure pool core: stickiness, eligibility, selection
  health.rs      quota classification, retry-after parsing
  provider.rs    Backend trait
  codex.rs       ChatGPT/Codex backend (device flow, refresh, headers)
  copilot.rs     GitHub Copilot backend (device flow, catalog, headers)
  claude.rs      Claude Code backend (PKCE paste-back flow, Anthropic surface)
  cline.rs       Cline backend (API key, Chat-Completions upstream)
  opencode_go.rs OpenCode Go backend (API key, per-model OpenAI surface)
  vercel.rs      Vercel AI Gateway backend (API key, dynamic catalog, credits)
  flows.rs       device-code flow registry for onboarding
  tokens.rs      single-flight token refresh
  jwt.rs         token claim parsing (account id extraction)
  resets.rs      Codex usage snapshots and banked reset redemption
  proxy.rs       /v1/* handlers, failover, streaming
  responses.rs   Responses-to-Chat-Completions translation
  usage.rs       token + stream-outcome tap over upstream bodies
  stats.rs       pure stats core: concurrency sweep, bucketing, rollup merge
  stats_api.rs   stats query, event import, retention/rollup maintenance
  stats_cli.rs   `stats` verb and Codex rollout import
  monitor.rs     read-only snapshot for the terminal monitor
  top.rs         `top` terminal monitor client
  correlation.rs validated `x-request-id` propagation
  logging.rs     structured logs, correlation IDs, redaction
  ui.rs          admin API
  ui.html        embedded single-page web UI
  cli.rs         `connect` verb, JSONC-safe opencode config merge
tests/
  properties.rs  Hegel property tests over the pure core
  e2e.rs         full-pool story against a mock upstream
  correlation.rs request-ID middleware tests
scripts/
  deploy_macos.sh   macOS install/update through launchd, with rollback points
  migrate_db.sh     OS-neutral database migration runner used by deploy_macos.sh

About

underclass: an OpenAI-compatible pooling proxy that pins sessions to one account (prompt cache stays warm), cools quota-exhausted subscriptions until their window resets, and fails fast with the earliest Retry-After when the whole pool is dry.

ghuntley.com

Resources

Readme
License

Contributing

Contributing
Activity

Stars

0 stars

Watchers

1 watching

Forks

0 forks
Report repository

Releases

Packages

Contributors

Languages

You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.