Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

docs: reorganise docs into per-domain folders with overviews and changelogs (#979)

Davisville36850e81f0da
diff --git a/.github/workflows/cli-release.yml b/.github/workflows/cli-release.yml
index 54ab55d7..cf9f4431 100644
--- a/.github/workflows/cli-release.yml
+++ b/.github/workflows/cli-release.yml
@@ -1,7 +1,7 @@
name: CLI release
# Publishes the `freellmapi` CLI to npm. Closes #671 — the README and
-# docs/clients.md have always documented `npx freellmapi setup-claude`, but the
+# docs/clients/01-agent-clients.md have always documented `npx freellmapi setup-claude`, but the
# package was never pushed to the registry, so every one of those commands died
# with npm E404.
#
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 59d37bff..ffa726d5 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -48,7 +48,7 @@ npm run db:migration:down
The dashboard ships 60 locales. `en.json` is the source of truth and every other file mirrors
its keys, so run `npm run check:i18n` from `client/` before opening a PR. See
-[docs/translating.md](docs/translating.md) for the full rules and the settled Chinese
+[docs/i18n/01-translating.md](docs/i18n/01-translating.md) for the full rules and the settled Chinese
terminology.
## Commit checklist hook
diff --git a/README.md b/README.md
index 8e96b24a..379de98c 100644
--- a/README.md
+++ b/README.md
@@ -54,7 +54,7 @@ Your router updates its own model catalog from a signed feed: new free models, q
- [Contributing](#contributing)
- [Disclaimer](#disclaimer)
-**Guides:** [Install & deploy](docs/install.md) · [API reference](docs/api.md) · [Clients & coding agents](docs/clients.md) · [Prompt compression](docs/compression.md) · [Architecture & internals](docs/architecture.md) · [Documentation index](docs/README.md) · [Contributor guide](CONTRIBUTING.md)
+**Guides:** [Install & deploy](docs/install.md) · [API reference](docs/api/01-rest-api.md) · [Clients & coding agents](docs/clients/01-agent-clients.md) · [Prompt compression](docs/compression/01-compression-pipeline.md) · [Architecture & internals](docs/architecture.md) · [Documentation index](docs/README.md) · [Contributor guide](CONTRIBUTING.md)
## Why this exists
@@ -137,9 +137,9 @@ The full, always-current list lives at **[freellmapi.co/models](https://freellma
</div>
-Most of these configure themselves with one command — `npx freellmapi setup-claude`, `setup-codex`, `setup-aider`, `setup-dsh` (DeepSeek Harness), and eleven more generators that fetch your live catalog, back up existing config, and never clobber what's already there. Claude Code and Codex also get zero-persistence launchers (`freellmapi launch`, `freellmapi launch-codex`) that inject credentials into the child process only. Zed and JetBrains AI connect through the opt-in [Ollama emulation](docs/clients.md#ollama-clients); Gemini CLI speaks its native wire on `/v1beta`.
+Most of these configure themselves with one command — `npx freellmapi setup-claude`, `setup-codex`, `setup-aider`, `setup-dsh` (DeepSeek Harness), and eleven more generators that fetch your live catalog, back up existing config, and never clobber what's already there. Claude Code and Codex also get zero-persistence launchers (`freellmapi launch`, `freellmapi launch-codex`) that inject credentials into the child process only. Zed and JetBrains AI connect through the opt-in [Ollama emulation](docs/clients/01-agent-clients.md#ollama-clients); Gemini CLI speaks its native wire on `/v1beta`.
-Per-tool recipes, the setup CLI reference, revocable URL tokens for headerless clients, and the MCP server all live in **[Clients & coding agents →](docs/clients.md)**
+Per-tool recipes, the setup CLI reference, revocable URL tokens for headerless clients, and the MCP server all live in **[Clients & coding agents →](docs/clients/01-agent-clients.md)**
## How it compares
@@ -151,21 +151,21 @@ Based on public documentation, July 2026 — corrections welcome.
![Feature overview](repo-assets/features.png)
-- **Every OpenAI-style surface** — `/v1/chat/completions`, `/v1/responses` (what Codex CLI needs), `/v1/completions` (editor ghost-text autocomplete), `/v1/images/generations`, `/v1/videos/generations`, `/v1/audio/speech`, `/v1/audio/transcriptions`, `/v1/embeddings`, and `/v1/models` — streaming and non-streaming, from the official SDKs or any OpenAI-compatible client. [API reference →](docs/api.md)
-- **Anthropic Messages API** — `/v1/messages` speaks Anthropic's wire format over the same router, so **Claude Code** and the official Anthropic SDKs run against your free pool. [Details →](docs/api.md#anthropic--claude-clients)
+- **Every OpenAI-style surface** — `/v1/chat/completions`, `/v1/responses` (what Codex CLI needs), `/v1/completions` (editor ghost-text autocomplete), `/v1/images/generations`, `/v1/videos/generations`, `/v1/audio/speech`, `/v1/audio/transcriptions`, `/v1/embeddings`, and `/v1/models` — streaming and non-streaming, from the official SDKs or any OpenAI-compatible client. [API reference →](docs/api/01-rest-api.md)
+- **Anthropic Messages API** — `/v1/messages` speaks Anthropic's wire format over the same router, so **Claude Code** and the official Anthropic SDKs run against your free pool. [Details →](docs/api/01-rest-api.md#anthropic--claude-clients)
- **Native Gemini + Ollama surfaces** — Gemini CLI can use `/v1beta` (`generateContent`, streaming, token counting, models), while opt-in Ollama emulation serves NDJSON chat/generate, tags, metadata, and embeddings for Zed, JetBrains, and other local-model clients.
-- **Fusion (multi-model synthesis)** — request the virtual `fusion` model and the router fans your prompt out to a panel of diverse free models in parallel, then a judge model synthesizes one answer from the drafts. [Details →](docs/api.md#fusion-multi-model-synthesis)
+- **Fusion (multi-model synthesis)** — request the virtual `fusion` model and the router fans your prompt out to a panel of diverse free models in parallel, then a judge model synthesizes one answer from the drafts. [Details →](docs/api/01-rest-api.md#fusion-multi-model-synthesis)
- **Image, video & speech generation** — `/v1/images/generations`, `/v1/videos/generations`, and `/v1/audio/speech` route across the providers that serve media models; images and speech also accept custom OpenAI-compatible media endpoints. Video jobs are normalized across synchronous and queued providers and return a completed MP4.
- **Tool calling & structured outputs** — OpenAI-style `tools` round-trip across providers (plain-text tool calls are rescued into real `tool_calls`), plus `response_format`, `seed`, `logprobs`, penalties, and the rest of the sampling params passed through per provider.
- **Smart routing, six strategies** — live per-model speed/capability/reliability scores rank your chain; automatic fallover retries the next model on 429/5xx with cooldowns and key rotation. [Routing in detail →](docs/architecture.md#routing-in-detail)
- **Unified models & profiles** — the same model on several providers collapses into one entry with strict in-group failover; named fallback-chain profiles (a coding chain, a vision chain) switch from the dashboard or per request via `auto:<profile>`.
- **Per-key rate tracking** — RPM/RPD/TPM/TPD counters per `(platform, model, key)` that learn providers' reported ceilings, so routing always stays under every cap.
- **Self-updating model catalog** — the router syncs a signed catalog from freellmapi.co twice a day: new models, quota changes, and provider quirk fixes land automatically. Free installs track the monthly snapshot, which each model joins 30 days after it lands in the live feed; premium routers get it same-day. [Premium →](#premium-live-catalog)
-- **Sticky sessions & context handoff** — conversations stay on one model for 30 minutes; an optional compact handoff note keeps the thread coherent when a mid-chat switch does happen. [Details →](docs/clients.md#context-handoff)
-- **Prompt compression (opt-in)** — a shared, fail-open request pipeline can deduplicate prompts, filter tool output, compact repeated JSON, and trim stale context before cache lookup and routing. [Details →](docs/compression.md)
+- **Sticky sessions & context handoff** — conversations stay on one model for 30 minutes; an optional compact handoff note keeps the thread coherent when a mid-chat switch does happen. [Details →](docs/clients/01-agent-clients.md#context-handoff)
+- **Prompt compression (opt-in)** — a shared, fail-open request pipeline can deduplicate prompts, filter tool output, compact repeated JSON, and trim stale context before cache lookup and routing. [Details →](docs/compression/01-compression-pipeline.md)
- **Encrypted keys, one token out** — provider keys are AES-256-GCM encrypted in SQLite and decrypted in-memory per request; your apps only ever see a single unified `freellmapi-…` bearer token.
- **Admin dashboard & analytics** — React UI to manage keys, reorder the chain, run a playground, and read p50/p95/TTFT analytics over 24h–90d windows; login-gated, dark/light themes, [60 languages](#languages).
-- **MCP server & interactive docs** — agents can introspect usable models, provider health, and routing strategy over `/mcp`; a dependency-free OpenAPI viewer lives at `/v1/docs`. [Coding agents →](docs/clients.md)
+- **MCP server & interactive docs** — agents can introspect usable models, provider health, and routing strategy over `/mcp`; a dependency-free OpenAPI viewer lives at `/v1/docs`. [Coding agents →](docs/clients/01-agent-clients.md)
- **Ops niceties** — opt-in response cache, encrypted DB backups, periodic key health checks, bulk key import/export, declarative startup config. [Install & deploy →](docs/install.md)
- **Runs anywhere Node 20+ runs** — Windows, macOS, Linux servers, or a small ARM SBC (Raspberry Pi included). ~40 MB RSS at idle behind PM2 / systemd / whatever supervisor you prefer.
@@ -197,7 +197,7 @@ A native menu-bar app lives in [`desktop/`](./desktop): the entire router + dash
## Works with OpenAI-compatible clients
-Anything that can target an OpenAI-compatible base URL works: set it to `http://localhost:3001/v1` with the unified key from the dashboard. **Claude Code**, **Codex CLI**, **Cline / Roo Code**, **Continue** (including inline autocomplete), **Aider**, **opencode**, and **Cursor** each have a short recipe in **[docs/clients.md](docs/clients.md)** — and the router doubles as an MCP server your agents can introspect mid-session.
+Anything that can target an OpenAI-compatible base URL works: set it to `http://localhost:3001/v1` with the unified key from the dashboard. **Claude Code**, **Codex CLI**, **Cline / Roo Code**, **Continue** (including inline autocomplete), **Aider**, **opencode**, and **Cursor** each have a short recipe in **[docs/clients/01-agent-clients.md](docs/clients/01-agent-clients.md)** — and the router doubles as an MCP server your agents can introspect mid-session.
The fastest setup is generated from the models available on your live server:
@@ -303,7 +303,7 @@ print(resp.choices[0].message.content)
print("Routed via:", resp.headers.get("x-routed-via"))
```
-Streaming, the `auto:*` routing strategies, tool calling, vision input, Gemini Google Search grounding, embeddings, and the Anthropic Messages surface — with curl and Python examples for each — are all in **[docs/api.md](docs/api.md)**. Every response carries an `X-Routed-Via: <platform>/<model>` header so you can see which provider actually served it.
+Streaming, the `auto:*` routing strategies, tool calling, vision input, Gemini Google Search grounding, embeddings, and the Anthropic Messages surface — with curl and Python examples for each — are all in **[docs/api/01-rest-api.md](docs/api/01-rest-api.md)**. Every response carries an `X-Routed-Via: <platform>/<model>` header so you can see which provider actually served it.
## Screenshots
@@ -476,6 +476,7 @@ Contributors very welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for the dev lo
<a href="https://github.com/oppih"><img src="https://images.weserv.nl/?url=github.com/oppih.png&w=40&h=40&fit=cover&mask=circle" width="40" alt="@oppih" /></a>
<a href="https://github.com/n3dhir"><img src="https://images.weserv.nl/?url=github.com/n3dhir.png&w=40&h=40&fit=cover&mask=circle" width="40" alt="@n3dhir" /></a>
<a href="https://github.com/ksp2000"><img src="https://images.weserv.nl/?url=github.com/ksp2000.png&w=40&h=40&fit=cover&mask=circle" width="40" alt="@ksp2000" /></a>
+<a href="https://github.com/quabynahdavis"><img src="https://images.weserv.nl/?url=github.com/quabynahdavis.png&w=40&h=40&fit=cover&mask=circle" width="40" alt="@quabynahdavis" /></a>
## Disclaimer
diff --git a/cli/README.md b/cli/README.md
index b98e4c55..eaea3729 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -62,7 +62,7 @@ Node.js >= 20.18. A running FreeLLMAPI gateway
## Links
-- [Clients & coding agents guide](https://github.com/tashfeenahmed/freellmapi/blob/main/docs/clients.md)
+- [Clients & coding agents guide](https://github.com/tashfeenahmed/freellmapi/blob/main/docs/clients/01-agent-clients.md)
- [Issue tracker](https://github.com/tashfeenahmed/freellmapi/issues)
MIT © Tashfeen Ahmed
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
new file mode 100644
index 00000000..ffe962d2
--- /dev/null
+++ b/docs/CHANGELOG.md
@@ -0,0 +1,66 @@
+# Changelog
+
+Revision history for `docs/`, derived from git commits touching this directory. Most recent first.
+
+## 2026-08-25
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `60d03d6` | 2026-08-25 | docs(api): document video platforms (pollinations/huggingface, 5-min bound, fal queue), free-tier budget API (`GET /api/free-tier`, pool-deduped), and backups API (`GET /api/backups`, DUMP_FORMAT=1, sha256 fingerprint) |
+| `b7482d4` | 2026-08-25 | docs(fallback): add named-chains domain — chain lifecycle, empty-chain authoritative 400 (`activeChainOrThrow`, e852ff1), `auto:<name>` in `GET /v1/models` (cc1e985), `profiles.auto_include_new_models` (b3bf20f), named-chain manager UI (8bb2004) |
+| `5a77e44` | 2026-08-25 | docs(observability): dedupe 06-observability.md against logs viewer, cross-link both ways, add desktop `freeapi.log` file-logger note (90aaa5b) |
+| `f4135a3` | 2026-08-25 | docs(providers): refresh free-tier numbers to 34 providers / 474 families / 635 endpoints (~7.4B tokens/month) in providers/OVERVIEW.md and providers/01-supported-platforms.md |
+
+## 2026-08-23
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `0e515ac` | 2026-08-23 | docs(meta): fix broken links from 2026-08-23 doc updates — 24 links fixed across 16 files (api/compression/clients/i18nzh) |
+| `1a0ce48` | 2026-08-23 | feat(cli): setup-dsh — configure DeepSeek Harness in one command (#995) |
+| `cf0c216` | 2026-08-23 | perf(compression): early-exit protected-span check in the per-line hot path (#990) |
+| `74df985` | 2026-08-23 | Server log viewer in the dashboard, under an Analytics nav menu (#993) |
+| `96b6f75` | 2026-08-22 | docs(meta): index providers/testing domains and log today's additions |
+| `676ae20` | 2026-08-22 | docs(testing): add test matrix and compatibility-suite documentation |
+| `b21ec10` | 2026-08-22 | docs(providers): add platform catalog and integration guides |
+| `abe6b00` | 2026-08-22 | docs(deployment): add Docker operations and maintenance domain |
+| `ac0a9ce` | 2026-08-22 | docs(env): add runtime configuration reference domain |
+
+## 2026-08-22
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `676ae20` | 2026-08-22 | docs(testing): add test matrix and compatibility-suite documentation |
+| `b21ec10` | 2026-08-22 | docs(providers): add platform catalog and integration guides |
+| `abe6b00` | 2026-08-22 | docs(deployment): add Docker operations and maintenance domain |
+| `ac0a9ce` | 2026-08-22 | docs(env): add runtime configuration reference domain |
+
+## 2026-08-10 and earlier
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `8cb75ac` | 2026-08-10 | feat(proxy): opt-in X-Fallback-Detail header with per-hop failover timings (#792) |
+| `35af82c` | 2026-08-10 | fix(anthropic): stop silently dropping document content blocks (#793) |
+| `c7a71a2` | 2026-08-03 | fix(i18n): polish zh-CN strings (#740) |
+| `5d51fec` | 2026-08-03 | docs(docker): explain why a container cannot reach providers the host can (#737) |
+| `72658ad` | 2026-08-03 | fix(headers,clipboard): serve dashboard cleanly over plain HTTP (#735) |
+| `93afdca` | 2026-08-01 | docs(i18n): give the zh README a 贡献者 heading (#701) |
+| `76c3e6b` | 2026-07-31 | docs: center language toggle above hero screenshot (#691) |
+| `3ea33cb` | 2026-07-31 | docs(i18n): translate install.md and api.md into zh-CN (#690) |
+| `41527f2` | 2026-07-31 | docs(i18n): add translated-docs tree + zh-CN README (#689) |
+| `c8be5a6` | 2026-07-31 | docs(i18n): pin zh glossary, land two agreed zh-CN fixes (#683) |
+| `36eea7b` | 2026-07-30 | cli: publish freellmapi to npm (#672) |
+| `e0befba` | 2026-07-29 | feat(custom): per-endpoint identity for relay models (#659) |
+| `d695bbc` | 2026-07-28 | fix(server): make X-Routed-Via header-safe (#639) |
+| `19168ac` | 2026-07-27 | Add end-to-end coding-agent compatibility suite (#629) |
+| `878fb89` | 2026-07-27 | Add prompt and context compression pipeline (#628) |
+| `90d291d` | 2026-07-27 | Split README into focused docs pages (#627) |
+| `099fcd5` | 2026-07-20 | Termux support, docs index, health-check error surfacing (#573) |
+| `03da4bb` | 2026-06-20 | ci(desktop): Windows .exe + macOS .dmg installers; Windows install path (#349) |
+| `076fa69` | 2026-06-10 | feat: Premium live catalog — signed sync, license keys, self-serve billing |
+| `9c2fa1b` | 2026-06-07 | feat(catalog): V24 Zen roster refresh |
+| `2127a42` | 2026-06-07 | feat(catalog): V23 free-tier audit |
+| `dd5b015` | 2026-05-31 | docs(site): landing page update to 16 providers (~1.7B tokens) (#150) |
+| `8257eff` | 2026-05-02 | fix(catalog): 400 on explicit unknown/disabled model + sync docs (#24) |
+| `b5f8f4d` | 2026-05-02 | docs: Open Graph + Twitter Card meta + OG image (#21) |
+
+Regenerate with `git log --oneline -- docs/`.
diff --git a/docs/OVERVIEW.md b/docs/OVERVIEW.md
new file mode 100644
index 00000000..87c77fd7
--- /dev/null
+++ b/docs/OVERVIEW.md
@@ -0,0 +1,34 @@
+# Docs directory overview
+
+## Scope
+
+This file is the domain index for `docs/` — a complete file map of every guide and domain folder (install, API, clients, compression, architecture deep-dives, env, deployment, providers, testing, fallback, logs, i18n). It lists where each document lives and how the domain folders relate.
+
+For getting started as a user, see [README.md](README.md) (the user entry point); for the product overview, see the root [README](../README.md).
+
+## File index
+
+| File | Description |
+| --- | --- |
+| [README.md](README.md) | Documentation index: links every guide plus related docs elsewhere in the repo. |
+| [install.md](install.md) | Install & deploy: one-liner quick start, Docker Compose, local development, declarative startup config, the Docker image, desktop app, and data locations. |
+| [api/01-rest-api.md](api/01-rest-api.md) | API reference: chat completions, `auto:*` routing strategies, streaming, tool calling, vision, embeddings, response headers, and the Anthropic Messages surface. |
+| [clients/01-agent-clients.md](clients/01-agent-clients.md) | Clients & coding agents: OpenAI-compatible clients, setup recipes for Claude Code / Codex CLI / Cline / Continue / Aider / opencode / Cursor, MCP server, autocomplete, Context Handoff. |
+| [compression/01-compression-pipeline.md](compression/01-compression-pipeline.md) | Prompt compression: request-side modes, safeguards, per-request controls, custom tool-output filters, statistics, and preview APIs. |
+| [architecture.md](architecture.md) | Architecture & internals (high-level index): how the router works, routing and operational details, what is not supported, limitations, and the provider Terms-of-Service review. |
+| [architecture/](architecture/OVERVIEW.md) | Architecture deep-dives: bandit routing & scoring, quota & cooldown engine, streaming pipeline, degraded mode & failover, catalog sync, observability; see its own [OVERVIEW.md](architecture/OVERVIEW.md). |
+| [i18n/01-translating.md](i18n/01-translating.md) | Translating: rules for locale files, the validator, and the settled zh-CN terminology table. |
+| [index.html](index.html) | Static website asset (not a doc): redirect page to freellmapi.co. |
+| [success.html](success.html) | Static website asset (not a doc): post-install success page. |
+| [install.sh](install.sh) | Unix Docker bootstrap script served by the project website. |
+| [install.ps1](install.ps1) | PowerShell bootstrap script served by the project website. |
+| [env/](env/OVERVIEW.md) | Runtime configuration: full `.env` variable reference, encryption-key lifecycle, and outbound-proxy configuration; see its own [OVERVIEW.md](env/OVERVIEW.md). |
+| [deployment/](deployment/OVERVIEW.md) | Docker operations: image & Compose reference, container networking gotchas, upgrades, backups, declarative config; see its own [OVERVIEW.md](deployment/OVERVIEW.md). |
+| [providers/](providers/OVERVIEW.md) | Provider integrations: supported-platform catalog with auth models and adapter classes, per-key quota accounting and cooldowns, and a contributor walkthrough for adding a provider; see its own [OVERVIEW.md](providers/OVERVIEW.md). |
+| [testing/](testing/OVERVIEW.md) | Testing: local test command matrix and CI summary, server-suite layout and conventions, and the e2e coding-agent compatibility suite; see its own [OVERVIEW.md](testing/OVERVIEW.md). |
+| [i18n/](i18n/OVERVIEW.md) | Translated documentation tree (zh-CN); see its own [OVERVIEW.md](i18n/OVERVIEW.md). |
+| [install/](install/OVERVIEW.md) | Platform-specific installation guides; see its own [OVERVIEW.md](install/OVERVIEW.md). |
+| [logs/](logs/OVERVIEW.md) | Server logs viewer: live dashboard panel, two-tier store, polling API, and configuration; see its own [OVERVIEW.md](logs/OVERVIEW.md). |
+| [fallback/](fallback/OVERVIEW.md) | Named fallback chains: chain lifecycle, empty-chain authoritative 400, `auto:<name>` discovery, catalog-sync backfill (`auto_include_new_models`); see its own [OVERVIEW.md](fallback/OVERVIEW.md). |
+
+> `index.html` and `success.html` are static website assets shipped with the docs directory, not markdown documentation.
diff --git a/docs/README.md b/docs/README.md
index 0078b8c4..15fa0a82 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -2,20 +2,21 @@
# FreeLLMAPI documentation
-The root [README](../README.md) is the product overview; the detailed guides live here.
+This is the user entry point — start here to install the gateway, call the OpenAI-compatible API, connect coding agents and understand the high-level architecture. The root [README](../README.md) is the product overview; this index gets you running.
## Guides
- **[Install & deploy](install.md)** — quick start, Docker Compose, local development, declarative startup config, the Docker image, backups, the desktop app, where your data lives, and an FAQ on password resets, logs and uninstalling.
-- **[API reference](api.md)** — chat completions, `auto:*` routing strategies, streaming, tool calling, vision, Gemini Google Search grounding, embeddings, response headers, and the Anthropic Messages surface.
-- **[Clients & coding agents](clients.md)** — OpenAI-compatible clients, recipes for Claude Code / Codex CLI / Cline / Continue / Aider / opencode / Cursor, the MCP server, editor autocomplete, and Context Handoff.
-- **[Prompt compression](compression.md)** — request-side modes, safeguards, per-request controls, custom tool-output filters, statistics, and preview APIs.
+- **[API reference](api/01-rest-api.md)** — chat completions, `auto:*` routing strategies, streaming, tool calling, vision, Gemini Google Search grounding, embeddings, response headers, and the Anthropic Messages surface.
+- **[Clients & coding agents](clients/01-agent-clients.md)** — OpenAI-compatible clients, recipes for Claude Code / Codex CLI / Cline / Continue / Aider / opencode / Cursor, the MCP server, editor autocomplete, and Context Handoff.
+- **[Prompt compression](compression/01-compression-pipeline.md)** — request-side modes, safeguards, per-request controls, custom tool-output filters, statistics, and preview APIs.
- **[Fetch Relay](fetch-relay.md)** — route provider HTTP requests through a user-controlled, streaming application-layer relay.
- **[Architecture & internals](architecture.md)** — how the router works, routing and operational details, what's not supported, honest limitations, and the provider Terms-of-Service review.
## More
- [Android with Termux](install/android-termux.md) — experimental local installation using Node's built-in SQLite driver.
+- [Fallback chains](fallback/01-named-chains.md) — named fallback-chain lifecycle, empty-chain authoritative 400, `auto:<name>` routing, and catalog-sync backfill.
- [Docker deployment](../docker/README.md) — container configuration and persistent storage.
- [Desktop app](../desktop/README.md) — build and package the Electron application.
- [Contributor guide](../CONTRIBUTING.md) — development loop, testing expectations, and contribution policy.
diff --git a/docs/api.md b/docs/api/01-rest-api.md
similarity index 78%
rename from docs/api.md
rename to docs/api/01-rest-api.md
index 54628c8b..947c0b5a 100644
--- a/docs/api.md
+++ b/docs/api/01-rest-api.md
@@ -1,8 +1,8 @@
-**English** · [简体中文](i18n/zh-CN/docs/api.md)
+**English** · [简体中文](../i18n/zh-CN/docs/api/01-rest-api.md)
# API reference
-[← Back to README](../README.md) · [Documentation index](README.md)
+[← Back to README](../README.md) · [Documentation index](../README.md)
Any OpenAI-compatible client works (Anthropic / Claude clients too — see [Anthropic / Claude clients](#anthropic--claude-clients)). Base URL `http://localhost:3001/v1`, unified key from the dashboard's Keys page. An interactive OpenAPI viewer covering every proxy endpoint is served at `GET /v1/docs`; the spec itself lives at `GET /v1/openapi.json`.
@@ -21,6 +21,8 @@ Any OpenAI-compatible client works (Anthropic / Claude clients too — see [Anth
- [Response headers](#response-headers)
- [Embeddings](#embeddings)
- [Anthropic / Claude clients](#anthropic--claude-clients)
+- [Free-tier budget API](#free-tier-budget-api)
+- [Backups API](#backups-api)
## Chat completions
@@ -243,7 +245,9 @@ Anthropic's `document` content blocks are accepted on `/v1/messages` when their
`POST /v1/images/generations`, `POST /v1/videos/generations`, and `POST /v1/audio/speech` route across the providers that serve media models. Images and speech also accept custom OpenAI-compatible media endpoints; video does not. Browse and toggle them on the dashboard's **Models → Image / Video / Audio** tabs.
-Video generation accepts a JSON body with `prompt`, optional `model` (`auto` by default), and provider-dependent `duration`, `aspect_ratio`, `image`, `seed`, and `audio` options. It waits for queued providers to finish and returns the generated video as binary MP4 data:
+Video generation is served by two platforms — **`pollinations`** and **`huggingface`** (`VIDEO_PLATFORMS`). It accepts a JSON body with `prompt`, optional `model` (`auto` by default), and provider-dependent `duration`, `aspect_ratio`, `image`, `seed`, and `audio` options. A video job runs for minutes, so the whole surface is **bounded to a 5-minute timeout** (`VIDEO_FETCH_TIMEOUT_MS`); if the provider hasn't finished by then the request returns `504`. A client that hangs up mid-generation is detected via the socket `close` event, which aborts the work so the gateway does not keep polling (and fail over to a second provider) for a response nobody is waiting for.
+
+HuggingFace models route through the **fal queue** (`router.huggingface.co/fal-ai/…`): the request is submitted as a queued job, polled every 500 ms until `COMPLETED`, and the resulting video URL is fetched and streamed back. Pollinations models are requested directly. Both return the generated video as binary MP4 data with `X-Provider` and `X-Model` response headers:
```bash
curl http://localhost:3001/v1/videos/generations \
@@ -282,7 +286,7 @@ HTTP headers only carry printable ASCII, so a model id with characters outside t
The opt-in response cache can be toggled per request with `X-FreeLLM-Cache: on|off` — an exact-match in-memory LRU for identical non-streaming requests (canonical SHA-256 keys over the full request, TTL and temperature gates, saved-token stats on the dashboard). Off by default; cache hits consume zero provider quota.
-When [prompt compression](compression.md) is enabled, `X-FreeLLM-Compress: off|on|lossless|standard|aggressive` can disable or lower the configured mode for one request. It cannot raise the operator's configured mode. The response reports the effective mode and estimated savings, for example `X-FreeLLM-Compress: standard; saved~=1840`.
+When [prompt compression](../compression/01-compression-pipeline.md) is enabled, `X-FreeLLM-Compress: off|on|lossless|standard|aggressive` can disable or lower the configured mode for one request. It cannot raise the operator's configured mode. The response reports the effective mode and estimated savings, for example `X-FreeLLM-Compress: standard; saved~=1840`.
## Embeddings
@@ -355,3 +359,70 @@ claude
```
> Use `ANTHROPIC_AUTH_TOKEN` (sent as a Bearer token), **not** `ANTHROPIC_API_KEY` — Claude Code treats a set `ANTHROPIC_API_KEY` as a conflicting first-party credential and refuses to start.
+
+## Free-tier budget API
+
+`GET /api/free-tier` returns the operator's free-tier budget as a **pool-deduped** monthly overview. Many models on one platform share the same free pool, so summing every model's label would double-count; the endpoint collapses models into quota pools (`inferQuotaPoolKey`) and reports **one documented budget per pool** (the largest `parseBudget` value seen in it), scaled by the number of usable (enabled + healthy/unknown) keys for the platform. Chain-disabled rows still contribute to a pool — they share the same provider allowance — and are only marked, never dropped, so the totals match the dashboard's stacked per-model bar.
+
+```json
+{
+ "generatedAt": "2026-08-25T12:00:00.000Z",
+ "summary": {
+ "poolCount": 18,
+ "documentedMonthlyTokens": 7400000000,
+ "creditsBasedPools": 2,
+ "unpublishedPools": 3
+ },
+ "pools": [
+ {
+ "poolKey": "google",
+ "platform": "google",
+ "memberModelIds": ["gemini-3.0-flash", "gemini-2.5-flash"],
+ "modelCount": 2,
+ "disabledModelCount": 0,
+ "keyCount": 1,
+ "documentedBudget": 120000000,
+ "bestLabel": "~120M",
+ "kind": "documented",
+ "quota": { "limit": 150000000, "remaining": 98000000, "resetAt": "2026-08-26T00:00:00.000Z", "metric": "tokens", "keyCount": 1 }
+ }
+ ]
+}
+```
+
+- `kind` ∈ `documented` (a parseable monthly budget), `credits` (credit-based), or `unpublished` (no public figure).
+- `quota` carries live observations (limit / remaining / reset / metric) when the provider reports them; `metric` prefers `tokens` → `credits` → `neurons` → `requests`.
+- Mounted behind the dashboard session (`requireAuth`); not the unified `/v1` key.
+
+## Backups API
+
+`GET /api/backups` lists the encrypted database snapshots the gateway has taken (scheduled or manual via `POST /api/backups`). Each backup is an SQL dump with a header carrying its **sha256 key fingerprint** — `restore` refuses a dump written under a different `ENCRYPTION_KEY` (reports `backup: <fingerprint>; server: <fingerprint>`). The on-disk layout is versioned with `DUMP_FORMAT = 1`; a dump of a different format is rejected with `409`.
+
+```json
+{
+ "items": [
+ {
+ "id": 14,
+ "filename": "freellmapi-20260825-040000-enc.sql",
+ "filesize": 2418688,
+ "isFull": true,
+ "source": "scheduled",
+ "createdAt": "2026-08-25T04:00:00.000Z",
+ "tables": ["api_keys", "models", "fallback_config", "settings", "..."]
+ }
+ ],
+ "total": 14
+}
+```
+
+Endpoints (all behind `requireAuth`):
+
+| Method | Path | Purpose |
+| --- | --- | --- |
+| `GET` | `/api/backups` | Paginated listing (`?page=&pageSize=`, max 200) |
+| `POST` | `/api/backups` | Create now; optional `tables` whitelist (≤ 500 names) |
+| `GET` | `/api/backups/:id/download` | Download the encrypted dump |
+| `POST` | `/api/backups/:id/restore` | Restore into the live DB (refuses mismatched key / format) |
+| `DELETE` | `/api/backups/:id` | Delete one backup |
+| `GET` | `/api/backups/tables` | Tables a dump may contain |
+| `GET` / `PUT` | `/api/backups/schedule` | Read / write the backup schedule (HH:mm, interval days, path) |
diff --git a/docs/api/CHANGELOG.md b/docs/api/CHANGELOG.md
new file mode 100644
index 00000000..124c35ad
--- /dev/null
+++ b/docs/api/CHANGELOG.md
@@ -0,0 +1,19 @@
+# API Domain — Changelog
+
+Doc revision history for `docs/api/`, seeded from API-relevant commits.
+
+## 2026-08-25
+
+- **docs(api): document video platforms, free-tier budget, and backups APIs** — expanded `POST /v1/videos/generations` with the bounded pollinations/huggingface surface (5-minute timeout, fal queue); added `GET /api/free-tier` (pool-deduped monthly budget) and `GET /api/backups` (DUMP_FORMAT=1, sha256 key fingerprint) endpoint reference.
+
+## 2026-08-23 — Docs reorganization
+
+- **e8dde9e** `docs(api): fold API guide into api domain` — moved `docs/api.md` → `docs/api/01-rest-api.md` with `OVERVIEW.md` + `CHANGELOG.md` scaffold.
+
+## 2026-08-10 and earlier
+
+- **8cb75ac** feat(proxy): opt-in X-Fallback-Detail header with per-hop failover timings (#792)
+- **878fb89** Add prompt and context compression pipeline (#628)
+- **90d291d** Split README into focused docs pages (#627)
+
+> Older history for this content is available via `git log --follow -- docs/api.md`.
diff --git a/docs/api/OVERVIEW.md b/docs/api/OVERVIEW.md
new file mode 100644
index 00000000..619e667e
--- /dev/null
+++ b/docs/api/OVERVIEW.md
@@ -0,0 +1,21 @@
+# API Domain — Overview & File Index
+
+This domain documents FreeLLMAPI's OpenAI-compatible HTTP surface and its Anthropic/Gemini-compatible shims. The root [`README.md`](../README.md) and [`OVERVIEW.md`](../OVERVIEW.md) index this as the gateway's external contract.
+
+## File Index
+
+| File | Scope |
+|------|-------|
+| [`01-rest-api.md`](01-rest-api.md) | OpenAI-compatible endpoints (`/v1/chat/completions`, `/v1/responses`, `/v1/embeddings`, `/v1/models`, streaming, tool calling, vision, video, Gemini grounding, response headers), the Anthropic Messages surface (`/v1/messages`), the pool-deduped free-tier budget API (`/api/free-tier`), and the encrypted backups API (`/api/backups`). |
+| [`CHANGELOG.md`](CHANGELOG.md) | Doc revision history for this domain, seeded from API-relevant commits. |
+
+## Navigation
+
+- ← [Documentation root](../README.md)
+- API reference: [`01-rest-api.md`](01-rest-api.md)
+
+## Related
+
+- [../clients/](../clients/) — Coding-agent integration recipes that consume this API.
+- [../compression/](../compression/) — Request-side compression (`X-FreeLLM-Compress`) visible on API responses.
+- [../architecture/](../architecture/) — Router, scoring, and streaming internals behind these endpoints.
diff --git a/docs/architecture.md b/docs/architecture.md
index a0a69a88..ac3890e0 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -1,12 +1,14 @@
# Architecture & internals
-[← Back to README](../README.md) · [Documentation index](README.md)
+[← Back to README](../README.md) · [Documentation index](README.md) · [Deep-dive domain](architecture/OVERVIEW.md)
-How the router decides, what to expect from stacked free tiers, and where the boundaries are.
+FreeLLMAPI is a self-hosted OpenAI-compatible gateway that stacks the free tiers of ~34 providers behind a single `freellmapi-…` bearer token. An Express proxy exposes `/v1/chat/completions` (plus `/v1/responses`, `/v1/messages`, `/v1/completions`, `/v1/embeddings` and `/v1/models`) and, per request, the router selects the best healthy model that is under all of its rate limits, decrypts its upstream key in memory, and streams the response back.
+
+Because no single free tier is generous enough to live on, the router treats the catalog as a pooled fallback chain: it scores live reliability, speed, capability and headroom via a Thompson-sampling bandit, enforces RPM/RPD/TPM/TPD and provider-wide caps with a persistent ledger, and fails over across up to 20 attempts within a wall-clock budget. When the top of the chain exhausts its daily caps the endpoint gracefully degrades to the next healthy tier and resets at UTC midnight.
+
+See [OVERVIEW.md](architecture/OVERVIEW.md) for deep-dives.
- [How it works](#how-it-works)
-- [Routing in detail](#routing-in-detail)
-- [Operational details](#operational-details)
- [Not yet supported](#not-yet-supported)
- [Limitations](#limitations)
- [Terms of Service review](#terms-of-service-review)
@@ -42,28 +44,10 @@ How the router decides, what to expect from stacked free tiers, and where the bo
- **Health service** (`server/src/services/health.ts`) — periodic probe keeps key status fresh.
- **Dashboard** (`client/`) — React + Vite + shadcn/ui admin surface.
- **Storage** — SQLite (`better-sqlite3`) with AES-256-GCM envelope encryption for keys.
-
-## Routing in detail
-
-- **Automatic fallover** — If the chosen provider returns a 429, 5xx, or times out, the router skips it, puts the key on a short cooldown, and retries on the next model in your fallback chain (up to 20 attempts, bounded by a wall-clock retry budget). A dead key rotates to its siblings instead of failing the request, and exhaustion errors carry the full attempt trail so you can see exactly what was tried.
-- **Smart routing, six strategies** — the chain is ranked by a selectable strategy: `priority` (your manual order), `balanced`, `smartest`, `fastest`, `reliable`, or `custom` with your own weight mix. Scores come from live per-model measurements (speed, capability, rate-limit headroom, recent errors) with a Thompson-sampling bandit under the hood; one-click sort presets reorder the chain from the dashboard.
-- **Unified models** — the same logical model served by several providers (say, GLM-4.7 on Cloudflare and Z.ai) collapses into one entry: one name in `/v1/models`, strict in-group failover between its providers, and merge/split overrides when the grouping guesses wrong.
-- **Model profiles** — save named fallback-chain configurations (a coding chain, a long-context chain, a vision chain) and switch the active one from the dashboard.
-- **Per-key rate tracking** — RPM, RPD, TPM, and TPD counters per `(platform, model, key)` so the router always picks a key that's under its caps. The ledger also learns: ceilings a provider reports in error bodies or quota headers (a Groq 413 naming its TPM limit) tighten the router's own limits automatically.
-- **Sticky sessions** — Multi-turn conversations keep talking to the same model for 30 minutes to avoid the hallucination spike that comes from mid-conversation model switches. See also [Context Handoff](clients.md#context-handoff) for what happens when a switch is unavoidable.
-- **Structured outputs & full sampling passthrough** — `response_format` (`json_object` / `json_schema`, translated to Gemini's native `responseSchema`), plus `seed`, `top_k`, `min_p`, presence/frequency/repetition penalties, `logit_bias`, `logprobs`, and the `max_completion_tokens` alias. Params a provider is known to reject are dropped per platform (Mistral's strict API, Groq's logprobs family…), and every model advertises its honest list in `/v1/models` `supported_parameters`.
-- **Tool-call rescue** — models that emit tool calls as plain text instead of structured JSON are rescued into real `tool_calls` automatically, and tool requests only route to models that actually support them.
-
-## Operational details
-
-- **Encrypted key storage** — API keys are encrypted with AES-256-GCM before hitting SQLite; decryption happens in-memory just before a request.
-- **Unified API key** — Clients authenticate to your proxy with a single `freellmapi-…` bearer token. You never expose upstream provider keys to your apps.
-- **Dashboard login** — The admin UI and all `/api/*` routes are gated behind an email + password account (scrypt-hashed, session-token auth), set on first run. The `/v1` proxy keeps its own unified-key auth for apps.
-- **Health checks** — Periodic probes mark keys as `healthy`, `rate_limited`, `invalid`, or `error` so the router skips dead ones automatically.
-- **Response cache (opt-in)** — an exact-match in-memory LRU for identical non-streaming requests: canonical SHA-256 keys over the full request, TTL and temperature gates, per-request `X-FreeLLM-Cache: on|off` override, and saved-token stats on the dashboard. Off by default; cache hits consume zero provider quota.
+- **Tool-call rescue** (`server/src/lib/tool-call-rescue.ts`) — models that emit tool calls as plain text instead of structured JSON are rescued into real `tool_calls` automatically, and tool requests only route to models that actually support them.
- **Key import & export** — bulk-import keys by pasting a `.env` file (with preview and per-key selection), export back out as JSON, `.env`, or CSV.
-- **Analytics** — Per-request logging with latency (p50 / p95 and time-to-first-token for streams), token counts, success rate, estimated cost savings, and per-provider / per-model / per-key breakdowns over 24h to 90d windows.
-- **Encrypted DB backups** — optional periodic encrypted snapshots of the SQLite database to a local path or HTTP target, restored automatically on a fresh boot (see [Install & deploy](install.md#docker-image--operations)).
+
+> Routing strategies, bandit scoring, quota and cooldown accounting, streaming, degraded-mode failover and the provider catalog are covered at implementation depth in the deep-dives — See [OVERVIEW.md](architecture/OVERVIEW.md) for deep-dives.
## Not yet supported
diff --git a/docs/architecture/01-routing-and-bandit-scoring.md b/docs/architecture/01-routing-and-bandit-scoring.md
new file mode 100644
index 00000000..f4941202
--- /dev/null
+++ b/docs/architecture/01-routing-and-bandit-scoring.md
@@ -0,0 +1,308 @@
+# Routing & Bandit Scoring — Deep Dive
+
+> **Source:** `server/src/services/router.ts`, `server/src/services/scoring.ts`
+
+## 1. Overview
+
+The router picks one `(platform, model, key)` tuple per request. It is **not** a round-robin load balancer — it is a contextual bandit that continuously learns from live traffic and composes a score from five normalized axes:
+
+```
+base = w_rel·reliability + w_speed·speed + w_intel·intelligence (convex, weights sum to 1)
+effective = base × headroomFactor × rateLimitFactor (guardrail multipliers ∈ [floor, 1])
+```
+
+The **weights** come from a selectable strategy (`balanced` / `smartest` / `fastest` / `reliable` / `custom` / `priority`). The default is `balanced` (0.5 / 0.25 / 0.25). Operators can switch strategies from the dashboard or via `PUT /api/fallback/routing`.
+
+Key selection within a model is driven by a separate `KeySelectionStrategy` (`auto` / `least-remaining`), independent of the model-ranking bandit so the two concerns don't interfere (#919, #930).
+
+---
+
+## 2. Chain Construction
+
+The enabled fallback chain is sourced from (in priority order):
+
+1. **Active profile** (`profile_models` table) — named chains like "coding", "long-context"
+2. **Global fallback_config** — the legacy single chain
+3. **Global sort alias** — `auto:smart`, `auto:fast`, `auto:cheap`, `auto:reliable`, `auto:balanced`
+4. **Profile by name** — `auto:my-profile`
+
+Each chain row (`ChainRow`) carries the model's static metadata (`intelligence_rank`, `size_label`, `monthly_token_budget`, rate limits, capabilities) plus the **endpoint scope** (`''` for catalog models, `'custom:<base_url_hash>'` for relay models) so two relays serving the same `model_id` are scored and rate-limited independently.
+
+### Match Tier
+
+`match_tier` (default 0) is an **outer sort key** that dominates score. It is set only when a unified group resolves a slug (e.g. `glm-4.7`) to a provider-specific model (`z-ai/glm-4.5`) — the matched member gets `match_tier = 1` so it never outranks a direct `model_id` request, no matter how good its live numbers are.
+
+---
+
+## 3. Reliability — Thompson Sampling with Beta Posteriors
+
+### Decay-Weighted Samples
+
+Reliability is not a raw success rate. The analytics window is 7 days with a **2-day half-life** exponential decay:
+
+```
+weight(age_days) = 0.5^(age_days / 2)
+```
+
+Each request bucket (grouped by `platform, model_id, key_id, age_days`) contributes decay-weighted pseudo-counts to `successes` and `failures`. Timeouts count as **failures for reliability** but **contribute to speed** (wall-clock latency, zero tokens).
+
+### Posterior & Sampling
+
+```
+α = successes + community_successes + 1 (Beta(1,1) uniform prior)
+β = failures + community_failures + 1
+```
+
+- **Routing (live)**: `reliability = sampleBeta(α, β)` — Thompson sampling. Exploration is automatic and proportional to uncertainty.
+- **Dashboard (display)**: `reliability = α / (α + β)` — expected value, stable for sorting.
+
+### Community Prior (opt-in)
+
+When `routing_community_prior_enabled = 1`, de-poisoned aggregated counts from other self-hosted instances are folded into the posterior as a starting balance. Each prior is capped at **50 effective samples** so local evidence (decay-weighted, ~hundreds of samples on a busy install) always dominates within a few hundred requests.
+
+### Exploration Floor (10%)
+
+When `routing_explore_enabled = 1` (off by default), an unmeasured model (decay-weighted `successes + failures < 5`) gets a **guaranteed 10% chance** to be tried first, preventing starvation by prior-heavy rivals. The bandit's Thompson sampling already explores; this is a hard floor.
+
+---
+
+## 4. Speed Axis — Throughput + TTFB Blended
+
+```
+throughputScore(tok/s) = 1 - exp(-tok/s / 60) # saturating, 60 tok/s ≈ 0.63
+ttfbScore(ms) = linear ramp 300ms→1.0 … 5000ms→0.0
+speedScore = 0.6·throughput + 0.4·ttfb # when both present
+```
+
+- No successful samples → returns `SPEED_PRIOR = 0.6` (optimistic, so unmeasured models get explored on speed too).
+- Throughput-only (no TTFB) → throughput alone.
+- TTFB-only (no throughput) → TTFB alone.
+
+**Timeouts feed speed** (#619): a timeout contributes its capped wall-clock latency (max 120s) to the throughput denominator with **zero output tokens**, and the same latency as a TTFB sample (which lands past `TTFB_WORST_MS`, earning no latency credit). A model that hangs constantly can no longer keep a stellar speed number.
+
+### Observed Speed Rank Writeback
+
+Every 10 minutes, models with ≥20 decay-weighted speed-bearing samples (successes + timeouts) and no user-set `speed_rank` override have their observed speed projected back onto the catalog's 1..10 `speed_rank` scale (1 = fastest). This keeps the dashboard's sort-by-speed preset honest for relay models.
+
+---
+
+## 5. Intelligence Axis — Tier-First, √-Compressed Rank
+
+```
+tierValue: Frontier=4, Large=3, Medium=2, Small=1, unknown=0
+intelligenceComposite = tierValue * 1000 - sqrt(rank) * 31
+```
+
+- **Tier dominates strictly**: worst rank in a tier (√1000·31 ≈ 980) still beats best rank of tier below (1000).
+- **Rank edits are visible**: √ compression makes a change from rank 1→3→10 move the axis noticeably, unlike the old linear rank which was drowned by the tier multiplier.
+- Min-max normalized across the enabled chain to [0,1].
+
+Custom models are seeded at the catalog median tier ("unknown" = no opinion, not "worst").
+
+---
+
+## 6. Guardrails — Multiplicative, Never Reordering Good Models
+
+### Headroom Factor (quota protection)
+
+```
+remaining = 1 - usedTokens / budgetTokens
+if remaining >= rampStart: factor = 1.0
+else: factor = floor + (1 - floor) * (remaining / rampStart)
+```
+
+- `budgetTokens` = `monthly_token_budget` × `usableKeyCount(platform)` — pools N keys' free tiers.
+- Unknown budget (0 or NULL) → factor = 1 (no opinion).
+
+### Tunable Headroom Thresholds (env / settings: `routing_headroom_ramp_start`, `routing_headroom_floor`)
+
+The ramp is now operator-tunable via `GET/PUT /api/settings/headroom` (#989, #899). The thresholds are read **once per chain** instead of per model:
+
+| Setting | Default | Purpose |
+|---------|---------|---------|
+| `rampStart` (`HEADROOM_RAMP_START`) | 0.2 (20% remaining) | Fraction at which demotion begins |
+| `floor` (`HEADROOM_FLOOR`) | 0.1 (10% of score) | Score floor at 0 remaining budget |
+
+Out-of-range / non-finite operator input falls back to the default rather than silently clamping to a legal-but-unintended value. The **same** ramp and thresholds also drive the rate-window headroom guardrail (see #8) — a single pair of operator-tuned thresholds governs both.
+
+### Rate-Limit Factor (live penalty)
+
+```
+penalty ∈ [0, 10] (from 429 escalation ladder, decays 1 per 2 min)
+factor = 1 - (penalty / 10) * 0.6 # at max penalty, keeps 40% of score
+```
+
+- Demotes hard but never excludes — model recovers as penalty decays.
+
+### Rate-Window Headroom Factor (RPD/TPD/RPM/TPM demotion, #899)
+
+The monthly-budget guardrail only has an opinion about models that declare a `monthly_token_budget`. The far more common free-tier shape is a per-day request or token cap (RPD/TPD plus per-minute RPM/TPM), which was previously **binary**: the hard gates reject at 100% and the router happily keeps a model pinned at #1 until the very request that exhausts it, then eats a 429 and falls through.
+
+The fix: the same tunable ramp, driven by **live window utilization** instead of monthly tokens:
+
+```
+usedFraction = consumed / limit (0 = idle, 1 = exhausted) — worst of the four windows
+factor = headroomRamp(1 - usedFraction, opts) — same tunable thresholds
+```
+
+- `usedFraction` is memoized inside `ratelimit.ts` as a **5-second snapshot** (`WINDOW_USAGE_TTL_MS = 5000`) — one grouped scan of `rate_limit_usage` plus one read of `api_keys`, shared by every entry of every chain. The hard gates are unaffected — they still read live counts.
+- `null` means the model declares no window limits, or has no routable key to measure — factor = 1 (no opinion).
+- **Combined headroom**: the router takes `Math.min(monthlyHeadroom, windowHeadroom)` — the **worse** of the two, never their product (which would push a model low on both to floor², below the operator-configured floor).
+
+The chosen key is the **eligible key with the most headroom** (the one the router would pick NEXT), not the worst key — a platform with one exhausted key and one idle key routes perfectly well (#921).
+
+### Peak-Hours Adjustment (opt-in, #760, #909)
+
+During an operator-declared peak window, free relays are congested, so a model's raw throughput is a weaker signal than its reliability: part of the speed weight is moved onto reliability.
+
+| Parameter | Default | Purpose |
+|-----------|---------|---------|
+| `enabled` | `false` | Opt-in by design — routing that silently changes with the wall clock is impossible to reason about |
+| `startHour` / `endHour` | 18 / 6 (spans midnight) | Window in the operator's IANA timezone |
+| `timezone` | `UTC` | IANA name; read via `Intl` (never `Date#getHours`, since the host is frequently UTC while the traffic it serves is not) |
+
+- **Shift amount**: `PEAK_SPEED_TO_RELIABILITY = 0.6` (60% of the speed weight moves onto reliability).
+- **Exempt strategies** (`PEAK_EXEMPT_STRATEGIES`): `fastest` and `reliable` are **exempt** — they are the two ends of the speed↔reliability axis, and an operator who picked one has already decided which end they want. `priority` and `custom` are also never rewritten (the operator's explicit choice).
+- The adjustment applies only to the mixed presets (`balanced`, `smartest`), where trading some speed for reliability stays inside the span the presets already describe.
+- `peakAdjustedWeights()` returns `{ weights, adjusted }` — the dashboard labels the weight summary from the `adjusted` flag.
+- `startHour === endHour` is an **empty** window (not 24-hour) — an operator who drags both ends to the same value means "nothing".
+
+---
+
+## 7. Per-Model Weight Overrides (env: `MODEL_ROUTING_OVERRIDES`)
+
+```
+MODEL_ROUTING_OVERRIDES='{"gpt-4o": {"weight": 0.5}, "llama-3.3-70b": {"weight": 1.5}}'
+```
+
+Scales the **final effective score** (after guardrails) so a slow/poor model is demoted without being disabled. A manual `priority` chain can still select it.
+
+---
+
+## 8. In-Model Key Selection (Bandit per Key)
+
+When a model has multiple keys, keys are ordered by a **per-key Thompson score**:
+
+```
+keyReliability = sampleBeta(α_key + community_α, β_key + community_β)
+keySpeed = speedScore(keyStats.tokPerSec, keyStats.avgTtfbMs)
+keyScore = 0.75·keyReliability + 0.25·keySpeed
+```
+
+Returns `null` (fall back to round-robin) when <2 keys have recorded data. Catches expired/drained/region-blocked keys that the rolled-up model bucket cannot see.
+
+---
+
+## 9. Fallback Loop & Exhaustion Diagnostics
+
+The shared loop (`lib/fallback-loop.ts`) drives every surface (`/v1/chat/completions`, `/v1/responses`, `/v1/messages`, legacy `/completions`):
+
+- **Max 20 retries** (configurable).
+- **Wall-clock retry budget** (default 45s, setting `fallback_time_budget_ms`). Stops starting new attempts after budget; first retry always allowed.
+- **Hedging** (1d2226a): when budget expires mid-attempt, `abortInFlight()` cancels the upstream fetch instead of waiting for a stall.
+- **Circuit breaker**: `max_consecutive_upstream_fails` (default 0 = off) stops the loop with 503 when the pool looks unhealthy.
+- **Per-attempt trail**: `X-Fallback-Trail` header + `X-Fallback-Detail` (opt-in) with timings and redacted error summaries.
+- **Synchronous exhaustion** (zero upstream calls): `RouteError.diagnostics` carries one line per considered model with the reason it could not serve (no key, cooldown, provider cap, rpm/rpd, tpm/tpd, context too small, …). `summarizeExhaustion()` rolls this into a client-safe bucketed message (e.g. "All models exhausted: 5 routes checked (3 rate-limited or on cooldown, 2 no usable key configured). Add more API keys or wait for rate limits to reset. Soonest reset ~2m.").
+
+### Failure Classification & Bookkeeping
+
+| Error | Skip | Cooldown | Model Penalty | Limit Learning |
+|-------|------|----------|---------------|----------------|
+| 401 invalid key | key only | 5 min (health cycle) | no | no |
+| 402 payment required | key only | 24h | no | no |
+| 403 model forbidden | model | 24h | no | no |
+| 429 daily exhausted | model+key | until UTC midnight / Retry-After | heavy (3) | yes |
+| 429 transient (rpm/tpm) | key only | 90s / escalation ladder | light (1) | yes |
+| 5xx / timeout / transport | **platform** (#788) | 90s / ladder | light (1) | no |
+| empty completion (reasoning) | key only | **exempt** (streak ≤3) | no | no |
+| context too large | model | — | no | no |
+| response_format ignored | model | — | no | no |
+
+- **Model-level failure benching** (#806): 3 retryable failures across keys within 15 min → bench model on **all its keys** for 10 min (heuristic, probe-eligible).
+- **Empty-completion streak limit** (#751): 3 consecutive reasoning-truncated completions on same model+key lifts the exemption.
+
+---
+
+## 10. Sticky Sessions
+
+- Key = SHA-1(first user message [:: strategyKey]), TTL 30 min.
+- Prevents mid-conversation model switches → hallucination spike.
+- Session-affine reasoning trace memory (#797): restores `reasoning_content` stripped by clients on replay, scoped to the model that produced it.
+
+---
+
+## 11. Unified Model Groups (Unify)
+
+When enabled, logical models (e.g. `glm-4.7`) collapse multiple providers into one `/v1/models` entry. Routing **strictly fails over within the group** — never to a different model. `match_tier = 1` on slug-resolved members prevents silent substitution.
+
+---
+
+## 12. Strategy Presets
+
+| Strategy | Reliability | Speed | Intelligence |
+|----------|-------------|-------|--------------|
+| balanced | 0.50 | 0.25 | 0.25 |
+| smartest | 0.35 | 0.10 | 0.55 |
+| fastest | 0.35 | 0.55 | 0.10 |
+| reliable | 0.70 | 0.15 | 0.15 |
+| custom | user-tuned (normalized) | | |
+| priority | manual order + 429 penalty (dense rank + penalty) | | |
+
+### Key Selection Strategy (#919, #930)
+
+Independent of the routing strategy on purpose — model ranking and key selection are independent choices, and folding this into the strategy enum would make switching key policy also switch (or disable) the model bandit.
+
+| Strategy | Behavior |
+|----------|----------|
+| `auto` (default) | Per-key bandit score when ≥2 keys have recorded data, else round-robin |
+| `least-remaining` | Additionally rank by observed remaining quota — roomiest key first, so the key nearest its cap is held back instead of being the next to 429 |
+
+- `least-remaining` layers **on top** of the existing order (bandit ranking when there's data, else the round-robin rotation) — ties fall back to that order instead of rowid.
+- Account-scoped pools (`<platform>::account`) are **skipped** for remaining-quota weighting, since every key reports the same shared number and reordering would only churn the rotation (#919).
+- Reads quota headroom through the cached platform-filtered `getKeyQuotaHeadroom()` query.
+- A key the quota tracker has never seen gets a neutral `UNKNOWN_QUOTA_HEADROOM = 0.5` — no opinion, not a reason to prefer or avoid.
+
+---
+
+## 13. Key Functions (router.ts)
+
+| Function | Purpose |
+|----------|---------|
+| `routeRequest(...)` | Main entry: picks route, applies all filters (vision, tools, sticky, group, response_format) |
+| `orderChain(chain, strategy, sampled)` | Orders chain by strategy; `sampled=true` for live routing, `false` for stable dashboard |
+| `scoreChainEntry(...)` | Computes five axes + guardrails → final score |
+| `orderKeysByScore(entry, keys)` | Per-key Thompson ordering |
+| `orderKeysByRemainingQuota(entry, ordered)` | Re-sorts by observed remaining quota (roomiest first) |
+| `quotaWeightingApplies(entry)` | Whether remaining-quota weighting is meaningful for this chain entry |
+| `resolveRoutingChain(modelString)` | Parses `auto`, `auto:smart`, `auto:profile-name` |
+| `getKeySelectionStrategy()` / `setKeySelectionStrategy(s)` | Read/write the `key_selection_strategy` setting |
+| `getHeadroomThresholds()` / `setHeadroomThresholds(rampStart, floor)` | Read/write tunable headroom thresholds |
+| `getPeakHoursConfig()` / `setPeakHoursConfig(patch)` | Read/write peak-hours settings |
+| `getActiveRoutingWeights()` | Active weight vector + whether peak adjustment moved it |
+| `recordRateLimitHit/recordModelFailure/recordSuccess` | Penalty mutations |
+| `summarizeExhaustion(diag, soonestResetMs)` | Client-safe exhaustion message |
+
+---
+
+## 14. Key Functions (scoring.ts)
+
+| Function | Purpose |
+|----------|---------|
+| `reliabilityPosterior(s, f, community?)` | Returns `{alpha, beta}` |
+| `expectedReliability(s, f, community?)` | Deterministic α/(α+β) |
+| `sampleBeta(α, β)` | Marsaglia & Tsang via two Gamma draws |
+| `speedScore(tok/s, ttfbMs)` | Blended [0,1] speed |
+| `intelligenceComposite(sizeLabel, rank)` | Tier-first composite |
+| `intelligenceScore(composite, min, max)` | Min-max normalize |
+| `headroomFactor(used, budget, opts?)` | Quota guardrail multiplier (tunable thresholds) |
+| `rateWindowHeadroomFactor(usedFraction, opts?)` | Live window-utilization guardrail |
+| `rateLimitFactor(penalty)` | Penalty guardrail multiplier |
+| `combineScore(inputs, weights)` | Convex base × guardrails |
+| `peakAdjustedWeights(base, strategy, config, now)` | Peak-hours reweighting + whether it fired |
+| `isPeakHours(config, now)` | Whether `now` falls inside the configured window |
+
+---
+
+## 15. Cache Key v4 (#901)
+
+The exact-match response cache key is now at **version 4**. Default-valued sampling params (`top_p: 1`, `n: 1`, `presence_penalty: 0`, `frequency_penalty: 0`) are normalized down to `undefined` so a client that always serializes the full param set shares a cache entry with one that omits the defaults. `reasoning_effort` and `compression` were also added to the key. Bump version when changing the key shape — `v: 4` is embedded in the canonical JSON.
\ No newline at end of file
diff --git a/docs/architecture/02-quota-and-cooldown-engine.md b/docs/architecture/02-quota-and-cooldown-engine.md
new file mode 100644
index 00000000..476dcb78
--- /dev/null
+++ b/docs/architecture/02-quota-and-cooldown-engine.md
@@ -0,0 +1,278 @@
+# Quota & Cooldown Engine — Deep Dive
+
+> **Source:** `server/src/services/ratelimit.ts`, `server/src/services/cooldown-probe.ts`, `server/src/services/provider-quota.ts`
+
+## 1. Overview
+
+The quota engine is the **gatekeeper** between the router and upstream providers. It tracks four sliding windows per `(platform, model, key)` plus provider-wide pools, persists to SQLite, and learns real limits from provider error bodies. Cooldowns bench failing keys/models with an escalating ladder, and a background probe job recovers heuristic cooldowns early.
+
+---
+
+## 2. Four-Dimensional Quota Accounting
+
+### Per-(Platform, Model, Key) Windows
+
+| Window | Width | Persisted Column | In-Memory Fallback |
+|--------|-------|------------------|-------------------|
+| RPM | 60 s | `rpm_limit` | `timestamps[]` |
+| RPD | 24 h (UTC midnight) | `rpd_limit` | `timestamps[]` |
+| TPM | 60 s | `tpm_limit` | `{ts, tokens}[]` |
+| TPD | 24 h (UTC midnight) | `tpd_limit` | `{ts, tokens}[]` |
+
+- **Sliding minute** for RPM/TPM; **UTC-day boundary** for RPD/TPD (providers reset at midnight, not 24h rolling).
+- `rate_limit_usage` table: one row per request/token event with `kind = 'request' | 'tokens'`, `created_at_ms`.
+- Retention: 1 day (pruned on insert, throttled to 1/min).
+- **Degraded mode**: when DB write fails, counts go to in-memory windows only (pruned on push so a long outage can't grow unbounded).
+
+### Provisional Usage (In-Flight Leases)
+
+> **The check-then-act closer.** Between key selection and the post-success `recordRequest/recordTokens` write, N concurrent requests would all read the same pre-check and collectively blow through the limit. **Leases make in-flight requests visible to the next caller.**
+
+```typescript
+acquireLease(platform, modelId, keyId, estimatedTokens) → leaseId
+releaseLease(leaseId) // in finally block, idempotent
+```
+
+- Leases count against **both minute and day windows** (a request in flight belongs to this minute and today).
+- Max lease age: 2 min (backstop for leaked leases).
+- Per-key concurrency cap (opt-in via `MAX_CONCURRENT_REQUESTS_PER_KEY[_PLATFORM]`).
+
+### Provider-Wide Pools
+
+Some providers enforce **one quota across the whole account**, not per model:
+
+| Pool | Providers | Config |
+|------|-----------|--------|
+| Daily requests | OpenRouter (1000/day free, 50/day <10 credits), ModelScope (2000→1800 margin) | `PROVIDER_DAILY_REQUEST_CAP_<PLATFORM>` |
+| Daily tokens | NavyAI (150K/day shared, model multipliers) | `PROVIDER_DAILY_TOKEN_CAP_<PLATFORM>` |
+| Minute requests | NVIDIA NIM (40 RPM account-wide) | `PROVIDER_MINUTE_REQUEST_CAP_<PLATFORM>` |
+
+- Counted by summing per-model windows for the same `platform + keyId`.
+- NavyAI token multiplier parsed from `monthly_token_budget` label (e.g. `2x`) or derived from `tpd_limit`.
+
+### Provider Quota Keys (pooling across models)
+
+`inferQuotaPoolKey(platform, modelId)` → string like `openrouter::free`, `google::project`, `nvidia::account`. Used by analytics and routing to attribute usage to the correct shared bucket.
+
+- Per-platform `inferPoolForPlatform()` maps each platform to its pool key shape. Aggregators with a single shared free pool (`routeway`, `bazaarlink`, `unorouter`, `orcarouter`, `xkiro`, `anyapi`, `navy`, `nara`, `sealion`, `aion`, `requesty`) get one pool; `openrouter` distinguishes `:free` from `:account`; others default to `::account` or `::<modelId>`.
+- `isSharedPool(platform)` returns the list of platforms that enforce one quota across the whole account — used by analytics and the `least-remaining` key selection (which skips `::account` pools since every key reports the same number).
+- `provider-quota.ts` also exposes `getKeyQuotaHeadroom(platform)` → a cached, platform-filtered read of `provider_quota_state` (5s TTL, confidence ≥ 0.7 floor, expired windows treated as full) that the router's `least-remaining` strategy reads to rank keys by remaining budget.
+
+---
+
+## 3. Window Utilization Snapshot (for the routing guardrail, #899)
+
+The hard gates (`canMakeRequest` / `canUseTokens`) answer a yes/no question on the hot path. The router also needs a **graded** signal — "how much of its window quota has this model already burned" — so it can steer traffic away from a model at 95% of its daily cap before that cap actually rejects anything. This is the input to `rateWindowHeadroomFactor` in `scoring.ts`.
+
+### 5-Second Snapshot (`modelWindowUsedFraction`)
+
+Cost is the whole design constraint: this runs per chain entry per request, and the naive shape is four counts per model × key. So it is:
+
+- **One grouped scan** of `rate_limit_usage` (replaces four counts per model × key) plus one read of `api_keys`, **memoised for 5 seconds** (`WINDOW_USAGE_TTL_MS = 5000`) and shared by every entry of every chain.
+- Per-entry work is then pure in-memory arithmetic over the model's own limit columns (which the router already has in hand).
+- The hard gates above are **unaffected** — they still read live counts, so nothing here can let a request through a real limit.
+
+### Key Selection
+
+The chosen key is the **eligible key with the most headroom** (the one the router would pick NEXT), not the worst key on the account — a platform with one exhausted key and one idle key routes perfectly well (#921). In-flight leases are deliberately **not** counted: they close the check-then-act race on the hard gates; this is a steering signal averaged over a whole window, and folding a per-request quantity into a cached snapshot would buy noise, not accuracy.
+
+### Pressure Calculation
+
+A key metered on several windows takes the **worst** of them (the binding constraint is what 429s). Returns `null` (no opinion) when the model declares no window limits, has no routable key to measure, or the database is unreachable.
+
+---
+
+## 4. Cooldown Ladder & Provenance
+
+### Sources (CooldownSource)
+
+| Source | Meaning | Probe-Eligible? |
+|--------|---------|-----------------|
+| `heuristic` | Our own guess (transient 90s, escalation ladder, auth-failure bench, empty-completion) | **Yes** |
+| `authoritative` | Backed by explicit provider Retry-After or daily-quota reset (a fact) | No |
+| `credit` | 402 out-of-credits — key validation proves nothing about top-up | No |
+| `tier` | 403 model-not-on-tier — key validates but model stays gated | No |
+
+### Escalation Ladder (per model+key, rolling 24h)
+
+| Hit # | Duration | Notes |
+|-------|----------|-------|
+| 1 | 2 min | |
+| 2 | 10 min | |
+| 3 | 1 h | |
+| 4+ | 24 h | |
+
+- **Transient RPM/TPM 429** with healthy daily counters → short 90s cooldown, **does not count** toward ladder.
+- **Daily exhaustion** (RPD/TPD counter ≥ cap) → takes ladder step (up to 24h).
+- **Unknown limits** (NULL RPD/TPD): heuristic — 2+ 429s in 1h → "effectively daily exhausted" → escalate **but capped at 10 min** (`UNKNOWN_LIMIT_MAX_COOLDOWN_MS`). Prevents Ollama/Cloudflare/etc. from looping 90s forever when every request is a 429.
+- **Local endpoints** (loopback/RFC1918 `base_url`): capped at **5 s**, never escalates (#592).
+
+### Retry-After Handling
+
+```
+if (retryAfterMs > ourBench) → bench = min(retryAfterMs, 24h), source = 'authoritative'
+else → our bench stands, source = 'heuristic'
+```
+
+Provider-stated reset wins; everything past it is our guess.
+
+### Special Cooldowns
+
+| Trigger | Duration | Source |
+|---------|----------|--------|
+| 402 Payment Required | 24 h | `credit` |
+| 403 Model Forbidden | 24 h | `tier` |
+| Daily quota exhausted (explicit) | until UTC midnight / Retry-After | `authoritative` |
+| Auth failure (401) | 5 min (health cycle) | `heuristic` |
+| Empty completion streak (≥3) | normal ladder | `heuristic` |
+
+---
+
+## 5. Learning Real Limits from Error Bodies (#798)
+
+When a provider rejects with its real limit in the body, we **persist it** so pre-checks stop us before the next 413/429.
+
+```typescript
+// Groq 413: "...on tokens per minute (TPM): Limit 30000, Requested 33476"
+parseProviderLimit(message) → { kind: 'tpm', limit: 30000 }
+learnLimitFromError(modelDbId, err) → writes to models.tpm_limit if NULL or lower
+```
+
+- **Only tightens**: fills NULL or **lowers** an existing limit. Never raises — hitting a ceiling means our pre-check already let too much through.
+- Axis priority: TPD → TPM → RPD → RPM (day before minute, tokens before requests).
+- Requires BOTH "Limit N" and a confident axis match — no guessing.
+
+---
+
+## 6. Cooldown-Probe Early Recovery (`cooldown-probe.ts`)
+
+### Goal
+
+Heuristic cooldowns are pessimistic. When the provider recovers sooner (minute window rolled over, incident ended), capacity sits idle until the timer expires. The probe job **validates the key** and clears heuristic cooldowns early.
+
+### Algorithm
+
+- **Scan interval**: 60 s (cheap indexed SELECT on `rate_limit_cooldowns` where `source = 'heuristic'`).
+- **Ripeness**: cooldown must have served ≥50% of its bench **AND** have ≥60 s remaining.
+- **Per-key backoff**: 2m → 4m → 8m → 15m cap (failed probe = back off, bench unchanged).
+- **First-sighting stagger**: on restart, all persisted cooldowns are sighted at once. First probe scheduled at `now + jitter(0..45s)` to avoid thundering herd.
+- **Budget**: `COOLDOWN_PROBE_MAX_PER_PASS` (default 3, env-tunable).
+- **On valid probe**: clear **all** heuristic cooldowns for that key (across models), log `cooldown_recovered` event.
+- **Never probes**: authoritative/credit/tier cooldowns (filtered at query).
+
+### Kill Switch
+
+`COOLDOWN_PROBE_DISABLED=1`
+
+---
+
+## 7. Key Functions (ratelimit.ts)
+
+| Function | Purpose |
+|----------|---------|
+| `canMakeRequest(platform, modelId, keyId, limits)` | Pre-check RPM+RPD + in-flight leases |
+| `canUseTokens(platform, modelId, keyId, estTokens, limits)` | Pre-check TPM+TPD + in-flight leases |
+| `canUseProvider(platform, keyId)` | Provider-wide daily request cap |
+| `canUseProviderMinute(platform, keyId)` | Provider-wide minute request cap |
+| `canUseProviderTokens(platform, keyId, modelId, estTokens)` | Provider-wide daily token cap |
+| `recordRequest/recordTokens` | Post-success accounting (DB + in-flight release) |
+| `acquireLease/releaseLease` | In-flight concurrency + provisional usage |
+| `getCooldownDecisionForLimit(...)` | Full ladder + Retry-After + provenance |
+| `setCooldown(platform, modelId, keyId, durationMs, source)` | Persist + memory |
+| `isOnCooldown(platform, modelId, keyId)` | Check memory → DB → expiry |
+| `getProbeableCooldowns()` | Heuristic-only, for probe job |
+| `clearCooldownEarly(platform, modelId, keyId)` | Probe recovery (keeps escalation history) |
+| `parseProviderLimit(message)` | Extract `{kind, limit}` from error body |
+| `learnLimitFromError(modelDbId, err)` | Persist if tightens |
+| `getSoonestCooldownExpiry()` | For `Retry-After` header + exhaustion message |
+| `modelWindowUsedFraction(model, limits, now)` | 0..1 binding-window utilization (5s snapshot) |
+| `invalidateWindowUsage()` | Drop the memoised window snapshot (tests) |
+
+---
+
+## 8. Key Functions (cooldown-probe.ts)
+
+| Function | Purpose |
+|----------|---------|
+| `runCooldownProbePass(opts?)` | One scan → probe ripe keys → clear on valid |
+| `isRipe(cooldown, now)` | ≥50% served + ≥60s remaining |
+| `startCooldownProbe(scheduler)` | Registers 60s interval job |
+| `resetCooldownProbeState()` | Test seam |
+
+---
+
+## 9. Persistence Schema (relevant tables)
+
+```sql
+-- Per-(platform,model,key) usage events
+CREATE TABLE rate_limit_usage (
+ platform TEXT, model_id TEXT, key_id INTEGER,
+ kind TEXT CHECK(kind IN ('request','tokens')),
+ tokens INTEGER, created_at_ms INTEGER
+);
+CREATE INDEX idx_rate_limit_usage_lookup
+ ON rate_limit_usage(platform, model_id, key_id, kind, created_at_ms);
+
+-- Cooldowns with provenance
+CREATE TABLE rate_limit_cooldowns (
+ platform TEXT, model_id TEXT, key_id INTEGER,
+ expires_at_ms INTEGER, source TEXT CHECK(source IN ('heuristic','authoritative','credit','tier')),
+ set_at_ms INTEGER,
+ PRIMARY KEY (platform, model_id, key_id)
+);
+
+-- Server logs (warn/error only)
+CREATE TABLE server_logs (
+ id INTEGER PRIMARY KEY, level TEXT, source TEXT, provider TEXT,
+ model TEXT, event TEXT, request_id TEXT, message TEXT, created_at_ms INTEGER
+);
+```
+
+---
+
+## 10. Environment Variables
+
+| Variable | Default | Purpose |
+|----------|---------|---------|
+| `MAX_CONCURRENT_REQUESTS_PER_KEY` | null (unlimited) | Global per-key concurrency cap |
+| `MAX_CONCURRENT_REQUESTS_PER_KEY_<PLATFORM>` | null | Platform-specific override |
+| `PROVIDER_DAILY_REQUEST_CAP_<PLATFORM>` | see table | Provider-wide daily request cap (0 = disable) |
+| `PROVIDER_DAILY_TOKEN_CAP_<PLATFORM>` | see table | Provider-wide daily token cap |
+| `PROVIDER_MINUTE_REQUEST_CAP_<PLATFORM>` | see table | Provider-wide minute request cap |
+| `COOLDOWN_PROBE_DISABLED` | 0 | Kill switch for probe job |
+| `COOLDOWN_PROBE_MAX_PER_PASS` | 3 | Probes per 60s scan |
+| `DEGRADED_HEALTHY_RATIO` | 0.5 | Degraded mode threshold (see 04-degraded-mode) |
+| `DEGRADED_MIN_PROVIDERS` | 3 | Min providers for degraded eval |
+| `DEGRADED_ENTRY_GRACE_MS` | 60000 | Time below threshold before entry |
+| `DEGRADED_EXIT_GRACE_MS` | 120000 | Time above threshold before exit |
+
+---
+
+## 11. Flow Diagram: Request → Quota Check → Dispatch → Account
+
+```
+routeRequest()
+ ├─ canMakeRequest() → RPM + RPD + in-flight leases
+ ├─ canUseTokens() → TPM + TPD + in-flight leases
+ ├─ canUseProvider() → provider daily request cap
+ ├─ canUseProviderMinute() → provider minute request cap
+ ├─ canUseProviderTokens() → provider daily token cap
+ ├─ canUseKeyConcurrency() → per-key concurrency cap
+ └─ isOnCooldown() → heuristic/authoritative bench
+ ↓
+acquireLease() (provisional usage now visible to next caller)
+ ↓
+dispatch to provider
+ ↓
+success:
+ recordRequest() → DB + releaseLease()
+ recordTokens() → DB + releaseLease()
+ clear cooldown hits / null-limit hits
+failure (retryable):
+ recordRetryableFailure() → cooldownDecisionForError() → setCooldown()
+ recordRateLimitHit() / recordModelFailure() (model penalty)
+ learnLimitFromError() (if provider reported ceiling)
+ skipKeys.add(platform:modelId:keyId)
+ skipModels.add(modelDbId) on 403/404/context-too-large
+ skipPlatforms.add(platform) on 5xx/timeout (#788)
+```
\ No newline at end of file
diff --git a/docs/architecture/03-streaming-pipeline.md b/docs/architecture/03-streaming-pipeline.md
new file mode 100644
index 00000000..b1e13099
--- /dev/null
+++ b/docs/architecture/03-streaming-pipeline.md
@@ -0,0 +1,257 @@
+# Streaming Pipeline — Deep Dive
+
+> **Source:** `server/src/routes/proxy.ts`, `server/src/routes/responses.ts`, `server/src/routes/anthropic.ts`, `server/src/lib/fallback-loop.ts`
+
+## 1. Design Principles
+
+- **SSE only** — zero WebSockets. Every surface (`/v1/chat/completions`, `/v1/responses`, `/v1/messages`, legacy `/completions`) streams via Server-Sent Events.
+- **Turn integrity** — the stream is validated as a *turn*, not a transport. Headers are held until first real payload; anything dying before that fails over invisibly.
+- **Failover mid-stream** — if an error frame arrives before headers flush, it's retryable; after flush, an error frame is surfaced honestly (stream_error).
+- **Unified fallback loop** — all surfaces share `lib/fallback-loop.ts` for retry budget, cooldowns, attempt trail, exhaustion rendering.
+
+---
+
+## 2. OpenAI Chat Completions (`/v1/chat/completions`)
+
+### Request Flow
+
+```
+parse + validate (zod)
+ ├─ compression (optional, X-FreeLLM-Compress)
+ ├─ system-prompt injection (profile-enforced)
+ ├─ image downscale (normalizeMessageImages)
+ ├─ token estimation (chars/4 heuristic)
+ ├─ vision/tools gates (422 if no capable model)
+ ├─ token budget guardrail (request_max_tokens_budget)
+ ├─ response cache check (opt-in, exact-match LRU)
+ ├─ sticky session / context handoff
+ ├─ resolve routing chain (auto / pinned / group)
+ └─ runFallbackLoop()
+ ├─ route() → picks model+key
+ ├─ dispatch() → streamChatCompletion()
+ ├─ on success → recordUpstreamSuccess(), log, cache store
+ ├─ on retryable failure → recordRetryableFailure(), cooldown, skipKeys, next
+ ├─ on fatal → onFatal() (502)
+ └─ on exhaustion → exhaustedRetryError() → onExhausted() (429/502/413/404/503)
+```
+
+### Streaming Pump (`proxy.ts` lines ~1873–2150)
+
+**State machine per attempt:**
+
+```
+mode = 'undecided' | 'passthrough' | 'dialect'
+heldText = ''
+preamble = [] // role/keep-alive chunks held until mode decided
+toolCallAcc = Map<index, {id, name, args}>
+ttfbMs = null // first token of ANY kind (content or reasoning)
+headerSent = false
+```
+
+**Per chunk:**
+
+1. **Metadata capture**: `upstreamModel` (first frame with `model` field), `lastMeta` (id/created/model for our framing).
+2. **In-band error frame** (`{error:..., choices: undefined}`):
+ - Before headers: throw → failover
+ - After headers: write error frame + `[DONE]` → `committed`
+3. **Usage frame**: captured wherever it lands (choice-less or on last choice), re-emitted once after our finish chunk.
+4. **Reasoning accumulation** (#764): `streamReasoningText()` extracts `reasoning_content` / `reasoning`; added to `streamReasoning` for session memory + token accounting.
+5. **Tool-call deltas**: buffered in `toolCallAcc`, arguments repaired against request schemas at end.
+6. **Content text**: `streamChunkText()` extracts `delta.content`.
+7. **TTFB** (#764): recorded on **first token of any kind** (content OR reasoning).
+8. **Mode decision**:
+ - `undecided` + `wantsTools` + `startsWithDialectMarker(heldText)` → `dialect` (buffer everything)
+ - `undecided` + `!wantsTools` OR `!couldBecomeDialectMarker` OR `heldText > 256` → `passthrough`, flush headers, stream
+ - `passthrough` → forward immediately (strip tool_calls from delta, re-emit complete at end)
+ - `dialect` → keep buffering
+9. **Empty chunks** (role/keep-alive/reasoning-only): held in `preamble` until flush.
+
+**Stream end (clean):**
+
+1. Assemble buffered tool calls → `repairToolArguments()` against request schemas.
+2. If `dialect` mode: `rescueInlineToolCalls(heldText)` → structured `tool_calls` or failover.
+3. Emit complete tool calls (single chunk, `finish_reason: 'tool_calls'`).
+4. Emit final chunk (`finish_reason: 'stop' | 'length' | upstreamFinish`).
+5. Emit captured usage frame.
+6. `recordUpstreamSuccess()`, `logRequest()`, `observeServedModel()`, store in cache if applicable.
+
+**Mid-stream error:**
+
+- Before headers: throw → failover (next model)
+- After headers: write `stream_error` frame + `[DONE]` → `committed` (loop stops, no further fallback)
+
+### Token Accounting (Streaming)
+
+- **Output tokens**: `ceil((text.length + reasoning.length) / 4)` per chunk — reasoning tokens are real consumption (#764).
+- **TTFB**: wall-clock to first content OR reasoning token.
+- **Non-stream reconciliation**: provider's `usage` block overrides estimates.
+
+---
+
+## 3. Anthropic Messages (`/v1/messages`)
+
+### Translation Layer (`routes/anthropic.ts`)
+
+| Anthropic | OpenAI (internal) |
+|-----------|-------------------|
+| `messages[]` (no system role) | `system` + `messages[]` |
+| `tool_use` blocks in content | `tool_calls` array |
+| `tool_result` blocks | `tool` messages |
+| `stop_reason: 'tool_use'` | `finish_reason: 'tool_calls'` |
+| `thinking` budget/type | `reasoning_effort` / `max_completion_tokens` |
+
+**Streaming**: upstream OpenAI SSE → translated chunk-by-chunk to Anthropic SSE events (`message_start`, `content_block_start`, `content_block_delta`, `content_block_stop`, `message_delta`, `message_stop`). Tool-use blocks are rendered as structured `tool_use` content blocks, not inline text.
+
+### Error Mapping (exhaustion)
+
+| FreeLLM kind | Anthropic type |
+|--------------|----------------|
+| `auth` | `api_error` |
+| `bad_request` | `invalid_request_error` |
+| `rate_limit` | `overloaded_error` (429) |
+| `unavailable` | `overloaded_error` (503) |
+| `context_too_large` | `request_too_large` |
+| `model_not_found` | `not_found_error` |
+| `upstream` | `api_error` |
+
+---
+
+## 4. Gemini (`/v1beta` via `/v1/chat/completions`)
+
+### Request Translation (`providers/gemini.ts`)
+
+- **Parts-based content**: `content: [{text:...}, {inline_data:...}, {function_call:...}]`
+- **System prompt**: injected as first `user` turn with `role: 'user'` + `parts: [{text: system}]` then a `model` acknowledgement (Gemini requires alternating roles).
+- **Tool calls**: `function_call` parts → OpenAI `tool_calls` on forward; `function_response` parts ← OpenAI `tool` messages.
+- **Structured output**: `response_format: json_schema` → Gemini native `responseSchema` + `responseMimeType: 'application/json'`.
+- **Thinking**: `thinking_config: {thinking_budget: N}` from `reasoning_effort` / `max_completion_tokens`.
+
+### Streaming
+
+- Native Gemini SSE → normalized to OpenAI chunk shape in `base.ts` `streamChatCompletion()`.
+- Inline tool-call dialect (`function_call` in text) rescued by same dialect detector.
+- `thought_signature` preserved on tool calls (#13).
+
+---
+
+## 5. Responses API Shim (`/v1/responses`)
+
+> **Source:** `server/src/routes/responses.ts`
+
+### Purpose
+
+Codex CLI and Agents SDK speak the **Responses API** (stateful, `previous_response_id` chaining). The shim translates to/from chat completions so the same router/quota/failover machinery serves both.
+
+### Translation
+
+| Responses API | Chat Completions |
+|---------------|------------------|
+| `input` (string or array) | `messages[]` |
+| `previous_response_id` | sticky session (sessionId = response_id) |
+| `tools` (function + `type: 'function'`) | `tools` + `tool_choice` |
+| `text.format` (json_schema) | `response_format: json_schema` |
+| `reasoning` (effort/summary) | `reasoning_effort` + `max_completion_tokens` |
+| `stream: true` | SSE with `_fusion`-style additive frames for tool calls |
+
+### Streaming
+
+- Opens SSE immediately.
+- Tool calls emitted as additive `_fusion` frames (no `choices`, standard clients skip) → final answer streamed as normal content deltas.
+- `response.output_text` convenience field on final non-stream response.
+
+### Failover
+
+- Shares `runFallbackLoop()` — identical retry budget, cooldowns, attempt trail.
+- Exhaustion rendering maps to Responses API error shape.
+
+---
+
+## 6. Legacy Completions (`/v1/completions`)
+
+Thin adapter over shared fallback loop:
+
+- `prompt` + `suffix` → chat messages (system: "code autocomplete engine", user: prefix/suffix).
+- Response: `text_completion` shape (choices[0].text).
+- Streaming: `legacyCompletionChunk()` wraps upstream chunks.
+- Same commit-point logic: headers held until first text; reasoning tokens counted (#764).
+
+---
+
+## 7. Fusion Virtual Model (`model: "fusion"`)
+
+> **Source:** `server/src/services/fusion.ts`
+
+- Fans prompt to **panel of diverse models** in parallel (vision/tools filtered per member).
+- **Judge model** synthesizes one answer.
+- Each sub-call routes through **normal path** (cooldowns, quotas, analytics).
+- Streaming: additive `_fusion` frames for panel/judge events, then judge's synthesis as normal content deltas.
+- Non-stream: structured-output enforcement on judge output (#516).
+- Failover: panel members fail over within their own chains; judge failure → fallback to best-of panel.
+
+---
+
+## 8. Error Handling Mid-Stream
+
+| Scenario | Before Headers | After Headers |
+|----------|----------------|---------------|
+| In-band `{error}` frame | Throw → failover | Write error frame + `[DONE]` → `committed` |
+| Client disconnect | `clientGone` → abort in-flight, no bench | `clientGone` → stop pulling, `committed` |
+| Hedge abort (budget expiry) | `abortInFlight()` → `HedgeAbortError` → loop stops, `timedOut` exhaustion | Same |
+| Empty completion (no text, no tools) | Throw `empty completion` → failover | N/A (would have flushed) |
+| Upstream classification output ("safe"/"unsafe") | Throw → failover (a961d93) | N/A |
+| Tool dialect detected | Buffer → rescue at end or failover | N/A |
+
+---
+
+## 9. Headers Emitted on Every Response
+
+| Header | Value |
+|--------|-------|
+| `X-Request-ID` | UUID (or `x-request-id` from client) |
+| `X-Routed-Via` | `platform/model` (safeHeaderValue) |
+| `X-Fallback-Attempts` | Failed hops before this response |
+| `X-Fallback-Trail` | `platform/model keyN=class; …` (max 10) |
+| `X-Fallback-Detail` | **Opt-in**: `platform/model keyN=outcome t=start+durationMs msg=summary; …` |
+| `Retry-After` | Seconds until soonest cooldown expiry (429 exhaustions) |
+| `X-FreeLLM-Cache` | `HIT` / `MISS` (response cache) |
+| `X-FreeLLM-Compress` | Compression pipeline metadata |
+
+---
+
+## 10. Key Functions (proxy.ts)
+
+| Function | Purpose |
+|----------|---------|
+| `runFallbackLoop(hooks)` | Shared attempt loop (see 04-degraded-mode) |
+| `streamChunkText(chunk)` | Extract `delta.content` (tolerates no-choices frames) |
+| `streamReasoningText(chunk)` | Extract `delta.reasoning_content` / `delta.reasoning` |
+| `restoreSessionReasoning(messages, reasoning, platform)` | #797: replay thinking trace stripped by client |
+| `rememberReasoning(sessionKey, modelKey, reasoning)` | Store per-session trace |
+| `rescueInlineToolCalls(text, tools)` | Convert inline dialect → structured `tool_calls` |
+| `repairToolArguments(args, schemas)` | Fix double-encoded JSON against request schemas |
+| `truncateMessagesForGithub(messages)` | Trim history to GitHub Models input ceiling |
+| `normalizeOutboundContent(chunk)` | Provider-specific response normalization |
+| `sanitizeResponse(chunk)` | Redact secrets from streamed frames |
+
+---
+
+## 11. Concurrency & Cancellation
+
+- **Client disconnect**: `res.on('close')` → `clientGone = true`, `clientAbort.abort()` → in-flight fetch canceled, lease released immediately.
+- **Hedging** (1d2226a): `hedgeAbort` controller, `abortInFlight()` called when wall-clock budget expires mid-attempt. `HedgeAbortError` is **non-provider-health** → no cooldown/penalty, renders `timedOut` exhaustion.
+- **Lease release**: in `finally` block of `dispatch()`, idempotent. Optional on `RouteResult` so a `TypeError` in `finally` cannot replace the upstream error.
+
+---
+
+## 12. Compression Pipeline (Opt-In)
+
+`X-FreeLLM-Compress` header → `compressRequest(messages, {header, tools, cacheControlPrefixLength})` → returns compressed messages + cache key. Engines: `lite`, `jsoncompact`, `dedup`, `aging`, `relevance`, `hard-budget`, `filter-definitions`, `custom-filters`, `toolfilter`, `read-lifecycle`. Cache key includes `compression.cacheKey` so different compression levels never collide.
+
+---
+
+## 13. Response Cache (Opt-In)
+
+- **Scope**: non-streaming only, cacheable temperature (`temperature ≤ 1` or unset), `X-FreeLLM-Cache: on` or `RESPONSE_CACHE=1`.
+- **Key**: SHA-256 over canonical request (model, messages, all sampling params, tools, stop, response_format, n, seed, penalties, logit_bias, logprobs, top_logprobs, reasoning_effort, compression).
+- **Store**: in-memory LRU, TTL + temperature gates.
+- **Hit**: returns cached body, `X-Routed-Via: cache`, `X-FreeLLM-Cache: HIT`, **zero provider quota consumed**.
\ No newline at end of file
diff --git a/docs/architecture/04-degraded-mode-and-failover.md b/docs/architecture/04-degraded-mode-and-failover.md
new file mode 100644
index 00000000..f279ddad
--- /dev/null
+++ b/docs/architecture/04-degraded-mode-and-failover.md
@@ -0,0 +1,317 @@
+# Degraded Mode & Failover — Deep Dive
+
+> **Source:** `server/src/services/degradation.ts`, `server/src/lib/fallback-loop.ts`, `server/src/routes/proxy.ts`, `server/src/services/ratelimit.ts`
+
+## 1. Degraded-Mode State Machine (f412e97)
+
+### Purpose
+
+When a large share of enabled providers fails simultaneously, per-request probing and bandit exploration just burn retry budget on dead routes. The degraded-mode state machine tracks the **healthy-provider ratio** (driven by the scheduled health pass) and flips the gateway into a degraded state once the ratio stays below a threshold for a sustained period.
+
+### State Machine
+
+```
+┌─────────────┐ ratio < threshold for DEGRADED_ENTRY_GRACE_MS ┌─────────────┐
+│ normal │ ─────────────────────────────────────────────────────▶ │ degraded │
+└─────────────┘ └─────────────┘
+ ▲ │
+ │ ratio ≥ threshold for DEGRADED_EXIT_GRACE_MS │
+ └────────────────────────────────────────────────────────────────────┘
+```
+
+### Parameters (env-tunable)
+
+| Variable | Default | Meaning |
+|----------|---------|---------|
+| `DEGRADED_HEALTHY_RATIO` | 0.5 | Fraction of providers that must have ≥1 usable key |
+| `DEGRADED_MIN_PROVIDERS` | 3 | Min enabled providers for evaluation (single-provider deployments don't flap) |
+| `DEGRADED_ENTRY_GRACE_MS` | 60,000 | Time below threshold before entering degraded |
+| `DEGRADED_EXIT_GRACE_MS` | 120,000 | Time above threshold before exiting (longer = hysteresis) |
+
+### Health Snapshot
+
+```typescript
+interface HealthSnapshot {
+ healthyProviders: number // enabled providers with ≥1 key in {healthy, unknown}
+ totalProviders: number // enabled providers with ≥1 key (any status)
+ ratio: number // healthy / total (1 if total=0)
+}
+```
+
+- `unknown` counts as healthy (unprobed key = usable until probe says otherwise).
+- Computed from `api_keys` table on every health pass + on demand (dashboard, router entry).
+
+### Behavioral Changes in Degraded Mode
+
+| Aspect | Normal | Degraded |
+|--------|--------|----------|
+| Bandit exploration | 10% floor (if enabled) | **Disabled** — sticks to scored order of remaining healthy providers |
+| Router | `isDegraded()` checked at route time | Same |
+| Health endpoint | Reports `state: 'normal'` | Reports `state: 'degraded', degradedAt: timestamp` |
+| Logging | — | `console.warn` on entry, `console.log` on exit |
+
+### API
+
+```typescript
+isDegraded(): boolean // read-only, used by router
+getDegradationStatus(): DegradationStatus // {healthyProviders, totalProviders, ratio, state, degradedAt}
+updateDegradationState(now?): DegradationStatus // call after every health pass
+resetDegradationState() // tests, post-start re-probe
+```
+
+---
+
+## 2. Retry Budget & Hedging (1d2226a)
+
+### Wall-Clock Retry Budget
+
+- **Default**: 45 s (`FALLBACK_TIME_BUDGET_MS`, setting `fallback_time_budget_ms`, 0 = disabled).
+- **Checked BEFORE starting each retry** (attempt ≥ 1). Attempt 0 always runs; attempt 1 always runs (so failover is structurally possible even when attempt 0 consumes the whole budget).
+- **Exhaustion rendering**: `timedOut: true` + `budgetMs` in `ExhaustionContext` → message includes "stopped early: retry time budget 45s exceeded — one failover hop is always allowed, and past that the budget stops starting further retries and cancels an attempt still waiting on its first byte".
+
+### Hedging (Abort In-Flight)
+
+> Pre-v2: budget only refused to *start* the next retry. A stalled attempt could run for minutes, blocking the chain.
+>
+> **v2 (1d2226a)**: When budget expires mid-attempt, `abortInFlight()` cancels the upstream fetch via `AbortController` (threaded as `CompletionOptions.signal`).
+
+```typescript
+// In fallback-loop.ts
+abortInFlight: () => hedgeAbort.abort(newHedgeAbortError())
+```
+
+- `HedgeAbortError` is **non-provider-health** → no cooldown, no penalty, no limit learning.
+- Renders `timedOut` exhaustion (not a provider failure).
+- Streaming surfaces call `ctx.disarmHedge()` on first byte / header flush — past that point the answer is on its way, killing it would truncate a healthy response for no failover benefit.
+
+### Circuit Breaker Guardrail
+
+- `max_consecutive_upstream_fails` (setting `max_consecutive_upstream_fails`, default 0 = disabled).
+- Counts consecutive retryable upstream failures across the attempt loop.
+- Trips → `breakerFails` in `ExhaustionContext` → **503 service_unavailable** with "upstream_unhealthy" code.
+- "The enabled pool looks unhealthy right now, so the remaining candidates were skipped instead of burning quota on them."
+
+---
+
+## 3. X-Fallback-Detail Header (8cb75ac)
+
+### Purpose
+
+`X-Fallback-Trail` tells **which hops burned and why**. `X-Fallback-Detail` adds **how long they cost** — the part an agent cannot reconstruct (a 40s response: one provider stalled 39s vs four failed fast).
+
+### Format
+
+```
+X-Fallback-Detail: platform/model keyN=outcome t=startOffset+durationMs msg=summary; +N more
+```
+
+- **Per-hop timings** + redacted provider message.
+- **Opt-in**: `EXPOSE_FALLBACK_DETAIL_HEADER=1` or setting `expose_fallback_detail_header`.
+- **Budget**: 2048 chars total, 120 chars per message summary, max 10 hops shown.
+- **Only failed hops**: the currently-serving hop isn't knowable while headers are open (recorded after dispatch returns).
+
+### Example
+
+```
+X-Fallback-Detail: google/gemini-2.5-pro key1=rate_limited t=0+1205ms msg=429 Quota exceeded; groq/llama-3.3-70b key2=upstream_error t=1205+3450ms msg=503 Service unavailable; +1 more
+```
+
+### Implementation
+
+```typescript
+// fallback-loop.ts
+formatAttemptDetail(records: AttemptTraceRecord[]): string
+// AttemptTraceRecord: {platform, modelId, keyOrdinal, outcome, startOffsetMs, durationMs, errorSummary}
+
+// Set on response (before flush):
+if (isFallbackDetailHeaderEnabled() && records?.length) {
+ res.setHeader('X-Fallback-Detail', safeHeaderValue(formatAttemptDetail(records), 2048));
+}
+```
+
+---
+
+## 4. Bare Safe/Unsafe Classification Failover (a961d93)
+
+### Problem
+
+Some relay models (e.g. OpenCode Zen) emit a bare `"safe"` or `"unsafe"` classification word as the **entire completion** instead of the requested answer. This is an upstream content filter, not the model's output.
+
+### Fix
+
+```typescript
+// proxy.ts, after non-stream completion:
+const text = completionTextFromChat(result);
+if (!text) { throw empty completion... }
+
+// #809: fail over on relay's bare classification output
+if (isUpstreamClassificationOutput(text, route.platform)) {
+ throw Object.assign(
+ new Error(`empty completion from ${route.displayName} (upstream classification output)`),
+ result.choices?.[0]?.finish_reason === 'length' ? { skipBench: true } : {},
+ );
+}
+```
+
+- `isUpstreamClassificationOutput(text, platform)` checks for exact `"safe"` / `"unsafe"` (case-insensitive, trimmed) on known relay platforms.
+- Treated like an empty completion: **fail over**, `skipBench: true` when `finish_reason === 'length'` (reasoning consumed budget).
+- Streaming path: same check on accumulated text at stream end.
+
+---
+
+## 5. Unified Fallback Loop (`lib/fallback-loop.ts`)
+
+### Shared by All Surfaces
+
+| Surface | Route | Dispatch |
+|---------|-------|----------|
+| `/v1/chat/completions` | `proxy.ts` | SSE streaming + non-stream |
+| `/v1/responses` | `responses.ts` | Responses API framing |
+| `/v1/messages` | `anthropic.ts` | Anthropic SSE events |
+| `/v1/completions` | `proxy.ts` | Legacy text_completion SSE |
+
+### Loop Contract
+
+```typescript
+interface FallbackHooks {
+ maxRetries?: number; // default 20
+ timeBudgetMs?: number; // default getFallbackTimeBudgetMs()
+ breakerLimit?: number; // default getMaxConsecutiveUpstreamFails()
+ attemptLog?: AttemptRecord[]; // mutated, used for X-Fallback-Trail
+ state: FallbackState; // skipKeys, skipModels, skipPlatforms
+ clientGone?: () => boolean; // checked before each retry
+ abortInFlight?: () => void; // hedging (v2)
+ route(attempt): RouteResult; // throws RouteError on synchronous exhaustion
+ dispatch(route, attempt, ctx): Promise<'done' | 'committed'>;
+ logFailure(route, err, attempt): void;
+ onFatal(route, err, attempt): void; // non-retryable → 502
+ onRoutingExhausted(lastError, routeErr, exhaustion, info): void; // zero attempts
+ onExhausted(exhaustion, info): void; // retries exhausted
+}
+```
+
+### Attempt Classification (recordRetryableFailure)
+
+| Error | Skip Scope | Cooldown | Model Penalty | Limit Learn |
+|-------|------------|----------|---------------|-------------|
+| 401 invalid key | key | 5 min | no | no |
+| 402 payment required | key | 24h | no | no |
+| 403 model forbidden | **model** | 24h | no | no |
+| 429 daily exhausted | model+key | until midnight / Retry-After | **heavy (3)** | yes |
+| 429 transient (rpm/tpm) | key | 90s / ladder | light (1) | yes |
+| 5xx / timeout / transport | **platform** (#788) | 90s / ladder | light (1) | no |
+| empty completion (reasoning) | key | exempt (streak ≤3) | no | no |
+| context too large | model | — | no | no |
+| response_format ignored | model | — | no | no |
+| invalid tool arguments | key | — | no | no |
+
+### Model-Level Failure Benching (#806)
+
+- 3 retryable failures across keys within 15 min → bench model on **all its keys** for 10 min (heuristic, probe-eligible).
+- A served request clears the failure window.
+
+### Empty-Completion Streak Limit (#751)
+
+- 3 consecutive reasoning-truncated completions on same model+key → exemption lifts → normal cooldown/penalty/limit-learning applies.
+- Reset on success or normally-penalized failure.
+
+### Provider-Level Skip (#788)
+
+- 5xx / timeout / transport / degraded → `skipPlatforms.add(platform)`.
+- Whole provider ruled out for this request — loop moves to next provider instead of burning one hop per key.
+
+### Exhaustion Rendering (exhaustedRetryError)
+
+**Most-specific-first aggregation over attempt classes:**
+
+1. **All auth** → 502 `provider_error` (`provider_authentication_failed`) — distinct from rate-limit, never blames client key.
+2. **All context_too_large** → 413 `invalid_request_error` (`context_length_exceeded`).
+3. **All model_not_found** → 404 `invalid_request_error` (`model_not_found`).
+4. **Last error = degraded 400** (NVIDIA NIM) → 503 `service_unavailable` (`provider_degraded`).
+5. **Last error = provider bad request** → 400 `invalid_request_error` (`provider_rejected_request`).
+6. **Circuit breaker** → 503 `service_unavailable` (`upstream_unhealthy`).
+7. **All UNAVAILABLE_UNTIL_KNOWN_TIME** (rate_limited, daily_quota_exhausted, out_of_credits, forbidden) → 429 `rate_limit_error` with `retryAtMs` + `Retry-After`.
+8. **Mixed/other** → 502 `provider_error` (`upstream_failed`) — never 500 (our bugs).
+
+**Synchronous exhaustion (zero attempts):** `routingExhaustionBody(routeErr)` maps diagnostics to same taxonomy:
+- All config (no key, no provider) → 503 `no_providers_configured`
+- All too_large (+ config) → 413 `context_length_exceeded`
+- Some time_bound, rest config/too_large → 429 with `retryAtMs`
+- Else → 429 `routing_exhausted`
+
+---
+
+## 6. Attempt Trail & Headers
+
+### X-Fallback-Attempts
+
+Count of failed hops before this response (on success AND exhaustion).
+
+### X-Fallback-Trail
+
+```
+platform/model key1=class; platform/model key2=class; +N more
+```
+
+- `class` ∈ `AttemptErrorClass` (auth, out_of_credits, daily_quota_exhausted, model_not_found, forbidden, context_too_large, provider_bad_request, empty_completion, format_ignored, invalid_tool_arguments, timeout, rate_limited, upstream_error, error).
+- Max 10 shown, 1024 char cap.
+
+### X-Fallback-Detail (opt-in)
+
+See §3 above.
+
+---
+
+## 7. Key Functions (degradation.ts)
+
+| Function | Purpose |
+|----------|---------|
+| `computeHealthSnapshot()` | Reads `api_keys` → `{healthyProviders, totalProviders, ratio}` |
+| `updateDegradationState(now)` | State machine step, called after health pass |
+| `isDegraded()` | Router gate |
+| `getDegradationStatus()` | Dashboard + health endpoint |
+| `resetDegradationState()` | Tests / boot re-probe |
+
+---
+
+## 8. Key Functions (fallback-loop.ts)
+
+| Function | Purpose |
+|----------|---------|
+| `runFallbackLoop(hooks)` | Main loop |
+| `newFallbackState()` | Fresh `{skipKeys, skipModels, skipPlatforms}` |
+| `cooldownDecisionForError(route, err)` | Ladder + Retry-After + provenance |
+| `recordRetryableFailure(route, err, state, now)` | Full bookkeeping |
+| `recordAuthFailure(route, state)` | 401: skip key, 5min bench, trigger revalidation |
+| `recordUpstreamSuccess(route, tokens)` | Account + clear streaks + mark key healthy |
+| `exhaustedRetryError(lastError, maxRetries, ctx)` | Honest terminal status + body |
+| `routingExhaustionBody(routeErr)` | Zero-attempt exhaustion from diagnostics |
+| `setFallbackHeaders(res, failedAttempts, trail)` | X-Fallback-Attempts + X-Fallback-Trail |
+| `setExhaustionHeaders(res, body)` | Retry-After from `retryAtMs` |
+| `formatAttemptTrail(attempts)` | X-Fallback-Trail value |
+| `formatAttemptDetail(records)` | X-Fallback-Detail value |
+| `isFallbackDetailHeaderEnabled()` | Settings → env → false |
+| `getFallbackTimeBudgetMs()` | Settings → env → 45s |
+| `msUntilNextUtcMidnight()` | Daily quota reset boundary |
+
+---
+
+## 9. Flow: Request Enters Degraded Gateway
+
+```
+request → /v1/chat/completions
+ ├─ isDegraded() = true
+ │ └─ router: exploration DISABLED, scored order only
+ ├─ runFallbackLoop()
+ │ ├─ attempt 0: route() → best healthy model
+ │ ├─ dispatch() → 429 daily exhausted
+ │ │ └─ recordRetryableFailure() → cooldown (authoritative, until midnight)
+ │ │ └─ skipKeys.add(), skipModels.add() (daily exhausted = model-level)
+ │ ├─ attempt 1: route() → next healthy (skipKeys honored)
+ │ ├─ ... budget check before each retry ...
+ │ ├─ budget exceeded mid-attempt 3
+ │ │ └─ abortInFlight() → HedgeAbortError
+ │ │ └─ loop stops, timedOut exhaustion
+ │ └─ onExhausted() → 429 with X-Fallback-Detail + Retry-After
+ └─ response headers: X-Fallback-Attempts, X-Fallback-Trail, X-Fallback-Detail
+```
\ No newline at end of file
diff --git a/docs/architecture/05-catalog-sync.md b/docs/architecture/05-catalog-sync.md
new file mode 100644
index 00000000..6d0d51e6
--- /dev/null
+++ b/docs/architecture/05-catalog-sync.md
@@ -0,0 +1,279 @@
+# Catalog Sync — Deep Dive
+
+> **Source:** `server/src/services/catalog-sync.ts`, `server/src/services/model-state.ts`, `server/src/db/migrations/`
+
+## 1. Overview
+
+The catalog sync keeps the local model catalog in step with the published catalog at `freellmapi.co`. It runs **twice daily** (and on demand), fetches a **signed catalog**, verifies it against a **pinned Ed25519 public key**, and applies it **transactionally** to the local SQLite database.
+
+### Two Tiers
+
+| Tier | Audience | Refresh Cadence | Auth |
+|------|----------|-----------------|------|
+| **Live** | Premium license holders | Every 2–3 days | Bearer `premium_license_key` |
+| **Monthly** | Free installs | ~30 days | None (public) |
+
+Free installs still self-heal, just on a slower cadence. The bundled migrations remain the **baseline** — a fetched catalog is applied only when **newer than `MIN_CATALOG_VERSION`** (bumped on every model migration), so a stale monthly snapshot can never roll back models added by a newer app version.
+
+---
+
+## 2. Catalog Structure
+
+```typescript
+interface Catalog {
+ version: string; // e.g. "2026.06.07"
+ generatedAt: string; // ISO timestamp
+ tier: 'live' | 'monthly';
+ models: CatalogModel[]; // chat models
+ embeddings?: CatalogEmbedding[]; // optional, joined freshness feed
+ transcriptionModels?: CatalogTranscriptionModel[]; // STT, own top-level key
+ quirks: CatalogQuirk[]; // operational advisories
+}
+```
+
+### CatalogModel (chat)
+
+| Field | Purpose |
+|-------|---------|
+| `platform`, `modelId` | Primary key (with `endpoint_scope` for relays) |
+| `displayName` | UI name |
+| `intelligenceRank` | 1..1000 (1 = best), within provider |
+| `speedRank` | 1..11 (catalog hand-assigned, 1 = fastest) |
+| `sizeLabel` | `Frontier` \| `Large` \| `Medium` \| `Small` (cross-provider tier) |
+| `limits` | `{rpm, rpd, tpm, tpd}` — per-model caps |
+| `monthlyTokenBudget` | String label (e.g. `"1M"`, `"2x"`) for headroom guardrail |
+| `contextWindow` | Max context (tokens) |
+| `enabled` | Catalog-level enable (force-disables if false) |
+| `supportsVision` / `supportsTools` | Capability flags |
+| `modality` | `'text'` (default) → `models` table; `'image'`/`'audio'` → `media_models` |
+| `mediaNote` | Short display for media models |
+| `requestStyle` | Adapter flavor (e.g. Cloudflare images: `'json'` \| `'multipart'`) |
+
+### Generative Media & Transcription
+
+- **Media models** (`modality: 'image' | 'audio'`) → `media_models` table, gated by `MEDIA_PLATFORMS` set.
+- **Transcription models** → `media_models` with `modality = 'transcription'`, gated by `TRANSCRIPTION_PLATFORMS`.
+- Separate top-level keys (`transcriptionModels`, `embeddings`) so older binaries ignore unknown modalities instead of misrouting them as chat models.
+
+---
+
+## 3. Signature Verification
+
+```typescript
+const PINNED_CATALOG_PUBKEY = `-----BEGIN PUBLIC KEY-----
+MCowBQYDK2VwAyEAq9yv4+3EeyMHKsfVYBhkcz1lYgIXSUeHNnN6tNgYX3k=
+-----END PUBLIC KEY-----`;
+
+// Fetch
+const res = await fetch(`${catalogBaseUrl()}/v1/latest`, { headers: { Authorization: `Bearer ${key}` } });
+const signature = res.headers.get('x-catalog-signature');
+const bytes = Buffer.from(await res.arrayBuffer());
+const verified = crypto.verify(null, bytes, catalogPublicKey(), Buffer.from(signature, 'base64'));
+```
+
+- **Pinned key**: private half never left catalog host.
+- **Self-hosted catalog override**: `CATALOG_BASE_URL`, `CATALOG_PUBKEY` env vars.
+- **Tamper-proof**: anything unsigned or modified is discarded. Compromised CDN / MITM cannot inject models or quirks.
+
+---
+
+## 4. Application Rules (User Data Protection)
+
+Applied inside **one transaction** (`applyCatalog`):
+
+| Rule | Behavior |
+|------|----------|
+| Metadata (name, ranks, limits, context, capabilities) | Tracks catalog **unless** user has explicit local override |
+| `enabled: false` | **Force-disables** (model dead upstream) |
+| `enabled: true` | **Never re-enables** a model the user turned off |
+| User-created rows (`source = 'user'`) | **Never updated, never deleted, never adopted** — on `platform:model_id` collision, user row wins, catalog entry skipped |
+| Catalog models user deleted | Stay deleted via **tombstones** (`catalog_model_tombstones` table) |
+| Auto-retired (410/end-of-life) | **Disabled, not deleted** — catalog listing them enabled lifts retirement (#634) |
+| Models vanished from catalog | **Deleted** (fallback_config first, FK order) |
+
+### Provenance Column (`source`)
+
+Replaces the old `size_label NOT IN ('User','Custom')` heuristic. Values:
+
+- `'catalog'` — created by catalog sync
+- `'user'` — declarative config, admin add, custom endpoint
+- `'declarative'` — from declarative config file
+
+---
+
+## 5. Sync Flow
+
+```
+syncCatalog(force=false)
+ ├─ GET /v1/latest?since=<appliedVersion> (with Bearer license if set)
+ ├─ 304 → up_to_date
+ ├─ Verify signature (Ed25519)
+ ├─ Parse + structural validation (isCatalog)
+ ├─ version < MIN_CATALOG_VERSION? → skipped_older (would roll back migrations)
+ ├─ Same version+tier as applied? → up_to_date
+ ├─ applyCatalog(db, catalog) → transactional upsert/insert/delete
+ ├─ Persist settings: appliedVersion, appliedTier, appliedJSON (verified doc)
+ └─ Log counts: updated, inserted, removed, skippedUnknownPlatform, quirks
+```
+
+### Boot Re-apply (`reapplyCachedCatalog`)
+
+Migrations run on every boot and re-assert the bundled baseline (INSERT OR IGNORE baseline models the catalog may have deleted). The boot-time network sync 304s on unchanged version and would **NOT** re-apply. Without this step, every restart drifts the DB back toward the baseline until the next catalog version bump.
+
+```
+reapplyCachedCatalog()
+ ├─ Read SETTING_APPLIED_JSON (cached verified document)
+ ├─ Validate + version ≥ MIN_CATALOG_VERSION
+ ├─ applyCatalog(db, parsed) → synchronous, no network
+ └─ Log: "re-applied cached live v2026.06.07 after boot"
+```
+
+- Legacy upgrade: installs with applied-version but no cached doc → clear applied version → next poll fetches full catalog.
+
+---
+
+## 6. Model-Age Gate (30 Days)
+
+Models older than 30 days from `generatedAt` are **excluded from the live tier** (free tier trailing snapshot). The catalog service enforces this; the client just receives what the tier provides.
+
+---
+
+## 7. License Status
+
+```typescript
+interface LicenseStatus {
+ valid: boolean;
+ plan: 'annual' | 'lifetime' | null;
+ status: string | null;
+ expiresAt: string | null;
+ checkedAtMs: number;
+}
+```
+
+- Cached in settings (`premium_license_status`), refreshed on every sync.
+- Entitlement enforced **server-side** at `/v1/latest` — local cache is informational UI state.
+- Offline / service down → keep cached status.
+
+---
+
+## 8. Quirks (Operational Advisories)
+
+```typescript
+interface CatalogQuirk {
+ slug: string;
+ title: string;
+ body: string;
+ severity: 'blocker' | 'warning' | 'info';
+ targets: { platform: string | null; modelGlob: string | null }[];
+}
+```
+
+- Pure content: **replaced wholesale** on every sync (DELETE + INSERT).
+- Dashboard surfaces blockers/warnings for affected models.
+
+---
+
+## 9. Settings Keys
+
+| Key | Purpose |
+|-----|---------|
+| `premium_license_key` | Bearer token for live tier |
+| `premium_license_status` | Cached `LicenseStatus` JSON |
+| `catalog_applied_version` | Last applied catalog version |
+| `catalog_applied_tier` | `'live'` \| `'monthly'` |
+| `catalog_applied_json` | Verified catalog document (for boot re-apply) |
+| `catalog_last_sync_ms` | Timestamp of last successful sync |
+| `catalog_last_error` | Last sync error message |
+
+---
+
+## 10. Scheduler Integration
+
+```typescript
+startCatalogSync(scheduler: Scheduler)
+ ├─ reapplyCachedCatalog() // synchronous, no network
+ ├─ scheduler.after(10s, run) // boot delay
+ └─ scheduler.every(12h, run) // twice daily
+```
+
+- `run()` = `refreshLicenseStatus()` + `syncCatalog()`
+- Kill switch: `CATALOG_SYNC_DISABLED=1`
+
+---
+
+## 11. Migration Seeding vs Hosted Catalog
+
+| Aspect | Bundled Migrations | Hosted Catalog Sync |
+|--------|-------------------|---------------------|
+| **Authority** | Baseline floor | Live source of truth |
+| **Version** | `MIN_CATALOG_VERSION` (date) | `catalog.version` (date) |
+| **New models** | Added via migration PR | Appear in next catalog publish |
+| **Limit corrections** | Migration PR | Learned from provider errors + catalog update |
+| **Retirements** | Migration (disabled + tombstone) | Catalog `enabled: false` → force-disable |
+| **Relay models** | Not in catalog | Custom endpoints only (user rows) |
+| **Rollback protection** | N/A | `version < MIN_CATALOG_VERSION` → skipped |
+
+### Custom Models / Relay Models
+
+- **Never** come from catalog. Created via:
+ - `POST /api/media/custom` (generative media / STT)
+ - `POST /api/custom-endpoint` (chat relays)
+ - Declarative config file
+- Bound to `api_keys` row carrying their endpoint (`key_id` on `models` row).
+- `endpoint_scope = 'custom:<base_url_hash>'` distinguishes relays serving same `model_id`.
+- Catalog sync **skips** `platform = 'custom'` and unknown platforms (older binary).
+
+---
+
+## 12. Key Functions
+
+| Function | Purpose |
+|----------|---------|
+| `syncCatalog(force?)` | Fetch → verify → apply (or 304/skip) |
+| `applyCatalog(db, catalog)` | Transactional upsert/insert/delete + quirks |
+| `reapplyCachedCatalog()` | Boot-time re-apply from verified cache |
+| `refreshLicenseStatus()` | Validate license against catalog service |
+| `getSyncState()` | Dashboard status panel |
+| `startCatalogSync(scheduler)` | Register 12h interval + boot delay |
+| `isCatalog(value)` | Structural validation (fail loud on garbled body) |
+| `routableContextWindow(platform, modelId, cw)` | GitHub gpt-4.1 override (8000) |
+
+---
+
+## 13. Tables Touched
+
+| Table | Operation |
+|-------|-----------|
+| `models` | UPSERT chat models (catalog source) |
+| `media_models` | UPSERT image/audio/transcription |
+| `embedding_models` | UPSERT embeddings (full snapshot) |
+| `fallback_config` | Ensure every model has a row |
+| `catalog_model_tombstones` | Respect user deletions |
+| `quirks` + `quirk_targets` | Replace wholesale |
+| `settings` | Persist applied version/tier/json, license status, sync time |
+
+---
+
+## 14. Environment Variables
+
+| Variable | Default | Purpose |
+|----------|---------|---------|
+| `CATALOG_BASE_URL` | `https://api.freellmapi.co` | Catalog service endpoint |
+| `CATALOG_PUBKEY` | Pinned Ed25519 key | Override for self-hosted catalog |
+| `CATALOG_SYNC_DISABLED` | `0` | Kill switch (`1` = disabled) |
+
+---
+
+## 15. Error Handling
+
+| Scenario | Behavior |
+|----------|----------|
+| Network timeout (20s) | Log warning, keep previous catalog |
+| HTTP 304 | `up_to_date`, update `last_sync_ms` |
+| HTTP non-2xx | Error, keep previous catalog |
+| Missing signature | Discard, error |
+| Signature verification FAILED | Discard, **loud error** — "catalog signature verification FAILED — discarding response" |
+| Invalid JSON / shape | Discard, error |
+| Version older than baseline | `skipped_older`, wait for newer catalog |
+| DB unavailable during apply | Transaction rolls back, error, keep previous state |
+| License check unreachable | Keep cached status, sync still runs (tier determined server-side) |
\ No newline at end of file
diff --git a/docs/architecture/06-observability.md b/docs/architecture/06-observability.md
new file mode 100644
index 00000000..bc3381a7
--- /dev/null
+++ b/docs/architecture/06-observability.md
@@ -0,0 +1,290 @@
+# Observability — Deep Dive
+
+> **Source:** `server/src/lib/server-logs.ts`, `server/src/routes/logs.ts`, `server/src/lib/request-log.ts`, `server/src/lib/log-redaction.ts`, `server/src/lib/attempt-trace.ts`
+
+## 1. Server Logs Viewer (`server-logs.ts`)
+
+> **User-facing guide:** the dashboard viewer, its two-tier store, the polling API (`/api/logs`, `/api/logs/counts`, `/api/logs/clear`), environment variables, and the React client implementation are documented in **[`logs/01-server-logs-viewer.md`](../logs/01-server-logs-viewer.md)**. This section covers the internals that guide deliberately omits.
+
+The store keeps a 1000-entry in-memory ring (all levels) plus a persisted `server_logs` SQLite table (warn/error only) behind a single `sinceId`-based id space. For the operator-facing contract (tier capacities, retention, cursor semantics, request/response shape) see the [Server Logs Viewer guide](../logs/01-server-logs-viewer.md#two-tier-store) and its [API contract](../logs/01-server-logs-viewer.md#api-contract).
+
+### Ingest Path
+
+```
+console.log/warn/error/debug/trace
+ │
+ ▼
+lib/log-redaction.ts (console wrapper)
+ ├─ redacts secrets (API keys, tokens, auth headers, etc.)
+ ▼
+server-logs.ts.recordConsoleLine(level, args)
+ ├─ formats args (Error → stack, objects → inspect depth 2)
+ ├─ noise filter + length cap
+ ├─ pushes to ring (splice if > 1000)
+ └─ if level ∈ {warn, error} → persist(entry) → INSERT INTO server_logs
+```
+
+**Reentrancy guards**:
+- `mirroring` — `providerLog()` mirrors to stdout via wrapped console; prevents double-ingest.
+- `persisting` — DB layer can log (busy timeout, permissions); skips persist write but ring still accepts.
+- `seeding` — boot seed probes DB, which can log.
+
+### Structured Provider Logs
+
+```typescript
+providerLog(level, message, { provider, model, event, requestId })
+```
+
+- Recorded with metadata for dashboard filtering **AND** mirrored to stdout (redacted).
+- Used by: Health checker, Cooldown probe, Router, Fallback loop, Catalog sync.
+
+### Boot Preload
+
+On first ingest (or explicit `initServerLogs()` call):
+1. Seed `lastId` from `MAX(id)` in `server_logs`.
+2. Preload latest 200 persisted rows (newest-first, reversed to oldest-first in ring).
+3. Re-stamp any pre-DB ring entries **above** persisted max (IDs unique across tiers).
+
+### Querying & Maintenance
+
+The public query API (`queryLogs({ levels, q, provider, sinceId, limit })`), level-count badges (`levelCounts()`), and clear/reset behavior (`clearLogs()`, `resetServerLogsForTest()`) are specified in the [Server Logs Viewer API contract](../logs/01-server-logs-viewer.md#api-contract). The ID counter is preserved across `clearLogs()` so a dashboard cursor never sees duplicate ids.
+
+### Desktop file logger
+
+The desktop app has no terminal attached, so it tees every console line to a **file logger** (`desktop/src/logger.ts`, added in `90aaa5b`) instead of relying on the in-memory ring: `<data dir>/logs/freeapi.log`, plus one rotated `freeapi.log.1` at 1 MB each. The same redaction wrapper feeds both the ring (server) and the file (desktop), so secrets never reach the file either. The desktop's password-reset code appears here — see the [Install & deploy FAQ](../install.md#where-are-the-logs).
+
+---
+
+## 2. Request Analytics (`request-log.ts`)
+
+### Per-Request Row (`requests` table)
+
+| Column | Source |
+|--------|--------|
+| `platform`, `model_id`, `key_id` | RouteResult |
+| `request_type` | `'chat' \| 'embeddings' \| 'image' \| 'speech' \| 'transcription' \| 'fusion'` |
+| `status` | `'success' \| 'error' \| 'canceled'` |
+| `input_tokens`, `output_tokens`, `total_tokens` | Provider usage + estimates |
+| `latency_ms` | Wall-clock |
+| `ttfb_ms` | First token (content OR reasoning) |
+| `error` | Redacted provider message |
+| `created_at_ms` | Timestamp |
+| `client_info` | User agent, IP hash |
+| `served_model` | Upstream-reported model (observability) |
+| `attempt_error_summary` | Aggregated failure classes for this request |
+
+### Attempt Trail (`request_attempts` table)
+
+One row per dispatched-and-failed attempt:
+
+| Column | Purpose |
+|--------|---------|
+| `request_id` | FK to `requests` |
+| `attempt_ordinal` | 0-based |
+| `platform`, `model_id`, `key_id` | What was tried |
+| `error_class` | `AttemptErrorClass` (auth, rate_limited, upstream_error, ...) |
+| `error_summary` | Redacted provider message (≤200 chars) |
+| `latency_ms` | Per-attempt wall-clock |
+| `ttfb_ms` | Per-attempt TTFB |
+| `input_tokens`, `output_tokens` | Per-attempt estimates |
+
+- Powers `X-Fallback-Trail` / `X-Fallback-Detail` headers.
+- Enables per-request drill-down in dashboard.
+
+### Aggregates (`request_aggregates` materialized view)
+
+Pre-computed rollups for dashboard charts (24h / 7d / 30d / 90d windows):
+- Latency p50 / p95 / p99
+- TTFB p50 / p95
+- Token throughput
+- Success rate
+- Estimated cost savings
+- Per-provider / per-model / per-key breakdowns
+
+---
+
+## 3. Log Redaction (`log-redaction.ts`)
+
+### What Gets Redacted
+
+| Pattern | Replacement |
+|---------|-------------|
+| `Bearer <token>` | `Bearer [REDACTED]` |
+| `x-api-key: <key>` | `x-api-key: [REDACTED]` |
+| `x-goog-api-key: <key>` | `x-goog-api-key: [REDACTED]` |
+| `Authorization: Basic <creds>` | `Authorization: Basic [REDACTED]` |
+| API keys in JSON bodies | `[REDACTED]` |
+| URLs with embedded credentials | `[REDACTED]` |
+| SQLite encryption keys | `[REDACTED]` |
+
+- Single pass at console wrapper → **all** log paths (console, providerLog, boot lines) are redacted.
+- Idempotent: already-redacted text passes through unchanged.
+
+---
+
+## 4. Attempt Tracing (`attempt-trace.ts`)
+
+### AsyncLocalStorage Scope
+
+Each request gets an `AsyncLocalStorage<RequestTrace>` scope:
+
+```typescript
+interface RequestTrace {
+ requestId: string;
+ startedAtMs: number;
+ records: AttemptTraceRecord[];
+}
+
+interface AttemptTraceRecord {
+ platform: string;
+ modelId: string;
+ keyOrdinal: number; // 1-based per request
+ outcome: AttemptOutcome; // 'success' | 'retryable_failure' | 'auth_failure' | 'fatal' | 'hedge_abort'
+ startOffsetMs: number; // relative to request start
+ durationMs: number;
+ errorSummary: string | null; // redacted, ≤200 chars
+}
+```
+
+- `runWithRequestTrace(fn)` wraps the fallback loop.
+- `dispatch()` records start offset, runs attempt, records duration + outcome + summary.
+- `getRequestTrace()` reads current scope (for `X-Fallback-Detail` header).
+
+### Outcomes
+
+| Outcome | Meaning |
+|---------|---------|
+| `success` | Attempt completed, response sent |
+| `retryable_failure` | 429/5xx/timeout/empty → failover |
+| `auth_failure` | 401 → key revalidation triggered |
+| `fatal` | Non-retryable (400, 404 model gone, etc.) |
+| `hedge_abort` | Budget expired mid-attempt (1d2226a) |
+
+---
+
+## 5. Health Endpoint (`/api/health`, `/livez`, `/readyz`)
+
+| Endpoint | Purpose |
+|----------|---------|
+| `GET /livez` | Process alive (k8s liveness) |
+| `GET /readyz` | Ready to serve (DB + at least one healthy provider) |
+| `GET /api/health` | Full status: `{status, degraded, providers: [{platform, healthy, totalKeys, usableKeys, status}], catalog: {version, tier, lastSync}}` |
+
+- Degraded mode reported via `degradation.getDegradationStatus()`.
+- Provider health from `api_keys` statuses (healthy/unknown/rate_limited/invalid/error).
+
+---
+
+## 6. Routing Trace Headers (Every Response)
+
+| Header | Value |
+|--------|-------|
+| `X-Request-ID` | UUID (or client `x-request-id`) |
+| `X-Routed-Via` | `platform/model` (safeHeaderValue) |
+| `X-Fallback-Attempts` | Failed hops before success/exhaustion |
+| `X-Fallback-Trail` | `platform/model keyN=class; …` (max 10, 1KB) |
+| `X-Fallback-Detail` | **Opt-in**: `platform/model keyN=outcome t=start+dur msg=summary; …` (2KB) |
+| `Retry-After` | Seconds until soonest cooldown expiry (429 exhaustions) |
+| `X-FreeLLM-Cache` | `HIT` / `MISS` (response cache) |
+| `X-FreeLLM-Compress` | Compression pipeline metadata |
+
+---
+
+## 7. Dashboard Analytics Pages
+
+| Page | Data Source |
+|------|-------------|
+| **Overview** | `request_aggregates` (24h/7d/30d/90d) |
+| **Models** | Per-model latency, tokens, success rate, cost savings |
+| **Providers** | Per-provider breakdown + quota usage |
+| **Keys** | Per-key health, usage, cooldowns, revalidation history |
+| **Logs** | `server_logs` ring + persisted (filter by level, provider, search) |
+| **Cache** | Hit rate, token savings, LRU stats |
+
+---
+
+## 8. Key Functions (server-logs.ts)
+
+| Function | Purpose |
+|----------|---------|
+| `recordLogEntry(options)` | Single ingest point (console tap, providerLog, boot preload) |
+| `recordConsoleLine(level, args)` | Called by log-redaction wrapper |
+| `providerLog(level, message, meta)` | Structured + stdout mirror |
+| `initServerLogs()` | Force seed/preload (route calls on first poll) |
+| `queryLogs(query)` | Filtered, paginated, cursor-based |
+| `levelCounts()` | Dashboard badges |
+| `currentMaxId()` | Cursor ceiling |
+| `clearLogs()` | Empty both tiers (ID counter preserved) |
+| `resetServerLogsForTest()` | Test cold-start simulation |
+
+---
+
+## 9. Key Functions (request-log.ts)
+
+| Function | Purpose |
+|----------|---------|
+| `logRequest(platform, modelId, keyId, status, inTokens, outTokens, latencyMs, error, ttfbMs, pinnedModelId)` | Insert request row |
+| `persistRequestAttempts(requestId, attempts)` | Batch insert attempt trail |
+| `getRequestAnalytics(window)` | Aggregated rollups for dashboard |
+| `getRequestAttempts(requestId)` | Per-request drill-down |
+
+---
+
+## 10. Environment Variables
+
+| Variable | Default | Purpose |
+|----------|---------|---------|
+| `RESPONSE_CACHE` | `0` | Enable response cache (opt-in) |
+| `REQUEST_MAX_TOKENS_BUDGET` | `0` (off) | Per-request token ceiling |
+| `FALLBACK_TIME_BUDGET_MS` | `45000` | Retry budget (affects exhaustion) |
+| `MAX_CONSECUTIVE_UPSTREAM_FAILS` | `0` (off) | Circuit breaker threshold |
+| `EXPOSE_FALLBACK_DETAIL_HEADER` | `0` | Opt-in X-Fallback-Detail |
+| `COOLDOWN_PROBE_DISABLED` | `0` | Kill switch for probe job |
+
+---
+
+## 11. Privacy & Security
+
+- **No PII in logs**: Request bodies never logged. Only metadata (model, platform, tokens, latency, redacted errors).
+- **Redaction first**: Console wrapper redacts before `server-logs` ever sees the line.
+- **Single-user design**: No multi-tenant log isolation needed.
+- **Local-first**: Logs never leave the machine unless operator configures external log shipper.
+
+---
+
+## 12. Tables
+
+```sql
+-- Server logs (warn/error only, persists across restarts)
+CREATE TABLE server_logs (
+ id INTEGER PRIMARY KEY,
+ level TEXT CHECK(level IN ('trace','debug','info','warn','error')),
+ source TEXT, provider TEXT, model TEXT, event TEXT, request_id TEXT,
+ message TEXT, created_at_ms INTEGER
+);
+
+-- Per-request analytics
+CREATE TABLE requests (
+ id INTEGER PRIMARY KEY,
+ platform TEXT, model_id TEXT, key_id INTEGER,
+ request_type TEXT, status TEXT,
+ input_tokens INTEGER, output_tokens INTEGER, total_tokens INTEGER,
+ latency_ms INTEGER, ttfb_ms INTEGER,
+ error TEXT, created_at_ms INTEGER,
+ client_info TEXT, served_model TEXT, attempt_error_summary TEXT
+);
+
+-- Per-attempt trail
+CREATE TABLE request_attempts (
+ id INTEGER PRIMARY KEY,
+ request_id INTEGER, attempt_ordinal INTEGER,
+ platform TEXT, model_id TEXT, key_id INTEGER,
+ error_class TEXT, error_summary TEXT,
+ latency_ms INTEGER, ttfb_ms INTEGER,
+ input_tokens INTEGER, output_tokens INTEGER,
+ FOREIGN KEY(request_id) REFERENCES requests(id)
+);
+
+-- Materialized aggregates (refreshed periodically)
+CREATE VIEW request_aggregates AS ...;
+```
\ No newline at end of file
diff --git a/docs/architecture/CHANGELOG.md b/docs/architecture/CHANGELOG.md
new file mode 100644
index 00000000..65e8afce
--- /dev/null
+++ b/docs/architecture/CHANGELOG.md
@@ -0,0 +1,223 @@
+# Architecture Domain — Changelog
+
+Doc revision history for `docs/architecture/`, seeded from commits touching architecture-relevant code.
+
+## 2026-08-25
+
+- **docs(architecture): deduplicate `architecture.md` vs `architecture/OVERVIEW.md` intros, clarify `docs/README.md` vs `docs/OVERVIEW.md`** — root `architecture.md` is now the high-level index (what the system is, two-paragraph summary, request-flow diagram, limitations and ToS) with a `See [OVERVIEW.md](OVERVIEW.md) for deep-dives` bridge and no duplicated provider/routing summaries (removed the deep-dive reference table and the Routing/Operational detail sections — those live in `01`/`02` deep-dives); `architecture/OVERVIEW.md` is now the domain scope (Scope + File Index + How deep-dives fit, high-level index cross-link); `docs/README.md` clarified as the user entry point (getting started) vs `docs/OVERVIEW.md` as the domain index (full file map) and verified no dangling `api.md`/`clients.md`/`compression.md` links (`rg "api\.md|clients\.md|compression\.md" docs --glob '!CHANGELOG.md'` — only numbered `01-*.md` hits remain).
+- **docs(observability): dedupe 06-observability.md against logs/01-server-logs-viewer.md** — the operator-facing log viewer, polling API, env vars, and client implementation now live solely in the logs domain; the observability deep-dive keeps the internals (ingest path, structured provider logs, boot preload, schema) and cross-links both ways. Added the desktop `freeapi.log` file-logger note (90aaa5b).
+
+## 2026-08-23 — Routing, Quota & Chain Overhaul
+
+- **547692a** feat(router): make the headroom guardrail thresholds tunable (#989)
+ - `GET/PUT /api/settings/headroom` exposes `rampStart` and `floor` — operators can tune without a code change
+ - Thresholds read once per chain (not per model) to avoid uncached `getSetting` per model per request
+ - `HEADROOM_RAMP_START` / `HEADROOM_FLOOR` in `scoring.ts`, persisted as `routing_headroom_ramp_start` / `routing_headroom_floor`
+ - Out-of-range / non-finite input falls back to defaults rather than silently clamping
+
+- **45a05c7** feat(router): demote models burning through rpd/tpd windows (#1001)
+ - `rateWindowHeadroomFactor(usedFraction, opts)` — same tunable ramp driven by live rpm/rpd/tpm/tpd utilization instead of monthly tokens
+ - `modelWindowUsedFraction()` in `ratelimit.ts`: one grouped scan of `rate_limit_usage` + one `api_keys` read, memoised for 5s (`WINDOW_USAGE_TTL_MS`)
+ - Router takes `Math.min(monthlyHeadroom, windowHeadroom)` — the worse of the two, never their product
+ - Chosen key = eligible key with the MOST headroom (the one the router would pick next)
+
+- **c4c0221** feat(router): add a least-remaining key selection strategy (#930)
+ - New `key_selection_strategy` setting (`auto` / `least-remaining`), independent of the routing strategy
+ - `orderKeysByRemainingQuota()` re-sorts by observed remaining quota — roomiest key first
+ - Skips account-scoped pools (`<platform>::account`) where every key reports the same number
+ - Reads quota headroom through cached `getKeyQuotaHeadroom()`; unobserved keys get neutral 0.5
+
+- **f9af5f7** feat(router): add an opt-in peak-hours routing adjustment (#909)
+ - Off by default; configurable window (`startHour`/`endHour`) and IANA `timezone` read via `Intl`
+ - `peakAdjustedWeights()` shifts 60% of speed weight onto reliability during the window
+ - Exempt strategies: `fastest`, `reliable` (ends of the axis), plus `priority`/`custom` (operator's explicit choice)
+ - Dashboard labels adjusted weights from the `adjusted` flag
+
+- **e852ff1** fix(fallback): make a fallback chain mean itself, empty or not (#1023)
+ - A profile is now authoritative whenever one is active — empty chain reads as "catalog, nothing turned on yet"
+ - Saving upserts into the chain; routing follows the same rule (empty active chain routes nothing)
+ - Playground offers every custom chain as its `auto:<name>` id
+
+- **b3bf20f** feat(fallback): let a fallback chain be built by hand and stay that way (#1004)
+ - Chains can start empty; `auto_include_new_models` flag keeps catalog sync from refilling curated chains
+ - Routing table gets enable-all / disable-all
+
+- **8bb2004** feat(fallback): add a named chain manager to the Fallback page (#988)
+ - Collapsed accordion for creating, renaming, deleting named fallback chains, showing the `auto:<name>` id clients send
+
+- **d03021e** fix(cache): normalize default-valued sampling params in the cache key (#901)
+ - `top_p: 1`, `n: 1`, zero penalties → normalized to `undefined`, sharing a cache entry with requests that omit them
+ - Cache key version bumped to **v4**; `reasoning_effort` and `compression` added to the key
+
+- **a9b8774** feat(server): add database backups with safe restore (#999)
+ - Backups service, routes, migration, collapsed Backups section under Keys
+ - Auth tables excluded; restore checks schema + encryption key fingerprint, runs in one transaction with pre-restore snapshot
+
+## 2026-08-23 — Domain Expansion
+
+- **Commit (this PR)**: `docs(architecture): expand into deep-dive domain`
+ - Created `docs/architecture/` domain folder with 6 deep-dive docs + `OVERVIEW.md` + `CHANGELOG.md`
+ - Root `docs/architecture.md` retained as high-level index, updated with cross-refs
+ - `docs/OVERVIEW.md` index updated with architecture/ domain row
+
+## 2026-06-xx — Observability & Logging
+
+- **74df985** Server log viewer in the dashboard, under an Analytics nav menu (#993)
+ - Added `server-logs.ts`: two-tier store (ring buffer + persisted warn/error)
+ - Added `GET /api/logs` API with cursor pagination, level/provider/search filters
+ - Added log redaction at console wrapper (API keys, tokens, auth headers)
+ - Added request analytics (`requests`, `request_attempts` tables) + aggregates view
+ - Added attempt tracing via AsyncLocalStorage for `X-Fallback-Detail` header
+
+## 2026-06-xx — Routing & Scoring Fixes
+
+- **f08e17c** fix(router): context-window safety margin against chars/4 under-counting (#956)
+ - Routing token estimate now caps reserved OUTPUT at 2000 tokens (was full max_tokens)
+ - Prevents falsely excluding entire free pool on huge client max_tokens
+ - Input still counted in full; upstream 429/413 handled by retry loop
+
+- **a9895bc** Fix a batch of routing, streaming, and deployment quick wins (#941)
+ - Multiple small fixes across router, proxy, quota, catalog sync
+
+- **4270280** fix(router): warn when MODEL_ROUTING_OVERRIDES will never apply (#738) (#857)
+ - Validates override model IDs exist in catalog at save time
+
+- **1fea8d5** fix(fallback): reset model-failure windows between tests and thread an injectable now (#856)
+ - Testability improvements for model failure benching
+
+## 2026-05-xx — Degraded Mode & Failover v2
+
+- **f412e97** feat(server): degraded-mode state machine (#904) (#906)
+ - New `degradation.ts`: healthy-provider ratio tracker with hysteresis
+ - Enters degraded when ratio < 50% for 60s (configurable), exits after 120s above
+ - In degraded: bandit exploration disabled, sticks to scored healthy providers
+ - Health endpoint + dashboard report state
+
+- **1d2226a** feat(fallback): abort stalled attempts when the retry time budget expires (hedging) (#828)
+ - `abortInFlight()` cancels upstream fetch via AbortController when wall-clock budget expires mid-attempt
+ - `HedgeAbortError` = non-provider-health → no cooldown/penalty
+ - Renders `timedOut` exhaustion with budget note
+ - Streaming surfaces call `ctx.disarmHedge()` on first byte
+
+- **8cb75ac** feat(proxy): opt-in X-Fallback-Detail header with per-hop failover timings (#792)
+ - `X-Fallback-Detail`: `platform/model keyN=outcome t=start+dur msg=summary; …`
+ - Opt-in via `EXPOSE_FALLBACK_DETAIL_HEADER=1` or setting
+ - 2KB budget, 120 chars per message, max 10 hops
+
+- **a961d93** fix(routing): fail over on a relay's bare "safe"/"unsafe" classification output (#809) (#830)
+ - Detects bare classification words from relay models (OpenCode Zen)
+ - Treats as empty completion → fail over with `skipBench: true` when `finish_reason=length`
+
+## 2026-04-xx — Routing Enhancements
+
+- **c3f538e** feat(routing): per-model weight overrides via MODEL_ROUTING_OVERRIDES (#747)
+ - `MODEL_ROUTING_OVERRIDES='{"model-id": {"weight": 0.5}}'` scales final effective score
+ - Demotes without disabling; priority chain can still select
+
+- **1e675cc** feat(routing): fold community reliability priors into the Beta posterior (#744)
+ - Opt-in `routing_community_prior_enabled` folds de-poisoned aggregated counts from other instances
+ - Capped at 50 effective samples per prior so local evidence dominates
+
+- **96da9ec** feat(routing): add an exploration toggle for unmeasured models (#731)
+ - `routing_explore_enabled=1` gives unmeasured models (<5 samples) 10% guaranteed chance to be tried first
+ - Prevents starvation by prior-heavy rivals
+
+- **fc4e47d** fix(router): let timeouts cost speed, and write an observed speed_rank (#619)
+ - Timeouts now feed speed axis: capped latency (120s) + zero tokens → drags throughput down
+ - TTFB sample at capped latency → past TTFB_WORST_MS → no latency credit
+ - Periodic writeback of observed speed_rank (1..10) for models with ≥20 speed samples
+
+- **8ad9010** Fix routing chain semantics
+ - Dense ranking + penalty fixes for priority strategy
+
+## 2026-03-xx — Quota & Cooldown Engine
+
+- **076fa69** feat: Premium live catalog — signed sync, license keys, self-serve billing
+ - Live catalog tier (2-3 day refresh) for premium licenses
+ - Monthly snapshot tier (30-day trail) for free installs
+ - Ed25519 signed catalogs, pinned public key, boot re-apply from cache
+ - Model-age gate (30 days), premium/free tiers, migration seeding vs hosted catalog
+
+- **75f0498** fix: default output floor on Cloudflare + pace the health probe pass (#553) (#644)
+ - Health probe pacing, Cloudflare output floor
+
+- **8c9cf94** fix(ratelimit): escalate NULL-limit providers via hit-count heuristic (#392)
+ - Providers with no published RPD/TPD: 2+ 429s in 1h → "effectively daily exhausted"
+ - Escalates but capped at 10 min (UNKNOWN_LIMIT_MAX_COOLDOWN_MS)
+ - Reversible: success clears hit window
+
+- **bfcef93** fix: rate ledger drift, token double-count, penalty decay, error sanitization
+ - Fixed in-flight lease accounting, penalty decay, error redaction
+
+- **67006c5** feat(routing): honor upstream Retry-After when benching a key
+ - Retry-After honored as floor, capped at 24h, source = 'authoritative'
+
+- **2180ead** filter v1 models by connected providers
+ - `/v1/models` shows availability per provider key status
+
+- **12166bd** feat(router): skip models whose tpm_limit can't fit the request
+ - Pre-check TPM against estimated tokens
+
+- **438eaa2** feat(proxy): agent turn integrity — stream validation, tool-dialect rescue, sticky-session fixes (#231 audit)
+ - Stream validation: headers held until first payload
+ - Tool dialect rescue: inline tool calls → structured tool_calls
+ - Sticky sessions: 30min TTL keyed by first user message hash
+
+- **940986c** refactor(gateway): unify the four provider fallback loops, fix drift (#482 base) (#483)
+ - Single `fallback-loop.ts` for `/v1/chat/completions`, `/v1/responses`, `/v1/messages`, `/v1/completions`
+ - Eliminated drift in cooldowns, exhaustion rendering, attempt trail
+
+- **e57a0f8** feat(gateway): fallback hardening pack (401 rotation, rich exhaustion, daily-quota bench, truncation policy, retry budget, usage fallback) (#484)
+ - 401 → immediate key revalidation + 5min bench
+ - Daily quota exhaustion → bench until UTC midnight
+ - Retry time budget (45s default)
+ - Rich exhaustion bodies with attempt trail
+
+## 2026-02-xx — Catalog & Provider Quota
+
+- **2410f87** feat(catalog-sync): re-apply the cached catalog on every boot
+ - Solves drift: migrations re-assert baseline, boot sync 304s, cached doc re-applied
+
+- **03480d8** feat(router): enforce provider-wide daily request caps (#162)
+ - OpenRouter 1000/day (50/day <10 credits), ModelScope 2000/day
+ - Provider-wide RPM: NVIDIA NIM 40 RPM
+
+- **a2d2a54** fix(routing): multi-key quota fixes for #470, #454, #456, #453 (#479)
+ - Pooled monthly budget: `monthly_token_budget × usableKeyCount`
+ - Per-key scoring for key selection within model
+
+## 2026-01-xx — Early Architecture
+
+- **413b5e4** feat(router): analytics-driven bandit routing with weighted axes
+ - Thompson sampling bandit with reliability/speed/intelligence axes
+ - Guardrails: headroomFactor, rateLimitFactor
+ - Strategy presets: balanced, smartest, fastest, reliable, custom
+
+- **dd46daf** fix(router): escalating cooldown for repeated 429s (credits @meliani) (#92)
+ - Ladder: 2m → 10m → 1h → 24h per model+key over 24h window
+
+- **7cc751a** fix: rate-limit and cooldown state is lost on restart (#88)
+ - Persisted cooldowns to SQLite (`rate_limit_cooldowns` table)
+
+- **57541ea** fix(router): treat provider 400 errors as retryable (#80)
+ - 400 → failover instead of hard error
+
+- **a27dc42** fix: non-decryptable keys can block routing (#85)
+ - Decrypt errors → skip key, don't block chain
+
+- **8aea92c** fix(router): treat 404 model-removed as retryable (#76)
+ - 404 → fail over to next model
+
+- **839fe5a** fix(router): treat 413 Payload Too Large as retryable (#64)
+ - 413 → fail over
+
+- **2121550** feat(proxy): expose 'auto' as a virtual model in /v1/models (#62)
+ - `model: "auto"` or omitted → router picks
+
+- **9b97219** feat(router): exhaust all keys before falling back + tests (#42)
+ - Round-robin all keys for a model before next model
+
+## 2025 — Foundation
+
+- **04e1503** Initial release of FreeLLMAPI
+ - Basic router, rate limiting, provider adapters, SQLite storage
\ No newline at end of file
diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.md
new file mode 100644
index 00000000..3ad887c9
--- /dev/null
+++ b/docs/architecture/OVERVIEW.md
@@ -0,0 +1,26 @@
+# Architecture Domain — Overview & File Index
+
+## Scope
+
+This domain holds the implementation deep-dives for FreeLLMAPI's server-side architecture. Each file expands one subsystem with source pointers, scoring formulas, state machines and commit-tagged history. For the high-level summary — what the system is, how a request flows, honest limitations and the provider ToS review — see the high-level index [`architecture.md`](../architecture.md).
+
+## File Index
+
+| File | Scope |
+|------|-------|
+| [`01-routing-and-bandit-scoring.md`](01-routing-and-bandit-scoring.md) | Thompson-sampling bandit router, reliability posteriors, factor weights (reliability/speed/intelligence/headroom/rate-limit), tunable headroom thresholds (#989), rate-window headroom factor (#899), peak-hours adjustment (#909), least-remaining key selection (#930), 10% explore floor, fallback loop with per-model exhaustion diagnostics, cache key v4 |
+| [`02-quota-and-cooldown-engine.md`](02-quota-and-cooldown-engine.md) | RPM/RPD/TPM/TPD accounting, concurrency leases, cooldown ladder (90s → 2m → 10m → 1h → 1d), probe-based early recovery, back-off from error body/header (#798), provider-quota pooling (openrouter::free, google::project), 5s window-utilization snapshot (#899) |
+| [`03-streaming-pipeline.md`](03-streaming-pipeline.md) | SSE-only streaming (zero WebSockets), OpenAI chat/completions, Anthropic Messages tool_use block rendering, Gemini `/v1beta`, Responses API shim, error handling mid-stream |
+| [`04-degraded-mode-and-failover.md`](04-degraded-mode-and-failover.md) | Degraded-mode state machine (f412e97), hedging/abort on retry budget expiry (1d2226a), X-Fallback-Detail header (8cb75ac), bare safe/unsafe classification failover (a961d93) |
+| [`05-catalog-sync.md`](05-catalog-sync.md) | Live signed catalog sync from freellmapi.co, model-age gate (30 days), premium/free tiers, migration seeding vs hosted catalog |
+| [`06-observability.md`](06-observability.md) | Observability internals: server-logs ingest path, structured provider logs, boot preload, request analytics, log redaction, attempt tracing, health/routing-trace headers, desktop `freeapi.log` file logger. The operator-facing log viewer and polling API live in [logs/](../logs/01-server-logs-viewer.md). |
+| [`CHANGELOG.md`](CHANGELOG.md) | Doc revision history for this domain, seeded from architecture-relevant commits |
+
+## How deep-dives fit
+
+The root [`architecture.md`](../architecture.md) stays the high-level index (two-paragraph system summary, request-flow diagram, limitations and ToS). The files above are the deep-dives: start with `01` (bandit scoring & routing) and `02` (quota & cooldown) for the router core, then `03`/`04` for streaming and degraded-mode failover, `05` for catalog sync and `06` for observability internals. The operator-facing logs viewer and polling API are documented separately in [`logs/`](../logs/01-server-logs-viewer.md) and cross-linked from `06`.
+
+## Navigation
+
+- ← [Documentation root](../README.md)
+- ↑ [High-level architecture index](../architecture.md)
\ No newline at end of file
diff --git a/docs/clients.md b/docs/clients/01-agent-clients.md
similarity index 98%
rename from docs/clients.md
rename to docs/clients/01-agent-clients.md
index f46ab645..6f1ea15f 100644
--- a/docs/clients.md
+++ b/docs/clients/01-agent-clients.md
@@ -1,6 +1,6 @@
# Clients & coding agents
-[← Back to README](../README.md) · [Documentation index](README.md)
+[← Back to README](../README.md) · [Documentation index](../README.md)
- [OpenAI-compatible clients](#openai-compatible-clients)
- [Coding agents](#coding-agents)
@@ -28,6 +28,7 @@ Use the generator instead of hand-editing a client configuration:
export FREELLMAPI_API_KEY=<unified-key> # or pass --api-key on each command
npx freellmapi setup-claude --url http://localhost:3001 --dry-run
npx freellmapi setup-claude --url http://localhost:3001
+npx freellmapi setup-dsh --url http://localhost:3001 --api-key <unified-key>
```
`--dry-run` prints a diff. Real writes merge with the existing configuration
diff --git a/docs/clients/CHANGELOG.md b/docs/clients/CHANGELOG.md
new file mode 100644
index 00000000..2fc7a489
--- /dev/null
+++ b/docs/clients/CHANGELOG.md
@@ -0,0 +1,12 @@
+# Changelog
+
+Doc revision history for `docs/clients/`. Most recent first.
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `1a0ce48` | 2026-08-23 | feat(cli): setup-dsh — configure DeepSeek Harness in one command (#995) |
+| `36eea7b` | 2026-07-27 | cli: publish freellmapi to npm (#672) |
+| `19168ac` | 2026-07-27 | Add end-to-end coding-agent compatibility suite (#629) |
+| `90d291d` | 2026-07-27 | Split README into focused docs pages (#627) |
+
+> Older history for this content is available via `git log --follow -- docs/clients.md`.
\ No newline at end of file
diff --git a/docs/clients/OVERVIEW.md b/docs/clients/OVERVIEW.md
new file mode 100644
index 00000000..e2b1a28f
--- /dev/null
+++ b/docs/clients/OVERVIEW.md
@@ -0,0 +1,21 @@
+# Clients Domain
+
+## Scope
+
+This domain covers all integration guides for connecting coding agents, CLI tools,
+and OpenAI-compatible clients to FreeLLMAPI. It documents the automated setup
+generators, manual configuration recipes, URL tokens for headerless clients, the
+Ollama emulation surface, the MCP server interface, and the Context Handoff
+feature for mid-conversation model switches.
+
+## File index
+
+| File | Description |
+| --- | --- |
+| [01-agent-clients.md](01-agent-clients.md) | Complete reference for coding-agent generators (`setup-claude`, `setup-codex`, `setup-dsh`, etc.), manual base URLs, Ollama clients, headerless URL tokens, MCP server, VS Code autocomplete, and Context Handoff. |
+
+## Related
+
+- [../api/](../api/) — OpenAI-compatible `/v1` and Anthropic Messages API reference.
+- [../compression/](../compression/) — Prompt compression that agents benefit from automatically.
+- [../i18n/zh-CN/docs/clients/](../i18n/zh-CN/docs/clients/) — Simplified Chinese mirror (when translated).
\ No newline at end of file
diff --git a/docs/compression.md b/docs/compression/01-compression-pipeline.md
similarity index 93%
rename from docs/compression.md
rename to docs/compression/01-compression-pipeline.md
index ff942a8e..1657a342 100644
--- a/docs/compression.md
+++ b/docs/compression/01-compression-pipeline.md
@@ -1,6 +1,6 @@
# Prompt compression
-[← Back to README](../README.md) · [Documentation index](README.md) · [API reference](api.md)
+[← Back to README](../README.md) · [Documentation index](../README.md) · [API reference](../api/01-rest-api.md)
Long coding-agent sessions repeatedly send system prompts, file reads, command output, and tool schemas. FreeLLMAPI can shrink that request context before cache lookup, token budgeting, and routing, so the router sees the reduced estimate and more small-context models remain eligible. Provider responses are never rewritten.
@@ -49,6 +49,11 @@ When `autoTriggerEstTokens` is configured and an uncompressed request crosses th
The pipeline is fail-open. Every engine runs independently, and its output is discarded if it grows the request, throws an exception, or fails a fidelity gate. The gate requires:
+> **Perf note (cf0c216):** The protected-span check now early-exits when a span is
+> already known to be preserved, avoiding redundant work in the per-line hot path.
+
+- all distinct numeric literals and diff hunks to survive;
+
- all distinct numeric literals and diff hunks to survive;
- every explicit constraint, security instruction, and error line to survive;
- at least 90% of JSON keys to survive;
diff --git a/docs/compression/CHANGELOG.md b/docs/compression/CHANGELOG.md
new file mode 100644
index 00000000..f457215e
--- /dev/null
+++ b/docs/compression/CHANGELOG.md
@@ -0,0 +1,10 @@
+# Changelog
+
+Doc revision history for `docs/compression/`. Most recent first.
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `cf0c216` | 2026-08-23 | perf(compression): early-exit protected-span check in the per-line hot path (#990) |
+| `878fb89` | 2026-07-27 | Add prompt and context compression pipeline (#628) |
+
+> Older history for this content is available via `git log --follow -- docs/compression.md`.
\ No newline at end of file
diff --git a/docs/compression/OVERVIEW.md b/docs/compression/OVERVIEW.md
new file mode 100644
index 00000000..376503a9
--- /dev/null
+++ b/docs/compression/OVERVIEW.md
@@ -0,0 +1,21 @@
+# Compression Domain
+
+## Scope
+
+This domain covers the prompt and context compression pipeline that reduces request
+size before cache lookup, token budgeting, and routing. It documents the
+compression modes (lossless, standard, aggressive), the individual engines,
+preservation guarantees and fidelity gates, per-request controls, custom
+tool-output filters, and the statistics/preview APIs.
+
+## File index
+
+| File | Description |
+| --- | --- |
+| [01-compression-pipeline.md](01-compression-pipeline.md) | Complete reference for compression modes, engines, fidelity gates, adaptive triggering, tool-output filters, settings APIs, and MCP tool access. |
+
+## Related
+
+- [../api/](../api/) — API reference showing `X-FreeLLM-Compress` response header.
+- [../clients/](../clients/) — Coding agents that benefit from automatic compression.
+- [../i18n/zh-CN/docs/compression/](../i18n/zh-CN/docs/compression/) — Simplified Chinese mirror (when translated).
\ No newline at end of file
diff --git a/docs/deployment/01-docker.md b/docs/deployment/01-docker.md
new file mode 100644
index 00000000..0a4729e5
--- /dev/null
+++ b/docs/deployment/01-docker.md
@@ -0,0 +1,105 @@
+# Docker
+
+The production image, the Compose quickstart, and everything about running FreeLLMAPI in a container: persistence, ports, health, and the networking gotchas.
+
+- [The image](#the-image)
+- [Compose quickstart](#compose-quickstart)
+- [Ports & LAN access](#ports--lan-access)
+- [Volumes & persistence](#volumes--persistence)
+- [Healthcheck](#healthcheck)
+- [Non-root runtime](#non-root-runtime)
+- [Why better-sqlite3 is compiled from source](#why-better-sqlite3-is-compiled-from-source)
+- [Troubleshooting: container cannot reach providers (#733)](#troubleshooting-container-cannot-reach-providers-733)
+
+## The image
+
+FreeLLMAPI publishes a single production image containing the Express server and the built React dashboard:
+
+```bash
+docker pull ghcr.io/tashfeenahmed/freellmapi:latest # or pin a release, e.g. :v1.2.3
+```
+
+Published tags: `latest` (default branch), `v*.*.*` (git release tags), and `sha-<commit>`. The image is multi-arch (`linux/amd64` + `linux/arm64`, so it runs on a Raspberry Pi).
+
+Build shape ([Dockerfile](../../Dockerfile)):
+
+- Three stages on the `node:20-bookworm-slim` base (`deps` → `build` → `runtime`); only already-built artifacts are copied into the runtime stage.
+- The runtime sets `NODE_ENV=production`, `PORT=3001`, and `FREELLMAPI_INSTALL_METHOD=docker`; the process is `node server/dist/index.js`.
+- A `FREELLMAPI_COMMIT_SHA` ARG/ENV pair sits deliberately after all `COPY` layers: the SHA changes every commit, and placing it higher would invalidate the layer cache for the whole image on each build.
+- The runtime also copies `desktop/package.json` (a 400-byte manifest) so a container install can name its own release version (#703).
+- `.dockerignore` keeps secrets and local state out of the build context: `.env`, `.env.*`, `*.db` (+ `-wal`/`-shm` sidecars), `.encryption-key`, and `server/data` never enter an image.
+
+## Compose quickstart
+
+Prerequisites: Docker, Docker Compose, OpenSSL. macOS/Linux:
+
+```bash
+git clone https://github.com/tashfeenahmed/freellmapi.git
+cd freellmapi
+
+# Generate an encryption key for at-rest key storage
+ENCRYPTION_KEY="$(openssl rand -hex 32)"
+printf "ENCRYPTION_KEY=%s\nPORT=3001\n" "$ENCRYPTION_KEY" > .env
+
+docker compose up -d
+```
+
+Windows PowerShell variant and a curl one-liner bootstrap live in [`docs/install.md`](../install.md#docker-compose). Then follow the logs:
+
+```bash
+docker compose logs -f freellmapi
+```
+
+Open http://localhost:3001, add provider keys on the **Keys** page, and grab your unified API key from that page's header — that key is what your OpenAI SDK points at.
+
+## Ports & LAN access
+
+The compose file publishes `"${HOST_BIND:-127.0.0.1}:${PORT:-3001}:3001"`. By default the dashboard/API is reachable only from the machine running Docker; to reach it from other devices (e.g. a Raspberry Pi at `http://192.168.1.x:3001`):
+
+```bash
+HOST_BIND=0.0.0.0 docker compose up -d
+```
+
+Only do this on a trusted network — the proxy is single-user and guarded only by the unified API key.
+
+## Volumes & persistence
+
+SQLite data lives in the named volume `freellmapi-data`, mounted at `/app/server/data`. Keep the same `.env` `ENCRYPTION_KEY` and the same volume when upgrading, because provider keys are encrypted at rest. If your host only persists one specific directory, point the database there with `FREEAPI_DB_PATH=/that/path/freellmapi.db`.
+
+The Dockerfile declares **no** `VOLUME` for `/app/server/data` on purpose. Persistence is the deployment's job — the compose file maps the named volume there, and plain `docker run` takes `-v`. Declaring it in the image instead would create an ANONYMOUS volume on every container that doesn't override it: PaaS runtimes that build from the Dockerfile (Railway, Render, Coolify, Dokploy, CapRover) would then either refuse the image or silently hand each redeploy a fresh empty volume, and the declaration would also shadow a bind mount made at the same path.
+
+See [02-updates-and-backup.md](02-updates-and-backup.md) for backups of this volume.
+
+## Healthcheck
+
+Both the Dockerfile and the compose file define the same probe: a Node one-liner fetching `http://127.0.0.1:<port>/api/ping` inside the container, exiting non-zero unless the response is OK.
+
+| Setting | Value |
+| --- | --- |
+| Interval | 30s |
+| Timeout | 5s |
+| Start period | 15s |
+| Retries | 3 |
+
+## Non-root runtime
+
+The runtime stage switches to `USER node` before `EXPOSE 3001`. The server data directory `/app/server/data` is created and chowned to `node:node` during the build so the running user owns it; all copied artifacts carry `--chown=node:node`.
+
+## Why better-sqlite3 is compiled from source
+
+`better-sqlite3` is a native module. On slim images without a usable prebuilt binary — notably the `linux/arm64` leg under QEMU — node-gyp compiles it from source, which needs Python and a C++ toolchain. The build stages therefore install `python3 make g++` via apt, and the runtime image copies the already-compiled `node_modules` instead, keeping the shipped image free of build tooling. (This toolchain was added by #143 after builds broke without it.)
+
+A related packaging subtlety: npm nests some production packages under the workspace instead of hoisting them (`undici` lives at `server/node_modules/undici`). Skipping the `server/node_modules` copy shipped images where the HTTP(S) proxy dispatcher failed to load and every request silently went direct (#550, fixed in c6589ff).
+
+## Troubleshooting: container cannot reach providers (#733)
+
+Providers unreachable from the container, but fine from the host? A container has its own network stack, so two things that work on your machine do not carry over:
+
+- **A proxy on `127.0.0.1` is not your machine.** Inside the container, loopback is the container itself. If you reach providers through a proxy client on the host (Clash, v2rayN, sing-box, a corporate proxy), point FreeLLMAPI at the host instead: `PROXY_URL=socks5h://host.docker.internal:7890`. The bundled `docker-compose.yml` maps `host.docker.internal` to the host gateway via `extra_hosts`, so this works on plain Linux Docker as well as Docker Desktop. The proxy also has to accept connections from outside loopback (in Clash, `allow-lan: true`). More detail in [03-outbound-proxies.md](../env/03-outbound-proxies.md#docker-127001-is-the-container).
+- **An IPv6-only host needs IPv6 enabled in Docker.** The default bridge network is IPv4-only, so on a host with no IPv4 route the container cannot reach anything, DNS included. Enable it in `/etc/docker/daemon.json` with `"ipv6": true`, `"ip6tables": true` and a `"fixed-cidr-v6"` range, then restart Docker.
+
+To see which case you are hitting, ask the container directly:
+
+```bash
+docker compose exec freellmapi node -e "fetch('https://generativelanguage.googleapis.com/').then(r=>console.log('ok',r.status)).catch(e=>console.log('fail',e.cause?.code||e.message))"
+```
diff --git a/docs/deployment/02-updates-and-backup.md b/docs/deployment/02-updates-and-backup.md
new file mode 100644
index 00000000..45d5c127
--- /dev/null
+++ b/docs/deployment/02-updates-and-backup.md
@@ -0,0 +1,104 @@
+# Updates and backup
+
+Keeping a Docker deployment current, protecting the SQLite data volume, and making installs reproducible with declarative configuration.
+
+- [Upgrading the container](#upgrading-the-container)
+- [Dashboard update checker (#635 / #703)](#dashboard-update-checker-635--703)
+- [Backing up the SQLite data volume](#backing-up-the-sqlite-data-volume)
+- [Declarative config & catalog controls (#f4cd7b4)](#declarative-config--catalog-controls-f4cd7b4)
+
+## Upgrading the container
+
+Track `:latest` (or pin a release tag) and re-create the container on a new image:
+
+```bash
+docker compose pull && docker compose up -d
+```
+
+Two invariants across any upgrade:
+
+1. **Keep the same `.env` `ENCRYPTION_KEY`.** Provider keys are encrypted at rest; a changed key makes every stored key undecryptable. See [02-security-and-keys.md](../env/02-security-and-keys.md).
+2. **Keep the same data volume** (`freellmapi-data` at `/app/server/data`). Migrations run idempotently on boot.
+
+The desktop dashboard's update dialog shows this exact command for Docker installs (see below).
+
+## Dashboard update checker (#635 / #703)
+
+Settings carries a single update surface: it reports the running release, lists recent commits, and — when the installation is Docker — prints the `docker compose pull && docker compose up -d` upgrade command. Relevant controls:
+
+| Variable | Default | Purpose |
+| --- | --- | --- |
+| `FREELLMAPI_UPDATE_CHECK` | Enabled | Set to `off` to hide the checker from Settings and prevent Git discovery or outbound update-check requests. This also switches off the automatic release reminder, a separate dashboard setting (Settings > General) that is off until turned on there. |
+| `FREELLMAPI_UPDATE_GITHUB_TOKEN` | Empty (anonymous checks) | Optional token used only for update checks against GitHub. Use a narrowly scoped token only if higher rate limits are needed; generic `GITHUB_TOKEN` values are intentionally ignored. |
+
+Two build-level facts back the version display: `FREELLMAPI_INSTALL_METHOD=docker` tells the server which upgrade path to suggest, and the runtime image copies `desktop/package.json` — where the release version lives, since `server/package.json` tracks the workspace — as a ~400-byte manifest so a container install can name its own version (#703).
+
+## Backing up the SQLite data volume
+
+Everything that matters lives in one place: the named volume `freellmapi-data` mounted at `/app/server/data`, containing the SQLite database (`freeapi.db`, or wherever `FREEAPI_DB_PATH` points), its `-wal`/`-shm` sidecars, and the `.encryption-key` file for dev-style installs. Back up all of it together, and keep the matching `ENCRYPTION_KEY` safe — without it, backed-up provider keys are undecryptable ciphertext.
+
+Built-in encrypted backups (recommended, zero downtime). FreeLLMAPI can push an encrypted backup of the live database on a schedule:
+
+```env
+FREEAPI_DB_BACKUP_PATH=/app/server/data/freellmapi.db.backup
+# or:
+FREEAPI_DB_BACKUP_URL=https://example.com/freellmapi.db.backup
+FREEAPI_DB_BACKUP_TOKEN=optional-bearer-token
+FREEAPI_DB_BACKUP_KEY=64-char-hex-backup-key # defaults to ENCRYPTION_KEY
+FREEAPI_DB_BACKUP_INTERVAL_MS=300000
+```
+
+Restore semantics: when the configured database file is missing at startup, FreeLLMAPI restores the backup before migrations run; while the server is running it uploads a fresh encrypted backup periodically. On hosts with ephemeral disks this is the primary protection.
+
+Volume snapshot (plain Docker approach). The standard pattern works unchanged:
+
+```bash
+docker run --rm -v freellmapi-data:/data -v "$PWD":/backup alpine \
+ tar czf /backup/freellmapi-data.tar.gz -C /data .
+```
+
+Because the server keeps the database open (WAL mode), prefer doing this while the container is stopped (`docker compose stop`) so you capture a quiescent copy, then `docker compose start`.
+
+## Declarative config & catalog controls (#f4cd7b4)
+
+For repeatable Docker/server installs, FreeLLMAPI can apply a JSON config on every boot. Set `FREEAPI_CONFIG_PATH=/path/to/freellmapi.config.json`, or put the same JSON inline in `FREEAPI_CONFIG_JSON`. The application is idempotent: existing keys, custom providers, model edits, fallback rows, and routing settings are updated instead of duplicated, after migrations, on every boot.
+
+```json
+{
+ "keys": [
+ { "platform": "groq", "key": "gsk_...", "label": "main" },
+ { "platform": "google", "key": "AIza...", "enabled": true }
+ ],
+ "customProviders": [
+ {
+ "baseUrl": "http://host.docker.internal:11434/v1",
+ "label": "Ollama",
+ "models": [
+ { "model": "llama3.1:8b", "displayName": "Local Llama", "supportsTools": true }
+ ]
+ }
+ ],
+ "models": [
+ {
+ "platform": "groq",
+ "modelId": "llama-3.3-70b-versatile",
+ "displayName": "Llama 3.3 70B",
+ "supportsTools": true,
+ "fallbackEnabled": true
+ }
+ ],
+ "routing": { "strategy": "balanced" }
+}
+```
+
+If two custom endpoints serve the same model id, add `"endpoint"` to a `models` or `fallback` entry to say which one you mean — the endpoint's URL, or the short handle the dashboard shows next to it. Without it, an entry that matches more than one endpoint is rejected rather than applied to an arbitrary one:
+
+```json
+{
+ "models": [
+ { "platform": "custom", "modelId": "deepseek-v3.1", "endpoint": "https://relay-b.example.com/v1", "enabled": false }
+ ]
+}
+```
+
+Catalog side: an install keeps its model roster current from the signed catalog feed (the full catalog is listed at freellmapi.co/models), so no manual roster maintenance is required alongside upgrades.
diff --git a/docs/deployment/CHANGELOG.md b/docs/deployment/CHANGELOG.md
new file mode 100644
index 00000000..f35ad360
--- /dev/null
+++ b/docs/deployment/CHANGELOG.md
@@ -0,0 +1,17 @@
+# Changelog
+
+Revision history for `docs/deployment/`, listing the commits that shaped the Docker operations and maintenance behavior documented here. Most recent first.
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `a9895bc` | 2026-08-20 | Fix batch of routing, streaming, deployment quick wins (#941). |
+| `29eb340` | 2026-08-06 | feat: in-dashboard update checker, single Settings update surface (#635). |
+| `5d51fec` | 2026-08-03 | docs(docker): why a container cannot reach providers the host can (#737) — source of the troubleshooting section in [01-docker.md](01-docker.md). |
+| `5e5da26` | 2026-08-02 | fix(version,desktop): serve release version to every install (#718). |
+| `c6589ff` | 2026-07-19 | fix(docker): copy server/node_modules into runtime so proxy loads undici (#550). |
+| `a66f752` | 2026-07-06 | security: first-run setup code, key file out of DB, CSV export hardening (#477). |
+| `f4cd7b4` | 2026-06-27 | catalog controls, persistence backup, declarative config — basis for the config/backup sections in [02-updates-and-backup.md](02-updates-and-backup.md). |
+| `1da10bf` | 2026-05-31 | fix(docker): build toolchain for better-sqlite3 native compile (#143). |
+| `606397f` | 2026-05-30 | feat(docker): Docker + GHCR support, multi-arch & localhost-bind (#129). |
+
+Regenerate with `git log --oneline -- Dockerfile docker-compose.yml .dockerignore`.
diff --git a/docs/deployment/OVERVIEW.md b/docs/deployment/OVERVIEW.md
new file mode 100644
index 00000000..81257c3e
--- /dev/null
+++ b/docs/deployment/OVERVIEW.md
@@ -0,0 +1,24 @@
+# Deployment overview
+
+## Scope
+
+Operating FreeLLMAPI in Docker: the published image, Compose quickstart, persistence, healthchecks, the container-networking gotchas, and the ongoing maintenance work — upgrading, backups, and declarative configuration. Content is derived from [`Dockerfile`](../../Dockerfile), [`docker-compose.yml`](../../docker-compose.yml), [`.dockerignore`](../../.dockerignore), and [`docs/install.md`](../install.md).
+
+For installation paths beyond Docker (one-liner script, local development, desktop app), see [Install & deploy](../install.md).
+
+## File index
+
+| File | Description |
+| --- | --- |
+| [01-docker.md](01-docker.md) | The image (multi-stage build on `node:20-bookworm-slim`), Compose quickstart, ports and LAN access, volumes and persistence, healthcheck, non-root runtime, native `better-sqlite3` compile rationale, and why a container cannot reach providers the host can (#733). |
+| [02-updates-and-backup.md](02-updates-and-backup.md) | Upgrade flow (`docker compose pull && docker compose up -d`), the dashboard update checker (#635/#703), backing up the SQLite data volume, and declarative config/catalog controls (#f4cd7b4). |
+
+## Quick facts
+
+| Aspect | Value |
+| --- | --- |
+| Image | `ghcr.io/tashfeenahmed/freellmapi:latest` |
+| Port | 3001 (published on `127.0.0.1` by default; `HOST_BIND=0.0.0.0` opens it to the LAN) |
+| Data volume | Named volume `freellmapi-data`, mounted at `/app/server/data` |
+| Runtime user | `node` (non-root) |
+| Healthcheck | `GET /api/ping` every 30s via an in-container Node fetch |
diff --git a/docs/env/01-variables.md b/docs/env/01-variables.md
new file mode 100644
index 00000000..cdce0ecf
--- /dev/null
+++ b/docs/env/01-variables.md
@@ -0,0 +1,117 @@
+# Environment variable reference
+
+Every variable FreeLLMAPI reads from `.env`, grouped by concern. Defaults and descriptions are derived only from the comments and values in [`.env.example`](../../.env.example). Variables shown commented out in `.env.example` are optional; their documented default is listed here.
+
+- [Server & binding](#server--binding)
+- [Outbound proxies (local destinations)](#outbound-proxies-local-destinations)
+- [Security & encryption](#security--encryption)
+- [Rate limits](#rate-limits)
+- [Routing overrides, timeouts & failover](#routing-overrides-timeouts--failover)
+- [Outbound proxies](#outbound-proxies)
+- [Request body & media limits](#request-body--media-limits)
+- [Storage, cache, analytics & misc](#storage-cache-analytics--misc)
+
+Related reading: [02-security-and-keys.md](02-security-and-keys.md) expands on `ENCRYPTION_KEY`; [03-outbound-proxies.md](03-outbound-proxies.md) expands on the proxy chain.
+
+## Server & binding
+
+| Variable | Default | Purpose |
+| --- | --- | --- |
+| `PORT` | `3001` | Server port. |
+| `HOST` | `::` (dual-stack IPv4+IPv6) | Network interface the server listens on. Hosts with IPv6 disabled fall back to IPv4 automatically. Set `0.0.0.0` for IPv4-only or `127.0.0.1` to restrict to localhost. Distinct from `HOST_BIND`, which only affects Docker port publishing. |
+| `HOST_BIND` | `127.0.0.1` | Docker only: which host interface the container's port is published on. The default keeps the dashboard/API reachable only from the machine running Docker; set `0.0.0.0` to open it to the LAN (e.g. a Raspberry Pi at `http://192.168.1.x:3001`) — only on a trusted network, since the proxy is single-user and guarded only by the unified API key. |
+| `DASHBOARD_ORIGINS` | `localhost:5173`, `127.0.0.1:5173`, `[::1]:5173` allowed | Comma-separated extra origins allowed to call the API from a browser. Only needed if you serve the dashboard from a different host than the API (e.g. `http://my-server.local`). |
+| `CSP_UPGRADE_INSECURE_REQUESTS` | Auto (unset) | Controls the Content-Security-Policy `upgrade-insecure-requests` directive (#682). Unset: emit only when the request arrives over TLS or behind an HTTPS reverse proxy (`X-Forwarded-Proto: https`), so plain-HTTP LAN installs stay renderable. `true`: force the directive on even over plain HTTP (rarely useful). `false`: force it off even behind HTTPS (e.g. mixed-content reverse proxies). |
+
+## Outbound proxies (local destinations)
+
+| Variable | Default | Purpose |
+| --- | --- | --- |
+| `FREEAPI_PROXY_LOCAL_DESTINATIONS` | `false` | Allow proxying localhost/LAN destinations (Ollama, llama.cpp, LM Studio). By default local and LAN destinations (localhost, 127.0.0.0/8, ::1, 0.0.0.0, RFC1918/ULA/CGNAT addresses) always bypass the outbound proxy — a remote proxy has no route back to your own machine. Set to `true` only when proxying them is the point, e.g. an `ssh -D` dynamic tunnel where `http://127.0.0.1:11434` through the SOCKS proxy is meant to reach the **remote** host's Ollama. |
+
+## Security & encryption
+
+| Variable | Default | Purpose |
+| --- | --- | --- |
+| `ENCRYPTION_KEY` | Placeholder value; required in production, auto-generated key file outside production | Server encryption key for API-key storage. Generate with `node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"`. Precedence: this env var, then a `.encryption-key` file next to the SQLite database (not inside it, 0600 permissions), then a legacy key found in the old settings table (migrated to the file on first boot), then a freshly generated key. See [02-security-and-keys.md](02-security-and-keys.md). |
+| `FREEAPI_BLOCK_PRIVATE_PROVIDER_URLS` | Unset — localhost and private LAN addresses stay allowed for custom providers | Custom-provider URL policy. Cloud metadata and link-local addresses (`169.254.169.254`, `metadata.google.internal`, `fe80::/10`, ...) are ALWAYS blocked as custom provider base URLs. Set to `true` to also block loopback and RFC1918/ULA private ranges — recommended when hosting on a VPS or anywhere the dashboard is reachable by others. |
+| `FREEAPI_DB_DIR_HARDENING` | Automatic where safe | Whether to restrict the directory holding the database to this account, so the SQLite `-wal`/`-shm` sidecars are protected too (they are created on first write, after any startup permission check could reach them). Done automatically for the default `server/data` directory and for any directory FreeLLMAPI creates itself; skipped for a `FREEAPI_DB_PATH` pointing somewhere pre-existing, since that may be a shared location. Set to `1` to force, `0` to disable entirely. |
+
+First-run note: the first dashboard account is normally created from a browser on the same machine with no extra step. If the server is reachable from other devices, creating that first account also requires a one-time setup code printed in the server logs at startup while no account exists.
+
+## Rate limits
+
+| Variable | Default | Purpose |
+| --- | --- | --- |
+| `PROXY_RATE_LIMIT_RPM` | `120` | Max `/v1` proxy requests per minute per client IP. Set to `0` to disable proxy rate limiting. See [03-outbound-proxies.md](03-outbound-proxies.md) for related knobs. |
+| `ADMIN_RATE_LIMIT_RPM` | `600` | Max `/api` dashboard requests per minute per client IP. A flood guard — login has its own per-email lockout and key export its own much tighter cap. Set to `0` to disable. |
+
+## Routing overrides, timeouts & failover
+
+| Variable | Default | Purpose |
+| --- | --- | --- |
+| `MODEL_ROUTING_OVERRIDES` | Unset | Per-model routing score multipliers (#738), JSON object of model id → `0..2`. `1.0` leaves a model unchanged, below `1` demotes it, above `1` promotes it, and `0` means the automatic router never picks it (Manual priority still can). Matching is by model id alone, across all platforms serving that id, exact and case-sensitive; copy ids from the dashboard Models page. An id that matches nothing is silently ignored, but the boot log flags it once the catalog has synced. |
+| `PROVIDER_TIMEOUT_<PLATFORM>` | Built-in per provider: `60s` most OpenAI-compatible platforms, `180s` NVIDIA, `120s` Ollama Cloud / AI Horde / custom providers, `60s` Google as registered | Per-provider chat HTTP timeout in milliseconds (platform name upper-cased). On streaming requests this value also serves as the FIRST-BYTE grace budget: how long the stream may stay silent before its first byte (issue #584 — providers like NVIDIA NIM send SSE headers instantly, then prefill long prompts for minutes). `0` disables the timeout entirely. Read at startup. Example: `PROVIDER_TIMEOUT_NVIDIA=300000` gives NVIDIA NIM's slow reasoning models 5 minutes. |
+| `PROVIDER_STREAM_STALL_TIMEOUT_MS` | `90000` | Mid-stream inactivity timeout in milliseconds. If an SSE stream goes this long without a single byte AFTER the first byte arrived, the gateway gives up: before any output reached the client it fails over to the next candidate; after output was sent the stream ends with an error frame. Time-to-FIRST-byte is governed by `PROVIDER_TIMEOUT_<PLATFORM>` instead (whichever of the two is larger). Providers that queue heavily on free tiers can pause longer than 90s mid-stream — raise this if streamed responses stop early. `0` disables the stall watchdog entirely. |
+| `PROVIDER_STREAM_STALL_TIMEOUT_<PLATFORM>` | Falls through to the global value above, then the built-in `90000` | Per-provider variant (platform name upper-cased). Precedence: per-platform > global > built-in 90s default. Example: `PROVIDER_STREAM_STALL_TIMEOUT_OLLAMA=240000` lets Ollama Cloud pause 4 minutes mid-stream without loosening the watchdog everywhere else. |
+| `PROVIDER_DAILY_REQUEST_CAP_<PLATFORM>` | Built-in default per provider | Per-provider daily request cap (platform name upper-cased). Overrides the built-in default for that provider; set to `0` to disable the cap. Example: `PROVIDER_DAILY_REQUEST_CAP_OPENROUTER=50`. |
+| `FALLBACK_TIME_BUDGET_MS` | `45000` | Wall-clock budget for provider failover, in milliseconds. A request that keeps failing over stops STARTING new attempts once this much time has passed and returns the exhaustion error instead (the first attempt always runs; an in-flight attempt is never cut off). `0` disables and retries until the attempt cap. Also settable at runtime via the `fallback_time_budget_ms` settings key, which takes precedence. |
+| `FALLBACK_DETAIL_HEADER` | Off | Opt-in `X-Fallback-Detail` response header (`=1` enables). `X-Fallback-Trail` already names every hop that failed and why; the detail header adds what each one COST — e.g. `groq/llama-3.3-70b key1=rate_limited t=0+39000ms msg=...` — so a caller can tell one 39s stall apart from four fast failures without opening the dashboard. Off by default because it puts hop timings and provider error text on the response. Runtime override via the `expose_fallback_detail_header` settings key takes precedence. |
+| `VALIDATE_TOOL_ARGUMENTS` | Off (`=1` enables) | Check tool-call arguments against the schema the caller declared and fail over when they violate it. `lib/tool-args.ts` already repairs what it can prove is repairable; this catches what is left, which today reaches Anthropic clients as a `tool_use` block with `input: {}`. Off by default because a false positive costs a failover hop — turn it on, watch `X-Fallback-Trail` for `invalid_tool_arguments`, then decide. Applies wherever the turn can still fail over (non-streaming surfaces, plus `/v1/chat/completions`, `/v1/messages`, Gemini and Ollama emulations); `/v1/responses` streaming commits on the first tool-call delta and is the exception. Runtime override via the `validate_tool_arguments` settings key. |
+| `REQUEST_MAX_TOKENS_BUDGET` | `0` (off) | Per-request token guardrail: estimated input + requested max_tokens must fit this ceiling or the request is rejected with a 413 before any provider is tried; a request that sent no max_tokens gets its output capped to the remainder instead. Runtime-tunable via the `request_max_tokens_budget` settings key (dashboard API `PUT /api/settings/guardrails`). |
+| `MAX_CONSECUTIVE_UPSTREAM_FAILS` | `0` (off) | Failover circuit breaker: after this many consecutive upstream failures in one request, stop the failover chain with a 503 instead of trying every remaining candidate of an unhealthy pool. Runtime-tunable via the `max_consecutive_upstream_fails` settings key. |
+| `MODELSCOPE_VALIDATE_CACHE_MS` | `86400000` (24h) | ModelScope (魔搭) validates API keys with a paid 1-token chat completion (`GET /v1/models` does not enforce auth), spending magic-grain (魔粒) quota per probe — observed as 2 魔粒 per ultra-tier request. To stop the 5-minute health pass burning ~288 paid probes per key per day, a successful validation is cached per key for this long (milliseconds). `0` probes on every pass; a revoked key is still caught by the next real request's 401. |
+| `FREELLMAPI_CONTEXT_HANDOFF` | Off | Context handoff on model switch. When enabled (`on_model_switch`), FreeLLMAPI injects a compact system message into the outbound request whenever a session switches from one model to another (e.g. after a fallback). |
+
+## Outbound proxies
+
+| Variable | Default | Purpose |
+| --- | --- | --- |
+| `PROXY_URL` | Unset | Outbound proxy for provider requests. Normally set in the dashboard (Keys → Outbound proxy); env vars exist for headless installs. Schemes: `http`, `https`, `socks4`, `socks4a`, `socks5`, `socks5h` — the `h`/`a` variants resolve DNS at the proxy, which is what you want on a DNS-poisoned network. Highest link in the precedence chain below. |
+| `ALL_PROXY` | Unset | Standard proxy variable, third in the precedence chain. |
+| `HTTPS_PROXY` | Unset | Standard proxy variable, fourth in the precedence chain. |
+| `HTTP_PROXY` | Unset | Standard proxy variable, last in the precedence chain. |
+| `NO_PROXY` | Unset | Hosts that must be reached directly, bypassing the proxy above. Comma-separated; a bare domain also covers its subdomains, and `*` disables the proxy entirely. |
+
+**Precedence:** `PROXY_URL` → dashboard setting → `ALL_PROXY` → `HTTPS_PROXY` → `HTTP_PROXY`. The standard variables are also read in their lower-case spellings.
+
+In Docker, `127.0.0.1` is the container, not your machine — see [03-outbound-proxies.md](03-outbound-proxies.md).
+
+## Request body & media limits
+
+| Variable | Default | Purpose |
+| --- | --- | --- |
+| `REQUEST_BODY_LIMIT_MB` | `25` | JSON body limit in MB for the inference surfaces (`/v1`, `/v1beta`, `/mcp`, Ollama `/api/*`). Vision requests embed base64 images in the body and replay them with every turn, so large sessions can clear 10MB; this ceiling only gates parsing — inbound image normalization shrinks the payload afterwards. Raise it if bigger payloads are rejected with 413 `request_too_large`. |
+| `IMAGE_NORMALIZE` | `on` | Inbound image normalization master switch (`off` disables entirely). Data-URL images over the threshold are downscaled to the long-edge cap and re-encoded (JPEG, or PNG only when the alpha channel carries real transparency) before routing, shrinking replayed screenshots ~6–10x. Also normalizes exotic formats upstreams reject (bmp/gif/tiff/avif/webp → jpeg/png); gif keeps its first frame only. Every upstream resizes internally anyway (OpenAI to 2048px, Anthropic to 1568px), so pixels beyond the cap are transport waste. |
+| `IMAGE_NORMALIZE_MAX_DIMENSION` | `2048` | Long-edge cap in pixels for normalized images. |
+| `IMAGE_NORMALIZE_THRESHOLD_KB` | `1024` | Images above this size (KB) are candidates for downscaling. |
+| `IMAGE_NORMALIZE_QUALITY` | `90` | Re-encode quality for normalized images. |
+
+## Storage, cache, analytics & misc
+
+| Variable | Default | Purpose |
+| --- | --- | --- |
+| `RESPONSE_CACHE` | `false` | Opt-in response cache. When on, a successful non-streaming `/v1/chat/completions` answer is stored in a bounded in-memory LRU keyed by a canonical hash of the request, so an IDENTICAL later request is served from memory without spending provider quota. Exact match only — a near-miss never returns a different prompt's answer. Toggled at runtime via the dashboard (`PUT /api/cache/config`) and per-request with the `X-FreeLLM-Cache: on\|off` header. A restart flushes it. |
+| `RESPONSE_CACHE_TTL_SECONDS` | `3600` (1 hour) | How long a cached answer stays fresh, in seconds. |
+| `RESPONSE_CACHE_MAX_TEMPERATURE` | `1.0` | Only cache requests at/below this temperature; higher temperatures want fresh variety. Default caches everything when enabled; lower it (e.g. `0.2`) to cache only near-deterministic calls. |
+| `RESPONSE_CACHE_MAX_ENTRIES` | `5000` | Hard cap on stored entries; least-recently-used entries are evicted past this. |
+| `FREELLMAPI_COMPRESSION` | `off` | Request-side prompt/context compression. `lossless` applies whitespace hygiene, exact repeated-block references, and reversible tabular-JSON encoding; `standard` also filters tool output and superseded file reads; `aggressive` adds age/relevance/budget condensation. The dashboard can change this live under Settings. A request may lower the configured mode with `X-FreeLLM-Compress`, but cannot override a global `off` master switch. |
+| `REQUEST_ANALYTICS_RETENTION_DAYS` | `90` | Request analytics retention in days. Set to `0` to disable this limit. |
+| `REQUEST_ANALYTICS_MAX_ROWS` | `100000` | Request analytics row cap. Set to `0` to disable this limit. |
+| `REQUEST_ANALYTICS_LOG_CLIENT` | `true` | Per-request caller identity (client IP + User-Agent) recorded into request analytics and shown in the dashboard "Recent calls" table. Set to `false` to store nulls instead (aggregate analytics unaffected). |
+| `SERVER_LOGS_RETENTION_DAYS` | `7` | Persisted server logs behind the dashboard's log viewer. Only warn/error lines are written to the database (the live view is an in-memory ring), so these bounds are far tighter than the analytics ones above. Set to `0` to disable this limit. |
+| `SERVER_LOGS_MAX_ROWS` | `50000` | Persisted server logs row cap. Set to `0` to disable this limit. |
+| `FREEAPI_DB_PATH` | Default location next to the server build | Optional SQLite location override. Useful on hosts where only one directory is mounted persistently, or to keep the DB outside `server/data`. Example: `/app/server/data/freellmapi.db`. |
+| `FREEAPI_DB_BACKUP_PATH` | Unset | Optional encrypted SQLite backup target (file path). On startup, FreeLLMAPI restores this backup if the configured DB file is missing; while running, it uploads a fresh backup periodically. |
+| `FREEAPI_DB_BACKUP_URL` | Unset | HTTP(S) backup target, alternative to the path above. |
+| `FREEAPI_DB_BACKUP_TOKEN` | Unset | Optional bearer token for uploads to `FREEAPI_DB_BACKUP_URL`. |
+| `FREEAPI_DB_BACKUP_KEY` | Uses `ENCRYPTION_KEY` if omitted | Separate 64-char hex key for the backup envelope. |
+| `FREEAPI_DB_BACKUP_INTERVAL_MS` | `300000` (5 min) | Period between background backups. |
+| `FREEAPI_CONFIG_PATH` | Unset | Optional declarative startup config: path to a JSON file applied idempotently after migrations on every boot. Example: `/app/server/data/freellmapi.config.json`. |
+| `FREEAPI_CONFIG_JSON` | Unset | Same declarative config inline instead of via file, e.g. `{"keys":[{"platform":"groq","key":"gsk_...","label":"main"}],"routing":{"strategy":"balanced"}}`. |
+| `FREELLMAPI_UPDATE_CHECK` | Enabled | Manual application update checker. Set to `off` to hide it from Settings and prevent Git discovery or outbound update-check requests. This also switches off the automatic release reminder, which is a separate dashboard setting (Settings > General) that stays off until turned on there. |
+| `FREELLMAPI_UPDATE_GITHUB_TOKEN` | Empty (anonymous checks) | Token used only for update checks against GitHub. The checker is anonymous by default; use a narrowly scoped token only if higher rate limits are needed. Generic `GITHUB_TOKEN` values are intentionally ignored. |
+| `FREELLMAPI_COMMIT_SHA` | Injected by official builds | Build metadata identifying the exact commit. Normally should not be set in `.env`. |
+| `FREELLMAPI_INSTALL_METHOD` | Injected by official builds (the Docker image sets `docker`) | Install-type metadata used by the update checker. Normally should not be set in `.env`. |
+| `CLIENT_DIST` | Bundled client build | Path to a prebuilt client `dist` directory to serve. Set this only if you build the dashboard separately. |
+| `FREEAPI_ENV_PATH` | `./.env` | Explicit path to the `.env` file to load. Useful for embedders (e.g. the desktop app, where the code runs from inside a bundle); dotenv silently no-ops on a missing file. |
diff --git a/docs/env/02-security-and-keys.md b/docs/env/02-security-and-keys.md
new file mode 100644
index 00000000..e5ea5b65
--- /dev/null
+++ b/docs/env/02-security-and-keys.md
@@ -0,0 +1,74 @@
+# Security and key handling
+
+How FreeLLMAPI protects the provider API keys you store in it, and how the `ENCRYPTION_KEY` that makes that protection real is generated, stored, and migrated.
+
+Sources: [`.env.example`](../../.env.example) (key lifecycle comments), [`server/src/lib/crypto.ts`](../../server/src/lib/crypto.ts), and [`server/src/db/index.ts`](../../server/src/db/index.ts).
+
+- [The encryption key at a glance](#the-encryption-key-at-a-glance)
+- [Key resolution precedence](#key-resolution-precedence)
+- [The dev auto-generated key file](#the-dev-auto-generated-key-file)
+- [Why the key file is not in the database](#why-the-key-file-is-not-in-the-database)
+- [At-rest encryption of provider keys](#at-rest-encryption-of-provider-keys)
+- [Data directory hardening (WAL sidecars)](#data-directory-hardening-wal-sidecars)
+- [First-run setup code](#first-run-setup-code)
+
+## The encryption key at a glance
+
+`ENCRYPTION_KEY` is the server-side key for API-key storage. It must be 64 hex characters — a 32-byte AES-256-GCM key. Generate one with:
+
+```bash
+node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
+```
+
+(or `openssl rand -hex 32`, as the Compose quickstart uses). The placeholder value from `.env.example` (`your-64-char-hex-key-here`) is never accepted as a real key.
+
+A typo'd or short key fails fast with an actionable error instead of being silently truncated and only surfacing as a cryptic `node:crypto` failure on the first encrypt call.
+
+## Key resolution precedence
+
+On boot, after the database is initialized, the key is resolved in this order:
+
+1. **`ENCRYPTION_KEY` env var** — always wins when set to a non-placeholder value.
+2. **Key file** — a `.encryption-key` file next to the SQLite database.
+3. **Legacy settings row** — older installs kept the key in a `settings` table row; it is migrated to the file on first boot, then deleted from the table.
+4. **Freshly generated key** — written to the key file (outside production only; see below).
+
+## The dev auto-generated key file
+
+Outside production, `ENCRYPTION_KEY` is optional: when unset, a key is auto-generated and written to a file named `.encryption-key` next to the SQLite database — not inside it — with `0600` permissions. This exists so a fresh clone boots under `npm run dev` without manual setup; otherwise the placeholder in `.env.example` would crash the server on boot, which surfaces in the client as "Can't reach the server".
+
+Production still requires an explicit env key: a generated key lives only on the local disk, and silently losing it would make every stored API key undecryptable.
+
+Two write-safety details:
+
+- The key file is written atomically via temp-file-and-rename, so a crash never leaves a half-written key.
+- The temp file is restricted to owner-only permissions BEFORE the rename, so the key is never briefly world-readable under its final name; the rename carries the DACL with it, and a second restriction pass on the final path is idempotent belt-and-braces. If the final restriction cannot be applied, a warning is logged.
+
+Do not rely on the fallback with real provider keys: set `ENCRYPTION_KEY`.
+
+## Why the key file is not in the database
+
+Storing the key beside the ciphertext it protects (the old `settings` row) meant encryption-at-rest protected nothing for a default install: whoever copied the DB also copied the key. The key file sits in the same directory but is a separate artifact, chmod `0600`, so copying the database alone no longer yields usable ciphertext. Legacy installs are migrated to this scheme automatically on first boot.
+
+## At-rest encryption of provider keys
+
+Stored provider keys are encrypted with AES-256-GCM using the resolved key. Consequences worth knowing:
+
+- **Keep the same `ENCRYPTION_KEY` across restarts and upgrades.** Losing it makes every stored provider key undecryptable; there is no recovery path.
+- The dashboard's key export exists for backup purposes; its rate limit is deliberately much tighter than the general `/api` flood guard (see [01-variables.md](01-variables.md#rate-limits)).
+- The optional encrypted DB backup ([02-updates-and-backup.md](../deployment/02-updates-and-backup.md)) defaults its envelope key to `ENCRYPTION_KEY`; `FREEAPI_DB_BACKUP_KEY` can override that with a separate 64-char hex key.
+
+## Data directory hardening (WAL sidecars)
+
+SQLite creates `-wal` and `-shm` sidecar files on the first write and deletes them on the last clean close — so at startup there may be nothing there to chmod, and the files' protection has to come from the directory they live in. FreeLLMAPI therefore restricts the directory holding the database to the owning account before opening the connection (on Windows the ACL is inherited, so hardening first means the database file is born protected rather than spending its first moments with whatever ACL the parent handed down).
+
+Because locking down a directory that is not ours would be a worse outage than the leak it prevents (pointing the DB at `/tmp/freeapi.db` must not chmod `0700` `/tmp`), hardening applies by ownership-by-construction:
+
+1. The directory was just created by this process, or
+2. It is the built-in default data directory (`server/data`), which ships as ours.
+
+An operator pointing `FREEAPI_DB_PATH` at a dedicated pre-existing directory can opt in with `FREEAPI_DB_DIR_HARDENING=1`, and opt out entirely with `=0`. The default is default-on-where-safe rather than a required flag, because hardening that only runs when someone remembers to ask for it is the same class of failure as hardening nobody noticed had stopped running.
+
+## First-run setup code
+
+The first dashboard account is created through the UI. A browser on the same machine as the server can do this with no extra step. If the server is reachable from other devices, creating that first account also requires a one-time setup code, printed in the server logs at startup while no account exists — this stops a stranger from claiming a freshly exposed install.
diff --git a/docs/env/03-outbound-proxies.md b/docs/env/03-outbound-proxies.md
new file mode 100644
index 00000000..098d2101
--- /dev/null
+++ b/docs/env/03-outbound-proxies.md
@@ -0,0 +1,88 @@
+# Outbound proxies
+
+How FreeLLMAPI routes its provider-bound traffic through proxies, which variables win when several are set, and the Docker networking gotchas that come with that.
+
+Sources: [`.env.example`](../../.env.example) (proxy block), [`docker-compose.yml`](../../docker-compose.yml), and the container-networking notes in [`docs/install.md`](../install.md).
+
+- [Proxy chain precedence](#proxy-chain-precedence)
+- [Scheme support](#scheme-support)
+- [NO_PROXY bypasses](#no_proxy-bypasses)
+- [Docker: 127.0.0.1 is the container](#docker-127001-is-the-container)
+- [Related inbound rate-limit knobs](#related-inbound-rate-limit-knobs)
+
+## Proxy chain precedence
+
+Outbound proxy for provider requests is normally set in the dashboard (Keys → Outbound proxy); the env vars exist for headless installs. When several sources are present, resolution order is:
+
+```
+PROXY_URL → dashboard setting → ALL_PROXY → HTTPS_PROXY → HTTP_PROXY
+```
+
+The standard variables are also read in their lower-case spellings (`all_proxy`, `https_proxy`, `http_proxy`).
+
+| Variable | Role in the chain |
+| --- | --- |
+| `PROXY_URL` | Explicit FreeLLMAPI proxy setting; highest precedence. |
+| Dashboard setting | Keys → Outbound proxy; beats the generic environment variables. |
+| `ALL_PROXY` | Standard catch-all proxy variable. |
+| `HTTPS_PROXY` / `HTTP_PROXY` | Conventional per-scheme variables, lowest precedence. |
+
+## Scheme support
+
+Accepted schemes: `http`, `https`, `socks4`, `socks4a`, `socks5`, `socks5h`.
+
+The `h`/`a` variants (`socks5h`, `socks4a`) resolve DNS at the proxy rather than locally, which is what you want on a DNS-poisoned network. Example:
+
+```env
+PROXY_URL=socks5h://127.0.0.1:1080
+```
+
+## NO_PROXY bypasses
+
+`NO_PROXY` lists hosts that must be reached directly, bypassing whichever proxy won above:
+
+```env
+NO_PROXY=localhost,127.0.0.1,.internal.corp
+```
+
+- Comma-separated entries.
+- A bare domain also covers its subdomains.
+- The special value `*` disables the proxy entirely.
+
+## Docker: 127.0.0.1 is the container
+
+Inside a container, `127.0.0.1` is the container itself — not your machine (#733). If your proxy client runs on the host (Clash, v2rayN, sing-box, a corporate proxy), two adjustments are needed:
+
+1. Point FreeLLMAPI at the host's address instead of loopback:
+
+ ```env
+ PROXY_URL=socks5h://host.docker.internal:7890
+ ```
+
+2. Make sure the proxy listens on more than loopback (in Clash: `allow-lan: true`).
+
+The bundled `docker-compose.yml` maps `host.docker.internal` to the host gateway via an `extra_hosts` entry, so this works on plain Linux Docker too, not just Docker Desktop (which provides the name already):
+
+```yaml
+extra_hosts:
+ - "host.docker.internal:host-gateway"
+```
+
+A second, unrelated way a container can be cut off from providers while the host works fine: on an IPv6-only host, the default bridge network is IPv4-only, so the container cannot reach anything — DNS included. Enable IPv6 in `/etc/docker/daemon.json` (`"ipv6": true`, `"ip6tables": true`, a `"fixed-cidr-v6"` range) and restart Docker.
+
+To see which case you are hitting, ask the container directly:
+
+```bash
+docker compose exec freellmapi node -e "fetch('https://generativelanguage.googleapis.com/').then(r=>console.log('ok',r.status)).catch(e=>console.log('fail',e.cause?.code||e.message))"
+```
+
+## Related inbound rate-limit knobs
+
+Despite the shared "proxy" name, these two variables throttle *inbound* traffic to FreeLLMAPI itself, not outbound provider calls:
+
+| Variable | Default | Purpose |
+| --- | --- | --- |
+| `PROXY_RATE_LIMIT_RPM` | `120` | Max `/v1` proxy requests per minute per client IP. `0` disables. |
+| `ADMIN_RATE_LIMIT_RPM` | `600` | Max `/api` dashboard requests per minute per client IP — a flood guard; login has its own per-email lockout and key export its own much tighter cap. `0` disables. |
+
+Full descriptions live in [01-variables.md](01-variables.md#rate-limits).
diff --git a/docs/env/CHANGELOG.md b/docs/env/CHANGELOG.md
new file mode 100644
index 00000000..7b9f62fd
--- /dev/null
+++ b/docs/env/CHANGELOG.md
@@ -0,0 +1,18 @@
+# Changelog
+
+Revision history for `docs/env/`, listing the commits that shaped the runtime configuration surface documented here. Most recent first.
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `74df985` | 2026-08-23 | Server log viewer in the dashboard (#993) — added `SERVER_LOGS_RETENTION_DAYS` and `SERVER_LOGS_MAX_ROWS` for persisted warn/error logs. |
+| `fe7744c` | 2026-08-23 | fix(proxy): never route loopback destinations through the proxy (#963) — added `FREEAPI_PROXY_LOCAL_DESTINATIONS` to opt in to proxying local/LAN endpoints via an ssh tunnel. |
+| `473d790` | 2026-08-20 | fix(modelscope): stop health checks burning magic-grain quota (#882) — basis for the `MODELSCOPE_VALIDATE_CACHE_MS` entry. |
+| `48591a8` | 2026-08-12 | fix(router): warn when MODEL_ROUTING_OVERRIDES never apply (#857) — boot-log warning for unmatched model ids. |
+| `8f27336` | 2026-08-12 | feat(vision): end-to-end image input, body limits, inbound normalization (#852) — introduced `REQUEST_BODY_LIMIT_MB` and the `IMAGE_NORMALIZE*` knobs. |
+| `c3f538e` | 2026-08-11 | feat(routing): per-model weight overrides via MODEL_ROUTING_OVERRIDES (#747) — introduced the routing override variable. |
+| `ba39318` | 2026-08-11 | feat(dashboard): automatic update check w/ release-notes dialog (#782) — automatic release reminder behind the update-checker settings. |
+| `8cb75ac` | 2026-08-10 | feat(proxy): opt-in X-Fallback-Detail header (#792) — introduced `FALLBACK_DETAIL_HEADER`. |
+| `a6f7718` | 2026-08-06 | fix(db): harden data dir so WAL sidecars are covered (#795) — data-directory restriction and `FREEAPI_DB_DIR_HARDENING`. |
+| `29eb340` | 2026-08-06 | feat: in-dashboard update checker (#635) — `FREELLMAPI_UPDATE_CHECK` and related variables. |
+
+Regenerate with `git log --oneline -- .env.example`.
diff --git a/docs/env/OVERVIEW.md b/docs/env/OVERVIEW.md
new file mode 100644
index 00000000..35e800d9
--- /dev/null
+++ b/docs/env/OVERVIEW.md
@@ -0,0 +1,21 @@
+# Environment configuration overview
+
+## Scope
+
+This domain documents FreeLLMAPI's runtime configuration surface: every variable the server reads from `.env`, how provider API keys are encrypted at rest, and how outbound traffic can be steered through proxies. The single source of truth is [`.env.example`](../../.env.example) at the repository root; the references here are derived from it (and from the code paths it describes) and never invent values.
+
+For getting an install running in the first place, see [Install & deploy](../install.md).
+
+## File index
+
+| File | Description |
+| --- | --- |
+| [01-variables.md](01-variables.md) | Full variable reference grouped by concern (server/bind, security, rate limits, routing overrides, outbound proxies, body/media limits, misc), with defaults taken verbatim from `.env.example`. |
+| [02-security-and-keys.md](02-security-and-keys.md) | `ENCRYPTION_KEY` lifecycle: generation, dev auto-generated key file, AES-256-GCM at-rest encryption of stored provider keys, key-file-out-of-DB hardening, and data-directory permissions. |
+| [03-outbound-proxies.md](03-outbound-proxies.md) | Outbound proxy configuration: scheme support, resolution-chain precedence (`PROXY_URL` through `HTTP_PROXY`), `NO_PROXY` bypasses, the Docker `host.docker.internal` gotcha, and the related inbound rate-limit knobs. |
+
+## Conventions
+
+- Variables are loaded by [`server/src/env.ts`](../../server/src/env.ts) via dotenv; `FREEAPI_ENV_PATH` selects an alternate `.env` location for embedders.
+- Commented lines in `.env.example` are optional; uncommented ones ship active defaults.
+- Where a variable can also be changed at runtime from the dashboard, the runtime settings key is noted and always takes precedence over the environment value.
diff --git a/docs/fallback/01-named-chains.md b/docs/fallback/01-named-chains.md
new file mode 100644
index 00000000..2ba7f657
--- /dev/null
+++ b/docs/fallback/01-named-chains.md
@@ -0,0 +1,58 @@
+# Named Fallback Chains
+
+> **Source:** `server/src/services/router.ts` (`activeChainOrThrow`, `resolveRoutingChain`), `server/src/services/profile-models.ts` (`getActiveProfileId`, `autoIncludeNewModelsForProfiles`), `server/src/routes/fallback.ts`, `server/src/routes/profiles.ts`
+
+A *fallback chain* is the ordered set of models the router may try for a request. One chain is **active** at a time; `plain auto` always follows the active chain. Chains are stored in two places, depending on whether the install uses named profiles:
+
+- **No profiles (legacy install):** the global `fallback_config` table.
+- **Named profiles:** the `profiles` table plus a `profile_models` row per chained model, with `priority` and `enabled` per row.
+
+Create, rename, delete, and switch the active chain on the dashboard's **Fallback** page. A profile name uses Latin letters, digits, hyphens and underscores (max 20 chars) and may not collide with the reserved routing words (`auto`, `smart`, `fast`, `cheap`, `budget`, `intelligence`, `speed`, `active`, `default`).
+
+## Lifecycle: the empty-chain refusal
+
+When a named profile is the active chain, `auto` is **not** a free pass over the whole catalog. The router resolves the active chain and, if it has no enabled models, **throws a client-facing `400`** rather than silently falling back to the global table:
+
+```
+The active fallback chain '<name>' has no enabled models.
+Enable models for it on the Models page, switch the active chain,
+or name another one with "auto:<chain>".
+```
+
+This refusal only triggers when a profile is active. A legacy install with no profiles keeps the ordinary "all models exhausted" path — the router runs the (possibly empty) global chain and returns a normal exhaustion error. The point: an empty chain must *mean* "nothing allowed", not "everything allowed". See [Commits](#commits) for the history.
+
+`activeChainOrThrow` (`router.ts`) is the single chokepoint: `auto`, an unknown `auto:` suffix, and a blank model string all route through it. It is also what `GET /api/fallback` and `/token-usage` read, so the dashboard and the router never disagree about what the active chain contains.
+
+## `auto:<name>` in `GET /v1/models`
+
+Every custom routing profile is advertised to clients as a discoverable model id `auto:<name>` (`cc1e985`). `GET /v1/models` lists each named chain with its max context and availability, alongside the plain OpenAI-shaped catalog and the Claude family discovery ids. A client can switch chains per request by sending `model="auto:coding"` — no dashboard change, no key rotation. An unknown chain name returns a clear `400` instead of silently using the active chain.
+
+Because the named-chain rows come from `profile_models` (not the global `fallback_config`), two installs can run entirely different model sets through the same unified key — the chain is selected by the request's `model` field, not by the account.
+
+## Catalog sync and curated chains
+
+A brand-new profile defaults to **"Start empty"** — its `profile_models` set begins empty, and it opts out of catalog-sync backfill. This is the whole point of a named chain: the operator hand-picks "these three models, in this order" and the gateway stops guessing.
+
+The `profiles.auto_include_new_models` flag (`b3bf20f`) controls the exception:
+
+- **`auto_include_new_models = 0` (default):** catalog sync never refills the chain. The chain stays exactly what the operator put in it. Disable this on a curated coding/vision chain so a newly-discovered model can't silently appear in it.
+- **`auto_include_new_models = 1`:** every newly synced model is appended to the chain (next priority, inheriting the model's global `enabled` state). Use this on a "catch-all" profile that should grow with the catalog.
+
+Sync runs `autoIncludeNewModelsForProfiles`, which only touches profiles with the flag set — curated chains are never touched.
+
+## Per-row enable / disable
+
+`PUT /api/fallback` writes a full chain replacement into the active chain, and the **Enable all / Disable all** actions (`b3bf20f`) flip every row at once. `chain_enabled` is only a marker at read time: a disabled row still consumes the provider's free allowance and still counts toward a quota pool, it is just ranked after every enabled row and skipped by `activeChainOrThrow`'s "has any enabled?" check. This is what makes a hand-built ("start empty") chain usable at all: the page renders as "the catalog, minus what I turned off", ranked after the rows I explicitly added.
+
+## Notes, not the global table
+
+`fallback_config` is now **only** the chain for an install that has no profiles. As soon as a profile exists, its `profile_models` is authoritative and the global table is bypassed. Treating the global table as a fallback for an empty `profile_models` set is exactly the bug `e852ff1` fixed — before that, a freshly-created "Start empty" profile rendered the whole catalog as enabled, because every consumer read zero rows as "no chain configured" and quietly fell through to `fallback_config`.
+
+## Commits
+
+| Commit | Change |
+|--------|--------|
+| `e852ff1` | **A fallback chain means itself, empty or not.** `activeChainOrThrow` returns the active profile's chain even when it has no enabled rows, instead of falling through to the global `fallback_config`. An empty curated chain now refuses with `400` rather than silently routing over the whole catalog. |
+| `b3bf20f` | **Let a hand-built chain stay that hand-built.** Chains can start empty; the new `auto_include_new_models` flag keeps catalog sync from refilling curated chains; the routing table gets Enable all / Disable all. Closes #895. |
+| `8bb2004` | **Named chain manager on the Fallback page.** Collapsed accordion for creating, renaming and deleting named chains, surfacing the `auto:<name>` id clients send. Refs #895 #960. |
+| `cc1e985` | **List named chains as `auto:<name>` models.** Every custom routing profile shows up in `GET /v1/models` as `auto:<name>` with its max context and availability. Refs #895 #880 #960. |
diff --git a/docs/fallback/CHANGELOG.md b/docs/fallback/CHANGELOG.md
new file mode 100644
index 00000000..6644ce69
--- /dev/null
+++ b/docs/fallback/CHANGELOG.md
@@ -0,0 +1,14 @@
+# Fallback Domain — Changelog
+
+Doc revision history for `docs/fallback/`, seeded from fallback-relevant commits.
+
+## 2026-08-25
+
+- **docs(fallback): scaffold fallback domain** — new `docs/fallback/` domain with `OVERVIEW.md` + `CHANGELOG.md`, and `01-named-chains.md` covering the chain lifecycle, the empty-chain `400` refusal (`activeChainOrThrow`), `auto:<name>` exposure in `GET /v1/models`, and `profiles.auto_include_new_models`, with the authoritative empty-chain commits `e852ff1`, `b3bf20f`, `8bb2004`, `cc1e985`.
+
+## 2026-08-23 — Prerequisite history
+
+- **e852ff1** Make a fallback chain mean itself, empty or not (#1023)
+- **b3bf20f** Let a fallback chain be built by hand and stay that way (#1004)
+- **8bb2004** Add a named chain manager to the Fallback page (#988)
+- **cc1e985** List named fallback chains as `auto:<name>` models (#986)
diff --git a/docs/fallback/OVERVIEW.md b/docs/fallback/OVERVIEW.md
new file mode 100644
index 00000000..a845e1d3
--- /dev/null
+++ b/docs/fallback/OVERVIEW.md
@@ -0,0 +1,21 @@
+# Fallback Domain — Overview & File Index
+
+This domain documents FreeLLMAPI's named fallback-chain system: how chains are stored, how the router resolves the active chain (and refuses when it is empty), how named chains surface to clients as `auto:<name>`, and how catalog sync interacts with curated chains. The root [`README.md`](../README.md) and [`OVERVIEW.md`](../OVERVIEW.md) index this as the operator's primary mechanism for controlling which models the router may use.
+
+## File Index
+
+| File | Scope |
+|------|-------|
+| [`01-named-chains.md`](01-named-chains.md) | Chain lifecycle, the empty-chain refusal, `auto:<name>` routing, `profiles.auto_include_new_models`, and the commits that made an empty chain authoritative. |
+| [`CHANGELOG.md`](CHANGELOG.md) | Doc revision history for this domain. |
+
+## Navigation
+
+- ← [Documentation root](../README.md)
+- Deep-dive: [`01-named-chains.md`](01-named-chains.md)
+
+## Related
+
+- [../architecture/](../architecture/) — Router, scoring, and failover internals that execute a resolved chain.
+- [../api/](../api/) — The `auto:*` routing strategies and `GET /v1/models` surface that expose named chains to clients.
+- [../providers/](../providers/) — Per-key quota accounting and cooldowns that gate each hop in a chain.
diff --git a/docs/translating.md b/docs/i18n/01-translating.md
similarity index 97%
rename from docs/translating.md
rename to docs/i18n/01-translating.md
index 0332811d..e53d586c 100644
--- a/docs/translating.md
+++ b/docs/i18n/01-translating.md
@@ -4,7 +4,7 @@ The dashboard ships 60 locales under `client/src/i18n/locales/`. `en.json` is th
truth: every other file mirrors its key structure exactly.
Translating the README and the docs pages is a separate job with its own layout and rules,
-covered in [i18n/README.md](i18n/README.md). The terminology table below applies to both.
+covered in [i18n/README.md](README.md). The terminology table below applies to both.
## Before you open a PR
diff --git a/docs/i18n/CHANGELOG.md b/docs/i18n/CHANGELOG.md
new file mode 100644
index 00000000..86df9d12
--- /dev/null
+++ b/docs/i18n/CHANGELOG.md
@@ -0,0 +1,23 @@
+# Changelog
+
+Doc revision history for `docs/i18n/`. Most recent first.
+
+| Date | Commit | Change |
+| --- | --- | --- |
+| 2026-08-23 | `e82f85f` | docs(i18n): translate logs/ and architecture/ domains to zh-CN |
+| 2026-08-23 | [`2331045`](https://github.com/tashfeenahmed/freellmapi/commit/2331045) | docs(providers): add unorouter and xkiro to platform catalog |
+| 2026-08-23 | [`453de80`](https://github.com/tashfeenahmed/freellmapi/commit/453de80) | docs(providers): document xkiro 5M tokens/day and unorouter per-min RPM in quotas |
+| 2026-08-23 | [`acb1511`](https://github.com/tashfeenahmed/freellmapi/commit/acb1511) | docs(env): add FREEAPI_PROXY_LOCAL_DESTINATIONS, SERVER_LOGS_RETENTION_DAYS/MAX_ROWS |
+| 2026-08-23 | [`e8dde9e`](https://github.com/tashfeenahmed/freellmapi/commit/e8dde9e) | docs(clients): add setup-dsh note in coding agents intro |
+| 2026-08-23 | [`6a1c1a9`](https://github.com/tashfeenahmed/freellmapi/commit/6a1c1a9) | docs(compression): add early-exit protected-span check perf note |
+| 2026-08-23 | [`6813e40`](https://github.com/tashfeenahmed/freellmapi/commit/6813e40) | docs(testing): add new test files note for August 2026 batch |
+| 2026-08-22 | — | zh-CN mirrors for env/deployment/providers/testing domains; translation commit hashes land in git log |
+| 2026-08-22 | [`ac0a9ce`](https://github.com/tashfeenahmed/freellmapi/commit/ac0a9ce) | docs(env): add runtime configuration reference domain — English source now mirrored under zh-CN |
+| 2026-08-22 | [`abe6b00`](https://github.com/tashfeenahmed/freellmapi/commit/abe6b00) | docs(deployment): add Docker operations and maintenance domain — English source now mirrored under zh-CN |
+| 2026-08-22 | [`b21ec10`](https://github.com/tashfeenahmed/freellmapi/commit/b21ec10) | docs(providers): add platform catalog and integration guides — English source now mirrored under zh-CN |
+| 2026-08-22 | [`676ae20`](https://github.com/tashfeenahmed/freellmapi/commit/676ae20) | docs(testing): add test matrix and compatibility-suite documentation — English source now mirrored under zh-CN |
+| 2026-08-03 | [`5d51fec`](https://github.com/tashfeenahmed/freellmapi/commit/5d51fec) | docs(docker): explain why a container cannot reach providers the host can (#737) |
+| 2026-08-01 | [`93afdca`](https://github.com/tashfeenahmed/freellmapi/commit/93afdca) | docs(i18n): give the zh README a 贡献者 heading (#701) |
+| 2026-07-31 | [`76c3e6b`](https://github.com/tashfeenahmed/freellmapi/commit/76c3e6b) | language toggle centering (#691) |
+| 2026-07-31 | [`3ea33cb`](https://github.com/tashfeenahmed/freellmapi/commit/3ea33cb) | translate install.md and api.md into zh-CN (#690) |
+| 2026-07-31 | [`41527f2`](https://github.com/tashfeenahmed/freellmapi/commit/41527f2) | initial translated-docs tree + zh-CN README (#689) |
\ No newline at end of file
diff --git a/docs/i18n/OVERVIEW.md b/docs/i18n/OVERVIEW.md
new file mode 100644
index 00000000..efffdaaa
--- /dev/null
+++ b/docs/i18n/OVERVIEW.md
@@ -0,0 +1,39 @@
+# i18n Documentation
+
+## Scope
+
+This directory holds the translated documentation tree: Simplified Chinese and
+future locales for the pages a new user reads before they ever clone the repo.
+English is the source of truth; every file here is a mirror of an English
+original elsewhere in the repository and is expected to lag slightly behind it.
+
+Translation of the dashboard UI strings is a separate concern and lives in
+`client/src/i18n/locales/`. The shared terminology rules that apply to both are
+in [01-translating.md](01-translating.md).
+
+## Conventions
+
+- **Mirror layout.** One directory per locale (`zh-CN`, `pt-BR`, `fr`, ...).
+ Deleting `docs/i18n/<locale>/` from any translated path yields the path of its
+ English original, and adding it back yields the translation.
+- **Language toggle.** The root README and every translated README carry a
+ centered language bar near the top (above the hero screenshot) linking the
+ available editions, e.g. `**English** · [简体中文](zh-CN/README.md)`.
+ When a locale is added, its link goes into this bar on every README.
+- **Translate prose, not markup.** Badges, code blocks, endpoint paths,
+ environment variables, and model ids stay untouched; relative asset and doc
+ links must be re-pointed for the deeper directory.
+- **Honest status.** Pages without a translation link to the English original
+ rather than shipping something stale.
+
+## File index
+
+| File | Description |
+| --- | --- |
+| [README.md](README.md) | Translation workflow: layout mirror, per-locale status table, rules that keep translations maintainable, and what to do when English changes. |
+| [zh-CN/](zh-CN/OVERVIEW.md) | Simplified Chinese translations of the core docs. See its [OVERVIEW.md](zh-CN/OVERVIEW.md) for the file index. |
+
+## Related
+
+- [01-translating.md](01-translating.md) - dashboard locale strings and the settled zh-CN terminology table (applies here too).
+- Root [README.md](../../README.md) - carries the language-toggle bar linking to these translations.
diff --git a/docs/i18n/README.md b/docs/i18n/README.md
index 35856ff9..7e470b76 100644
--- a/docs/i18n/README.md
+++ b/docs/i18n/README.md
@@ -5,7 +5,7 @@ a file that lives elsewhere in the repo, and it is expected to lag a little
behind. That is fine, as long as it is honest about it.
This is separate from the dashboard UI strings, which live in
-`client/src/i18n/locales/` and are covered by [../translating.md](../translating.md).
+`client/src/i18n/locales/` and are covered by [01-translating.md](01-translating.md).
Read that file too if you are translating into Chinese, because the terminology
table there applies here as well. A README that calls a provider `提供商` while
the dashboard calls it `提供方` is worse than no translation.
@@ -32,9 +32,9 @@ too.
| `README.md` | ✅ |
| `docs/README.md` | ✅ |
| `docs/install.md` | ✅ |
-| `docs/api.md` | ✅ |
-| `docs/clients.md` | English |
-| `docs/compression.md` | English |
+| `docs/api/01-rest-api.md` | ✅ |
+| `docs/clients/01-agent-clients.md` | English |
+| `docs/compression/01-compression-pipeline.md` | English |
| `docs/architecture.md` | English |
Untranslated pages are not a gap to apologise for. Link to the English original
@@ -55,8 +55,8 @@ that someone will trust and act on.
and CLI commands stay exactly as they are. So do product names, endpoint paths,
environment variables, and model ids.
- **Fix the relative paths.** A translated README sits three directories deep, so
- `repo-assets/x.png` becomes `../../../repo-assets/x.png` and `docs/api.md`
- becomes `../../api.md`. Broken image links are the most common mistake here.
+ `repo-assets/x.png` becomes `../../../repo-assets/x.png` and `docs/api/01-rest-api.md`
+ becomes `../../api/01-rest-api.md`. Broken image links are the most common mistake here.
- **Do not copy the contributor avatar list.** It changes with nearly every merge
and nobody wants to update it in six languages. Keep the heading so the
section structure still matches one-to-one, and link out to the English
diff --git a/docs/i18n/zh-CN/CHANGELOG.md b/docs/i18n/zh-CN/CHANGELOG.md
new file mode 100644
index 00000000..d23aedc6
--- /dev/null
+++ b/docs/i18n/zh-CN/CHANGELOG.md
@@ -0,0 +1,23 @@
+# Changelog
+
+Doc revision history for `docs/i18n/zh-CN/`. Most recent first.
+
+| Date | Commit | Change |
+| --- | --- | --- |
+| 2026-08-23 | `e82f85f` | docs(i18n): translate logs/ and architecture/ domains to zh-CN |
+| 2026-08-23 | [`2331045`](https://github.com/tashfeenahmed/freellmapi/commit/2331045) | docs(providers): add unorouter and xkiro to platform catalog |
+| 2026-08-23 | [`453de80`](https://github.com/tashfeenahmed/freellmapi/commit/453de80) | docs(providers): document xkiro 5M tokens/day and unorouter per-min RPM in quotas |
+| 2026-08-23 | [`acb1511`](https://github.com/tashfeenahmed/freellmapi/commit/acb1511) | docs(env): add FREEAPI_PROXY_LOCAL_DESTINATIONS, SERVER_LOGS_RETENTION_DAYS/MAX_ROWS |
+| 2026-08-23 | [`e8dde9e`](https://github.com/tashfeenahmed/freellmapi/commit/e8dde9e) | docs(clients): add setup-dsh note in coding agents intro |
+| 2026-08-23 | [`6a1c1a9`](https://github.com/tashfeenahmed/freellmapi/commit/6a1c1a9) | docs(compression): add early-exit protected-span check perf note |
+| 2026-08-23 | [`6813e40`](https://github.com/tashfeenahmed/freellmapi/commit/6813e40) | docs(testing): add new test files note for August 2026 batch |
+| 2026-08-22 | — | env/deployment/providers/testing 四个域的 zh-CN 镜像;翻译提交的哈希见 git log |
+| 2026-08-22 | [`ac0a9ce`](https://github.com/tashfeenahmed/freellmapi/commit/ac0a9ce) | docs(env): add runtime configuration reference domain —— 英文原文已镜像到 zh-CN |
+| 2026-08-22 | [`abe6b00`](https://github.com/tashfeenahmed/freellmapi/commit/abe6b00) | docs(deployment): add Docker operations and maintenance domain —— 英文原文已镜像到 zh-CN |
+| 2026-08-22 | [`b21ec10`](https://github.com/tashfeenahmed/freellmapi/commit/b21ec10) | docs(providers): add platform catalog and integration guides —— 英文原文已镜像到 zh-CN |
+| 2026-08-22 | [`676ae20`](https://github.com/tashfeenahmed/freellmapi/commit/676ae20) | docs(testing): add test matrix and compatibility-suite documentation —— 英文原文已镜像到 zh-CN |
+| 2026-08-03 | [`5d51fec`](https://github.com/tashfeenahmed/freellmapi/commit/5d51fec) | docs(docker): container/provider network mismatch note (#737) |
+| 2026-08-01 | [`93afdca`](https://github.com/tashfeenahmed/freellmapi/commit/93afdca) | zh README 贡献者 heading alignment (#701) |
+| 2026-07-31 | [`76c3e6b`](https://github.com/tashfeenahmed/freellmapi/commit/76c3e6b) | language toggle centering (#691) |
+| 2026-07-31 | [`3ea33cb`](https://github.com/tashfeenahmed/freellmapi/commit/3ea33cb) | translate install.md and api.md into zh-CN (#690) |
+| 2026-07-31 | [`41527f2`](https://github.com/tashfeenahmed/freellmapi/commit/41527f2) | initial translated-docs tree + zh-CN README (#689) |
\ No newline at end of file
diff --git a/docs/i18n/zh-CN/OVERVIEW.md b/docs/i18n/zh-CN/OVERVIEW.md
new file mode 100644
index 00000000..48e0c688
--- /dev/null
+++ b/docs/i18n/zh-CN/OVERVIEW.md
@@ -0,0 +1,44 @@
+# zh-CN Translations
+
+## Scope
+
+Simplified Chinese translations of the core documentation: the pages that cover
+what FreeLLMAPI is, how to install it, and how to call its API. Each file below
+mirrors an English original at the same position in the tree, with
+`docs/i18n/zh-CN/` removed from the path.
+
+Terminology follows the settled zh-CN table in
+[../01-translating.md](../01-translating.md) so these docs and the dashboard UI
+use the same words (提供方, 词元, 令牌, ...).
+
+## File index
+
+| File | Mirrors | Description |
+| --- | --- | --- |
+| [README.md](README.md) | [../../../README.md](../../../README.md) | Project overview: what the gateway does, supported providers, quick start, and configuration - the full root README in Simplified Chinese. |
+| [docs/README.md](docs/README.md) | [../../../docs/README.md](../../../docs/README.md) | Documentation index page listing every guide in the docs tree. |
+| [docs/install.md](docs/install.md) | [../../../docs/install.md](../../../docs/install.md) | Installation guide covering Docker Compose, local setup, and desktop app installs. |
+| [docs/api/01-rest-api.md](docs/api/01-rest-api.md) | [../../../docs/api/01-rest-api.md](../../../docs/api/01-rest-api.md) | API reference for the OpenAI-compatible `/v1` endpoints, authentication, and request formats. |
+
+### Translated domain subtrees
+
+Each folder below mirrors a `docs/` subdomain (OVERVIEW, numbered topic
+docs, CHANGELOG):
+
+| Folder | Mirrors | Contents |
+| --- | --- | --- |
+| [docs/env/](docs/env/OVERVIEW.md) | [../../../docs/env/](../../../docs/env/) | Runtime configuration surface: the full `.env` variable reference, encryption-key handling, and outbound proxy configuration. |
+| [docs/deployment/](docs/deployment/OVERVIEW.md) | [../../../docs/deployment/](../../../docs/deployment/) | Docker operations: image, Compose quickstart, persistence, healthchecks, upgrades, and backups. |
+| [docs/providers/](docs/providers/OVERVIEW.md) | [../../../docs/providers/](../../../docs/providers/) | Provider layer: supported platforms catalog, quotas/cooldowns/key health, and how to add a new provider. |
+| [docs/testing/](docs/testing/OVERVIEW.md) | [../../../docs/testing/](../../../docs/testing/) | Test matrix across workspaces, server suite conventions, and the coding-agent compatibility suite. |
+| [docs/logs/](docs/logs/OVERVIEW.md) | [../../../docs/logs/](../../../docs/logs/) | Live server log viewer in the dashboard: two-tier store, polling API, level counts, clear endpoint, env vars, redaction integration. |
+| [docs/architecture/](docs/architecture/OVERVIEW.md) | [../../../docs/architecture/](../../../docs/architecture/) | Deep-dive server architecture: bandit router, quota/cooldown engine, streaming pipeline, degraded mode, catalog sync, observability. |
+
+Pages not listed here have no translation yet; they link to their English
+originals by design.
+
+## Navigation
+
+- Up one level: [../OVERVIEW.md](../OVERVIEW.md)
+- Language toggle: every README above links back to
+ **[English](../../../README.md)** via the centered language bar at the top.
diff --git a/docs/i18n/zh-CN/README.md b/docs/i18n/zh-CN/README.md
index 13d2a1b8..85658cab 100644
--- a/docs/i18n/zh-CN/README.md
+++ b/docs/i18n/zh-CN/README.md
@@ -48,7 +48,7 @@
- [参与贡献](#参与贡献)
- [免责声明](#免责声明)
-**指南:** [安装与部署](docs/install.md) · [API 参考](docs/api.md) · [客户端与编程智能体](../../clients.md) · [提示词压缩](../../compression.md) · [架构与内部实现](../../architecture.md) · [文档索引](docs/README.md) · [贡献者指南](../../../CONTRIBUTING.md)
+**指南:** [安装与部署](docs/install.md) · [API 参考](docs/api/01-rest-api.md) · [客户端与编程智能体](../../clients/01-agent-clients.md) · [提示词压缩](../../compression/01-compression-pipeline.md) · [架构与内部实现](../../architecture.md) · [文档索引](docs/README.md) · [贡献者指南](../../../CONTRIBUTING.md)
> 「安装与部署」和「API 参考」已有中文版。「客户端与编程智能体」「提示词压缩」「架构与内部实现」目前只有英文版,上面的链接直接指向英文原文。完整的翻译状态见 [这里](../README.md#status)。
@@ -129,9 +129,9 @@
</div>
-其中大多数一条命令就能配好:`npx freellmapi setup-claude`、`setup-codex`、`setup-aider`,还有另外十几个生成器。它们会拉取你当前的实时目录,备份已有配置,并且绝不覆盖你已经写好的内容。Claude Code 和 Codex 另有零留存启动器(`freellmapi launch`、`freellmapi launch-codex`),只把凭据注入子进程。Zed 和 JetBrains AI 通过可选的 [Ollama 模拟](../../clients.md#ollama-clients) 接入;Gemini CLI 走它自己的 `/v1beta` 协议。
+其中大多数一条命令就能配好:`npx freellmapi setup-claude`、`setup-codex`、`setup-aider`,还有另外十几个生成器。它们会拉取你当前的实时目录,备份已有配置,并且绝不覆盖你已经写好的内容。Claude Code 和 Codex 另有零留存启动器(`freellmapi launch`、`freellmapi launch-codex`),只把凭据注入子进程。Zed 和 JetBrains AI 通过可选的 [Ollama 模拟](../../clients/01-agent-clients.md#ollama-clients) 接入;Gemini CLI 走它自己的 `/v1beta` 协议。
-各工具的具体配方、setup CLI 参考、给无法发送请求头的客户端用的可撤销 URL 令牌,以及 MCP 服务,都在 **[客户端与编程智能体 →](../../clients.md)**
+各工具的具体配方、setup CLI 参考、给无法发送请求头的客户端用的可撤销 URL 令牌,以及 MCP 服务,都在 **[客户端与编程智能体 →](../../clients/01-agent-clients.md)**
## 横向对比
@@ -143,21 +143,21 @@
![功能概览](../../../repo-assets/features.png)
-- **OpenAI 的全部接口** —— `/v1/chat/completions`、`/v1/responses`(Codex CLI 需要它)、`/v1/completions`(编辑器的幽灵文本补全)、`/v1/images/generations`、`/v1/audio/speech`、`/v1/embeddings` 和 `/v1/models`,流式与非流式均可,来自官方 SDK 或任何 OpenAI 兼容客户端都行。[API 参考 →](docs/api.md)
-- **Anthropic Messages API** —— `/v1/messages` 在同一套路由之上讲 Anthropic 的协议,所以 **Claude Code** 和官方 Anthropic SDK 可以直接跑在你的免费池上。[详情 →](docs/api.md#anthropic-与-claude-客户端)
+- **OpenAI 的全部接口** —— `/v1/chat/completions`、`/v1/responses`(Codex CLI 需要它)、`/v1/completions`(编辑器的幽灵文本补全)、`/v1/images/generations`、`/v1/audio/speech`、`/v1/embeddings` 和 `/v1/models`,流式与非流式均可,来自官方 SDK 或任何 OpenAI 兼容客户端都行。[API 参考 →](docs/api/01-rest-api.md)
+- **Anthropic Messages API** —— `/v1/messages` 在同一套路由之上讲 Anthropic 的协议,所以 **Claude Code** 和官方 Anthropic SDK 可以直接跑在你的免费池上。[详情 →](docs/api/01-rest-api.md#anthropic-与-claude-客户端)
- **原生 Gemini 与 Ollama 接口** —— Gemini CLI 可以用 `/v1beta`(`generateContent`、流式、词元计数、模型列表);可选的 Ollama 模拟则为 Zed、JetBrains 以及其他本地模型客户端提供 NDJSON 的 chat/generate、标签、元数据和嵌入。
-- **Fusion(多模型合成)** —— 请求虚拟模型 `fusion`,路由器会把你的提示词并行分发给一组风格各异的免费模型,再由一个评审模型从这些草稿中合成出一个答案。[详情 →](docs/api.md#fusion-多模型合成)
+- **Fusion(多模型合成)** —— 请求虚拟模型 `fusion`,路由器会把你的提示词并行分发给一组风格各异的免费模型,再由一个评审模型从这些草稿中合成出一个答案。[详情 →](docs/api/01-rest-api.md#fusion-多模型合成)
- **图像生成与文本转语音** —— `/v1/images/generations` 和 `/v1/audio/speech` 会在提供媒体模型的提供方之间路由,也包括自定义的 OpenAI 兼容媒体端点。
- **工具调用与结构化输出** —— OpenAI 风格的 `tools` 可在各提供方之间往返(纯文本形式的工具调用会被救回成真正的 `tool_calls`),另有 `response_format`、`seed`、`logprobs`、惩罚项以及其余采样参数按提供方透传。
- **智能路由,六种策略** —— 实时的每模型速度、能力、稳定性评分决定你的链路顺序;遇到 429/5xx 时自动转移到下一个模型,并带冷却和密钥轮换。[路由详解 →](../../architecture.md#routing-in-detail)
- **统一模型与配置档** —— 同一个模型在多家提供方上会合并成一个条目,并在组内严格故障转移;命名的回退链配置档(比如一条编程链、一条视觉链)可以在仪表盘里切换,也可以按请求用 `auto:<profile>` 指定。
- **按密钥的限流跟踪** —— 以 `(平台, 模型, 密钥)` 为单位的 RPM/RPD/TPM/TPD 计数器,会学习提供方公布的上限,让路由始终不越线。
- **自更新的模型目录** —— 路由器每天两次从 freellmapi.co 同步经过签名的目录:新模型、额度变更和提供方的怪癖修复都会自动生效。[Premium →](#premium-实时目录)
-- **粘性会话与上下文交接** —— 对话会在同一个模型上停留 30 分钟;如果中途确实换了模型,可选的精简交接说明能让话题保持连贯。[详情 →](../../clients.md#context-handoff)
-- **提示词压缩(可选开启)** —— 一条共享且失败即放行的请求流程,可以在缓存查找和路由之前对提示词去重、过滤工具输出、压紧重复的 JSON,并裁掉过时的上下文。[详情 →](../../compression.md)
+- **粘性会话与上下文交接** —— 对话会在同一个模型上停留 30 分钟;如果中途确实换了模型,可选的精简交接说明能让话题保持连贯。[详情 →](../../clients/01-agent-clients.md#context-handoff)
+- **提示词压缩(可选开启)** —— 一条共享且失败即放行的请求流程,可以在缓存查找和路由之前对提示词去重、过滤工具输出、压紧重复的 JSON,并裁掉过时的上下文。[详情 →](../../compression/01-compression-pipeline.md)
- **密钥加密存储,对外只有一个令牌** —— 提供方密钥以 AES-256-GCM 加密存放在 SQLite 中,每次请求时在内存里解密;你的应用自始至终只看到一个统一的 `freellmapi-…` bearer 令牌。
- **管理仪表盘与分析** —— React 界面用来管理密钥、调整链路顺序、使用试验台,并查看 24 小时到 90 天窗口的 p50/p95/首个词元用时分析;带登录保护,支持明暗主题和 [60 种语言](#语言)。
-- **MCP 服务与交互式文档** —— 智能体可以通过 `/mcp` 查询可用模型、提供方健康状况和路由策略;`/v1/docs` 提供一个零依赖的 OpenAPI 浏览器。[编程智能体 →](../../clients.md)
+- **MCP 服务与交互式文档** —— 智能体可以通过 `/mcp` 查询可用模型、提供方健康状况和路由策略;`/v1/docs` 提供一个零依赖的 OpenAPI 浏览器。[编程智能体 →](../../clients/01-agent-clients.md)
- **运维上的便利** —— 可选的响应缓存、加密的数据库备份、定期密钥健康检查、密钥批量导入导出、声明式启动配置。[安装与部署 →](docs/install.md)
- **能跑 Node 20+ 的地方都能跑** —— Windows、macOS、Linux 服务器,或者一块小小的 ARM 单板机(树莓派也行)。在 PM2 / systemd 或你惯用的守护进程下,空闲时常驻内存约 40 MB。
@@ -189,7 +189,7 @@ curl -fsSL https://freellmapi.co/install.sh | bash
## 兼容 OpenAI 的客户端
-任何能指定 OpenAI 兼容 base URL 的东西都能用:把它设成 `http://localhost:3001/v1`,配上仪表盘里的统一密钥。**Claude Code**、**Codex CLI**、**Cline / Roo Code**、**Continue**(含行内补全)、**Aider**、**opencode** 和 **Cursor** 在 **[docs/clients.md](../../clients.md)** 里各有一段简短配方。此外路由器本身还兼作 MCP 服务,你的智能体可以在会话中随时查询它。
+任何能指定 OpenAI 兼容 base URL 的东西都能用:把它设成 `http://localhost:3001/v1`,配上仪表盘里的统一密钥。**Claude Code**、**Codex CLI**、**Cline / Roo Code**、**Continue**(含行内补全)、**Aider**、**opencode** 和 **Cursor** 在 **[docs/clients/01-agent-clients.md](../../clients/01-agent-clients.md)** 里各有一段简短配方。此外路由器本身还兼作 MCP 服务,你的智能体可以在会话中随时查询它。
最快的配置方式是根据你服务器上实际可用的模型生成:
@@ -226,7 +226,7 @@ FreeLLMAPI 在设计上是本地优先、单用户的。你的提供方密钥留
翻译文件以扁平 JSON 的形式放在 [`client/src/i18n/locales/`](../../../client/src/i18n/locales)。想修某个字符串,直接改对应语言 JSON 里的值即可。想加一门语言,复制 `en.json`、翻译其中的值,再到 `client/src/i18n/locale-config.ts` 注册这个语言(托盘文案还需要改 `desktop/src/i18n.ts`);`npm test` 会检查每种语言的键和占位符是否对齐。欢迎提 PR。
-中文的术语约定见 [docs/translating.md](../../translating.md),提交翻译前请先过一遍,这样 README 和仪表盘里的说法能对得上。
+中文的术语约定见 [docs/i18n/01-translating.md](../01-translating.md),提交翻译前请先过一遍,这样 README 和仪表盘里的说法能对得上。
## Premium 实时目录
@@ -263,7 +263,7 @@ print(resp.choices[0].message.content)
print("Routed via:", resp.headers.get("x-routed-via"))
```
-流式、`auto:*` 路由策略、工具调用、视觉输入、Gemini 的 Google 搜索接地、嵌入,以及 Anthropic Messages 接口,连同各自的 curl 和 Python 示例,全都在 **[docs/api.md](docs/api.md)**。每个响应都带一个 `X-Routed-Via: <平台>/<模型>` 头,你可以据此看出实际是哪家提供方处理的。
+流式、`auto:*` 路由策略、工具调用、视觉输入、Gemini 的 Google 搜索接地、嵌入,以及 Anthropic Messages 接口,连同各自的 curl 和 Python 示例,全都在 **[docs/api/01-rest-api.md](docs/api/01-rest-api.md)**。每个响应都带一个 `X-Routed-Via: <平台>/<模型>` 头,你可以据此看出实际是哪家提供方处理的。
## 截图
diff --git a/docs/i18n/zh-CN/docs/README.md b/docs/i18n/zh-CN/docs/README.md
index b44584e5..742464e0 100644
--- a/docs/i18n/zh-CN/docs/README.md
+++ b/docs/i18n/zh-CN/docs/README.md
@@ -10,9 +10,9 @@
## 指南
- **[安装与部署](install.md)** —— 快速开始、Docker Compose、本地开发、声明式启动配置、Docker 镜像、备份、桌面应用,以及你的数据存放在哪里。
-- **[API 参考](api.md)** —— 聊天补全、`auto:*` 路由策略、流式、工具调用、视觉、Gemini 的 Google 搜索接地、嵌入、响应头,以及 Anthropic Messages 接口。
-- **[客户端与编程智能体](../../../clients.md)** —— 兼容 OpenAI 的客户端,Claude Code / Codex CLI / Cline / Continue / Aider / opencode / Cursor 的配方,MCP 服务,编辑器补全,以及上下文交接。
-- **[提示词压缩](../../../compression.md)** —— 请求侧的各种模式、安全保护、按请求的控制项、自定义工具输出过滤器、统计数据和预览 API。
+- **[API 参考](api/01-rest-api.md)** —— 聊天补全、`auto:*` 路由策略、流式、工具调用、视觉、Gemini 的 Google 搜索接地、嵌入、响应头,以及 Anthropic Messages 接口。
+- **[客户端与编程智能体](../../../clients/01-agent-clients.md)** —— 兼容 OpenAI 的客户端,Claude Code / Codex CLI / Cline / Continue / Aider / opencode / Cursor 的配方,MCP 服务,编辑器补全,以及上下文交接。
+- **[提示词压缩](../../../compression/01-compression-pipeline.md)** —— 请求侧的各种模式、安全保护、按请求的控制项、自定义工具输出过滤器、统计数据和预览 API。
- **[架构与内部实现](../../../architecture.md)** —— 路由器如何工作、路由与运维细节、哪些还不支持、诚实的局限性说明,以及各提供方的服务条款审查。
## 更多
@@ -22,7 +22,7 @@
- [桌面应用](../../../../desktop/README.md) —— 构建和打包 Electron 应用。
- [贡献者指南](../../../../CONTRIBUTING.md) —— 开发流程、测试要求和贡献政策。
- [数据库迁移](../../../../server/src/db/README.md) —— 创建、应用、查看和回滚 schema 迁移。
-- [翻译指南](../../../translating.md) —— 仪表盘字符串的规则,以及中文术语约定。
+- [翻译指南](../../01-translating.md) —— 仪表盘字符串的规则,以及中文术语约定。
## docs 目录里的站点资源
diff --git a/docs/i18n/zh-CN/docs/api.md b/docs/i18n/zh-CN/docs/api/01-rest-api.md
similarity index 97%
rename from docs/i18n/zh-CN/docs/api.md
rename to docs/i18n/zh-CN/docs/api/01-rest-api.md
index 6592f722..3d5bddcb 100644
--- a/docs/i18n/zh-CN/docs/api.md
+++ b/docs/i18n/zh-CN/docs/api/01-rest-api.md
@@ -1,8 +1,8 @@
-[English](../../../api.md) · **简体中文**
+[English](../../../../api/01-rest-api.md) · **简体中文**
# API 参考
-[← 返回 README](../README.md) · [文档索引](README.md)
+[← 返回 README](../README.md) · [文档索引](../README.md)
任何兼容 OpenAI 的客户端都能用(Anthropic / Claude 客户端也可以,见 [Anthropic 与 Claude 客户端](#anthropic-与-claude-客户端))。Base URL 为 `http://localhost:3001/v1`,统一密钥在仪表盘的密钥页获取。`GET /v1/docs` 提供一个覆盖所有代理端点的交互式 OpenAPI 浏览器;规范文件本身在 `GET /v1/openapi.json`。
@@ -225,7 +225,7 @@ HTTP 头只能携带可打印的 ASCII 字符,所以模型 id 里超出这个
可选开启的响应缓存能按请求用 `X-FreeLLM-Cache: on|off` 开关。它是一个针对完全相同的非流式请求做精确匹配的内存 LRU(以整个请求的规范化 SHA-256 为键,带 TTL 和温度门槛,节省量统计显示在仪表盘上)。默认关闭;缓存命中不消耗任何提供方额度。
-启用[提示词压缩](../../../compression.md)后,`X-FreeLLM-Compress: off|on|lossless|standard|aggressive` 可以对单次请求关闭或调低已配置的模式,但不能高于运维方配置的模式。响应会报告实际生效的模式和预估节省量,例如 `X-FreeLLM-Compress: standard; saved~=1840`。
+启用[提示词压缩](../compression/01-compression-pipeline.md)后,`X-FreeLLM-Compress: off|on|lossless|standard|aggressive` 可以对单次请求关闭或调低已配置的模式,但不能高于运维方配置的模式。响应会报告实际生效的模式和预估节省量,例如 `X-FreeLLM-Compress: standard; saved~=1840`。
## 嵌入
diff --git a/docs/i18n/zh-CN/docs/api/CHANGELOG.md b/docs/i18n/zh-CN/docs/api/CHANGELOG.md
new file mode 100644
index 00000000..60b16f54
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/api/CHANGELOG.md
@@ -0,0 +1,9 @@
+[English](../../../../api/CHANGELOG.md) · **简体中文**
+
+# API 域 —— 变更日志
+
+`docs/api/` 的文档修订历史。最近的在前。
+
+## 2026-08-23 —— 文档重组
+
+- **e8dde9e** `docs(api): fold API guide into api domain` — `docs/api.md` → `docs/api/01-rest-api.md`,补 `OVERVIEW.md` + `CHANGELOG.md` 脚手架。
diff --git a/docs/i18n/zh-CN/docs/api/OVERVIEW.md b/docs/i18n/zh-CN/docs/api/OVERVIEW.md
new file mode 100644
index 00000000..650ae870
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/api/OVERVIEW.md
@@ -0,0 +1,17 @@
+[English](../../../../api/OVERVIEW.md) · **简体中文**
+
+# API 域 —— 概览与文件索引
+
+本目录镜像 FreeLLMAPI 的 OpenAI 兼容 HTTP 接口及 Anthropic/Gemini 兼容适配层的英文文档。
+
+## 文件索引
+
+| 文件 | 范围 |
+|------|-------|
+| [`01-rest-api.md`](01-rest-api.md) | OpenAI 兼容端点(`/v1/chat/completions`、`/v1/responses`、`/v1/embeddings`、`/v1/models`、流式、工具调用、视觉、Gemini grounding、响应头)及 Anthropic Messages 接口(`/v1/messages`)。 |
+| [`CHANGELOG.md`](CHANGELOG.md) | 本域文档修订历史 |
+
+## 导航
+
+- ← [文档根目录](../README.md)
+- API 参考:[`01-rest-api.md`](01-rest-api.md)
diff --git a/docs/i18n/zh-CN/docs/architecture/01-routing-and-bandit-scoring.md b/docs/i18n/zh-CN/docs/architecture/01-routing-and-bandit-scoring.md
new file mode 100644
index 00000000..b6521dd4
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/architecture/01-routing-and-bandit-scoring.md
@@ -0,0 +1,235 @@
+[English](../../../../architecture/01-routing-and-bandit-scoring.md) · **简体中文**
+
+# 路由与老虎机评分 —— 深度剖析
+
+> **源码:** `server/src/services/router.ts`、`server/src/services/scoring.ts`
+
+## 1. 概览
+
+路由器为每个请求挑选一个 `(platform, model, key)` 三元组。它**不是**轮询负载均衡器——它是一个持续从实时流量学习的上下文老虎机,从五个归一化轴合成一个分数:
+
+```
+base = w_rel·reliability + w_speed·speed + w_intel·intelligence (凸组合,权重和为 1)
+effective = base × headroomFactor × rateLimitFactor (护栏乘数 ∈ [floor, 1])
+```
+
+**权重**来自可选策略(`balanced` / `smartest` / `fastest` / `reliable` / `custom` / `priority`)。默认是 `balanced`(0.5 / 0.25 / 0.25)。操作者可从仪表盘或经 `PUT /api/fallback/routing` 切换策略。
+
+---
+
+## 2. 链构建
+
+启用的回退链按优先级从以下来源取:
+
+1. **活跃配置档**(`profile_models` 表)——命名链如 "coding"、"long-context"
+2. **全局 fallback_config**——旧版单链
+3. **全局排序别名**——`auto:smart`、`auto:fast`、`auto:cheap`、`auto:reliable`、`auto:balanced`
+4. **按名配置档**——`auto:my-profile`
+
+每个链行(`ChainRow`)携带模型的静态元数据(`intelligence_rank`、`size_label`、`monthly_token_budget`、限流、能力)加上**端点作用域**(目录模型为 `''`,中继模型为 `'custom:<base_url_hash>'`),这样服务同一 `model_id` 的两个中继能独立评分、独立限流。
+
+### 匹配层级
+
+`match_tier`(默认 0)是**外层排序键**,支配分数。仅当统一组把一个 slug(如 `glm-4.7`)解析到提供方专属模型(如 `z-ai/glm-4.5`)时才设置——被匹配的成员得 `match_tier = 1`,这样无论它的实时数字多好,永远不会超越直接请求 `model_id` 的行。
+
+---
+
+## 3. 可靠性 —— 带 Beta 后验的 Thompson 采样
+
+### 衰减加权样本
+
+可靠性不是原始成功率。分析窗口 7 天,**2 天半衰期**指数衰减:
+
+```
+weight(age_days) = 0.5^(age_days / 2)
+```
+
+每个请求桶(按 `platform, model_id, key_id, age_days` 分组)贡献衰减加权的伪计数到 `successes` 和 `failures`。超时对可靠性算**失败**但对速度**有贡献**(挂钟延迟、零词元)。
+
+### 后验与采样
+
+```
+α = successes + community_successes + 1 (Beta(1,1) 均匀先验)
+β = failures + community_failures + 1
+```
+
+- **路由(实时)**:`reliability = sampleBeta(α, β)` —— Thompson 采样。探索自动且与不确定性成正比。
+- **仪表盘(显示)**:`reliability = α / (α + β)` —— 期望值,排序稳定。
+
+### 社区先验(可选)
+
+`routing_community_prior_enabled = 1` 时,来自其他自托管实例的去毒聚合计数折入后验作起始余额。每个先验封顶 **50 个有效样本**,所以本地证据(衰减加权、繁忙实例上百个样本)几百请求内就占主导。
+
+### 探索底线(10%)
+
+`routing_explore_enabled = 1` 时(默认关),未测量模型(衰减加权 `successes + failures < 5`)获得**保底 10% 概率**被优先尝试,防止被先验重的对手饿死。老虎机的 Thompson 采样本身就会探索;这是个硬底线。
+
+---
+
+## 4. 速度轴 —— 吞吐 + TTFB 混合
+
+```
+throughputScore(tok/s) = 1 - exp(-tok/s / 60) # 饱和,60 tok/s ≈ 0.63
+ttfbScore(ms) = 线性斜坡 300ms→1.0 … 5000ms→0.0
+speedScore = 0.6·throughput + 0.4·ttfb # 两者皆有时
+```
+
+- 无成功样本 → 返回 `SPEED_PRIOR = 0.6`(乐观,让未测模型在速度上也被探索)。
+- 仅有吞吐(无 TTFB)→ 单用吞吐。
+- 仅有 TTFB(无吞吐)→ 单用 TTFB。
+
+**超时喂速度**(#619):超时把其封顶挂钟延迟(最长 120s)算进吞吐分母且**零输出词元**,同一延迟也作 TTFB 样本(落在 `TTFB_WORST_MS` 之后,得零延迟信用)。一个老是挂起的模型不能再靠着优秀的速度数混日子。
+
+### 观测速度秩回写
+
+每 10 分钟,拥有 ≥20 个衰减加权速度承载样本(成功+超时)且无用户设置 `speed_rank` 覆盖的模型,把观测速度投影回目录 1..10 的 `speed_rank` 刻度(1 = 最快)。这让仪表盘的按速度排序预设对中继模型也诚实。
+
+---
+
+## 5. 智能轴 —— 层优先,√-压缩秩
+
+```
+tierValue: Frontier=4, Large=3, Medium=2, Small=1, unknown=0
+intelligenceComposite = tierValue * 1000 - sqrt(rank) * 31
+```
+
+- **层严格占优**:某层最差秩(√1000·31 ≈ 980)仍打赢下一层最好秩(1000)。
+- **秩编辑可见**:√ 压缩让 1→3→10 的变化在轴上明显移动,不像旧线性秩被层乘数淹没。
+- 在启用链上做 min-max 归一化到 [0,1]。
+
+自定义模型按目录中位数层播种("unknown" = 无意见,不是"最差")。
+
+---
+
+## 6. 护栏 —— 乘法,从不重排好模型
+
+### 余量因子(额度保护)
+
+```
+remaining = 1 - usedTokens / budgetTokens
+if remaining >= 0.2: factor = 1.0
+else: factor = 0.1 + 0.9 * (remaining / 0.2) # 线性斜坡到底线 0.1
+```
+
+- `budgetTokens` = `monthly_token_budget` × `usableKeyCount(platform)` —— 汇聚 N 个密钥的免费额度。
+- 未知预算(0 或 NULL)→ factor = 1(无意见)。
+
+### 限流因子(实时惩罚)
+
+```
+penalty ∈ [0, 10] (来自 429 升级阶梯,每 2 分钟衰减 1)
+factor = 1 - (penalty / 10) * 0.6 # 最大惩罚时保留 40% 分数
+```
+
+- 强降但不排除——惩罚衰减时模型恢复。
+
+---
+
+## 7. 按模型权重覆盖(环境变量:`MODEL_ROUTING_OVERRIDES`)
+
+```
+MODEL_ROUTING_OVERRIDES='{"gpt-4o": {"weight": 0.5}, "llama-3.3-70b": {"weight": 1.5}}'
+```
+
+缩放**最终有效分数**(护栏之后),让又慢又烂的模型降级而不禁用。手动 `priority` 链仍可选它。
+
+---
+
+## 8. 模型内密钥选择(密钥级老虎机)
+
+模型有多密钥时,密钥按**密钥级 Thompson 分数**排序:
+
+```
+keyReliability = sampleBeta(α_key + community_α, β_key + community_β)
+keySpeed = speedScore(keyStats.tokPerSec, keyStats.avgTtfbMs)
+keyScore = 0.75·keyReliability + 0.25·keySpeed
+```
+
+<2 个密钥有记录数据时返回 `null`(回退轮询)。捕捉汇总模型桶看不见的过期/耗尽/区域封锁密钥。
+
+---
+
+## 9. 回退循环与耗尽诊断
+
+共享循环(`lib/fallback-loop.ts`)驱动所有面(`/v1/chat/completions`、`/v1/responses`、`/v1/messages`、旧版 `/completions`):
+
+- **最多 20 次重试**(可配)。
+- **挂钟重试预算**(默认 45s,设置 `fallback_time_budget_ms`)。预算用完后不再**发起**新尝试,改返回耗尽错误(首次尝试总跑;进行中的尝试绝不中途截断)。
+- **对冲**(1d2226a):预算中途过期时,`abortInFlight()` 取消上游取获,而不是等停滞。
+- **断路器**:`max_consecutive_upstream_fails`(默认 0 = 关)在池看起来不健康时以 503 停下循环。
+- **逐尝试轨迹**:`X-Fallback-Trail` 头 + `X-Fallback-Detail`(可选)含耗时和脱敏错误摘要。
+- **同步耗尽**(零上游调用):`RouteError.diagnostics` 逐行记录每个被考虑模型及其不能服务的理由(无密钥、冷却、提供方上限、rpm/rpd、tpm/tpd、上下文太小……)。`summarizeExhaustion()` 把这卷成客户端安全的分桶消息(如 "All models exhausted: 5 routes checked (3 rate-limited or on cooldown, 2 no usable key configured). Add more API keys or wait for rate limits to reset. Soonest reset ~2m.")。
+
+### 失败分类与记账
+
+| 错误 | 跳过范围 | 冷却 | 模型惩罚 | 限流学习 |
+|-------|----------|------|----------|----------|
+| 401 无效密钥 | 仅密钥 | 5 min(健康周期) | 否 | 否 |
+| 402 需付款 | 仅密钥 | 24h | 否 | 否 |
+| 403 模型被禁 | **模型** | 24h | 否 | 否 |
+| 429 每日耗尽 | 模型+密钥 | 到 UTC 午夜 / Retry-After | 重 (3) | 是 |
+| 429 瞬时 (rpm/tpm) | 仅密钥 | 90s / 升级阶梯 | 轻 (1) | 是 |
+| 5xx / 超时 / 传输 | **平台** (#788) | 90s / 阶梯 | 轻 (1) | 否 |
+| 空补全(推理) | 仅密钥 | **豁免**(连击 ≤3) | 否 | 否 |
+| 上下文过大 | 模型 | — | 否 | 否 |
+| response_format 被忽略 | 模型 | — | 否 | 否 |
+
+- **模型级失败停用**(#806):15 分钟内跨密钥 3 次可重试失败 → 模型在**其所有密钥**上停用 10 分钟(启发式、可探测)。
+- **空补全连击限制**(#751):同一模型+密钥上连续 3 次推理截断补全 → 豁免取消 → 正常冷却/惩罚/限流学习生效。
+
+---
+
+## 10. 粘性会话
+
+- 键 = SHA-1(首条用户消息 [:: strategyKey]),TTL 30 分钟。
+- 防止会话中途换模型 → 幻觉激增。
+- 会话亲和推理轨迹记忆(#797):恢复客户端回放时剥离的 `reasoning_content`,作用域限定在生成它的模型。
+
+---
+
+## 11. 统一模型组(Unify)
+
+启用时,逻辑模型(如 `glm-4.7`)把多提供方折叠成一个 `/v1/models` 条目。路由**严格在组内回退**——绝不去别的模型。slug 解析成员上的 `match_tier = 1` 防止静默替换。
+
+---
+
+## 12. 策略预设
+
+| 策略 | 可靠性 | 速度 | 智能 |
+|----------|-------------|-------|--------------|
+| balanced | 0.50 | 0.25 | 0.25 |
+| smartest | 0.35 | 0.10 | 0.55 |
+| fastest | 0.35 | 0.55 | 0.10 |
+| reliable | 0.70 | 0.15 | 0.15 |
+| custom | 用户自调(归一化) | | |
+| priority | 手动顺序 + 429 惩罚(密集秩 + 惩罚) | | |
+
+---
+
+## 13. 关键函数 (router.ts)
+
+| 函数 | 用途 |
+|----------|---------|
+| `routeRequest(...)` | 主入口:选路由,应用所有过滤(视觉、工具、粘性、组、response_format) |
+| `orderChain(chain, strategy, sampled)` | 按策略排序链;`sampled=true` 实时路由,`false` 稳定仪表盘 |
+| `scoreChainEntry(...)` | 算五轴 + 护栏 → 最终分 |
+| `orderKeysByScore(entry, keys)` | 密钥级 Thompson 排序 |
+| `resolveRoutingChain(modelString)` | 解析 `auto`、`auto:smart`、`auto:profile-name` |
+| `recordRateLimitHit/recordModelFailure/recordSuccess` | 惩罚突变 |
+| `summarizeExhaustion(diag, soonestResetMs)` | 客户端安全耗尽消息 |
+
+---
+
+## 14. 关键函数 (scoring.ts)
+
+| 函数 | 用途 |
+|----------|---------|
+| `reliabilityPosterior(s, f, community?)` | 返回 `{alpha, beta}` |
+| `expectedReliability(s, f, community?)` | 确定性 α/(α+β) |
+| `sampleBeta(α, β)` | Marsaglia & Tsang 双 Gamma 抽样 |
+| `speedScore(tok/s, ttfbMs)` | 混合 [0,1] 速度 |
+| `intelligenceComposite(sizeLabel, rank)` | 层优先复合 |
+| `intelligenceScore(composite, min, max)` | Min-max 归一化 |
+| `headroomFactor(used, budget)` | 额度护栏乘数 |
+| `rateLimitFactor(penalty)` | 惩罚护栏乘数 |
+| `combineScore(inputs, weights)` | 凸基础 × 护栏 |
\ No newline at end of file
diff --git a/docs/i18n/zh-CN/docs/architecture/02-quota-and-cooldown-engine.md b/docs/i18n/zh-CN/docs/architecture/02-quota-and-cooldown-engine.md
new file mode 100644
index 00000000..b610d145
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/architecture/02-quota-and-cooldown-engine.md
@@ -0,0 +1,252 @@
+[English](../../../../architecture/02-quota-and-cooldown-engine.md) · **简体中文**
+
+# 额度与冷却引擎 —— 深度剖析
+
+> **源码:** `server/src/services/ratelimit.ts`、`server/src/services/cooldown-probe.ts`、`server/src/services/provider-quota.ts`
+
+## 1. 概览
+
+额度引擎是路由器与上游提供方之间的**看门人**。它为每个 `(platform, model, key)` 维护四个滑动窗口加提供方级池、持久化到 SQLite、并从提供方错误正文学真实限额。冷却用升级阶梯停用失败的密钥/模型,后台探测任务提前恢复启发式冷却。
+
+---
+
+## 2. 四维额度核算
+
+### 按 (平台, 模型, 密钥) 的窗口
+
+| 窗口 | 宽度 | 持久化列 | 内存兜底 |
+|--------|-------|------------------|-------------------|
+| RPM | 60 s | `rpm_limit` | `timestamps[]` |
+| RPD | 24 h (UTC 午夜) | `rpd_limit` | `timestamps[]` |
+| TPM | 60 s | `tpm_limit` | `{ts, tokens}[]` |
+| TPD | 24 h (UTC 午夜) | `tpd_limit` | `{ts, tokens}[]` |
+
+- RPM/TPM 用**滑动分钟**;RPD/TPD 用 **UTC 天边界**(提供方在午夜重置,不是 24h 滚动)。
+- `rate_limit_usage` 表:每个请求/词元事件一行,`kind = 'request' | 'tokens'`,`created_at_ms`。
+- 留存:1 天(插入时修剪,节流到 1/分)。
+- **降级模式**:数据库写失败时,计数只进内存窗口(推入时修剪,长故障也不会无界增长)。
+
+### 暂存用量(在途租约)
+
+> **把 check-then-act 缝紧。** 从选密钥到事后 `recordRequest/recordTokens` 写入之间,N 个并发请求会读到同一个预检值,合力冲破限额。**租约让在途请求对下一个调用者可见。**
+
+```typescript
+acquireLease(platform, modelId, keyId, estimatedTokens) → leaseId
+releaseLease(leaseId) // finally 块里,幂等
+```
+
+- 租约同时计入**分钟和天窗口**(一个在途请求属于本分钟也属于今天)。
+- 最大租约寿命:2 分钟(泄漏租约的兜底)。
+- 按密钥并发上限(经 `MAX_CONCURRENT_REQUESTS_PER_KEY[_PLATFORM]` 可选开启)。
+
+### 提供方级池
+
+有些提供方在**整个账号**上强制一个额度,不是按模型:
+
+| 池 | 提供方 | 配置 |
+|------|-----------|--------|
+| 每日请求 | OpenRouter(免费 1000/天,<10 积分 50/天)、ModelScope(2000→1800 边际) | `PROVIDER_DAILY_REQUEST_CAP_<PLATFORM>` |
+| 每日词元 | NavyAI(共享 150K/天,模型乘数) | `PROVIDER_DAILY_TOKEN_CAP_<PLATFORM>` |
+| 每分钟请求 | NVIDIA NIM(账号级 40 RPM) | `PROVIDER_MINUTE_REQUEST_CAP_<PLATFORM>` |
+
+- 通过对同一 `platform + keyId` 的各模型窗口求和来计数。
+- NavyAI 词元乘数从 `monthly_token_budget` 标签(如 `2x`)解析或从 `tpd_limit` 推导。
+
+### 提供方额度键(跨模型池化)
+
+`inferQuotaPoolKey(platform, modelId)` → 形如 `openrouter::free`、`google::project`、`nvidia::account` 的字符串。供分析把用量归到正确的共享桶。
+
+---
+
+## 3. 冷却阶梯与来源
+
+### 来源
+
+| 来源 | 含义 | 可探测? |
+|--------|---------|-----------------|
+| `heuristic` | 我们自己的猜测(瞬时 90s、升级阶梯、鉴权失败停用、空补全) | **是** |
+| `authoritative` | 有显式提供方 Retry-After 或每日额度重置支撑(事实) | 否 |
+| `credit` | 402 额度用光——密钥校验对充值证明不了任何事 | 否 |
+| `tier` | 403 模型不在档位——密钥校验通过但模型仍被档位门槛挡住 | 否 |
+
+### 升级阶梯(按模型+密钥,滚动 24h)
+
+| 命中数 | 时长 | 注记 |
+|-------|----------|-------|
+| 1 | 2 min | |
+| 2 | 10 min | |
+| 3 | 1 h | |
+| 4+ | 24 h | |
+
+- 日计数器健康时的**瞬时 RPM/TPM 429** → 短 90s 冷却,**不计入**阶梯。
+- **每日耗尽**(RPD/TPD 计数器 ≥ 上限) → 走阶梯(最多 24h)。
+- **未知限额**(NULL RPD/TPD):启发式——1 小时内 2+ 次 429 → "实际上每日耗尽" → 升级**但封顶 10 分钟**(`UNKNOWN_LIMIT_MAX_COOLDOWN_MS`)。防止 Ollama/Cloudflare 等在每个请求都是 429 时陷入 90s 死循环。
+- **本地端点**(环回/RFC1918 `base_url`):封顶 **5 s**,绝不升级(#592)。
+
+### Retry-After 处理
+
+```
+if (retryAfterMs > ourBench) → bench = min(retryAfterMs, 24h), source = 'authoritative'
+else → our bench 维持, source = 'heuristic'
+```
+
+提供方给的重置时间胜出;超过它的部分是我们猜的。
+
+### 特殊冷却
+
+| 触发 | 时长 | 来源 |
+|---------|----------|--------|
+| 402 需付款 | 24 h | `credit` |
+| 403 模型被禁 | 24 h | `tier` |
+| 每日额度耗尽(显式) | 到 UTC 午夜 / Retry-After | `authoritative` |
+| 鉴权失败 (401) | 5 min(健康周期) | `heuristic` |
+| 空补全连击(≥3) | 正常阶梯 | `heuristic` |
+
+---
+
+## 4. 从错误正文学真实限额 (#798)
+
+提供方拒绝时在正文里给出真实限额时,我们**持久化它**,让预检在下一次 413/429 前拦住我们。
+
+```typescript
+// Groq 413: "...on tokens per minute (TPM): Limit 30000, Requested 33476"
+parseProviderLimit(message) → { kind: 'tpm', limit: 30000 }
+learnLimitFromError(modelDbId, err) → 写入 models.tpm_limit(如果 NULL 或更低)
+```
+
+- **只收紧**:填 NULL 或**降低**现有限额。永不升高——撞上天花板意味着预检已经放行过量。
+- 轴优先级:TPD → TPM → RPD → RPM(天先于分钟,词元先于请求)。
+- 要求**同时**有 "Limit N" 和自信的轴匹配——不猜。
+
+---
+
+## 5. 冷却探测提前恢复 (`cooldown-probe.ts`)
+
+### 目的
+
+启发式冷却是悲观的。提供方更早恢复(分钟窗口滚过、事故结束)时,产能会闲置到计时器过期。探测任务**校验密钥**并提前清除启发式冷却。
+
+### 算法
+
+- **扫描间隔**:60 s(在 `rate_limit_cooldowns` 上做便宜的索引 SELECT,`source = 'heuristic'`)。
+- **成熟度**:冷却必须已过 ≥50% **且** 剩余 ≥60 s。
+- **按密钥退避**:2m → 4m → 8m → 15m 封顶(探测失败 = 退避,冷却不变)。
+- **首见错开**:重启时所有持久化冷却一次性被看见。首次探测排在 `now + jitter(0..45s)` 避免惊群。
+- **预算**:`COOLDOWN_PROBE_MAX_PER_PASS`(默认 3,环境变量可调)。
+- **探测通过时**:清除该密钥的**所有**启发式冷却(跨模型),记 `cooldown_recovered` 事件。
+- **绝不探测**:authoritative/credit/tier 冷却(查询时过滤掉)。
+
+### 熔断开关
+
+`COOLDOWN_PROBE_DISABLED=1`
+
+---
+
+## 6. 关键函数 (ratelimit.ts)
+
+| 函数 | 用途 |
+|----------|---------|
+| `canMakeRequest(platform, modelId, keyId, limits)` | RPM+RPD+在途租约预检 |
+| `canUseTokens(platform, modelId, keyId, estTokens, limits)` | TPM+TPD+在途租约预检 |
+| `canUseProvider(platform, keyId)` | 提供方级每日请求上限 |
+| `canUseProviderMinute(platform, keyId)` | 提供方级每分钟请求上限 |
+| `canUseProviderTokens(platform, keyId, modelId, estTokens)` | 提供方级每日词元上限 |
+| `recordRequest/recordTokens` | 成功后核算(DB + 在途释放) |
+| `acquireLease/releaseLease` | 在途并发 + 暂存用量 |
+| `getCooldownDecisionForLimit(...)` | 完整阶梯 + Retry-After + 来源 |
+| `setCooldown(platform, modelId, keyId, durationMs, source)` | 持久化 + 内存 |
+| `isOnCooldown(platform, modelId, keyId)` | 查内存 → DB → 过期 |
+| `getProbeableCooldowns()` | 仅启发式,给探测任务 |
+| `clearCooldownEarly(platform, modelId, keyId)` | 探测恢复(保留升级历史) |
+| `parseProviderLimit(message)` | 从错误正文提取 `{kind, limit}` |
+| `learnLimitFromError(modelDbId, err)` | 收紧时持久化 |
+| `getSoonestCooldownExpiry()` | 给 `Retry-After` 头 + 耗尽消息 |
+
+---
+
+## 7. 关键函数 (cooldown-probe.ts)
+
+| 函数 | 用途 |
+|----------|---------|
+| `runCooldownProbePass(opts?)` | 一次扫描 → 探测成熟密钥 → 通过即清除 |
+| `isRipe(cooldown, now)` | ≥50% 已过 + ≥60s 剩余 |
+| `startCooldownProbe(scheduler)` | 注册 60s 间隔任务 |
+| `resetCooldownProbeState()` | 测试缝合点 |
+
+---
+
+## 8. 持久化 Schema(相关表)
+
+```sql
+-- 按 (平台,模型,密钥) 的用量事件
+CREATE TABLE rate_limit_usage (
+ platform TEXT, model_id TEXT, key_id INTEGER,
+ kind TEXT CHECK(kind IN ('request','tokens')),
+ tokens INTEGER, created_at_ms INTEGER
+);
+CREATE INDEX idx_rate_limit_usage_lookup
+ ON rate_limit_usage(platform, model_id, key_id, kind, created_at_ms);
+
+-- 带来源的冷却
+CREATE TABLE rate_limit_cooldowns (
+ platform TEXT, model_id TEXT, key_id INTEGER,
+ expires_at_ms INTEGER, source TEXT CHECK(source IN ('heuristic','authoritative','credit','tier')),
+ set_at_ms INTEGER,
+ PRIMARY KEY (platform, model_id, key_id)
+);
+
+-- 服务器日志(仅 warn/error)
+CREATE TABLE server_logs (
+ id INTEGER PRIMARY KEY, level TEXT, source TEXT, provider TEXT,
+ model TEXT, event TEXT, request_id TEXT, message TEXT, created_at_ms INTEGER
+);
+```
+
+---
+
+## 9. 环境变量
+
+| 变量 | 默认值 | 用途 |
+|----------|---------|---------|
+| `MAX_CONCURRENT_REQUESTS_PER_KEY` | null(无限) | 全局按密钥并发上限 |
+| `MAX_CONCURRENT_REQUESTS_PER_KEY_<PLATFORM>` | null | 平台专属覆盖 |
+| `PROVIDER_DAILY_REQUEST_CAP_<PLATFORM>` | 见表 | 提供方级每日请求上限(0 = 关) |
+| `PROVIDER_DAILY_TOKEN_CAP_<PLATFORM>` | 见表 | 提供方级每日词元上限 |
+| `PROVIDER_MINUTE_REQUEST_CAP_<PLATFORM>` | 见表 | 提供方级每分钟请求上限 |
+| `COOLDOWN_PROBE_DISABLED` | 0 | 探测任务熔断开关 |
+| `COOLDOWN_PROBE_MAX_PER_PASS` | 3 | 每 60s 扫描的探测数 |
+| `DEGRADED_HEALTHY_RATIO` | 0.5 | 降级模式阈值(见 04-degraded-mode) |
+| `DEGRADED_MIN_PROVIDERS` | 3 | 降级评估的最少提供方数 |
+| `DEGRADED_ENTRY_GRACE_MS` | 60000 | 低于阈值多久后进入 |
+| `DEGRADED_EXIT_GRACE_MS` | 120000 | 高于阈值多久后退出 |
+
+---
+
+## 10. 流程图:请求 → 额度检查 → 派发 → 核算
+
+```
+routeRequest()
+ ├─ canMakeRequest() → RPM + RPD + 在途租约
+ ├─ canUseTokens() → TPM + TPD + 在途租约
+ ├─ canUseProvider() → 提供方每日请求上限
+ ├─ canUseProviderMinute() → 提供方每分钟请求上限
+ ├─ canUseProviderTokens() → 提供方每日词元上限
+ ├─ canUseKeyConcurrency() → 按密钥并发上限
+ └─ isOnCooldown() → 启发式/权威性停用
+ ↓
+acquireLease() (暂存用量对下一个调用者可见)
+ ↓
+派发给提供方
+ ↓
+成功:
+ recordRequest() → DB + releaseLease()
+ recordTokens() → DB + releaseLease()
+ 清除冷却命中 / 空限额命中
+失败(可重试):
+ recordRetryableFailure() → cooldownDecisionForError() → setCooldown()
+ recordRateLimitHit() / recordModelFailure() (模型惩罚)
+ learnLimitFromError() (提供方报了天花板)
+ skipKeys.add(platform:modelId:keyId)
+ 403/404/上下文过大 → skipModels.add(modelDbId)
+ 5xx/超时 → skipPlatforms.add(platform) (#788)
+```
\ No newline at end of file
diff --git a/docs/i18n/zh-CN/docs/architecture/03-streaming-pipeline.md b/docs/i18n/zh-CN/docs/architecture/03-streaming-pipeline.md
new file mode 100644
index 00000000..b987f6d0
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/architecture/03-streaming-pipeline.md
@@ -0,0 +1,259 @@
+[English](../../../../architecture/03-streaming-pipeline.md) · **简体中文**
+
+# 流式管线 —— 深度剖析
+
+> **源码:** `server/src/routes/proxy.ts`、`server/src/routes/responses.ts`、`server/src/routes/anthropic.ts`、`server/src/lib/fallback-loop.ts`
+
+## 1. 设计原则
+
+- **纯 SSE** —— 零 WebSocket。每个面(`/v1/chat/completions`、`/v1/responses`、`/v1/messages`、旧版 `/completions`)都经 Server-Sent Events 流式。
+- **轮次完整性** —— 流作为**轮次**校验,不是传输。头部拿到首个真实载荷前保留;在此之前挂掉的隐式回退。
+- **流中回退** —— 错误帧在头部刷出前到达则可重试;刷出后则诚实浮出(stream_error)。
+- **统一回退循环** —— 所有面共享 `lib/fallback-loop.ts` 做重试预算、冷却、尝试轨迹、耗尽渲染。
+
+---
+
+## 2. OpenAI Chat Completions (`/v1/chat/completions`)
+
+### 请求流
+
+```
+解析 + 校验 (zod)
+ ├─ 压缩(可选,X-FreeLLM-Compress)
+ ├─ 系统提示词注入(配置档强制)
+ ├─ 图片降采样 (normalizeMessageImages)
+ ├─ 词元估算(chars/4 启发式)
+ ├─ 视觉/工具闸门(无能模型则 422)
+ ├─ 词元预算护栏 (request_max_tokens_budget)
+ ├─ 响应缓存检查(可选、精确匹配 LRU)
+ ├─ 粘性会话 / 上下文交接
+ ├─ 解析路由链(auto / 固定 / 组)
+ └─ runFallbackLoop()
+ ├─ route() → 选模型+密钥
+ ├─ dispatch() → streamChatCompletion()
+ ├─ 成功 → recordUpstreamSuccess()、记日志、缓存存入
+ ├─ 可重试失败 → recordRetryableFailure()、冷却、skipKeys、下一个
+ ├─ 致命 → onFatal() (502)
+ └─ 耗尽 → exhaustedRetryError() → onExhausted() (429/502/413/404/503)
+```
+
+### 流式泵 (`proxy.ts` 行 ~1873–2150)
+
+**每尝试状态机:**
+
+```
+mode = 'undecided' | 'passthrough' | 'dialect'
+heldText = ''
+preamble = [] // 角色/保活块,持有到模式定夺
+toolCallAcc = Map<index, {id, name, args}>
+ttfbMs = null // 任意类型的首词元(内容或推理)
+headerSent = false
+```
+
+**逐块:**
+
+1. **元数据捕获**:`upstreamModel`(首个带 `model` 字段的帧)、`lastMeta`(id/created/model,供我们分帧用)。
+2. **带内错误帧**(`{error:..., choices: undefined}`):
+ - 头部前:抛出 → 回退
+ - 头部后:写错误帧 + `[DONE]` → `committed`
+3. **用量帧**:落在哪捕哪(无 choice 或最后一个 choice 上),我们的结束块后重发一次。
+4. **推理累积**(#764):`streamReasoningText()` 提取 `reasoning_content` / `reasoning`;加入 `streamReasoning` 供会话记忆 + 词元核算。
+5. **工具调用增量**:缓冲在 `toolCallAcc`,末尾对请求 schema 修参数。
+6. **内容文本**:`streamChunkText()` 提取 `delta.content`。
+7. **TTFB**(#764):在**任意类型首词元**(内容**或**推理)上记录。
+8. **模式裁决**:
+ - `undecided` + `wantsTools` + `startsWithDialectMarker(heldText)` → `dialect`(全缓冲)
+ - `undecided` + `!wantsTools` OR `!couldBecomeDialectMarker` OR `heldText > 256` → `passthrough`,刷头部、流式转发
+ - `passthrough` → 即时转发(从 delta 剥 tool_calls,末尾补全重发)
+ - `dialect` → 继续缓冲
+9. **空块**(角色/保活/仅推理):攒在 `preamble` 等刷新。
+
+**流正常结束:**
+
+1. 组装缓冲工具调用 → `repairToolArguments()` 对请求 schema。
+2. `dialect` 模式:`rescueInlineToolCalls(heldText)` → 结构化 `tool_calls` 或回退。
+3. 发完整工具调用(单块、`finish_reason: 'tool_calls'`)。
+4. 发最终块(`finish_reason: 'stop' | 'length' | upstreamFinish`)。
+5. 发捕获的用量帧。
+6. `recordUpstreamSuccess()`、`logRequest()`、`observeServedModel()`、适用时存入缓存。
+
+**流中错误:**
+
+- 头部前:抛出 → 回退(下一模型)
+- 头部后:写 `stream_error` 帧 + `[DONE]` → `committed`(循环停,不再回退)
+
+### 词元核算(流式)
+
+- **输出词元**:`ceil((text.length + reasoning.length) / 4)` 每块——推理词元是真实消耗(#764)。
+- **TTFB**:到首个内容**或**推理词元的挂钟。
+- **非流对账**:提供方的 `usage` 块覆盖估算。
+
+---
+
+## 3. Anthropic Messages (`/v1/messages`)
+
+### 翻译层 (`routes/anthropic.ts`)
+
+| Anthropic | OpenAI (内部) |
+|-----------|-------------------|
+| `messages[]`(无 system 角色) | `system` + `messages[]` |
+| content 里的 `tool_use` 块 | `tool_calls` 数组 |
+| `tool_result` 块 | `tool` 消息 |
+| `stop_reason: 'tool_use'` | `finish_reason: 'tool_calls'` |
+| `thinking` budget/type | `reasoning_effort` / `max_completion_tokens` |
+
+**流式**:上游 OpenAI SSE → 逐块翻译成 Anthropic SSE 事件(`message_start`、`content_block_start`、`content_block_delta`、`content_block_stop`、`message_delta`、`message_stop`)。tool-use 块渲染成结构化 `tool_use` 内容块,不是内联文本。
+
+### 错误映射(耗尽)
+
+| FreeLLM 类别 | Anthropic 类型 |
+|--------------|----------------|
+| `auth` | `api_error` |
+| `bad_request` | `invalid_request_error` |
+| `rate_limit` | `overloaded_error` (429) |
+| `unavailable` | `overloaded_error` (503) |
+| `context_too_large` | `request_too_large` |
+| `model_not_found` | `not_found_error` |
+| `upstream` | `api_error` |
+
+---
+
+## 4. Gemini (`/v1beta` 经由 `/v1/chat/completions`)
+
+### 请求翻译 (`providers/gemini.ts`)
+
+- **基于 part 的内容**:`content: [{text:...}, {inline_data:...}, {function_call:...}]`
+- **系统提示词**:注入为首个 `user` 轮,`role: 'user'` + `parts: [{text: system}]`,再一个 `model` 确认(Gemini 要求角色交替)。
+- **工具调用**:`function_call` parts → 转发时变 OpenAI `tool_calls`;`function_response` parts ← OpenAI `tool` 消息。
+- **结构化输出**:`response_format: json_schema` → Gemini 原生 `responseSchema` + `responseMimeType: 'application/json'`。
+- **Thinking**:`thinking_config: {thinking_budget: N}` 从 `reasoning_effort` / `max_completion_tokens` 来。
+
+### 流式
+
+- 原生 Gemini SSE → `base.ts` `streamChatCompletion()` 里归一化成 OpenAI 块形状。
+- 内联工具调用方言(文本里的 `function_call`)被同一方言探测器救回。
+- `thought_signature` 随工具调用保留(#13)。
+
+---
+
+## 5. Responses API 适配 (`/v1/responses`)
+
+> **源码:** `server/src/routes/responses.ts`
+
+### 目的
+
+Codex CLI 和 Agents SDK 说 **Responses API**(有状态、`previous_response_id` 链式)。适配层双向翻译到/自 chat completions,这样同一套路由/额度/回退机制服务两者。
+
+### 翻译
+
+| Responses API | Chat Completions |
+|---------------|------------------|
+| `input`(字符串或数组) | `messages[]` |
+| `previous_response_id` | 粘性会话(sessionId = response_id) |
+| `tools`(function + `type: 'function'`) | `tools` + `tool_choice` |
+| `text.format` (json_schema) | `response_format: json_schema` |
+| `reasoning` (effort/summary) | `reasoning_effort` + `max_completion_tokens` |
+| `stream: true` | 带工具调用的加法式 `_fusion` 帧的 SSE |
+
+### 流式
+
+- 即刻开 SSE。
+- 工具调用作为加法式 `_fusion` 帧发(无 `choices`,标准客户端跳过) → 最终答案作为正常内容增量流出。
+- 非流响应上有 `response.output_text` 便利字段。
+
+### 回退
+
+- 共享 `runFallbackLoop()` —— 同重试预算、冷却、尝试轨迹。
+- 耗尽渲染映射到 Responses API 错误形状。
+
+---
+
+## 6. 旧版 Completions (`/v1/completions`)
+
+共享回退循环上的薄适配器:
+
+- `prompt` + `suffix` → chat 消息(system: "code autocomplete engine", user: prefix/suffix)。
+- 响应:`text_completion` 形状(choices[0].text)。
+- 流式:`legacyCompletionChunk()` 包装上游块。
+- 同提交点逻辑:头部拿到首文本前保留;推理词元计数(#764)。
+
+---
+
+## 7. Fusion 虚拟模型 (`model: "fusion"`)
+
+> **源码:** `server/src/services/fusion.ts`
+
+- 把提示词**并行扇给多样模型面板**(视觉/工具按成员过滤)。
+- **裁判模型**综合出一个答案。
+- 每个子调用走**正常路径**(冷却、额度、分析)。
+- 流式:面板/裁判事件的加法式 `_fusion` 帧,再裁判的综合作为正常内容增量。
+- 非流:裁判输出上的结构化输出强制(#516)。
+- 回退:面板成员在各自链内回退;裁判失败 → 回退到面板最佳。
+
+---
+
+## 8. 流中错误处理
+
+| 场景 | 头部前 | 头部后 |
+|----------|----------------|---------------|
+| 带内 `{error}` 帧 | 抛出 → 回退 | 写错误帧 + `[DONE]` → `committed` |
+| 客户端断开 | `clientGone` → 中止在途、不停用 | `clientGone` → 停拉取、`committed` |
+| 对冲中止(预算过期) | `abortInFlight()` → `HedgeAbortError` → 循环停、`timedOut` 耗尽 | 同 |
+| 空补全(无文本、无工具) | 抛出 `empty completion` → 回退 | N/A(早刷头部了) |
+| 上游分类输出 ("safe"/"unsafe") | 抛出 → 回退 (a961d93) | N/A |
+| 探测到工具方言 | 缓冲 → 末尾救回或回退 | N/A |
+
+---
+
+## 9. 每个响应都发的头部
+
+| 头部 | 值 |
+|--------|-------|
+| `X-Request-ID` | UUID(或客户端 `x-request-id`) |
+| `X-Routed-Via` | `platform/model` (safeHeaderValue) |
+| `X-Fallback-Attempts` | 成功/耗尽前的失败跳数 |
+| `X-Fallback-Trail` | `platform/model keyN=class; …`(最多 10,1KB) |
+| `X-Fallback-Detail` | **可选**:`platform/model keyN=outcome t=start+dur msg=summary; …`(2KB) |
+| `Retry-After` | 到最近冷却过期的秒数(429 耗尽) |
+| `X-FreeLLM-Cache` | `HIT` / `MISS`(响应缓存) |
+| `X-FreeLLM-Compress` | 压缩管线元数据 |
+
+---
+
+## 10. 关键函数 (proxy.ts)
+
+| 函数 | 用途 |
+|----------|---------|
+| `runFallbackLoop(hooks)` | 共享尝试循环(见 04-degraded-mode) |
+| `streamChunkText(chunk)` | 提取 `delta.content`(容忍无 choices 帧) |
+| `streamReasoningText(chunk)` | 提取 `delta.reasoning_content` / `delta.reasoning` |
+| `restoreSessionReasoning(messages, reasoning, platform)` | #797:回放客户端剥离的思考轨迹 |
+| `rememberReasoning(sessionKey, modelKey, reasoning)` | 按会话存轨迹 |
+| `rescueInlineToolCalls(text, tools)` | 内联方言 → 结构化 `tool_calls` |
+| `repairToolArguments(args, schemas)` | 对请求 schema 修双重编码 JSON |
+| `truncateMessagesForGithub(messages)` | 裁历史到 GitHub Models 输入天花板 |
+| `normalizeOutboundContent(chunk)` | 提供方专属响应归一化 |
+| `sanitizeResponse(chunk)` | 从流式帧脱敏机密 |
+
+---
+
+## 11. 并发与取消
+
+- **客户端断开**:`res.on('close')` → `clientGone = true`、`clientAbort.abort()` → 在途取获取消、租约即刻释放。
+- **对冲**(1d2226a):`hedgeAbort` 控制器,挂钟预算中途过期时调 `abortInFlight()`。`HedgeAbortError` 是**非提供方健康** → 无冷却/惩罚、渲染 `timedOut` 耗尽。
+- **租约释放**:`dispatch()` 的 `finally` 块里,幂等。在 `RouteResult` 上可选,这样 `finally` 里的 `TypeError` 不能替换上游错误。
+
+---
+
+## 12. 压缩管线(可选)
+
+`X-FreeLLM-Compress` 头 → `compressRequest(messages, {header, tools, cacheControlPrefixLength})` → 返回压缩后消息 + 缓存键。引擎:`lite`、`jsoncompact`、`dedup`、`aging`、`relevance`、`hard-budget`、`filter-definitions`、`custom-filters`、`toolfilter`、`read-lifecycle`。缓存键含 `compression.cacheKey`,不同压缩等级永不碰撞。
+
+---
+
+## 13. 响应缓存(可选)
+
+- **范围**:仅非流、可缓存温度(`temperature ≤ 1` 或未设)、`X-FreeLLM-Cache: on` 或 `RESPONSE_CACHE=1`。
+- **键**:规范化请求(模型、消息、所有采样参数、工具、stop、response_format、n、seed、惩罚、logit_bias、logprobs、top_logprobs、reasoning_effort、压缩)的 SHA-256。
+- **存储**:内存 LRU、TTL + 温度闸门。
+- **命中**:返回缓存体、`X-Routed-Via: cache`、`X-FreeLLM-Cache: HIT`,**零提供方额度消耗**。
\ No newline at end of file
diff --git a/docs/i18n/zh-CN/docs/architecture/04-degraded-mode-and-failover.md b/docs/i18n/zh-CN/docs/architecture/04-degraded-mode-and-failover.md
new file mode 100644
index 00000000..df604912
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/architecture/04-degraded-mode-and-failover.md
@@ -0,0 +1,319 @@
+[English](../../../../architecture/04-degraded-mode-and-failover.md) · **简体中文**
+
+# 降级模式与回退 —— 深度剖析
+
+> **源码:** `server/src/services/degradation.ts`、`server/src/lib/fallback-loop.ts`、`server/src/routes/proxy.ts`、`server/src/services/ratelimit.ts`
+
+## 1. 降级模式状态机 (f412e97)
+
+### 目的
+
+当大量启用的提供方同时挂掉时,逐请求探测和老虎机探索只会在死路上烧重试预算。降级模式状态机跟踪**健康提供方比率**(由定时健康巡检驱动),一旦比率在持续期内跌破阈值,就把网关翻进降级态。
+
+### 状态机
+
+```
+┌─────────────┐ 比率 < 阈值 持续 DEGRADED_ENTRY_GRACE_MS ┌─────────────┐
+│ normal │ ─────────────────────────────────────────────────────▶ │ degraded │
+└─────────────┘ └─────────────┘
+ ▲ │
+ │ 比率 ≥ 阈值 持续 DEGRADED_EXIT_GRACE_MS │
+ └────────────────────────────────────────────────────────────────────┘
+```
+
+### 参数(环境变量可调)
+
+| 变量 | 默认值 | 含义 |
+|----------|---------|---------|
+| `DEGRADED_HEALTHY_RATIO` | 0.5 | 必须有 ≥1 可用密钥的提供方占比 |
+| `DEGRADED_MIN_PROVIDERS` | 3 | 评估用的最少启用提供方数(单提供方部署不抖动) |
+| `DEGRADED_ENTRY_GRACE_MS` | 60,000 | 低于阈值多久后进入降级 |
+| `DEGRADED_EXIT_GRACE_MS` | 120,000 | 高于阈值多久后退出(更长 = 迟滞) |
+
+### 健康快照
+
+```typescript
+interface HealthSnapshot {
+ healthyProviders: number // 有 ≥1 密钥处于 {healthy, unknown} 的启用提供方数
+ totalProviders: number // 有 ≥1 密钥的启用提供方数(任意状态)
+ ratio: number // healthy / total(total=0 时为 1)
+}
+```
+
+- `unknown` 算健康(未探测密钥 = 探测说不行前视为可用)。
+- 每次健康巡检 + 按需(仪表盘、路由器入口)从 `api_keys` 表算出。
+
+### 降级态下的行为变化
+
+| 方面 | 正常 | 降级 |
+|--------|--------|----------|
+| 老虎机探索 | 10% 底线(若开启) | **禁用** —— 只按剩余健康提供方的评分顺序 |
+| 路由器 | 路由时查 `isDegraded()` | 同 |
+| 健康端点 | 报 `state: 'normal'` | 报 `state: 'degraded', degradedAt: timestamp` |
+| 日志 | — | 进入时 `console.warn`,退出时 `console.log` |
+
+### API
+
+```typescript
+isDegraded(): boolean // 只读,路由器用
+getDegradationStatus(): DegradationStatus // {healthyProviders, totalProviders, ratio, state, degradedAt}
+updateDegradationState(now?): DegradationStatus // 每次健康巡检后调
+resetDegradationState() // 测试、启动后重探
+```
+
+---
+
+## 2. 重试预算与对冲 (1d2226a)
+
+### 挂钟重试预算
+
+- **默认**:45 s(`FALLBACK_TIME_BUDGET_MS`、设置 `fallback_time_budget_ms`、0 = 关)。
+- **在每次重试**前检查(尝试 ≥ 1)。尝试 0 总跑;尝试 1 总跑(这样尝试 0 即使耗尽整个预算,回退在结构上也是可能的)。
+- **耗尽渲染**:`timedOut: true` + `budgetMs` 在 `ExhaustionContext` 里 → 消息含 "stopped early: retry time budget 45s exceeded — one failover hop is always allowed, and past that the budget stops starting further retries and cancels an attempt still waiting on its first byte"。
+
+### 对冲(中止在途)
+
+> v2 前:预算只拒绝**发起**下一次重试。一个停滞的尝试能跑几分钟,卡住链。
+>
+> **v2 (1d2226a)**:预算中途过期时,`abortInFlight()` 经 `AbortController` 取消上游取获(穿进 `CompletionOptions.signal`)。
+
+```typescript
+// 在 fallback-loop.ts 里
+abortInFlight: () => hedgeAbort.abort(newHedgeAbortError())
+```
+
+- `HedgeAbortError` 是**非提供方健康** → 无冷却、无惩罚、无限额学习。
+- 渲染 `timedOut` 耗尽(不是提供方失败)。
+- 流式面在首字节/头部刷出时调 `ctx.disarmHedge()` —— 过了那点答案已经在路上了,杀掉它只会为了无回退收益而截断健康响应。
+
+### 断路器护栏
+
+- `max_consecutive_upstream_fails`(设置 `max_consecutive_upstream_fails`,默认 0 = 关)。
+- 计数尝试循环里连续的可重试上游失败。
+- 触发 → `ExhaustionContext` 里的 `breakerFails` → **503 service_unavailable** 并带 "upstream_unhealthy" 码。
+- "The enabled pool looks unhealthy right now, so the remaining candidates were skipped instead of burning quota on them."
+
+---
+
+## 3. X-Fallback-Detail 头 (8cb75ac)
+
+### 目的
+
+`X-Fallback-Trail` 告诉**哪些跳烧了、为什么**。`X-Fallback-Detail` 加上**烧了多久**——这是智能体重构不出来的部分(一个 40s 响应:一家卡了 39s vs 四家快速失败)。
+
+### 格式
+
+```
+X-Fallback-Detail: platform/model keyN=outcome t=startOffset+durationMs msg=summary; +N more
+```
+
+- **逐跳耗时** + 脱敏提供方消息。
+- **可选**:`EXPOSE_FALLBACK_DETAIL_HEADER=1` 或设置 `expose_fallback_detail_header`。
+- **预算**:总计 2048 字符,单条消息摘要 120 字符,最多显示 10 跳。
+- **仅失败跳**:当前服务的跳在头部开着时不可知(dispatch 返回后才记),所以不显示。
+
+### 示例
+
+```
+X-Fallback-Detail: google/gemini-2.5-pro key1=rate_limited t=0+1205ms msg=429 Quota exceeded; groq/llama-3.3-70b key2=upstream_error t=1205+3450ms msg=503 Service unavailable; +1 more
+```
+
+### 实现
+
+```typescript
+// fallback-loop.ts
+formatAttemptDetail(records: AttemptTraceRecord[]): string
+// AttemptTraceRecord: {platform, modelId, keyOrdinal, outcome, startOffsetMs, durationMs, errorSummary}
+
+// 响应上设置(flush 前):
+if (isFallbackDetailHeaderEnabled() && records?.length) {
+ res.setHeader('X-Fallback-Detail', safeHeaderValue(formatAttemptDetail(records), 2048));
+}
+```
+
+---
+
+## 4. 裸 Safe/Unsafe 分类输出回退 (a961d93)
+
+### 问题
+
+某些中继模型(如 OpenCode Zen)把裸的 `"safe"` 或 `"unsafe"` 分类词作为**整个补全**吐出来,而不是被请求的答案。这是上游内容过滤器,不是模型输出。
+
+### 修复
+
+```typescript
+// proxy.ts,非流补全后:
+const text = completionTextFromChat(result);
+if (!text) { throw empty completion... }
+
+// #809:中继吐裸分类输出时回退
+if (isUpstreamClassificationOutput(text, route.platform)) {
+ throw Object.assign(
+ new Error(`empty completion from ${route.displayName} (upstream classification output)`),
+ result.choices?.[0]?.finish_reason === 'length' ? { skipBench: true } : {},
+ );
+}
+```
+
+- `isUpstreamClassificationOutput(text, platform)` 在已知中继平台上检查精确的 `"safe"` / `"unsafe"`(大小写不敏感、去首尾空白)。
+- 视同空补全:**回退**,`finish_reason === 'length'` 时 `skipBench: true`(推理吃光预算)。
+- 流式路径:流结束时对累积文本做同一检查。
+
+---
+
+## 5. 统一回退循环 (`lib/fallback-loop.ts`)
+
+### 所有面共享
+
+| 面 | 路由 | 派发 |
+|---------|-------|----------|
+| `/v1/chat/completions` | `proxy.ts` | SSE 流式 + 非流 |
+| `/v1/responses` | `responses.ts` | Responses API 分帧 |
+| `/v1/messages` | `anthropic.ts` | Anthropic SSE 事件 |
+| `/v1/completions` | `proxy.ts` | 旧版 text_completion SSE |
+
+### 循环契约
+
+```typescript
+interface FallbackHooks {
+ maxRetries?: number; // 默认 20
+ timeBudgetMs?: number; // 默认 getFallbackTimeBudgetMs()
+ breakerLimit?: number; // 默认 getMaxConsecutiveUpstreamFails()
+ attemptLog?: AttemptRecord[]; // 突变,用于 X-Fallback-Trail
+ state: FallbackState; // skipKeys, skipModels, skipPlatforms
+ clientGone?: () => boolean; // 每次重试前查
+ abortInFlight?: () => void; // 对冲 (v2)
+ route(attempt): RouteResult; // 同步耗尽时抛 RouteError
+ dispatch(route, attempt, ctx): Promise<'done' | 'committed'>;
+ logFailure(route, err, attempt): void;
+ onFatal(route, err, attempt): void; // 非可重试 → 502
+ onRoutingExhausted(lastError, routeErr, exhaustion, info): void; // 零尝试
+ onExhausted(exhaustion, info): void; // 重试耗尽
+}
+```
+
+### 尝试分类 (recordRetryableFailure)
+
+| 错误 | 跳过范围 | 冷却 | 模型惩罚 | 限额学习 |
+|-------|------------|------|---------------|-------------|
+| 401 无效密钥 | 密钥 | 5 min | 否 | 否 |
+| 402 需付款 | 密钥 | 24h | 否 | 否 |
+| 403 模型被禁 | **模型** | 24h | 否 | 否 |
+| 429 每日耗尽 | 模型+密钥 | 到午夜 / Retry-After | **重 (3)** | 是 |
+| 429 瞬时 (rpm/tpm) | 密钥 | 90s / 阶梯 | 轻 (1) | 是 |
+| 5xx / 超时 / 传输 | **平台** (#788) | 90s / 阶梯 | 轻 (1) | 否 |
+| 空补全(推理) | 密钥 | 豁免(连击 ≤3) | 否 | 否 |
+| 上下文过大 | 模型 | — | 否 | 否 |
+| response_format 被忽略 | 模型 | — | 否 | 否 |
+| 无效工具参数 | 密钥 | — | 否 | 否 |
+
+### 模型级失败停用 (#806)
+
+- 15 分钟内跨密钥 3 次可重试失败 → 模型在**其所有密钥**上停用 10 分钟(启发式、可探测)。
+- 一次服务成功的请求清空失败窗口。
+
+### 空补全连击限制 (#751)
+
+- 同一模型+密钥上连续 3 次推理截断补全 → 豁免取消 → 正常冷却/惩罚/限额学习生效。
+- 成功或正常惩罚失败时重置。
+
+### 提供方级跳过 (#788)
+
+- 5xx / 超时 / 传输 / 降级 → `skipPlatforms.add(platform)`。
+- 整个提供方在本请求里排除——循环直接跳到下一提供方,而不是按密钥烧一跳。
+
+### 耗尽渲染 (exhaustedRetryError)
+
+**按尝试类最具体优先聚合:**
+
+1. **全 auth** → 502 `provider_error` (`provider_authentication_failed`) —— 区别于限流,从不怪客户端密钥。
+2. **全 context_too_large** → 413 `invalid_request_error` (`context_length_exceeded`)。
+3. **全 model_not_found** → 404 `invalid_request_error` (`model_not_found`)。
+4. **末尾错误 = degraded 400**(NVIDIA NIM) → 503 `service_unavailable` (`provider_degraded`)。
+5. **末尾错误 = 提供方坏请求** → 400 `invalid_request_error` (`provider_rejected_request`)。
+6. **断路器** → 503 `service_unavailable` (`upstream_unhealthy`)。
+7. **全 UNAVAILABLE_UNTIL_KNOWN_TIME**(rate_limited、daily_quota_exhausted、out_of_credits、forbidden) → 429 `rate_limit_error` 带 `retryAtMs` + `Retry-After`。
+8. **混合/其他** → 502 `provider_error` (`upstream_failed`) —— 绝不 500(那是我们的 bug)。
+
+**同步耗尽(零尝试):** `routingExhaustionBody(routeErr)` 把 diagnostics 映射到同一分类:
+- 全配置(无密钥、无提供方) → 503 `no_providers_configured`
+- 全 too_large (+ 配置) → 413 `context_length_exceeded`
+- 部分 time_bound、其余配置/too_large → 429 带 `retryAtMs`
+- 否则 → 429 `routing_exhausted`
+
+---
+
+## 6. 尝试轨迹与头部
+
+### X-Fallback-Attempts
+
+成功**和**耗尽响应上、本次响应前的失败跳数。
+
+### X-Fallback-Trail
+
+```
+platform/model key1=class; platform/model key2=class; +N more
+```
+
+- `class` ∈ `AttemptErrorClass`(auth、out_of_credits、daily_quota_exhausted、model_not_found、forbidden、context_too_large、provider_bad_request、empty_completion、format_ignored、invalid_tool_arguments、timeout、rate_limited、upstream_error、error)。
+- 最多显示 10 个,1024 字符上限。
+
+### X-Fallback-Detail(可选)
+
+见 §3 上文。
+
+---
+
+## 7. 关键函数 (degradation.ts)
+
+| 函数 | 用途 |
+|----------|---------|
+| `computeHealthSnapshot()` | 读 `api_keys` → `{healthyProviders, totalProviders, ratio}` |
+| `updateDegradationState(now)` | 状态机步进,健康巡检后调 |
+| `isDegraded()` | 路由器闸门 |
+| `getDegradationStatus()` | 仪表盘 + 健康端点 |
+| `resetDegradationState()` | 测试 / 启动重探 |
+
+---
+
+## 8. 关键函数 (fallback-loop.ts)
+
+| 函数 | 用途 |
+|----------|---------|
+| `runFallbackLoop(hooks)` | 主循环 |
+| `newFallbackState()` | 新 `{skipKeys, skipModels, skipPlatforms}` |
+| `cooldownDecisionForError(route, err)` | 阶梯 + Retry-After + 来源 |
+| `recordRetryableFailure(route, err, state, now)` | 完整记账 |
+| `recordAuthFailure(route, state)` | 401:跳密钥、5min 停用、触发重校验 |
+| `recordUpstreamSuccess(route, tokens)` | 核算 + 清连击 + 标密钥健康 |
+| `exhaustedRetryError(lastError, maxRetries, ctx)` | 诚实终态 + 响应体 |
+| `routingExhaustionBody(routeErr)` | 从 diagnostics 来的零尝试耗尽 |
+| `setFallbackHeaders(res, failedAttempts, trail)` | X-Fallback-Attempts + X-Fallback-Trail |
+| `setExhaustionHeaders(res, body)` | 从 `retryAtMs` 算 Retry-After |
+| `formatAttemptTrail(attempts)` | X-Fallback-Trail 值 |
+| `formatAttemptDetail(records)` | X-Fallback-Detail 值 |
+| `isFallbackDetailHeaderEnabled()` | 设置 → 环境 → false |
+| `getFallbackTimeBudgetMs()` | 设置 → 环境 → 45s |
+| `msUntilNextUtcMidnight()` | 每日额度重置边界 |
+
+---
+
+## 9. 流程:请求进入降级网关
+
+```
+request → /v1/chat/completions
+ ├─ isDegraded() = true
+ │ └─ router: 探索 禁用,只按评分顺序
+ ├─ runFallbackLoop()
+ │ ├─ 尝试 0: route() → 最佳健康模型
+ │ ├─ dispatch() → 429 每日耗尽
+ │ │ └─ recordRetryableFailure() → 冷却(权威性、到午夜)
+ │ │ └─ skipKeys.add()、skipModels.add()(每日耗尽 = 模型级)
+ │ ├─ 尝试 1: route() → 下一健康(遵守 skipKeys)
+ │ ├─ ... 每次重试前预算检查 ...
+ │ ├─ 预算中途过期于尝试 3
+ │ │ └─ abortInFlight() → HedgeAbortError
+ │ │ └─ 循环停、timedOut 耗尽
+ │ └─ onExhausted() → 429 带 X-Fallback-Detail + Retry-After
+ └─ 响应头:X-Fallback-Attempts、X-Fallback-Trail、X-Fallback-Detail
+```
\ No newline at end of file
diff --git a/docs/i18n/zh-CN/docs/architecture/05-catalog-sync.md b/docs/i18n/zh-CN/docs/architecture/05-catalog-sync.md
new file mode 100644
index 00000000..05d3480f
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/architecture/05-catalog-sync.md
@@ -0,0 +1,281 @@
+[English](../../../../architecture/05-catalog-sync.md) · **简体中文**
+
+# 目录同步 —— 深度剖析
+
+> **源码:** `server/src/services/catalog-sync.ts`、`server/src/services/model-state.ts`、`server/src/db/migrations/`
+
+## 1. 概览
+
+目录同步把本地模型目录与 `freellmapi.co` 的发布目录保持同步。它**每天两次**(及按需)跑、抓取**签名目录**、对**钉死的 Ed25519 公钥**验签、并**事务性**应用到本地 SQLite。
+
+### 两层
+
+| 层 | 受众 | 刷新节奏 | 认证 |
+|------|----------|-----------------|------|
+| **Live** | 付费授权持有者 | 2–3 天 | Bearer `premium_license_key` |
+| **Monthly** | 免费安装 | ~30 天 | 无(公开) |
+
+免费安装仍能自愈,只是节奏慢。**打包迁移仍是基线**——抓到的目录只有在**比 `MIN_CATALOG_VERSION` 新**(每次模型迁移都会推这个版本)时才应用,所以陈旧的月度快照永远回滚不了更新版本加进来的模型。
+
+---
+
+## 2. 目录结构
+
+```typescript
+interface Catalog {
+ version: string; // 如 "2026.06.07"
+ generatedAt: string; // ISO 时间戳
+ tier: 'live' | 'monthly';
+ models: CatalogModel[]; // 聊天模型
+ embeddings?: CatalogEmbedding[]; // 可选,合并新鲜度源
+ transcriptionModels?: CatalogTranscriptionModel[]; // STT,独立顶层键
+ quirks: CatalogQuirk[]; // 运维建议
+}
+```
+
+### CatalogModel(聊天)
+
+| 字段 | 用途 |
+|-------|---------|
+| `platform`, `modelId` | 主键(中继模型含 `endpoint_scope`) |
+| `displayName` | UI 名称 |
+| `intelligenceRank` | 1..1000(1 = 最强),提供方内部 |
+| `speedRank` | 1..11(目录手分,1 = 最快) |
+| `sizeLabel` | `Frontier` \| `Large` \| `Medium` \| `Small`(跨提供方层级) |
+| `limits` | `{rpm, rpd, tpm, tpd}` —— 按模型上限 |
+| `monthlyTokenBudget` | 字符串标签(如 `"1M"`、`"2x"`)供余量护栏 |
+| `contextWindow` | 最大上下文(词元) |
+| `enabled` | 目录级启用(false 则强制禁用) |
+| `supportsVision` / `supportsTools` | 能力标记 |
+| `modality` | `'text'`(默认)→ `models` 表;`'image'`/`'audio'` → `media_models` |
+| `mediaNote` | 媒体模型的短显示文案 |
+| `requestStyle` | 适配器风格(如 Cloudflare 图像:`'json'` \| `'multipart'`) |
+
+### 生成式媒体 & 语音识别
+
+- **媒体模型**(`modality: 'image' | 'audio'`)→ `media_models` 表,受 `MEDIA_PLATFORMS` 集合门控。
+- **语音识别模型** → `media_models` 且 `modality = 'transcription'`,受 `TRANSCRIPTION_PLATFORMS` 门控。
+- 独立顶层键(`transcriptionModels`、`embeddings`),让旧二进制忽略未知模态、不把它们误路由成聊天模型。
+
+---
+
+## 3. 签名验证
+
+```typescript
+const PINNED_CATALOG_PUBKEY = `-----BEGIN PUBLIC KEY-----
+MCowBQYDK2VwAyEAq9yv4+3EeyMHKsfVYBhkcz1lYgIXSUeHNnN6tNgYX3k=
+-----END PUBLIC KEY-----`;
+
+// 抓取
+const res = await fetch(`${catalogBaseUrl()}/v1/latest`, { headers: { Authorization: `Bearer ${key}` } });
+const signature = res.headers.get('x-catalog-signature');
+const bytes = Buffer.from(await res.arrayBuffer());
+const verified = crypto.verify(null, bytes, catalogPublicKey(), Buffer.from(signature, 'base64'));
+```
+
+- **钉死公钥**:私钥半边从未离开目录主机。
+- **自托管目录覆盖**:`CATALOG_BASE_URL`、`CATALOG_PUBKEY` 环境变量。
+- **防篡改**:未签名或被改的直接丢弃。被攻陷的 CDN / MITM 无法注入模型或 quirks。
+
+---
+
+## 4. 应用规则(用户数据保护)
+
+在**单个事务**里应用(`applyCatalog`):
+
+| 规则 | 行为 |
+|------|---------|
+| 元数据(名、秩、限额、上下文、能力) | 跟目录走,**除非**用户有显式本地覆盖 |
+| `enabled: false` | **强制禁用**(模型上游已死) |
+| `enabled: true` | **永不重启用**用户关掉的模型 |
+| 用户建行(`source = 'user'`) | **永不更新、永不删除、永不收养** —— `platform:model_id` 撞车时用户行胜、目录条目跳过 |
+| 用户删过的目录模型 | 经**墓碑**(`catalog_model_tombstones` 表)保持删除 |
+| 自动退役(410/寿终) | **禁用、不删** —— 目录里再出现 enabled 就解除退役(#634) |
+| 目录里消失的模型 | **删除**(先 fallback_config、FK 顺序) |
+
+### 来源列(`source`)
+
+替代旧 `size_label NOT IN ('User','Custom')` 启发式。取值:
+
+- `'catalog'` —— 目录同步建的
+- `'user'` —— 声明式配置、管理员添加、自定义端点
+- `'declarative'` —— 来自声明式配置文件
+
+---
+
+## 5. 同步流程
+
+```
+syncCatalog(force=false)
+ ├─ GET /v1/latest?since=<appliedVersion>(有授权则带 Bearer)
+ ├─ 304 → up_to_date
+ ├─ 验签(Ed25519)
+ ├─ 解析 + 结构校验 (isCatalog)
+ ├─ version < MIN_CATALOG_VERSION? → skipped_older(会回滚迁移)
+ ├─ 同版本+同层已应用? → up_to_date
+ ├─ applyCatalog(db, catalog) → 事务性 upsert/insert/delete
+ ├─ 持久化设置:appliedVersion、appliedTier、appliedJSON(已验证文档)
+ └─ 记数:updated、inserted、removed、skippedUnknownPlatform、quirks
+```
+
+### 启动重应用 (`reapplyCachedCatalog`)
+
+迁移每次启动都跑、重断言打包基线(目录可能删了的基线模型 `INSERT OR IGNORE`)。启动时网络同步若版本没变会 304,**不**重应用。没有这一步,每次重启都会把数据库往基线方向漂、直到下一次目录版本推进。
+
+```
+reapplyCachedCatalog()
+ ├─ 读 SETTING_APPLIED_JSON(缓存的已验证文档)
+ ├─ 校验 + version ≥ MIN_CATALOG_VERSION
+ ├─ applyCatalog(db, parsed) → 同步、无网络
+ └─ 记录:"re-applied cached live v2026.06.07 after boot"
+```
+
+- 旧版升级:有 applied-version 但无缓存文档的安装 → 清 applied version → 下轮轮询抓全量目录。
+
+---
+
+## 6. 模型年龄闸(30 天)
+
+`generatedAt` 起算超 30 天的模型从 **Live 层排除**(免费层拖尾快照)。目录服务端强制;客户端只收到该层提供的东西。
+
+---
+
+## 7. 授权状态
+
+```typescript
+interface LicenseStatus {
+ valid: boolean;
+ plan: 'annual' | 'lifetime' | null;
+ status: string | null;
+ expiresAt: string | null;
+ checkedAtMs: number;
+}
+```
+
+- 缓存在设置里(`premium_license_status`),每次同步刷新。
+- 权利**服务端**在 `/v1/latest` 强制——本地缓存只是 UI 用的信息态。
+- 离线/服务挂了 → 保留缓存状态。
+
+---
+
+## 8. Quirks(运维建议)
+
+```typescript
+interface CatalogQuirk {
+ slug: string;
+ title: string;
+ body: string;
+ severity: 'blocker' | 'warning' | 'info';
+ targets: { platform: string | null; modelGlob: string | null }[];
+}
+```
+
+- 纯内容:**每次同步整体替换**(DELETE + INSERT)。
+- 仪表盘为受影响模型展示 blocker/warning。
+
+---
+
+## 9. 设置键
+
+| 键 | 用途 |
+|-----|---------|
+| `premium_license_key` | Live 层用的 Bearer 令牌 |
+| `premium_license_status` | 缓存的 `LicenseStatus` JSON |
+| `catalog_applied_version` | 最后应用的目录版本 |
+| `catalog_applied_tier` | `'live'` \| `'monthly'` |
+| `catalog_applied_json` | 已验证目录文档(供启动重应用) |
+| `catalog_last_sync_ms` | 最后成功同步的时间戳 |
+| `catalog_last_error` | 最后同步错误消息 |
+
+---
+
+## 10. 调度器集成
+
+```typescript
+startCatalogSync(scheduler: Scheduler)
+ ├─ reapplyCachedCatalog() // 同步、无网络
+ ├─ scheduler.after(10s, run) // 启动延迟
+ └─ scheduler.every(12h, run) // 每天两次
+```
+
+- `run()` = `refreshLicenseStatus()` + `syncCatalog()`
+- 熔断开关:`CATALOG_SYNC_DISABLED=1`
+
+---
+
+## 11. 迁移播种 vs 托管目录
+
+| 方面 | 打包迁移 | 托管目录同步 |
+|--------|-------------------|---------------------|
+| **权威** | 基线地板 | 实时事实来源 |
+| **版本** | `MIN_CATALOG_VERSION`(日期) | `catalog.version`(日期) |
+| **新模型** | 迁移 PR 加 | 下次目录发布出现 |
+| **限额修正** | 迁移 PR | 从提供方错误学 + 目录更新 |
+| **退役** | 迁移(禁用 + 墓碑) | 目录 `enabled: false` → 强制禁用 |
+| **中继模型** | 不在目录 | 仅自定义端点(用户行) |
+| **回滚保护** | N/A | `version < MIN_CATALOG_VERSION` → 跳过 |
+
+### 自定义模型 / 中继模型
+
+- **永不**来自目录。通过下列创建:
+ - `POST /api/media/custom`(生成式媒体 / STT)
+ - `POST /api/custom-endpoint`(聊天中继)
+ - 声明式配置文件
+- 绑定到携带其端点的 `api_keys` 行(`models` 行上 `key_id`)。
+- `endpoint_scope = 'custom:<base_url_hash>'` 区分服务同一 `model_id` 的中继。
+- 目录同步**跳过** `platform = 'custom'` 和未知平台(旧二进制)。
+
+---
+
+## 12. 关键函数
+
+| 函数 | 用途 |
+|----------|---------|
+| `syncCatalog(force?)` | 抓 → 验签 → 应用(或 304/跳过) |
+| `applyCatalog(db, catalog)` | 事务性 upsert/insert/delete + quirks |
+| `reapplyCachedCatalog()` | 启动时从已验证缓存重应用 |
+| `refreshLicenseStatus()` | 对目录服务校验授权 |
+| `getSyncState()` | 仪表盘状态面板 |
+| `startCatalogSync(scheduler)` | 注册 12h 间隔 + 启动延迟 |
+| `isCatalog(value)` | 结构校验(畸形 body 大声报错) |
+| `routableContextWindow(platform, modelId, cw)` | GitHub gpt-4.1 覆盖(8000) |
+
+---
+
+## 13. 涉及表
+
+| 表 | 操作 |
+|-------|-----------|
+| `models` | UPSERT 聊天模型(catalog 来源) |
+| `media_models` | UPSERT 图像/音频/语音识别 |
+| `embedding_models` | UPSERT 嵌入(全量快照) |
+| `fallback_config` | 保证每个模型有行 |
+| `catalog_model_tombstones` | 尊重用户删除 |
+| `quirks` + `quirk_targets` | 整体替换 |
+| `settings` | 持久化 applied version/tier/json、授权状态、同步时间 |
+
+---
+
+## 14. 环境变量
+
+| 变量 | 默认值 | 用途 |
+|----------|---------|---------|
+| `CATALOG_BASE_URL` | `https://api.freellmapi.co` | 目录服务端点 |
+| `CATALOG_PUBKEY` | 钉死 Ed25519 公钥 | 自托管目录覆盖 |
+| `CATALOG_SYNC_DISABLED` | `0` | 熔断开关(`1` = 禁用) |
+
+---
+
+## 15. 错误处理
+
+| 场景 | 行为 |
+|----------|----------|
+| 网络超时 (20s) | 记警告、保留上一版目录 |
+| HTTP 304 | `up_to_date`、更新 `last_sync_ms` |
+| HTTP 非 2xx | 错误、保留上一版目录 |
+| 缺签名 | 丢弃、报错 |
+| 签名验证**失败** | 丢弃、**大声报错** —— "catalog signature verification FAILED — discarding response" |
+| 无效 JSON / 结构 | 丢弃、报错 |
+| 版本老于基线 | `skipped_older`、等更新版目录 |
+| 应用时 DB 不可用 | 事务回滚、报错、保留上一状态 |
+| 授权检查不可达 | 保留缓存状态、同步仍跑(层由服务端定) |
\ No newline at end of file
diff --git a/docs/i18n/zh-CN/docs/architecture/06-observability.md b/docs/i18n/zh-CN/docs/architecture/06-observability.md
new file mode 100644
index 00000000..9ac95727
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/architecture/06-observability.md
@@ -0,0 +1,321 @@
+[English](../../../../architecture/06-observability.md) · **简体中文**
+
+# 可观测性 —— 深度剖析
+
+> **源码:** `server/src/lib/server-logs.ts`、`server/src/routes/logs.ts`、`server/src/lib/request-log.ts`、`server/src/lib/log-redaction.ts`、`server/src/lib/attempt-trace.ts`
+
+## 1. 服务器日志查看器 (`server-logs.ts`)
+
+### 双层存储
+
+| 层级 | 容量 | 持久化 | 级别 | 用途 |
+|------|----------|-------------|--------|---------|
+| **环形缓冲区** | 1000 条 | 仅内存 | 全部(trace、debug、info、warn、error) | 实时仪表盘视图、轮询 |
+| **SQLite 表** | 无界(经用量修剪 1 天留存) | 持久化 | **仅 warn、error** | 重启保留、历史分析 |
+
+- **单一 ID 空间**:`id` 在入口分配(不是 SQLite),启动时从 `MAX(id)` 种子,所以 ID 跨重启单调递增。仪表盘用 `sinceId` 游标轮询,两层通用。
+- **噪音过滤**:`NOISE_RE` 丢弃 `GET /api/logs` 和 `GET /api/ping` 的访问日志行(防自喂缓冲)。
+- **消息上限**:6000 字符,超出截断并加 `… [truncated]` 后缀。
+- **来源提取**:从消息里的 `[Tag]` 前缀推导(如 `[Health]`、`[CooldownProbe]`、`[Proxy]`)——无需调用点标注。
+
+### 入口路径
+
+```
+console.log/warn/error/debug/trace
+ │
+ ▼
+lib/log-redaction.ts (console 包装器)
+ ├─ 脱敏机密(API 密钥、令牌、认证头等)
+ ▼
+server-logs.ts.recordConsoleLine(level, args)
+ ├─ 格式化参数(Error → 堆栈、对象 → inspect 深度 2)
+ ├─ 噪音过滤 + 长度上限
+ ├─ 推入环(>1000 则 splice)
+ └─ 若 level ∈ {warn, error} → persist(entry) → INSERT INTO server_logs
+```
+
+**重入守卫**:
+- `mirroring` —— `providerLog()` 经包装过的 console 镜像回 stdout;防二次入口。
+- `persisting` —— DB 层会记日志(忙超时、权限);跳过持久化写但环仍收。
+- `seeding` —— 启动种子探 DB,那也能记日志。
+
+### 结构化提供方日志
+
+```typescript
+providerLog(level, message, { provider, model, event, requestId })
+```
+
+- 带元数据记录供仪表盘过滤,**并**镜像到 stdout(已脱敏)。
+- 用于:健康检查器、冷却探测、路由器、回退循环、目录同步。
+
+### 启动预加载
+
+首次入口(或显式 `initServerLogs()` 调用)时:
+1. 从 `server_logs` 的 `MAX(id)` 种子 `lastId`。
+2. 预加载最近 200 条持久化行(最新优先,反转成最旧优先进环)。
+3. 把持久化最大 ID **之上**的任何启动前环条目**重打戳**(ID 跨层唯一)。
+
+### API (`GET /api/logs`)
+
+```typescript
+queryLogs({
+ levels?: ServerLogLevel[], // 过滤(trace 并入 debug)
+ q?: string, // 全文搜(message + provider + source + event)
+ provider?: string, // 精确提供方过滤
+ sinceId?: number, // 游标(返回 > sinceId 的条目)
+ limit?: number // 1..500(默认 200)
+}): ServerLogEntry[]
+```
+
+- **倒着走环**,这样 `limit` 真管用,不是只管结果集大小。
+- 返回最旧→最新。
+- `currentMaxId()` → 最高已发 ID(即使被过滤空也能给游标上界)。
+
+### 级别计数(仪表盘徽章)
+
+```typescript
+levelCounts(): { debug: number; info: number; warn: number; error: number }
+```
+
+- `trace` 并入 `debug`(共 4 个徽章)。
+
+### 清空 / 重置
+
+- `clearLogs()` —— 清环 + `DELETE FROM server_logs`。**ID 计数器不重置**(不然仪表盘游标会收到重复 ID)。
+- `resetServerLogsForTest()` —— 测试缝:全清 + 计数器 + 种子态。
+
+---
+
+## 2. 请求分析 (`request-log.ts`)
+
+### 逐请求行 (`requests` 表)
+
+| 列 | 来源 |
+|--------|--------|
+| `platform`, `model_id`, `key_id` | RouteResult |
+| `request_type` | `'chat' \| 'embeddings' \| 'image' \| 'speech' \| 'transcription' \| 'fusion'` |
+| `status` | `'success' \| 'error' \| 'canceled'` |
+| `input_tokens`, `output_tokens`, `total_tokens` | 提供方用量 + 估算 |
+| `latency_ms` | 挂钟 |
+| `ttfb_ms` | 首词元(内容**或**推理) |
+| `error` | 脱敏提供方消息 |
+| `created_at_ms` | 时间戳 |
+| `client_info` | User agent、IP 哈希 |
+| `served_model` | 上游报的模型(可观测性) |
+| `attempt_error_summary` | 本请求聚合的失败类别 |
+
+### 尝试轨迹 (`request_attempts` 表)
+
+每个派发并失败的尝试一行:
+
+| 列 | 用途 |
+|--------|---------|
+| `request_id` | FK 到 `requests` |
+| `attempt_ordinal` | 0-based |
+| `platform`, `model_id`, `key_id` | 试了什么 |
+| `error_class` | `AttemptErrorClass`(auth、rate_limited、upstream_error、...) |
+| `error_summary` | 脱敏提供方消息(≤200 字符) |
+| `latency_ms` | 逐尝试挂钟 |
+| `ttfb_ms` | 逐尝试 TTFB |
+| `input_tokens`, `output_tokens` | 逐尝试估算 |
+
+- 给 `X-Fallback-Trail` / `X-Fallback-Detail` 头供电。
+- 让仪表盘能按请求钻取。
+
+### 聚合 (`request_aggregates` 物化视图)
+
+仪表盘图表的预计算卷起(24h / 7d / 30d / 90d 窗口):
+- 延迟 p50 / p95 / p99
+- TTFB p50 / p95
+- 词元吞吐
+- 成功率
+- 估算成本节省
+- 按提供方 / 模型 / 密钥细分
+
+---
+
+## 3. 日志脱敏 (`log-redaction.ts`)
+
+### 脱敏什么
+
+| 模式 | 替换 |
+|---------|-------------|
+| `Bearer <token>` | `Bearer [REDACTED]` |
+| `x-api-key: <key>` | `x-api-key: [REDACTED]` |
+| `x-goog-api-key: <key>` | `x-goog-api-key: [REDACTED]` |
+| `Authorization: Basic <creds>` | `Authorization: Basic [REDACTED]` |
+| JSON 体里的 API 密钥 | `[REDACTED]` |
+| 带嵌入凭证的 URL | `[REDACTED]` |
+| SQLite 加密密钥 | `[REDACTED]` |
+
+- 在 console 包装器单次通过 → **所有**日志路径(console、providerLog、启动行)都被脱敏。
+- 幂等:已脱敏文本原样通过。
+
+---
+
+## 4. 尝试追踪 (`attempt-trace.ts`)
+
+### AsyncLocalStorage 作用域
+
+每个请求得一个 `AsyncLocalStorage<RequestTrace>` 作用域:
+
+```typescript
+interface RequestTrace {
+ requestId: string;
+ startedAtMs: number;
+ records: AttemptTraceRecord[];
+}
+
+interface AttemptTraceRecord {
+ platform: string;
+ modelId: string;
+ keyOrdinal: number; // 本请求内 1-based
+ outcome: AttemptOutcome; // 'success' | 'retryable_failure' | 'auth_failure' | 'fatal' | 'hedge_abort'
+ startOffsetMs: number; // 相对请求开始
+ durationMs: number;
+ errorSummary: string | null; // 脱敏、≤200 字符
+}
+```
+
+- `runWithRequestTrace(fn)` 包装回退循环。
+- `dispatch()` 记开始偏移、跑尝试、记时长 + 结果 + 摘要。
+- `getRequestTrace()` 读当前作用域(给 `X-Fallback-Detail` 头)。
+
+### 结果
+
+| 结果 | 含义 |
+|---------|---------|
+| `success` | 尝试完成、响应已发 |
+| `retryable_failure` | 429/5xx/超时/空 → 回退 |
+| `auth_failure` | 401 → 触发密钥重校验 |
+| `fatal` | 非可重试(400、404 模型没了、等) |
+| `hedge_abort` | 预算中途过期中止尝试 (1d2226a) |
+
+---
+
+## 5. 健康端点 (`/api/health`、`/livez`、`/readyz`)
+
+| 端点 | 用途 |
+|----------|---------|
+| `GET /livez` | 进程活着(k8s 存活探针) |
+| `GET /readyz` | 可服务(DB + 至少一健康提供方) |
+| `GET /api/health` | 完整状态:`{status, degraded, providers: [{platform, healthy, totalKeys, usableKeys, status}], catalog: {version, tier, lastSync}}` |
+
+- 降级模式经 `degradation.getDegradationStatus()` 上报。
+- 提供方健康来自 `api_keys` 状态(healthy/unknown/rate_limited/invalid/error)。
+
+---
+
+## 6. 路由追踪头部(每个响应都有)
+
+| 头部 | 值 |
+|--------|-------|
+| `X-Request-ID` | UUID(或客户端 `x-request-id`) |
+| `X-Routed-Via` | `platform/model` (safeHeaderValue) |
+| `X-Fallback-Attempts` | 成功/耗尽前的失败跳数 |
+| `X-Fallback-Trail` | `platform/model keyN=class; …`(最多 10,1KB) |
+| `X-Fallback-Detail` | **可选**:`platform/model keyN=outcome t=start+dur msg=summary; …`(2KB) |
+| `Retry-After` | 到最近冷却过期的秒数(429 耗尽) |
+| `X-FreeLLM-Cache` | `HIT` / `MISS`(响应缓存) |
+| `X-FreeLLM-Compress` | 压缩管线元数据 |
+
+---
+
+## 7. 仪表盘分析页
+
+| 页 | 数据源 |
+|------|-------------|
+| **概览** | `request_aggregates` (24h/7d/30d/90d) |
+| **模型** | 逐模型延迟、词元、成功率、成本节省 |
+| **提供方** | 逐提供方细分 + 额度用量 |
+| **密钥** | 逐密钥健康、用量、冷却、重校验历史 |
+| **日志** | `server_logs` 环 + 持久化(按级别、提供方、搜索过滤) |
+| **缓存** | 命中率、词元节省、LRU 统计 |
+
+---
+
+## 8. 关键函数 (server-logs.ts)
+
+| 函数 | 用途 |
+|----------|---------|
+| `recordLogEntry(options)` | 单一入口(console 抽头、providerLog、启动预加载) |
+| `recordConsoleLine(level, args)` | 被 log-redaction 包装器调 |
+| `providerLog(level, message, meta)` | 结构化 + stdout 镜像 |
+| `initServerLogs()` | 强制种子/预加载(首次轮询时路由调) |
+| `queryLogs(query)` | 过滤、分页、游标式 |
+| `levelCounts()` | 仪表盘徽章 |
+| `currentMaxId()` | 游标上界 |
+| `clearLogs()` | 清两层(ID 计数器保留) |
+| `resetServerLogsForTest()` | 测试冷启动模拟 |
+
+---
+
+## 9. 关键函数 (request-log.ts)
+
+| 函数 | 用途 |
+|----------|---------|
+| `logRequest(platform, modelId, keyId, status, inTokens, outTokens, latencyMs, error, ttfbMs, pinnedModelId)` | 插入请求行 |
+| `persistRequestAttempts(requestId, attempts)` | 批量插入尝试轨迹 |
+| `getRequestAnalytics(window)` | 仪表盘用的聚合卷起 |
+| `getRequestAttempts(requestId)` | 逐请求钻取 |
+
+---
+
+## 10. 环境变量
+
+| 变量 | 默认值 | 用途 |
+|----------|---------|---------|
+| `RESPONSE_CACHE` | `0` | 启用响应缓存(可选) |
+| `REQUEST_MAX_TOKENS_BUDGET` | `0`(关) | 逐请求词元天花板 |
+| `FALLBACK_TIME_BUDGET_MS` | `45000` | 重试预算(影响耗尽) |
+| `MAX_CONSECUTIVE_UPSTREAM_FAILS` | `0`(关) | 断路器阈值 |
+| `EXPOSE_FALLBACK_DETAIL_HEADER` | `0` | 可选 X-Fallback-Detail |
+| `COOLDOWN_PROBE_DISABLED` | `0` | 探测任务熔断开关 |
+
+---
+
+## 11. 隐私与安全
+
+- **日志无 PII**:请求体从不记。仅元数据(模型、平台、词元、延迟、脱敏错误)。
+- **先脱敏**:Console 包装器在 `server-logs` 看到行前先脱敏。
+- **单用户设计**:无多租户日志隔离需求。
+- **本地优先**:除非操作员配置外部日志传输,日志永不出机器。
+
+---
+
+## 12. 表
+
+```sql
+-- 服务器日志(仅 warn/error,跨重启保留)
+CREATE TABLE server_logs (
+ id INTEGER PRIMARY KEY,
+ level TEXT CHECK(level IN ('trace','debug','info','warn','error')),
+ source TEXT, provider TEXT, model TEXT, event TEXT, request_id TEXT,
+ message TEXT, created_at_ms INTEGER
+);
+
+-- 逐请求分析
+CREATE TABLE requests (
+ id INTEGER PRIMARY KEY,
+ platform TEXT, model_id TEXT, key_id INTEGER,
+ request_type TEXT, status TEXT,
+ input_tokens INTEGER, output_tokens INTEGER, total_tokens INTEGER,
+ latency_ms INTEGER, ttfb_ms INTEGER,
+ error TEXT, created_at_ms INTEGER,
+ client_info TEXT, served_model TEXT, attempt_error_summary TEXT
+);
+
+-- 逐尝试轨迹
+CREATE TABLE request_attempts (
+ id INTEGER PRIMARY KEY,
+ request_id INTEGER, attempt_ordinal INTEGER,
+ platform TEXT, model_id TEXT, key_id INTEGER,
+ error_class TEXT, error_summary TEXT,
+ latency_ms INTEGER, ttfb_ms INTEGER,
+ input_tokens INTEGER, output_tokens INTEGER,
+ FOREIGN KEY(request_id) REFERENCES requests(id)
+);
+
+-- 物化聚合(定期刷新)
+CREATE VIEW request_aggregates AS ...;
+```
\ No newline at end of file
diff --git a/docs/i18n/zh-CN/docs/architecture/CHANGELOG.md b/docs/i18n/zh-CN/docs/architecture/CHANGELOG.md
new file mode 100644
index 00000000..d33a9f64
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/architecture/CHANGELOG.md
@@ -0,0 +1,174 @@
+[English](../../../../architecture/CHANGELOG.md) · **简体中文**
+
+# 架构域 —— 变更日志
+
+`docs/architecture/` 的文档修订历史,从触及架构相关代码的提交播种而来。最近的在前。
+
+## 2026-08-23 —— 领域扩展
+
+- **提交(本 PR)**:`docs(architecture): expand into deep-dive domain`
+ - 创建 `docs/architecture/` 领域文件夹,含 6 篇深度文档 + `OVERVIEW.md` + `CHANGELOG.md`
+ - 根目录 `docs/architecture.md` 保留为高层索引,更新了交叉引用
+ - `docs/OVERVIEW.md` 索引新增 architecture/ 域行
+
+## 2026-06-xx —— 可观测性与日志
+
+- **74df985** 仪表盘里的服务器日志查看器,位于分析导航菜单下 (#993)
+ - 新增 `server-logs.ts`:双层存储(环形缓冲区 + 持久化 warn/error)
+ - 新增 `GET /api/logs` API,带游标分页、级别/提供方/搜索过滤
+ - 在 console 包装器层做日志脱敏(API 密钥、令牌、认证头)
+ - 新增请求分析(`requests`、`request_attempts` 表)+ 聚合视图
+ - 经 `AsyncLocalStorage` 做尝试追踪,服务 `X-Fallback-Detail` 头
+
+## 2026-06-xx —— 路由与评分修复
+
+- **f08e17c** fix(router): chars/4 欠计时的上下文窗口安全边际 (#956)
+ - 路由词元估算现在把保留输出封顶 2000 词元(原为完整 max_tokens)
+ - 防止在巨大客户端 max_tokens 时误把整个免费池排除
+ - 输入仍全量计入;上游 429/413 由重试循环处理
+
+- **a9895bc** Fix a batch of routing, streaming, and deployment quick wins (#941)
+ - 路由器、代理、额度、目录同步上的多处小修复
+
+- **4270280** fix(router): `MODEL_ROUTING_OVERRIDES` 永不生效时警告 (#738) (#857)
+ - 保存时校验覆盖的模型 ID 在目录里存在
+
+- **1fea8d5** fix(fallback): 测试间重置模型失败窗口并穿个可注入的 now (#856)
+ - 模型失败停用的可测性改进
+
+## 2026-05-xx —— 降级模式与回退 v2
+
+- **f412e97** feat(server): 降级模式状态机 (#904) (#906)
+ - 新增 `degradation.ts`:健康提供方比率追踪器,带迟滞
+ - 比率 < 50% 持续 60s 进入降级(可配),高于阈值 120s 后退出
+ - 降级态下:老虎机探索禁用,只按剩余健康提供方的评分顺序
+ - 健康端点 + 仪表盘上报状态
+
+- **1d2226a** feat(fallback): 重试时间预算过期时中止停滞尝试(对冲) (#828)
+ - 挂钟预算中途过期时,`abortInFlight()` 经 `AbortController` 取消上游取获
+ - `HedgeAbortError` = 非提供方健康 → 无冷却/惩罚
+ - 渲染 `timedOut` 耗尽并附预算说明
+ - 流式面在首字节时调 `ctx.disarmHedge()`
+
+- **8cb75ac** feat(proxy): 可选 X-Fallback-Detail 头,带逐跳回退耗时 (#792)
+ - `X-Fallback-Detail`:`platform/model keyN=outcome t=start+dur msg=summary; …`
+ - 经 `EXPOSE_FALLBACK_DETAIL_HEADER=1` 或设置可选开启
+ - 2KB 预算,单条摘要 120 字符,最多 10 跳
+
+- **a961d93** fix(routing): 中继吐裸 "safe"/"unsafe" 分类输出时回退 (#809) (#830)
+ - 探测中继模型(OpenCode Zen)的裸分类词
+ - 视同空补全 → 回退,`finish_reason=length` 时 `skipBench: true`
+
+## 2026-04-xx —— 路由增强
+
+- **c3f538e** feat(routing): 经 `MODEL_ROUTING_OVERRIDES` 做按模型权重覆盖 (#747)
+ - `MODEL_ROUTING_OVERRIDES='{"model-id": {"weight": 0.5}}'` 缩放最终有效分
+ - 降级而不禁用;priority 链仍可选它
+
+- **1e675cc** feat(routing): 把社区可靠性先验折入 Beta 后验 (#744)
+ - 可选 `routing_community_prior_enabled` 把其他实例的去毒聚合计数折入
+ - 每个先验封顶 50 个有效样本,让本地证据占主导
+
+- **96da9ec** feat(routing): 给未测模型加探索开关 (#731)
+ - `routing_explore_enabled=1` 给未测模型(<5 样本)保底 10% 优先尝试机会
+ - 防止被先验重的对手饿死
+
+- **fc4e47d** fix(router): 让超时费速度,并回写观测 speed_rank (#619)
+ - 超时现在喂速度轴:封顶延迟(120s)+ 零词元 → 拖低吞吐
+ - TTFB 样本在封顶延迟 → 过 `TTFB_WORST_MS` → 无延迟信用
+ - 定期把有 ≥20 速度样本的模型的观测速度回写到 1..10 `speed_rank`
+
+- **8ad9010** Fix routing chain semantics
+ - priority 策略的密集秩 + 惩罚修复
+
+## 2026-03-xx —— 额度与冷却引擎
+
+- **076fa69** feat: 付费实时目录——签名同步、授权密钥、自助计费
+ - 付费授权的实时目录层(2-3 天刷新)
+ - 免费安装的月度快照层(30 天拖尾)
+ - Ed25519 签名目录、钉死公钥、启动从缓存重应用
+ - 模型年龄闸(30 天)、付费/免费层、迁移播种 vs 托管目录
+
+- **75f0498** fix: Cloudflare 默认输出底线 + 给健康探测巡检限速 (#553) (#644)
+ - 健康探测限速、Cloudflare 输出底线
+
+- **8c9cf94** fix(ratelimit): 经命中启发式升级 NULL 限额提供方 (#392)
+ - 无发布 RPD/TPD 的提供方:1 小时内 2+ 次 429 → "实际上每日耗尽"
+ - 升级但封顶 10 分钟(`UNKNOWN_LIMIT_MAX_COOLDOWN_MS`)
+ - 可逆:成功清空命中窗口
+
+- **bfcef93** fix: 率账本漂移、词元双计、惩罚衰减、错误脱敏
+ - 修在途租约核算、惩罚衰减、错误脱敏
+
+- **67006c5** feat(routing): 停用密钥时遵从上游 Retry-After
+ - Retry-After 作底线遵从,封顶 24h,来源 = 'authoritative'
+
+- **2180ead** 按连接的提供方过滤 v1 models
+ - `/v1/models` 按提供方密钥状态显示可用性
+
+- **12166bd** feat(router): 跳过 tpm_limit 装不下请求的模型
+ - 预检 TPM 对估算词元
+
+- **438eaa2** feat(proxy): 智能体轮次完整性——流校验、工具方言救回、粘性会话修复 (#231 audit)
+ - 流校验:头部拿到首载荷前保留
+ - 工具方言救回:内联工具调用 → 结构化 tool_calls
+ - 粘性会话:30min TTL,键 = 首条用户消息哈希
+
+- **940986c** refactor(gateway): 统一四个提供方回退循环、修漂移 (#482 base) (#483)
+ - 单 `fallback-loop.ts` 服务 `/v1/chat/completions`、`/v1/responses`、`/v1/messages`、`/v1/completions`
+ - 消除冷却、耗尽渲染、尝试轨迹的漂移
+
+- **e57a0f8** feat(gateway): 回退硬化包(401 轮换、丰富耗尽、每日额度停用、截断策略、重试预算、用量兜底) (#484)
+ - 401 → 即时密钥重校验 + 5min 停用
+ - 每日额度耗尽 → 停用到 UTC 午夜
+ - 重试时间预算(默认 45s)
+ - 带尝试轨迹的丰富耗尽响应体
+
+## 2026-02-xx —— 目录与提供方额度
+
+- **2410f87** feat(catalog-sync): 每次启动重应用缓存目录
+ - 解决漂移:迁移重断言基线、启动同步 304、缓存文档重应用
+
+- **03480d8** feat(router): 强制提供方级每日请求上限 (#162)
+ - OpenRouter 1000/天(<10 积分 50/天)、ModelScope 2000/天
+ - 提供方级 RPM:NVIDIA NIM 40 RPM
+
+- **a2d2a54** fix(routing): 多密钥额度修复 #470, #454, #456, #453 (#479)
+ - 汇聚月度预算:`monthly_token_budget × usableKeyCount`
+ - 模型内密钥评分做密钥选择
+
+## 2026-01-xx —— 早期架构
+
+- **413b5e4** feat(router): 分析驱动的老虎机路由,加权轴
+ - 带可靠性/速度/智能轴的 Thompson 采样老虎机
+ - 护栏:headroomFactor、rateLimitFactor
+ - 策略预设:balanced、smartest、fastest、reliable、custom
+
+- **dd46daf** fix(router): 连续 429 的升级冷却(credits @meliani) (#92)
+ - 阶梯:2m → 10m → 1h → 24h,按模型+密钥滚动 24h 窗口
+
+- **7cc751a** fix: 重启丢失率限与冷却状态 (#88)
+ - 冷却持久化到 SQLite(`rate_limit_cooldowns` 表)
+
+- **57541ea** fix(router): 把提供方 400 错误当可重试 (#80)
+ - 400 → 回退而非硬错误
+
+- **a27dc42** fix: 不可解密密钥能阻塞路由 (#85)
+ - 解密错误 → 跳过密钥、不阻链
+
+- **8aea92c** fix(router): 把 404 模型移除当可重试 (#76)
+ - 404 → 回退到下一模型
+
+- **839fe5a** fix(router): 把 413 Payload Too Large 当可重试 (#64)
+ - 413 → 回退
+
+- **2121550** feat(proxy): 在 `/v1/models` 里把 'auto' 暴露为虚拟模型 (#62)
+ - `model: "auto"` 或省略 → 路由器选
+
+- **9b97219** feat(router): 回退前穷尽所有密钥 + 测试 (#42)
+ - 轮询完一个模型的所有密钥再去下一模型
+
+## 2025 —— 基石
+
+- **04e1503** FreeLLMAPI 初版发布
+ - 基础路由、限流、提供方适配器、SQLite 存储
\ No newline at end of file
diff --git a/docs/i18n/zh-CN/docs/architecture/OVERVIEW.md b/docs/i18n/zh-CN/docs/architecture/OVERVIEW.md
new file mode 100644
index 00000000..bea8503f
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/architecture/OVERVIEW.md
@@ -0,0 +1,22 @@
+[English](../../../../architecture/OVERVIEW.md) · **简体中文**
+
+# 架构域 —— 概览与文件索引
+
+本目录包含 FreeLLMAPI 服务端架构的深度文档。根目录的 [`architecture.md`](../../../../architecture.md) 仍是高层索引;这些文件把各子系统展开并给出实现细节。
+
+## 文件索引
+
+| 文件 | 范围 |
+|------|-------|
+| [`01-routing-and-bandit-scoring.md`](01-routing-and-bandit-scoring.md) | Thompson 采样老虎机路由器、可靠性后验、因子权重(可靠性/速度/智能/余量/限流)、10% 探索底线、带模型级耗尽诊断的回退循环 |
+| [`02-quota-and-cooldown-engine.md`](02-quota-and-cooldown-engine.md) | RPM/RPD/TPM/TPD 核算、并发租约、冷却阶梯(90s → 2m → 10m → 1h → 1d)、基于探测的提前恢复、从错误正文/头部退避 (#798)、提供方额度池化(openrouter::free、google::project) |
+| [`03-streaming-pipeline.md`](03-streaming-pipeline.md) | 纯 SSE 流式(零 WebSocket)、OpenAI chat/completions、Anthropic Messages tool_use 块渲染、Gemini `/v1beta`、Responses API 适配、流中错误处理 |
+| [`04-degraded-mode-and-failover.md`](04-degraded-mode-and-failover.md) | 降级模式状态机 (f412e97)、重试预算耗尽时的对冲/中止 (1d2226a)、X-Fallback-Detail 头 (8cb75ac)、裸 safe/unsafe 分类输出回退 (a961d93) |
+| [`05-catalog-sync.md`](05-catalog-sync.md) | 从 freellmapi.co 的实时签名目录同步、模型年龄闸(30 天)、付费/免费层、迁移播种 vs 托管目录 |
+| [`06-observability.md`](06-observability.md) | 服务器日志查看器(环形缓冲 + 持久化 warn/error)、`/api/logs` API、请求分析、日志脱敏 |
+| [`CHANGELOG.md`](CHANGELOG.md) | 本域文档修订历史,从触及架构相关代码的提交播种而来 |
+
+## 导航
+
+- ← [文档根目录](../README.md)
+- ↑ [高层架构索引](../../../../architecture.md)
\ No newline at end of file
diff --git a/docs/i18n/zh-CN/docs/clients/01-agent-clients.md b/docs/i18n/zh-CN/docs/clients/01-agent-clients.md
new file mode 100644
index 00000000..efeb48b0
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/clients/01-agent-clients.md
@@ -0,0 +1,170 @@
+[English](../../../../clients/01-agent-clients.md) · **简体中文**
+
+# 客户端与编程智能体
+
+[← 返回 README](../README.md) · [文档索引](../README.md)
+
+- [OpenAI 兼容客户端](#openai-兼容客户端)
+- [编程智能体](#编程智能体)
+- [原生 Gemini 客户端](#原生-gemini-客户端)
+- [Ollama 客户端](#ollama-客户端)
+- [无头客户端](#无头客户端)
+- [MCP 服务器](#mcp-服务器)
+- [VS Code 幽灵文本自动完成](#vs-code-幽灵文本自动完成)
+- [上下文交接](#上下文交接)
+
+## OpenAI 兼容客户端
+
+任何能指向 OpenAI 兼容 base URL 的客户端都能使用 FreeLLMAPI:
+
+- **LangChain、LlamaIndex、官方 OpenAI SDK**:把 `base_url` 设为
+ `http://localhost:3001/v1`,使用仪表盘里的统一密钥。
+- **本地 GPU 盒子**:为 Ollama、llama.cpp、LM Studio、vLLM 或内部网关添加自定义 OpenAI 兼容端点。
+
+## 编程智能体
+
+用生成器代替手改客户端配置:
+
+```bash
+export FREELLMAPI_API_KEY=<统一密钥> # 或每条命令传 --api-key
+npx freellmapi setup-claude --url http://localhost:3001 --dry-run
+npx freellmapi setup-claude --url http://localhost:3001
+npx freellmapi setup-dsh --url http://localhost:3001 --api-key <统一密钥>
+```
+
+`--dry-run` 打印差异。真实写入会与现有配置合并,并先创建带时间戳的备份。`--profile <name>` 创建一个命名的 Claude/Codex 配置档。实时 `/v1/models` 目录提供模型 id 和上下文窗口。
+
+| 智能体 | 自动化命令 | 手动 base URL | 线上协议 |
+| --- | --- | --- | --- |
+| **Claude Code** | `setup-claude` 或免凭证 `launch` | `http://localhost:3001` | Anthropic Messages |
+| **Codex CLI** | `setup-codex` 或 `launch-codex` | `http://localhost:3001/v1` | Responses (`wire_api = "responses"`) |
+| **Cline** | `setup-cline` | `http://localhost:3001/v1` | OpenAI Chat |
+| **Continue** | `setup-continue` | `http://localhost:3001/v1` | OpenAI Chat / 旧版 Completions |
+| **Aider** | `setup-aider` | `http://localhost:3001/v1` | OpenAI Chat |
+| **OpenCode** | `setup-opencode` | `http://localhost:3001/v1` | OpenAI Chat |
+| **Goose** | `setup-goose` | `http://localhost:3001/v1` | OpenAI Chat |
+| **Qwen Code** | `setup-qwen` | `http://localhost:3001/v1` | OpenAI Chat(原生 Gemini 也可用) |
+| **Roo Code** | `setup-roo` | `http://localhost:3001/v1` | OpenAI Chat |
+| **Kilo Code** | `setup-kilo` | `http://localhost:3001/v1` | OpenAI Chat |
+| **Crush** | `setup-crush` | `http://localhost:3001/v1` | OpenAI Chat |
+| **DeepSeek Harness** | `setup-dsh` | `http://localhost:3001/v1` | OpenAI Chat (`api: openai-completions`) |
+| **Cursor** | `setup-cursor` 打印指引 | 公共 `https://…/v1` | OpenAI Chat |
+| **其他** | `setup-generic` 打印现成配置块 | `http://localhost:3001/v1` | OpenAI Chat |
+
+根路径与 `/v1` 的区别很重要:Claude Code 期望服务器根路径,因为它会追加 Anthropic Messages 路径。本表中兼容 OpenAI 的客户端——包括 Cline、Aider、Goose、Codex、Continue、OpenCode、Qwen、Roo、Kilo、Crush 和 DeepSeek Harness——期望它们配置的 base URL 包含 `/v1`。
+
+### DeepSeek Harness (`dsh`)
+
+[DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 把每个提供方都作为一条路由放在
+`llm-pi-ai.providers` 下面,文件是 `$DSH_HOME/settings.yaml`(默认 `~/.dsh`)。
+`setup-dsh` 在那里添加一条 `freellmapi` 路由——`api: openai-completions`、网关的 `/v1` base URL、以及实时目录作为该路由的 `models` 列表(DSH 要求提供方在其自带目录里没有的模型也得列出来)——并把 `freellmapi/auto` 设为默认模型。密钥写进 `$DSH_HOME/.env`(权限 0600)作为 `FREELLMAPI_API_KEY`,这是 DSH 自己读取的环境层,所以无需导出。两次写入都是结构化合并:文件里其他的路由、注释、设置保持原样。
+
+```bash
+npx freellmapi setup-dsh --url http://localhost:3001 --api-key <统一密钥>
+npx @deepseek-ai/dsh web
+```
+
+设置是热重载的,所以运行中的 `dsh` 下一次请求就会用上这条路由。`--profile <name>` 添加第二条路由(`freellmapi-<name>`)而不改变默认模型;`--model <id>` 固定默认值。路由只声明文本——在 `freellmapi.models` 下给某模型条目加上 `input: [text, image]` 即可发图。尊重 `DSH_HOME`。
+
+## 原生 Gemini 客户端
+
+Gemini CLI 和 Gemini 系客户端能直接说 Google 的线上格式:
+
+```bash
+export GOOGLE_GEMINI_BASE_URL=http://localhost:3001
+export GEMINI_API_KEY=freellmapi-your-unified-key
+gemini
+```
+
+原生面实现了 `GET /v1beta/models`、模型元数据、`generateContent`、`streamGenerateContent`(含 `?alt=sse`)和 `countTokens`。鉴权接受 `x-goog-api-key`、Bearer 或 Gemini 的 `?key=` 兜底。首选头部:查询凭证会泄露进历史和代理日志。
+
+**密钥 → 智能体** 标签页把 Gemini Pro、Flash 和 Flash-Lite 系列名映射到 Auto 或某个固定的目录模型。
+
+## Ollama 客户端
+
+Ollama 模拟默认关闭。在 **密钥 → 智能体** 里启用下列模式之一:
+
+- `open-loopback`:本机免密钥。套接字对端必须是
+ `127.0.0.1`/`::1`;启用桌面局域网访问不会扩大此范围。
+ **Docker 注意事项:** 容器内套接字对端是 Docker 网桥 IP,不是环回,所以此模式甚至拒绝通过发布端口的宿主机本地流量——Docker 部署请用 `key-required`。
+- `key-required`:客户端必须发送 `Authorization: Bearer <统一密钥>`。
+
+确切端点是 `/api/tags`、`/api/chat`、`/api/generate`、`/api/show`、
+`/api/version`、`/api/embed` 和旧版 `/api/embeddings`。流式用
+换行分隔 JSON,而非 SSE。把 Zed、JetBrains AI Assistant 或其他
+支持 Ollama 的客户端指向 `http://localhost:3001`。
+
+## 无头客户端
+
+如果客户端无法设置头部,在 **密钥 → 智能体** 里单独创建一个可撤销的令牌,然后用:
+
+```text
+http://localhost:3001/v1/t/<token>/chat/completions
+http://localhost:3001/v1/t/<token>/responses
+http://localhost:3001/v1/t/<token>/models
+```
+
+同一前缀也暴露 `/api/chat` 和 `/api/tags`。永远别把统一 API 密钥放进 URL。URL 令牌有独立哈希和即时撤销,因为 URL 经常泄露进 shell 历史、反向代理日志和遥测。
+
+## MCP 服务器
+
+在推理之上,路由器还是个 **MCP 服务器**:智能体能在会话中途内省它
+(可用模型及各模型支持的参数、提供方健康度、用量与缓存统计、
+路由策略)。对 Claude Code:
+
+```bash
+claude mcp add --transport http freellmapi http://localhost:3001/mcp \
+ --header "Authorization: Bearer freellmapi-your-unified-key"
+```
+
+任何说 Streamable HTTP 的 MCP 客户端都一样:指向 `/mcp`,用统一密钥作 Bearer 令牌。
+
+FreeLLMAPI 设计为本地优先、单用户。你的提供方密钥留在你的 SQLite 里,静态加密,请求从你的机器直达你启用的上游提供方。
+
+## VS Code 幽灵文本自动完成
+
+FreeLLMAPI 暴露 `/v1/completions` 给发旧版 OpenAI prompt/suffix 请求的编辑器自动完成客户端。Continue 配置示例:
+
+```yaml
+models:
+ - name: FreeLLMAPI Autocomplete
+ provider: openai
+ model: auto
+ apiBase: http://localhost:3001/v1
+ apiKey: freellmapi-your-unified-key
+ useLegacyCompletionsEndpoint: true
+ roles:
+ - autocomplete
+```
+
+## 上下文交接
+
+当 FreeLLMAPI 在对话中途故障转移到另一个模型(额度、限流、冷却),新模型不知道它在接别人的活。**上下文交接**往出站请求里注入一条精简的 `system` 消息,精确告诉新模型这事:
+
+```
+FreeLLMAPI context handoff:
+You are taking over an ongoing conversation from another model (groq:llama-3 → google:gemini-flash).
+Continue the user's task using the conversation context already provided in this request.
+Do not restart the task, re-ask already answered setup questions, or discard prior tool results.
+Respect the user's latest message as the highest-priority instruction.
+
+Recent session summary:
+User: …
+Assistant: …
+```
+
+**在 `.env` 里启用:**
+
+```env
+FREELLMAPI_CONTEXT_HANDOFF=on_model_switch
+```
+
+**工作原理:**
+
+- 每会话消息存在内存里(TTL:3 小时)。
+- 只有给定会话键的选中模型变了才注入。
+- 首次请求、同模型续写、或已有交接消息时不注入。
+- 会话键:有 `X-Session-Id` 头则用它,否则用首条用户消息的 SHA-1(同粘性会话)。
+- 存储纯内存。不写磁盘、不记日志。
+
+> **重要:** 上下文交接改善了经由 FreeLLMAPI 路由的对话的连贯性。它无法恢复提供方内部的隐藏状态,也无法挽回从未发给代理的消息。
\ No newline at end of file
diff --git a/docs/i18n/zh-CN/docs/clients/CHANGELOG.md b/docs/i18n/zh-CN/docs/clients/CHANGELOG.md
new file mode 100644
index 00000000..7d083145
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/clients/CHANGELOG.md
@@ -0,0 +1,9 @@
+[English](../../../../clients/CHANGELOG.md) · **简体中文**
+
+# 客户端域 —— 变更日志
+
+`docs/clients/` 的文档修订历史。最近的在前。
+
+## 2026-08-23 —— 领域创建
+
+- **e8dde9e** `docs(clients): fold agent guide into clients domain` — `docs/clients.md` → `docs/clients/01-agent-clients.md`,补 `OVERVIEW.md` + `CHANGELOG.md`。
diff --git a/docs/i18n/zh-CN/docs/clients/OVERVIEW.md b/docs/i18n/zh-CN/docs/clients/OVERVIEW.md
new file mode 100644
index 00000000..d2226f02
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/clients/OVERVIEW.md
@@ -0,0 +1,16 @@
+[English](../../../../clients/OVERVIEW.md) · **简体中文**
+
+# 客户端域 —— 概览与文件索引
+
+本目录镜像「客户端与编程智能体」英文域的文档:连接编程智能体、CLI 工具及 OpenAI 兼容客户端到 FreeLLMAPI 的集成指南。
+
+## 文件索引
+
+| 文件 | 范围 |
+|------|-------|
+| [`01-agent-clients.md`](01-agent-clients.md) | 编程智能体生成器(`setup-claude`、`setup-codex`、`setup-dsh` 等)、手工 base URL、Ollama 客户端、无头 URL 令牌、MCP 服务、VS Code 补全与 Context Handoff 的完整参考。 |
+| [`CHANGELOG.md`](CHANGELOG.md) | 本域文档修订历史 |
+
+## 导航
+
+- ← [文档根目录](../README.md)
diff --git a/docs/i18n/zh-CN/docs/compression/01-compression-pipeline.md b/docs/i18n/zh-CN/docs/compression/01-compression-pipeline.md
new file mode 100644
index 00000000..bd141e3c
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/compression/01-compression-pipeline.md
@@ -0,0 +1,91 @@
+[English](../../../../compression/01-compression-pipeline.md) · **简体中文**
+
+# 提示词压缩
+
+[← 返回 README](../README.md) · [文档索引](../README.md) · [API 参考](../api/01-rest-api.md)
+
+长的编程智能体会话反复发送系统提示词、文件读取、命令输出和工具 schema。FreeLLMAPI 能在缓存查找、词元预算和路由之前先压缩请求上下文,这样路由器看到的是缩减后的估算值,更多小上下文模型就能保持符合条件。提供方响应绝不重写。
+
+同一条管线跑在 Chat Completions、Responses、Anthropic Messages 和 Anthropic 词元计数上。压缩**默认关闭**。
+
+## 启用它
+
+在仪表盘 **设置 → 提示词压缩** 里选个模式,或用环境变量引导初始模式:
+
+```env
+FREELLMAPI_COMPRESSION=lossless
+```
+
+一旦仪表盘里保存过设置,存储的设置优先于环境变量。
+
+| 模式 | 运行内容 |
+| --- | --- |
+| `off` | 不重写请求。这是总开关;请求头无法开启它。 |
+| `lossless` | 重复块去重、空白清理、可逆的同构 JSON 表格编码。 |
+| `standard` | lossless 引擎外加命令感知的工具输出过滤和陈旧文件读取取代。 |
+| `aggressive` | standard 引擎外加旧轮次浓缩、词汇相关性过滤、可选的硬词元目标。 |
+
+仪表盘还能独立控制各引擎、估算词元自动触发、目标大小、稳定前缀冻结、以及是否信任仓库本地过滤器。
+
+## 逐请求控制
+
+随 `X-FreeLLM-Compress` 发下列值之一:
+
+```text
+off | on | lossless | standard | aggressive
+```
+
+请求头可关闭压缩或降低操作者配置的模式,但不能提高它。`on` 用配置的模式。响应报告生效模式和估算节省:
+
+```text
+X-FreeLLM-Compress: standard; saved~=1840
+```
+
+节省用和路由相同的估算 `chars / 4` 核算,所以头部刻意用 `~=`。
+
+## 自适应压缩
+
+配置了 `autoTriggerEstTokens` 且未压缩请求跨过那个估算时,管线即便在正常配置模式更低时也可能用 aggressive 引擎。一旦达到 `targetTokens` 就停。显式请求头在降低允许模式时仍优先。
+
+## 保真度与缓存安全
+
+管线是 fail-open 的。每个引擎独立运行,输出若增大请求、抛异常、或过不了保真度闸门就会被丢弃。闸门要求:
+
+> **性能注记 (cf0c216):** 受保护跨度检查现在在跨度已知被保留时早退出,避免了逐行热路径上的冗余工作。
+
+- 所有不同的数字字面量和 diff hunks 存活;
+- 所有不同的数字字面量和 diff hunks 存活;
+- 所有显式约束、安全指令、错误行存活;
+- 至少 90% JSON 键存活;
+- 至少 95% 其他受保护跨度存活;
+- 工具调用和工具结果信封保持有效。
+
+受保护跨度包括代码围栏、URL、文件路径、堆栈跟踪、显式约束、错误行、键值对、结构化工具元数据。
+
+重复的稳定系统前缀在第三次出现后冻结。Anthropic `cache_control` 前缀封顶为 lossless 重写。压缩配置计入响应缓存指纹,所以不同压缩等级的请求永不会共享陈旧缓存条目。
+
+## 工具输出过滤器
+
+内置过滤器理解 Git、包管理器、测试运行器、构建、Docker、搜索工具、JSON、堆栈跟踪的常见输出。它们能去 ANSI 转义序列、折叠重复段、保留匹配行、在字符和行数限制下保留有用的首尾上下文。错误输出受到保守处理。
+
+额外的 JSON 过滤器定义可从下列位置加载:
+
+- `~/.freellmapi/filters/*.json` 供用户自有过滤器;
+- 项目里的 `.freellmapi/filters.json`,仅当**信任项目过滤器文件**启用时。
+
+项目过滤器默认关闭,因为仓库可能不受信。
+
+## 设计边界
+
+内置路径是确定性、同步、轻依赖、提供方中立的。它不调用另一个模型、不使用学习式词元剪枝模型、不重写图片、不发布不透明的提供方专属压缩块。那些方法在兼容的上游提供方或智能体运行时拥有上下文状态时可能有用,但跨提供方静默翻译它们会削弱本路由器的 fail-open 和保真度保证。
+
+## 设置、预览与统计 API
+
+认证的管理端可用:
+
+- `GET /api/settings/compression` —— 读取生效配置。
+- `PUT /api/settings/compression` —— 更新模式、引擎、限制、信任控制。
+- `POST /api/compression/preview` —— 检查压缩输出和各引擎结果,不影响实时统计。
+- `GET /api/compression/stats` —— 读取滚动聚合和各引擎的节省与保真度闸门丢弃。
+
+MCP 客户端可用 `compression_stats` 工具读取相同的实时聚合。统计只含计数、耗时、估算节省;请求正文绝不保留。
\ No newline at end of file
diff --git a/docs/i18n/zh-CN/docs/compression/CHANGELOG.md b/docs/i18n/zh-CN/docs/compression/CHANGELOG.md
new file mode 100644
index 00000000..3dfac60b
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/compression/CHANGELOG.md
@@ -0,0 +1,9 @@
+[English](../../../../compression/CHANGELOG.md) · **简体中文**
+
+# 压缩域 —— 变更日志
+
+`docs/compression/` 的文档修订历史。最近的在前。
+
+## 2026-08-23 —— 领域创建
+
+- **6a1c1a9** `docs(compression): fold pipeline guide into compression domain` — `docs/compression.md` → `docs/compression/01-compression-pipeline.md`,补 `OVERVIEW.md` + `CHANGELOG.md`。
diff --git a/docs/i18n/zh-CN/docs/compression/OVERVIEW.md b/docs/i18n/zh-CN/docs/compression/OVERVIEW.md
new file mode 100644
index 00000000..cb1fb55a
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/compression/OVERVIEW.md
@@ -0,0 +1,16 @@
+[English](../../../../compression/OVERVIEW.md) · **简体中文**
+
+# 压缩域 —— 概览与文件索引
+
+本目录镜像提示词与上下文压缩流水线的英文域文档:请求前缓存查询、词元预算与路由前的尺寸缩减。
+
+## 文件索引
+
+| 文件 | 范围 |
+|------|-------|
+| [`01-compression-pipeline.md`](01-compression-pipeline.md) | 压缩模式、引擎、保真度门槛、自适应触发、工具输出过滤器、设置 API 与 MCP 工具访问的完整参考。 |
+| [`CHANGELOG.md`](CHANGELOG.md) | 本域文档修订历史 |
+
+## 导航
+
+- ← [文档根目录](../README.md)
diff --git a/docs/i18n/zh-CN/docs/deployment/01-docker.md b/docs/i18n/zh-CN/docs/deployment/01-docker.md
new file mode 100644
index 00000000..c3ab50a4
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/deployment/01-docker.md
@@ -0,0 +1,107 @@
+[English](../../../../deployment/01-docker.md) · **简体中文**
+
+# Docker
+
+生产镜像、Compose 快速开始,以及在容器里运行 FreeLLMAPI 的一切:持久化、端口、健康检查和网络坑点。
+
+- [镜像](#镜像)
+- [Compose 快速开始](#compose-快速开始)
+- [端口与局域网访问](#端口与局域网访问)
+- [卷与持久化](#卷与持久化)
+- [健康检查](#健康检查)
+- [非 root 运行时](#非-root-运行时)
+- [为什么 better-sqlite3 要从源码编译](#为什么-better-sqlite3-要从源码编译)
+- [排障:容器够不着提供方(#733)](#排障容器够不着提供方733)
+
+## 镜像
+
+FreeLLMAPI 发布单个生产镜像,内含 Express 服务器和构建好的 React 仪表盘:
+
+```bash
+docker pull ghcr.io/tashfeenahmed/freellmapi:latest # 或固定到某个发布版本,如 :v1.2.3
+```
+
+已发布的标签:`latest`(默认分支)、`v*.*.*`(git release 标签)和 `sha-<commit>`。镜像是多架构的(`linux/amd64` + `linux/arm64`,所以树莓派也能跑)。
+
+构建形态([Dockerfile](../../../../../Dockerfile)):
+
+- 基于 `node:20-bookworm-slim` 的三个阶段(`deps` → `build` → `runtime`);只有已构建完成的产物会被复制进 runtime 阶段。
+- runtime 阶段设置 `NODE_ENV=production`、`PORT=3001` 和 `FREELLMAPI_INSTALL_METHOD=docker`;进程为 `node server/dist/index.js`。
+- 一对 `FREELLMAPI_COMMIT_SHA` ARG/ENV 刻意放在所有 `COPY` 层之后:SHA 每次提交都会变,放得更高会让每次构建都使整个镜像的层缓存失效。
+- runtime 还会复制 `desktop/package.json`(一个约 400 字节的清单),让容器安装能报出自己的发布版本(#703)。
+- `.dockerignore` 把秘密和本地状态挡在构建上下文之外:`.env`、`.env.*`、`*.db`(含 `-wal`/`-shm` 边车文件)、`.encryption-key` 以及 `server/data` 永远不会进入镜像。
+
+## Compose 快速开始
+
+前置条件:Docker、Docker Compose、OpenSSL。macOS/Linux:
+
+```bash
+git clone https://github.com/tashfeenahmed/freellmapi.git
+cd freellmapi
+
+# 生成用于静态存储密钥的加密密钥
+ENCRYPTION_KEY="$(openssl rand -hex 32)"
+printf "ENCRYPTION_KEY=%s\nPORT=3001\n" "$ENCRYPTION_KEY" > .env
+
+docker compose up -d
+```
+
+Windows PowerShell 版本和 curl 一行命令引导见 [`docs/install.md`](../install.md#docker-compose)。然后跟踪日志:
+
+```bash
+docker compose logs -f freellmapi
+```
+
+打开 http://localhost:3001 ,在「密钥」页添加提供方密钥,并从该页顶部拿到你的统一 API 密钥——你的 OpenAI SDK 要指向的就是它。
+
+## 端口与局域网访问
+
+Compose 文件把端口发布为 `"${HOST_BIND:-127.0.0.1}:${PORT:-3001}:3001"`。默认仪表盘/API 只能从运行 Docker 的那台机器访问;想从其他设备访问它(例如树莓派上的 `http://192.168.1.x:3001`):
+
+```bash
+HOST_BIND=0.0.0.0 docker compose up -d
+```
+
+只在可信网络上这么做——这个代理是单用户的,唯一的防护就是统一 API 密钥。
+
+## 卷与持久化
+
+SQLite 数据存放在命名卷 `freellmapi-data` 中,挂载于 `/app/server/data`。升级时保持同一个 `.env` 的 `ENCRYPTION_KEY` 和同一个卷,因为提供方密钥是静态加密的。如果你的主机只有一个特定目录做了持久化,用 `FREEAPI_DB_PATH=/that/path/freellmapi.db` 把数据库指过去。
+
+Dockerfile 有意不为 `/app/server/data` 声明 `VOLUME`。持久化是部署方的职责——Compose 文件在那里映射命名卷,普通 `docker run` 则用 `-v`。改在镜像里声明的话,每个没有覆盖它的容器都会创建一个匿名卷:从 Dockerfile 构建的 PaaS 运行时(Railway、Render、Coolify、Dokploy、CapRover)要么拒绝该镜像,要么悄悄给每次重新部署发一个全新的空卷;这条声明还会遮蔽挂载在同一路径的 bind mount。
+
+这个卷的备份见 [02-updates-and-backup.md](02-updates-and-backup.md)。
+
+## 健康检查
+
+Dockerfile 和 Compose 文件定义了同一个探针:一条 Node 单行命令,在容器内请求 `http://127.0.0.1:<port>/api/ping`,响应不 OK 就以非零码退出。
+
+| 设置 | 取值 |
+| --- | --- |
+| 间隔 | 30s |
+| 超时 | 5s |
+| 启动期 | 15s |
+| 重试次数 | 3 |
+
+## 非 root 运行时
+
+runtime 阶段在 `EXPOSE 3001` 之前切换到 `USER node`。服务器数据目录 `/app/server/data` 在构建期间创建并 chown 给 `node:node`,保证运行用户拥有它;所有复制的产物都带 `--chown=node:node`。
+
+## 为什么 better-sqlite3 要从源码编译
+
+`better-sqlite3` 是原生模块。在没有可用预编译二进制的 slim 镜像上——尤其是 QEMU 下的 `linux/arm64` 架构——node-gyp 会从源码编译它,这需要 Python 和一套 C++ 工具链。因此构建阶段通过 apt 安装 `python3 make g++`,而 runtime 镜像直接复制已经编译好的 `node_modules`,让发布的镜像保持干净、不带构建工具。(这套工具链由 #143 加入,此前没有它会构建失败。)
+
+一个相关的打包细节:npm 会把某些生产包嵌套在工作区之下而不是提升到顶层(`undici` 位于 `server/node_modules/undici`)。跳过 `server/node_modules` 的复制曾导致发布镜像里 HTTP(S) 代理分发器加载失败、所有请求都静默直连(#550,c6589ff 修复)。
+
+## 排障:容器够不着提供方(#733)
+
+宿主机一切正常,容器里的提供方却不可达?容器有自己独立的网络栈,有两件在你机器上顺理成章的事不会自动延续过去:
+
+- **`127.0.0.1` 上的代理不是你的机器。** 在容器内部,环回地址指容器自己。如果你经由宿主机上的代理客户端(Clash、v2rayN、sing-box 或公司代理)访问提供方,就让 FreeLLMAPI 指向宿主机:`PROXY_URL=socks5h://host.docker.internal:7890`。随附的 `docker-compose.yml` 通过 `extra_hosts` 把 `host.docker.internal` 映射到宿主机网关,所以在原生 Linux Docker 上和 Docker Desktop 里都可用。代理还得接受来自环回之外的连接(在 Clash 里是 `allow-lan: true`)。更多细节见 [../env/03-outbound-proxies.md](../env/03-outbound-proxies.md#docker-127001-指的是容器)。
+- **纯 IPv6 的宿主机需要在 Docker 里启用 IPv6。** 默认桥接网络只有 IPv4,所以在没有 IPv4 路由的主机上容器什么都够不着,DNS 也一样。在 `/etc/docker/daemon.json` 中以 `"ipv6": true`、`"ip6tables": true` 和一段 `"fixed-cidr-v6"` 网段启用,然后重启 Docker。
+
+想分辨自己撞上的是哪种情况,直接问容器本身:
+
+```bash
+docker compose exec freellmapi node -e "fetch('https://generativelanguage.googleapis.com/').then(r=>console.log('ok',r.status)).catch(e=>console.log('fail',e.cause?.code||e.message))"
+```
diff --git a/docs/i18n/zh-CN/docs/deployment/02-updates-and-backup.md b/docs/i18n/zh-CN/docs/deployment/02-updates-and-backup.md
new file mode 100644
index 00000000..a1eeb6bd
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/deployment/02-updates-and-backup.md
@@ -0,0 +1,106 @@
+[English](../../../../deployment/02-updates-and-backup.md) · **简体中文**
+
+# 更新与备份
+
+让 Docker 部署保持最新、保护 SQLite 数据卷,并用声明式配置让安装可复现。
+
+- [升级容器](#升级容器)
+- [仪表盘更新检查器(#635 / #703)](#仪表盘更新检查器635--703)
+- [备份 SQLite 数据卷](#备份-sqlite-数据卷)
+- [声明式配置与目录控制项(#f4cd7b4)](#声明式配置与目录控制项f4cd7b4)
+
+## 升级容器
+
+跟踪 `:latest`(或固定到某个发布标签),在新镜像上重建容器:
+
+```bash
+docker compose pull && docker compose up -d
+```
+
+任何升级都要守住两条不变量:
+
+1. **保持同一个 `.env` 的 `ENCRYPTION_KEY`。** 提供方密钥是静态加密的;换了密钥,所有已存密钥都无法解密。见 [../env/02-security-and-keys.md](../env/02-security-and-keys.md)。
+2. **保持同一个数据卷**(`freellmapi-data`,位于 `/app/server/data`)。迁移在每次启动时幂等地执行。
+
+桌面版仪表盘的更新对话框会为 Docker 安装显示这条确切的命令(见下文)。
+
+## 仪表盘更新检查器(#635 / #703)
+
+设置页承载唯一的更新入口:它报告当前运行的版本、列出近期提交,并且——当安装方式是 Docker 时——打印 `docker compose pull && docker compose up -d` 升级命令。相关的控制项:
+
+| 变量 | 默认值 | 用途 |
+| --- | --- | --- |
+| `FREELLMAPI_UPDATE_CHECK` | 启用 | 设为 `off` 可把检查器从设置页隐藏,并阻止 Git 发现和对外发出的更新检查请求。这也会一并关掉自动版本提醒——一个独立的仪表盘设置项(设置 > 通用),在被打开之前始终保持关闭。 |
+| `FREELLMAPI_UPDATE_GITHUB_TOKEN` | 空(匿名检查) | 仅用于对 GitHub 做更新检查的可选令牌。只有在需要更高限额时才使用窄权限令牌;通用的 `GITHUB_TOKEN` 值会被有意忽略。 |
+
+两个构建层面的事实支撑着版本显示:`FREELLMAPI_INSTALL_METHOD=docker` 告诉服务器该建议哪条升级路径;runtime 镜像还会复制 `desktop/package.json` ——发布版本号就住在那里,因为 `server/package.json` 跟踪的是工作区版本——作为一个约 400 字节的清单,让容器安装能报出自己的版本(#703)。
+
+## 备份 SQLite 数据卷
+
+要紧的东西都集中在一个地方:命名卷 `freellmapi-data`,挂载于 `/app/server/data`,里面有 SQLite 数据库(`freeapi.db`,或 `FREEAPI_DB_PATH` 指向的位置)、它的 `-wal`/`-shm` 边车文件,以及开发式安装的 `.encryption-key` 文件。把它们作为整体一起备份,并妥善保管配套的 `ENCRYPTION_KEY`——没有它,备份下来的提供方密钥只是无法解密的密文。
+
+内置加密备份(推荐,零停机)。FreeLLMAPI 可以按计划推送活动数据库的加密备份:
+
+```env
+FREEAPI_DB_BACKUP_PATH=/app/server/data/freellmapi.db.backup
+# 或者:
+FREEAPI_DB_BACKUP_URL=https://example.com/freellmapi.db.backup
+FREEAPI_DB_BACKUP_TOKEN=optional-bearer-token
+FREEAPI_DB_BACKUP_KEY=64-char-hex-backup-key # 默认取 ENCRYPTION_KEY
+FREEAPI_DB_BACKUP_INTERVAL_MS=300000
+```
+
+恢复语义:启动时若配置的数据库文件缺失,FreeLLMAPI 会在迁移运行之前恢复备份;服务器运行期间则定期上传新的加密备份。在临时磁盘的主机上,这是主要的保护手段。
+
+卷快照(纯 Docker 做法)。标准模式原样适用:
+
+```bash
+docker run --rm -v freellmapi-data:/data -v "$PWD":/backup alpine \
+ tar czf /backup/freellmapi-data.tar.gz -C /data .
+```
+
+由于服务器一直持有数据库(WAL 模式),建议在容器停止时执行(`docker compose stop`),拿到一份静止的拷贝之后再 `docker compose start`。
+
+## 声明式配置与目录控制项(#f4cd7b4)
+
+对需要可复现的 Docker/服务器安装,FreeLLMAPI 可以在每次启动时应用一份 JSON 配置。设置 `FREEAPI_CONFIG_PATH=/path/to/freellmapi.config.json`,或者把同样的 JSON 内联进 `FREEAPI_CONFIG_JSON`。应用过程是幂等的:已有的密钥、自定义提供方、模型编辑、回退行和路由设置都会被更新而不是重复添加,且发生在每次启动的迁移之后。
+
+```json
+{
+ "keys": [
+ { "platform": "groq", "key": "gsk_...", "label": "main" },
+ { "platform": "google", "key": "AIza...", "enabled": true }
+ ],
+ "customProviders": [
+ {
+ "baseUrl": "http://host.docker.internal:11434/v1",
+ "label": "Ollama",
+ "models": [
+ { "model": "llama3.1:8b", "displayName": "Local Llama", "supportsTools": true }
+ ]
+ }
+ ],
+ "models": [
+ {
+ "platform": "groq",
+ "modelId": "llama-3.3-70b-versatile",
+ "displayName": "Llama 3.3 70B",
+ "supportsTools": true,
+ "fallbackEnabled": true
+ }
+ ],
+ "routing": { "strategy": "balanced" }
+}
+```
+
+如果两个自定义端点提供同一个模型 id,就在 `models` 或 `fallback` 条目里加上 `"endpoint"` 说明你指的是哪一个——端点的 URL,或者仪表盘显示在它旁边的短名。缺省时,匹配到多个端点的条目会被拒绝,而不是随便应用到其中某一个:
+
+```json
+{
+ "models": [
+ { "platform": "custom", "modelId": "deepseek-v3.1", "endpoint": "https://relay-b.example.com/v1", "enabled": false }
+ ]
+}
+```
+
+目录方面:安装会从经过签名的目录订阅源保持模型名册最新(完整目录见 freellmapi.co/models),所以升级之外无需手工维护名册。
diff --git a/docs/i18n/zh-CN/docs/deployment/CHANGELOG.md b/docs/i18n/zh-CN/docs/deployment/CHANGELOG.md
new file mode 100644
index 00000000..59e9bbf0
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/deployment/CHANGELOG.md
@@ -0,0 +1,17 @@
+# 变更记录
+
+`docs/deployment/` 的修订历史,列出塑造了本文档所述 Docker 运维与维护行为的提交。最新在前。
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `a9895bc` | 2026-08-20 | Fix batch of routing, streaming, deployment quick wins (#941). |
+| `29eb340` | 2026-08-06 | feat: in-dashboard update checker, single Settings update surface (#635). |
+| `5d51fec` | 2026-08-03 | docs(docker): why a container cannot reach providers the host can (#737) — source of the troubleshooting section in [01-docker.md](01-docker.md). |
+| `5e5da26` | 2026-08-02 | fix(version,desktop): serve release version to every install (#718). |
+| `c6589ff` | 2026-07-19 | fix(docker): copy server/node_modules into runtime so proxy loads undici (#550). |
+| `a66f752` | 2026-07-06 | security: first-run setup code, key file out of DB, CSV export hardening (#477). |
+| `f4cd7b4` | 2026-06-27 | catalog controls, persistence backup, declarative config — basis for the config/backup sections in [02-updates-and-backup.md](02-updates-and-backup.md). |
+| `1da10bf` | 2026-05-31 | fix(docker): build toolchain for better-sqlite3 native compile (#143). |
+| `606397f` | 2026-05-30 | feat(docker): Docker + GHCR support, multi-arch & localhost-bind (#129). |
+
+Regenerate with `git log --oneline -- Dockerfile docker-compose.yml .dockerignore`.
diff --git a/docs/i18n/zh-CN/docs/deployment/OVERVIEW.md b/docs/i18n/zh-CN/docs/deployment/OVERVIEW.md
new file mode 100644
index 00000000..0d7dfdb3
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/deployment/OVERVIEW.md
@@ -0,0 +1,26 @@
+[English](../../../../deployment/OVERVIEW.md) · **简体中文**
+
+# 部署总览
+
+## 范围
+
+在 Docker 中运营 FreeLLMAPI:已发布的镜像、Compose 快速开始、持久化、健康检查、容器网络坑点,以及日常维护工作——升级、备份和声明式配置。内容取材自 [`Dockerfile`](../../../../../Dockerfile)、[`docker-compose.yml`](../../../../../docker-compose.yml)、[`.dockerignore`](../../../../../.dockerignore) 与 [`docs/install.md`](../install.md)。
+
+Docker 之外的安装路径(一行命令脚本、本地开发、桌面应用)见「[安装与部署](../install.md)」。
+
+## 文件索引
+
+| 文件 | 说明 |
+| --- | --- |
+| [01-docker.md](01-docker.md) | 镜像本身(基于 `node:20-bookworm-slim` 的多阶段构建)、Compose 快速开始、端口与局域网访问、卷与持久化、健康检查、非 root 运行时、原生 `better-sqlite3` 编译缘由,以及为什么容器够不着宿主机能到达的提供方(#733)。 |
+| [02-updates-and-backup.md](02-updates-and-backup.md) | 升级流程(`docker compose pull && docker compose up -d`)、仪表盘更新检查器(#635/#703)、SQLite 数据卷的备份,以及声明式配置/目录控制项(#f4cd7b4)。 |
+
+## 速览
+
+| 方面 | 取值 |
+| --- | --- |
+| 镜像 | `ghcr.io/tashfeenahmed/freellmapi:latest` |
+| 端口 | 3001(默认发布在 `127.0.0.1`;`HOST_BIND=0.0.0.0` 对局域网开放) |
+| 数据卷 | 命名卷 `freellmapi-data`,挂载于 `/app/server/data` |
+| 运行用户 | `node`(非 root) |
+| 健康检查 | 每 30 秒一次 `GET /api/ping`,由容器内的 Node fetch 发起 |
diff --git a/docs/i18n/zh-CN/docs/env/01-variables.md b/docs/i18n/zh-CN/docs/env/01-variables.md
new file mode 100644
index 00000000..1e451930
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/env/01-variables.md
@@ -0,0 +1,119 @@
+[English](../../../../env/01-variables.md) · **简体中文**
+
+# 环境变量参考
+
+FreeLLMAPI 从 `.env` 读取的全部变量,按主题分组。默认值和说明仅依据 [`.env.example`](../../../../../.env.example) 中的注释与取值推导而来。在 `.env.example` 中以注释形式出现的变量是可选的;此处列出的是它们文档记载的默认值。
+
+- [服务器与绑定](#服务器与绑定)
+- [出站代理(本地目的地)](#出站代理本地目的地)
+- [安全与加密](#安全与加密)
+- [限流](#限流)
+- [路由覆盖、超时与故障转移](#路由覆盖超时与故障转移)
+- [出站代理](#出站代理)
+- [请求正文与媒体限制](#请求正文与媒体限制)
+- [存储、缓存、分析与杂项](#存储缓存分析与杂项)
+
+相关阅读:[02-security-and-keys.md](02-security-and-keys.md) 详述 `ENCRYPTION_KEY`;[03-outbound-proxies.md](03-outbound-proxies.md) 详述代理链。
+
+## 服务器与绑定
+
+| 变量 | 默认值 | 用途 |
+| --- | --- | --- |
+| `PORT` | `3001` | 服务器端口。 |
+| `HOST` | `::`(IPv4+IPv6 双栈) | 服务器监听的网络接口。禁用了 IPv6 的主机会自动回退到 IPv4。设为 `0.0.0.0` 表示仅 IPv4,设为 `127.0.0.1` 则只允许本机访问。注意与 `HOST_BIND` 区分:后者只影响 Docker 的端口发布。 |
+| `HOST_BIND` | `127.0.0.1` | 仅 Docker 有效:容器的端口发布在宿主机的哪个接口上。默认值让仪表盘/API 只能从运行 Docker 的那台机器访问;设为 `0.0.0.0` 可对局域网开放(例如树莓派上的 `http://192.168.1.x:3001`)——只在可信网络上这么做,因为这个代理是单用户的,唯一的防护就是统一 API 密钥。 |
+| `DASHBOARD_ORIGINS` | 允许 `localhost:5173`、`127.0.0.1:5173`、`[::1]:5173` | 额外允许从浏览器调用 API 的来源,逗号分隔。只有当仪表盘部署在与 API 不同的主机上时才需要(例如 `http://my-server.local`)。 |
+| `CSP_UPGRADE_INSECURE_REQUESTS` | 自动(未设置) | 控制 Content-Security-Policy 的 `upgrade-insecure-requests` 指令(#682)。未设置:仅当请求经 TLS 到达、或位于 HTTPS 反向代理之后(`X-Forwarded-Proto: https`)时才输出该指令,纯 HTTP 的局域网安装仍可正常渲染。`true`:即使走纯 HTTP 也强制开启该指令(很少有用)。`false`:即使在 HTTPS 之后也强制关闭(例如存在混合内容的反向代理)。 |
+
+## 出站代理(本地目的地)
+
+| 变量 | 默认值 | 用途 |
+| --- | --- | --- |
+| `FREEAPI_PROXY_LOCAL_DESTINATIONS` | `false` | 允许代理 localhost/局域网目的地(Ollama、llama.cpp、LM Studio)。默认情况下本地和局域网目的地(localhost、127.0.0.0/8、::1、0.0.0.0、RFC1918/ULA/CGNAT 地址)总是绕过出站代理——远程代理没有路由回你自己的机器。仅当代理它们才是目的时设为 `true`,例如 `ssh -D` 动态隧道,其中经由 SOCKS 代理的 `http://127.0.0.1:11434` 本意是要到达**远程**主机的 Ollama。 |
+
+## 安全与加密
+
+| 变量 | 默认值 | 用途 |
+| --- | --- | --- |
+| `ENCRYPTION_KEY` | 占位值;生产环境必填,非生产环境使用自动生成的密钥文件 | 用于 API 密钥存储的服务器加密密钥。生成方式:`node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"`。优先级:先看这个环境变量,再看 SQLite 数据库旁边的 `.encryption-key` 文件(不在数据库里面,权限 0600),再看旧 settings 表里的遗留密钥(首次启动时迁移到文件),最后才新生成一把密钥。参见 [02-security-and-keys.md](02-security-and-keys.md)。 |
+| `FREEAPI_BLOCK_PRIVATE_PROVIDER_URLS` | 未设置——自定义提供方仍然允许 localhost 和私有局域网地址 | 自定义提供方的 URL 策略。云元数据和链路本地地址(`169.254.169.254`、`metadata.google.internal`、`fe80::/10` 等)作为自定义提供方 base URL 时一律被阻止。设为 `true` 可以连环回地址和 RFC1918/ULA 私有网段一起阻止——把服务放在 VPS 或任何别人能访问到仪表盘的地方时建议开启。 |
+| `FREEAPI_DB_DIR_HARDENING` | 在安全的前提下自动启用 | 是否把存放数据库的目录限制为本账户可见,这样 SQLite 的 `-wal`/`-shm` 边车文件也能得到保护(它们在第一次写入时才创建,任何启动期的权限检查都来不及顾及)。对默认的 `server/data` 目录以及 FreeLLMAPI 自行创建的目录会自动执行;`FREEAPI_DB_PATH` 指向某个已存在的目录时会跳过,因为那里可能是共享位置。设为 `1` 强制启用,设为 `0` 彻底关闭。 |
+
+首次运行说明:第一个仪表盘账户通常在同一台机器的浏览器里创建,无需额外步骤。如果服务器能被其他设备访问到,创建这第一个账户还需要一个一次性的安装码,它会在尚无账户时的启动阶段打印到服务器日志中。
+
+## 限流
+
+| 变量 | 默认值 | 用途 |
+| --- | --- | --- |
+| `PROXY_RATE_LIMIT_RPM` | `120` | 每个客户端 IP 每分钟可发送的 `/v1` 代理请求上限。设为 `0` 可关闭代理限流。相关的旋钮见 [03-outbound-proxies.md](03-outbound-proxies.md)。 |
+| `ADMIN_RATE_LIMIT_RPM` | `600` | 每个客户端 IP 每分钟可发送的 `/api` 仪表盘请求上限。这是一道防洪水闸——登录有自己的按邮箱锁定机制,密钥导出则有自己严格得多的上限。设为 `0` 关闭。 |
+
+## 路由覆盖、超时与故障转移
+
+| 变量 | 默认值 | 用途 |
+| --- | --- | --- |
+| `MODEL_ROUTING_OVERRIDES` | 未设置 | 按模型的路由评分乘数(#738),JSON 对象,键为模型 id,值为 `0..2`。`1.0` 保持不变,低于 `1` 降低优先级,高于 `1` 提升优先级,`0` 表示自动路由器绝不选它(手动指定优先级仍可用)。匹配只按模型 id 进行,覆盖所有提供该 id 的平台,精确且区分大小写;id 可以从仪表盘的模型页复制。匹配不到任何模型的 id 会被静默忽略,但目录同步完成后,启动日志会对它警告一次。 |
+| `PROVIDER_TIMEOUT_<PLATFORM>` | 内置于各提供方:多数 OpenAI 兼容平台 `60s`,NVIDIA `180s`,Ollama Cloud / AI Horde / 自定义提供方 `120s`,Google 注册时为 `60s` | 各提供方的聊天 HTTP 超时时间,单位毫秒(平台名大写)。对流式请求,这个值同时充当首字节的宽限预算:流在首个字节之前可以沉默多久(issue #584——NVIDIA NIM 这类提供方会立刻发回 SSE 响应头,然后花几分钟预填充长提示词)。`0` 彻底关闭超时。启动时读取。示例:`PROVIDER_TIMEOUT_NVIDIA=300000` 给 NVIDIA NIM 缓慢的推理模型 5 分钟。 |
+| `PROVIDER_STREAM_STALL_TIMEOUT_MS` | `90000` | 流中途的停滞超时,单位毫秒。如果一条 SSE 流在首字节已到达之后持续这么久没有任何字节,网关就放弃:若尚无输出到达客户端,则故障转移到下一个候选;若已有输出,则以一个错误帧结束流。到「第一个」字节为止的时间由 `PROVIDER_TIMEOUT_<PLATFORM>` 管(两者取较大者)。在免费额度上排长队的提供方可能在流中途停顿超过 90 秒——如果流式响应总是提前中断,就调高这个值。`0` 彻底关闭停滞看门狗。 |
+| `PROVIDER_STREAM_STALL_TIMEOUT_<PLATFORM>` | 先回落到上面的全局值,再到内置的 `90000` | 按提供方的变体(平台名大写)。优先级:按平台 > 全局 > 内置 90 秒默认。示例:`PROVIDER_STREAM_STALL_TIMEOUT_OLLAMA=240000` 允许 Ollama Cloud 在流中途停顿 4 分钟,而其他地方的看门狗不受影响。 |
+| `PROVIDER_DAILY_REQUEST_CAP_<PLATFORM>` | 各提供方内置的默认值 | 按提供方的每日请求上限(平台名大写)。覆盖该提供方的内置默认值;设为 `0` 关闭上限。示例:`PROVIDER_DAILY_REQUEST_CAP_OPENROUTER=50`。 |
+| `FALLBACK_TIME_BUDGET_MS` | `45000` | 提供方故障转移的挂钟时间预算,单位毫秒。一个不断失败转移的请求,一旦耗时超过这个预算就不再「发起」新的尝试,改为返回耗尽错误(第一次尝试总会执行;进行中的尝试绝不会被拦腰截断)。`0` 表示不限制,一直重试直到触及尝试次数上限。也可以在运行时通过 `fallback_time_budget_ms` 设置键修改,后者优先。 |
+| `FALLBACK_DETAIL_HEADER` | 关闭 | 可选开启的 `X-Fallback-Detail` 响应头(`=1` 开启)。`X-Fallback-Trail` 已经列出了每一跳的失败原因;这个详情头额外给出每一跳的「代价」——例如 `groq/llama-3.3-70b key1=rate_limited t=0+39000ms msg=...`——这样调用者不用打开仪表盘就能分辨一次 39 秒的卡顿和四次快速失败。默认关闭,因为它会把各跳的耗时和提供方错误文本暴露在响应上。运行时通过 `expose_fallback_detail_header` 设置键覆盖,后者优先。 |
+| `VALIDATE_TOOL_ARGUMENTS` | 关闭(`=1` 开启) | 对照调用方声明的 schema 校验工具调用参数,违反时触发故障转移。`lib/tool-args.ts` 已经修复它能确证可修的部分;这个开关负责剩下的漏网之鱼——它们如今到达 Anthropic 客户端时会是一个带 `input: {}` 的 `tool_use` 块。默认关闭,因为误报的代价是一跳故障转移——先打开它,盯着 `X-Fallback-Trail` 观察 `invalid_tool_arguments`,再决定去留。适用于回合仍可故障转移的所有场合(非流式端点,外加 `/v1/chat/completions`、`/v1/messages`、Gemini 与 Ollama 模拟);`/v1/responses` 的流式在第一个工具调用增量上就已提交,属于例外。运行时通过 `validate_tool_arguments` 设置键调整。 |
+| `REQUEST_MAX_TOKENS_BUDGET` | `0`(关闭) | 按请求的词元护栏:估算输入词元加所请求的 max_tokens 必须落在这个上限之内,否则在任何提供方被尝试之前就以 413 拒绝请求;没有发送 max_tokens 的请求,其输出会被截断到剩余额度。可在运行时通过 `request_max_tokens_budget` 设置键调整(仪表盘 API `PUT /api/settings/guardrails`)。 |
+| `MAX_CONSECUTIVE_UPSTREAM_FAILS` | `0`(关闭) | 故障转移断路器:单个请求内连续上游失败达到这个次数后,以 503 终止故障转移链,而不是在一个不健康的池子里试遍每个剩余候选。可在运行时通过 `max_consecutive_upstream_fails` 设置键调整。 |
+| `MODELSCOPE_VALIDATE_CACHE_MS` | `86400000`(24 小时) | ModelScope(魔搭)用一次消耗额度的单词元聊天补全来校验 API 密钥(`GET /v1/models` 不做鉴权),每次探测都要花费魔粒额度——实测每个超档请求约 2 魔粒。为了不让每 5 分钟一轮的健康检查每天烧掉约 288 次付费探测,校验成功后会按密钥缓存这么长时间(毫秒)。`0` 表示每轮都探测;被撤销的密钥仍会被下一次真实请求的 401 抓住。 |
+| `FREELLMAPI_CONTEXT_HANDOFF` | 关闭 | 模型切换时的上下文交接。启用后(`on_model_switch`),每当一个会话从一个模型切换到另一个(例如发生故障转移之后),FreeLLMAPI 会向出站请求注入一条精简的系统消息。 |
+
+## 出站代理
+
+| 变量 | 默认值 | 用途 |
+| --- | --- | --- |
+| `PROXY_URL` | 未设置 | 提供方请求的出站代理。通常在仪表盘里设置(密钥 → 出站代理);环境变量是为无界面的安装准备的。协议:`http`、`https`、`socks4`、`socks4a`、`socks5`、`socks5h`——带 `h`/`a` 的变体在代理解析 DNS,这正是 DNS 污染网络下想要的。位于下方优先级链的最高一环。 |
+| `ALL_PROXY` | 未设置 | 标准代理变量,优先级链第三位。 |
+| `HTTPS_PROXY` | 未设置 | 标准代理变量,优先级链第四位。 |
+| `HTTP_PROXY` | 未设置 | 标准代理变量,优先级链最后一位。 |
+| `NO_PROXY` | 未设置 | 必须直连、绕开上述代理的主机。逗号分隔;裸域名同时涵盖其子域名,`*` 则彻底禁用代理。 |
+
+**优先级:** `PROXY_URL` → 仪表盘设置 → `ALL_PROXY` → `HTTPS_PROXY` → `HTTP_PROXY`。标准变量的全小写拼写同样会被读取。
+
+在 Docker 里,`127.0.0.1` 指的是容器而不是你的机器——见 [03-outbound-proxies.md](03-outbound-proxies.md)。
+
+## 请求正文与媒体限制
+
+| 变量 | 默认值 | 用途 |
+| --- | --- | --- |
+| `REQUEST_BODY_LIMIT_MB` | `25` | 推理端点(`/v1`、`/v1beta`、`/mcp`、Ollama `/api/*`)的 JSON 正文大小上限,单位 MB。视觉请求会把 base64 图片嵌进正文并随每一轮回放,大型会话很容易超过 10MB;这个上限只管解析——入站图片归一化随后会缩小载荷。如果更大的载荷被 413 `request_too_large` 拒绝,就调高它。 |
+| `IMAGE_NORMALIZE` | `on` | 入站图片归一化的总开关(`off` 彻底关闭)。超过阈值的数据 URL 图片会在路由前被降采样到长边上限并重新编码(JPEG,或仅在 alpha 通道携带真实透明度时保留 PNG),把回放的截图缩小约 6–10 倍。同时会把上游拒收的冷门格式归一化(bmp/gif/tiff/avif/webp → jpeg/png);gif 只保留第一帧。反正每个上游内部都会自行缩放(OpenAI 到 2048px,Anthropic 到 1568px),超出上限的像素纯属传输浪费。 |
+| `IMAGE_NORMALIZE_MAX_DIMENSION` | `2048` | 归一化图片的长边像素上限。 |
+| `IMAGE_NORMALIZE_THRESHOLD_KB` | `1024` | 超过这个大小(KB)的图片才会进入降采样候选。 |
+| `IMAGE_NORMALIZE_QUALITY` | `90` | 归一化图片重新编码的质量。 |
+
+## 存储、缓存、分析与杂项
+
+| 变量 | 默认值 | 用途 |
+| --- | --- | --- |
+| `RESPONSE_CACHE` | `false` | 可选开启的响应缓存。开启后,一次成功的非流式 `/v1/chat/completions` 回答会存进一个有界的内存 LRU(以整个请求的规范化哈希为键),因此完全相同的后续请求直接由内存应答,不再消耗提供方额度。只做精确匹配——近似请求绝不会返回另一个提示词的答案。可在运行时通过仪表盘切换(`PUT /api/cache/config`),也可按请求用 `X-FreeLLM-Cache: on\|off` 头控制。重启即清空。 |
+| `RESPONSE_CACHE_TTL_SECONDS` | `3600`(1 小时) | 缓存的回答保持新鲜多久,单位秒。 |
+| `RESPONSE_CACHE_MAX_TEMPERATURE` | `1.0` | 只缓存温度不高于该值的请求;更高的温度需要新鲜多样的输出。默认在开启时全部缓存;调低它(如 `0.2`)则只缓存接近确定性的调用。 |
+| `RESPONSE_CACHE_MAX_ENTRIES` | `5000` | 存储条目的硬上限;超过后按最近最少使用逐出。 |
+| `FREELLMAPI_COMPRESSION` | `off` | 请求侧的提示词/上下文压缩。`lossless` 应用空白清理、完全重复块的引用以及可逆的表格化 JSON 编码;`standard` 再过滤工具输出和已被取代的文件读取;`aggressive` 追加基于年龄/相关性/预算的浓缩。仪表盘可以在设置里实时更改。单个请求可以用 `X-FreeLLM-Compress` 把配置的模式调低,但不能越过全局 `off` 总开关。 |
+| `REQUEST_ANALYTICS_RETENTION_DAYS` | `90` | 请求分析的留存天数。设为 `0` 取消此限制。 |
+| `REQUEST_ANALYTICS_MAX_ROWS` | `100000` | 请求分析的行数上限。设为 `0` 取消此限制。 |
+| `REQUEST_ANALYTICS_LOG_CLIENT` | `true` | 把每次请求的调用者身份(客户端 IP + User-Agent)记入请求分析,并显示在仪表盘的「最近调用」表里。设为 `false` 则改存 null(聚合分析不受影响)。 |
+| `SERVER_LOGS_RETENTION_DAYS` | `7` | 仪表盘日志查看器后面的持久化服务器日志。只有 warn/error 行会写入数据库(实时视图是内存环),所以这些界限比上面的分析界限紧得多。设为 `0` 取消此限制。 |
+| `SERVER_LOGS_MAX_ROWS` | `50000` | 持久化服务器日志的行数上限。设为 `0` 取消此限制。 |
+| `FREEAPI_DB_PATH` | 默认位置,紧邻 server 构建产物 | 可选的 SQLite 位置覆盖。适合只有某一个目录做了持久化挂载的主机,或者想把数据库放到 `server/data` 之外的场景。示例:`/app/server/data/freellmapi.db`。 |
+| `FREEAPI_DB_BACKUP_PATH` | 未设置 | 可选的加密 SQLite 备份目标(文件路径)。启动时若配置的数据库文件缺失,FreeLLMAPI 会恢复这份备份;运行期间则定期上传新的备份。 |
+| `FREEAPI_DB_BACKUP_URL` | 未设置 | HTTP(S) 备份目标,上面路径的替代方案。 |
+| `FREEAPI_DB_BACKUP_TOKEN` | 未设置 | 向 `FREEAPI_DB_BACKUP_URL` 上传时可选的 bearer 令牌。 |
+| `FREEAPI_DB_BACKUP_KEY` | 省略时使用 `ENCRYPTION_KEY` | 备份信封专用的 64 位十六进制密钥,可与主密钥分开。 |
+| `FREEAPI_DB_BACKUP_INTERVAL_MS` | `300000`(5 分钟) | 后台备份之间的间隔。 |
+| `FREEAPI_CONFIG_PATH` | 未设置 | 可选的声明式启动配置:指向一个 JSON 文件的路径,每次启动都会在迁移之后幂等地应用。示例:`/app/server/data/freellmapi.config.json`。 |
+| `FREEAPI_CONFIG_JSON` | 未设置 | 同样的声明式配置,以内联方式而非文件给出,例如 `{"keys":[{"platform":"groq","key":"gsk_...","label":"main"}],"routing":{"strategy":"balanced"}}`。 |
+| `FREELLMAPI_UPDATE_CHECK` | 启用 | 手动的应用更新检查器。设为 `off` 可把它从设置页隐藏,并阻止 Git 发现和对外发出的更新检查请求。这也会一并关掉自动版本提醒——那是另一个独立的仪表盘设置项(设置 > 通用),在被打开之前始终保持关闭。 |
+| `FREELLMAPI_UPDATE_GITHUB_TOKEN` | 空(匿名检查) | 仅用于对 GitHub 做更新检查的令牌。检查器默认匿名;只有在需要更高限额时才使用窄权限令牌。通用的 `GITHUB_TOKEN` 会被有意忽略。 |
+| `FREELLMAPI_COMMIT_SHA` | 由官方构建注入 | 标识确切提交的构建元数据。一般不应写进 `.env`。 |
+| `FREELLMAPI_INSTALL_METHOD` | 由官方构建注入(Docker 镜像设为 `docker`) | 更新检查器使用的安装类型元数据。一般不应写进 `.env`。 |
+| `CLIENT_DIST` | 随附的客户端构建 | 指向要伺服的预构建客户端 `dist` 目录的路径。只有单独构建仪表盘时才需要设置。 |
+| `FREEAPI_ENV_PATH` | `./.env` | 要加载的 `.env` 文件的显式路径。对嵌入式场景有用(例如桌面应用,代码从打包内部运行);dotenv 对缺失文件静默忽略。 |
\ No newline at end of file
diff --git a/docs/i18n/zh-CN/docs/env/02-security-and-keys.md b/docs/i18n/zh-CN/docs/env/02-security-and-keys.md
new file mode 100644
index 00000000..19e71bbb
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/env/02-security-and-keys.md
@@ -0,0 +1,76 @@
+[English](../../../../env/02-security-and-keys.md) · **简体中文**
+
+# 安全与密钥处理
+
+FreeLLMAPI 如何保护你存进来的提供方 API 密钥,以及让这层保护真正生效的 `ENCRYPTION_KEY` 是如何生成、存储和迁移的。
+
+来源:[`.env.example`](../../../../../.env.example)(密钥生命周期注释)、[`server/src/lib/crypto.ts`](../../../../../server/src/lib/crypto.ts) 与 [`server/src/db/index.ts`](../../../../../server/src/db/index.ts)。
+
+- [加密密钥一览](#加密密钥一览)
+- [密钥解析优先级](#密钥解析优先级)
+- [开发环境自动生成的密钥文件](#开发环境自动生成的密钥文件)
+- [为什么密钥文件不在数据库里](#为什么密钥文件不在数据库里)
+- [提供方密钥的静态加密](#提供方密钥的静态加密)
+- [数据目录加固(WAL 边车文件)](#数据目录加固wal-边车文件)
+- [首次运行的安装码](#首次运行的安装码)
+
+## 加密密钥一览
+
+`ENCRYPTION_KEY` 是用于 API 密钥存储的服务器端密钥。它必须是 64 个十六进制字符——一把 32 字节的 AES-256-GCM 密钥。生成方式:
+
+```bash
+node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
+```
+
+(或者用 Compose 快速开始里的 `openssl rand -hex 32`)。`.env.example` 中的占位值(`your-64-char-hex-key-here`)永远不会被当成真密钥接受。
+
+打错或过短的密钥会快速失败并给出可操作的错误信息,而不是被悄悄截断,直到第一次加密调用才以一条莫名其妙的 `node:crypto` 错误浮出水面。
+
+## 密钥解析优先级
+
+启动时数据库初始化完成之后,密钥按以下顺序解析:
+
+1. **`ENCRYPTION_KEY` 环境变量** —— 只要设置为非占位值就永远胜出。
+2. **密钥文件** —— SQLite 数据库旁边的 `.encryption-key` 文件。
+3. **遗留的 settings 表行** —— 更早的安装把密钥存在 `settings` 表的一行里;它会在首次启动时迁移到文件,然后从表中删除。
+4. **新生成的密钥** —— 写入密钥文件(仅在非生产环境;见下文)。
+
+## 开发环境自动生成的密钥文件
+
+在非生产环境下 `ENCRYPTION_KEY` 是可选的:未设置时会自动生成一把密钥并写入 SQLite 数据库旁边的 `.encryption-key` 文件——注意不是数据库里面——权限为 `0600`。这样做的目的是让新克隆的仓库在 `npm run dev` 下无需手工设置即可启动;否则 `.env.example` 里的占位值会让服务器一启动就崩溃,在客户端表现为「无法连接服务器」。
+
+生产环境仍然要求显式设置环境变量密钥:自动生成的密钥只存在于本地磁盘上,一旦悄悄丢失,所有已存储的 API 密钥都无法解密。
+
+两个写入安全细节:
+
+- 密钥文件通过「临时文件加改名」原子写入,崩溃绝不会留下半截密钥。
+- 临时文件在改名「之前」就被限制为仅所有者可读写,因此密钥不会顶着最终文件名短暂地变成全局可读;改名的瞬间 DACL 随之带走,对最终路径再做一次权限收紧只是幂等的双保险。如果最终的限制无法施加,会记录一条警告。
+
+不要拿真实提供方密钥去依赖这套回退机制:请设置 `ENCRYPTION_KEY`。
+
+## 为什么密钥文件不在数据库里
+
+把密钥和它保护的密文放在一处(旧的 `settings` 行方案),意味着默认安装下的静态加密什么也保护不了:谁拷走了数据库,谁就连密钥一起拷走。密钥文件位于同一目录但是一件独立的产物,chmod 为 `0600`,因此只拷贝数据库不再能得到可用的密文。遗留安装会在首次启动时自动迁移到这一方案。
+
+## 提供方密钥的静态加密
+
+存储的提供方密钥使用解析出的密钥以 AES-256-GCM 加密。有几点值得知道:
+
+- **重启和升级时保持同一个 `ENCRYPTION_KEY`。** 丢失它意味着每一条已存的提供方密钥都无法解密;没有任何恢复途径。
+- 仪表盘的密钥导出功能是为备份而存在的;它的限流被刻意设置得远比常规 `/api` 防洪水闸严格(见 [01-variables.md](01-variables.md#限流))。
+- 可选的加密数据库备份([../deployment/02-updates-and-backup.md](../deployment/02-updates-and-backup.md))的信封密钥默认取 `ENCRYPTION_KEY`;`FREEAPI_DB_BACKUP_KEY` 可以用一个单独的 64 位十六进制密钥覆盖它。
+
+## 数据目录加固(WAL 边车文件)
+
+SQLite 在第一次写入时创建 `-wal` 和 `-shm` 边车文件,并在最后一次干净关闭时删除它们——所以启动那一刻那里可能什么都没有、无从 chmod,这些文件的保护只能来自它们所在的目录。因此 FreeLLMAPI 在打开连接之前就把存放数据库的目录限制为仅属主账户可见(Windows 上 ACL 是继承的,所以先加固目录意味着数据库文件一出生就受到保护,而不是带着父目录给的 ACL 度过最初一段时间)。
+
+由于锁死一个不属于我们的目录会比它防住的泄漏更糟(把数据库指到 `/tmp/freeapi.db` 绝不能 chmod `0700` 整个 `/tmp`),加固按照「构造上即属主」的原则执行:
+
+1. 该目录刚刚由本进程创建;或者
+2. 它是内置的默认数据目录(`server/data`),发布时就属于我们。
+
+把 `FREEAPI_DB_PATH` 指向某个专用既有目录的运维者可以用 `FREEAPI_DB_DIR_HARDENING=1` 显式加入,也可以用 `=0` 彻底退出。默认行为是「安全处默认开启」而不是一个必填开关:只在有人记得开口时才执行的加固,和没人察觉已经停摆的加固,属于同一类失败。
+
+## 首次运行的安装码
+
+第一个仪表盘账户通过界面创建。与服务器同机的浏览器可以直接创建,无需额外步骤。如果服务器能被其他设备访问到,创建这第一个账户还需要一个一次性的安装码——它在尚无任何账户时于启动阶段打印到服务器日志中——这样陌生人就无法认领一个刚暴露出来的全新安装。
diff --git a/docs/i18n/zh-CN/docs/env/03-outbound-proxies.md b/docs/i18n/zh-CN/docs/env/03-outbound-proxies.md
new file mode 100644
index 00000000..78f9e3e1
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/env/03-outbound-proxies.md
@@ -0,0 +1,90 @@
+[English](../../../../env/03-outbound-proxies.md) · **简体中文**
+
+# 出站代理
+
+FreeLLMAPI 如何把发往提供方的流量经由代理转发、多个变量同时设置时谁说了算,以及随之而来的 Docker 网络坑点。
+
+来源:[`.env.example`](../../../../../.env.example)(代理配置块)、[`docker-compose.yml`](../../../../../docker-compose.yml),以及 [`docs/install.md`](../install.md) 中的容器网络说明。
+
+- [代理链优先级](#代理链优先级)
+- [协议支持](#协议支持)
+- [`NO_PROXY` 直连豁免](#no_proxy-直连豁免)
+- [Docker:`127.0.0.1` 指的是容器](#docker-127001-指的是容器)
+- [相关的入站限流旋钮](#相关的入站限流旋钮)
+
+## 代理链优先级
+
+发往提供方请求的出站代理通常在仪表盘里设置(密钥 → 出站代理);环境变量是为无界面的安装准备的。当多个来源同时存在时,解析顺序为:
+
+```
+PROXY_URL → dashboard setting → ALL_PROXY → HTTPS_PROXY → HTTP_PROXY
+```
+
+标准变量的全小写拼写同样会被读取(`all_proxy`、`https_proxy`、`http_proxy`)。
+
+| 变量 | 在链中的角色 |
+| --- | --- |
+| `PROXY_URL` | FreeLLMAPI 显式的代理设置;最高优先级。 |
+| 仪表盘设置 | 密钥 → 出站代理;胜过通用的环境变量。 |
+| `ALL_PROXY` | 标准的兜底代理变量。 |
+| `HTTPS_PROXY` / `HTTP_PROXY` | 常规的按协议变量,优先级最低。 |
+
+## 协议支持
+
+接受的协议:`http`、`https`、`socks4`、`socks4a`、`socks5`、`socks5h`。
+
+带 `h`/`a` 的变体(`socks5h`、`socks4a`)在代理端而非本地解析 DNS,这正是 DNS 污染网络下想要的。示例:
+
+```env
+PROXY_URL=socks5h://127.0.0.1:1080
+```
+
+## `NO_PROXY` 直连豁免
+
+`NO_PROXY` 列出必须直连的主机,绕开上面胜出的那个代理:
+
+```env
+NO_PROXY=localhost,127.0.0.1,.internal.corp
+```
+
+- 条目之间用逗号分隔。
+- 裸域名同时涵盖其子域名。
+- 特殊值 `*` 彻底禁用代理。
+
+## Docker:`127.0.0.1` 指的是容器
+
+在容器内部,`127.0.0.1` 是容器自己——不是你的机器(#733)。如果你的代理客户端跑在宿主机上(Clash、v2rayN、sing-box 或公司代理),需要两处调整:
+
+1. 让 FreeLLMAPI 指向宿主机的地址而不是环回地址:
+
+ ```env
+ PROXY_URL=socks5h://host.docker.internal:7890
+ ```
+
+2. 确保代理监听的不只是环回地址(在 Clash 里是 `allow-lan: true`)。
+
+随附的 `docker-compose.yml` 通过一条 `extra_hosts` 条目把 `host.docker.internal` 映射到宿主机网关,所以在原生 Linux Docker 上同样可用,并不限于已经内置这个名字的 Docker Desktop:
+
+```yaml
+extra_hosts:
+ - "host.docker.internal:host-gateway"
+```
+
+另一种与此无关、却同样会让容器失联而宿主机安然无恙的情况:在纯 IPv6 的宿主机上,默认桥接网络只有 IPv4,于是容器什么都够不着——DNS 也一样。在 `/etc/docker/daemon.json` 里启用 IPv6(`"ipv6": true`、`"ip6tables": true`,以及一段 `"fixed-cidr-v6"` 网段)并重启 Docker。
+
+想分辨自己撞上的是哪种情况,直接问容器本身:
+
+```bash
+docker compose exec freellmapi node -e "fetch('https://generativelanguage.googleapis.com/').then(r=>console.log('ok',r.status)).catch(e=>console.log('fail',e.cause?.code||e.message))"
+```
+
+## 相关的入站限流旋钮
+
+虽然都带「proxy」这个名字,下面这两个变量限的是「进入」FreeLLMAPI 自身的流量,而不是发往提供方的出站调用:
+
+| 变量 | 默认值 | 用途 |
+| --- | --- | --- |
+| `PROXY_RATE_LIMIT_RPM` | `120` | 每个客户端 IP 每分钟可发送的 `/v1` 代理请求上限。`0` 关闭。 |
+| `ADMIN_RATE_LIMIT_RPM` | `600` | 每个客户端 IP 每分钟可发送的 `/api` 仪表盘请求上限——一道防洪水闸;登录有自己的按邮箱锁定机制,密钥导出则有自己严格得多的上限。`0` 关闭。 |
+
+完整描述见 [01-variables.md](01-variables.md#限流)。
diff --git a/docs/i18n/zh-CN/docs/env/CHANGELOG.md b/docs/i18n/zh-CN/docs/env/CHANGELOG.md
new file mode 100644
index 00000000..4d8051e8
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/env/CHANGELOG.md
@@ -0,0 +1,16 @@
+# 变更记录
+
+`docs/env/` 的修订历史,列出塑造了本文档所述运行时配置面的提交。最新在前。
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `473d790` | 2026-08-20 | fix(modelscope): stop health checks burning magic-grain quota (#882) — basis for the `MODELSCOPE_VALIDATE_CACHE_MS` entry. |
+| `48591a8` | 2026-08-12 | fix(router): warn when MODEL_ROUTING_OVERRIDES never apply (#857) — boot-log warning for unmatched model ids. |
+| `8f27336` | 2026-08-12 | feat(vision): end-to-end image input, body limits, inbound normalization (#852) — introduced `REQUEST_BODY_LIMIT_MB` and the `IMAGE_NORMALIZE*` knobs. |
+| `c3f538e` | 2026-08-11 | feat(routing): per-model weight overrides via MODEL_ROUTING_OVERRIDES (#747) — introduced the routing override variable. |
+| `ba39318` | 2026-08-11 | feat(dashboard): automatic update check w/ release-notes dialog (#782) — automatic release reminder behind the update-checker settings. |
+| `8cb75ac` | 2026-08-10 | feat(proxy): opt-in X-Fallback-Detail header (#792) — introduced `FALLBACK_DETAIL_HEADER`. |
+| `a6f7718` | 2026-08-06 | fix(db): harden data dir so WAL sidecars are covered (#795) — data-directory restriction and `FREEAPI_DB_DIR_HARDENING`. |
+| `29eb340` | 2026-08-06 | feat: in-dashboard update checker (#635) — `FREELLMAPI_UPDATE_CHECK` and related variables. |
+
+Regenerate with `git log --oneline -- .env.example`.
diff --git a/docs/i18n/zh-CN/docs/env/OVERVIEW.md b/docs/i18n/zh-CN/docs/env/OVERVIEW.md
new file mode 100644
index 00000000..250d7174
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/env/OVERVIEW.md
@@ -0,0 +1,23 @@
+[English](../../../../env/OVERVIEW.md) · **简体中文**
+
+# 环境变量配置总览
+
+## 范围
+
+本域文档描述 FreeLLMAPI 的运行时配置面:服务器从 `.env` 读取的每一个变量、提供方 API 密钥如何静态加密存储,以及出站流量如何经由代理转发。唯一的权威来源是仓库根目录的 [`.env.example`](../../../../../.env.example);这里的参考内容均由它(及其描述的代码路径)推导而来,绝不编造取值。
+
+如果是第一次把安装跑起来,请看[安装与部署](../install.md)。
+
+## 文件索引
+
+| 文件 | 说明 |
+| --- | --- |
+| [01-variables.md](01-variables.md) | 按主题分组的完整变量参考(服务器/绑定、安全、限流、路由覆盖、出站代理、请求正文/媒体限制、杂项),默认值逐字取自 `.env.example`。 |
+| [02-security-and-keys.md](02-security-and-keys.md) | `ENCRYPTION_KEY` 的生命周期:生成、开发环境自动生成的密钥文件、已存储提供方密钥的 AES-256-GCM 静态加密、密钥文件移出数据库的加固措施,以及数据目录权限。 |
+| [03-outbound-proxies.md](03-outbound-proxies.md) | 出站代理配置:协议支持、解析链优先级(从 `PROXY_URL` 到 `HTTP_PROXY`)、`NO_PROXY` 直连豁免、Docker 的 `host.docker.internal` 坑点,以及相关的入站限流旋钮。 |
+
+## 约定
+
+- 变量由 [`server/src/env.ts`](../../../../../server/src/env.ts) 通过 dotenv 加载;`FREEAPI_ENV_PATH` 可为嵌入式场景指定另一处 `.env` 位置。
+- `.env.example` 中被注释掉的行是可选变量;未注释的行自带生效的默认值。
+- 凡是也能在运行时从仪表盘修改的变量,都会注明对应的运行时设置键,且该设置键始终优先于环境变量的取值。
diff --git a/docs/i18n/zh-CN/docs/logs/01-server-logs-viewer.md b/docs/i18n/zh-CN/docs/logs/01-server-logs-viewer.md
new file mode 100644
index 00000000..cf8009ff
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/logs/01-server-logs-viewer.md
@@ -0,0 +1,126 @@
+[English](../../../../logs/01-server-logs-viewer.md) · **简体中文**
+
+# 服务器日志查看器
+
+仪表盘内置实时 **服务器日志** 查看器(从分析导航菜单进入),它把服务器打印到 stdout 的同那些诊断行——路由决策、提供方健康检查、密钥冷却、额度耗尽、压缩保真度闸门、以及任何 `warn`/`error` 级别事件——呈现在面前,无需 SSH 或容器日志访问。
+
+---
+
+## 双层存储
+
+日志存储在两个层级使用**同一 id 空间**:
+
+| 层级 | 容量 | 级别 | 持久化 | 用途 |
+| --- | --- | --- | --- | --- |
+| **环形缓冲区** | 1,000 条(最新) | `trace`、`debug`、`info`、`warn`、`error` | 仅内存 | 轮询仪表盘的实时尾部;经得起过滤器变更,经不住重启。 |
+| **`server_logs` 表** | 可配置(`SERVER_LOGS_MAX_ROWS`,默认 50,000) | 仅 `warn`、`error` | SQLite(重启保留) | 对最重要的警告/错误的持久历史。 |
+
+- **Id 由存储分配**,不是 SQLite。启动时计数器从 `MAX(id)` 种子,所以 id 跨重启单调递增。拿着 `sinceId` 游标的仪表盘标签页永远不会见到它倒退。
+- 启动时存储**预加载至多 200 条最近持久化行**(最新优先)进环形缓冲,这样仪表盘显示的是重启前的警告,而不是空面板。
+- 采集发生在**脱敏包装器内部**(`lib/log-redaction.ts`)。进程里只有一个 console 补丁;它先脱敏,然后存储只看到已脱敏的形式。机密永不进入环形缓冲或数据库。
+- 匹配 `GET|HEAD /api/(logs|ping)` 的行在入口处被过滤掉,防止自喂缓冲(轮询端点原本会成为日志里最吵的东西)。
+
+---
+
+## API 契约
+
+所有端点挂在 `/api/logs` 下,受仪表盘会话门控保护(统一 `/v1` 密钥打开推理面,**绝不**打开这个——这些行会泄露提供方、模型、密钥 id、失败原因)。
+
+### `GET /api/logs` —— 轮询端点
+
+面向每隔几秒轮询一次的仪表盘的基于游标分页。
+
+| 查询参数 | 类型 | 说明 |
+| --- | --- | --- |
+| `sinceId` | `integer`(可选) | 返回比这个 id **更新**的条目。省略则取最新 `limit` 条(默认 200)。返回的 `nextId` 游标是存储的最高 id,**不是**返回的最高 id——所以匹配全被过滤掉的一次轮询仍能推进游标,而不是永远重扫同一段尾部。 |
+| `levels` | `csv`(可选) | 逗号分隔的级别过滤:`trace,debug,info,warn,error`。未知级别返回 `400`。 |
+| `q` | `string`(可选) | 跨 `message`、`provider`、`source`、`event` 的大小写不敏感文本搜索。 |
+| `provider` | `string`(可选) | 精确提供方名过滤(如 `openai`、`anthropic`)。 |
+| `limit` | `integer`(可选) | 钳制在 `[1, 500]`,默认 `200`。 |
+
+**响应:**
+
+```json
+{
+ "entries": [
+ {
+ "id": 12345,
+ "ts": "2026-08-23T14:32:11.123Z",
+ "level": "warn",
+ "source": "CooldownProbe",
+ "provider": "openai",
+ "model": "gpt-4o",
+ "event": "cooldown_triggered",
+ "requestId": "req_abc123",
+ "message": "[CooldownProbe] openai:gpt-4o key #3 entered 45s cooldown (rate limit)"
+ }
+ ],
+ "nextId": 12345,
+ "counts": { "debug": 12, "info": 145, "warn": 8, "error": 2 }
+}
+```
+
+- `trace` 在计数里并入 `debug`(仪表盘显示四个徽章)。
+- `entries` 数组在返回页内是 **最旧 → 最新**。
+- 已追上来的调用者(`sinceId >= lastId`)只需一次整数比较就拿到 `entries: []`。
+
+### `GET /api/logs/counts` —— 级别计数
+
+返回每次轮询响应里都带的同一个 `LogLevelCounts` 对象,所以只想要徽章数字的页面能一次性取走,不用拉完整条目载荷。
+
+```json
+{ "debug": 12, "info": 145, "warn": 8, "error": 2 }
+```
+
+### `POST /api/logs/clear` —— 清空两层
+
+清空环形缓冲区**并**截断 `server_logs` 表。id 计数器**不重置**——不然拿着游标的仪表盘标签页会收到它已经见过的 id。
+
+```json
+{ "ok": true }
+```
+
+---
+
+## 环境变量
+
+| 变量 | 默认值 | 说明 |
+| --- | --- | --- |
+| `SERVER_LOGS_RETENTION_DAYS` | `7` | 超过这么多天的行会被每日维护任务删除(见 `server/src/jobs/prune-logs.ts`)。 |
+| `SERVER_LOGS_MAX_ROWS` | `50000` | `server_logs` 表的硬上限。超限时下一次插入会删最旧的行。 |
+
+两者启动时读取;改它们要重启。
+
+---
+
+## 脱敏集成
+
+存储是 `lib/log-redaction.ts` **内部的一个抽头**,不是第二层 console 包装器。流向:
+
+1. 应用代码调用 `console.log` / `providerLog()` / 等。
+2. 脱敏包装器拦截,擦除机密(API 密钥、Bearer 令牌、URL 令牌等),把干净行发给**原始** stdout。
+3. 包装器**然后**调用 `recordConsoleLine()` / 存储收到已脱敏文本。
+4. `providerLog()`(用于结构化运维事件)在记录前自己脱敏消息,再镜像给包装过的 console——二次通过也是幂等的。
+
+结果:**机密永不进入环形缓冲区或数据库**,运维看到的仪表盘行跟终端里看到的完全一样。
+
+---
+
+## 客户端实现注记 (`client/src/pages/LogsPage.tsx`)
+
+- **轮询间隔:** 3 秒(`LOG_POLL_MS`),标签页后台时暂停(`refetchIntervalInBackground: false`)。
+- **过滤器变更**(级别复选框、提供方下拉、搜索框)重置流:缓冲清空、游标置空、新查询键 → 全新的最新 200 页。
+- **搜索防抖:** 300 ms(`SEARCH_DEBOUNCE_MS`)。
+- **跟随尾部:** 只有用户停在底部(40 px 内)时才自动滚动。向上滚动即分离;分离期间有新行到来会出现「跳到最新」药丸。
+- **条目缓冲:** 组件状态里封顶 500 条(`LOG_BUFFER_LIMIT`);新页到来时最旧逐出。
+- **可展开行:** 超过 300 字符的消息被钳制并带「展开/收起」切换。
+- **级别徽章:** 按严重度着色(error=红、warn=橙、info=蓝、debug=淡)并带来自 `counts` 载荷的实时计数。
+- **提供方下拉:** 从当前流里见过的条目的 `provider` 字段动态填充。
+- **清空按钮:** 确认动作,调 `POST /api/logs/clear`,然后失效查询缓存并重置本地状态。
+
+---
+
+## 导航
+
+日志页从 **分析** 导航菜单链接过来
+(`client/src/pages/AnalyticsPage.tsx` → 侧边栏)。它和分析图表并列,作为诊断伴侣:图表显示*发生了什么*(请求量、延迟、错误);日志显示*为什么*。
\ No newline at end of file
diff --git a/docs/i18n/zh-CN/docs/logs/CHANGELOG.md b/docs/i18n/zh-CN/docs/logs/CHANGELOG.md
new file mode 100644
index 00000000..1968de40
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/logs/CHANGELOG.md
@@ -0,0 +1,12 @@
+[English](../../../../logs/CHANGELOG.md) · **简体中文**
+
+# 变更日志
+
+`docs/logs/` 的文档修订历史。最近的在前。
+
+| 日期 | 提交 | 变更 |
+| --- | --- | --- |
+| 2026-08-23 | `74df985` | 仪表盘里的服务器日志查看器,位于分析导航菜单下 (#993) |
+| 2026-08-22 | `96b6f75` | docs(meta): 为 providers/testing 域建索引并记录今日新增 |
+
+> 实现提交:`74df985`(日志查看器功能),`96b6f75`(元索引)。
\ No newline at end of file
diff --git a/docs/i18n/zh-CN/docs/logs/OVERVIEW.md b/docs/i18n/zh-CN/docs/logs/OVERVIEW.md
new file mode 100644
index 00000000..f9d2ca91
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/logs/OVERVIEW.md
@@ -0,0 +1,18 @@
+[English](../../../../logs/OVERVIEW.md) · **简体中文**
+
+# 日志域
+
+## 范围
+
+本域记录仪表盘里的实时服务器日志查看器。涵盖双层存储架构(内存环形缓冲区 + 持久化 warn/error 条目)、基于游标分页和过滤的轮询 API 契约、级别计数和清空端点、环境变量配置、以及与现有日志脱敏管线的集成。
+
+## 文件索引
+
+| 文件 | 说明 |
+| --- | --- |
+| [01-server-logs-viewer.md](01-server-logs-viewer.md) | 服务器日志查看器完整参考:双层存储、`/api/logs` 轮询 API、级别计数、清空端点、环境变量、脱敏集成。 |
+
+## 相关
+
+- [../api/](../api/) —— 推理端点的 API 参考(日志查看器是 `/api/logs` 下的管理路由)。
+- [./](./) —— 简体中文镜像(本目录)。
\ No newline at end of file
diff --git a/docs/i18n/zh-CN/docs/providers/01-supported-platforms.md b/docs/i18n/zh-CN/docs/providers/01-supported-platforms.md
new file mode 100644
index 00000000..421b622e
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/providers/01-supported-platforms.md
@@ -0,0 +1,63 @@
+[English](../../../../providers/01-supported-platforms.md) · **简体中文**
+
+# 支持的平台
+
+[`shared/types.ts`(第 59 行)](../../../../../shared/types.ts) 中的 `Platform` 联合类型是平台身份的唯一事实来源;[`server/src/providers/index.ts`](../../../../../server/src/providers/index.ts) 中的运行时注册表必须与它保持一致。联合类型目前声明了 **41 个成员**:
+
+- **39 个内置平台**,启动时注册为适配器;
+- 加上 **`custom`** 占位(一个按 API 密钥逐个构建的真实 OpenAI 兼容适配器,因为它的 base URL 由用户提供),注册表共 **40 个条目**;
+- 再加 **`sambanova`**——保留在类型联合中但不再注册:它在 V23(2026 年 6 月)被移除,当时它的免费额度被永久收回(一次性 $5 试用额度用完后,每次聊天调用都返回 402「需要绑定支付方式」)。
+
+39 个内置平台中,**7 个使用专属原生适配器**,**32 个搭载 `OpenAICompatProvider`** 对着各自提供方专属的 base URL。三个平台以免密钥方式注册(`kilo`、`ovh`,以及 `aihorde`——它用文档记载的匿名哨兵密钥自动配置)。README 里的公开目录招牌数字约为 29 家免费提供方 / 251 个模型系列 / 358 个免费端点——比联合类型少,因为若干已注册的网关把免费名册放在托管目录里维护,而不是随每个二进制一起发布。
+
+## 目录
+
+| 平台 | 显示名称 | 鉴权 | 适配器 | 备注 |
+| --- | --- | --- | --- | --- |
+| `google` | Google Gemini | 带密钥 | 原生(`GoogleProvider`) | Gemini 线上格式;默认超时 60s,因为 Gemma 推理变体冷启动要花 20–60 秒。 |
+| `groq` | Groq | 带密钥 | OpenAI 兼容 | `api.groq.com/openai/v1` 的标准兼容端点。 |
+| `cerebras` | Cerebras | 带密钥 | OpenAI 兼容 | `api.cerebras.ai/v1`。 |
+| `bai` | B.AI | 带密钥 | OpenAI 兼容 | #918 加入的网关;目录里唯一的一行是限时 0 额度促销,保留在托管目录中。 |
+| `anyapi` | AnyAPI | 带密钥 | OpenAI 兼容 | 免费档 $0 / 无需信用卡 / 不循环扣费,上限为「免费和基础」模型每日 10 万词元;未公布 RPM/RPD(#772)。模型 id 经由目录同步送达,绝不盲目播种。 |
+| `nvidia` | NVIDIA NIM | 带密钥 | OpenAI 兼容 | `parallel_tool_calls` 固定为 false(#255);180s 超时兼任流式首字节宽限(#584)。 |
+| `mistral` | Mistral | 带密钥 | OpenAI 兼容 | `api.mistral.ai/v1`。 |
+| `sambanova` | SambaNova | 已退役(V23) | 未注册 | 免费额度永久消失;因历史密钥行而保留在类型联合中。 |
+| `openrouter` | OpenRouter | 带密钥 | OpenAI 兼容 | 发送 `HTTP-Referer`/`X-Title` 头;`:free` 模型后缀标记零成本路由。 |
+| `github` | GitHub Models | 带密钥 | OpenAI 兼容 | 路由到 `models.github.ai/inference`;目录使用 `<publisher>/<model>` 形式的 id。 |
+| `cohere` | Cohere | 带密钥 | 原生(`CohereProvider`) | 使用 Cohere 的 OpenAI 兼容端点。 |
+| `cloudflare` | Cloudflare Workers AI | 带密钥(`account_id:token`) | 原生(`CloudflareProvider`) | 复合凭据格式由适配器解析。 |
+| `zhipu` | Zhipu (Z.ai / bigmodel.cn) | 带密钥 | 原生(`ZhipuProvider`) | 控制台自动探测:国内密钥被拒后会改向全球 `api.z.ai` 主机重新探测;60s 超时覆盖 glm-4.7-flash 的隐藏推理。 |
+| `ollama` | Ollama Cloud | 带密钥 | OpenAI 兼容 | 为前沿推理模型设 120s 超时;推理内容放在 `message.reasoning` 里返回;目录过滤到确认免费的行。 |
+| `kilo` | Kilo Gateway | 免密钥 | OpenAI 兼容 | 匿名 `:free` 路由按 IP 限流每小时 200 次请求;提示词/输出会被记录用于训练;校验探测 `/api/gateway/models`(#181)。 |
+| `pollinations` | Pollinations | 带密钥 | 原生(`PollinationsProvider`) | 即使密钥已被撤销,`GET /v1/models` 也返回 200,因此校验改为探测需鉴权的 `/account/key`(#608)。 |
+| `llm7` | LLM7.io | 带密钥(基础模型可匿名) | OpenAI 兼容 | 免费档每小时 100 次请求。 |
+| `huggingface` | Hugging Face Router | 带密钥 | OpenAI 兼容 | `router.huggingface.co` 元路由器(V13 重新加入);免费档每月循环发放 $0.10 路由额度。 |
+| `opencode` | OpenCode Zen | 带密钥 | OpenAI 兼容 | 仅限试用的促销免费名册,经文档确认的 id 通过 `migrateModelsV18` 播种。 |
+| `ovh` | OVHcloud AI Endpoints | 免密钥 | OpenAI 兼容 | 匿名档:每 IP 每模型每分钟 2 次请求(实测更严);鉴权档要求绑定了支付方式的 Public Cloud 项目(`migrateModelsV26`)。 |
+| `agnes` | Agnes AI | 带密钥 | OpenAI 兼容 | 专有模型以 $0/词元促销提供;约 30 个并发请求后开始出现 429;为推理首字节设 60s 超时。 |
+| `reka` | Reka | 带密钥 | OpenAI 兼容 | 通过每月循环的额度赠金免费(无需信用卡);余额只在仪表盘可见。 |
+| `siliconflow` | SiliconFlow | 带密钥 | OpenAI 兼容 | 主要为 FREE 生成媒体模型而注册(FLUX.1-schnell 图像、CosyVoice2 TTS),经由 `services/media.ts` 路由。 |
+| `routeway` | Routeway | 带密钥 | OpenAI 兼容 | 要求浏览器风格的 User-Agent(Cloudflare 对其他值报错误 1010);实测免费池约 5 rpm,比文档写的 20 rpm / 200 rpd 更严。 |
+| `bazaarlink` | BazaarLink | 带密钥 | OpenAI 兼容 | 只有 `auto:free` 路由进了目录——直接指定模型 id 是付费的(#385)。 |
+| `ainative` | AINative Studio | 带密钥 | OpenAI 兼容 | 宣称每月循环约 1000 万词元的免费配额;在真实账号确认之前按未核实处理。 |
+| `aion` | Aion Labs | 带密钥 | OpenAI 兼容 | 无需信用卡的免费密钥;可用性在 30 天观察期之后交由目录管理。 |
+| `requesty` | Requesty | 带密钥 | OpenAI 兼容 | 路由端点位于 `router.requesty.ai/v1`;免费行随月度目录逐步纳入。 |
+| `navy` | NavyAI | 带密钥 | OpenAI 兼容 | 免费计划:每日 15 万词元、20 RPM;线上冒烟测试需要显式 User-Agent 头。 |
+| `nara` | NaraRouter | 带密钥 | OpenAI 兼容 | 免费计划额外要求 Telegram 频道/链接验证;2026 年 7 月 9 日做过线上探测。 |
+| `sealion` | SEA-LION (AI Singapore) | 带密钥 | OpenAI 兼容 | 第一方 API;Google 登录、无需信用卡、没有地区墙;免费档每月循环 10 RPM。 |
+| `orcarouter` | OrcaRouter | 带密钥 | OpenAI 兼容 | 循环 `$0` 免费别名,限额刻意不予公布(#896):429 是干净的额度信号,因为免费路由从不回退到付费模型。 |
+| `unorouter` | UnoRouter | 带密钥 | OpenAI 兼容 | 免费模型带 `:free` 后缀;每分钟限流(达上限即 429)。`GET /v1/models` 公开(无密钥也返回 200),但错误密钥会得到 401;默认密钥校验有效。目录行在托管目录中(目前是付费,30 天观察期后转免费)。 |
+| `xkiro` | xKiro | 带密钥 | OpenAI 兼容 | 免费计划:免费模型(Mistral、MiniMax、DeepSeek 系列)每日 500 万词元;付费模型返回 403。`GET /v1/models` 公开(无密钥返回 200),所以 `validateUrl` 指向 `/v1/usage`,缺失或无效密钥时返回 401。接受 Bearer 或 `x-api-key`。目录行在托管目录中(目前是付费,30 天观察期后转免费)。 |
+| `modelscope` | ModelScope (Alibaba) | 带密钥 | 原生(`ModelScopeProvider`) | 调用需要绑定完成实名的阿里云中国站账号;`GET /v1/models` 接受任意垃圾令牌,所以校验采用单词元聊天探测;退役模型以 429「余额不足」回应(#581)。 |
+| `qianfan` | Baidu Qianfan | 带密钥 | OpenAI 兼容 | ERNIE-Speed/Lite/Tiny 以按量计费封顶于限流规则的方式长期免费;需要中国实名认证(#936)。 |
+| `volcengine` | Volcengine Ark (ByteDance) | 带密钥 | OpenAI 兼容 | 个人开发者在一次性 50 万词元新用户赠金之外,还有每模型每日 200 万词元的循环奖励额度;需要实名认证(#936)。 |
+| `longcat` | LongCat (Meituan) | 带密钥 | OpenAI 兼容 | 每日免费额度;是中国提供方中的例外——中国大陆之外也能用邮箱注册。同时在 `/anthropic` 提供 Anthropic 线上格式(此处未使用)(#936)。 |
+| `xfyun` | iFlytek Spark | 带密钥 | OpenAI 兼容 | 鉴权是把控制台的 APIPassword 当作 Bearer 令牌使用;Lite 是文档记载的免费模型;未公布词元/QPS 上限(#936)。 |
+| `aihorde` | AI Horde | 免密钥(匿名哨兵 `0000000000`;注册密钥可提升队列优先级) | 原生(`AIHordeProvider`) | 社区志愿算力经队列代理接入:max_tokens >= 16、stop 必须是数组、不支持工具、用量以 kudos 计、120s 超时、无上游流式(#345)。 |
+| `custom` | 自定义(OpenAI 兼容) | 用户提供的 base URL 存于各 `api_keys` 行 | 经 `resolveProvider()` 按密钥构建的 OpenAI 兼容适配器 | 注册占位让 `getProvider('custom')`/`hasProvider('custom')` 行为良好;为缓慢的本地运行时(llama.cpp、vLLM、LM Studio)设 120s 超时(#145)。 |
+
+## 相关历史
+
+- Moonshot 直连集成与 MiniMax 直连在 `migrateModelsV4` 中移除(仅付费 / 被 OpenRouter 路线取代)。
+- Hugging Face 在 V4 中移除(「工具调用格式问题」),并在 V13 经 Inference Providers 元路由器重新加入。
+- Chutes 曾为 V11 评估过然后放弃:所有模型都返回 402 要求非零余额,与项目「无需信用卡」的标准冲突。
\ No newline at end of file
diff --git a/docs/i18n/zh-CN/docs/providers/02-quotas-and-cooldowns.md b/docs/i18n/zh-CN/docs/providers/02-quotas-and-cooldowns.md
new file mode 100644
index 00000000..47fd5da2
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/providers/02-quotas-and-cooldowns.md
@@ -0,0 +1,71 @@
+[English](../../../../providers/02-quotas-and-cooldowns.md) · **简体中文**
+
+# 额度、冷却与密钥健康
+
+免费额度以特定的、被计量的方式耗尽:每分钟和每日的请求上限、词元预算、并发限制,以及直接的额度枯竭。网关把这一切建模出来,让路由器不再把回退尝试浪费在明知已经花光的密钥上。相关机制位于 [`server/src/services/ratelimit.ts`](../../../../../server/src/services/ratelimit.ts)、[`server/src/services/provider-quota.ts`](../../../../../server/src/services/provider-quota.ts)、[`server/src/services/cooldown-probe.ts`](../../../../../server/src/services/cooldown-probe.ts)、[`server/src/services/health.ts`](../../../../../server/src/services/health.ts),以及 [`server/src/providers/base.ts`](../../../../../server/src/providers/base.ts) 中共享的退避解析器。
+
+## 限流窗口(RPM/RPD)
+
+每条目录模型行都带有 `rpm_limit` / `rpd_limit` 列。派发一次尝试之前,路由器检查以 `platform:modelId:keyId:rpm`(分钟)或 `...:rpd`(天)为键的滑动窗口:
+
+- 只有当 `recorded + in-flight < limit` 时请求才被放行——把进行中的租约计入,堵住了 N 个并发请求都读到同一个未消耗计数器的竞态。
+- 窗口同时存在于内存和持久化存储中;数据库不可用时路由器回退为累加内存窗口键。
+
+## 词元预算(TPM/TPD)
+
+`tpm_limit` / `tpd_limit` 以估算词元按同样的方式工作:只有当 `used + in-flight tokens + estimate` 落在限额之内时,请求才计入其分钟/天词元窗口。由于有些提供方公布的 RPD 很宽裕而 TPM 却很小(代码里举了 groq 的 `gpt-oss-120b`:rpd 1000 但 tpm 8000),每日词元检查还会喂给一个推导出的上限,防止一次大爆发在几秒内烧光一整天的预算。
+
+## 平台级共享池
+
+按模型的窗口看不见账号层面的天花板:OpenRouter 把 `:free` 路由计量成一个池,Google 按项目计量,NVIDIA NIM 计量一个额度池(所有模型合计约每分钟 40 次请求,无视各模型行)。UnoRouter 的 `:free` 模型共享一个按分钟的账号级上限(一波并行请求会触发几分钟内所有 `:free` 模型的 429)。xKiro 的免费计划在所有免费模型(Mistral、MiniMax、DeepSeek 系列)间强制执行一个每日 500 万词元的账号级预算。`inferPoolForPlatform` 把平台映射到共享池(`openrouter::free`、`google::project`、`groq::account`、`nvidia::credit-pool`、`unorouter::free`、`xkiro::free` 等),每个池有自己的聚合闸门,`(models × rpd)` 式的扇出再也换不来意外 429。
+
+## 并发租约
+
+- **租约**让进行中的请求可见:每次派发的尝试都会获取一个租约,并在尝试落定后释放(释放是幂等的;泄漏的租约按年龄清理)。没有租约的话,计数器要等到 await 的提供方调用「之后」才写入,并行的流会径直越过限制、收获真实的 429。
+- **可选的并发上限**:多数免费额度计量的是每分钟请求数而不是并行度,默认设上限只会白白串行化各个提供方。`MAX_CONCURRENT_REQUESTS_PER_KEY_<PLATFORM>`(按平台)或 `MAX_CONCURRENT_REQUESTS_PER_KEY`(兜底)可启用一个对照实时租约数检查的按密钥上限。刻意不提供内置的按平台表:行为如此的提供方,文档精确得足以给出断言数字的还没有。
+
+## 冷却
+
+一次 429 会让那个「模型+密钥」组合停用一段时间:
+
+| 机制 | 时长 | 备注 |
+| --- | --- | --- |
+| 瞬时冷却 | 90s | 分钟窗口内的 429;约一个窗口之内即可恢复。 |
+| 升级阶梯 | 2min → 10min → 1h → 1 天 | 命中在一个滚动的 24 小时窗口上累计;真正耗尽的每日额度会把密钥隔离到当天结束,而不是反复走短冷却。一次成功的请求会清零命中计数。 |
+| 未知限额的天花板 | 上限 10min | 当耗尽是猜测而非实测时,停用时长要有封顶,因为这个结论只是猜的。 |
+| 需要付款(402) | 1 天 | 额度用光。 |
+| 模型被禁(403 档位门槛) | 1 天 | 密钥有效,模型被划到更高档位。 |
+| 本地端点错误 | 5s | 绝不进入阶梯。 |
+| 鉴权失败(401) | 停用到下一轮健康周期 | 约 5 分钟。 |
+
+### 来源与基于探测的提前恢复
+
+冷却会记录它存在的原因(`heuristic`、`authoritative`、`credit`、`tier`)。只有 `heuristic` 类的停用属于猜测、常常比故障本身活得更久;提供方明说的事实(显式的 Retry-After 到期时间、每日额度的重置)以及 credit/tier 类停用绝不会被探测,因为一次通过的密钥校验对它们证明不了任何事。
+
+冷却探测任务每 60 秒扫描一轮,重新校验探测时机成熟的密钥,提前解除启发式冷却:
+
+- 只有过半停用期已过、且剩余超过 60s 才算成熟(探测一个快到期的停用纯属浪费一次校验调用);
+- 失败的探测绝不延长停用——它把下一次探测排得更远(2min 翻倍,封顶 15min);
+- 探测对健康账本无副作用,重启后错开执行,并且每轮有预算(`COOLDOWN_PROBE_MAX_PER_PASS`,默认 3);`COOLDOWN_PROBE_DISABLED=1` 可杀死该任务;
+- 探测的单位是「密钥」而非模型:一次 `validateKey` 的结果就是这把密钥持有的每一个启发式冷却的证据。
+
+## 来自响应头与错误正文的退避(#798)
+
+在 #798 之前,明确说了何时可以回来的提供方,得到的却和什么都没说的提供方同一套启发式阶梯,因为错误正文在到达路由器之前就被压扁成一条消息字符串。如今每个适配器都经 `providerHttpError` 构造错误,它会捕获:
+
+1. **`Retry-After` 响应头** —— delta-seconds 或 HTTP-date,只解析一次(共享解析器在 `providers/base.ts`),且两种来源同时存在时仍是胜出通道。
+2. **错误正文里写明的延迟**:
+ - 结构化字段:Gemini 以 429 应答时带 `error.details[]`,其中 `google.rpc.RetryInfo` 的 `retryDelay` 读作 `"17s"`;正文会被深度封顶地遍历(最大深度 6),寻找 `retryDelay` / `retry_after` / `retryAfterSeconds` 形状——跨提供方比死路径更耐用;
+ - 自然语言:锚定的短语如 "try again in 30 seconds" 或 "retry after 2m" ——之所以锚定,是为了让错误消息里无关的数字永远不可能被误认成退避时间。
+3. 所有解析出的延迟都被钳制在 24h 内,畸形或恶意的提示不可能永久停用一个密钥。
+
+只保留数字——正文从不保留——因此没有任何多余的东西进入日志或尝试轨迹。测试:[`server/src/__tests__/providers/stated-retry.test.ts`](../../../../../server/src/__tests__/providers/stated-retry.test.ts)。
+
+## 健康检查不得燃烧计量额度(#882)
+
+健康检查每 5 分钟跑一轮计划任务(±20% 抖动,3.5 分钟内校验过的密钥跳过,默认并发 8,同提供方探测之间间隔 ≥1s)。这个节奏对免费的校验端点没问题,在校验本身就耗费额度的地方却是毒药:
+
+- ModelScope 用一次消耗额度的单词元聊天补全校验密钥(`GET /v1/models` 不做鉴权),花费魔粒额度——按默认节奏约合每密钥每天 288 次付费探测。修复(#882):不带 `ms-` 前缀的令牌在本地直接拒绝、零网络调用,校验成功后按密钥缓存 `MODELSCOPE_VALIDATE_CACHE_MS`(默认 24 小时)。
+- Pollinations 的公开 `/v1/models` 对已撤销的密钥也返回 200,所以校验指向需鉴权的 `/account/key`;AI Horde 则把任何可达的端点视为健康,而不去占用队列名额。
+
+给贡献者的规则:**如果 `validateKey` 会消耗计量额度,就需要缓存或一条免费的探测路径** ——见 [03-adding-a-new-provider.md](03-adding-a-new-provider.md)。
\ No newline at end of file
diff --git a/docs/i18n/zh-CN/docs/providers/03-adding-a-new-provider.md b/docs/i18n/zh-CN/docs/providers/03-adding-a-new-provider.md
new file mode 100644
index 00000000..d249b014
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/providers/03-adding-a-new-provider.md
@@ -0,0 +1,73 @@
+[English](../../../../providers/03-adding-a-new-provider.md) · **简体中文**
+
+# 添加新提供方
+
+一篇贡献者走查,与现有 37 个内置平台的接入方式如出一辙。阅读时请把 [`server/src/providers/index.ts`](../../../../../server/src/providers/index.ts) 放在手边——它既是注册表,也是各平台取舍判断的最好文档。
+
+## 1. 声明平台
+
+在 [`shared/types.ts`](../../../../../shared/types.ts)(第 59 行)的 `Platform` 联合中加入 id,并附注释写明你能够辩护的免费额度事实:什么免费、循环发放还是促销、要不要信用卡、有没有注册墙。联合必须与 [`server/src/routes/keys.ts`](../../../../../server/src/routes/keys.ts) 的 `PLATFORMS` 白名单保持同步——那个 zod 枚举决定用户可以为哪些平台登记密钥。
+
+## 2. 选择适配器
+
+- **OpenAI 兼容端点** → 无需新类。带着平台 base URL 注册 `OpenAICompatProvider`,groq、cerebras、openrouter 以及另外约 27 家都是这么做的。
+- **线上格式有分歧** → 在独立文件里子类化 `BaseProvider` 并注册。现有先例:
+ - `GoogleProvider` —— 原生 Gemini 线上格式;
+ - `CohereProvider` / `CloudflareProvider` / `ZhipuProvider` —— 兼容聊天路由外加密钥形状或控制台探测行为;
+ - `PollinationsProvider` / `ModelScopeProvider` —— 因为它们的公开模型列表端点对坏密钥也返回 200,校验需要另一种探测;
+ - `AIHordeProvider` —— 基于队列的代理,偏离 OpenAI 契约(`max_tokens >= 16`、仅数组的 `stop`、kudos 用量、无工具)。
+
+每个适配器白得的功能:超时/停滞接线(`fetchWithTimeout`,首字节预算 #584)、带截断检测的 SSE 读取、`<think>` 提取,以及经 `providerHttpError` 的错误构造。
+
+## 3. 用正确的选项注册
+
+在 `index.ts` 里:
+
+```ts
+register(new OpenAICompatProvider({
+ platform: 'yourplatform',
+ name: 'Your Platform',
+ baseUrl: 'https://api.example.com/v1',
+}));
+```
+
+值得考虑的选项,每一个都有真实的注册在用:
+
+| 选项 | 何时使用 | 示例 |
+| --- | --- | --- |
+| `timeoutMs` | 冷启动或隐藏推理超过默认的 15s;按调用覆盖仍然优先。 | google 60s, nvidia 180s, ollama/custom 120s |
+| `keyless: true` | 免费档可以匿名使用。提供方省略 Authorization;密钥页会存一行哨兵记录,让路由把该平台视为已配置。 | kilo, ovh |
+| `extraHeaders` | 提供方要求特定请求头。 | openrouter referer/title; routeway/navy browser-style User-Agent behind Cloudflare |
+| `forceSingleToolCall` | 上游拒绝并行工具调用。 | nvidia (#255) |
+| `validateUrl` | 密钥校验应探测 `/v1/models` 之外的另一个 URL。 | kilo probes `/api/gateway/models` |
+
+可调的超时会经由 `PROVIDER_TIMEOUT_<PLATFORM>` 自动生效(#547)。
+
+## 4. 把密钥校验做对
+
+`validateKey` 返回布尔值或 `{ valid: false, error }`。用继承来的 `validationResult(res)` 助手把 401/403 变成携带上游原因的诊断性失败。两条从生产中学到的铁律:
+
+1. **绝不要把公开的模型列表端点当成密钥有效的证据**(pollinations #608、modelscope):如果 `GET /v1/models` 未鉴权也返回 200,就改为探测某个需要鉴权的东西。
+2. **如果校验消耗计量额度,就缓存它或找一条免费探测** ——见 [#882](02-quotas-and-cooldowns.md#健康检查不得燃烧计量额度882)。健康检查每约 5 分钟对每条已存密钥跑一轮。
+
+## 5. 有意识地播种目录
+
+模型行来自两个地方,选错了会把付费模型泄漏给免费用户:
+
+- **版本化迁移**(`migrateModelsV<N>`)用于随二进制发布的、经文档确认的免费名册(opencode V18、ovh V26)。
+- **托管目录**,经 `services/catalog-sync.ts`(以 `hasProvider` 为门槛),当可用性应当集中管理时——如今通常是 Premium 先行,30 天观察期后转免费。绝不未经线上验证就从第三方列表播种:一个坏模型 id 宁可被健康检查抓住,也不作为默认值发布出去。
+
+平台未公布限额时填 `null` 而不是猜;未知限额的冷却路径之所以把停用封顶在 10 分钟,正是因为猜测不等于测量。
+
+## 6. 测试
+
+在 [`server/src/__tests__/providers/`](../../../../../server/src/__tests__/providers/) 下按照既有模式补测试(一批 OpenAI 兼容注册参见 `cn-providers.test.ts`):断言出站请求的形状(URL、鉴权头的位置、请求头)、响应归一化,以及你引入的任何怪癖处理。在仓库根目录用 `npm test` 跑完整链路——见 [docs/testing](../testing/OVERVIEW.md)。
+
+## 清单
+
+- [ ] `Platform` 联合与 `routes/keys.ts` 的 `PLATFORMS` 白名单一起更新
+- [ ] 在 `providers/index.ts` 中注册,超时/请求头/免密钥的选择经得起推敲
+- [ ] `validateKey` 对真实 401/403 正文和公开端点陷阱验证过
+- [ ] 免费额度的说法经过线上核实(注释里写日期和观测,与 `index.ts` 其余部分一致)
+- [ ] 明确做出目录播种决策(迁移 vs 托管目录 vs 不播种)
+- [ ] 补了提供方测试;根目录 `npm test` 通过
diff --git a/docs/i18n/zh-CN/docs/providers/CHANGELOG.md b/docs/i18n/zh-CN/docs/providers/CHANGELOG.md
new file mode 100644
index 00000000..f9011b26
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/providers/CHANGELOG.md
@@ -0,0 +1,18 @@
+# 变更记录
+
+`docs/providers/` 的修订历史,列出塑造了本文档所述提供方层的上游提交。最新在前。
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `df1000a` | 2026-08-20 | Qianfan/Volcengine Ark/LongCat/iFlytek Spark (#936) — four Chinese domestic OpenAI-compat platforms. |
+| `00268be` | 2026-08-18 | B.AI gateway (#918). |
+| `fba4b3d` | 2026-08-15 | OrcaRouter (#896). |
+| `5999d48` | 2026-08-11 | AnyAPI (#772). |
+| `6f13332` | 2026-08-10 | honor back-off from error body (#798). |
+| `24b5f9c` | 2026-06-26 | Routeway/BazaarLink/AINative (#385). |
+| `cba6ac8` | 2026-06-03 | keyless Kilo + Gemma 4 (#181). |
+| `6305924` | 2026-06-02 | OpenCode Zen 4 free models. |
+| `a89cc64` | 2026-05-31 | generic custom OpenAI-compat provider (#145). |
+| `694d75c` | 2026-04-26 | error handler crash + missing platforms + per-provider timeout (#7). |
+
+Regenerate with `git log --oneline -- server/src/providers`.
diff --git a/docs/i18n/zh-CN/docs/providers/OVERVIEW.md b/docs/i18n/zh-CN/docs/providers/OVERVIEW.md
new file mode 100644
index 00000000..3870cf6c
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/providers/OVERVIEW.md
@@ -0,0 +1,23 @@
+[English](../../../../providers/OVERVIEW.md) · **简体中文**
+
+# 提供方集成总览
+
+## 范围
+
+本域文档描述 FreeLLMAPI 的提供方层:网关聚合了哪些平台、每个平台如何鉴权和适配,以及按密钥的额度记账、冷却和健康检查如何让各家免费额度在同一个 OpenAI 兼容 API 之下保持可用。
+
+权威来源是 [`shared/types.ts`](../../../../../shared/types.ts)(`Platform` 联合类型)、[`server/src/providers/index.ts`](../../../../../server/src/providers/index.ts)(运行时注册表)和 [`server/src/providers/base.ts`](../../../../../server/src/providers/base.ts)(适配器契约)。公开目录的招牌数字——约 29 家免费提供方、251 个模型系列、358 个免费端点(约合每月 40 亿词元的在册容量)——来自 [README 的提供方表格](../../README.md);目录实际跟踪的平台比类型联合声明的要少,因为联合中的部分成员已退役,或者由用户自定义而非由目录管理。
+
+## 文件索引
+
+| 文件 | 说明 |
+| --- | --- |
+| [01-supported-platforms.md](01-supported-platforms.md) | `shared/types.ts` 中声明的每个平台一行:鉴权方式(带密钥/免密钥)、适配器类(原生/OpenAI 兼容)以及集成注意事项。每种分组都有明确的数量。 |
+| [02-quotas-and-cooldowns.md](02-quotas-and-cooldowns.md) | RPM/RPD 与 TPM/TPD 窗口记账、并发租约与可选上限、冷却阶梯及其来源分类、基于探测的提前恢复、从 `Retry-After` 响应头和错误正文解析退避时间(#798),以及为什么健康检查绝不能烧掉计量额度(#882)。 |
+| [03-adding-a-new-provider.md](03-adding-a-new-provider.md) | 贡献者走查:扩展 `Platform` 联合、选择适配器、注册选项(超时、免密钥、额外请求头)、密钥校验语义、目录播种策略,以及新提供方应当随附的测试。 |
+
+## 约定
+
+- 适配器位于 [`server/src/providers/`](../../../../../server/src/providers/);在那里注册的每个平台立即出现在 `/v1` 路由上——没有单独的启用步骤。
+- 模型行有两种播种途径:发布期名册用版本化迁移,此后的目录托管内容一律走经过签名的托管目录(`services/catalog-sync.ts`,以 `hasProvider` 为门槛)。
+- 额度上限是数据而非代码:每条目录模型行上的 `rpm_limit` / `rpd_limit` / `tpm_limit` / `tpd_limit` 列驱动预限流;见 [02-quotas-and-cooldowns.md](02-quotas-and-cooldowns.md)。
diff --git a/docs/i18n/zh-CN/docs/testing/01-running-tests.md b/docs/i18n/zh-CN/docs/testing/01-running-tests.md
new file mode 100644
index 00000000..52c7f910
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/testing/01-running-tests.md
@@ -0,0 +1,59 @@
+[English](../../../../testing/01-running-tests.md) · **简体中文**
+
+# 运行测试
+
+## 根链
+
+仓库根目录的 `npm test` 按顺序运行([package.json](../../../../../package.json)):
+
+| 步骤 | 命令 | 覆盖内容 |
+| --- | --- | --- |
+| `test:bootstrap` | `node --test scripts/dev-bootstrap.test.mjs` | 开发引导脚本。 |
+| `test:hooks` | `node --test .claude/hooks/contributing-check.test.mjs` | 贡献者检查 hook 逻辑。 |
+| server | `npm run test -w server` | Vitest 套件(见 [02-server-suite.md](02-server-suite.md))。 |
+| cli | `npm run test -w cli` | Setup-CLI 测试(工具、配置文件合并、index)。 |
+| client | `npm run test -w client --if-present` | 客户端 vitest 套件加 i18n 一致性检查。 |
+
+desktop 工作区有自己的一小组套件(`desktop/src/__tests__/window-chrome.test.ts`),但不属于根链;它用自带工具经 `npm --prefix desktop` 运行。
+
+## 按工作区的命令
+
+### Server (`server/package.json`)
+
+```
+npm run test -w server # vitest run --pool=forks --fileParallelism=false
+npm run test:watch -w server # watch mode
+npm run test:migrations -w server # migration roundtrip only
+```
+
+`test:migrations` 只瞄准一个文件——[`src/__tests__/db/migrate/roundtrip.test.ts`](../../../../../server/src/__tests__/db/migrate/roundtrip.test.ts)——把每条已记录的迁移上滚再下滚,证明往返无损。动过 `src/db/migrate/` 下面的任何东西之后都要跑它。
+
+2026 年 8 月新增的测试文件,扩充了覆盖率:
+- `src/__tests__/routes/logs.test.ts` —— 服务器日志查看器的持久化与 API
+- `src/__tests__/routes/custom-transcription.test.ts` —— 自定义 STT 模型注册与转写用法
+- `src/__tests__/lib/provider-identity.test.ts` —— 自定义端点身份分类(#889)
+
+### Client (`client/package.json`)
+
+```
+npm run test -w client # vitest run && npm run check:i18n
+npm run check:i18n -w client # scripts/check-i18n.mjs
+```
+
+`check:i18n` 校验每个语言文件的键/占位符一致性;缺失或占位符损坏的翻译会让套件失败,而不只是构建失败。
+
+### 其余部分
+
+`npm run build` 也必须通过——CI 在测试之后构建所有工作区,所以类型错误即使躲过单元测试也会在那里浮出。
+
+## CI 摘要
+
+[`.github/workflows/ci.yml`](../../../../../.github/workflows/ci.yml) 运行在 `ubuntu-24.04` 上,针对 `main` 的推送和 PR 触发,是一个横跨 Node **20 和 22** 矩阵的单一 `test` 任务——正好是受支持引擎区间(`>=20.18 <25`)的两端。Node 20 是基线,历史上曾抓住被较新的本地 Node 掩盖的崩溃;22 是多数贡献者在用的 LTS。步骤按顺序:
+
+1. checkout + setup-node(带 npm 缓存)
+2. `npm install`
+3. **检查迁移往返**:`npm run test:migrations`(在主套件之前,让 schema 漂移尽早失败)
+4. `npm test`(上面的根链)
+5. `npm run build`
+
+`fail-fast: false` 保证一个 Node 版本的失败不会掩盖另一个的结果。
diff --git a/docs/i18n/zh-CN/docs/testing/02-server-suite.md b/docs/i18n/zh-CN/docs/testing/02-server-suite.md
new file mode 100644
index 00000000..4114f169
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/testing/02-server-suite.md
@@ -0,0 +1,51 @@
+[English](../../../../testing/02-server-suite.md) · **简体中文**
+
+# 服务器套件
+
+## 布局
+
+所有服务器测试位于 [`server/src/__tests__/`](../../../../../server/src/__tests__) 下,与 `src/` 镜像:
+
+| 目录 | 内容 |
+| --- | --- |
+| `db/` | 数据库初始化/加密/加固、智能档位、node-sqlite 行为,以及 `db/migrate/`——迁移运行器测试、注册表漂移、端点身份,还有 `test:migrations` 单独运行的 `roundtrip.test.ts`。 |
+| `lib/` | 纯模块单元:错误分类、加密、预算、Gemini 线上格式/schema、回退循环(含客户端中止、hedge、租约、模型停用变体)、env 漂移、模块纯度(见下文)。 |
+| `providers/` | 按适配器的测试:google(参数/鉴权头/schema)、openai-compat、cohere、cloudflare、zhipu、aihorde、modelscope、pollinations、cn-providers 批量测试,外加横切行为——abort 信号、推理超时、流式首字节、声明式重试解析(#798)、max-token 上限。 |
+| `routes/` | HTTP 面测试:代理/重试/回退、anthropic messages 垫片、gemini `/v1beta`、ollama 模拟、url-tokens、auth、分析、自定义提供方/端点、压缩/CSP 安全头。 |
+| `services/` | 路由器/评分/fusion、健康检查(调度、节奏、错误/日志/传输)、冷却探测、目录同步(调度器/来源)、密钥并发、限额学习、降级、嵌入/媒体/转写。 |
+| `integration/` | `full-flow.test.ts` ——穿过组装完成的应用的请求生命周期。 |
+| `helpers/` | 共享测试工具(`auth.ts`、`acl.ts`)。 |
+| `fixtures/` | 黄金文件(如 `compression-golden.json`)。 |
+
+## 串行 fork 执行
+
+`npm run test -w server` 以 `vitest run --pool=forks --fileParallelism=false` 运行。两个刻意的选择:
+
+- **`--pool=forks`** 把每个测试文件隔离在全新进程里。套件操纵真实状态——better-sqlite3 数据库、`process.env`、模块级缓存(冷却映射、健康调度器)——这些绝不能在文件之间泄漏。
+- **`--fileParallelism=false`** 让文件串行执行,共享资源(端口、临时数据目录)就不会在并发执行的文件之间相撞。
+
+代价是挂钟时间;回报是约 2300 个测试的套件是确定性的。client 工作区不需要这些:它的[独立 vitest 配置](../../../../../client/vitest.config.ts)主要是为了避免加载 React/Tailwind 的 vite 插件,其测试就是默认 node 环境里的普通 TypeScript。
+
+## 纯库导入守卫(#858)
+
+[`src/__tests__/lib/module-purity.test.ts`](../../../../../server/src/__tests__/lib/module-purity.test.ts) 强制一条架构不变量:在 [`server/src/lib/`](../../../../../server/src/lib/) 中被声明为纯的模块(只对其参数做函数运算——无 I/O、无数据库、无配置)必须保持没有**值**导入。`import type` 依然合法,因为类型导入会在制造循环之前就被擦除。
+
+它存在的理由:像 `error-classify.ts` 这样的纯叶子模块之所以同时被代理聊天路径、responses 路径和 fusion 面板导入,正是因为它们不依赖任何东西。加一句 `import { getDb }` 能干净地编译、通过每一个行为测试,然后悄悄把一片叶子变成一个枢纽——日后以导入循环(fusion↔proxy 案例)或某个突然需要数据库的单元测试的形式浮出水面。守卫还能识别动态导入、再导出和 `require()`。
+
+这份清单自我维护:任何新加入的无导入库模块都会让套件失败,直到它被归类为受守卫或有意不管——这个决策必须在 diff 里大声说出来,而不是靠沉默带过。
+
+## 环回绑定约定(#888)
+
+每个 route/integration 测试都这样启动服务器:
+
+```ts
+const server = app.listen(0, '127.0.0.1');
+if (!server.listening) await new Promise<void>(r => server.once('listening', () => r()));
+```
+
+两个细节,都是承重的(#888):
+
+1. **显式绑定到 `127.0.0.1`。** 较老的 `app.listen(0)` 绑定的是 IPv6 通配地址 `::`,而测试却经 IPv4 请求 `http://127.0.0.1:PORT`。地址不一致意味着:某个持有同 ephemeral 端口 IPv4 监听的无关本地进程会赢得连接而不触发 `EADDRINUSE`——请求被那个进程应答了(观测到 `wrangler dev` 的 workerd 进程回复 404/501),造成随机的断言失败、JSON 解析损坏,以及大约每二到四次运行出现一次的 5 秒超时。
+2. **读到 `listening` 事件之后再读 `address()`。** `listen(port, host)` 是异步解析主机名的(不同于 `listen(port)`),所以 `server.address().port` 只在该事件触发之后才可靠。
+
+修复经过验证:在冲突进程仍在运行的那台机器上,连续十次完整套件运行全部干净通过。
diff --git a/docs/i18n/zh-CN/docs/testing/03-compatibility-suite.md b/docs/i18n/zh-CN/docs/testing/03-compatibility-suite.md
new file mode 100644
index 00000000..97efa880
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/testing/03-compatibility-suite.md
@@ -0,0 +1,37 @@
+[English](../../../../testing/03-compatibility-suite.md) · **简体中文**
+
+# 兼容性套件
+
+## 它是什么
+
+编程智能体兼容性套件(提交 `19168ac`,#629,2026-07-27)证明的是真实的 AI 编程智能体能对着 FreeLLMAPI 的各个端面工作——而不仅仅是端点存在。它覆盖智能体触及的三层集成:它调用的线上 API、被指过去的配置文件,以及网关对其流量施加的客户端分类。
+
+## 覆盖什么、位于哪里
+
+### 原生 Gemini `/v1beta` 端面
+
+[`server/src/__tests__/routes/gemini.test.ts`](../../../../../server/src/__tests__/routes/gemini.test.ts) 经 HTTP 驱动组装完成的 Express 应用:
+
+- 模型发现、`generateContent`(JSON 与 SSE 流式)、`countTokens`;
+- Gemini 的 schema 方言与上游提供方之间的工具/思考/结构化输出翻译;
+- 面向 Gemini CLI 的系列映射与正确默认值(输出上限、动态思考、省略 `tool_choice`)。
+
+### Ollama 模拟(需主动开启)
+
+[`server/src/__tests__/routes/ollama.test.ts`](../../../../../server/src/__tests__/routes/ollama.test.ts) 覆盖 NDJSON 的 `chat`/`generate`、`tags`/`show`/`version`、嵌入,以及模式矩阵(off / open loopback / key-required 加按 IP 限流),还有协议保真细节:generate 帧、旧版 embeddings 正文、load 探测、`done_reason` 词汇表。
+
+### Setup CLI
+
+`cli/` 工作区(同一提交加入,由根链测试)为 Claude Code、Codex CLI、Cline、Continue、OpenCode、Goose、Qwen Code、Roo/Kilo/Crush 和 Cursor 生成各自的配置——13 个数据驱动的生成器,带保留注释的结构化合并(TOML 能在已有 MCP 表之下存活)、备份、dry run、凭据安全的启动器,以及 Claude Code 发现别名。测试:`cli/src/tools.test.ts`、`cli/src/config-files.test.ts`(含快照)、`cli/src/index.test.ts`。
+
+### 客户端分类与 URL 令牌
+
+客户端分类器测试(`server/src/__tests__/lib/client-context.test.ts` 及同侪)钉住喂给仪表盘「智能体」页和按智能体分析的识别逻辑;[`routes/url-tokens.test.ts`](../../../../../server/src/__tests__/routes/url-tokens.test.ts) 覆盖供无请求头客户端使用的、可单独撤销的 URL 令牌,校验过程防时序攻击。
+
+## 它证明了什么
+
+1. **协议保真**:说原生 Gemini 或 Ollama 线上格式的智能体得到的是语义正确的回答——流式帧、工具调用翻译、词元计数——而不只是一个 200。
+2. **零配置接入**:setup CLI 写出的智能体配置文件即使已含有无关内容也依然正确(结构化合并而非覆盖),且绝不把凭据泄漏进生成的启动器。
+3. **加固的回归安全**:#629 审查加固中的修复(Gemini CLI 默认值、Ollama 协议边角、TOML 合并存活、防时序的令牌检查)都以测试的形式钉死。
+
+提交信息里注明:该套件曾在一个隔离部署上用真实提供方密钥对所有新端面做过线上验证——这些测试把那些观测编码下来,让保证在重构之后依然成立。
diff --git a/docs/i18n/zh-CN/docs/testing/CHANGELOG.md b/docs/i18n/zh-CN/docs/testing/CHANGELOG.md
new file mode 100644
index 00000000..8812e044
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/testing/CHANGELOG.md
@@ -0,0 +1,11 @@
+# 变更记录
+
+`docs/testing/` 的修订历史,列出塑造了本文档所述测试基础设施的上游提交。最新在前。
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `4a47b3a` | 2026-08-18 | pure lib import guard (#858). |
+| `37ce9ac` | 2026-08-14 | bind test servers to loopback (#888). |
+| `19168ac` | 2026-07-27 | coding-agent compatibility suite (#629). |
+
+Regenerate with `git log --oneline -- server/src/__tests__`.
diff --git a/docs/i18n/zh-CN/docs/testing/OVERVIEW.md b/docs/i18n/zh-CN/docs/testing/OVERVIEW.md
new file mode 100644
index 00000000..bb13970b
--- /dev/null
+++ b/docs/i18n/zh-CN/docs/testing/OVERVIEW.md
@@ -0,0 +1,23 @@
+[English](../../../../testing/OVERVIEW.md) · **简体中文**
+
+# 测试总览
+
+## 范围
+
+本域文档描述 FreeLLMAPI 如何被测试:跨 monorepo 各工作区的本地命令矩阵、服务器套件的布局与约定(串行 fork 执行、模块纯度守卫、环回绑定),以及 #629 引入的端到端编程智能体兼容性套件。
+
+来源:根目录 [`package.json`](../../../../../package.json) 的测试链、各工作区的 `package.json` 脚本([server](../../../../../server/package.json)、[client](../../../../../client/package.json))、[`.github/workflows/ci.yml`](../../../../../.github/workflows/ci.yml),以及 [`server/src/__tests__/`](../../../../../server/src/__tests__) 下的各个套件本身。
+
+## 文件索引
+
+| 文件 | 说明 |
+| --- | --- |
+| [01-running-tests.md](01-running-tests.md) | 完整的本地矩阵——根链执行顺序、按工作区的命令、迁移往返检查——以及 CI 在 ubuntu-24.04 上运行内容的摘要。 |
+| [02-server-suite.md](02-server-suite.md) | `src/__tests__/` 目录布局、vitest 为什么用 `--pool=forks --fileParallelism=false` 运行、纯库导入守卫(#858),以及绑定到环回的约定(#888)。 |
+| [03-compatibility-suite.md](03-compatibility-suite.md) | 来自 #629 的端到端编程智能体兼容性套件:覆盖什么、位于哪里、证明了什么。 |
+
+## 约定
+
+- 唯一入口:仓库根目录的 `npm test` 按顺序运行 bootstrap 和 hook 检查,然后是 server、cli、client 工作区。
+- 服务器测试是确定性且注意副作用的:不发起真实的提供方调用,服务器绑定 `127.0.0.1`,共享状态通过在 fork 池中串行运行文件来隔离。
+- CI 是同一个矩阵,跑在受支持 Node 区间的两端(20 和 22)——如果本地 `npm test && npm run build` 通过,CI 也应当同意。
diff --git a/docs/install/CHANGELOG.md b/docs/install/CHANGELOG.md
new file mode 100644
index 00000000..9f0b798b
--- /dev/null
+++ b/docs/install/CHANGELOG.md
@@ -0,0 +1,9 @@
+# Changelog
+
+Revision history for `docs/install/`, derived from git commits touching this directory. Most recent first.
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `099fcd5` | 2026-07-20 | Termux support, docs index, health-check error surfacing (#573) |
+
+Regenerate with `git log --oneline -- docs/install/`.
diff --git a/docs/install/OVERVIEW.md b/docs/install/OVERVIEW.md
new file mode 100644
index 00000000..1abcaa09
--- /dev/null
+++ b/docs/install/OVERVIEW.md
@@ -0,0 +1,13 @@
+# Install guides overview
+
+## Scope
+
+Platform-specific installation guides that do not fit the main [Install & deploy](../install.md) page. These cover running FreeLLMAPI on unusual platforms or form factors, with platform-specific requirements, steps, and troubleshooting.
+
+Start with [install.md](../install.md) for the standard paths: the one-liner Docker quick start, Docker Compose, local development, and the desktop app.
+
+## Guides
+
+| File | Description |
+| --- | --- |
+| [android-termux.md](android-termux.md) | Experimental Android installation under Termux: runs locally on the device using Node's built-in SQLite driver instead of `better-sqlite3` (no NDK toolchain). Covers requirements (Android 7+, Node 22.13+), install and LAN access, keeping the process awake with a wake lock, troubleshooting, and updating. |
diff --git a/docs/logs/01-server-logs-viewer.md b/docs/logs/01-server-logs-viewer.md
new file mode 100644
index 00000000..2f7213ca
--- /dev/null
+++ b/docs/logs/01-server-logs-viewer.md
@@ -0,0 +1,163 @@
+# Server Logs Viewer
+
+The dashboard includes a live **Server Logs** viewer (accessible from the
+Analytics nav menu) that surfaces the same diagnostic lines the server prints to
+stdout — routing decisions, provider health checks, key cooldowns, quota
+exhaustion, compression fidelity gates, and any `warn`/`error` level events —
+without requiring SSH or container log access.
+
+> **Implementation internals:** the ingest path, structured `providerLog` metadata, boot preload, the `server_logs` / `requests` / `request_attempts` schema, and the desktop file logger (`freeapi.log`) are covered in the [Observability deep-dive](../architecture/06-observability.md). This guide covers the operator-facing dashboard, polling API, and client implementation.
+
+---
+
+## Two-tier store
+
+The log store uses **one id space across two tiers**:
+
+| Tier | Capacity | Levels | Persistence | Purpose |
+| --- | --- | --- | --- | --- |
+| **Ring buffer** | 1,000 entries (newest) | `trace`, `debug`, `info`, `warn`, `error` | In-memory only | Live tail for the polling dashboard; survives filter changes, not restarts. |
+| **`server_logs` table** | Configurable (`SERVER_LOGS_MAX_ROWS`, default 50,000) | `warn`, `error` only | SQLite (survives restart) | Durable history for the warnings/errors that matter most. |
+
+- **Ids are assigned by the store**, not by SQLite. The counter is seeded from
+ `MAX(id)` at initialization so ids keep increasing across restarts. A
+ dashboard tab holding a `sinceId` cursor never sees it go backwards.
+- At startup the store **preloads up to 200 recent persisted rows** (newest
+ first) into the ring so the dashboard shows the warnings that preceded the
+ restart instead of an empty panel.
+- Capture happens **inside the redaction wrapper** (`lib/log-redaction.ts`).
+ There is exactly one console patch in the process; it redacts first, then
+ the store only ever sees the redacted form. Secrets never reach the ring or
+ the database.
+- Lines matching `GET|HEAD /api/(logs|ping)` are filtered out at ingest to
+ prevent a self-feeding buffer (the polling endpoint would otherwise be the
+ loudest thing in the log).
+
+---
+
+## API contract
+
+All endpoints are mounted under `/api/logs` behind the dashboard session gate
+(the unified `/v1` key opens the inference surface, **never** this one — these
+lines name providers, models, key ids, and failure reasons).
+
+### `GET /api/logs` — Polling endpoint
+
+Cursor-based pagination built for a dashboard that polls every few seconds.
+
+| Query param | Type | Description |
+| --- | --- | --- |
+| `sinceId` | `integer` (optional) | Return entries **newer** than this id. Omit for the newest `limit` entries (default 200). The cursor returned as `nextId` is the store's highest id, not the highest id returned — so a poll whose matches were all filtered still advances the cursor instead of re-scanning the same tail forever. |
+| `levels` | `csv` (optional) | Comma-separated level filter: `trace,debug,info,warn,error`. Unknown levels return `400`. |
+| `q` | `string` (optional) | Case-insensitive text search across `message`, `provider`, `source`, `event`. |
+| `provider` | `string` (optional) | Exact provider name filter (e.g., `openai`, `anthropic`). |
+| `limit` | `integer` (optional) | Clamped to `[1, 500]`, default `200`. |
+
+**Response:**
+
+```json
+{
+ "entries": [
+ {
+ "id": 12345,
+ "ts": "2026-08-23T14:32:11.123Z",
+ "level": "warn",
+ "source": "CooldownProbe",
+ "provider": "openai",
+ "model": "gpt-4o",
+ "event": "cooldown_triggered",
+ "requestId": "req_abc123",
+ "message": "[CooldownProbe] openai:gpt-4o key #3 entered 45s cooldown (rate limit)"
+ }
+ ],
+ "nextId": 12345,
+ "counts": { "debug": 12, "info": 145, "warn": 8, "error": 2 }
+}
+```
+
+- `trace` is folded into `debug` in the counts (the dashboard shows four badges).
+- The `entries` array is **oldest → newest** within the returned page.
+- An already-caught-up caller (`sinceId >= lastId`) gets `entries: []` for the
+ cost of one integer comparison.
+
+### `GET /api/logs/counts` — Level counts
+
+Returns the same `LogLevelCounts` object included in every poll response, so a
+page that only wants the badge numbers can fetch them once without the full
+entry payload.
+
+```json
+{ "debug": 12, "info": 145, "warn": 8, "error": 2 }
+```
+
+### `POST /api/logs/clear` — Clear both tiers
+
+Empties the ring buffer **and** truncates the `server_logs` table. The id
+counter is **not reset** — a dashboard tab holding a cursor would otherwise be
+handed ids it has already seen.
+
+```json
+{ "ok": true }
+```
+
+---
+
+## Environment variables
+
+| Variable | Default | Description |
+| --- | --- | --- |
+| `SERVER_LOGS_RETENTION_DAYS` | `7` | Rows older than this many days are deleted by a daily maintenance job (see `server/src/jobs/prune-logs.ts`). |
+| `SERVER_LOGS_MAX_ROWS` | `50000` | Hard cap on the `server_logs` table. When exceeded, oldest rows are deleted on the next insert. |
+
+Both are read at server boot; changing them requires a restart.
+
+---
+
+## Redaction integration
+
+The store is a **tap inside `lib/log-redaction.ts`**, not a second console
+wrapper. The flow:
+
+1. Application code calls `console.log` / `providerLog()` / etc.
+2. The redaction wrapper intercepts, scrubs secrets (API keys, Bearer tokens,
+ URL tokens, etc.), and emits the clean line to the **original** stdout.
+3. The wrapper **then** calls `recordConsoleLine()` / the store receives the
+ already-redacted text.
+4. `providerLog()` (used for structured operational events) redacts its own
+ message before recording, then mirrors to the wrapped console — idempotent
+ under a second pass.
+
+Result: **secrets never enter the ring buffer or the database**, and operators
+see exactly the same lines in the dashboard that they would see in the terminal.
+
+---
+
+## Client implementation notes (`client/src/pages/LogsPage.tsx`)
+
+- **Polling interval:** 3 seconds (`LOG_POLL_MS`), paused when the tab is
+ backgrounded (`refetchIntervalInBackground: false`).
+- **Filter changes** (level checkboxes, provider dropdown, search box) reset the
+ stream: buffer cleared, cursor nulled, new query key → fresh newest-200 page.
+- **Search debounce:** 300 ms (`SEARCH_DEBOUNCE_MS`).
+- **Tail-follow:** The view auto-scrolls only while the user is parked at the
+ bottom (within 40 px). Scrolling up detaches; a "Jump to latest" pill appears
+ when new lines arrive while detached.
+- **Entry buffer:** Capped at 500 entries (`LOG_BUFFER_LIMIT`) in component
+ state; oldest evicted as new pages arrive.
+- **Expandable rows:** Long messages (> 300 chars) are clamped with a
+ "Show more/less" toggle.
+- **Level badges:** Color-coded per severity (error=red, warn=amber, info=blue,
+ debug=muted) with live counts from the `counts` payload.
+- **Provider dropdown:** Populated dynamically from the `provider` field of
+ entries seen in the current stream.
+- **Clear button:** Confirmed action calling `POST /api/logs/clear`, then
+ invalidates the query cache and resets local state.
+
+---
+
+## Navigation
+
+The Logs page is linked from the **Analytics** nav menu
+(`client/src/pages/AnalyticsPage.tsx` → sidebar). It sits alongside the
+analytics charts as a diagnostic companion: the charts show *what* happened
+(request volumes, latencies, errors); the logs show *why*.
\ No newline at end of file
diff --git a/docs/logs/CHANGELOG.md b/docs/logs/CHANGELOG.md
new file mode 100644
index 00000000..2511d8cf
--- /dev/null
+++ b/docs/logs/CHANGELOG.md
@@ -0,0 +1,10 @@
+# Changelog
+
+Doc revision history for `docs/logs/`. Most recent first.
+
+| Date | Commit | Change |
+| --- | --- | --- |
+| 2026-08-23 | `74df985` | Server log viewer in the dashboard, under an Analytics nav menu (#993) |
+| 2026-08-22 | `96b6f75` | docs(meta): index providers/testing domains and log today's additions |
+
+> Implementation commits: `74df985` (log viewer feature), `96b6f75` (meta indexing).
\ No newline at end of file
diff --git a/docs/logs/OVERVIEW.md b/docs/logs/OVERVIEW.md
new file mode 100644
index 00000000..9d9714d5
--- /dev/null
+++ b/docs/logs/OVERVIEW.md
@@ -0,0 +1,24 @@
+# Logs Domain
+
+## Scope
+
+This domain documents the operator-facing server log viewer in the dashboard: the
+two-tier storage architecture (in-memory ring buffer + persisted warn/error
+entries), the polling API contract with cursor-based pagination and filtering,
+level counts and clear endpoints, configuration via environment variables,
+integration with the log redaction pipeline, and the React client implementation.
+
+For the implementation internals (ingest path, structured provider-log metadata,
+boot preload, the underlying database schema, and the desktop `freeapi.log` file
+logger), see the [Observability deep-dive](../architecture/06-observability.md).
+
+## File index
+
+| File | Description |
+| --- | --- |
+| [01-server-logs-viewer.md](01-server-logs-viewer.md) | Complete reference for the server logs viewer: two-tier store, `/api/logs` polling API, level counts, clear endpoint, environment variables, and redaction integration. |
+
+## Related
+
+- [../api/](../api/) — API reference for inference endpoints (the log viewer is an admin route under `/api/logs`).
+- [../i18n/zh-CN/docs/logs/](../i18n/zh-CN/docs/logs/) — Simplified Chinese mirror (when translated).
\ No newline at end of file
diff --git a/docs/providers/01-supported-platforms.md b/docs/providers/01-supported-platforms.md
new file mode 100644
index 00000000..2c31d133
--- /dev/null
+++ b/docs/providers/01-supported-platforms.md
@@ -0,0 +1,61 @@
+# Supported platforms
+
+The `Platform` union in [`shared/types.ts` (line 59)](../../shared/types.ts) is the single source of truth for platform identity; the runtime registry in [`server/src/providers/index.ts`](../../server/src/providers/index.ts) must match it. The union currently declares **41 members**:
+
+- **39 built-in platforms** registered as adapters at startup,
+- plus the **`custom`** placeholder (a real OpenAI-compatible adapter built per API key, since its base URL is user-supplied), giving **40 entries** in the registry map,
+- plus **`sambanova`**, retained in the type union but no longer registered — it was dropped in V23 (June 2026) when its free tier was permanently retired (every chat call returns 402 "payment method required" once the one-time $5 trial credit lapses).
+
+Of the 39 built-in platforms, **7 use dedicated native adapters** and **32 ride `OpenAICompatProvider`** against a provider-specific base URL. Three platforms are registered keyless (`kilo`, `ovh`, and `aihorde`, which auto-configures with its documented anonymous sentinel key). The public catalog headline in the README counts ~34 free providers / 474 model families / 635 free endpoints (~7.4 billion tokens/month of listed capacity) — fewer than the union because several registered gateways keep their free rosters in the hosted catalog rather than shipping them to every binary.
+
+## Catalog
+
+| Platform | Display name | Auth | Adapter | Notes |
+| --- | --- | --- | --- | --- |
+| `google` | Google Gemini | Keyed | Native (`GoogleProvider`) | Gemini wire format; 60s default timeout because Gemma reasoning variants take 20–60s on cold start. |
+| `groq` | Groq | Keyed | OpenAI-compat | Standard compatible endpoint at `api.groq.com/openai/v1`. |
+| `cerebras` | Cerebras | Keyed | OpenAI-compat | `api.cerebras.ai/v1`. |
+| `bai` | B.AI | Keyed | OpenAI-compat | Gateway added in #918; only catalog row is a limited-time 0-credit promo, kept in the hosted catalog. |
+| `anyapi` | AnyAPI | Keyed | OpenAI-compat | Free tier $0/no card/recurring, capped at 100K tokens/day over "free and basic" models; no RPM/RPD published (#772). Model ids arrive via catalog-sync, never seeded blind. |
+| `nvidia` | NVIDIA NIM | Keyed | OpenAI-compat | `parallel_tool_calls` pinned false (#255); 180s timeout doubles as streaming first-byte grace (#584). |
+| `mistral` | Mistral | Keyed | OpenAI-compat | `api.mistral.ai/v1`. |
+| `sambanova` | SambaNova | Retired (V23) | Not registered | Free tier permanently gone; kept in the type union for historical key rows. |
+| `openrouter` | OpenRouter | Keyed | OpenAI-compat | Sends `HTTP-Referer`/`X-Title` headers; `:free` model suffix marks zero-cost routes. |
+| `github` | GitHub Models | Keyed | OpenAI-compat | Routes to `models.github.ai/inference`; catalog uses `<publisher>/<model>` ids. |
+| `cohere` | Cohere | Keyed | Native (`CohereProvider`) | Uses Cohere's OpenAI-compatible endpoint. |
+| `cloudflare` | Cloudflare Workers AI | Keyed (`account_id:token`) | Native (`CloudflareProvider`) | Compound credential format parsed by the adapter. |
+| `zhipu` | Zhipu (Z.ai / bigmodel.cn) | Keyed | Native (`ZhipuProvider`) | Console autodetect: a rejected domestic key is re-probed against the global `api.z.ai` host; 60s timeout covers glm-4.7-flash hidden reasoning. |
+| `ollama` | Ollama Cloud | Keyed | OpenAI-compat | 120s timeout for frontier reasoning models; reasoning returned in `message.reasoning`; catalog filtered to confirmed-free rows. |
+| `kilo` | Kilo Gateway | Keyless | OpenAI-compat | Anonymous `:free` routes rate-limited 200 req/hr per IP; prompts/outputs logged for training; validation probes `/api/gateway/models` (#181). |
+| `pollinations` | Pollinations | Keyed | Native (`PollinationsProvider`) | `GET /v1/models` answers 200 even for revoked keys, so validation probes the authenticated `/account/key` instead (#608). |
+| `llm7` | LLM7.io | Keyed (anonymous works for basic models) | OpenAI-compat | 100 req/hr free tier. |
+| `huggingface` | Hugging Face Router | Keyed | OpenAI-compat | `router.huggingface.co` meta-router (re-added V13); recurring $0.10/mo router credit on the free tier. |
+| `opencode` | OpenCode Zen | Keyed | OpenAI-compat | Trial-only promotional free roster, docs-confirmed ids seeded via `migrateModelsV18`. |
+| `ovh` | OVHcloud AI Endpoints | Keyless | OpenAI-compat | Anonymous tier: 2 req/min per IP per model (observed stricter); authenticated tier requires a Public Cloud project with payment method on file (`migrateModelsV26`). |
+| `agnes` | Agnes AI | Keyed | OpenAI-compat | Proprietary models served at $0/token promotionally; ~30 concurrent requests before 429s; 60s timeout for reasoning TTFB. |
+| `reka` | Reka | Keyed | OpenAI-compat | Free via recurring monthly credit grant (no card); balance dashboard-only. |
+| `siliconflow` | SiliconFlow | Keyed | OpenAI-compat | Registered mainly for FREE generative-media models (FLUX.1-schnell image, CosyVoice2 TTS) routed via `services/media.ts`. |
+| `routeway` | Routeway | Keyed | OpenAI-compat | Requires browser-style User-Agent (Cloudflare rejects others with error 1010); free pool observed stricter (~5 rpm) than the documented 20 rpm / 200 rpd. |
+| `bazaarlink` | BazaarLink | Keyed | OpenAI-compat | Only the `auto:free` route is cataloged — direct model ids are paid (#385). |
+| `ainative` | AINative Studio | Keyed | OpenAI-compat | Advertises recurring ~10M tokens/month free allocation; quota treated as unverified until confirmed by a real account. |
+| `aion` | Aion Labs | Keyed | OpenAI-compat | No-card free key; availability catalog-managed behind the 30-day age gate. |
+| `requesty` | Requesty | Keyed | OpenAI-compat | Router endpoint at `router.requesty.ai/v1`; free rows age into the monthly catalog. |
+| `navy` | NavyAI | Keyed | OpenAI-compat | Free plan: 150K tokens/day and 20 RPM; live smoke tests require an explicit User-Agent header. |
+| `nara` | NaraRouter | Keyed | OpenAI-compat | Free plan additionally requires Telegram channel/link verification; live-probed 2026-07-09. |
+| `sealion` | SEA-LION (AI Singapore) | Keyed | OpenAI-compat | First-party API; Google sign-in, no card, no region wall; 10 RPM recurring free tier. |
+| `orcarouter` | OrcaRouter | Keyed | OpenAI-compat | Recurring `$0` free aliases with intentionally unpublished limits (#896): 429 is a clean quota signal because free routes never fall back to paid models. |
+| `unorouter` | UnoRouter | Keyed | OpenAI-compat | Free models carry `:free` suffix; per-minute rate limit (429 on cap). `GET /v1/models` public (200 no key) but 401 on wrong key; default key validation works. Catalog rows in hosted catalog (premium now, free after 30-day age gate). |
+| `xkiro` | xKiro | Keyed | OpenAI-compat | Free plan: 5M tokens/day on free models (Mistral, MiniMax, DeepSeek families); paid models 403. `GET /v1/models` public (200 no key), so `validateUrl` points to `/v1/usage` which 401s on missing/invalid key. Accepts Bearer or `x-api-key`. Catalog rows in hosted catalog (premium now, free after 30-day age gate). |
+| `modelscope` | ModelScope (Alibaba) | Keyed | Native (`ModelScopeProvider`) | Calls require binding to an Alibaba Cloud CHINA-site account with real-name verification; `GET /v1/models` accepts garbage tokens so validation uses a 1-token chat probe; retired models answer 429 "insufficient balance" (#581). |
+| `qianfan` | Baidu Qianfan | Keyed | OpenAI-compat | ERNIE-Speed/Lite/Tiny free indefinitely via pay-as-you-go billing bounded by rate limits; Chinese real-name auth required (#936). |
+| `volcengine` | Volcengine Ark (ByteDance) | Keyed | OpenAI-compat | Recurring daily per-model reward quota of 2M tokens/day/model for individual developers, on top of a one-time 500K new-user grant; real-name auth required (#936). |
+| `longcat` | LongCat (Meituan) | Keyed | OpenAI-compat | Daily free quota; exception among the Chinese providers — email signup works from outside mainland China. Also speaks Anthropic wire at `/anthropic` (unused here) (#936). |
+| `xfyun` | iFlytek Spark | Keyed | OpenAI-compat | Auth is the console APIPassword as a Bearer token; the Lite model is the documented free one; no published token/QPS ceiling (#936). |
+| `aihorde` | AI Horde | Keyless (anonymous sentinel `0000000000`; registered key raises queue priority) | Native (`AIHordeProvider`) | Community volunteer workers via queue-based proxy: max_tokens >= 16, stop must be array, no tools, usage reported as kudos, 120s timeout, no upstream streaming (#345). |
+| `custom` | Custom (OpenAI-compatible) | User-supplied base URL stored per `api_keys` row | OpenAI-compat built per key via `resolveProvider()` | Registered placeholder keeps `getProvider('custom')`/`hasProvider('custom')` well-behaved; 120s timeout for slow local runtimes (llama.cpp, vLLM, LM Studio) (#145). |
+
+## Related history
+
+- Moonshot direct integration and MiniMax direct were dropped in `migrateModelsV4` (paid-only / superseded by the OpenRouter route).
+- Hugging Face was dropped in V4 ("tool-call format issues") and re-added in V13 through the Inference Providers meta-router.
+- Chutes was evaluated for V11 and dropped: every model returned 402 requiring a non-zero balance, conflicting with the project's no-card criterion.
diff --git a/docs/providers/02-quotas-and-cooldowns.md b/docs/providers/02-quotas-and-cooldowns.md
new file mode 100644
index 00000000..45a1e153
--- /dev/null
+++ b/docs/providers/02-quotas-and-cooldowns.md
@@ -0,0 +1,69 @@
+# Quotas, cooldowns, and key health
+
+Free tiers fail in specific, metered ways: per-minute and per-day request caps, token budgets, concurrency limits, and outright quota exhaustion. The gateway models all of them so the router stops spending fallback attempts on keys it already knows are spent. The machinery lives in [`server/src/services/ratelimit.ts`](../../server/src/services/ratelimit.ts), [`server/src/services/provider-quota.ts`](../../server/src/services/provider-quota.ts), [`server/src/services/cooldown-probe.ts`](../../server/src/services/cooldown-probe.ts), [`server/src/services/health.ts`](../../server/src/services/health.ts), and the shared back-off parsers in [`server/src/providers/base.ts`](../../server/src/providers/base.ts).
+
+## Rate-limit windows (RPM/RPD)
+
+Every catalog model row carries `rpm_limit` / `rpd_limit` columns. Before dispatching an attempt, the router checks sliding windows keyed `platform:modelId:keyId:rpm` (minute) or `...:rpd` (day):
+
+- A request is admitted only when `recorded + in-flight < limit` — counting in-flight leases (below) closes the race where N concurrent requests all read the same counter as unspent.
+- Windows exist both in memory and persisted; on DB unavailability the router falls back to summing the in-memory window keys.
+
+## Token budgets (TPM/TPD)
+
+`tpm_limit` / `tpd_limit` work the same way with estimated tokens: a request counts against its minute/day token window only if `used + in-flight tokens + estimate` fits under the limit. Because some providers publish a generous RPD but a tiny TPM (the code cites groq `gpt-oss-120b`: rpd 1000 yet tpm 8000), the daily token check also feeds a derived cap so one large burst cannot exhaust a day's budget in seconds.
+
+## Platform-wide pools
+
+Per-model windows cannot see account-level ceilings: OpenRouter meters `:free` routes as one pool, Google meters per project, NVIDIA NIM meters a credit pool (~40 req/min across all models regardless of per-model rows). UnoRouter's `:free` models share a per-minute account-wide cap (a burst of parallel requests trips a 429 on every `:free` model for several minutes). xKiro's free plan enforces a 5M token/day account-wide budget across all free models (Mistral, MiniMax, DeepSeek families). `inferPoolForPlatform` maps platforms to shared pools (`openrouter::free`, `google::project`, `groq::account`, `nvidia::credit-pool`, `unorouter::free`, `xkiro::free`, ...) and each pool gets its own aggregate gate, so `(models × rpd)` fan-out earns surprise 429s no more.
+
+## Concurrency leases
+
+- **Leases** make in-flight requests visible: every dispatched attempt acquires a lease and releases it after the attempt settles (idempotent release; leaked leases are pruned by age). Without leases, counters are only written *after* the awaited provider call, so parallel streams would sail through the limit and collect real 429s.
+- **Opt-in concurrency caps**: most free tiers meter requests-per-minute, not parallelism, so capping by default would serialize providers for no benefit. `MAX_CONCURRENT_REQUESTS_PER_KEY_<PLATFORM>` (per platform) or `MAX_CONCURRENT_REQUESTS_PER_KEY` (fallback) enables a per-key cap checked against live lease counts. There is deliberately no built-in per-platform table: the providers that behave this way are not documented precisely enough to assert numbers for.
+
+## Cooldowns
+
+A 429 blocks that model+key pair for a period:
+
+| Mechanism | Duration | Notes |
+| --- | --- | --- |
+| Transient cooldown | 90s | Per-minute-window 429; recovers within ~one window. |
+| Escalation ladder | 2min → 10min → 1h → 1 day | Hits tracked over a rolling 24h window; a genuinely exhausted daily quota quarantines the key for the rest of the day instead of looping through short cooldowns. A successful request clears the hit counter. |
+| Unknown-limit ceiling | capped at 10min | When exhaustion is guessed rather than measured, the bench is capped since the verdict is a guess. |
+| Payment required (402) | 1 day | Out-of-credits. |
+| Model forbidden (403 tier gate) | 1 day | Key valid, model gated to a higher tier. |
+| Local endpoint errors | 5s | Never enters the ladder. |
+| Auth failure (401) | benched until the next health cycle | ~5 minutes. |
+
+### Provenance and probe-based early recovery
+
+Cooldowns record why they exist (`heuristic`, `authoritative`, `credit`, `tier`). Only `heuristic` benches are guesses that often outlive the outage; provider-stated facts (explicit Retry-After expiry, daily-quota reset) and credit/tier benches are never probed because a passing key-validation probe proves nothing about them.
+
+The cooldown-probe job scans every 60s and re-validates probe-ripe keys to clear heuristic cooldowns early:
+
+- ripe only after half the bench has elapsed, and only if >60s remains (probing a nearly-expired bench wastes a validate call);
+- a failed probe never extends the bench — it schedules the next probe further out (2min doubling, capped at 15min);
+- probes are side-effect-free for health bookkeeping, staggered after restart, and budgeted per pass (`COOLDOWN_PROBE_MAX_PER_PASS`, default 3); `COOLDOWN_PROBE_DISABLED=1` kills the job;
+- the probe unit is the KEY, not the model: one `validateKey` result is evidence for every heuristic cooldown that key holds.
+
+## Back-off from headers and error bodies (#798)
+
+Before #798, a provider that stated exactly when to come back got the same heuristic ladder as one that said nothing, because error bodies were flattened to a message string before reaching the router. Now every adapter builds errors via `providerHttpError`, which captures:
+
+1. **The `Retry-After` header** — delta-seconds or HTTP-date, parsed once (shared parser in `providers/base.ts`) and still the winning channel when both sources are present.
+2. **A delay stated inside the error body**:
+ - structured fields: Gemini answers 429 with `error.details[]` carrying `google.rpc.RetryInfo` whose `retryDelay` reads `"17s"`; the body is walked depth-capped (max depth 6) looking for `retryDelay` / `retry_after` / `retryAfterSeconds` shapes, which is more durable across providers than exact paths;
+ - prose: anchored phrases like "try again in 30 seconds" or "retry after 2m" — anchored so an unrelated number in an error message can never be mistaken for a back-off.
+3. All parsed delays are clamped to 24h so a malformed/hostile hint cannot bench a key forever.
+
+Only the number is kept — never the body — so nothing extra reaches logs or attempt traces. Tests: [`server/src/__tests__/providers/stated-retry.test.ts`](../../server/src/__tests__/providers/stated-retry.test.ts).
+
+## Health checks must not burn metered quota (#882)
+
+Health runs a scheduled pass every 5 minutes (±20% jitter, keys validated more recently than 3.5 minutes skipped, default concurrency 8, ≥1s spacing between same-provider probes). That cadence is fine for free validation endpoints but poisonous where validation itself costs quota:
+
+- ModelScope validates keys with a paid 1-token chat completion (`GET /v1/models` does not enforce auth), spending magic-grain quota — at the default cadence roughly 288 paid probes/key/day. Fix (#882): tokens not prefixed `ms-` are rejected locally with zero network calls, and a successful validation is cached per key for `MODELSCOPE_VALIDATE_CACHE_MS` (default 24h).
+- Pollinations' public `/v1/models` answers 200 even for revoked keys, so validation targets the authenticated `/account/key`; AI Horde treats any reachable endpoint as healthy rather than spending queue slots.
+
+The rule for contributors: **if `validateKey` consumes metered quota, it needs a cache or a free probe path** — see [03-adding-a-new-provider.md](03-adding-a-new-provider.md).
diff --git a/docs/providers/03-adding-a-new-provider.md b/docs/providers/03-adding-a-new-provider.md
new file mode 100644
index 00000000..c8c42b26
--- /dev/null
+++ b/docs/providers/03-adding-a-new-provider.md
@@ -0,0 +1,71 @@
+# Adding a new provider
+
+A contributor walkthrough that mirrors how the existing 37 built-in platforms are wired. Read [`server/src/providers/index.ts`](../../server/src/providers/index.ts) alongside this guide — it is both the registry and the best documentation of per-platform judgment calls.
+
+## 1. Declare the platform
+
+Add the id to the `Platform` union in [`shared/types.ts`](../../shared/types.ts) (line 59) with a comment stating the free-tier facts you can defend: what is free, recurring or promotional, card or no card, and any signup walls. The union must stay in sync with the `PLATFORMS` allowlist in [`server/src/routes/keys.ts`](../../server/src/routes/keys.ts) — that zod enum gates which platforms users may register keys for.
+
+## 2. Choose an adapter
+
+- **OpenAI-compatible endpoint** → no new class. Register `OpenAICompatProvider` with the platform's base URL, as groq, cerebras, openrouter, and ~27 others do.
+- **Wire-format divergence** → subclass `BaseProvider` in its own file and register it. Existing precedents:
+ - `GoogleProvider` — native Gemini wire format;
+ - `CohereProvider` / `CloudflareProvider` / `ZhipuProvider` — compatible chat routing plus key-shape or console-detection behavior;
+ - `PollinationsProvider` / `ModelScopeProvider` — needed because their public model-list endpoints answer 200 even for bad keys, so validation needs a different probe;
+ - `AIHordeProvider` — queue-based proxy diverging from the OpenAI contract (`max_tokens >= 16`, array-only `stop`, kudos usage, no tools).
+
+Every adapter gets for free: timeout/stall wiring (`fetchWithTimeout`, first-byte budgeting #584), SSE reading with truncation detection, `<think>` extraction, and error construction via `providerHttpError`.
+
+## 3. Register with the right options
+
+In `index.ts`:
+
+```ts
+register(new OpenAICompatProvider({
+ platform: 'yourplatform',
+ name: 'Your Platform',
+ baseUrl: 'https://api.example.com/v1',
+}));
+```
+
+Options to consider, each used by a real registration:
+
+| Option | When | Example |
+| --- | --- | --- |
+| `timeoutMs` | Cold starts or hidden reasoning exceed the 15s default; per-call overrides still win. | google 60s, nvidia 180s, ollama/custom 120s |
+| `keyless: true` | The free tier works anonymously. The provider omits Authorization; the Keys page stores a sentinel row so routing treats the platform as configured. | kilo, ovh |
+| `extraHeaders` | Provider requires specific headers. | openrouter referer/title; routeway/navy browser-style User-Agent behind Cloudflare |
+| `forceSingleToolCall` | Upstream rejects parallel tool calls. | nvidia (#255) |
+| `validateUrl` | Key validation should probe a different URL than `/v1/models`. | kilo probes `/api/gateway/models` |
+
+Env-tunable timeouts come automatically via `PROVIDER_TIMEOUT_<PLATFORM>` (#547).
+
+## 4. Get key validation right
+
+`validateKey` returns a boolean or `{ valid: false, error }`. Use the inherited `validationResult(res)` helper to turn 401/403 into a diagnostic failure carrying the upstream reason. Two hard rules learned in production:
+
+1. **Never trust a public models endpoint as proof of a valid key** (pollinations #608, modelscope): if `GET /v1/models` answers 200 unauthenticated, probe something authenticated instead.
+2. **If validation consumes metered quota, cache it or find a free probe** — see [#882](02-quotas-and-cooldowns.md#health-checks-must-not-burn-metered-quota-882). Health runs every ~5 minutes against every stored key.
+
+## 5. Seed the catalog deliberately
+
+Model rows come from two places, and picking wrong leaks paid models to free users:
+
+- **Versioned migrations** (`migrateModelsV<N>`) for docs-confirmed free rosters shipped to every binary (opencode V18, ovh V26).
+- **Hosted catalog** via `services/catalog-sync.ts` (gated on `hasProvider`) when availability should be managed centrally — typically premium now, free after the 30-day age gate. Rows are never seeded from third-party lists without live verification: a bad model id is caught by health checks instead of shipped as default.
+
+If the platform publishes no limits, set `null` rather than guessing; the unknown-limit cooldown path caps benches at 10 minutes precisely because guesses are not measurements.
+
+## 6. Test it
+
+Ship tests under [`server/src/__tests__/providers/`](../../server/src/__tests__/providers/) following the existing pattern (see `cn-providers.test.ts` for a batch of OpenAI-compat registrations): assert the outgoing request shape (URL, auth header placement, headers), response normalization, and any quirk you introduced. Run the full chain with `npm test` from the repo root — see [docs/testing](../testing/OVERVIEW.md).
+
+## Checklist
+
+- [ ] `Platform` union + `routes/keys.ts` `PLATFORMS` allowlist updated together
+- [ ] Registration in `providers/index.ts` with defensible timeout/headers/keyless choices
+- [ ] `validateKey` proven against real 401/403 bodies and public-endpoint gotchas
+- [ ] Free-tier claims verified live (dates and observations in comments, like the rest of `index.ts`)
+- [ ] Catalog seeding decision made explicitly (migration vs hosted catalog vs none)
+- [ ] Provider tests added; root `npm test` green
diff --git a/docs/providers/CHANGELOG.md b/docs/providers/CHANGELOG.md
new file mode 100644
index 00000000..870f74ec
--- /dev/null
+++ b/docs/providers/CHANGELOG.md
@@ -0,0 +1,20 @@
+# Changelog
+
+Revision history for `docs/providers/`, listing the upstream commits that shaped the provider layer documented here. Most recent first.
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `ef4519a` | 2026-08-23 | feat(providers): add xkiro.com as OpenAI-compatible provider (#967) |
+| `68ddca4` | 2026-08-23 | feat(providers): add UnoRouter (unorouter.com) as OpenAI-compatible provider (#875) |
+| `df1000a` | 2026-08-20 | Qianfan/Volcengine Ark/LongCat/iFlytek Spark (#936) — four Chinese domestic OpenAI-compat platforms. |
+| `00268be` | 2026-08-18 | B.AI gateway (#918). |
+| `fba4b3d` | 2026-08-15 | OrcaRouter (#896). |
+| `5999d48` | 2026-08-11 | AnyAPI (#772). |
+| `6f13332` | 2026-08-10 | honor back-off from error body (#798). |
+| `24b5f9c` | 2026-06-26 | Routeway/BazaarLink/AINative (#385). |
+| `cba6ac8` | 2026-06-03 | keyless Kilo + Gemma 4 (#181). |
+| `6305924` | 2026-06-02 | OpenCode Zen 4 free models. |
+| `a89cc64` | 2026-05-31 | generic custom OpenAI-compat provider (#145). |
+| `694d75c` | 2026-04-26 | error handler crash + missing platforms + per-provider timeout (#7). |
+
+Regenerate with `git log --oneline -- server/src/providers`.
diff --git a/docs/providers/OVERVIEW.md b/docs/providers/OVERVIEW.md
new file mode 100644
index 00000000..0372fe53
--- /dev/null
+++ b/docs/providers/OVERVIEW.md
@@ -0,0 +1,21 @@
+# Provider integrations overview
+
+## Scope
+
+This domain documents FreeLLMAPI's provider layer: the platforms the gateway aggregates, how each is authenticated and adapted, and how per-key quota accounting, cooldowns, and health checks keep free tiers usable behind one OpenAI-compatible API.
+
+The authoritative sources are [`shared/types.ts`](../../shared/types.ts) (the `Platform` union), [`server/src/providers/index.ts`](../../server/src/providers/index.ts) (the runtime registry), and [`server/src/providers/base.ts`](../../server/src/providers/base.ts) (the adapter contract). The public catalog headline — roughly 34 free providers, 474 model families, 635 free endpoints (~7.4 billion tokens/month of listed capacity) — comes from the [provider table in the README](../../README.md); the catalog itself tracks fewer platforms than the type union declares because some union members are retired or user-defined rather than catalog-managed.
+
+## File index
+
+| File | Description |
+| --- | --- |
+| [01-supported-platforms.md](01-supported-platforms.md) | One row per platform declared in `shared/types.ts`: auth model (keyed/keyless), adapter class (native/OpenAI-compatible), and integration notes. Explicit counts for every grouping. |
+| [02-quotas-and-cooldowns.md](02-quotas-and-cooldowns.md) | RPM/RPD and TPM/TPD window accounting, concurrency leases and opt-in caps, the cooldown ladder and its provenance classes, probe-based early recovery, back-off parsed from `Retry-After` headers and error bodies (#798), and why health checks must not burn metered quota (#882). |
+| [03-adding-a-new-provider.md](03-adding-a-new-provider.md) | Contributor walkthrough: extending the `Platform` union, choosing an adapter, registration options (timeouts, keyless, extra headers), key-validation semantics, catalog seeding policy, and the tests a new provider is expected to ship. |
+
+## Conventions
+
+- Adapters live in [`server/src/providers/`](../../server/src/providers/); every platform registered there appears on `/v1` routing immediately — no separate enable step.
+- Model rows are seeded two ways: versioned migrations for launch-time rosters, and the signed hosted catalog (`services/catalog-sync.ts`, gated on `hasProvider`) for everything catalog-managed afterwards.
+- Quota limits are data, not code: `rpm_limit` / `rpd_limit` / `tpm_limit` / `tpd_limit` columns on each catalog model row drive pre-throttling; see [02-quotas-and-cooldowns.md](02-quotas-and-cooldowns.md).
diff --git a/docs/testing/01-running-tests.md b/docs/testing/01-running-tests.md
new file mode 100644
index 00000000..85e484ed
--- /dev/null
+++ b/docs/testing/01-running-tests.md
@@ -0,0 +1,57 @@
+# Running tests
+
+## Root chain
+
+`npm test` at the repo root runs, in order ([package.json](../../package.json)):
+
+| Step | Command | What it covers |
+| --- | --- | --- |
+| `test:bootstrap` | `node --test scripts/dev-bootstrap.test.mjs` | The dev bootstrap script. |
+| `test:hooks` | `node --test .claude/hooks/contributing-check.test.mjs` | Contributor-check hook logic. |
+| server | `npm run test -w server` | Vitest suite (see [02-server-suite.md](02-server-suite.md)). |
+| cli | `npm run test -w cli` | Setup-CLI tests (tools, config-file merging, index). |
+| client | `npm run test -w client --if-present` | Client vitest suite plus i18n parity check. |
+
+The desktop workspace has its own small suite (`desktop/src/__tests__/window-chrome.test.ts`) but is not part of the root chain; it runs with its own tooling via `npm --prefix desktop`.
+
+## Per-workspace commands
+
+### Server (`server/package.json`)
+
+```
+npm run test -w server # vitest run --pool=forks --fileParallelism=false
+npm run test:watch -w server # watch mode
+npm run test:migrations -w server # migration roundtrip only
+```
+
+`test:migrations` targets exactly one file — [`src/__tests__/db/migrate/roundtrip.test.ts`](../../server/src/__tests__/db/migrate/roundtrip.test.ts) — and replays every recorded migration up and down to prove the roundtrip. Run it after touching anything under `src/db/migrate/`.
+
+New test files added in the August 2026 batch that expand coverage:
+- `src/__tests__/routes/logs.test.ts` — server log viewer persistence and API
+- `src/__tests__/routes/custom-transcription.test.ts` — custom STT model registration and transcription usage
+- `src/__tests__/lib/provider-identity.test.ts` — custom endpoint identity classification (#889)
+
+### Client (`client/package.json`)
+
+```
+npm run test -w client # vitest run && npm run check:i18n
+npm run check:i18n -w client # scripts/check-i18n.mjs
+```
+
+`check:i18n` verifies every locale file for key/placeholder parity; a missing or placeholder-broken translation fails the suite, not just the build.
+
+### Everything else
+
+`npm run build` must also pass — CI builds all workspaces after tests, so type errors surface there even when unit tests stay green.
+
+## CI summary
+
+[`.github/workflows/ci.yml`](../../.github/workflows/ci.yml) runs on `ubuntu-24.04`, on pushes and PRs targeting `main`, as a single `test` job across a Node matrix of **20 and 22** — both ends of the supported engines range (`>=20.18 <25`). Node 20 is the baseline that historically caught crashes newer local Node hid; 22 is the LTS most contributors run. Steps, in order:
+
+1. checkout + setup-node (with npm cache)
+2. `npm install`
+3. **Check migration round trip**: `npm run test:migrations` (before the main suite, so schema drift fails fast)
+4. `npm test` (the root chain above)
+5. `npm run build`
+
+`fail-fast: false` keeps one Node version's failure from hiding the other's results.
diff --git a/docs/testing/02-server-suite.md b/docs/testing/02-server-suite.md
new file mode 100644
index 00000000..04ffab94
--- /dev/null
+++ b/docs/testing/02-server-suite.md
@@ -0,0 +1,49 @@
+# Server suite
+
+## Layout
+
+All server tests live under [`server/src/__tests__/`](../../server/src/__tests__), mirroring `src/`:
+
+| Directory | Contents |
+| --- | --- |
+| `db/` | DB init/encryption/hardening, intelligence tiers, node-sqlite behavior, and `db/migrate/` — migration runner tests, registry drift, endpoint identity, and the `roundtrip.test.ts` that `test:migrations` runs in isolation. |
+| `lib/` | Pure-module units: error classification, crypto, budget, Gemini wire/schema, fallback loop (incl. client-abort, hedge, lease, model-bench variants), env drift, module purity (see below). |
+| `providers/` | Per-adapter tests: google (params/auth-header/schema), openai-compat, cohere, cloudflare, zhipu, aihorde, modelscope, pollinations, cn-providers batch, plus cross-cutting behaviors — abort signals, reasoning timeouts, stream first-byte, stated-retry parsing (#798), max-token caps. |
+| `routes/` | HTTP surface tests: proxy/retry/fallback, anthropic messages shim, gemini `/v1beta`, ollama emulation, url-tokens, auth, analytics, custom providers/endpoints, compression/CSP security headers. |
+| `services/` | Router/scoring/fusion, health (scheduler, pacing, error/log/transport), cooldown-probe, catalog-sync (scheduler/source), key concurrency, learn-limits, degradation, embeddings/media/transcription. |
+| `integration/` | `full-flow.test.ts` — request lifecycle through the assembled app. |
+| `helpers/` | Shared test utilities (`auth.ts`, `acl.ts`). |
+| `fixtures/` | Golden files (e.g. `compression-golden.json`). |
+
+## Serial forked execution
+
+`npm run test -w server` runs `vitest run --pool=forks --fileParallelism=false`. Two deliberate choices:
+
+- **`--pool=forks`** isolates each test file in a fresh process. The suite manipulates real state — better-sqlite3 databases, `process.env`, module-level caches (cooldown maps, health schedulers) — that must not leak between files.
+- **`--fileParallelism=false`** serializes files so shared resources (ports, temp data dirs) cannot collide across concurrently executing files.
+
+The tradeoff is wall-clock time; the payoff is that the ~2300-test suite is deterministic. The client workspace does not need this: its [standalone vitest config](../../client/vitest.config.ts) exists mainly to avoid loading the React/Tailwind vite plugins, and its tests are plain TypeScript in the default node environment.
+
+## Pure-lib import guard (#858)
+
+[`src/__tests__/lib/module-purity.test.ts`](../../server/src/__tests__/lib/module-purity.test.ts) enforces an architectural invariant: modules declared pure in [`server/src/lib/`](../../server/src/lib/) (functions over their arguments — no I/O, no DB, no config) must stay free of **value** imports. `import type` stays legal because type imports are erased before they can create a cycle.
+
+Why it exists: pure leaf modules like `error-classify.ts` are imported by the proxy chat path, the responses path, AND the fusion panel precisely because they depend on nothing. One added `import { getDb }` compiles cleanly, passes every behavioral test, and quietly turns a leaf into a hub — surfacing later as an import cycle (the fusion↔proxy case) or a unit test that suddenly needs a database. The guard also detects dynamic imports, re-exports, and `require()`.
+
+The list maintains itself: any new import-free lib module fails the suite until it is classified as guarded or deliberately not — a decision made out loud in a diff rather than by omission.
+
+## Loopback binding convention (#888)
+
+Every route/integration test starts its server as:
+
+```ts
+const server = app.listen(0, '127.0.0.1');
+if (!server.listening) await new Promise<void>(r => server.once('listening', () => r()));
+```
+
+Two details, both load-bearing (#888):
+
+1. **Bind to `127.0.0.1` explicitly.** The older `app.listen(0)` bound the IPv6 wildcard `::`, while tests fetched `http://127.0.0.1:PORT` over IPv4. Different addresses means an unrelated local process holding an IPv4 listener on the same ephemeral port wins the connection without triggering `EADDRINUSE` — requests were answered by that process (observed with `wrangler dev` workerd processes replying 404/501), producing random assertion failures, broken JSON parses, and 5s timeouts roughly every second-to-fourth run.
+2. **Wait for the `listening` event before reading `address()`.** `listen(port, host)` resolves the host asynchronously (unlike `listen(port)`), so `server.address().port` is only reliable after the event fires.
+
+Verified fix: ten consecutive full suite runs clean against a machine with the colliding processes still running.
diff --git a/docs/testing/03-compatibility-suite.md b/docs/testing/03-compatibility-suite.md
new file mode 100644
index 00000000..f1e18538
--- /dev/null
+++ b/docs/testing/03-compatibility-suite.md
@@ -0,0 +1,35 @@
+# Compatibility suite
+
+## What it is
+
+The coding-agent compatibility suite (commit `19168ac`, #629, 2026-07-27) proves that real AI coding agents work against FreeLLMAPI's surfaces — not just that the endpoints exist. It covers the three integration layers an agent touches: the wire API it calls, the config files it is pointed at, and the client classification the gateway applies to its traffic.
+
+## What it covers and where
+
+### Native Gemini `/v1beta` surface
+
+[`server/src/__tests__/routes/gemini.test.ts`](../../server/src/__tests__/routes/gemini.test.ts) drives the assembled Express app over HTTP:
+
+- model discovery, `generateContent` (JSON and SSE streaming), `countTokens`;
+- tool / thinking / structured-output translation between Gemini's schema dialect and upstream providers;
+- family mapping and correct defaults for Gemini CLI (output cap, dynamic thinking, `tool_choice` omission).
+
+### Ollama emulation (opt-in)
+
+[`server/src/__tests__/routes/ollama.test.ts`](../../server/src/__tests__/routes/ollama.test.ts) covers NDJSON `chat`/`generate`, `tags`/`show`/`version`, embeddings, and the mode matrix (off / open loopback / key-required with per-IP rate limiting), plus protocol fidelity details: generate frames, legacy embeddings body, load probes, `done_reason` vocabulary.
+
+### Setup CLI
+
+The `cli/` workspace (added in the same commit, tested by the root chain) generates per-agent configuration for Claude Code, Codex CLI, Cline, Continue, OpenCode, Goose, Qwen Code, Roo/Kilo/Crush, and Cursor — 13 data-driven generators with comment-preserving structural merges (TOML that survives existing MCP tables), backups, dry runs, credential-safe launchers, and Claude Code discovery aliases. Tests: `cli/src/tools.test.ts`, `cli/src/config-files.test.ts` (with snapshots), `cli/src/index.test.ts`.
+
+### Client classification and URL tokens
+
+Client-classifier tests (`server/src/__tests__/lib/client-context.test.ts` and friends) pin agent identification feeding the Agents dashboard and per-agent analytics; [`routes/url-tokens.test.ts`](../../server/src/__tests__/routes/url-tokens.test.ts) covers separately revocable URL tokens used by headerless clients, validated timing-safely.
+
+## What it proves
+
+1. **Protocol fidelity**: an agent speaking native Gemini or Ollama wire formats gets semantically correct answers — streaming frames, tool-call translation, token counting — not merely a 200.
+2. **Zero-config onboarding**: the setup CLI writes agent config files correctly even when they already contain unrelated content (structural merge, not overwrite), and never leaks credentials into generated launchers.
+3. **Regression safety for hardening**: review-hardening fixes from #629 (Gemini CLI defaults, Ollama protocol edge cases, TOML merge survival, timing-safe token checks) are pinned as tests.
+
+The commit message notes the suite was live-verified against an isolated deployment with real provider keys across all new surfaces — these tests encode those observations so the guarantees survive refactors.
diff --git a/docs/testing/CHANGELOG.md b/docs/testing/CHANGELOG.md
new file mode 100644
index 00000000..cb92b5f4
--- /dev/null
+++ b/docs/testing/CHANGELOG.md
@@ -0,0 +1,14 @@
+# Changelog
+
+Revision history for `docs/testing/`, listing the upstream commits that shaped the test infrastructure documented here. Most recent first.
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `74df985` | 2026-08-23 | Server log viewer in the dashboard (#993) — added `routes/logs.test.ts`. |
+| `2463c14` | 2026-08-23 | fix(media): custom speech-to-text models (#992) — added `routes/custom-transcription.test.ts`. |
+| `3503f91` | 2026-08-22 | Analytics: give custom endpoints their own identity (#958) — added `lib/provider-identity.test.ts`. |
+| `4a47b3a` | 2026-08-18 | pure lib import guard (#858). |
+| `37ce9ac` | 2026-08-14 | bind test servers to loopback (#888). |
+| `19168ac` | 2026-07-27 | coding-agent compatibility suite (#629). |
+
+Regenerate with `git log --oneline -- server/src/__tests__`.
diff --git a/docs/testing/OVERVIEW.md b/docs/testing/OVERVIEW.md
new file mode 100644
index 00000000..738f25c9
--- /dev/null
+++ b/docs/testing/OVERVIEW.md
@@ -0,0 +1,21 @@
+# Testing overview
+
+## Scope
+
+This domain documents how FreeLLMAPI is tested: the local command matrix across the monorepo workspaces, the layout and conventions of the server suite (serial forked execution, module-purity guard, loopback binding), and the end-to-end coding-agent compatibility suite introduced in #629.
+
+Sources: the root [`package.json`](../../package.json) test chain, per-workspace `package.json` scripts ([server](../../server/package.json), [client](../../client/package.json)), [`.github/workflows/ci.yml`](../../.github/workflows/ci.yml), and the suites themselves under [`server/src/__tests__/`](../../server/src/__tests__).
+
+## File index
+
+| File | Description |
+| --- | --- |
+| [01-running-tests.md](01-running-tests.md) | The full local matrix — root chain order, per-workspace commands, the migration roundtrip check — and a summary of what CI runs on ubuntu-24.04. |
+| [02-server-suite.md](02-server-suite.md) | `src/__tests__/` directory layout, why vitest runs with `--pool=forks --fileParallelism=false`, the pure-lib import guard (#858), and the bind-to-loopback convention (#888). |
+| [03-compatibility-suite.md](03-compatibility-suite.md) | The e2e coding-agent compatibility suite from #629: what it covers, where it lives, and what it proves. |
+
+## Conventions
+
+- One entry point: `npm test` at the repo root runs bootstrap and hook checks, then server, cli, and client workspaces in order.
+- Server tests are deterministic and side-effect aware: no live provider calls, servers bound to `127.0.0.1`, shared state isolated by running files serially in forked pools.
+- CI is the same matrix on both ends of the supported Node range (20 and 22) — if it passes locally with `npm test && npm run build`, CI should agree.