Self-hosted chat over multiple LLM providers, with automatic model routing that enforces permissions and budget in code rather than in a prompt.
Built from three specifications — architecture.md, routing-design.md and
api-spec.md — which are the source of truth. Where this README and a spec
disagree, the spec wins and the README is wrong.
| Phase | Scope | State |
|---|---|---|
| 0 | Foundation: compose, migrations, config, logging, health, CI | done |
| 1 | Data layer: 17 tables, migrations, system group seeding | done |
| 2 | Auth and permissions: OIDC, superuser, sessions, resolver | done |
| 3 | Provider adapters: streaming, typed errors, breaker | done |
| 4 | Chat core: CRUD, WS gateway, streaming, resume, locking | done |
| 5 | Router: pipeline, selector, fallback, auto-titling | done |
| 6 | Frontend: auth, shell, composer, telemetry, settings, admin | partial |
| 7 | Admin: scoped endpoints, guards, audit, analytics, UI | partial |
| 8 | Lifecycle | next |
cp .env.example .env
python -c "import secrets; print(secrets.token_urlsafe(48))" # SECRET_KEY
python -c "import secrets; print(secrets.token_urlsafe(48))" # ENCRYPTION_KEYS
$EDITOR .env
make upThe API is on http://localhost:8000, the app on http://localhost:5173, and the OpenAPI docs on http://localhost:8000/docs outside production.
On the first boot with an empty database, a superuser is created and its password is written to the API logs once, at WARNING, inside a delimited block:
====================================================
SUPERUSER CREATED — this password is shown ONE TIME
username: admin
password: <generated>
====================================================
Capture it then. It is hashed with argon2id and is not recoverable from the database.
If you missed it, or you have booted before and the banner did not reappear — it only ever prints on the boot that creates the account:
docker compose exec api app superuser reset-passwordThat regenerates the password, prints it once, and requires a change at next sign-in. There is deliberately no HTTP endpoint for it.
Subsequent boots never regenerate, never overwrite and never re-log. The bootstrap holds a Postgres advisory lock, so replicas starting at the same moment cannot create two accounts or print two different passwords.
cd api && python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
alembic upgrade head
uvicorn app.main:app --reload
cd web && npm ci && npm run devPostgres and Redis still need to be running; docker compose up postgres redis
starts just those.
A fresh install has no models, so nothing can be sent. Sign in as the superuser and open Admin → Providers & models:
- Add a provider (name, optional base URL, API key).
- Add a model on it — model key, display name, tier, context window, prices. Tick "use as the router's classifier" on a cheap one, or auto mode falls back to the default tier on every message.
- Use Test connection: a one-token probe that catches a typo'd model key before a user meets it as a runtime failure.
- Open Groups & users and grant the model to a group.
The model appears in the composer dropdown immediately — permissions are cached for five minutes but invalidated eagerly on every grant.
"Reconnecting…" that never resolves. The chat socket connects to
/api/v1/ws, which the Vite dev proxy must be told to upgrade (ws: true on
the /api rule). If you have customised vite.config.ts, check that first —
REST will keep working while the socket silently fails.
No superuser password in the logs. It prints only on the boot that creates the account. To reissue it:
docker compose exec api app superuser reset-passwordSetup for Authentik and Microsoft Entra ID, including the one setting in each that silently breaks group sync, is in docs/identity-providers.md.
Everything is in .env.example with inline notes. List-valued variables
(CORS_ORIGINS, ENCRYPTION_KEYS) accept a bare value, a comma-separated list,
or a JSON array — all three are tested through the environment, not just through
the settings constructor. Four entries deserve reading
before a production deploy:
SECRET_KEYsigns access tokens. Rotating it logs everyone out.ENCRYPTION_KEYSencrypts provider API keys and the OAuth client secret at rest. The first key encrypts, all keys decrypt, so rotation is: prepend a new key, re-save the affected rows, drop the old one. Lose every key and every stored provider credential is gone — they are not recoverable from a backup of the database alone.SUPERUSER_ENABLED=falsecloses the local login path without touching the account, its group memberships or its conversations.RETENTION_PURGE_DAYS=0means never purge, and is the shipped default. Archiving at 30 days is on; permanent deletion is an explicit operator choice. SeeDECISIONS.mdD-004 for what happens when this changes after the fact.
api/
app/
config.py every tunable, typed, in one place
db.py async engine, session factory, naming conventions
redis_client.py live state only — never the system of record
core/
context.py ULID request ids in a contextvar
logging.py structured logs carrying request_id
errors.py api-spec §7 taxonomy and the one error envelope
middleware.py request id assignment, access logging
api/v1/ REST surface; feature routers mount here per phase
models/ ORM: enums, identity, catalog, chat, operations
auth/ permissions resolver, cache, tokens, OIDC sync
admin/ escalation guards, in-transaction audit logging
providers/ adapter contract, Anthropic + OpenAI, circuit breaker
chat/ costs and ledger, locks, delta buffer, generation runner
router/ task profile, deterministic selector, pipeline
bootstrap/ idempotent first-boot steps
cli.py operator commands that must not be HTTP endpoints
alembic/ migrations
scripts/ dump_openapi.py — the frontend's type source
tests/
invariants.py the twelve invariants, as checked data
db.py migration-built schema fixtures
data/ schema and seed tests
web/
src/api/ generated types + the fetch client
src/lib/ pure logic: timestamps, money, keyboard, grouping
src/ws/ socket client with seq tracking and resume
src/components/ composer, message list, telemetry, panels
src/store/ Zustand: drafts, panel state, expanded debug bars
make check # lint, types and both test suites
make test
make smoke # boot the stack and verify first-run behaviourmake smoke is the one that catches deployment-shaped problems: it runs
docker compose up, waits for readiness, and checks that the generated
superuser password actually signs in. CI runs the same checks as a third job,
because a green test suite has twice now coexisted with a stack that would not
start.
Backend tests run against a real Postgres and Redis, in CI as well as locally.
This is deliberate: advisory locks, SET NX generation locks and refresh-token
rotation races are precisely the behaviours a mock reproduces incorrectly.
Provider HTTP calls are stubbed at the transport layer with respx, so the
adapter code under test is the real thing.
tests/invariants.py registers the twelve non-negotiable invariants and the
named test that owns each one. CURRENT_PHASE gates enforcement: once a phase
ships, deleting or renaming its invariant test breaks the build.
The routing selector, permission resolver and cost calculation carry a 100% branch floor. They are small, pure and load-bearing, and every serious bug this system can have passes through one of them.
- Money is
Decimalend to end,NUMERICin Postgres, decimal strings on the wire. Afloatanywhere in a cost path is a defect, not a style choice. - All timestamps are
TIMESTAMPTZin UTC. The client formats to local time. - No
anyin frontend application code, and payload types are generated fromapi/openapi.jsonrather than written by hand. CI diffs both artifacts. - Access tokens live in memory; refresh tokens live in an httpOnly cookie.
ESLint bans the
localStorageglobal to keep it that way. - The WebSocket is authenticated by ticket exchange, never a JWT in the query string — query strings land in access logs and browser history.
- IdP endpoints must be https and ID tokens are fully validated: issuer, audience, expiry, nonce and signature against the IdP's JWKS.