llm-broker
CLAUDE.md1 starsChanged 9 months agoMITView on GitHub
Run a single test: Database migration (explicit, never auto-migrates on startup): Single entry point: cmd/relay/main.go. All code lives in internal/. The Driver interface is composed of role-specific sub-interfaces: Descriptor, RelayDriver, OAuthDriver, RefreshDriver, SchedulerDriver, AdminDriver. ExecutionDriver = RelayDriver + SchedulerDriver. Full Driver = all combined. The project is not a bag of Claude/Codex special cases. It is a small LLM account orchestration kernel. The design center is: The core execution law is: The state law is: Read this literally: This is…
- Reads credentials
- Installs packages
The file
Show its rules and text
We split this CLAUDE.md into the rules it gives an agent
14 rules. About 0 are common, 9 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈9
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 18
Run a single test:
- Very specific: line 126
Do not store duplicate state.
- Very specific: line 127
If status, cooldown_until, and driver.CanServe(...) determine availability, do not add shadow booleans like the old schedulable.
- Distinctive: line 130
Do not grow public schema columns for provider-specific utilization windows or reset fields.
- Very specific: line 133
Keep identity_json and provider_state_json conceptually separate: identity_json answers "who is this account?" provider_state_json answers …
- Distinctive: line 162
If a provider change requires touching many core packages, the boundary is regressing.
- Very specific: line 232
If you find yourself editing pool because a provider has a different header name, stop.
- Distinctive: line 240
add fallback layers that duplicate current truth
- Distinctive: line 243
add UI knobs for redundant state that should not exist
- Very specific: line 295
If provider-specific, can it live entirely in driver?
- Distinctive: line 300
If the answer to 2 is "no" or to 3-5 is "yes", rethink the change.
- Distinctive: line 308
Do not unbind a cell "to fix" a routing issue — ask first.
- Distinctive: line 309
Do not assume "no cell" (direct connect) is a safe fallback.
- Distinctive: line 310
If an account's cell is misconfigured, disable the cell or cooldown — do not touch the binding.
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Build & Dev Commands
make build # Build frontend + Go binary (output: ./llm-broker)
make test # Run all Go tests: go test ./...
make lint # Run go vet ./...
make ui # Build Svelte frontend only (cd web && npm install && npm run build)
make dev-ui # Run Svelte dev server (cd web && npm run dev)
make dev-go # Run Go backend only (go run ./cmd/relay)
make deps # Tidy Go modules
make clean # Remove binary and frontend distRun a single test:
go test ./internal/pool/ -run TestPickExclusion -vDatabase migration (explicit, never auto-migrates on startup):
./llm-broker migrateTech Stack
- Go 1.24 — backend, single binary with embedded frontend
- Svelte 5 + SvelteKit 2 + Vite 6 — frontend in
web/, built tointernal/ui/dist/and embedded - SQLite (pure Go
modernc.org/sqlite) — no CGO dependency - AES-256-GCM — token encryption via
ENCRYPTION_KEYenv var - uTLS — TLS fingerprint obfuscation for upstream requests
Architecture Map
Single entry point: cmd/relay/main.go. All code lives in internal/.
server HTTP handlers, routing, admin API, auth middleware
↓
relay Execution pipeline: plan → pick → token → build → upstream → interpret → observe
↓
pool In-memory account state machine. Loads from DB at startup.
Pick() selects accounts. Observe() is the sole write entrance for state transitions.
↓
driver Provider abstraction boundary. Each provider (Claude, Codex, Gemini) implements Driver.
Owns: OAuth, token refresh, request building, response interpretation, model catalog.
↓
tokens Token freshness manager. Refresh locks, expiry checks, encrypted storage.
↓
store SQLite persistence. Schema in store/schema.sql (embedded).
↓
events Ring-buffer event bus. Observability only — never source of truth.
transport HTTP client pool with per-account proxy routing.
domain Core types: Account, Provider, Status. No business logic.
config All config from environment variables. No config files.
crypto AES-256-GCM encrypt/decrypt for stored tokens.The Driver interface is composed of role-specific sub-interfaces:
Descriptor, RelayDriver, OAuthDriver, RefreshDriver, SchedulerDriver, AdminDriver.
ExecutionDriver = RelayDriver + SchedulerDriver. Full Driver = all combined.
Essence
The project is not a bag of Claude/Codex special cases. It is a small LLM account orchestration kernel.
The design center is:
provider is the change axis
core is the stable axisThe core execution law is:
Relay(req, drv) =
retry(N) {
a <- pool.Pick(drv, exclude, model, boundSession)
t <- tokens.Ensure(a)
u <- drv.BuildRequest(req, a, t)
r <- upstream(u)
e <- drv.Interpret(r)
pool.Observe(a, e)
surface.Write(drv, r)
}The state law is:
identity(account) = (provider, subject)
available(account, model, now) =
status == active
AND cooldown_until <= now
AND drv.CanServe(provider_state_json, model, now)
next_state = Observe(current_state, effect)Read this literally:
driverowns provider protocol.poolowns generic account state transitions.relayowns the execution pipeline.tokensowns token freshness.eventsare observability only, not source of truth.
This is a synchronous state-machine core with an event side channel. It is not an event-driven core.
Non-Negotiable Invariants
- Provider details must terminate at
driver.Driver.pool,relay,server, andstoreshould not learn provider-specific headers, body shapes, ban strings, or rate-limit parsing rules. pool.Observe()is the single semantic write entrance for provider outcomes. Effects enter there; state transitions happen there.- Real account identity is
UNIQUE(provider, subject).emailis display data only. Never deduplicate or bind by email. - Do not store duplicate state.
If
status,cooldown_until, anddriver.CanServe(...)determine availability, do not add shadow booleans like the oldschedulable. - Provider-owned state stays in
provider_state_json. Do not grow public schema columns for provider-specific utilization windows or reset fields. - Durable provider identity metadata stays in
identity_json. Keepidentity_jsonandprovider_state_jsonconceptually separate:identity_jsonanswers "who is this account?"provider_state_jsonanswers "what is this account's current provider-specific runtime state?" - Database migration is explicit.
Startup should not silently rewrite schema. Use
llm-broker migrate.
Architectural Boundary
What belongs in a driver:
- OAuth generation and code exchange
- token refresh request semantics
- upstream request construction
- response interpretation into
driver.Effect - streaming and non-stream response handling
- probe semantics
- model catalog
- provider-specific utilization math
- provider-specific account presentation fields
What does not belong in core:
if provider == ...branches for protocol behavior- provider-specific rate-limit headers in
pool - provider-specific JSON parsing in
server - provider-specific model catalogs hardcoded in
server - provider-specific schema columns in
domain.Account
If a provider change requires touching many core packages, the boundary is regressing.
The Correct Mental Model
Think in compiler terms:
provider protocol -> driver.Interpret -> Effect -> pool.Observe -> account statedriver.Effect is the IR between unstable upstream behavior and stable core semantics.
The core should only care about things like:
- success
- cooldown
- overload
- block
- auth failure
- updated provider state
The core should not care how any provider expressed those facts.
Schema Aesthetic
The schema should encode the fewest truths necessary.
Good:
idprovidersubjectemailstatusprioritypriority_modecooldown_until- encrypted tokens
- timestamps
identity_jsonprovider_state_json
Bad:
- provider-specific columns for rate limits
- duplicate booleans derivable from existing state
- compatibility debris kept after migration is over
The project prefers fewer states over more defensive code.
Route Truths
These are intentional and should not drift casually:
- UI lives at
/and/dashboard - onboarding lives at
/add-account/{provider} /add-accountwithout a provider should 404/ui/*should 404GET /v1/modelsis authenticated- relay paths are registered from driver metadata, not hardcoded server constants
Extension Rule
Adding a provider should look roughly like:
- implement
driver.Driver - register it in
cmd/relay/main.go - expose provider metadata through
Driver.Info()andDriver.Models() - reuse existing
pool,relay,server,tokens, andstore
If you find yourself editing pool because a provider has a different header name, stop. The driver abstraction is being violated.
Review Heuristics
Reject or challenge changes that:
- reintroduce provider conditionals into core packages
- deduplicate accounts by email or mutable metadata
- add fallback layers that duplicate current truth
- rebuild provider state from old legacy fields after migration is complete
- make events/logs authoritative for runtime state
- add UI knobs for redundant state that should not exist
Prefer changes that:
- delete invalid states
- tighten the provider boundary
- make
drivermore complete and core more ignorant - reduce cross-package knowledge
- improve rollback safety without preserving dead runtime compatibility
Operational Truths
- The project relies on VPS snapshots and
restore.shfor rollback safety. - A failed deploy should be recoverable with
bash .claude/skills/deploy/scripts/restore.sh latest. - That safety net exists so the code can stay clean; it is not permission to leave permanent compatibility clutter in the runtime path.
Client Anti-Bypass Setup
Clients must only reach upstream through the broker. Server-side rewriting alone is insufficient if clients can bypass the gateway.
Required client environment:
export ANTHROPIC_BASE_URL="https://<broker-host>"
export ANTHROPIC_API_KEY="<broker-token>"
export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
export CLAUDE_CODE_ATTRIBUTION_HEADER=falseOptional network-level blocking (Clash / ACL rules):
# Block direct connections to Anthropic from client machines
- DOMAIN-SUFFIX,anthropic.com,REJECT
- DOMAIN-SUFFIX,claude.com,REJECT
- DOMAIN-SUFFIX,claude.ai,REJECTServer-side opt-in:
# Enable prompt environment masking (normalize platform/shell/OS/paths)
export PROMPT_ENV_HOME=/Users/userVerification: GET /v1/models with a valid broker token returns the model list (proves auth + relay wiring). Direct curl https://api.anthropic.com from client machines is blocked by network rules.
Short Checklist Before You Edit
Ask:
- Is this change about stable orchestration semantics or provider-specific protocol?
- If provider-specific, can it live entirely in
driver? - Am I introducing duplicate state?
- Am I violating
identity(account) = (provider, subject)? - Am I making core understand something it should merely consume as
Effect?
If the answer to 2 is "no" or to 3-5 is "yes", rethink the change.
Operational Safety — Account Binding
NEVER unbind, rebind, or change an account's cell_id without explicit user confirmation.
Account-to-cell binding determines the egress IP. Changing it can expose the account to a different IP, triggering provider bans. This is an irreversible, destructive operation.
- Do not unbind a cell "to fix" a routing issue — ask first.
- Do not assume "no cell" (direct connect) is a safe fallback.
- If an account's cell is misconfigured, disable the cell or cooldown — do not touch the binding.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

