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: per-language layout docs/{en,zh-cn}, Chinese README, redirect stubs (#1138)

Davisvilleeab992f75359
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index ffa726d5..dddaeef8 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/i18n/01-translating.md](docs/i18n/01-translating.md) for the full rules and the settled Chinese
+[docs/TRANSLATION.md](docs/TRANSLATION.md) for the full rules and the settled Chinese
terminology.
## Commit checklist hook
diff --git a/README.md b/README.md
index cbefae06..23de0b22 100644
--- a/README.md
+++ b/README.md
@@ -15,13 +15,13 @@ Aggregate free tiers from dozens of providers, plus custom OpenAI-compatible cha
**[freellmapi.co](https://freellmapi.co/?utm_source=github&utm_medium=readme&utm_campaign=repository&utm_content=readme_top)** · browse the full catalog: 474 model families, 635 free endpoints
-**English** · [简体中文](docs/i18n/zh-CN/README.md)
+**English** · [简体中文](README.zh-cn.md)
<p align="center">
<a href="https://play.google.com/store/apps/details?id=co.freellmapi.app"><img src="repo-assets/badges/play-store.svg" height="60" alt="Get it on Google Play"></a>
<a href="https://github.com/tashfeenahmed/freellmapi/releases/latest"><img src="repo-assets/badges/macos.svg" height="60" alt="Download for macOS"></a>
<a href="https://github.com/tashfeenahmed/freellmapi/releases/latest"><img src="repo-assets/badges/windows.svg" height="60" alt="Download for Windows"></a>
- <a href="docs/install.md#docker-compose"><img src="repo-assets/badges/docker.svg" height="60" alt="Self-host with Docker"></a>
+ <a href="docs/en/install/01-install.md#docker-compose"><img src="repo-assets/badges/docker.svg" height="60" alt="Self-host with Docker"></a>
</p>
![FreeLLMAPI dashboard — Models page with the monthly token budget](repo-assets/github-hero.png)
@@ -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/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)
+**Guides:** [Install & deploy](docs/en/install/01-install.md) · [API reference](docs/en/api/01-rest-api.md) · [Clients & coding agents](docs/en/clients/01-agent-clients.md) · [Prompt compression](docs/en/compression/01-compression-pipeline.md) · [Architecture & internals](docs/en/architecture/00-high-level-index.md) · [Documentation index](docs/en/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/01-agent-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/en/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/01-agent-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/en/clients/01-agent-clients.md)**
## How it compares
@@ -151,25 +151,25 @@ 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/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)
+- **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/en/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/en/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/01-rest-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/en/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)
+- **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/en/architecture/00-high-level-index.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/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)
+- **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/en/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/en/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/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)
+- **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/en/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/en/install/01-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.
-The scope is deliberately narrow — see [what's not supported yet](docs/architecture.md#not-yet-supported).
+The scope is deliberately narrow — see [what's not supported yet](docs/en/architecture/00-high-level-index.md#not-yet-supported).
## Quick start
@@ -183,9 +183,9 @@ Prefer to read before you pipe to bash? [The script is here](https://freellmapi.
Open http://localhost:3001, add your provider keys on the **Keys** page, reorder the **Fallback Chain** to taste, and grab your unified API key from the **Keys** page header. That unified key is what you point your OpenAI SDK at.
-On Windows, the easiest path is the desktop **[`.exe` installer from Releases](https://github.com/tashfeenahmed/freellmapi/releases/latest)** (below). On Android, see the experimental [Termux guide](docs/install/android-termux.md).
+On Windows, the easiest path is the desktop **[`.exe` installer from Releases](https://github.com/tashfeenahmed/freellmapi/releases/latest)** (below). On Android, see the experimental [Termux guide](docs/en/install/02-android-termux.md).
-Everything else — Docker Compose, local development, declarative startup config, production builds, LAN access, and backups — is in **[docs/install.md](docs/install.md)**.
+Everything else — Docker Compose, local development, declarative startup config, production builds, LAN access, and backups — is in **[docs/install.md](docs/en/install/01-install.md)**.
## Desktop app
@@ -193,11 +193,11 @@ A native menu-bar app lives in [`desktop/`](./desktop): the entire router + dash
![FreeLLMAPI desktop app](repo-assets/desktop.png)
-**[Download from Releases](https://github.com/tashfeenahmed/freellmapi/releases/latest)** — the macOS `.dmg` and the Windows `.exe` installer are attached to every release. No account or password to set up: the only credential you need is the unified API key from the tray popover. Build-from-source steps and where your data lives: [docs/install.md](docs/install.md#desktop-app).
+**[Download from Releases](https://github.com/tashfeenahmed/freellmapi/releases/latest)** — the macOS `.dmg` and the Windows `.exe` installer are attached to every release. No account or password to set up: the only credential you need is the unified API key from the tray popover. Build-from-source steps and where your data lives: [docs/install.md](docs/en/install/01-install.md#desktop-app).
## 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/01-agent-clients.md](docs/clients/01-agent-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/en/clients/01-agent-clients.md](docs/en/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/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.
+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/en/api/01-rest-api.md](docs/en/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
@@ -335,7 +335,7 @@ Request volume, success rate, tokens in and out, average latency, and per-provid
![One request in, the best free model out — the fallback chain with live scores, cooldowns, and quota tracking](repo-assets/router-flow.png)
-One request in, the best free model out: the router picks the highest-priority model with a healthy key that's under all its rate limits, decrypts the key in memory, and calls the provider — on a 429/5xx it cools that key down and retries the next model in your chain. The component walkthrough, routing internals, and operational details live in **[docs/architecture.md](docs/architecture.md)**.
+One request in, the best free model out: the router picks the highest-priority model with a healthy key that's under all its rate limits, decrypts the key in memory, and calls the provider — on a 429/5xx it cools that key down and retries the next model in your chain. The component walkthrough, routing internals, and operational details live in **[docs/architecture.md](docs/en/architecture/00-high-level-index.md)**.
## FAQ
@@ -347,11 +347,11 @@ One request in, the best free model out: the router picks the highest-priority m
**How do I uninstall?** Remove the app (Trash on macOS, *Settings → Apps* on Windows, `docker compose down -v` for Docker), then delete the data directory: `%APPDATA%\FreeLLMAPI\`, `~/Library/Application Support/FreeLLMAPI/`, or `~/.config/FreeLLMAPI/`. Uninstalling never touches that folder on its own.
-Longer answers, per install method: **[docs/install.md#faq-passwords-logs-uninstall](docs/install.md#faq-passwords-logs-uninstall)**.
+Longer answers, per install method: **[docs/install.md#faq-passwords-logs-uninstall](docs/en/install/01-install.md#faq-passwords-logs-uninstall)**.
## Limitations
-Stacking free tiers has real trade-offs: no frontier models, variable latency, no SLA — and the effective intelligence of the endpoint dips late in the day as top models hit their daily caps, then resets at UTC midnight. Read the honest list in **[docs/architecture.md#limitations](docs/architecture.md#limitations)** before building anything real on this.
+Stacking free tiers has real trade-offs: no frontier models, variable latency, no SLA — and the effective intelligence of the endpoint dips late in the day as top models hit their daily caps, then resets at UTC midnight. Read the honest list in **[docs/architecture.md#limitations](docs/en/architecture/00-high-level-index.md#limitations)** before building anything real on this.
## Contributing
@@ -483,7 +483,7 @@ Contributors very welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for the dev lo
**This project is for personal experimentation and learning, not production.** Free tiers exist so developers can prototype against them; they aren't a stable, supported inference substrate and shouldn't be treated as one. If you build something real on top of FreeLLMAPI, swap in a paid API before you ship. Your relationship with each upstream provider is governed by the terms you accepted when you created your account — those terms still apply when the traffic is proxied through this project, and you're responsible for complying with them.
-How each provider's ToS views a personal, single-user proxy — reviewed provider by provider in May 2026 — is in [docs/architecture.md#terms-of-service-review](docs/architecture.md#terms-of-service-review).
+How each provider's ToS views a personal, single-user proxy — reviewed provider by provider in May 2026 — is in [docs/architecture.md#terms-of-service-review](docs/en/architecture/00-high-level-index.md#terms-of-service-review).
## License
diff --git a/docs/i18n/zh-CN/README.md b/README.zh-cn.md
similarity index 78%
rename from docs/i18n/zh-CN/README.md
rename to README.zh-cn.md
index 85658cab..66f2ec60 100644
--- a/docs/i18n/zh-CN/README.md
+++ b/README.zh-cn.md
@@ -8,18 +8,18 @@
[![CI](https://github.com/tashfeenahmed/freellmapi/actions/workflows/ci.yml/badge.svg)](https://github.com/tashfeenahmed/freellmapi/actions/workflows/ci.yml)
[![GitHub stars](https://img.shields.io/github/stars/tashfeenahmed/freellmapi?style=flat&logo=github&color=yellow)](https://github.com/tashfeenahmed/freellmapi/stargazers)
-[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](../../../LICENSE)
+[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](#参与贡献)
[![Docker image](https://img.shields.io/badge/ghcr.io-freellmapi-2496ED?logo=docker&logoColor=white)](https://github.com/tashfeenahmed/freellmapi/pkgs/container/freellmapi)
[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/tashfeenahmed/freellmapi)
**[freellmapi.co](https://freellmapi.co/?utm_source=github&utm_medium=readme&utm_campaign=repository&utm_content=readme_top)** · 浏览完整目录:474 个模型系列,635 个免费端点
-[English](../../../README.md) · **简体中文**
+[English](README.md) · **简体中文**
本翻译可能滞后,最新内容以英文 README 为准。
-![FreeLLMAPI 仪表盘 —— 带每月词元额度的模型页](../../../repo-assets/github-hero.png)
+![FreeLLMAPI 仪表盘 —— 带每月词元额度的模型页](repo-assets/github-hero.png)
你的路由器会从签名源自行更新模型目录:新的免费模型、额度变更和兼容性修复,都不需要 `git pull` 就能生效。
@@ -48,9 +48,9 @@
- [参与贡献](#参与贡献)
- [免责声明](#免责声明)
-**指南:** [安装与部署](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)
+**指南:** [安装与部署](docs/en/install/01-install.md) · [API 参考](docs/en/api/01-rest-api.md) · [客户端与编程智能体](docs/en/clients/01-agent-clients.md) · [提示词压缩](docs/en/compression/01-compression-pipeline.md) · [架构与内部实现](docs/en/architecture/00-high-level-index.md) · [文档索引](docs/en/README.md) · [贡献者指南](CONTRIBUTING.md)
-> 「安装与部署」和「API 参考」已有中文版。「客户端与编程智能体」「提示词压缩」「架构与内部实现」目前只有英文版,上面的链接直接指向英文原文。完整的翻译状态见 [这里](../README.md#status)。
+> 「安装与部署」和「API 参考」已有中文版。「客户端与编程智能体」「提示词压缩」「架构与内部实现」目前只有英文版,上面的链接直接指向英文原文。完整的翻译状态见 [这里](README.md#status)。
## 为什么会有这个项目
@@ -60,28 +60,28 @@
而且免费额度的格局每周都在变:提供方会上线新模型、下线旧模型,并且不打招呼就调整额度。这些 FreeLLMAPI 都替你盯着。路由器会自行从 [freellmapi.co](https://freellmapi.co) 拉取经过签名的模型目录,所以你的部署不用 `git pull` 也能跟上。跟进速度见 [Premium 实时目录](#premium-实时目录)。
-![叠加后的免费额度 —— 34 家提供方合计每月约 74 亿词元的免费推理](../../../repo-assets/free-tier.png)
+![叠加后的免费额度 —— 34 家提供方合计每月约 74 亿词元的免费推理](repo-assets/free-tier.png)
## 支持的提供方
<div align="center">
<table>
<tr>
-<td align="center" width="150"><img src="../../../repo-assets/providers/google.png" width="44" alt="Google"><br/><b>Google</b></td>
-<td align="center" width="150"><picture><source media="(prefers-color-scheme: dark)" srcset="../../../repo-assets/providers/groq-dark.png"><img src="../../../repo-assets/providers/groq.png" width="44" alt="Groq"></picture><br/><b>Groq</b></td>
-<td align="center" width="150"><img src="../../../repo-assets/providers/cerebras.png" width="44" alt="Cerebras"><br/><b>Cerebras</b></td>
-<td align="center" width="150"><picture><source media="(prefers-color-scheme: dark)" srcset="../../../repo-assets/providers/opencode-dark.png"><img src="../../../repo-assets/providers/opencode.png" width="44" alt="OpenCode Zen"></picture><br/><b>OpenCode Zen</b></td>
+<td align="center" width="150"><img src="repo-assets/providers/google.png" width="44" alt="Google"><br/><b>Google</b></td>
+<td align="center" width="150"><picture><source media="(prefers-color-scheme: dark)" srcset="repo-assets/providers/groq-dark.png"><img src="repo-assets/providers/groq.png" width="44" alt="Groq"></picture><br/><b>Groq</b></td>
+<td align="center" width="150"><img src="repo-assets/providers/cerebras.png" width="44" alt="Cerebras"><br/><b>Cerebras</b></td>
+<td align="center" width="150"><picture><source media="(prefers-color-scheme: dark)" srcset="repo-assets/providers/opencode-dark.png"><img src="repo-assets/providers/opencode.png" width="44" alt="OpenCode Zen"></picture><br/><b>OpenCode Zen</b></td>
</tr>
<tr>
-<td align="center"><img src="../../../repo-assets/providers/mistral.png" width="44" alt="Mistral"><br/><b>Mistral</b></td>
-<td align="center"><img src="../../../repo-assets/providers/openrouter.png" width="44" alt="OpenRouter"><br/><b>OpenRouter</b></td>
-<td align="center"><img src="../../../repo-assets/providers/cloudflare.png" width="44" alt="Cloudflare"><br/><b>Cloudflare</b></td>
-<td align="center"><img src="../../../repo-assets/providers/cohere.png" width="44" alt="Cohere"><br/><b>Cohere</b></td>
+<td align="center"><img src="repo-assets/providers/mistral.png" width="44" alt="Mistral"><br/><b>Mistral</b></td>
+<td align="center"><img src="repo-assets/providers/openrouter.png" width="44" alt="OpenRouter"><br/><b>OpenRouter</b></td>
+<td align="center"><img src="repo-assets/providers/cloudflare.png" width="44" alt="Cloudflare"><br/><b>Cloudflare</b></td>
+<td align="center"><img src="repo-assets/providers/cohere.png" width="44" alt="Cohere"><br/><b>Cohere</b></td>
</tr>
<tr>
-<td align="center"><img src="../../../repo-assets/providers/zhipu.png" width="44" alt="Z.ai (Zhipu)"><br/><b>Z.ai(智谱)</b></td>
-<td align="center"><img src="../../../repo-assets/providers/nvidia.png" width="44" alt="NVIDIA"><br/><b>NVIDIA</b></td>
-<td align="center"><img src="../../../repo-assets/providers/huggingface.png" width="44" alt="HuggingFace"><br/><b>HuggingFace</b></td>
+<td align="center"><img src="repo-assets/providers/zhipu.png" width="44" alt="Z.ai (Zhipu)"><br/><b>Z.ai(智谱)</b></td>
+<td align="center"><img src="repo-assets/providers/nvidia.png" width="44" alt="NVIDIA"><br/><b>NVIDIA</b></td>
+<td align="center"><img src="repo-assets/providers/huggingface.png" width="44" alt="HuggingFace"><br/><b>HuggingFace</b></td>
</tr>
<tr>
<td align="center"><a href="https://modelscope.cn"><b>ModelScope 魔搭</b><br/>Qwen3 · DeepSeek V4 · GLM-5(需要绑定阿里云中国站账号)</a></td>
@@ -101,27 +101,27 @@
<div align="center">
<table>
<tr>
-<td align="center" width="150"><img src="../../../repo-assets/agents/claude-code.png" width="44" alt="Claude Code"><br/><b>Claude Code</b></td>
-<td align="center" width="150"><img src="../../../repo-assets/agents/codex.png" width="44" alt="Codex CLI"><br/><b>Codex CLI</b></td>
-<td align="center" width="150"><img src="../../../repo-assets/agents/gemini-cli.png" width="44" alt="Gemini CLI"><br/><b>Gemini CLI</b></td>
-<td align="center" width="150"><img src="../../../repo-assets/agents/aider.png" width="44" alt="Aider"><br/><b>Aider</b></td>
+<td align="center" width="150"><img src="repo-assets/agents/claude-code.png" width="44" alt="Claude Code"><br/><b>Claude Code</b></td>
+<td align="center" width="150"><img src="repo-assets/agents/codex.png" width="44" alt="Codex CLI"><br/><b>Codex CLI</b></td>
+<td align="center" width="150"><img src="repo-assets/agents/gemini-cli.png" width="44" alt="Gemini CLI"><br/><b>Gemini CLI</b></td>
+<td align="center" width="150"><img src="repo-assets/agents/aider.png" width="44" alt="Aider"><br/><b>Aider</b></td>
</tr>
<tr>
-<td align="center"><img src="../../../repo-assets/agents/cline.png" width="44" alt="Cline"><br/><b>Cline</b></td>
-<td align="center"><img src="../../../repo-assets/agents/roo-code.png" width="44" alt="Roo Code"><br/><b>Roo Code</b></td>
-<td align="center"><img src="../../../repo-assets/agents/continue.png" width="44" alt="Continue"><br/><b>Continue</b></td>
-<td align="center"><img src="../../../repo-assets/agents/opencode.png" width="44" alt="OpenCode"><br/><b>OpenCode</b></td>
+<td align="center"><img src="repo-assets/agents/cline.png" width="44" alt="Cline"><br/><b>Cline</b></td>
+<td align="center"><img src="repo-assets/agents/roo-code.png" width="44" alt="Roo Code"><br/><b>Roo Code</b></td>
+<td align="center"><img src="repo-assets/agents/continue.png" width="44" alt="Continue"><br/><b>Continue</b></td>
+<td align="center"><img src="repo-assets/agents/opencode.png" width="44" alt="OpenCode"><br/><b>OpenCode</b></td>
</tr>
<tr>
-<td align="center"><img src="../../../repo-assets/agents/goose.png" width="44" alt="Goose"><br/><b>Goose</b></td>
-<td align="center"><img src="../../../repo-assets/agents/qwen-code.png" width="44" alt="Qwen Code"><br/><b>Qwen Code</b></td>
-<td align="center"><img src="../../../repo-assets/agents/kilo-code.png" width="44" alt="Kilo Code"><br/><b>Kilo Code</b></td>
-<td align="center"><img src="../../../repo-assets/agents/crush.png" width="44" alt="Crush"><br/><b>Crush</b></td>
+<td align="center"><img src="repo-assets/agents/goose.png" width="44" alt="Goose"><br/><b>Goose</b></td>
+<td align="center"><img src="repo-assets/agents/qwen-code.png" width="44" alt="Qwen Code"><br/><b>Qwen Code</b></td>
+<td align="center"><img src="repo-assets/agents/kilo-code.png" width="44" alt="Kilo Code"><br/><b>Kilo Code</b></td>
+<td align="center"><img src="repo-assets/agents/crush.png" width="44" alt="Crush"><br/><b>Crush</b></td>
</tr>
<tr>
-<td align="center"><img src="../../../repo-assets/agents/cursor.png" width="44" alt="Cursor"><br/><b>Cursor</b></td>
-<td align="center"><img src="../../../repo-assets/agents/zed.png" width="44" alt="Zed"><br/><b>Zed</b></td>
-<td align="center"><img src="../../../repo-assets/agents/jetbrains.png" width="44" alt="JetBrains AI"><br/><b>JetBrains AI</b></td>
+<td align="center"><img src="repo-assets/agents/cursor.png" width="44" alt="Cursor"><br/><b>Cursor</b></td>
+<td align="center"><img src="repo-assets/agents/zed.png" width="44" alt="Zed"><br/><b>Zed</b></td>
+<td align="center"><img src="repo-assets/agents/jetbrains.png" width="44" alt="JetBrains AI"><br/><b>JetBrains AI</b></td>
</tr>
</table>
@@ -129,39 +129,39 @@
</div>
-其中大多数一条命令就能配好:`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` 协议。
+其中大多数一条命令就能配好:`npx freellmapi setup-claude`、`setup-codex`、`setup-aider`,还有另外十几个生成器。它们会拉取你当前的实时目录,备份已有配置,并且绝不覆盖你已经写好的内容。Claude Code 和 Codex 另有零留存启动器(`freellmapi launch`、`freellmapi launch-codex`),只把凭据注入子进程。Zed 和 JetBrains AI 通过可选的 [Ollama 模拟](docs/en/clients/01-agent-clients.md#ollama-clients) 接入;Gemini CLI 走它自己的 `/v1beta` 协议。
-各工具的具体配方、setup CLI 参考、给无法发送请求头的客户端用的可撤销 URL 令牌,以及 MCP 服务,都在 **[客户端与编程智能体 →](../../clients/01-agent-clients.md)**
+各工具的具体配方、setup CLI 参考、给无法发送请求头的客户端用的可撤销 URL 令牌,以及 MCP 服务,都在 **[客户端与编程智能体 →](docs/en/clients/01-agent-clients.md)**
## 横向对比
-![与 OpenRouter、LiteLLM、Portkey 的功能对比](../../../repo-assets/comparison.png)
+![与 OpenRouter、LiteLLM、Portkey 的功能对比](repo-assets/comparison.png)
基于 2026 年 7 月的公开文档整理,欢迎指正。
## 功能
-![功能概览](../../../repo-assets/features.png)
+![功能概览](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/01-rest-api.md)
-- **Anthropic Messages API** —— `/v1/messages` 在同一套路由之上讲 Anthropic 的协议,所以 **Claude Code** 和官方 Anthropic SDK 可以直接跑在你的免费池上。[详情 →](docs/api/01-rest-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/en/api/01-rest-api.md)
+- **Anthropic Messages API** —— `/v1/messages` 在同一套路由之上讲 Anthropic 的协议,所以 **Claude Code** 和官方 Anthropic SDK 可以直接跑在你的免费池上。[详情 →](docs/en/api/01-rest-api.md#anthropic-与-claude-客户端)
- **原生 Gemini 与 Ollama 接口** —— Gemini CLI 可以用 `/v1beta`(`generateContent`、流式、词元计数、模型列表);可选的 Ollama 模拟则为 Zed、JetBrains 以及其他本地模型客户端提供 NDJSON 的 chat/generate、标签、元数据和嵌入。
-- **Fusion(多模型合成)** —— 请求虚拟模型 `fusion`,路由器会把你的提示词并行分发给一组风格各异的免费模型,再由一个评审模型从这些草稿中合成出一个答案。[详情 →](docs/api/01-rest-api.md#fusion-多模型合成)
+- **Fusion(多模型合成)** —— 请求虚拟模型 `fusion`,路由器会把你的提示词并行分发给一组风格各异的免费模型,再由一个评审模型从这些草稿中合成出一个答案。[详情 →](docs/en/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)
+- **智能路由,六种策略** —— 实时的每模型速度、能力、稳定性评分决定你的链路顺序;遇到 429/5xx 时自动转移到下一个模型,并带冷却和密钥轮换。[路由详解 →](docs/en/architecture/00-high-level-index.md#routing-in-detail)
- **统一模型与配置档** —— 同一个模型在多家提供方上会合并成一个条目,并在组内严格故障转移;命名的回退链配置档(比如一条编程链、一条视觉链)可以在仪表盘里切换,也可以按请求用 `auto:<profile>` 指定。
- **按密钥的限流跟踪** —— 以 `(平台, 模型, 密钥)` 为单位的 RPM/RPD/TPM/TPD 计数器,会学习提供方公布的上限,让路由始终不越线。
- **自更新的模型目录** —— 路由器每天两次从 freellmapi.co 同步经过签名的目录:新模型、额度变更和提供方的怪癖修复都会自动生效。[Premium →](#premium-实时目录)
-- **粘性会话与上下文交接** —— 对话会在同一个模型上停留 30 分钟;如果中途确实换了模型,可选的精简交接说明能让话题保持连贯。[详情 →](../../clients/01-agent-clients.md#context-handoff)
-- **提示词压缩(可选开启)** —— 一条共享且失败即放行的请求流程,可以在缓存查找和路由之前对提示词去重、过滤工具输出、压紧重复的 JSON,并裁掉过时的上下文。[详情 →](../../compression/01-compression-pipeline.md)
+- **粘性会话与上下文交接** —— 对话会在同一个模型上停留 30 分钟;如果中途确实换了模型,可选的精简交接说明能让话题保持连贯。[详情 →](docs/en/clients/01-agent-clients.md#context-handoff)
+- **提示词压缩(可选开启)** —— 一条共享且失败即放行的请求流程,可以在缓存查找和路由之前对提示词去重、过滤工具输出、压紧重复的 JSON,并裁掉过时的上下文。[详情 →](docs/en/compression/01-compression-pipeline.md)
- **密钥加密存储,对外只有一个令牌** —— 提供方密钥以 AES-256-GCM 加密存放在 SQLite 中,每次请求时在内存里解密;你的应用自始至终只看到一个统一的 `freellmapi-…` bearer 令牌。
- **管理仪表盘与分析** —— React 界面用来管理密钥、调整链路顺序、使用试验台,并查看 24 小时到 90 天窗口的 p50/p95/首个词元用时分析;带登录保护,支持明暗主题和 [60 种语言](#语言)。
-- **MCP 服务与交互式文档** —— 智能体可以通过 `/mcp` 查询可用模型、提供方健康状况和路由策略;`/v1/docs` 提供一个零依赖的 OpenAPI 浏览器。[编程智能体 →](../../clients/01-agent-clients.md)
-- **运维上的便利** —— 可选的响应缓存、加密的数据库备份、定期密钥健康检查、密钥批量导入导出、声明式启动配置。[安装与部署 →](docs/install.md)
+- **MCP 服务与交互式文档** —— 智能体可以通过 `/mcp` 查询可用模型、提供方健康状况和路由策略;`/v1/docs` 提供一个零依赖的 OpenAPI 浏览器。[编程智能体 →](docs/en/clients/01-agent-clients.md)
+- **运维上的便利** —— 可选的响应缓存、加密的数据库备份、定期密钥健康检查、密钥批量导入导出、声明式启动配置。[安装与部署 →](docs/en/install/01-install.md)
- **能跑 Node 20+ 的地方都能跑** —— Windows、macOS、Linux 服务器,或者一块小小的 ARM 单板机(树莓派也行)。在 PM2 / systemd 或你惯用的守护进程下,空闲时常驻内存约 40 MB。
-项目范围是刻意收窄的,参见 [尚不支持的部分](../../architecture.md#not-yet-supported)。
+项目范围是刻意收窄的,参见 [尚不支持的部分](docs/en/architecture/00-high-level-index.md#not-yet-supported)。
## 快速开始
@@ -175,21 +175,21 @@ curl -fsSL https://freellmapi.co/install.sh | bash
打开 http://localhost:3001 ,在 **密钥** 页添加你的提供方密钥,按喜好调整 **回退链** 的顺序,然后在 **密钥** 页顶部拿到你的统一 API 密钥。这个统一密钥就是你的 OpenAI SDK 要指向的东西。
-在 Windows 上,最省事的方式是下面提到的桌面版 **[Releases 里的 `.exe` 安装包](https://github.com/tashfeenahmed/freellmapi/releases/latest)**。Android 上可参考实验性的 [Termux 指南](../../install/android-termux.md)。
+在 Windows 上,最省事的方式是下面提到的桌面版 **[Releases 里的 `.exe` 安装包](https://github.com/tashfeenahmed/freellmapi/releases/latest)**。Android 上可参考实验性的 [Termux 指南](docs/en/install/02-android-termux.md)。
-其余内容,包括 Docker Compose、本地开发、声明式启动配置、生产构建、局域网访问和备份,都在 **[docs/install.md](docs/install.md)**。
+其余内容,包括 Docker Compose、本地开发、声明式启动配置、生产构建、局域网访问和备份,都在 **[docs/install.md](docs/en/install/01-install.md)**。
## 桌面应用
-[`desktop/`](../../../desktop) 里有一个原生的菜单栏应用:整个路由器加仪表盘就在你的托盘里本地运行,还有一个玻璃质感的悬浮窗显示实时请求统计。
+[`desktop/`](desktop) 里有一个原生的菜单栏应用:整个路由器加仪表盘就在你的托盘里本地运行,还有一个玻璃质感的悬浮窗显示实时请求统计。
-![FreeLLMAPI 桌面应用](../../../repo-assets/desktop.png)
+![FreeLLMAPI 桌面应用](repo-assets/desktop.png)
-**[从 Releases 下载](https://github.com/tashfeenahmed/freellmapi/releases/latest)** —— 每个版本都附带 macOS 的 `.dmg` 和 Windows 的 `.exe` 安装包。不需要注册账号或设置密码:你唯一需要的凭据就是托盘悬浮窗里的统一 API 密钥。从源码构建的步骤,以及数据存放位置,见 [docs/install.md](docs/install.md#桌面应用)。
+**[从 Releases 下载](https://github.com/tashfeenahmed/freellmapi/releases/latest)** —— 每个版本都附带 macOS 的 `.dmg` 和 Windows 的 `.exe` 安装包。不需要注册账号或设置密码:你唯一需要的凭据就是托盘悬浮窗里的统一 API 密钥。从源码构建的步骤,以及数据存放位置,见 [docs/install.md](docs/en/install/01-install.md#桌面应用)。
## 兼容 OpenAI 的客户端
-任何能指定 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 服务,你的智能体可以在会话中随时查询它。
+任何能指定 OpenAI 兼容 base URL 的东西都能用:把它设成 `http://localhost:3001/v1`,配上仪表盘里的统一密钥。**Claude Code**、**Codex CLI**、**Cline / Roo Code**、**Continue**(含行内补全)、**Aider**、**opencode** 和 **Cursor** 在 **[docs/en/clients/01-agent-clients.md](docs/en/clients/01-agent-clients.md)** 里各有一段简短配方。此外路由器本身还兼作 MCP 服务,你的智能体可以在会话中随时查询它。
最快的配置方式是根据你服务器上实际可用的模型生成:
@@ -220,13 +220,13 @@ FreeLLMAPI 在设计上是本地优先、单用户的。你的提供方密钥留
<img src="https://flagcdn.com/24x18/us.png" srcset="https://flagcdn.com/48x36/us.png 2x" width="24" height="18" alt="United States" title="United States"> <img src="https://flagcdn.com/24x18/cn.png" srcset="https://flagcdn.com/48x36/cn.png 2x" width="24" height="18" alt="China" title="China"> <img src="https://flagcdn.com/24x18/es.png" srcset="https://flagcdn.com/48x36/es.png 2x" width="24" height="18" alt="Spain" title="Spain"> <img src="https://flagcdn.com/24x18/fr.png" srcset="https://flagcdn.com/48x36/fr.png 2x" width="24" height="18" alt="France" title="France"> <img src="https://flagcdn.com/24x18/br.png" srcset="https://flagcdn.com/48x36/br.png 2x" width="24" height="18" alt="Brazil" title="Brazil"> <img src="https://flagcdn.com/24x18/it.png" srcset="https://flagcdn.com/48x36/it.png 2x" width="24" height="18" alt="Italy" title="Italy"> <img src="https://flagcdn.com/24x18/in.png" srcset="https://flagcdn.com/48x36/in.png 2x" width="24" height="18" alt="India" title="India"> <img src="https://flagcdn.com/24x18/sa.png" srcset="https://flagcdn.com/48x36/sa.png 2x" width="24" height="18" alt="Saudi Arabia" title="Saudi Arabia"> <img src="https://flagcdn.com/24x18/bd.png" srcset="https://flagcdn.com/48x36/bd.png 2x" width="24" height="18" alt="Bangladesh" title="Bangladesh"> <img src="https://flagcdn.com/24x18/ru.png" srcset="https://flagcdn.com/48x36/ru.png 2x" width="24" height="18" alt="Russia" title="Russia"> <img src="https://flagcdn.com/24x18/pk.png" srcset="https://flagcdn.com/48x36/pk.png 2x" width="24" height="18" alt="Pakistan" title="Pakistan"> <img src="https://flagcdn.com/24x18/id.png" srcset="https://flagcdn.com/48x36/id.png 2x" width="24" height="18" alt="Indonesia" title="Indonesia"> <img src="https://flagcdn.com/24x18/de.png" srcset="https://flagcdn.com/48x36/de.png 2x" width="24" height="18" alt="Germany" title="Germany"> <img src="https://flagcdn.com/24x18/jp.png" srcset="https://flagcdn.com/48x36/jp.png 2x" width="24" height="18" alt="Japan" title="Japan"> <img src="https://flagcdn.com/24x18/ke.png" srcset="https://flagcdn.com/48x36/ke.png 2x" width="24" height="18" alt="Kenya" title="Kenya"> <img src="https://flagcdn.com/24x18/tr.png" srcset="https://flagcdn.com/48x36/tr.png 2x" width="24" height="18" alt="Türkiye" title="Türkiye"> <img src="https://flagcdn.com/24x18/vn.png" srcset="https://flagcdn.com/48x36/vn.png 2x" width="24" height="18" alt="Vietnam" title="Vietnam"> <img src="https://flagcdn.com/24x18/kr.png" srcset="https://flagcdn.com/48x36/kr.png 2x" width="24" height="18" alt="South Korea" title="South Korea"> <img src="https://flagcdn.com/24x18/ir.png" srcset="https://flagcdn.com/48x36/ir.png 2x" width="24" height="18" alt="Iran" title="Iran"> <img src="https://flagcdn.com/24x18/th.png" srcset="https://flagcdn.com/48x36/th.png 2x" width="24" height="18" alt="Thailand" title="Thailand"> <img src="https://flagcdn.com/24x18/pl.png" srcset="https://flagcdn.com/48x36/pl.png 2x" width="24" height="18" alt="Poland" title="Poland"> <img src="https://flagcdn.com/24x18/ua.png" srcset="https://flagcdn.com/48x36/ua.png 2x" width="24" height="18" alt="Ukraine" title="Ukraine"> <img src="https://flagcdn.com/24x18/mm.png" srcset="https://flagcdn.com/48x36/mm.png 2x" width="24" height="18" alt="Myanmar" title="Myanmar"> <img src="https://flagcdn.com/24x18/ro.png" srcset="https://flagcdn.com/48x36/ro.png 2x" width="24" height="18" alt="Romania" title="Romania"> <img src="https://flagcdn.com/24x18/nl.png" srcset="https://flagcdn.com/48x36/nl.png 2x" width="24" height="18" alt="Netherlands" title="Netherlands"> <img src="https://flagcdn.com/24x18/my.png" srcset="https://flagcdn.com/48x36/my.png 2x" width="24" height="18" alt="Malaysia" title="Malaysia"> <img src="https://flagcdn.com/24x18/ph.png" srcset="https://flagcdn.com/48x36/ph.png 2x" width="24" height="18" alt="Philippines" title="Philippines"> <img src="https://flagcdn.com/24x18/ng.png" srcset="https://flagcdn.com/48x36/ng.png 2x" width="24" height="18" alt="Nigeria" title="Nigeria"> <img src="https://flagcdn.com/24x18/et.png" srcset="https://flagcdn.com/48x36/et.png 2x" width="24" height="18" alt="Ethiopia" title="Ethiopia"> <img src="https://flagcdn.com/24x18/uz.png" srcset="https://flagcdn.com/48x36/uz.png 2x" width="24" height="18" alt="Uzbekistan" title="Uzbekistan"> <img src="https://flagcdn.com/24x18/az.png" srcset="https://flagcdn.com/48x36/az.png 2x" width="24" height="18" alt="Azerbaijan" title="Azerbaijan"> <img src="https://flagcdn.com/24x18/lk.png" srcset="https://flagcdn.com/48x36/lk.png 2x" width="24" height="18" alt="Sri Lanka" title="Sri Lanka"> <img src="https://flagcdn.com/24x18/np.png" srcset="https://flagcdn.com/48x36/np.png 2x" width="24" height="18" alt="Nepal" title="Nepal"> <img src="https://flagcdn.com/24x18/kh.png" srcset="https://flagcdn.com/48x36/kh.png 2x" width="24" height="18" alt="Cambodia" title="Cambodia"> <img src="https://flagcdn.com/24x18/gr.png" srcset="https://flagcdn.com/48x36/gr.png 2x" width="24" height="18" alt="Greece" title="Greece"> <img src="https://flagcdn.com/24x18/cz.png" srcset="https://flagcdn.com/48x36/cz.png 2x" width="24" height="18" alt="Czechia" title="Czechia"> <img src="https://flagcdn.com/24x18/hu.png" srcset="https://flagcdn.com/48x36/hu.png 2x" width="24" height="18" alt="Hungary" title="Hungary"> <img src="https://flagcdn.com/24x18/se.png" srcset="https://flagcdn.com/48x36/se.png 2x" width="24" height="18" alt="Sweden" title="Sweden"> <img src="https://flagcdn.com/24x18/il.png" srcset="https://flagcdn.com/48x36/il.png 2x" width="24" height="18" alt="Israel" title="Israel"> <img src="https://flagcdn.com/24x18/dk.png" srcset="https://flagcdn.com/48x36/dk.png 2x" width="24" height="18" alt="Denmark" title="Denmark"> <img src="https://flagcdn.com/24x18/fi.png" srcset="https://flagcdn.com/48x36/fi.png 2x" width="24" height="18" alt="Finland" title="Finland"> <img src="https://flagcdn.com/24x18/no.png" srcset="https://flagcdn.com/48x36/no.png 2x" width="24" height="18" alt="Norway" title="Norway"> <img src="https://flagcdn.com/24x18/sk.png" srcset="https://flagcdn.com/48x36/sk.png 2x" width="24" height="18" alt="Slovakia" title="Slovakia"> <img src="https://flagcdn.com/24x18/bg.png" srcset="https://flagcdn.com/48x36/bg.png 2x" width="24" height="18" alt="Bulgaria" title="Bulgaria"> <img src="https://flagcdn.com/24x18/hr.png" srcset="https://flagcdn.com/48x36/hr.png 2x" width="24" height="18" alt="Croatia" title="Croatia"> <img src="https://flagcdn.com/24x18/rs.png" srcset="https://flagcdn.com/48x36/rs.png 2x" width="24" height="18" alt="Serbia" title="Serbia"> <img src="https://flagcdn.com/24x18/lt.png" srcset="https://flagcdn.com/48x36/lt.png 2x" width="24" height="18" alt="Lithuania" title="Lithuania"> <img src="https://flagcdn.com/24x18/tw.png" srcset="https://flagcdn.com/48x36/tw.png 2x" width="24" height="18" alt="Taiwan" title="Taiwan"> <img src="https://flagcdn.com/24x18/pt.png" srcset="https://flagcdn.com/48x36/pt.png 2x" width="24" height="18" alt="Portugal" title="Portugal"> <img src="https://flagcdn.com/24x18/ge.png" srcset="https://flagcdn.com/48x36/ge.png 2x" width="24" height="18" alt="Georgia" title="Georgia">
-完整的语言列表在 [`client/src/i18n/locale-config.ts`](../../../client/src/i18n/locale-config.ts)。
+完整的语言列表在 [`client/src/i18n/locale-config.ts`](client/src/i18n/locale-config.ts)。
最初的六种语言经过人工校对;较新的那些是机器翻译,并随着母语者提交修正而不断改进。改一个字符串的 PR 就是很好的第一次贡献。
-翻译文件以扁平 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。
+翻译文件以扁平 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/i18n/01-translating.md](../01-translating.md),提交翻译前请先过一遍,这样 README 和仪表盘里的说法能对得上。
+中文的术语约定见 [docs/i18n/01-translating.md](docs/TRANSLATION.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/01-rest-api.md](docs/api/01-rest-api.md)**。每个响应都带一个 `X-Routed-Via: <平台>/<模型>` 头,你可以据此看出实际是哪家提供方处理的。
+流式、`auto:*` 路由策略、工具调用、视觉输入、Gemini 的 Google 搜索接地、嵌入,以及 Anthropic Messages 接口,连同各自的 curl 和 Python 示例,全都在 **[docs/en/api/01-rest-api.md](docs/en/api/01-rest-api.md)**。每个响应都带一个 `X-Routed-Via: <平台>/<模型>` 头,你可以据此看出实际是哪家提供方处理的。
## 截图
@@ -271,39 +271,39 @@ print("Routed via:", resp.headers.get("x-routed-via"))
选一种路由策略,看着每月词元额度在整个提供方队列上被填满。每个模型都显示实时的稳定性、速度和智能评分,下面的顺序就是当前请求的路由顺序。
-![模型页](../../../repo-assets/models.png)
+![模型页](repo-assets/models.png)
### 密钥
管理提供方凭据,并拿到你的应用要用的统一 API 密钥。每个密钥都有一个状态点,以及最近一次健康检查的时间。
-![密钥页](../../../repo-assets/keys.png)
+![密钥页](repo-assets/keys.png)
### 试验台
通过路由器发一条聊天补全请求,看看是哪家提供方处理的,模型 ID 和延迟就印在消息上。可以用按钮、拖放或粘贴来添加附件:图片(PNG/JPEG/WebP/GIF)会在浏览器里先缩小,再作为图像内容块发给具备视觉能力的模型;文本文件(TXT/MD/CSV/JSON/LOG)则以代码块的形式内联进提示词。
-![试验台页](../../../repo-assets/playground.png)
+![试验台页](repo-assets/playground.png)
### 分析
请求量、成功率、输入与输出词元、平均延迟,以及按提供方的细分,覆盖 24 小时 / 7 天 / 30 天 / 90 天窗口。
-![分析页](../../../repo-assets/analytics.png)
+![分析页](repo-assets/analytics.png)
## 工作原理
-![一个请求进去,最合适的免费模型出来 —— 带实时评分、冷却和额度跟踪的回退链](../../../repo-assets/router-flow.png)
+![一个请求进去,最合适的免费模型出来 —— 带实时评分、冷却和额度跟踪的回退链](repo-assets/router-flow.png)
-一个请求进去,最合适的免费模型出来:路由器挑出优先级最高、密钥健康且未超出任何限流的模型,在内存中解密密钥并调用提供方;遇到 429/5xx 就让那个密钥进入冷却,然后重试你链路上的下一个模型。组件走查、路由内部实现和运维细节都在 **[docs/architecture.md](../../architecture.md)**。
+一个请求进去,最合适的免费模型出来:路由器挑出优先级最高、密钥健康且未超出任何限流的模型,在内存中解密密钥并调用提供方;遇到 429/5xx 就让那个密钥进入冷却,然后重试你链路上的下一个模型。组件走查、路由内部实现和运维细节都在 **[docs/architecture.md](docs/en/architecture/00-high-level-index.md)**。
## 局限性
-叠加免费额度是有实实在在的代价的:没有前沿模型,延迟不稳定,没有 SLA。而且到了一天的后半段,顶级模型陆续触及当日上限,这个端点的实际智能水平会下滑,然后在 UTC 午夜重置。在拿它做任何正经东西之前,请先读一遍 **[docs/architecture.md#limitations](../../architecture.md#limitations)** 里那份诚实的清单。
+叠加免费额度是有实实在在的代价的:没有前沿模型,延迟不稳定,没有 SLA。而且到了一天的后半段,顶级模型陆续触及当日上限,这个端点的实际智能水平会下滑,然后在 UTC 午夜重置。在拿它做任何正经东西之前,请先读一遍 **[docs/architecture.md#limitations](docs/en/architecture/00-high-level-index.md#limitations)** 里那份诚实的清单。
## 参与贡献
-非常欢迎贡献者!开发流程、PR 要求,以及关于 AI/LLM 辅助贡献的政策(简版:欢迎,质量标准和其他 PR 一样),都在 [CONTRIBUTING.md](../../../CONTRIBUTING.md)。适合上手的第一个 PR:
+非常欢迎贡献者!开发流程、PR 要求,以及关于 AI/LLM 辅助贡献的政策(简版:欢迎,质量标准和其他 PR 一样),都在 [CONTRIBUTING.md](CONTRIBUTING.md)。适合上手的第一个 PR:
- **加一家提供方** —— 复制 `server/src/providers/openai-compat.ts` 作为模板,在 `server/src/providers/index.ts` 里接上,在 `server/src/db/index.ts` 里种下它的模型,并在 `server/src/__tests__/providers/` 加一个测试。
- **加一个接口** —— moderations 以及其他 OpenAI 兼容接口。提供方基类可以扩展新方法,各适配器声明自己支持哪些。
@@ -311,21 +311,21 @@ print("Routed via:", resp.headers.get("x-routed-via"))
- **打磨仪表盘** —— 分析页的图表、密钥轮换的交互、从 `.env` 批量导入密钥。
- **文档** —— 更多示例、Go/Rust 等语言的客户端片段、Docker 或 Fly 的部署配方。
-`npm install && npm run dev` 就能起来:服务在 :3001,仪表盘在 :5173,两边都有热更新。PR 应当包含测试、保持现有测试套件通过(`npm test`),并遵循仓库里已有的 `.editorconfig` 和 tsconfig 默认配置。数据库迁移流程和完整的贡献者循环见 [CONTRIBUTING.md](../../../CONTRIBUTING.md)。
+`npm install && npm run dev` 就能起来:服务在 :3001,仪表盘在 :5173,两边都有热更新。PR 应当包含测试、保持现有测试套件通过(`npm test`),并遵循仓库里已有的 `.editorconfig` 和 tsconfig 默认配置。数据库迁移流程和完整的贡献者循环见 [CONTRIBUTING.md](CONTRIBUTING.md)。
### 贡献者
-约 90 位贡献者的头像墙维护在[英文 README](../../../README.md#contributors) 里。它几乎每次合并都会变动,所以只保留一份,不在各语言版本中重复。
+约 90 位贡献者的头像墙维护在[英文 README](README.md#contributors) 里。它几乎每次合并都会变动,所以只保留一份,不在各语言版本中重复。
## 免责声明
**本项目用于个人实验和学习,不适用于生产环境。** 免费额度的存在是为了让开发者拿来做原型;它们不是稳定、有支持的推理基础设施,也不该被当成这种东西。如果你要在 FreeLLMAPI 之上做真正的产品,上线前请换成付费 API。你和每家上游提供方之间的关系,受你注册账号时接受的条款约束;流量经由本项目代理时这些条款依然适用,遵守它们是你的责任。
-各家提供方的服务条款如何看待一个个人的、单用户的代理,在 2026 年 5 月逐家审查过,结论在 [docs/architecture.md#terms-of-service-review](../../architecture.md#terms-of-service-review)。
+各家提供方的服务条款如何看待一个个人的、单用户的代理,在 2026 年 5 月逐家审查过,结论在 [docs/architecture.md#terms-of-service-review](docs/en/architecture/00-high-level-index.md#terms-of-service-review)。
## 许可证
-[MIT](../../../LICENSE)
+[MIT](LICENSE)
---
diff --git a/cli/README.md b/cli/README.md
index eaea3729..6df89051 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -58,11 +58,11 @@ them into the child process environment for that run only.
## Requirements
Node.js >= 20.18. A running FreeLLMAPI gateway
-([install guide](https://github.com/tashfeenahmed/freellmapi/blob/main/docs/install.md)).
+([install guide](https://github.com/tashfeenahmed/freellmapi/blob/main/docs/en/install/01-install.md)).
## Links
-- [Clients & coding agents guide](https://github.com/tashfeenahmed/freellmapi/blob/main/docs/clients/01-agent-clients.md)
+- [Clients & coding agents guide](https://github.com/tashfeenahmed/freellmapi/blob/main/docs/en/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
index ffe962d2..20c8cbfc 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -1,7 +1,32 @@
# Changelog
+## 2026-09-02 — Per-language structure
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `c108132` | 2026-09-02 | scaffold per-language en/ and zh-cn/ top-level |
+| `7378adc` | 2026-09-02 | move English domains under en/ (17 domains, git mv) |
+| `cbb2620` | 2026-09-02 | fix link depths after move (0 broken in en/) |
+| `91c1776` | 2026-09-02 | migrate Chinese translations to zh-cn/ (10 domains) |
+| `ab0d0f9` | 2026-09-02 | obliterate i18n wrapper — simple /docs/{en,zh-cn} |
+| `9c679bd` | 2026-09-02 | fix zh-cn link depths |
+| `4761a0b` | 2026-09-02 | fix remaining link depths |
+| `5f887aa` | 2026-09-02 | translate cli and desktop domains to zh-cn |
+| `13ca740` | 2026-09-02 | translate proxy, fallback, glossary to zh-cn |
+| `a0a4df7` | 2026-09-02 | translate troubleshooting to zh-cn |
+
+
+
Revision history for `docs/`, derived from git commits touching this directory. Most recent first.
+## 2026-09-02
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `c2114c0` | 2026-09-02 | docs(proxy): create proxy domain and move Fetch Relay into it — `01-fetch-relay.md` moved from flat `fetch-relay.md`, `detectSystemProxy()` OS auto-detect, `TRUST_PROXY` |
+| `26f71dd` | 2026-09-02 | docs(env): cover `PROXY_MODE`, `FETCH_RELAY_TOKEN`, `TRUST_PROXY`, `QUOTA_OBSERVATIONS_*`, `IDEMPOTENCY_TTL_MS` — full precedence chain, callout boxes |
+| `8bd3acd` | 2026-09-02 | docs(api): document Idempotency-Key safe retries (`02-idempotency.md`) — replay/409/miss, fingerprint, curl example |
+
## 2026-08-25
| Commit | Date | Summary |
diff --git a/docs/OVERVIEW.md b/docs/OVERVIEW.md
index 87c77fd7..7a5bd52c 100644
--- a/docs/OVERVIEW.md
+++ b/docs/OVERVIEW.md
@@ -2,33 +2,20 @@
## 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.
+This file is the domain index for `docs/` — a complete file map of every guide and domain folder (install, API, clients, CLI, compression, architecture deep-dives, env, proxy, deployment, providers, testing, fallback, logs, desktop, troubleshooting, glossary, 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).
+For getting started as a user, see [en/README.md](en/README.md) (English 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. |
+| [en/](en/OVERVIEW.md) | **English** — all domains (api with 00-high-level-index, cli, clients, desktop, env, fallback, glossary, install, logs, proxy, providers, testing, troubleshooting). |
+| [zh-cn/](zh-cn/OVERVIEW.md) | **简体中文** — Chinese translations (mirrors `en/`, see `en/` for authoritative source; `zh-cn/` currently stubs — see `i18n/` for coverage). |
+| [TRANSLATION.md](TRANSLATION.md) | Translating: rules for locale files, the validator, and the settled 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 15fa0a82..e7d92d93 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -1,30 +1,8 @@
-**English** · [简体中文](i18n/zh-CN/docs/README.md)
-
# FreeLLMAPI documentation
-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/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.
-- [Database migrations](../server/src/db/README.md) — create, apply, inspect, and roll back schema migrations.
+Pick a language:
-## Website assets in this directory
+- **English:** [docs/en/README.md](en/README.md)
+- **简体中文:** [docs/zh-cn/README.md](zh-cn/README.md)
-- [`index.html`](index.html) — project landing page.
-- [`install.sh`](install.sh) — Unix Docker bootstrap script.
-- [`install.ps1`](install.ps1) — PowerShell bootstrap script.
-- [`success.html`](success.html) — post-install success page.
+Translation guide: [TRANSLATION.md](TRANSLATION.md). Layout: `docs/<lang>/<domain>/NN-topic.md`, every domain carries an `OVERVIEW.md` and a `CHANGELOG.md`.
diff --git a/docs/i18n/01-translating.md b/docs/TRANSLATION.md
similarity index 97%
rename from docs/i18n/01-translating.md
rename to docs/TRANSLATION.md
index e53d586c..e73fb2ae 100644
--- a/docs/i18n/01-translating.md
+++ b/docs/TRANSLATION.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](README.md). The terminology table below applies to both.
+covered in [TRANSLATION.md](TRANSLATION.md) itself. The terminology table below applies to both.
## Before you open a PR
diff --git a/docs/api.md b/docs/api.md
new file mode 100644
index 00000000..447b3e09
--- /dev/null
+++ b/docs/api.md
@@ -0,0 +1,3 @@
+# Moved
+
+This page now lives at **[docs/en/api/01-rest-api.md](en/api/01-rest-api.md)** (中文: [docs/zh-cn/api/01-rest-api.md](zh-cn/api/01-rest-api.md)).
diff --git a/docs/api/01-rest-api.md b/docs/api/01-rest-api.md
index 97de6e1a..5db15178 100644
--- a/docs/api/01-rest-api.md
+++ b/docs/api/01-rest-api.md
@@ -1,450 +1,3 @@
-**English** · [简体中文](../i18n/zh-CN/docs/api/01-rest-api.md)
+# Moved
-# API reference
-
-[← 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`.
-
-- [Chat completions](#chat-completions)
-- [Routing strategies (`auto:*`)](#routing-strategies-auto)
-- [Model listing](#model-listing)
-- [Streaming](#streaming)
-- [Tool calling](#tool-calling)
-- [Gemini Google Search grounding](#gemini-google-search-grounding)
-- [Native Gemini API](#native-gemini-api)
-- [Ollama emulation](#ollama-emulation)
-- [Revocable URL tokens](#revocable-url-tokens)
-- [Vision / image input](#vision--image-input)
-- [Document attachments](#document-attachments)
-- [Images, video & text-to-speech](#images-video--text-to-speech)
-- [Fusion (multi-model synthesis)](#fusion-multi-model-synthesis)
-- [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
-
-**Python**
-
-```python
-from openai import OpenAI
-
-client = OpenAI(
- base_url="http://localhost:3001/v1",
- api_key="freellmapi-your-unified-key",
-)
-
-resp = client.chat.completions.create(
- model="auto", # let the router pick; or specify e.g. "gemini-2.5-flash"
- messages=[{"role": "user", "content": "Summarise the fall of Rome in one sentence."}],
-)
-print(resp.choices[0].message.content)
-print("Routed via:", resp.headers.get("x-routed-via"))
-```
-
-**curl**
-
-```bash
-curl http://localhost:3001/v1/chat/completions \
- -H "Authorization: Bearer freellmapi-your-unified-key" \
- -H "Content-Type: application/json" \
- -d '{
- "model": "auto",
- "messages": [{"role": "user", "content": "hi"}]
- }'
-```
-
-## Routing strategies (`auto:*`)
-
-Plain `auto` follows your active fallback chain. Add a suffix to steer a single request instead — no dashboard changes needed:
-
-- `auto:smart` — favor the highest-intelligence models
-- `auto:fast` — favor measured speed (throughput and time-to-first-byte)
-- `auto:cheap` — budget-leaning; currently the same blend as `balanced` (everything in the pool is already free)
-- `auto:reliable` — favor recent success rate
-- `auto:balanced` — the default blend (reliability first, speed and intelligence split the rest)
-
-These rank **every enabled model**, ignoring your chain order. Common synonyms resolve too (`auto:fastest`, `auto:speed`, `auto:smartest`, `auto:cheapest`, `auto:budget`, …), and the whole model string is case-insensitive.
-
-```bash
-curl http://localhost:3001/v1/chat/completions \
- -H "Authorization: Bearer freellmapi-your-unified-key" \
- -H "Content-Type: application/json" \
- -d '{
- "model": "auto:fast",
- "messages": [{"role": "user", "content": "hi"}]
- }'
-```
-
-`auto:<profile-name>` routes through a named profile's chain instead of the active one, so different tools can use different chains through the same key:
-
-```bash
-curl http://localhost:3001/v1/chat/completions \
- -H "Authorization: Bearer freellmapi-your-unified-key" \
- -H "Content-Type: application/json" \
- -d '{
- "model": "auto:coding",
- "messages": [{"role": "user", "content": "Write a binary search in Rust."}]
- }'
-```
-
-An unknown profile name returns a clear `400` rather than silently falling back. Profiles are named fallback chains (see [Features](../README.md#features)) — create and switch them from the dashboard; whichever is active is what plain `auto` uses.
-
-## Model listing
-
-`GET /v1/models` lists the whole catalog, including models you cannot call yet, so a client can show what exists as well as what is connected. `?available=true` (aliases `?connected=true`, `?ready=true`) narrows to models that can serve a request now.
-
-Each catalog entry also carries `execution_status`, a live answer to "would a request work right now":
-
-- `ready` — at least one key can actually serve it: enabled, healthy or not yet probed, not scoped away from this model, not on a rate-limit cooldown, and inside its rate and token windows. A key whose `status` is still `unknown` counts as ready, because probing is lazy and a fresh key is usable until something says otherwise.
-- `needsKey` — the model is disabled, or no enabled key matches it at all.
-- `exhausted` — keys match the model but every one of them is blocked at this moment, so a request would fail immediately. This is the state a burst of 429s produces, and it clears on its own when the cooldowns expire.
-
-`?execution_status=ready` (also `needsKey`, `exhausted`; matched case-insensitively) narrows the catalog rows to one status, so an agent can ask for models it can call without reading the whole list. An unrecognised value filters nothing. Like `?available=`, the filter applies only to catalog rows: `auto`, `fusion` and the `auto:<profile>` chains are router entries rather than models with keys of their own, and are always listed.
-
-```bash
-curl "http://localhost:3001/v1/models?execution_status=ready" \
- -H "Authorization: Bearer freellmapi-your-unified-key"
-```
-
-## Streaming
-
-```python
-stream = client.chat.completions.create(
- model="auto",
- messages=[{"role": "user", "content": "Stream me a haiku about SQLite."}],
- stream=True,
-)
-for chunk in stream:
- print(chunk.choices[0].delta.content or "", end="", flush=True)
-```
-
-## Tool calling
-
-Pass OpenAI-style `tools` and `tool_choice`; the assistant response round-trips back through the proxy exactly like the OpenAI API. Multi-step flows (assistant `tool_calls` → `tool` role follow-up → final answer) work across every provider the router can reach.
-
-```python
-tools = [{
- "type": "function",
- "function": {
- "name": "get_weather",
- "description": "Get current weather for a city.",
- "parameters": {
- "type": "object",
- "properties": {"city": {"type": "string"}},
- "required": ["city"],
- },
- },
-}]
-
-# 1. Model asks for a tool call
-first = client.chat.completions.create(
- model="auto",
- messages=[{"role": "user", "content": "What's the weather in Karachi?"}],
- tools=tools,
- tool_choice="required",
-)
-call = first.choices[0].message.tool_calls[0]
-
-# 2. You execute the tool, feed the result back
-final = client.chat.completions.create(
- model="auto",
- messages=[
- {"role": "user", "content": "What's the weather in Karachi?"},
- first.choices[0].message,
- {"role": "tool", "tool_call_id": call.id, "content": '{"temp_c": 32, "cond": "sunny"}'},
- ],
- tools=tools,
-)
-print(final.choices[0].message.content)
-```
-
-Works with `stream=True` as well — you'll get `delta.tool_calls` chunks followed by a `finish_reason: "tool_calls"` close. Under the hood, OpenAI-compatible providers (Groq, Cerebras, Mistral, OpenRouter, GitHub Models, HuggingFace, Cloudflare, Cohere compat) get the request passed through; Gemini requests get translated into Google's `functionDeclarations` / `functionResponse` shape and the response is translated back.
-
-## Gemini Google Search grounding
-
-Google's models can ground their answers in live Google Search results. Since the OpenAI wire format has no way to express that, request a tool named `google_search` and the Google provider translates it into Gemini's native grounding tool. It can be sent on its own or alongside your normal function tools.
-
-```python
-resp = client.chat.completions.create(
- model="gemini-2.5-flash", # pin a Google model so the request routes there
- messages=[{"role": "user", "content": "Who won the F1 race this weekend?"}],
- tools=[{"type": "function", "function": {"name": "google_search", "parameters": {}}}],
-)
-print(resp.choices[0].message.content)
-```
-
-## Native Gemini API
-
-Gemini SDKs and Gemini CLI can use the native `/v1beta` surface:
-
-- `GET /v1beta/models`
-- `GET /v1beta/models/{model}`
-- `POST /v1beta/models/{model}:generateContent`
-- `POST /v1beta/models/{model}:streamGenerateContent` (`?alt=sse` for Gemini CLI)
-- `POST /v1beta/models/{model}:countTokens`
-
-```bash
-curl "http://localhost:3001/v1beta/models/gemini-2.5-flash:generateContent" \
- -H "x-goog-api-key: freellmapi-your-unified-key" \
- -H "Content-Type: application/json" \
- -d '{"contents":[{"role":"user","parts":[{"text":"hello"}]}]}'
-```
-
-Gemini model names like `gemini-2.5-flash` resolve through the Gemini family map (Keys → Gemini model mapping) rather than the catalog directly, so they route to Auto or whichever catalog model each family is pinned to. Catalog ids work verbatim too.
-
-`contents` text, inline data, function calls/responses, system instructions,
-function declarations, structured JSON output, generation controls, and
-thinking budgets translate into the same internal chat/fallback pipeline.
-Bearer auth works too. Gemini's `?key=` query parameter is accepted only below
-`/v1beta`; prefer a header because URL credentials leak into history and logs.
-
-## Ollama emulation
-
-The opt-in Ollama surface implements tags, chat, generate, show, version, embed,
-and legacy embeddings under `/api/*`. Streaming is Ollama-compatible NDJSON.
-It defaults to `off`; choose `open-loopback` or `key-required` on
-**Keys → Agents**. Open-loopback checks the direct socket peer, so desktop LAN
-access cannot silently turn it into an unauthenticated LAN endpoint.
-
-The dashboard also owns `/api/embeddings`. A request with a valid dashboard
-session continues to the dashboard handler; all other requests at that exact
-path are treated as Ollama legacy embeddings and follow the emulation policy.
-
-## Revocable URL tokens
-
-Headerless clients can mirror models, chat completions, Responses, and
-Ollama-style chat/tags under `/v1/t/{token}/…`. These tokens are random,
-stored only as hashes, separately revocable, and are not the unified key.
-Create/revoke them on **Keys → Agents**.
-
-Treat them as sensitive anyway: URLs are routinely retained by shell history,
-reverse proxies, browser history, and telemetry. Revocation is immediate.
-
-## Vision / image input
-
-Send images with the standard OpenAI `image_url` content blocks (base64 `data:` URLs or `http(s)` URLs). When a request contains an image, the router restricts itself to **vision-capable models** and ignores text-only ones. Vision models are tagged with a **Vision** badge on the Fallback Chain page; the current set includes Gemini (2.5 / 3.x), Llama 4 Scout/Maverick (Groq, NVIDIA), GLM-4.6V Flash (Z.ai), Nemotron Nano 12B VL (OpenRouter), and GitHub's GPT-4o / GPT-4.1.
-
-```python
-resp = client.chat.completions.create(
- model="auto", # auto-routes to a vision model
- messages=[{
- "role": "user",
- "content": [
- {"type": "text", "text": "What's in this image?"},
- {"type": "image_url", "image_url": {"url": "data:image/png;base64,<...>"}},
- ],
- }],
-)
-print(resp.choices[0].message.content)
-```
-
-If no vision-capable model is enabled in your Fallback Chain, an image request returns a clear `422` (`code: "no_vision_model"`) rather than silently dropping the image. (Image input on `/v1/responses` isn't supported yet — use `/v1/chat/completions`.)
-
-## Document attachments
-
-Anthropic's `document` content blocks are accepted on `/v1/messages` when their source is already text:
-
-```json
-{"type": "document", "title": "contract.txt",
- "source": {"type": "text", "media_type": "text/plain", "data": "PAYMENT TERMS: net 30."}}
-```
-
-`text` and `content` sources are inlined into the prompt, wrapped in a fence tagged with a hash of the document body so the model can tell quoted material from your instructions. The tag is derived from the content rather than randomized, so a repeated attachment keeps the prompt prefix stable and stays cacheable.
-
-**Binary sources — `base64` (PDF, DOCX, XLSX…) and `url` — return a `400`.** No provider in the pool accepts them, and there is no local converter, so the honest answer is to refuse: forwarding the request would drop the attachment and produce a confident answer about a document the model never saw. The rejection happens before routing, so it spends no provider quota. Send the extracted text instead.
-
-`url` sources are refused rather than fetched on your behalf; making the proxy retrieve arbitrary URLs would turn it into a request forwarder for whatever a client names.
-
-## Images, video & text-to-speech
-
-`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 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 \
- -H "Authorization: Bearer freellmapi-your-unified-key" \
- -H "Content-Type: application/json" \
- -d '{"model":"auto","prompt":"a sunrise over a quiet lake","duration":6}' \
- --output video.mp4
-```
-
-## 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. Panel, judge, and strategy are configurable on the dashboard's **Fusion** page or per request via the `fusion` field; each sub-call goes through normal routing, quotas, and analytics.
-
-## Response headers
-
-Every response carries an `X-Routed-Via: <platform>/<model>` header so you can see which provider actually served each call. If a request fell over between providers, you'll also see `X-Fallback-Attempts: N` and `X-Fallback-Trail`, which names each hop that failed and why:
-
-```
-X-Fallback-Attempts: 2
-X-Fallback-Trail: groq/llama-3.3-70b key1=rate_limited; google/gemini-2.5-flash key2=timeout
-```
-
-`X-Fallback-Detail` adds what each of those hops **cost**, which is the part you cannot reconstruct from the trail — a request answered in 40s reads identically whether one provider stalled for 39 seconds or four failed fast:
-
-```
-X-Fallback-Detail: groq/llama-3.3-70b key1=rate_limited t=0+39000ms msg=Groq API error 429: rate limit; google/gemini-2.5-flash key2=timeout t=39000+12ms
-```
-
-`t=<start>+<duration>ms` is the offset from the start of the failover chain and how long that hop ran. `msg=` is the provider's error, redacted and truncated; it is last in each record, and any semicolon inside it becomes a comma so `; ` stays an unambiguous record separator.
-
-The detail header is **off by default** — it puts hop timings and provider error text on the response. Turn it on with `FALLBACK_DETAIL_HEADER=1` or the `expose_fallback_detail_header` settings key, which takes precedence. Both headers list at most ten hops and then a `; +N more` marker.
-
-Only hops that already **failed** can appear. The hop actually serving your request is recorded after its response finishes — after the JSON is sent, or after the stream closes — so its duration does not exist while the headers are still open. Use `X-Routed-Via` to see which provider that was.
-
-HTTP headers only carry printable ASCII, so a model id with characters outside that range (a Chinese name from a relay catalog, for example) is percent-encoded in the header — run the value through `decodeURIComponent` (or `urllib.parse.unquote`) to read it back.
-
-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/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`.
-
-`X-FreeLLM-Task-Type: code|chat|auto` tells the router what kind of turn this is, so it can bias the routing weights: `code` trades some of the speed weight for intelligence (a wrong answer costs more than a slow one), `chat` does the reverse. It is a soft preference only — capability gates, the failover chain and the model catalog are untouched, and the shift is 30% of one axis by default. The default is `auto`: tool-bearing requests and messages carrying unambiguous code markers (a fenced block, a declaration, a stack frame, a `file.ts:214` reference) are treated as `code`, and everything else keeps the preset weights exactly as configured. The `fastest`, `reliable` and `custom` routing strategies ignore the header — those are an explicit operator choice about where on the axis to sit.
-
-How far the shift goes is operator-tunable: `GET /api/settings/task-weight-share` reads the current fraction and `PUT /api/settings/task-weight-share` with `{"share": 0..1}` sets it (default `0.3`). `0` disables the bias while leaving the header itself accepted, and `null` clears the setting back to the default. It takes effect on the next request, with no restart.
-
-## Embeddings
-
-`/v1/embeddings` is OpenAI-compatible, with one deliberate difference from chat routing: **failover never crosses models.** Vectors from different models live in incompatible spaces — silently switching models would corrupt any vector store built on top of the proxy. So embeddings route by **family** (one model identity + dimension), and failover only walks the providers serving that same family.
-
-```python
-resp = client.embeddings.create(
- model="auto", # default family; or a family name like "bge-m3"
- input=["the quick brown fox", "pack my box with five dozen liquor jugs"],
-)
-print(len(resp.data), "vectors of", len(resp.data[0].embedding), "dims")
-```
-
-```bash
-curl http://localhost:3001/v1/embeddings \
- -H "Authorization: Bearer freellmapi-your-unified-key" \
- -H "Content-Type: application/json" \
- -d '{"model": "auto", "input": "hello world"}'
-```
-
-`model` accepts `auto` (the configured default family), a family name, or a provider-specific model id (which resolves to its family). Available families:
-
-| Family (`model`) | Dims | Providers (failover order) |
-| --- | --- | --- |
-| `gemini-embedding-001` *(default)* | 3072 | Google |
-| `text-embedding-3-large` | 3072 | GitHub Models |
-| `text-embedding-3-small` | 1536 | GitHub Models |
-| `embed-v4.0` | 1536 | Cohere |
-| `bge-m3` | 1024 | Cloudflare → Hugging Face |
-| `qwen3-embedding-0.6b` | 1024 | Cloudflare |
-| `nv-embedqa-e5-v5` | 1024 | NVIDIA |
-| `llama-nemotron-embed-1b-v2` | 2048 | NVIDIA |
-| `llama-nemotron-embed-vl-1b-v2` | 2048 | NVIDIA → OpenRouter |
-| `embeddinggemma-300m` | 768 | Cloudflare |
-
-The default family, per-provider toggles, and priorities live on the dashboard's **Models → Embeddings** page. Pick your family once and stick with it for a given vector store — that's the whole point of the family model.
-
-## Anthropic / Claude clients
-
-FreeLLMAPI also speaks Anthropic's Messages API, so anything built for Claude — including **Claude Code** and the official Anthropic SDKs — can run against your free pool. Point the client at your server's **origin** (Anthropic clients append `/v1/messages` themselves) and authenticate with your unified key. Both `x-api-key` and `Authorization: Bearer` are accepted.
-
-```bash
-curl http://localhost:3001/v1/messages \
- -H "x-api-key: freellmapi-your-unified-key" \
- -H "anthropic-version: 2023-06-01" \
- -H "Content-Type: application/json" \
- -d '{
- "model": "claude-sonnet-4-5",
- "max_tokens": 256,
- "messages": [{"role": "user", "content": "hi"}]
- }'
-```
-
-Claude model names map to your free pool on the **Keys → Anthropic** tab: each family (`default`, `opus`, `sonnet`, `haiku`) routes to `auto` (the router picks a free model) or a model you pin. `POST /v1/messages/count_tokens` and a content-negotiated `GET /v1/models` (Anthropic shape when `anthropic-version` is sent) are implemented too. Streaming, system prompts, tool use, and image input all translate across the same router as the OpenAI endpoints.
-
-**Claude Code** — point it at your server and start it:
-
-*On macOS / Linux (Bash):*
-```bash
-export ANTHROPIC_BASE_URL=http://localhost:3001
-export ANTHROPIC_AUTH_TOKEN=freellmapi-your-unified-key # NOT ANTHROPIC_API_KEY
-claude
-```
-
-*On Windows (PowerShell):*
-```powershell
-$env:ANTHROPIC_BASE_URL="http://localhost:3001"
-$env:ANTHROPIC_AUTH_TOKEN="freellmapi-your-unified-key"
-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) |
+This page now lives at **[docs/en/api/01-rest-api.md](../en/api/01-rest-api.md)** (中文: [docs/zh-cn/api/01-rest-api.md](../zh-cn/api/01-rest-api.md)).
diff --git a/docs/architecture.md b/docs/architecture.md
index ac3890e0..df51d500 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -1,96 +1,3 @@
-# Architecture & internals
+# Moved
-[← Back to README](../README.md) · [Documentation index](README.md) · [Deep-dive domain](architecture/OVERVIEW.md)
-
-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)
-- [Not yet supported](#not-yet-supported)
-- [Limitations](#limitations)
-- [Terms of Service review](#terms-of-service-review)
-
-## How it works
-
-![One request in, the best free model out — the fallback chain with live scores, cooldowns, and quota tracking](../repo-assets/router-flow.png)
-
-```
-┌──────────────────┐ Bearer freellmapi-… ┌─────────────────────────┐
-│ OpenAI SDK / │ ──────────────────────▶ │ Express proxy (:3001) │
-│ curl / any │ ◀────────────────────── │ /v1/chat/completions │
-│ OpenAI client │ streamed tokens └────────────┬────────────┘
-└──────────────────┘ │
- ▼
- ┌────────────────────────────────────────────────┐
- │ Router │
- │ 1. Pick highest-priority model that │
- │ (a) has a healthy key and │
- │ (b) is under all its rate limits. │
- │ 2. Decrypt key, call provider SDK. │
- │ 3. On 429/5xx → cooldown + retry next model. │
- └────────────────────────────────────────────────┘
- │
- ┌──────────────┬────────────┬──────────┴─────────┬─────────────┬──────────┐
- ▼ ▼ ▼ ▼ ▼ ▼
- Google Groq Cerebras OpenRouter HF …29 more
-```
-
-- **Router** (`server/src/services/router.ts`) — picks a model per request.
-- **Rate-limit ledger** (`server/src/services/ratelimit.ts`) — in-memory RPM/RPD/TPM/TPD counters backed by SQLite, with cooldowns on 429s.
-- **Provider adapters** (`server/src/providers/*.ts`) — one file per provider, implementing the `Provider` base class: `chatCompletion()` and `streamChatCompletion()`.
-- **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.
-- **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.
-
-> 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
-
-The scope is deliberately narrow. If a feature isn't in the README's feature list and isn't below, assume it isn't there yet.
-
-- **Moderation** (`/v1/moderations`)
-- **`n > 1`** (multiple completions per request)
-- **Per-user billing / multi-tenant auth** — single-user by design
-
-PRs that add any of these are very welcome. See [Contributing](../README.md#contributing).
-
-## Limitations
-
-Stacking free tiers has real trade-offs. Be honest with yourself about them:
-
-- **Quota and availability are the ceiling, not model class.** The catalog does carry frontier-class rows — GPT-5.x, Grok 4.x, Kimi K3, DeepSeek V4 Pro, and Gemini 3.x all show up on somebody's free tier. What you don't get is *sustained* access to them: those are exactly the rows with the smallest daily allowances, the longest queues, and the highest chance of being pulled or paywalled at short notice. Budget for capacity and uptime, not for a capability limit.
-- **Intelligence degrades as the day progresses.** Your top-ranked models (usually Gemini 3.6 Flash, DeepSeek V4, Kimi K2.6) have the lowest daily caps. Once they hit their limits, the router falls down your priority chain to smaller/weaker models. Expect the effective intelligence of the endpoint to drop in the late hours of each day — then reset at UTC midnight.
-- **Latency is highly variable.** Cerebras and Groq are extremely fast; others are not. You get whichever one is available.
-- **Free tiers can change without notice.** Providers regularly tighten, loosen, or remove free tiers. When that happens you'll see 429s or auth errors until the catalog update reaches you — live-feed installs get those fixes within days, free installs on the 30-day trail. Re-seed scripts live in `server/src/scripts/`.
-- **No SLA, by definition.** If you need reliability, use a paid provider with a contract.
-- **Local-first.** There's no multi-tenant auth. Run this for yourself; don't expose it to the internet.
-
-## Terms of Service review
-
-A self-hosted, single-user, personal-use setup was re-reviewed against each provider's ToS (May 2026). Summary:
-
-| Provider | Verdict | Notes |
-|---|---|---|
-| Google Gemini | ⚠️ Caution | March 2026 ToS narrows scope to *"professional or business purposes, not for consumer use"* — a self-hosted developer proxy is still defensible, but the clause is new. |
-| Groq | ✅ Likely OK | GroqCloud Services Agreement permits Customer Application integration. |
-| Cerebras | ✅ Likely OK | Permitted; explicitly forbids selling/transferring API keys. |
-| Mistral | ✅ Likely OK | APIs allowed for personal/internal business use. |
-| OpenRouter | ✅ Likely OK | April 2026 ToS sharpens the no-resale / no-competing-service clause; private single-user proxy still fine. |
-| Cloudflare Workers AI | ⚠️ Ambiguous | No anti-proxy clause; covered by general Self-Serve Subscription Agreement. |
-| NVIDIA NIM | ⚠️ Caution | Trial ToS §1.2 / §1.4: *"evaluation only, not production."* Free access is a recurring 40 RPM rate limit (the 2025 credit system was discontinued), but the evaluation-only scope stands. |
-| GitHub Models | ⚠️ Caution | Free tier explicitly scoped to *"experimentation"* and *"prototyping."* |
-| Cohere | ❌ Avoid | Terms §14 still forbids *"personal, family or household purposes."* |
-| Zhipu (open.bigmodel.cn) | ✅ Likely OK | Personal/non-commercial research carve-out still in the platform docs. |
-| Z.ai (api.z.ai) | ⚠️ Caution | New row — Singapore entity (distinct from Zhipu CN). §III.3(l) anti-traffic-redirect clause could plausibly be read against a proxy; no explicit personal-use carve-out. |
-| Ollama Cloud | ✅ Likely OK | New row — Free plan permits cloud-model access (1 concurrent, 5-hour session caps). No anti-proxy / anti-resale clauses found. *(Integration tracked in #14.)* |
-| OVH AI Endpoints | ✅ Likely OK | New row (June 2026) — anonymous access is officially documented (2 req/min per IP per model). OVH reserves the right to introduce token/consumption caps. |
-| AI Horde | ✅ Likely OK | New row (June 2026) — a free, community-powered commons run by the Haidra non-profit; anonymous use is officially supported (key `0000000000`, lowest queue priority). No anti-proxy / anti-resale clause. The OpenAI proxy is a pilot and may be restricted by usage. *(Integration #345.)* |
-
-Rules of thumb that keep most providers happy: **one account per provider**, **no reselling**, **no sharing your endpoint with other humans**, **don't hammer a free tier as a paid production backend**. This is informational, not legal advice — read each provider's ToS and make your own call.
-
-Removed since the April 2026 review: Moonshot and MiniMax direct integrations were dropped from the catalog (Moonshot — moved to paid only; MiniMax — superseded by the OpenRouter `minimax/minimax-m2.5:free` route).
+This page now lives at **[docs/en/architecture/00-high-level-index.md](en/architecture/00-high-level-index.md)** (中文: [docs/zh-cn/architecture/00-high-level-index.md](zh-cn/architecture/00-high-level-index.md)).
diff --git a/docs/clients/01-agent-clients.md b/docs/clients/01-agent-clients.md
index a8ff52bd..67890341 100644
--- a/docs/clients/01-agent-clients.md
+++ b/docs/clients/01-agent-clients.md
@@ -1,299 +1,3 @@
-# Clients & coding agents
+# Moved
-[← Back to README](../README.md) · [Documentation index](../README.md)
-
-- [OpenAI-compatible clients](#openai-compatible-clients)
-- [Coding agents](#coding-agents)
-- [QwenPaw](#qwenpaw)
-- [Native Gemini clients](#native-gemini-clients)
-- [Ollama clients](#ollama-clients)
-- [Headerless clients](#headerless-clients)
-- [MCP server](#mcp-server)
-- [VS Code ghost-text autocomplete (Continue)](#vs-code-ghost-text-autocomplete-continue)
-- [Context Handoff](#context-handoff)
-
-## OpenAI-compatible clients
-
-Any client that can target an OpenAI-compatible base URL can use FreeLLMAPI:
-
-- **LangChain, LlamaIndex, official OpenAI SDKs**: set `base_url` to
- `http://localhost:3001/v1` and use the unified key from the dashboard.
-- **Local GPU boxes**: add custom OpenAI-compatible endpoints for Ollama,
- llama.cpp, LM Studio, vLLM, or an internal gateway.
-
-## Coding agents
-
-Use the generator instead of hand-editing a client configuration:
-
-```bash
-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
-and create a timestamped backup first. `--profile <name>` creates a named
-Claude/Codex profile. The live `/v1/models` catalog supplies the model ids and
-context windows.
-
-| Agent | Automated command | Manual base URL | Wire |
-| --- | --- | --- | --- |
-| **Claude Code** | `setup-claude` or credential-free-on-disk `launch` | `http://localhost:3001` | Anthropic Messages |
-| **Codex CLI** | `setup-codex` or `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 / legacy 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 (native Gemini also works) |
-| **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`) |
-| **MiMo Code** | `setup-mimo` | `http://localhost:3001/v1` | OpenAI Chat |
-| **AtomCode** | `setup-atomcode` | `http://localhost:3001/v1` | OpenAI Chat (`type = "openai"`) |
-| **QwenPaw** | Manual setup | `http://localhost:3001/v1` | OpenAI Chat (`chat.completions`) |
-| **Cursor** | `setup-cursor` prints the guide | public `https://…/v1` | OpenAI Chat |
-| **Anything else** | `setup-generic` prints a ready block | `http://localhost:3001/v1` | OpenAI Chat |
-
-The root-vs-`/v1` distinction matters: Claude Code expects the server root
-because it appends the Anthropic Messages path. OpenAI-compatible clients in
-this table—including Cline, Aider, Goose, Codex, Continue, OpenCode, Qwen,
-Roo, Kilo, Crush, MiMo Code, AtomCode, QwenPaw, and DeepSeek Harness—expect their configured
-base URL to include `/v1`.
-
-### DeepSeek Harness (`dsh`)
-
-[DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) keeps
-every provider as a route under `llm-pi-ai.providers` in
-`$DSH_HOME/settings.yaml` (`~/.dsh` by default). `setup-dsh` adds a
-`freellmapi` route there — `api: openai-completions`, the gateway's `/v1`
-base URL, and the live catalog as the route's `models` list, which DSH
-requires for a provider its installed catalog does not ship — and makes
-`freellmapi/auto` the default model. The key goes into `$DSH_HOME/.env`
-(mode 0600) as `FREELLMAPI_API_KEY`, the environment layer DSH reads on its
-own, so nothing needs exporting. Both writes are structural merges: other
-routes, comments, and settings in the file are left as they were.
-
-```bash
-npx freellmapi setup-dsh --url http://localhost:3001 --api-key <unified-key>
-npx @deepseek-ai/dsh web
-```
-
-Settings are hot-reloaded, so a running `dsh` uses the route on its next
-request. `--profile <name>` adds a second route (`freellmapi-<name>`) without
-changing the default model; `--model <id>` pins the default. Routes are
-declared text-only — add `input: [text, image]` to a model entry under
-`freellmapi.models` to send it images. `DSH_HOME` is honoured when set.
-
-### MiMo Code (`mimo`)
-
-[MiMo Code](https://mimo.xiaomi.com/mimocode) is an OpenCode derivative, so it
-takes any OpenAI-compatible endpoint as a custom entry under `provider` — an
-`npm` package to speak with (`@ai-sdk/openai-compatible`), the credentials in
-`options`, and a `models` map. `setup-mimo` writes that entry as `freellmapi`
-and names `freellmapi/<model>` as the default `model`.
-
-The file is `config.json` in MiMo's own global config directory:
-`$XDG_CONFIG_HOME/mimocode` (`~/.config/mimocode` on macOS and Linux), or
-`$MIMOCODE_HOME/config` when `MIMOCODE_HOME` is set. That directory merges
-`config.json`, `mimocode.json` and `mimocode.jsonc` in that order, so the
-generated file is the weakest layer and anything you hand-write in
-`mimocode.json` still wins. The write itself is a structural merge, so other
-providers and settings already in `config.json` are left as they were.
-
-```bash
-npx freellmapi setup-mimo --url http://localhost:3001
-export FREELLMAPI_API_KEY=<unified-key>
-mimo
-```
-
-The key is referenced as `{env:FREELLMAPI_API_KEY}`, MiMo's own substitution
-syntax, so it stays out of the config file. There is no `MIMOCODE_API_KEY` or
-`MIMOCODE_BASE_URL`: MiMo's environment variables locate resources and toggle
-features, they are not a general fallback for config fields. Each model is
-declared with the `limit.context` and `limit.output` pair MiMo's schema
-requires, both taken from the live catalog.
-
-### AtomCode (`atomcode`)
-
-[AtomCode](https://atomcode.atomgit.com/docs/en/) is AtomGit's terminal
-coding agent, written in Rust. It reads `~/.atomcode/config.toml`, where a
-root `default_provider` key names one `[providers.<id>]` table and
-`type = "openai"` makes that table speak the OpenAI-compatible wire.
-`setup-atomcode` writes a `[providers.freellmapi]` table — `base_url` on the
-gateway's `/v1`, the unified key as `api_key`, the chosen model and its
-`context_window` from the live catalog — and sets `default_provider` to it.
-The write is a structural merge: the root key is placed above any existing
-tables, only the `freellmapi` table is replaced, and other `[providers.*]`
-tables and settings in the file are left as they were.
-
-```bash
-npx freellmapi setup-atomcode --url http://localhost:3001 --api-key <unified-key>
-atomcode
-```
-
-AtomCode has no environment-variable fallback for the key, so it is written
-into the config file; the file is created with mode 0600 and a timestamped
-backup is taken before an existing one is changed. `--model <id>` pins the
-default model.
-
-### QwenPaw
-
-[QwenPaw](https://github.com/agentscope-ai/QwenPaw) supports custom providers
-that use the OpenAI `chat.completions` API. Start FreeLLMAPI, create or copy a
-unified key from its dashboard, then open **Settings → Models** in the QwenPaw
-Console:
-
-1. Under **Providers**, choose **Add Provider**.
-2. Give it a **Provider ID** such as `freellmapi` and a **Provider Name** such
- as `FreeLLMAPI`, and set the API compatibility mode to OpenAI
- `chat.completions`.
-3. Open the new provider's settings and set **Base URL** to
- `http://localhost:3001/v1` and **API Key** to your FreeLLMAPI unified key.
-4. On the provider's models page, add a model. Use `auto` as the **Model ID**
- to let FreeLLMAPI route the request, or copy a current id from
- `GET http://localhost:3001/v1/models`.
-5. Save, then pick the model as the default (or per chat) and send a test
- message.
-
-If QwenPaw runs in a container, `localhost` refers to that container rather
-than the host running FreeLLMAPI. Use a hostname or host-gateway address that
-the QwenPaw container can reach, while keeping the `/v1` suffix. Do not put the
-unified key in a URL, screenshot, or issue report. See QwenPaw's
-[official model configuration guide](https://qwenpaw.agentscope.io/docs/models)
-for the current Console field names.
-
-## Native Gemini clients
-
-Gemini CLI and Gemini-lineage clients can speak Google's wire format directly:
-
-```bash
-export GOOGLE_GEMINI_BASE_URL=http://localhost:3001
-export GEMINI_API_KEY=freellmapi-your-unified-key
-gemini
-```
-
-The native surface implements `GET /v1beta/models`, model metadata,
-`generateContent`, `streamGenerateContent` (including `?alt=sse`), and
-`countTokens`. Authentication accepts `x-goog-api-key`, Bearer, or Gemini's
-`?key=` fallback. Prefer the header: query credentials leak into history and
-proxy logs.
-
-The **Keys → Agents** tab maps Gemini Pro, Flash, and Flash-Lite family names to
-Auto or a pinned catalog model.
-
-## Ollama clients
-
-Ollama emulation is off by default. Enable one of these modes on
-**Keys → Agents**:
-
-- `open-loopback`: no key on this machine only. The socket peer must be
- `127.0.0.1`/`::1`; enabling desktop LAN access does not widen it.
- **Docker note:** inside a container the socket peer is the Docker bridge
- IP, not loopback, so this mode refuses even host-local traffic through a
- published port — use `key-required` for Docker deployments.
-- `key-required`: clients must send `Authorization: Bearer <unified-key>`.
-
-The exact endpoints are `/api/tags`, `/api/chat`, `/api/generate`, `/api/show`,
-`/api/version`, `/api/embed`, and legacy `/api/embeddings`. Streaming uses
-newline-delimited JSON, not SSE. Point Zed, JetBrains AI Assistant, or another
-Ollama-capable client at `http://localhost:3001`.
-
-## Headerless clients
-
-If a client cannot set headers, create a separately revocable token on
-**Keys → Agents** and use:
-
-```text
-http://localhost:3001/v1/t/<token>/chat/completions
-http://localhost:3001/v1/t/<token>/responses
-http://localhost:3001/v1/t/<token>/models
-```
-
-The same prefix exposes `/api/chat` and `/api/tags`. Never put the unified API
-key in a URL. URL tokens have independent hashes and immediate revocation
-because URLs routinely leak into shell history, reverse-proxy logs, and
-telemetry.
-
-## MCP server
-
-On top of inference, the router is an **MCP server**: agents can introspect it mid-session
-(usable models and the params each one honors, provider health, usage and cache stats,
-routing strategy).
-
-The MCP surface is a setting rather than an always-on endpoint (#925). **Fresh installs
-start with it off**; installs that already had provider keys configured when they upgraded
-keep it on, so an existing Claude Code or Cline session does not break on upgrade. Toggle
-it on the Keys page under **Agent compatibility**, or from the API:
-
-```bash
-curl -X PUT http://localhost:3001/api/settings/enable-mcp \
- -H "Authorization: Bearer <dashboard-token>" -H "Content-Type: application/json" \
- -d '{"enabled": true}'
-```
-
-While it is off, every verb on `/mcp` answers `403` with a JSON-RPC error saying so.
-
-For Claude Code:
-
-```bash
-claude mcp add --transport http freellmapi http://localhost:3001/mcp \
- --header "Authorization: Bearer freellmapi-your-unified-key"
-```
-
-Any MCP client that speaks Streamable HTTP works the same way: point it at `/mcp` with the
-unified key as a Bearer token.
-
-FreeLLMAPI is local-first and single-user by design. Your provider keys stay in
-your SQLite database, encrypted at rest, and requests go from your machine to the
-upstream providers you enabled.
-
-## VS Code ghost-text autocomplete (Continue)
-
-FreeLLMAPI exposes `/v1/completions` for editor autocomplete clients that send legacy OpenAI prompt/suffix requests. Example Continue config:
-
-```yaml
-models:
- - name: FreeLLMAPI Autocomplete
- provider: openai
- model: auto
- apiBase: http://localhost:3001/v1
- apiKey: freellmapi-your-unified-key
- useLegacyCompletionsEndpoint: true
- roles:
- - autocomplete
-```
-
-## Context Handoff
-
-When FreeLLMAPI falls over to a different model mid-conversation (quota, rate limit, cooldown), the new model has no idea it is picking up someone else's task. **Context handoff** adds a single compact `system` message to the outbound request that tells the new model exactly that:
-
-```
-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: …
-```
-
-**Enable it in `.env`:**
-
-```env
-FREELLMAPI_CONTEXT_HANDOFF=on_model_switch
-```
-
-**How it works:**
-
-- Messages per session are stored in memory (TTL: 3 hours).
-- Only injected when the selected model changes for a given session key.
-- Not injected on the first request, on same-model continuations, or if a handoff message is already present.
-- Session key: `X-Session-Id` header if present, otherwise SHA-1 of the first user message (same as sticky sessions).
-- Storage is in-memory only. Nothing is written to disk or logged.
-
-> **Important:** Context Handoff improves continuity for conversations routed through FreeLLMAPI. It cannot recover provider-internal hidden state or messages that were never sent to the proxy.
+This page now lives at **[docs/en/clients/01-agent-clients.md](../en/clients/01-agent-clients.md)** (中文: [docs/zh-cn/clients/01-agent-clients.md](../zh-cn/clients/01-agent-clients.md)).
diff --git a/docs/en/CHANGELOG.md b/docs/en/CHANGELOG.md
new file mode 100644
index 00000000..05dea470
--- /dev/null
+++ b/docs/en/CHANGELOG.md
@@ -0,0 +1,14 @@
+# Changelog — en
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `c108132` | 2026-09-02 | scaffold per-language en/ top-level |
+| `7378adc` | 2026-09-02 | move English domains under en/ (17 domains) |
+| `cbb2620` | 2026-09-02 | fix link depths after move |
+| `07506ed` | 2026-09-02 | fix root flat-file violations and name collisions |
+| `688a88a` | 2026-09-02 | complete desktop, cli, troubleshooting and glossary domains |
+| `8bd3acd` | 2026-09-02 | document Idempotency-Key safe retries |
+| `26f71dd` | 2026-09-02 | cover PROXY_MODE, FETCH_RELAY_TOKEN, TRUST_PROXY, QUOTA_OBSERVATIONS_* |
+| `c2114c0` | 2026-09-02 | create proxy domain and move Fetch Relay into it |
+
+Regenerate: `git log --oneline -- docs/en/`
diff --git a/docs/en/OVERVIEW.md b/docs/en/OVERVIEW.md
new file mode 100644
index 00000000..ad8c4c18
--- /dev/null
+++ b/docs/en/OVERVIEW.md
@@ -0,0 +1,32 @@
+# Docs — English
+
+Language-specific index for English documentation.
+
+## Domains
+
+| Domain | Description |
+| --- | --- |
+| [api/](api/OVERVIEW.md) | API reference: chat completions, streaming, tool calling, vision, embeddings, response headers, Anthropic Messages surface. |
+| [architecture/](architecture/OVERVIEW.md) | Architecture deep-dives: bandit routing & scoring, quota & cooldown engine, streaming, degraded mode & failover, catalog sync, observability. See also [00-high-level-index.md](architecture/00-high-level-index.md). |
+| [cli/](cli/OVERVIEW.md) | Setup CLI: `setup-*` generators, config-file merge layer. |
+| [clients/](clients/OVERVIEW.md) | Clients & coding agents: OpenAI-compatible clients, setup recipes, MCP, autocomplete. |
+| [compression/](compression/OVERVIEW.md) | Prompt compression: modes, safeguards, per-request controls, filters, statistics. |
+| [deployment/](deployment/OVERVIEW.md) | Docker operations: image, Compose, networking, upgrades, backups. |
+| [desktop/](desktop/OVERVIEW.md) | Desktop app: Electron shape, file logging, update delivery. |
+| [env/](env/OVERVIEW.md) | Runtime configuration: `.env` variables, encryption keys, outbound proxies. |
+| [fallback/](fallback/OVERVIEW.md) | Named fallback chains: lifecycle, `auto:<name>`, catalog-sync backfill. |
+| [glossary/](glossary/OVERVIEW.md) | Glossary of recurring terms: headroom, RPD/TPD, pool key, `auto:<name>`, model-age gate. |
+| [install/](install/OVERVIEW.md) | Installation: quick start, Docker Compose, local dev, desktop app, Termux. |
+| [logs/](logs/OVERVIEW.md) | Server logs viewer: live panel, two-tier store, polling API. |
+| [providers/](providers/OVERVIEW.md) | Provider integrations: supported-platform catalog, quota accounting, adding a provider. |
+| [proxy/](proxy/OVERVIEW.md) | Outbound proxy transports: forward vs fetch-relay, system auto-detect. |
+| [testing/](testing/OVERVIEW.md) | Testing: local matrix, server suite, e2e compatibility suite. |
+| [troubleshooting/](troubleshooting/OVERVIEW.md) | Common issues: Docker, empty chain, fetch-relay, idempotency, quota, TRUST_PROXY. |
+| [i18n/](../TRANSLATION.md) | Translation workflow — see [Translating](../TRANSLATION.md) for the cross-lang guide (outside per-language tree). |
+
+## Other entry points
+
+- [README.md](README.md) — English docs index (per-language).
+- [../../README.md](../../README.md) — Documentation index (global).
+
+See also: [简体中文 — Chinese](../zh-cn/OVERVIEW.md) · [Translating guide](../TRANSLATION.md)
diff --git a/docs/en/README.md b/docs/en/README.md
new file mode 100644
index 00000000..2cf41811
--- /dev/null
+++ b/docs/en/README.md
@@ -0,0 +1,30 @@
+**English** · [简体中文](../zh-cn/OVERVIEW.md)
+
+# FreeLLMAPI documentation
+
+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/01-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/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.
+- **[Proxy transports](proxy/OVERVIEW.md)** — outbound proxy transports — forward vs Fetch Relay, system auto-detect, `TRUST_PROXY` for inbound; see [Fetch Relay transport](proxy/01-fetch-relay.md) for the relay protocol and Cloudflare Worker reference.
+- **[Architecture & internals](architecture/00-high-level-index.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/02-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.
+- [Database migrations](../../server/src/db/README.md) — create, apply, inspect, and roll back schema migrations.
+
+## Website assets in this directory
+
+- [`index.html`](../index.html) — project landing page.
+- [`install.sh`](../install.sh) — Unix Docker bootstrap script.
+- [`install.ps1`](../install.ps1) — PowerShell bootstrap script.
+- [`success.html`](../success.html) — post-install success page.
diff --git a/docs/en/api/01-rest-api.md b/docs/en/api/01-rest-api.md
new file mode 100644
index 00000000..3f155d41
--- /dev/null
+++ b/docs/en/api/01-rest-api.md
@@ -0,0 +1,450 @@
+**English** · [简体中文](../../zh-cn/api/OVERVIEW.md)
+
+# API reference
+
+[← 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`.
+
+- [Chat completions](#chat-completions)
+- [Routing strategies (`auto:*`)](#routing-strategies-auto)
+- [Model listing](#model-listing)
+- [Streaming](#streaming)
+- [Tool calling](#tool-calling)
+- [Gemini Google Search grounding](#gemini-google-search-grounding)
+- [Native Gemini API](#native-gemini-api)
+- [Ollama emulation](#ollama-emulation)
+- [Revocable URL tokens](#revocable-url-tokens)
+- [Vision / image input](#vision--image-input)
+- [Document attachments](#document-attachments)
+- [Images, video & text-to-speech](#images-video--text-to-speech)
+- [Fusion (multi-model synthesis)](#fusion-multi-model-synthesis)
+- [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
+
+**Python**
+
+```python
+from openai import OpenAI
+
+client = OpenAI(
+ base_url="http://localhost:3001/v1",
+ api_key="freellmapi-your-unified-key",
+)
+
+resp = client.chat.completions.create(
+ model="auto", # let the router pick; or specify e.g. "gemini-2.5-flash"
+ messages=[{"role": "user", "content": "Summarise the fall of Rome in one sentence."}],
+)
+print(resp.choices[0].message.content)
+print("Routed via:", resp.headers.get("x-routed-via"))
+```
+
+**curl**
+
+```bash
+curl http://localhost:3001/v1/chat/completions \
+ -H "Authorization: Bearer freellmapi-your-unified-key" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "auto",
+ "messages": [{"role": "user", "content": "hi"}]
+ }'
+```
+
+## Routing strategies (`auto:*`)
+
+Plain `auto` follows your active fallback chain. Add a suffix to steer a single request instead — no dashboard changes needed:
+
+- `auto:smart` — favor the highest-intelligence models
+- `auto:fast` — favor measured speed (throughput and time-to-first-byte)
+- `auto:cheap` — budget-leaning; currently the same blend as `balanced` (everything in the pool is already free)
+- `auto:reliable` — favor recent success rate
+- `auto:balanced` — the default blend (reliability first, speed and intelligence split the rest)
+
+These rank **every enabled model**, ignoring your chain order. Common synonyms resolve too (`auto:fastest`, `auto:speed`, `auto:smartest`, `auto:cheapest`, `auto:budget`, …), and the whole model string is case-insensitive.
+
+```bash
+curl http://localhost:3001/v1/chat/completions \
+ -H "Authorization: Bearer freellmapi-your-unified-key" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "auto:fast",
+ "messages": [{"role": "user", "content": "hi"}]
+ }'
+```
+
+`auto:<profile-name>` routes through a named profile's chain instead of the active one, so different tools can use different chains through the same key:
+
+```bash
+curl http://localhost:3001/v1/chat/completions \
+ -H "Authorization: Bearer freellmapi-your-unified-key" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "auto:coding",
+ "messages": [{"role": "user", "content": "Write a binary search in Rust."}]
+ }'
+```
+
+An unknown profile name returns a clear `400` rather than silently falling back. Profiles are named fallback chains (see [Features](../README.md#features)) — create and switch them from the dashboard; whichever is active is what plain `auto` uses.
+
+## Model listing
+
+`GET /v1/models` lists the whole catalog, including models you cannot call yet, so a client can show what exists as well as what is connected. `?available=true` (aliases `?connected=true`, `?ready=true`) narrows to models that can serve a request now.
+
+Each catalog entry also carries `execution_status`, a live answer to "would a request work right now":
+
+- `ready` — at least one key can actually serve it: enabled, healthy or not yet probed, not scoped away from this model, not on a rate-limit cooldown, and inside its rate and token windows. A key whose `status` is still `unknown` counts as ready, because probing is lazy and a fresh key is usable until something says otherwise.
+- `needsKey` — the model is disabled, or no enabled key matches it at all.
+- `exhausted` — keys match the model but every one of them is blocked at this moment, so a request would fail immediately. This is the state a burst of 429s produces, and it clears on its own when the cooldowns expire.
+
+`?execution_status=ready` (also `needsKey`, `exhausted`; matched case-insensitively) narrows the catalog rows to one status, so an agent can ask for models it can call without reading the whole list. An unrecognised value filters nothing. Like `?available=`, the filter applies only to catalog rows: `auto`, `fusion` and the `auto:<profile>` chains are router entries rather than models with keys of their own, and are always listed.
+
+```bash
+curl "http://localhost:3001/v1/models?execution_status=ready" \
+ -H "Authorization: Bearer freellmapi-your-unified-key"
+```
+
+## Streaming
+
+```python
+stream = client.chat.completions.create(
+ model="auto",
+ messages=[{"role": "user", "content": "Stream me a haiku about SQLite."}],
+ stream=True,
+)
+for chunk in stream:
+ print(chunk.choices[0].delta.content or "", end="", flush=True)
+```
+
+## Tool calling
+
+Pass OpenAI-style `tools` and `tool_choice`; the assistant response round-trips back through the proxy exactly like the OpenAI API. Multi-step flows (assistant `tool_calls` → `tool` role follow-up → final answer) work across every provider the router can reach.
+
+```python
+tools = [{
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": "Get current weather for a city.",
+ "parameters": {
+ "type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"],
+ },
+ },
+}]
+
+# 1. Model asks for a tool call
+first = client.chat.completions.create(
+ model="auto",
+ messages=[{"role": "user", "content": "What's the weather in Karachi?"}],
+ tools=tools,
+ tool_choice="required",
+)
+call = first.choices[0].message.tool_calls[0]
+
+# 2. You execute the tool, feed the result back
+final = client.chat.completions.create(
+ model="auto",
+ messages=[
+ {"role": "user", "content": "What's the weather in Karachi?"},
+ first.choices[0].message,
+ {"role": "tool", "tool_call_id": call.id, "content": '{"temp_c": 32, "cond": "sunny"}'},
+ ],
+ tools=tools,
+)
+print(final.choices[0].message.content)
+```
+
+Works with `stream=True` as well — you'll get `delta.tool_calls` chunks followed by a `finish_reason: "tool_calls"` close. Under the hood, OpenAI-compatible providers (Groq, Cerebras, Mistral, OpenRouter, GitHub Models, HuggingFace, Cloudflare, Cohere compat) get the request passed through; Gemini requests get translated into Google's `functionDeclarations` / `functionResponse` shape and the response is translated back.
+
+## Gemini Google Search grounding
+
+Google's models can ground their answers in live Google Search results. Since the OpenAI wire format has no way to express that, request a tool named `google_search` and the Google provider translates it into Gemini's native grounding tool. It can be sent on its own or alongside your normal function tools.
+
+```python
+resp = client.chat.completions.create(
+ model="gemini-2.5-flash", # pin a Google model so the request routes there
+ messages=[{"role": "user", "content": "Who won the F1 race this weekend?"}],
+ tools=[{"type": "function", "function": {"name": "google_search", "parameters": {}}}],
+)
+print(resp.choices[0].message.content)
+```
+
+## Native Gemini API
+
+Gemini SDKs and Gemini CLI can use the native `/v1beta` surface:
+
+- `GET /v1beta/models`
+- `GET /v1beta/models/{model}`
+- `POST /v1beta/models/{model}:generateContent`
+- `POST /v1beta/models/{model}:streamGenerateContent` (`?alt=sse` for Gemini CLI)
+- `POST /v1beta/models/{model}:countTokens`
+
+```bash
+curl "http://localhost:3001/v1beta/models/gemini-2.5-flash:generateContent" \
+ -H "x-goog-api-key: freellmapi-your-unified-key" \
+ -H "Content-Type: application/json" \
+ -d '{"contents":[{"role":"user","parts":[{"text":"hello"}]}]}'
+```
+
+Gemini model names like `gemini-2.5-flash` resolve through the Gemini family map (Keys → Gemini model mapping) rather than the catalog directly, so they route to Auto or whichever catalog model each family is pinned to. Catalog ids work verbatim too.
+
+`contents` text, inline data, function calls/responses, system instructions,
+function declarations, structured JSON output, generation controls, and
+thinking budgets translate into the same internal chat/fallback pipeline.
+Bearer auth works too. Gemini's `?key=` query parameter is accepted only below
+`/v1beta`; prefer a header because URL credentials leak into history and logs.
+
+## Ollama emulation
+
+The opt-in Ollama surface implements tags, chat, generate, show, version, embed,
+and legacy embeddings under `/api/*`. Streaming is Ollama-compatible NDJSON.
+It defaults to `off`; choose `open-loopback` or `key-required` on
+**Keys → Agents**. Open-loopback checks the direct socket peer, so desktop LAN
+access cannot silently turn it into an unauthenticated LAN endpoint.
+
+The dashboard also owns `/api/embeddings`. A request with a valid dashboard
+session continues to the dashboard handler; all other requests at that exact
+path are treated as Ollama legacy embeddings and follow the emulation policy.
+
+## Revocable URL tokens
+
+Headerless clients can mirror models, chat completions, Responses, and
+Ollama-style chat/tags under `/v1/t/{token}/…`. These tokens are random,
+stored only as hashes, separately revocable, and are not the unified key.
+Create/revoke them on **Keys → Agents**.
+
+Treat them as sensitive anyway: URLs are routinely retained by shell history,
+reverse proxies, browser history, and telemetry. Revocation is immediate.
+
+## Vision / image input
+
+Send images with the standard OpenAI `image_url` content blocks (base64 `data:` URLs or `http(s)` URLs). When a request contains an image, the router restricts itself to **vision-capable models** and ignores text-only ones. Vision models are tagged with a **Vision** badge on the Fallback Chain page; the current set includes Gemini (2.5 / 3.x), Llama 4 Scout/Maverick (Groq, NVIDIA), GLM-4.6V Flash (Z.ai), Nemotron Nano 12B VL (OpenRouter), and GitHub's GPT-4o / GPT-4.1.
+
+```python
+resp = client.chat.completions.create(
+ model="auto", # auto-routes to a vision model
+ messages=[{
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "What's in this image?"},
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,<...>"}},
+ ],
+ }],
+)
+print(resp.choices[0].message.content)
+```
+
+If no vision-capable model is enabled in your Fallback Chain, an image request returns a clear `422` (`code: "no_vision_model"`) rather than silently dropping the image. (Image input on `/v1/responses` isn't supported yet — use `/v1/chat/completions`.)
+
+## Document attachments
+
+Anthropic's `document` content blocks are accepted on `/v1/messages` when their source is already text:
+
+```json
+{"type": "document", "title": "contract.txt",
+ "source": {"type": "text", "media_type": "text/plain", "data": "PAYMENT TERMS: net 30."}}
+```
+
+`text` and `content` sources are inlined into the prompt, wrapped in a fence tagged with a hash of the document body so the model can tell quoted material from your instructions. The tag is derived from the content rather than randomized, so a repeated attachment keeps the prompt prefix stable and stays cacheable.
+
+**Binary sources — `base64` (PDF, DOCX, XLSX…) and `url` — return a `400`.** No provider in the pool accepts them, and there is no local converter, so the honest answer is to refuse: forwarding the request would drop the attachment and produce a confident answer about a document the model never saw. The rejection happens before routing, so it spends no provider quota. Send the extracted text instead.
+
+`url` sources are refused rather than fetched on your behalf; making the proxy retrieve arbitrary URLs would turn it into a request forwarder for whatever a client names.
+
+## Images, video & text-to-speech
+
+`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 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 \
+ -H "Authorization: Bearer freellmapi-your-unified-key" \
+ -H "Content-Type: application/json" \
+ -d '{"model":"auto","prompt":"a sunrise over a quiet lake","duration":6}' \
+ --output video.mp4
+```
+
+## 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. Panel, judge, and strategy are configurable on the dashboard's **Fusion** page or per request via the `fusion` field; each sub-call goes through normal routing, quotas, and analytics.
+
+## Response headers
+
+Every response carries an `X-Routed-Via: <platform>/<model>` header so you can see which provider actually served each call. If a request fell over between providers, you'll also see `X-Fallback-Attempts: N` and `X-Fallback-Trail`, which names each hop that failed and why:
+
+```
+X-Fallback-Attempts: 2
+X-Fallback-Trail: groq/llama-3.3-70b key1=rate_limited; google/gemini-2.5-flash key2=timeout
+```
+
+`X-Fallback-Detail` adds what each of those hops **cost**, which is the part you cannot reconstruct from the trail — a request answered in 40s reads identically whether one provider stalled for 39 seconds or four failed fast:
+
+```
+X-Fallback-Detail: groq/llama-3.3-70b key1=rate_limited t=0+39000ms msg=Groq API error 429: rate limit; google/gemini-2.5-flash key2=timeout t=39000+12ms
+```
+
+`t=<start>+<duration>ms` is the offset from the start of the failover chain and how long that hop ran. `msg=` is the provider's error, redacted and truncated; it is last in each record, and any semicolon inside it becomes a comma so `; ` stays an unambiguous record separator.
+
+The detail header is **off by default** — it puts hop timings and provider error text on the response. Turn it on with `FALLBACK_DETAIL_HEADER=1` or the `expose_fallback_detail_header` settings key, which takes precedence. Both headers list at most ten hops and then a `; +N more` marker.
+
+Only hops that already **failed** can appear. The hop actually serving your request is recorded after its response finishes — after the JSON is sent, or after the stream closes — so its duration does not exist while the headers are still open. Use `X-Routed-Via` to see which provider that was.
+
+HTTP headers only carry printable ASCII, so a model id with characters outside that range (a Chinese name from a relay catalog, for example) is percent-encoded in the header — run the value through `decodeURIComponent` (or `urllib.parse.unquote`) to read it back.
+
+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/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`.
+
+`X-FreeLLM-Task-Type: code|chat|auto` tells the router what kind of turn this is, so it can bias the routing weights: `code` trades some of the speed weight for intelligence (a wrong answer costs more than a slow one), `chat` does the reverse. It is a soft preference only — capability gates, the failover chain and the model catalog are untouched, and the shift is 30% of one axis by default. The default is `auto`: tool-bearing requests and messages carrying unambiguous code markers (a fenced block, a declaration, a stack frame, a `file.ts:214` reference) are treated as `code`, and everything else keeps the preset weights exactly as configured. The `fastest`, `reliable` and `custom` routing strategies ignore the header — those are an explicit operator choice about where on the axis to sit.
+
+How far the shift goes is operator-tunable: `GET /api/settings/task-weight-share` reads the current fraction and `PUT /api/settings/task-weight-share` with `{"share": 0..1}` sets it (default `0.3`). `0` disables the bias while leaving the header itself accepted, and `null` clears the setting back to the default. It takes effect on the next request, with no restart.
+
+## Embeddings
+
+`/v1/embeddings` is OpenAI-compatible, with one deliberate difference from chat routing: **failover never crosses models.** Vectors from different models live in incompatible spaces — silently switching models would corrupt any vector store built on top of the proxy. So embeddings route by **family** (one model identity + dimension), and failover only walks the providers serving that same family.
+
+```python
+resp = client.embeddings.create(
+ model="auto", # default family; or a family name like "bge-m3"
+ input=["the quick brown fox", "pack my box with five dozen liquor jugs"],
+)
+print(len(resp.data), "vectors of", len(resp.data[0].embedding), "dims")
+```
+
+```bash
+curl http://localhost:3001/v1/embeddings \
+ -H "Authorization: Bearer freellmapi-your-unified-key" \
+ -H "Content-Type: application/json" \
+ -d '{"model": "auto", "input": "hello world"}'
+```
+
+`model` accepts `auto` (the configured default family), a family name, or a provider-specific model id (which resolves to its family). Available families:
+
+| Family (`model`) | Dims | Providers (failover order) |
+| --- | --- | --- |
+| `gemini-embedding-001` *(default)* | 3072 | Google |
+| `text-embedding-3-large` | 3072 | GitHub Models |
+| `text-embedding-3-small` | 1536 | GitHub Models |
+| `embed-v4.0` | 1536 | Cohere |
+| `bge-m3` | 1024 | Cloudflare → Hugging Face |
+| `qwen3-embedding-0.6b` | 1024 | Cloudflare |
+| `nv-embedqa-e5-v5` | 1024 | NVIDIA |
+| `llama-nemotron-embed-1b-v2` | 2048 | NVIDIA |
+| `llama-nemotron-embed-vl-1b-v2` | 2048 | NVIDIA → OpenRouter |
+| `embeddinggemma-300m` | 768 | Cloudflare |
+
+The default family, per-provider toggles, and priorities live on the dashboard's **Models → Embeddings** page. Pick your family once and stick with it for a given vector store — that's the whole point of the family model.
+
+## Anthropic / Claude clients
+
+FreeLLMAPI also speaks Anthropic's Messages API, so anything built for Claude — including **Claude Code** and the official Anthropic SDKs — can run against your free pool. Point the client at your server's **origin** (Anthropic clients append `/v1/messages` themselves) and authenticate with your unified key. Both `x-api-key` and `Authorization: Bearer` are accepted.
+
+```bash
+curl http://localhost:3001/v1/messages \
+ -H "x-api-key: freellmapi-your-unified-key" \
+ -H "anthropic-version: 2023-06-01" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "claude-sonnet-4-5",
+ "max_tokens": 256,
+ "messages": [{"role": "user", "content": "hi"}]
+ }'
+```
+
+Claude model names map to your free pool on the **Keys → Anthropic** tab: each family (`default`, `opus`, `sonnet`, `haiku`) routes to `auto` (the router picks a free model) or a model you pin. `POST /v1/messages/count_tokens` and a content-negotiated `GET /v1/models` (Anthropic shape when `anthropic-version` is sent) are implemented too. Streaming, system prompts, tool use, and image input all translate across the same router as the OpenAI endpoints.
+
+**Claude Code** — point it at your server and start it:
+
+*On macOS / Linux (Bash):*
+```bash
+export ANTHROPIC_BASE_URL=http://localhost:3001
+export ANTHROPIC_AUTH_TOKEN=freellmapi-your-unified-key # NOT ANTHROPIC_API_KEY
+claude
+```
+
+*On Windows (PowerShell):*
+```powershell
+$env:ANTHROPIC_BASE_URL="http://localhost:3001"
+$env:ANTHROPIC_AUTH_TOKEN="freellmapi-your-unified-key"
+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/en/api/02-idempotency.md b/docs/en/api/02-idempotency.md
new file mode 100644
index 00000000..d26b4c85
--- /dev/null
+++ b/docs/en/api/02-idempotency.md
@@ -0,0 +1,191 @@
+# Idempotency-Key — Safe Retries for Non-Streaming Chat Completions
+
+> **Sources:** `server/src/services/idempotency.ts`, `server/src/routes/proxy.ts:1793-1835` (entry) + `2640-2656` (persist), `server/src/db/migrations/20260901_000001_idempotency_claims.ts`, commit `36b877d` (feature), `95bc46f` (in-flight clarification), env `IDEMPOTENCY_TTL_MS` documented in `docs/env/01-variables.md#idempotency`.
+
+Non-streaming `POST /v1/chat/completions` supports an opt-in `Idempotency-Key` header so a client that times out and retries does not burn a second free-tier slot for an answer it already received. When the same key + same request content is seen again inside the replay window the gateway replays the stored response at **zero provider cost**; the same key with different content is a `409` rather than a silent wrong answer.
+
+---
+
+## 1. Header
+
+Send `Idempotency-Key` (case-insensitive — Express lower-cases to `idempotency-key`) on a **non-streaming** request:
+
+```
+Idempotency-Key: <opaque client token>
+```
+
+Normalization (`normalizeIdempotencyKey` in `server/src/services/idempotency.ts:176-182`):
+
+- Trim surrounding whitespace; empty after trim → ignored (no idempotency).
+- Must be `≤ 255` UTF-8 bytes (`Buffer.byteLength(..., 'utf8')`); longer → ignored.
+- If the header is repeated, the **first** value wins (`Array.isArray(raw) ? raw[0] : raw`), matching Express multi-value handling.
+
+Only a `SHA-256 hex` of the key is stored (`hashIdempotencyKey`) — the raw key never touches SQLite, mirroring how admin/runtime tokens are handled.
+
+Streaming requests (`stream: true`) **always bypass** idempotency (`const idemKey = !stream ? normalize... : null` in `proxy.ts:1805`). A stream cannot be replayed as a unit and the open connection is itself the retry signal — same policy as the response cache.
+
+---
+
+## 2. States — `miss` / `replay` / `409 conflict`
+
+`lookupIdempotencyReplay(keyHash, fingerprint)` in `server/src/services/idempotency.ts:91-119` queries the `idempotency_claims` table for an **unexpired** row with the same `key_hash` and compares its stored `request_fingerprint`:
+
+| Result | Condition | Gateway behavior |
+|--------|-----------|-----------------|
+| `miss` | No row `WHERE key_hash = ? AND expires_at_ms > now`, or corrupt stored body, or DB unavailable | Proceed normally; if the upstream later succeeds with `finish_reason !== 'length'`, persist the result for future replays. |
+| `replay` | Row exists **and** `request_fingerprint` matches | `X-Routed-Via: idempotency`, replay stored `response_status` + `response_body` verbatim. **No provider quota is consumed** — same zero-cost rationale as a `HIT` from the response cache, so request/usage bookkeeping is skipped. |
+| `conflict` | Row exists but fingerprints differ | `409` with `idempotency_key_conflict` (see §6) — the caller reused a key with different content. |
+
+Expired rows are treated as `miss`; a new successful completion with the same key **replaces** the previous claim (`INSERT ... ON CONFLICT(key_hash) DO UPDATE` in `storeIdempotencyResult`).
+
+DB failures degrade to `miss` — idempotency is best-effort and never fails the hot path (mirrors `services/cache.ts`).
+
+---
+
+## 3. Non-streaming only
+
+- Applies **only** to `POST /v1/chat/completions` with `stream` falsy. Streaming, `/v1/responses`, `/v1/messages` (Anthropic), `/v1/completions`, `/v1/embeddings`, and media endpoints are not covered.
+- A truncated turn (`finish_reason === 'length'`) is **not stored** and not replayed — replaying a cut-off answer would be worse than regenerating. This matches the response-cache policy (`proxy.ts:2644-2648` guards `result.choices?.[0]?.finish_reason !== 'length'`).
+
+---
+
+## 4. Fingerprint composition
+
+`computeIdempotencyFingerprint` (`server/src/services/idempotency.ts:51-70`) builds a canonical `SHA-256` over the JSON serialization of exactly these fields:
+
+```typescript
+{
+ model: input.model ?? null,
+ messages: input.messages,
+ temperature: input.temperature ?? null,
+ top_p: input.top_p ?? null,
+ max_tokens: input.max_tokens ?? null,
+ tools: input.tools ?? null,
+ tool_choice: input.tool_choice ?? null,
+}
+```
+
+`model` comes from the client's `model` field as-is (e.g. `auto`, `auto:fast`, `gemini-2.5-flash`); `messages` is the full OpenAI-shaped array after `developer`→`system` normalization. `tools`/`tool_choice` include their schemas so a retry that changes a tool binding correctly conflicts.
+
+Default-valued sampling params are canonicalized (`null` when absent) so `top_p: 1` and omitting `top_p` do not create two fingerprints for the same logical request — consistent with cache key `v4`.
+
+---
+
+## 5. In-flight requests are NOT deduplicated (95bc46f)
+
+A duplicate that arrives while the original is still running is **not coalesced**:
+
+> Only **completed** responses are claimable. If two requests race with the same key + fingerprint, both execute to completion; the second `storeIdempotencyResult` replaces the first. A third request that then repeats the key will replay the winner.
+
+Guarding the in-flight window would require a `pending`-claim state with its own short TTL so a crash cannot wedge a key for 24 h. That is **deliberately out of scope** (commit `95bc46f`, `server/src/services/idempotency.ts:17-20`). Callers that need stronger dedup should hold off retrying until the first request either returns or the client's own timeout fires.
+
+---
+
+## 6. TTL — `IDEMPOTENCY_TTL_MS`
+
+| Variable | Default | Meaning |
+|----------|---------|---------|
+| `IDEMPOTENCY_TTL_MS` | `86400000` (24 h) | Replay window for completed claims |
+
+- Read **per call** via `idempotencyTtlMs()` → `envNum('IDEMPOTENCY_TTL_MS', 24*60*60*1000)` so tests can flip it live; non-finite / negative → fallback.
+- `expires_at_ms = now + ttl`; stale rows are lazily swept **per `key_hash`** at the next `storeIdempotencyResult` (`DELETE ... WHERE key_hash = ? AND expires_at_ms <= ?`) and via the `idx_idempotency_claims_expires` index for range scans.
+- Source of truth: `server/src/services/idempotency.ts:40-42`, `docs/env/01-variables.md#idempotency`.
+
+---
+
+## 7. 409 handling — `idempotency_key_conflict`
+
+Reusing a key with **different** `model`/`messages`/sampling/`tools` is a `409 Conflict` (before any provider is called):
+
+```json
+HTTP/1.1 409 Conflict
+Content-Type: application/json
+
+{
+ "error": {
+ "message": "idempotency_key_conflict",
+ "type": "invalid_request_error"
+ }
+}
+```
+
+Client recovery:
+
+1. Generate a **new** `Idempotency-Key` for genuinely new content, or
+2. Resend the **original** body byte-for-byte to get the replay.
+
+No provider quota is spent on the `409` — it is returned directly from the lookup (`proxy.ts:1827-1835`). Treat it as a programmer error, not a retryable status.
+
+---
+
+## 8. Curl example — timeout, retry, replay
+
+```bash
+# 1. First attempt — times out on the client side, but the gateway
+# finishes and stores the response under the key hash.
+curl -X POST http://localhost:3001/v1/chat/completions \
+ -H "Authorization: Bearer freellmapi-your-unified-key" \
+ -H "Content-Type: application/json" \
+ -H "Idempotency-Key: 7f3a-2026-09-02-retry-1" \
+ -d '{
+ "model": "auto",
+ "messages": [{"role": "user", "content": "Summarise the fall of Rome in one sentence."}]
+ }' --max-time 10 || echo "client timed out"
+
+# 2. Retry with the SAME key + SAME body → replay, zero provider cost
+curl -i http://localhost:3001/v1/chat/completions \
+ -H "Authorization: Bearer freellmapi-your-unified-key" \
+ -H "Content-Type: application/json" \
+ -H "Idempotency-Key: 7f3a-2026-09-02-retry-1" \
+ -d '{
+ "model": "auto",
+ "messages": [{"role": "user", "content": "Summarise the fall of Rome in one sentence."}]
+ }'
+# Response headers include: X-Routed-Via: idempotency
+# Body is the exact JSON from the first success, including usage/model fields.
+
+# 3. Same key with DIFFERENT content → 409
+curl -i http://localhost:3001/v1/chat/completions \
+ -H "Authorization: Bearer freellmapi-your-unified-key" \
+ -H "Content-Type: application/json" \
+ -H "Idempotency-Key: 7f3a-2026-09-02-retry-1" \
+ -d '{
+ "model": "auto",
+ "messages": [{"role": "user", "content": "Different question"}]
+ }'
+# → 409 {"error":{"message":"idempotency_key_conflict","type":"invalid_request_error"}}
+```
+
+Tips:
+
+- Use a **UUID v4** or KSUID per logical operation; do not reuse keys across unrelated calls.
+- Timeouts are the expected use case — set the client timeout shorter than the gateway's provider budget so retries actually fire.
+- A replay can be distinguished by `X-Routed-Via: idempotency` (normal hits use `X-Routed-Via: <platform>/<model>`); cache hits use `X-FreeLLM-Cache: HIT`.
+
+---
+
+## 9. Storage & cost model
+
+| Aspect | Detail |
+|--------|--------|
+| Table | `idempotency_claims` (`id`, `key_hash UNIQUE`, `request_fingerprint`, `response_status`, `response_body TEXT`, `execution_id`, `created_at_ms`, `expires_at_ms`) — migration `20260901_000001_idempotency_claims.ts` |
+| Index | `idx_idempotency_claims_expires ON expires_at_ms` |
+| Cost | Replay = **zero provider keys/quota**, no `requests`/`request_attempts` rows, same as cache `HIT` |
+| Scoping | Per-caller key (caller controls the key), unlike the response cache which is global exact-match on request content |
+| Semantics | One row per `key_hash`; a new successful completion **replaces** the old one (fingerprint + body overwritten) |
+
+---
+
+## 10. Relationship to response cache & degraded mode
+
+- **Response cache** (`services/cache.ts`, `X-FreeLLM-Cache`) is orthogonal: global, temperature-gated, in-memory LRU; idempotency is durable (SQLite), per-caller, and fingerprint-bound. Both short-circuit provider calls.
+- **Degraded mode** (`docs/architecture/04-degraded-mode-and-failover.md`) disables bandit exploration but does not affect idempotency — replays still bypass routing entirely.
+- **Failover**: only the final successful body is stored. If a request exhausts the fallback loop, nothing is stored for that key.
+
+---
+
+## Related
+
+- `docs/env/01-variables.md#idempotency` — `IDEMPOTENCY_TTL_MS` defaults and bounds.
+- `docs/architecture/04-degraded-mode-and-failover.md` — retry budget, hedging, and fallback headers that apply when a `miss` enters the loop.
+- `01-rest-api.md` — OpenAI-compatible surface (`/v1/chat/completions`) and response headers (`X-Routed-Via`, `X-Fallback-Detail`).
diff --git a/docs/api/CHANGELOG.md b/docs/en/api/CHANGELOG.md
similarity index 55%
rename from docs/api/CHANGELOG.md
rename to docs/en/api/CHANGELOG.md
index 11d71c9f..660b3b1e 100644
--- a/docs/api/CHANGELOG.md
+++ b/docs/en/api/CHANGELOG.md
@@ -7,6 +7,10 @@ Doc revision history for `docs/api/`, seeded from API-relevant commits.
- **docs(api): document the task-type routing header** — added `X-FreeLLM-Task-Type: code|chat|auto` (#1127) to the per-request headers section, with the weight shift it applies and the strategies that ignore it.
- **docs(api): document the task-weight-share setting** — added `GET/PUT /api/settings/task-weight-share` (#1127), the operator knob for how much weight the task-type bias moves.
+## 2026-09-02
+
+- **docs(api): add Idempotency-Key documentation (02-idempotency.md)** — documents non-streaming `POST /v1/chat/completions` idempotency from `36b877d` / `95bc46f`: `Idempotency-Key` header (trim + `≤255` UTF-8 bytes, first value on repeat), `replay` vs `409 idempotency_key_conflict` vs `miss` via `lookupIdempotencyReplay`, fingerprint `SHA-256(model+messages+temperature/top_p/max_tokens/tools/tool_choice)`, SHA-256 key-hash storage, `X-Routed-Via: idempotency` zero-cost replay, `stream:true` bypass and `finish_reason:length` not stored, in-flight NOT deduplicated (both attempts execute; pending-claim out of scope per `95bc46f` / `idempotency.ts:17-20`), `IDEMPOTENCY_TTL_MS` 24 h (`idempotencyTtlMs` + `envNum` guard, lazy sweep per `key_hash`), `409` handling, and a `curl` timeout→retry→replay example. Sources: `server/src/services/idempotency.ts`, `server/src/routes/proxy.ts:1793-1835` + `2640-2656`, migration `20260901_000001_idempotency_claims.ts`. Updated `docs/api/OVERVIEW.md` index and added cross-ref in `docs/architecture/04-degraded-mode-and-failover.md:10`.
+
## 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.
diff --git a/docs/api/OVERVIEW.md b/docs/en/api/OVERVIEW.md
similarity index 67%
rename from docs/api/OVERVIEW.md
rename to docs/en/api/OVERVIEW.md
index 619e667e..c3d90698 100644
--- a/docs/api/OVERVIEW.md
+++ b/docs/en/api/OVERVIEW.md
@@ -7,12 +7,13 @@ This domain documents FreeLLMAPI's OpenAI-compatible HTTP surface and its Anthro
| 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`). |
+| [`02-idempotency.md`](02-idempotency.md) | `Idempotency-Key` on non-streaming `POST /v1/chat/completions` — `replay` vs `409 conflict` vs `miss`, fingerprint composition (`model`+`messages`+`temperature`/`top_p`/`max_tokens`/`tools`/`tool_choice`), SHA-256 key-hashing, non-streaming-only, in-flight NOT deduplicated (95bc46f), 24 h `IDEMPOTENCY_TTL_MS` window, `X-Routed-Via: idempotency`, curl retry example. Sources: `server/src/services/idempotency.ts`, `proxy.ts:1793-1835`. |
| [`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)
+- API reference: [`01-rest-api.md`](01-rest-api.md) · [`02-idempotency.md`](02-idempotency.md)
## Related
diff --git a/docs/en/architecture/00-high-level-index.md b/docs/en/architecture/00-high-level-index.md
new file mode 100644
index 00000000..cbf15698
--- /dev/null
+++ b/docs/en/architecture/00-high-level-index.md
@@ -0,0 +1,96 @@
+# Architecture & internals
+
+[← Back to README](../../../README.md) · [Documentation index](../README.md) · [Deep-dive domain](OVERVIEW.md)
+
+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](OVERVIEW.md) for deep-dives.
+
+- [How it works](#how-it-works)
+- [Not yet supported](#not-yet-supported)
+- [Limitations](#limitations)
+- [Terms of Service review](#terms-of-service-review)
+
+## How it works
+
+![One request in, the best free model out — the fallback chain with live scores, cooldowns, and quota tracking](../../../repo-assets/router-flow.png)
+
+```
+┌──────────────────┐ Bearer freellmapi-… ┌─────────────────────────┐
+│ OpenAI SDK / │ ──────────────────────▶ │ Express proxy (:3001) │
+│ curl / any │ ◀────────────────────── │ /v1/chat/completions │
+│ OpenAI client │ streamed tokens └────────────┬────────────┘
+└──────────────────┘ │
+ ▼
+ ┌────────────────────────────────────────────────┐
+ │ Router │
+ │ 1. Pick highest-priority model that │
+ │ (a) has a healthy key and │
+ │ (b) is under all its rate limits. │
+ │ 2. Decrypt key, call provider SDK. │
+ │ 3. On 429/5xx → cooldown + retry next model. │
+ └────────────────────────────────────────────────┘
+ │
+ ┌──────────────┬────────────┬──────────┴─────────┬─────────────┬──────────┐
+ ▼ ▼ ▼ ▼ ▼ ▼
+ Google Groq Cerebras OpenRouter HF …29 more
+```
+
+- **Router** (`server/src/services/router.ts`) — picks a model per request.
+- **Rate-limit ledger** (`server/src/services/ratelimit.ts`) — in-memory RPM/RPD/TPM/TPD counters backed by SQLite, with cooldowns on 429s.
+- **Provider adapters** (`server/src/providers/*.ts`) — one file per provider, implementing the `Provider` base class: `chatCompletion()` and `streamChatCompletion()`.
+- **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.
+- **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.
+
+> 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](OVERVIEW.md) for deep-dives.
+
+## Not yet supported
+
+The scope is deliberately narrow. If a feature isn't in the README's feature list and isn't below, assume it isn't there yet.
+
+- **Moderation** (`/v1/moderations`)
+- **`n > 1`** (multiple completions per request)
+- **Per-user billing / multi-tenant auth** — single-user by design
+
+PRs that add any of these are very welcome. See [Contributing](../README.md#contributing).
+
+## Limitations
+
+Stacking free tiers has real trade-offs. Be honest with yourself about them:
+
+- **Quota and availability are the ceiling, not model class.** The catalog does carry frontier-class rows — GPT-5.x, Grok 4.x, Kimi K3, DeepSeek V4 Pro, and Gemini 3.x all show up on somebody's free tier. What you don't get is *sustained* access to them: those are exactly the rows with the smallest daily allowances, the longest queues, and the highest chance of being pulled or paywalled at short notice. Budget for capacity and uptime, not for a capability limit.
+- **Intelligence degrades as the day progresses.** Your top-ranked models (usually Gemini 3.6 Flash, DeepSeek V4, Kimi K2.6) have the lowest daily caps. Once they hit their limits, the router falls down your priority chain to smaller/weaker models. Expect the effective intelligence of the endpoint to drop in the late hours of each day — then reset at UTC midnight.
+- **Latency is highly variable.** Cerebras and Groq are extremely fast; others are not. You get whichever one is available.
+- **Free tiers can change without notice.** Providers regularly tighten, loosen, or remove free tiers. When that happens you'll see 429s or auth errors until the catalog update reaches you — live-feed installs get those fixes within days, free installs on the 30-day trail. Re-seed scripts live in `server/src/scripts/`.
+- **No SLA, by definition.** If you need reliability, use a paid provider with a contract.
+- **Local-first.** There's no multi-tenant auth. Run this for yourself; don't expose it to the internet.
+
+## Terms of Service review
+
+A self-hosted, single-user, personal-use setup was re-reviewed against each provider's ToS (May 2026). Summary:
+
+| Provider | Verdict | Notes |
+|---|---|---|
+| Google Gemini | ⚠️ Caution | March 2026 ToS narrows scope to *"professional or business purposes, not for consumer use"* — a self-hosted developer proxy is still defensible, but the clause is new. |
+| Groq | ✅ Likely OK | GroqCloud Services Agreement permits Customer Application integration. |
+| Cerebras | ✅ Likely OK | Permitted; explicitly forbids selling/transferring API keys. |
+| Mistral | ✅ Likely OK | APIs allowed for personal/internal business use. |
+| OpenRouter | ✅ Likely OK | April 2026 ToS sharpens the no-resale / no-competing-service clause; private single-user proxy still fine. |
+| Cloudflare Workers AI | ⚠️ Ambiguous | No anti-proxy clause; covered by general Self-Serve Subscription Agreement. |
+| NVIDIA NIM | ⚠️ Caution | Trial ToS §1.2 / §1.4: *"evaluation only, not production."* Free access is a recurring 40 RPM rate limit (the 2025 credit system was discontinued), but the evaluation-only scope stands. |
+| GitHub Models | ⚠️ Caution | Free tier explicitly scoped to *"experimentation"* and *"prototyping."* |
+| Cohere | ❌ Avoid | Terms §14 still forbids *"personal, family or household purposes."* |
+| Zhipu (open.bigmodel.cn) | ✅ Likely OK | Personal/non-commercial research carve-out still in the platform docs. |
+| Z.ai (api.z.ai) | ⚠️ Caution | New row — Singapore entity (distinct from Zhipu CN). §III.3(l) anti-traffic-redirect clause could plausibly be read against a proxy; no explicit personal-use carve-out. |
+| Ollama Cloud | ✅ Likely OK | New row — Free plan permits cloud-model access (1 concurrent, 5-hour session caps). No anti-proxy / anti-resale clauses found. *(Integration tracked in #14.)* |
+| OVH AI Endpoints | ✅ Likely OK | New row (June 2026) — anonymous access is officially documented (2 req/min per IP per model). OVH reserves the right to introduce token/consumption caps. |
+| AI Horde | ✅ Likely OK | New row (June 2026) — a free, community-powered commons run by the Haidra non-profit; anonymous use is officially supported (key `0000000000`, lowest queue priority). No anti-proxy / anti-resale clause. The OpenAI proxy is a pilot and may be restricted by usage. *(Integration #345.)* |
+
+Rules of thumb that keep most providers happy: **one account per provider**, **no reselling**, **no sharing your endpoint with other humans**, **don't hammer a free tier as a paid production backend**. This is informational, not legal advice — read each provider's ToS and make your own call.
+
+Removed since the April 2026 review: Moonshot and MiniMax direct integrations were dropped from the catalog (Moonshot — moved to paid only; MiniMax — superseded by the OpenRouter `minimax/minimax-m2.5:free` route).
diff --git a/docs/architecture/01-routing-and-bandit-scoring.md b/docs/en/architecture/01-routing-and-bandit-scoring.md
similarity index 100%
rename from docs/architecture/01-routing-and-bandit-scoring.md
rename to docs/en/architecture/01-routing-and-bandit-scoring.md
diff --git a/docs/architecture/02-quota-and-cooldown-engine.md b/docs/en/architecture/02-quota-and-cooldown-engine.md
similarity index 100%
rename from docs/architecture/02-quota-and-cooldown-engine.md
rename to docs/en/architecture/02-quota-and-cooldown-engine.md
diff --git a/docs/architecture/03-streaming-pipeline.md b/docs/en/architecture/03-streaming-pipeline.md
similarity index 100%
rename from docs/architecture/03-streaming-pipeline.md
rename to docs/en/architecture/03-streaming-pipeline.md
diff --git a/docs/architecture/04-degraded-mode-and-failover.md b/docs/en/architecture/04-degraded-mode-and-failover.md
similarity index 80%
rename from docs/architecture/04-degraded-mode-and-failover.md
rename to docs/en/architecture/04-degraded-mode-and-failover.md
index f279ddad..0ddf4cc5 100644
--- a/docs/architecture/04-degraded-mode-and-failover.md
+++ b/docs/en/architecture/04-degraded-mode-and-failover.md
@@ -1,6 +1,8 @@
# 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`
+> **Source:** `server/src/services/degradation.ts`, `server/src/lib/fallback-loop.ts`, `server/src/routes/proxy.ts`, `server/src/services/ratelimit.ts`, `server/src/services/idempotency.ts`
+
+> **Cross-ref:** Client-facing contract for `Idempotency-Key` (header, replay/409/miss, fingerprint, TTL, curl example) lives in [`../api/02-idempotency.md`](../api/02-idempotency.md). This file notes how that replay interacts with failover.
## 1. Degraded-Mode State Machine (f412e97)
@@ -314,4 +316,47 @@ request → /v1/chat/completions
│ │ └─ 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
+```
+
+---
+
+## 10. Idempotency-Key Replay — Failover Interaction
+
+> Full client contract: [`../api/02-idempotency.md`](../api/02-idempotency.md). This section is the architecture cross-ref.
+
+### Where it sits in the request path
+
+```
+request → /v1/chat/completions
+ ├─ [BEFORE routing] Idempotency lookup (proxy.ts:1796-1838)
+ │ ├─ hit + fingerprint matches → replay 200 with X-Routed-Via: idempotency (zero cost, no routing)
+ │ ├─ hit + fingerprint differs → 409 idempotency_key_conflict (fail fast, no provider hit)
+ │ └─ miss / streaming / no key → continue to cache → runFallbackLoop() → provider
+ └─ [AFTER success, non-stream only] Persist response if finish_reason !== 'length'
+ └─ storeIdempotencyResult(keyHash, fingerprint, 200, body) (proxy.ts:2644-2656)
+```
+
+The lookup happens **before** response-cache lookup (the cache is keyed by request content; idempotency is caller-scoped per key hash) and **before** `newFallbackState()` — a replay never enters the fallback loop, never touches `routeRequest`, and never consumes a quota lease.
+
+### What is stored / replayed
+
+- Only a `SHA-256(key)` + `SHA-256(canonical model+messages+temperature/top_p/max_tokens/tools/tool_choice)` fingerprint are persisted; the raw key is never stored (`hashIdempotencyKey`, `computeIdempotencyFingerprint` in `server/src/services/idempotency.ts:46-70`).
+- `response_status` + `response_body` (the sanitized `outboundBody` that the client received) are replayed verbatim. Replays carry no `X-Fallback-*` headers and do not write analytics rows — same zero-cost semantics as a cache `HIT`.
+- Streaming (`stream: true`) and truncated turns (`finish_reason === 'length'`) are never stored — consistent with the response cache.
+
+### In-flight NOT deduplicated (95bc46f)
+
+A second request with the same `Idempotency-Key` arriving **while the first is still in flight** does **not** coalesce: only **completed** claims are claimable, so both execute. The second `storeIdempotencyResult` replaces the first. Guarding the window would require a `pending` claim with a short TTL so a crash cannot wedge a key for 24 h — deliberately out of scope (`idempotency.ts:17-20`).
+
+### TTL & expiry
+
+- `IDEMPOTENCY_TTL_MS` (default `24 h`, `idempotencyTtlMs()` in `idempotency.ts:40-42`, `envNum` guard) sets `expires_at_ms = now + ttl`.
+- Expired rows are lazily swept per `key_hash` at the next `storeIdempotencyResult` (`DELETE WHERE key_hash = ? AND expires_at_ms <= ?`) plus the `idx_idempotency_claims_expires` index; a lookup where `expires_at_ms <= now` is a `miss`.
+
+### Interaction with degraded mode & hedging
+
+- An `idempotency` replay bypasses `isDegraded()` entirely — it is already a success and does not consult the router's exploration gate.
+- A `miss` that then enters the fallback loop is subject to the normal degraded-mode rules (exploration disabled, retry budget, hedging via `abortInFlight`). The `409` path never enters the loop.
+- `HedgeAbortError` and other non-provider-health failures that cause `timedOut` exhaustion do not persist a claim for that `Idempotency-Key` — the attempt did not succeed.
+
+See [`../api/02-idempotency.md`](../api/02-idempotency.md) for the header contract, fingerprint details, `409` body, per-field TDD, and a full `curl` retry example.
\ No newline at end of file
diff --git a/docs/architecture/05-catalog-sync.md b/docs/en/architecture/05-catalog-sync.md
similarity index 100%
rename from docs/architecture/05-catalog-sync.md
rename to docs/en/architecture/05-catalog-sync.md
diff --git a/docs/architecture/06-observability.md b/docs/en/architecture/06-observability.md
similarity index 99%
rename from docs/architecture/06-observability.md
rename to docs/en/architecture/06-observability.md
index bc3381a7..ac0f655b 100644
--- a/docs/architecture/06-observability.md
+++ b/docs/en/architecture/06-observability.md
@@ -51,7 +51,7 @@ The public query API (`queryLogs({ levels, q, provider, sinceId, limit })`), lev
### 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).
+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/01-install.md#where-are-the-logs).
---
diff --git a/docs/architecture/CHANGELOG.md b/docs/en/architecture/CHANGELOG.md
similarity index 95%
rename from docs/architecture/CHANGELOG.md
rename to docs/en/architecture/CHANGELOG.md
index 65e8afce..74205334 100644
--- a/docs/architecture/CHANGELOG.md
+++ b/docs/en/architecture/CHANGELOG.md
@@ -2,6 +2,10 @@
Doc revision history for `docs/architecture/`, seeded from commits touching architecture-relevant code.
+## 2026-09-02
+
+- **docs(architecture): cross-ref Idempotency-Key replay in degraded-mode doc** — `04-degraded-mode-and-failover.md:10` now maps the pre-routing idempotency lookup (`server/src/services/idempotency.ts`, `proxy.ts:1793-1838`) and post-success persist (`proxy.ts:2640-2656`) to the fallback loop, notes `X-Routed-Via: idempotency` zero-cost replay, `stream:true` + `finish_reason:length` exclusion, in-flight NOT deduplicated (`95bc46f`), `IDEMPOTENCY_TTL_MS` 24 h lazy sweep, and that `409` + replay bypass `isDegraded()` / retry budget / hedging. Client contract lives in `docs/api/02-idempotency.md` (`36b877d`).
+
## 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).
diff --git a/docs/architecture/OVERVIEW.md b/docs/en/architecture/OVERVIEW.md
similarity index 73%
rename from docs/architecture/OVERVIEW.md
rename to docs/en/architecture/OVERVIEW.md
index 3ad887c9..c16ab72f 100644
--- a/docs/architecture/OVERVIEW.md
+++ b/docs/en/architecture/OVERVIEW.md
@@ -2,7 +2,7 @@
## 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).
+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`](00-high-level-index.md).
## File Index
@@ -11,16 +11,16 @@ This domain holds the implementation deep-dives for FreeLLMAPI's server-side arc
| [`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) |
+| [`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), Idempotency-Key replay cross-ref (`36b877d`/`95bc46f`, `X-Routed-Via: idempotency`) |
| [`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`.
+The root [`architecture.md`](00-high-level-index.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
+- ↑ [High-level architecture index](00-high-level-index.md)
\ No newline at end of file
diff --git a/docs/en/cli/01-generators.md b/docs/en/cli/01-generators.md
new file mode 100644
index 00000000..b1c9b1c2
--- /dev/null
+++ b/docs/en/cli/01-generators.md
@@ -0,0 +1,66 @@
+# Setup generators
+
+## Usage
+
+```bash
+npx freellmapi setup-claude # wire Claude Code
+npx freellmapi setup-codex # wire Codex CLI
+npx freellmapi setup-dsh # wire DeepSeek Harness
+npx freellmapi setup-mimo # wire MiMo Code
+npx freellmapi setup-atomcode # wire AtomCode
+npx freellmapi --dry-run setup-claude # preview without writing
+npx freellmapi setup-claude --model gpt-4o # pin a model
+```
+
+Every generator (`cli/src/tools.ts:52-622`) fetches the live catalog, resolves `--model` against the unfiltered catalog (`c942352`), backs up existing config with a timestamped copy, merges without clobbering unrelated keys, and writes with `0600`.
+
+## Generator table
+
+| Command | Target file | Protocol | Notes |
+| --- | --- | --- | --- |
+| `setup-claude` | `~/.claude/settings.json` | Anthropic Messages | `ANTHROPIC_BASE_URL`/`AUTH_TOKEN`/`MODEL`, `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1`, `launch` zero-persistence launcher |
+| `setup-codex` | `~/.codex/config.toml` | OpenAI Responses | `[model_providers.freellmapi]` `wire_api=responses`, `launch-codex` launcher |
+| `setup-cline` | `~/.config/Code/User/settings.json` | OpenAI Chat | Cline VS Code extension |
+| `setup-continue` | `~/.continue/config.json` | OpenAI Chat | Continue ghost-text autocomplete |
+| `setup-aider` | `~/.aider.conf.yml` | OpenAI Chat | Aider pair-programmer |
+| `setup-opencode` | `~/.config/opencode/config.json` | OpenAI Chat | OpenCode agent |
+| `setup-goose` | `~/.config/goose/config.yaml` | OpenAI Chat | Goose agent |
+| `setup-qwen` | `~/.qwen/settings.json` | OpenAI/Gemini | Qwen Code, `/v1` or native `/v1beta` |
+| `setup-roo` | `~/.config/roo/config.json` | OpenAI Chat | Roo Code |
+| `setup-kilo` | `~/.config/kilo/config.json` | OpenAI Chat | Kilo Code |
+| `setup-crush` | `~/.config/crush/config.json` | OpenAI Chat | Crush (charmbracelet) |
+| `setup-dsh` | `~/.dsh/config.json` | OpenAI Chat | DeepSeek Harness (#995) |
+| `setup-mimo` | `~/.config/mimocode/config.json` | OpenAI Chat | MiMo Code `~/.config/mimocode/config.json` `default_provider=freellmapi` + `[providers.freellmapi]` `type=openai` `base_url=/v1` `api_key` `model` `context_window` (#1003) |
+| `setup-atomcode` | `~/.atomcode/config.toml` | OpenAI Chat | AtomCode `default_provider=freellmapi` + `[providers.freellmapi]` TOML preserve other providers (#1025) |
+| `setup-cursor` | guide only | OpenAI Chat | Manual `Cursor Settings → Models → Add Model` (no file) |
+| `setup-generic` | guide only | OpenAI Chat | Any OpenAI-compatible client |
+
+## Zero-persistence launchers
+
+```bash
+npx freellmapi launch # injects FREELLMAPI_API_KEY + model into `claude`
+npx freellmapi launch-codex # injects into `codex --profile NAME`
+```
+
+These do not write config files; they spawn the child process with `FREELLMAPI_API_KEY`/`FREELLMAPI_MODEL` in env only. Useful for ephemeral or shared machines.
+
+## `freellmapi doctor`
+
+```bash
+npx freellmapi doctor
+```
+
+Proves a client's requests reach this gateway (checks routed `Authorization` header, catalog, live probe).
+
+## Common flags
+
+| Flag | Effect |
+| --- | --- |
+| `--dry-run` | Preview changes without writing; shows diff |
+| `--model <id>` | Pin to a model (resolved against unfiltered catalog) |
+| `--profile <name>` | Named profile (Codex `codex --profile NAME`, Claude `CLAUDE_CONFIG_DIR`) |
+
+## Related
+
+- [Config files](02-config-files.md) — merge strategies, `tools.json`, adding a new generator.
+- [Clients & agents](../clients/01-agent-clients.md) — per-agent wiring recipes, headerless URL tokens, MCP.
diff --git a/docs/en/cli/02-config-files.md b/docs/en/cli/02-config-files.md
new file mode 100644
index 00000000..88171de5
--- /dev/null
+++ b/docs/en/cli/02-config-files.md
@@ -0,0 +1,38 @@
+# Config files
+
+## Registry — `cli/tools.json`
+
+`cli/tools.json` is the single source of truth for the generator list. Each entry has `id`, `name`, `category` (`code`|`agent`), `configType` (`file`|`guide`), `protocol` (`Anthropic Messages`|`OpenAI Chat`|`OpenAI Responses`), `baseUrlSupport`, `command` (`setup-*`), and `docsUrl`. `client/src/data/agent-tools.json` is the dashboard copy (keep in sync).
+
+## `cli/src/config-files.ts` — merge layer
+
+Every `Xxx()` generator in `cli/src/tools.ts` returns a `Generation { files: { path, format, sensitive, value }[], notes }`. `config-files.ts` applies each file via:
+
+- **JSON** (`settings.json`, `config.json`) — deep-merge, preserve unrelated keys; `0600` (`0o600`) on write.
+- **TOML** (`config.toml` for Codex, AtomCode) — structural merge preserves other `[providers.*]` tables; Codex's single-file `~/.codex/config.toml` uses `[profiles.NAME]` tables, not per-profile files.
+- **YAML** (`config.yaml` for Goose) — similar merge.
+
+### Backup
+
+Before first write, `config-files.ts` copies the existing file to `<path>.bak.<ISO timestamp>` (e.g. `settings.json.bak.2026-09-02T10-30-00-000Z`). No backup if the file didn't exist. The backup is also `0600`.
+
+### Dry run
+
+`--dry-run` runs the merge in memory, prints a diff, and exits without touching disk.
+
+### `tools.test.ts` snapshot
+
+`cli/src/__snapshots__/tools.test.ts.snap` pins the generated file contents for each generator; update with `npm run test -- -u` after changing a generator.
+
+## Adding a new generator
+
+1. Add entry to `cli/tools.json` (`id`, `name`, `category`, `configType`, `protocol`, `baseUrlSupport`, `command`, `docsUrl`).
+2. Add `function myTool(ctx: GenerateContext): Generation` in `cli/src/tools.ts` — return `files` with correct `path`/`format`/`value` and `notes` for the CLI output. Use helpers `rootUrl()`/`v1Url()`/`primaryModel()`/`contextWindow()`.
+3. Add snapshot case in `cli/src/tools.test.ts`.
+4. Document in [01-generators.md](01-generators.md) table + `docs/clients/01-agent-clients.md` section.
+5. Sync `client/src/data/agent-tools.json` if the dashboard lists it.
+
+## Related
+
+- [Generators](01-generators.md) — all `setup-*` commands and target files.
+- [Clients & agents](../clients/01-agent-clients.md) — per-agent recipes.
diff --git a/docs/en/cli/CHANGELOG.md b/docs/en/cli/CHANGELOG.md
new file mode 100644
index 00000000..74ef0153
--- /dev/null
+++ b/docs/en/cli/CHANGELOG.md
@@ -0,0 +1,11 @@
+# Changelog — cli
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `ddaea9c` | 2026-08-24 | Add AtomCode to the agents catalog (#1025) — `atomcode()` `~/.atomcode/config.toml` |
+| `1585e76` | 2026-08-23 | Add MiMo Code to the agents catalog and describe every agent card (#1003) — `mimo()` `~/.config/mimocode/config.json` |
+| `1a0ce48` | 2026-08-23 | Configure DeepSeek Harness in one command — `setup-dsh` (#995) |
+| `c942352` | 2026-08-23 | Resolve --model against the unfiltered catalog before launching (#861) |
+| `19168ac` | 2026-07-27 | Add end-to-end coding-agent compatibility suite (#629) |
+
+Regenerate: `git log --oneline -- cli/`
diff --git a/docs/en/cli/OVERVIEW.md b/docs/en/cli/OVERVIEW.md
new file mode 100644
index 00000000..718a676d
--- /dev/null
+++ b/docs/en/cli/OVERVIEW.md
@@ -0,0 +1,22 @@
+# CLI Domain — Overview & File Index
+
+## Scope
+
+This domain documents the FreeLLMAPI setup CLI (`cli/`) — the `npx freellmapi` generators that wire coding agents to the local gateway in one command. Each generator (`setup-claude`, `setup-codex`, …) fetches the live catalog, backs up existing config, never clobbers unrelated keys, and records `tools.json` metadata for `freellmapi launch` / `launch-codex` zero-persistence launchers and `freellmapi doctor`.
+
+Authoritative sources: [`cli/src/tools.ts`](../../../cli/src/tools.ts) (all `Xxx()` generator functions), [`cli/tools.json`](../../../cli/tools.json) (registry), [`cli/src/config-files.ts`](../../../cli/src/config-files.ts) (merge + `0600` + timestamped backup), [`cli/README.md`](../../../cli/README.md), [`client/src/data/agent-tools.json`](../../../client/src/data/agent-tools.json).
+
+For per-agent wiring recipes and the MCP/headerless-client story, see [Clients & coding agents](../clients/OVERVIEW.md). For the env vars the CLI injects (`FREELLMAPI_API_KEY`, `FREELLMAPI_MODEL`), see [env/](../env/OVERVIEW.md).
+
+## File Index
+
+| File | Description |
+| --- | --- |
+| [01-generators.md](01-generators.md) | All `setup-*` generators (claude/codex/cline/continue/aider/opencode/goose/qwen/roo/kilo/crush/cursor/dsh/mimo/atomcode/generic), target files, merge behavior, `--model` resolution, and `launch`/`launch-codex`/`doctor` commands. |
+| [02-config-files.md](02-config-files.md) | Config-file layer: `tools.json` registry, `config-files.ts` merge strategies (JSON/TOML/YAML), `0600` permissions, timestamped backups, `--dry-run`, and how to add a new generator. |
+| [CHANGELOG.md](CHANGELOG.md) | Doc revision history for this domain. |
+
+## Navigation
+
+- ← [Documentation root](../README.md)
+- ↑ [Docs index](../OVERVIEW.md)
diff --git a/docs/en/clients/01-agent-clients.md b/docs/en/clients/01-agent-clients.md
new file mode 100644
index 00000000..a8ff52bd
--- /dev/null
+++ b/docs/en/clients/01-agent-clients.md
@@ -0,0 +1,299 @@
+# Clients & coding agents
+
+[← Back to README](../README.md) · [Documentation index](../README.md)
+
+- [OpenAI-compatible clients](#openai-compatible-clients)
+- [Coding agents](#coding-agents)
+- [QwenPaw](#qwenpaw)
+- [Native Gemini clients](#native-gemini-clients)
+- [Ollama clients](#ollama-clients)
+- [Headerless clients](#headerless-clients)
+- [MCP server](#mcp-server)
+- [VS Code ghost-text autocomplete (Continue)](#vs-code-ghost-text-autocomplete-continue)
+- [Context Handoff](#context-handoff)
+
+## OpenAI-compatible clients
+
+Any client that can target an OpenAI-compatible base URL can use FreeLLMAPI:
+
+- **LangChain, LlamaIndex, official OpenAI SDKs**: set `base_url` to
+ `http://localhost:3001/v1` and use the unified key from the dashboard.
+- **Local GPU boxes**: add custom OpenAI-compatible endpoints for Ollama,
+ llama.cpp, LM Studio, vLLM, or an internal gateway.
+
+## Coding agents
+
+Use the generator instead of hand-editing a client configuration:
+
+```bash
+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
+and create a timestamped backup first. `--profile <name>` creates a named
+Claude/Codex profile. The live `/v1/models` catalog supplies the model ids and
+context windows.
+
+| Agent | Automated command | Manual base URL | Wire |
+| --- | --- | --- | --- |
+| **Claude Code** | `setup-claude` or credential-free-on-disk `launch` | `http://localhost:3001` | Anthropic Messages |
+| **Codex CLI** | `setup-codex` or `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 / legacy 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 (native Gemini also works) |
+| **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`) |
+| **MiMo Code** | `setup-mimo` | `http://localhost:3001/v1` | OpenAI Chat |
+| **AtomCode** | `setup-atomcode` | `http://localhost:3001/v1` | OpenAI Chat (`type = "openai"`) |
+| **QwenPaw** | Manual setup | `http://localhost:3001/v1` | OpenAI Chat (`chat.completions`) |
+| **Cursor** | `setup-cursor` prints the guide | public `https://…/v1` | OpenAI Chat |
+| **Anything else** | `setup-generic` prints a ready block | `http://localhost:3001/v1` | OpenAI Chat |
+
+The root-vs-`/v1` distinction matters: Claude Code expects the server root
+because it appends the Anthropic Messages path. OpenAI-compatible clients in
+this table—including Cline, Aider, Goose, Codex, Continue, OpenCode, Qwen,
+Roo, Kilo, Crush, MiMo Code, AtomCode, QwenPaw, and DeepSeek Harness—expect their configured
+base URL to include `/v1`.
+
+### DeepSeek Harness (`dsh`)
+
+[DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) keeps
+every provider as a route under `llm-pi-ai.providers` in
+`$DSH_HOME/settings.yaml` (`~/.dsh` by default). `setup-dsh` adds a
+`freellmapi` route there — `api: openai-completions`, the gateway's `/v1`
+base URL, and the live catalog as the route's `models` list, which DSH
+requires for a provider its installed catalog does not ship — and makes
+`freellmapi/auto` the default model. The key goes into `$DSH_HOME/.env`
+(mode 0600) as `FREELLMAPI_API_KEY`, the environment layer DSH reads on its
+own, so nothing needs exporting. Both writes are structural merges: other
+routes, comments, and settings in the file are left as they were.
+
+```bash
+npx freellmapi setup-dsh --url http://localhost:3001 --api-key <unified-key>
+npx @deepseek-ai/dsh web
+```
+
+Settings are hot-reloaded, so a running `dsh` uses the route on its next
+request. `--profile <name>` adds a second route (`freellmapi-<name>`) without
+changing the default model; `--model <id>` pins the default. Routes are
+declared text-only — add `input: [text, image]` to a model entry under
+`freellmapi.models` to send it images. `DSH_HOME` is honoured when set.
+
+### MiMo Code (`mimo`)
+
+[MiMo Code](https://mimo.xiaomi.com/mimocode) is an OpenCode derivative, so it
+takes any OpenAI-compatible endpoint as a custom entry under `provider` — an
+`npm` package to speak with (`@ai-sdk/openai-compatible`), the credentials in
+`options`, and a `models` map. `setup-mimo` writes that entry as `freellmapi`
+and names `freellmapi/<model>` as the default `model`.
+
+The file is `config.json` in MiMo's own global config directory:
+`$XDG_CONFIG_HOME/mimocode` (`~/.config/mimocode` on macOS and Linux), or
+`$MIMOCODE_HOME/config` when `MIMOCODE_HOME` is set. That directory merges
+`config.json`, `mimocode.json` and `mimocode.jsonc` in that order, so the
+generated file is the weakest layer and anything you hand-write in
+`mimocode.json` still wins. The write itself is a structural merge, so other
+providers and settings already in `config.json` are left as they were.
+
+```bash
+npx freellmapi setup-mimo --url http://localhost:3001
+export FREELLMAPI_API_KEY=<unified-key>
+mimo
+```
+
+The key is referenced as `{env:FREELLMAPI_API_KEY}`, MiMo's own substitution
+syntax, so it stays out of the config file. There is no `MIMOCODE_API_KEY` or
+`MIMOCODE_BASE_URL`: MiMo's environment variables locate resources and toggle
+features, they are not a general fallback for config fields. Each model is
+declared with the `limit.context` and `limit.output` pair MiMo's schema
+requires, both taken from the live catalog.
+
+### AtomCode (`atomcode`)
+
+[AtomCode](https://atomcode.atomgit.com/docs/en/) is AtomGit's terminal
+coding agent, written in Rust. It reads `~/.atomcode/config.toml`, where a
+root `default_provider` key names one `[providers.<id>]` table and
+`type = "openai"` makes that table speak the OpenAI-compatible wire.
+`setup-atomcode` writes a `[providers.freellmapi]` table — `base_url` on the
+gateway's `/v1`, the unified key as `api_key`, the chosen model and its
+`context_window` from the live catalog — and sets `default_provider` to it.
+The write is a structural merge: the root key is placed above any existing
+tables, only the `freellmapi` table is replaced, and other `[providers.*]`
+tables and settings in the file are left as they were.
+
+```bash
+npx freellmapi setup-atomcode --url http://localhost:3001 --api-key <unified-key>
+atomcode
+```
+
+AtomCode has no environment-variable fallback for the key, so it is written
+into the config file; the file is created with mode 0600 and a timestamped
+backup is taken before an existing one is changed. `--model <id>` pins the
+default model.
+
+### QwenPaw
+
+[QwenPaw](https://github.com/agentscope-ai/QwenPaw) supports custom providers
+that use the OpenAI `chat.completions` API. Start FreeLLMAPI, create or copy a
+unified key from its dashboard, then open **Settings → Models** in the QwenPaw
+Console:
+
+1. Under **Providers**, choose **Add Provider**.
+2. Give it a **Provider ID** such as `freellmapi` and a **Provider Name** such
+ as `FreeLLMAPI`, and set the API compatibility mode to OpenAI
+ `chat.completions`.
+3. Open the new provider's settings and set **Base URL** to
+ `http://localhost:3001/v1` and **API Key** to your FreeLLMAPI unified key.
+4. On the provider's models page, add a model. Use `auto` as the **Model ID**
+ to let FreeLLMAPI route the request, or copy a current id from
+ `GET http://localhost:3001/v1/models`.
+5. Save, then pick the model as the default (or per chat) and send a test
+ message.
+
+If QwenPaw runs in a container, `localhost` refers to that container rather
+than the host running FreeLLMAPI. Use a hostname or host-gateway address that
+the QwenPaw container can reach, while keeping the `/v1` suffix. Do not put the
+unified key in a URL, screenshot, or issue report. See QwenPaw's
+[official model configuration guide](https://qwenpaw.agentscope.io/docs/models)
+for the current Console field names.
+
+## Native Gemini clients
+
+Gemini CLI and Gemini-lineage clients can speak Google's wire format directly:
+
+```bash
+export GOOGLE_GEMINI_BASE_URL=http://localhost:3001
+export GEMINI_API_KEY=freellmapi-your-unified-key
+gemini
+```
+
+The native surface implements `GET /v1beta/models`, model metadata,
+`generateContent`, `streamGenerateContent` (including `?alt=sse`), and
+`countTokens`. Authentication accepts `x-goog-api-key`, Bearer, or Gemini's
+`?key=` fallback. Prefer the header: query credentials leak into history and
+proxy logs.
+
+The **Keys → Agents** tab maps Gemini Pro, Flash, and Flash-Lite family names to
+Auto or a pinned catalog model.
+
+## Ollama clients
+
+Ollama emulation is off by default. Enable one of these modes on
+**Keys → Agents**:
+
+- `open-loopback`: no key on this machine only. The socket peer must be
+ `127.0.0.1`/`::1`; enabling desktop LAN access does not widen it.
+ **Docker note:** inside a container the socket peer is the Docker bridge
+ IP, not loopback, so this mode refuses even host-local traffic through a
+ published port — use `key-required` for Docker deployments.
+- `key-required`: clients must send `Authorization: Bearer <unified-key>`.
+
+The exact endpoints are `/api/tags`, `/api/chat`, `/api/generate`, `/api/show`,
+`/api/version`, `/api/embed`, and legacy `/api/embeddings`. Streaming uses
+newline-delimited JSON, not SSE. Point Zed, JetBrains AI Assistant, or another
+Ollama-capable client at `http://localhost:3001`.
+
+## Headerless clients
+
+If a client cannot set headers, create a separately revocable token on
+**Keys → Agents** and use:
+
+```text
+http://localhost:3001/v1/t/<token>/chat/completions
+http://localhost:3001/v1/t/<token>/responses
+http://localhost:3001/v1/t/<token>/models
+```
+
+The same prefix exposes `/api/chat` and `/api/tags`. Never put the unified API
+key in a URL. URL tokens have independent hashes and immediate revocation
+because URLs routinely leak into shell history, reverse-proxy logs, and
+telemetry.
+
+## MCP server
+
+On top of inference, the router is an **MCP server**: agents can introspect it mid-session
+(usable models and the params each one honors, provider health, usage and cache stats,
+routing strategy).
+
+The MCP surface is a setting rather than an always-on endpoint (#925). **Fresh installs
+start with it off**; installs that already had provider keys configured when they upgraded
+keep it on, so an existing Claude Code or Cline session does not break on upgrade. Toggle
+it on the Keys page under **Agent compatibility**, or from the API:
+
+```bash
+curl -X PUT http://localhost:3001/api/settings/enable-mcp \
+ -H "Authorization: Bearer <dashboard-token>" -H "Content-Type: application/json" \
+ -d '{"enabled": true}'
+```
+
+While it is off, every verb on `/mcp` answers `403` with a JSON-RPC error saying so.
+
+For Claude Code:
+
+```bash
+claude mcp add --transport http freellmapi http://localhost:3001/mcp \
+ --header "Authorization: Bearer freellmapi-your-unified-key"
+```
+
+Any MCP client that speaks Streamable HTTP works the same way: point it at `/mcp` with the
+unified key as a Bearer token.
+
+FreeLLMAPI is local-first and single-user by design. Your provider keys stay in
+your SQLite database, encrypted at rest, and requests go from your machine to the
+upstream providers you enabled.
+
+## VS Code ghost-text autocomplete (Continue)
+
+FreeLLMAPI exposes `/v1/completions` for editor autocomplete clients that send legacy OpenAI prompt/suffix requests. Example Continue config:
+
+```yaml
+models:
+ - name: FreeLLMAPI Autocomplete
+ provider: openai
+ model: auto
+ apiBase: http://localhost:3001/v1
+ apiKey: freellmapi-your-unified-key
+ useLegacyCompletionsEndpoint: true
+ roles:
+ - autocomplete
+```
+
+## Context Handoff
+
+When FreeLLMAPI falls over to a different model mid-conversation (quota, rate limit, cooldown), the new model has no idea it is picking up someone else's task. **Context handoff** adds a single compact `system` message to the outbound request that tells the new model exactly that:
+
+```
+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: …
+```
+
+**Enable it in `.env`:**
+
+```env
+FREELLMAPI_CONTEXT_HANDOFF=on_model_switch
+```
+
+**How it works:**
+
+- Messages per session are stored in memory (TTL: 3 hours).
+- Only injected when the selected model changes for a given session key.
+- Not injected on the first request, on same-model continuations, or if a handoff message is already present.
+- Session key: `X-Session-Id` header if present, otherwise SHA-1 of the first user message (same as sticky sessions).
+- Storage is in-memory only. Nothing is written to disk or logged.
+
+> **Important:** Context Handoff improves continuity for conversations routed through FreeLLMAPI. It cannot recover provider-internal hidden state or messages that were never sent to the proxy.
diff --git a/docs/clients/CHANGELOG.md b/docs/en/clients/CHANGELOG.md
similarity index 100%
rename from docs/clients/CHANGELOG.md
rename to docs/en/clients/CHANGELOG.md
diff --git a/docs/clients/OVERVIEW.md b/docs/en/clients/OVERVIEW.md
similarity index 89%
rename from docs/clients/OVERVIEW.md
rename to docs/en/clients/OVERVIEW.md
index e2b1a28f..efc62a65 100644
--- a/docs/clients/OVERVIEW.md
+++ b/docs/en/clients/OVERVIEW.md
@@ -18,4 +18,4 @@ feature for mid-conversation model switches.
- [../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
+- [../../zh-cn/clients/](../../zh-cn/clients/) — Simplified Chinese mirror (when translated).
\ No newline at end of file
diff --git a/docs/compression/01-compression-pipeline.md b/docs/en/compression/01-compression-pipeline.md
similarity index 100%
rename from docs/compression/01-compression-pipeline.md
rename to docs/en/compression/01-compression-pipeline.md
diff --git a/docs/compression/CHANGELOG.md b/docs/en/compression/CHANGELOG.md
similarity index 100%
rename from docs/compression/CHANGELOG.md
rename to docs/en/compression/CHANGELOG.md
diff --git a/docs/compression/OVERVIEW.md b/docs/en/compression/OVERVIEW.md
similarity index 87%
rename from docs/compression/OVERVIEW.md
rename to docs/en/compression/OVERVIEW.md
index 376503a9..77b64c6b 100644
--- a/docs/compression/OVERVIEW.md
+++ b/docs/en/compression/OVERVIEW.md
@@ -18,4 +18,4 @@ tool-output filters, and the statistics/preview APIs.
- [../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
+- [../../zh-cn/compression/](../../zh-cn/compression/) — Simplified Chinese mirror (when translated).
\ No newline at end of file
diff --git a/docs/deployment/01-docker.md b/docs/en/deployment/01-docker.md
similarity index 98%
rename from docs/deployment/01-docker.md
rename to docs/en/deployment/01-docker.md
index 0a4729e5..fa99dc15 100644
--- a/docs/deployment/01-docker.md
+++ b/docs/en/deployment/01-docker.md
@@ -21,7 +21,7 @@ docker pull ghcr.io/tashfeenahmed/freellmapi:latest # or pin a release, e.g. :
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)):
+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`.
@@ -44,7 +44,7 @@ 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:
+Windows PowerShell variant and a curl one-liner bootstrap live in [`docs/install.md`](../install/01-install.md#docker-compose). Then follow the logs:
```bash
docker compose logs -f freellmapi
diff --git a/docs/deployment/02-updates-and-backup.md b/docs/en/deployment/02-updates-and-backup.md
similarity index 100%
rename from docs/deployment/02-updates-and-backup.md
rename to docs/en/deployment/02-updates-and-backup.md
diff --git a/docs/deployment/CHANGELOG.md b/docs/en/deployment/CHANGELOG.md
similarity index 100%
rename from docs/deployment/CHANGELOG.md
rename to docs/en/deployment/CHANGELOG.md
diff --git a/docs/deployment/OVERVIEW.md b/docs/en/deployment/OVERVIEW.md
similarity index 84%
rename from docs/deployment/OVERVIEW.md
rename to docs/en/deployment/OVERVIEW.md
index 81257c3e..f3d1a63b 100644
--- a/docs/deployment/OVERVIEW.md
+++ b/docs/en/deployment/OVERVIEW.md
@@ -2,9 +2,9 @@
## 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).
+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/01-install.md).
-For installation paths beyond Docker (one-liner script, local development, desktop app), see [Install & deploy](../install.md).
+For installation paths beyond Docker (one-liner script, local development, desktop app), see [Install & deploy](../install/01-install.md).
## File index
diff --git a/docs/en/desktop/01-desktop-app.md b/docs/en/desktop/01-desktop-app.md
new file mode 100644
index 00000000..77c68373
--- /dev/null
+++ b/docs/en/desktop/01-desktop-app.md
@@ -0,0 +1,59 @@
+# Desktop app
+
+## Package manifest
+
+`desktop/package.json` `[email protected]` — Electron `38.8.6`, `[email protected]`, `[email protected]`, `[email protected]`. Entry `build/main.mjs` (`type: module`). AppId `com.freellmapi.desktop`, publish `github:tashfeenahmed/freellmapi` (`desktop/electron-builder.yml`). `asar` + `client-dist` in `extraResources`; per-OS signing targets (mac `dmg` `arm64` signed/notarized/stapled via `refresh-mac-update-metadata.mjs`, win `nsis`+`zip` `x64`, linux `AppImage`+`deb`+`tar.xz`+`rpm` `x64` since #981 `d8fae97`).
+
+## Build pipeline
+
+```
+bundle:server → build:main / build:preload → stage:client → electron-builder
+```
+
+- `scripts/bundle-server.mjs` esbuild `define: { 'process.env.FREELLMAPI_COMMIT_SHA', 'process.env.FREELLMAPI_INSTALL_METHOD' }` from `GITHUB_SHA` (40-hex); mirrored into live `process.env` in `server-host.ts` so `routes/update.ts` resolves.
+- `build/main.mjs` bundles `src/main.ts` (`--platform=node --format=esm --external:electron --external:./server.mjs`), `build/preload` for `preload.ts`/`preload-popover.ts`.
+- `scripts/stage-client.mjs` copies `client/dist` → `build/client-dist` or `Resources/client-dist` in packaged app; dev override via `FREEAPI_REPO`.
+
+## Runtime layout
+
+| Path | Notes |
+| --- | --- |
+| `<userData>/freeapi.db` | SQLite DB (`freeapi.db` + WAL/`-shm`), same schema as Docker/Node |
+| `<userData>/config.json` | Port (`31415` default), `lanAccess`, theme/locale |
+| `<userData>/logs/freeapi.log` | 1 MB + `freeapi.log.1` rotation (`desktop/src/logger.ts`) |
+| `<userData>/backups` | Server dumps (`services/backups.ts` `dataDir()`) |
+| `Resources/client-dist` | Packaged client; dev: `client/dist` via `FREEAPI_REPO` |
+
+`~/Library/Application Support/FreeLLMAPI` (macOS), `%APPDATA%/FreeLLMAPI` (Windows), `~/.config/FreeLLMAPI` (Linux).
+
+## Embedded server-host
+
+`desktop/src/server-host.ts` is the **only** module allowed to import `server/src/*` (`desktop/README.md`). It bundles the server via `bundle-server.mjs` and re-exports the DB singleton (`getDb`, `getUnifiedApiKey`) to avoid a second copy in the main bundle.
+
+Boot sequence mirrors `server/src/index.ts` step-for-step (`#949`); `__tests__/server-host-boot.test.ts` cross-checks the list so a new step added to `index.ts` fails a desktop test instead of silently never running (how `startBackupScheduler` was missed):
+
+`installLogRedaction` → `installProcessSafetyNet` → `initDb` → `ensureSessionToken` → `restoreProxySettings`/`flushProxyCache` → `startHealthChecker`/`checkAllKeys` → `startCatalogSync` → `startCooldownProbe` → `startCustomModelSync` → `startBackupScheduler` → `cleanupExpiredCooldowns` → `startWakeDetect` → `createApp` → `listenWithScan` (port `31415`, scan `+50` on conflict, persist to `config.json`).
+
+Deliberately NOT mirrored: `restoreDbBackupIfNeeded`/`startDbBackupPump` (`FREEAPI_DB_BACKUP_*` env-only, packaged app inherits no shell env).
+
+`listenWithScan` binds `127.0.0.1` by default; `lanAccess` → `0.0.0.0` (relaunch required).
+
+## Main-process wiring (`desktop/src/main.ts`)
+
+- Single-instance lock (`app.requestSingleInstanceLock`); second launch focuses existing window.
+- `userData` override from `FREEAPI_REPO` dev path.
+- `installFileLogger` ordering — must run before any `console.log` the server will emit.
+- Theme/locale mirroring from system.
+- `FREEAPI_SHOT` capture mode for screenshots.
+
+## Tray / popover / window
+
+- `desktop/src/tray.ts` — menu-bar icon, `Open Logs Folder` / `Open Backups Folder` (`logger.ts:openLogsFolder`/`openBackupsFolder` via `shell.openPath`), `Open FreeLLMAPI`, quit.
+- `desktop/src/popover.ts` — popover window for quick access.
+- `desktop/src/window.ts` — main BrowserWindow chrome.
+
+## Related
+
+- [Logging and updates](02-logging-and-updates.md) — `freeapi.log` rotation, update delivery, signing.
+- [Install & deploy](../install/01-install.md) — desktop vs Docker vs local dev.
+- [Logs viewer](../logs/01-server-logs-viewer.md) — the polling API the desktop log tap feeds.
diff --git a/docs/en/desktop/02-logging-and-updates.md b/docs/en/desktop/02-logging-and-updates.md
new file mode 100644
index 00000000..8139e7c9
--- /dev/null
+++ b/docs/en/desktop/02-logging-and-updates.md
@@ -0,0 +1,50 @@
+# Logging and updates — desktop
+
+## Why `freeapi.log` exists (#824)
+
+The embedded server prints operational output to `console` — including the one-time password-reset code that `POST /api/auth/forgot-password` prints and nothing else ever shows. A server operator reads it from `docker logs` or the terminal. A Finder/Explorer-launched Electron app has no attached `stdout`, so that code was unreadable and the reset flow could never complete. Hence `desktop/src/logger.ts` tees `console` into `<userData>/logs/freeapi.log` (90aaa5b).
+
+## `logger.ts` — `FileSink` + rotation
+
+- `LOG_NAME=freeapi.log`, `PREVIOUS_NAME=freeapi.log.1`, `MAX_LOG_BYTES=1 MB` (`desktop/src/logger.ts:18-21`). Two files, 1 MB each — enough history for a reset or bad boot, small enough nobody's disk notices.
+- `createFileSink(dir, maxBytes=1M)` — appends to `freeapi.log`, rotates to `freeapi.log.1` once it passes `maxBytes` (rotate *before* the write that would cross the limit, never on empty file). Synchronous `fs.writeSync` so a code printed a moment before the app quits is already on disk. Every filesystem call wrapped — logging never crashes the app.
+- `installFileLogger(dir=logsDir())` — wraps `console.log/info/warn/error`, prefixes `ISO timestamp [level]`, forwards to original console *and* `sink.write`. Idempotent (`installed` flag). `process.on('exit', () => sink.close())`. The only dashboard-logs feed on desktop is this tap (#993 coordination with `server/src/lib/server-logs.ts` — the server's in-memory ring + DB persisted `warn`/`error`).
+- `openLogsFolder()` / `openBackupsFolder()` — `fs.mkdirSync(..., { recursive: true })` then `shell.openPath`; create dir first so reveal works even before anything written. Tray → “Open Logs Folder” / “Open Backups Folder”.
+
+```ts
+// Ordering matters — install before any server console output
+import { installFileLogger } from './logger.js';
+installFileLogger(); // before createApp / server boot
+```
+
+## Tray discoverability
+
+The tray menu exposes both folders; `openBackupsFolder` resolves to `<userData>/backups` (where `server/src/services/backups.ts` `dataDir()` writes dumps). The dashboard's Backups panel shows paths relative to that directory.
+
+## Update delivery
+
+### Electron-builder publish
+
+`desktop/electron-builder.yml` `publish: { provider: github, owner: tashfeenahmed, repo: freellmapi }` — artifacts (`dmg`, `nsis`, `zip`, `AppImage`, `deb`, `tar.xz`, `rpm`) upload on `desktop-release.yml` (`*.rpm` glob since d8fae97). `latest.yml` / `latest-mac.yml` generated per channel.
+
+### Build identity
+
+`scripts/bundle-server.mjs` `define: { 'process.env.FREELLMAPI_COMMIT_SHA': JSON.stringify(GITHUB_SHA), 'process.env.FREELLMAPI_INSTALL_METHOD': '"desktop"' }` — 40-hex SHA stamped at build, mirrored into live `process.env` in `server-host.ts` so `server/src/routes/update.ts` resolves the running commit vs `GET /api/update` available. `FREEAPI_VERSION` from `app.getVersion()` (`0.9.2`).
+
+### In-dashboard checker
+
+The dashboard polls `GET /api/update` (checker #635/#703) — shows banner when `latest > running`, with release notes. Desktop and Docker/Node share the same checker; desktop additionally offers auto-update via Squirrel.
+
+### macOS signing / notarization
+
+Signed + notarized via `electron-builder` (`#373`/`#1035`): `CSC_*`, `APPLE_ID` secrets in `desktop-release.yml`. DMG re-stamp after ticket stapling via `scripts/refresh-mac-update-metadata.mjs` (the `latest-mac.yml` `sha512` must match the stapled DMG, not the pre-staple one). Linux `rpm` beside `deb` since `d8fae97`.
+
+### Why unsigned builds cannot auto-update
+
+`Squirrel.Mac` verifies the code signature before applying an update. An unsigned `dmg` (local `npm run dist` without certs) produces a valid app but no valid update feed — the auto-updater will fetch `latest-mac.yml` then refuse to apply. Manual download is required.
+
+## Related
+
+- [Desktop app](01-desktop-app.md) — package manifest, build pipeline, runtime layout.
+- [Logs viewer](../logs/01-server-logs-viewer.md) — the polling API the desktop tap feeds.
+- [Observability](../architecture/06-observability.md) — server store internals (ring + DB).
diff --git a/docs/en/desktop/CHANGELOG.md b/docs/en/desktop/CHANGELOG.md
new file mode 100644
index 00000000..2bedaea0
--- /dev/null
+++ b/docs/en/desktop/CHANGELOG.md
@@ -0,0 +1,14 @@
+# Changelog — desktop
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `90aaa5b` | 2026-08-24 | Desktop log file plus a passwords, logs and uninstall FAQ (#1002) — `desktop/src/logger.ts` `FileSink` + rotation + tray open folders |
+| `4774cf0` | 2026-08-23 | Bring the desktop boot sequence up to server parity and bump to 0.8.7 (#1017) — `server-host.ts` mirrors `index.ts` steps, cross-checked by `server-host-boot.test.ts` |
+| `73178f3` | 2026-08-23 | Fix: outlive the reverse proxy's idle connection pool (#1116) — keepAlive path touches server-host |
+| `d8fae97` | 2026-08-23 | Add an rpm target to the Linux desktop build (#981) — `electron-builder.yml` `rpm x64` beside `deb` |
+| `3b6f40e` | 2026-08-23 | Bump desktop to v0.9.0 (#1044) — version bump |
+| `9196ed0` | 2026-08-23 | Mac builds are signed and notarized — closes #373 #943 (#1035) |
+| `e70d130` | 2026-08-23 | Notarize the DMG itself, not just the app inside it (#1036) |
+| `c8e05f0` | 2026-08-23 | Bump desktop to v0.9.1 (#1115) |
+
+Regenerate: `git log --oneline -- desktop/`
diff --git a/docs/en/desktop/OVERVIEW.md b/docs/en/desktop/OVERVIEW.md
new file mode 100644
index 00000000..59963438
--- /dev/null
+++ b/docs/en/desktop/OVERVIEW.md
@@ -0,0 +1,44 @@
+# Desktop Domain — Overview & File Index
+
+## Scope
+
+This domain documents the FreeLLMAPI desktop app — a lean Electron menu-bar utility (`desktop/`) that bundles the entire router and dashboard into a single local process. The app has no attached `stdout` when launched from Finder/Explorer, so operational lines (including the one-time password-reset code) would otherwise be lost; it pins the server to a scanned loopback port, mints a hidden machine user (`desktop@localhost`) for the dashboard, and exposes tray, popover, and update plumbing that do not exist in the Docker or plain-Node flows.
+
+Authoritative sources: [`desktop/package.json`](../../../desktop/package.json) (version `0.9.2`, `[email protected]`, `[email protected]`, scripts), [`desktop/electron-builder.yml`](../../../desktop/electron-builder.yml) (AppId `com.freellmapi.desktop`, publish provider `github:tashfeenahmed/freellmapi`, `asar` + `client-dist` extraResources, per-OS signing targets), [`desktop/src/logger.ts`](../../../desktop/src/logger.ts) (file tee at `<userData>/logs/freeapi.log`, 1 MB rotation, synchronous never-crash wrapper), [`desktop/src/server-host.ts`](../../../desktop/src/server-host.ts) (only module allowed to import `server/src/*`, `startServer`/`ensureSessionToken`/`listenWithScan`, boot parity with `server/src/index.ts` cross-checked by `__tests__/server-host-boot.test.ts`), [`desktop/src/main.ts`](../../../desktop/src/main.ts) (single-instance lock, `userData` override, `installFileLogger` ordering, theme/locale mirroring, LAN toggle, `FREEAPI_SHOT`), [`desktop/src/config.ts`](../../../desktop/src/config.ts), [`desktop/src/tray.ts`](../../../desktop/src/tray.ts), [`desktop/src/window.ts`](../../../desktop/src/window.ts), [`desktop/src/popover.ts`](../../../desktop/src/popover.ts), [`desktop/scripts/bundle-server.mjs`](../../../desktop/scripts/bundle-server.mjs) (esbuild `define` for `FREELLMAPI_COMMIT_SHA` + `FREELLMAPI_INSTALL_METHOD`), and [`desktop/scripts/refresh-mac-update-metadata.mjs`](../../../desktop/scripts/refresh-mac-update-metadata.mjs) (DMG re-stamp after stapling).
+
+For installation from the user's point of view — quick start, Docker vs local dev vs desktop, data locations, and FAQ — see [Install & deploy](../install/01-install.md). For the image/Compose path, see [deployment/](../deployment/OVERVIEW.md). For the dashboard log viewer that the desktop embedder feeds, see [logs/](../logs/OVERVIEW.md) and the internals note in [architecture/06-observability.md](../architecture/06-observability.md).
+
+## File Index
+
+| File | Description |
+| --- | --- |
+| [01-desktop-app.md](01-desktop-app.md) | The Electron app shape: package manifest, build pipeline (`bundle:server` → `build:main`/`build:preload` → `stage:client` → `electron-builder`), runtime layout (`<userData>/freeapi.db`, `config.json`, `client-dist` in `extraResources`), embedded `server-host` boot sequence and its parity guard, main-process wiring (single instance, `userData` override, theme/locale, tray/popover/dashboard, LAN toggle, `FREEAPI_SHOT` capture), window chrome, and per-OS packaging/signing targets. |
+| [02-logging-and-updates.md](02-logging-and-updates.md) | File logging and update delivery: why `freeapi.log` exists (#824 password-reset story), `logger.ts` `FileSink` + rotation + `installFileLogger`/`openLogsFolder`/`openBackupsFolder`, ordering under the redaction tap (the only dashboard-logs feed on desktop, #993), tray discoverability, and the update surface (`electron-builder` `publish` + `latest.yml`, `FREELLMAPI_COMMIT_SHA` `define` mirrored into `process.env`, `FREEAPI_VERSION` from `app.getVersion()`, in-dashboard checker #635/#703, macOS signing/notarization #373/#1035, DMG re-stamping after ticket stapling, and why unsigned builds cannot auto-update via `Squirrel.Mac`). |
+| [CHANGELOG.md](CHANGELOG.md) | Doc revision history for this domain, seeded from desktop-relevant commits. |
+
+## Quick facts
+
+| Aspect | Value |
+| --- | --- |
+| Package | `freellmapi-desktop` `0.9.2` at [`desktop/package.json`](../../../desktop/package.json) |
+| Entry | `build/main.mjs` (`type: module`, Electron `38.8.6`) |
+| DB + config | `<userData>/freeapi.db` + `<userData>/config.json` (`~/Library/Application Support/FreeLLMAPI` on macOS, `%APPDATA%/FreeLLMAPI` on Windows) |
+| Log file | `<userData>/logs/freeapi.log` (1 MB, rotated to `freeapi.log.1`, sync tee — [`desktop/src/logger.ts`](../../../desktop/src/logger.ts)) |
+| Backups | `<userData>/backups` (tray → Open Backups Folder; server writes via `services/backups.ts`) |
+| Default port | `31415` on `127.0.0.1`; scans `+50` on conflict, persisted to `config.json`; `lanAccess` → `0.0.0.0` (relaunch required) |
+| Client bundle | `Resources/client-dist` (packaged) or `client/dist` from the monorepo in dev (`FREEAPI_REPO` override) |
+| Build identity | `bundle-server.mjs` `define: { 'process.env.FREELLMAPI_COMMIT_SHA', 'process.env.FREELLMAPI_INSTALL_METHOD' }` stamped from `GITHUB_SHA` (40-hex), mirrored into live `process.env` in `server-host.ts` so `routes/update.ts` resolves correctly |
+| Packaged targets | mac `dmg` `arm64` (signed, notarized, stapled), win `nsis` + `zip` `x64`, linux `AppImage`+`deb`+`tar.xz`+`rpm` `x64` (+ `rpm` since #981 `d8fae97`) |
+
+## Related
+
+- [Desktop README](../../../desktop/README.md) — prerequisites, `npm run desktop:dist`/`desktop:dev`, native rebuild note.
+- [Install & deploy](../install/01-install.md) — desktop column next to Docker/local-dev, data-location table, uninstall/FAQ.
+- [Deployment](../deployment/OVERVIEW.md) — Docker image/Compose operations (the other install shape).
+- [Logs viewer](../logs/01-server-logs-viewer.md) and [Observability](../architecture/06-observability.md) — the polling API and store internals that the desktop log tap feeds.
+- [Providers](../providers/OVERVIEW.md) — what the embedded router actually proxies once running.
+
+## Navigation
+
+- ← [Documentation root](../README.md)
+- ↑ [Docs index](../OVERVIEW.md)
diff --git a/docs/env/01-variables.md b/docs/en/env/01-variables.md
similarity index 71%
rename from docs/env/01-variables.md
rename to docs/en/env/01-variables.md
index 821b933a..109fa04c 100644
--- a/docs/env/01-variables.md
+++ b/docs/en/env/01-variables.md
@@ -1,6 +1,6 @@
# 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.
+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)
@@ -10,8 +10,9 @@ Every variable FreeLLMAPI reads from `.env`, grouped by concern. Defaults and de
- [Outbound proxies](#outbound-proxies)
- [Request body & media limits](#request-body--media-limits)
- [Storage, cache, analytics & misc](#storage-cache-analytics--misc)
+- [Idempotency](#idempotency)
-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.
+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; [`../proxy/01-fetch-relay.md`](../proxy/01-fetch-relay.md) details the Fetch Relay transport.
## Server & binding
@@ -22,6 +23,7 @@ Related reading: [02-security-and-keys.md](02-security-and-keys.md) expands on `
| `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). |
+| `TRUST_PROXY` | `false` | Trust forwarded headers (`X-Forwarded-For` / `X-Forwarded-Proto`) from a reverse proxy so Analytics and IP-based rate limiting see the real client IP (`server/src/lib/config.ts:95-110`, `.env.example:314`). Accepts `false` (default — do not trust; direct callers cannot spoof), `true` (trust every hop — only on a fully trusted network), a non-negative integer hop count e.g. `1` for a single reverse proxy (Caddy/nginx/Traefik on the same host — Express `trust proxy: 1` idiom), or a comma-separated list of proxy addresses/CIDRs e.g. `100.64.0.0/10,192.168.1.10`. Parsed by `parseTrustProxy()` and forwarded to Express `trust proxy`; when trusted, `client-context` and the per-IP rate limiters read the left-most untrusted `X-Forwarded-For` entry. See [03-outbound-proxies.md](03-outbound-proxies.md) inbound vs outbound callout. |
## Outbound proxies (local destinations)
@@ -43,8 +45,8 @@ First-run note: the first dashboard account is normally created from a browser o
| 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. |
+| `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. When `TRUST_PROXY` is set, the limiter counts the real client IP from `X-Forwarded-For` instead of the socket peer. |
+| `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. Also respects `TRUST_PROXY`. |
## Routing overrides, timeouts & failover
@@ -67,15 +69,17 @@ First-run note: the first dashboard account is normally created from a browser o
| 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. |
+| `PROXY_MODE` | `forward` | Selects how the outbound proxy URL is used (`server/src/lib/proxy.ts:52` `PROXY_MODES`, `.env.example:76`). `forward` (default) — ordinary forward proxy (HTTP/SOCKS) via undici `ProxyAgent` / `SocksProxyAgent`; `fetch-relay` (opt-in) — application-layer relay that forwards the provider request with `Fetch-Relay-Target` / `Fetch-Relay-Authorization` headers (`server/src/lib/proxy.ts:52-414`). When `fetch-relay`, `PROXY_URL` is interpreted as the relay endpoint and must be `https` (or `http` only for loopback hosts per `isLoopbackRelayHostname` — `localhost`, `127.0.0.1`, `::1`, `127.*`). A legacy `PROXY_URL` without an explicit `PROXY_MODE` always stays `forward` regardless of a saved dashboard mode. See [`../proxy/01-fetch-relay.md`](../proxy/01-fetch-relay.md) (owned by another writer; link assumes it will exist). |
+| `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. In `fetch-relay` mode this is the relay URL, not a forward proxy. |
+| `FETCH_RELAY_TOKEN` | Unset (empty → unauthenticated) | Bearer credential FreeLLMAPI uses to authenticate to the Fetch Relay (`server/src/lib/proxy.ts:389-417`, `.env.example:78`). Sent as `Fetch-Relay-Authorization: Bearer <token>` on the relay hop (separate from the provider's `Authorization` header, which is preserved). Encrypted at rest when saved via the dashboard (`encodeFetchRelayToken` → `encrypt()` JSON envelope `{encrypted,iv,authTag}` in the settings table; decrypted by `decodeFetchRelayToken`); the env var `FETCH_RELAY_TOKEN` never enters the DB and takes precedence over the dashboard value (`readEnv('FETCH_RELAY_TOKEN') || dbValue`). Empty means the relay is unauthenticated. A plaintext relay to a remote host leaks both the provider key and this token — `fetchRelayUrlError()` warns at boot and the probe fails 401/403 as relay rejection. Details in [`../proxy/01-fetch-relay.md`](../proxy/01-fetch-relay.md). |
| `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. |
+| `HTTP_PROXY` | Unset | Standard proxy variable, fifth in the precedence chain (before system fallback). |
+| `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. Also see `FREEAPI_PROXY_LOCAL_DESTINATIONS` above for local/LAN bypass. |
-**Precedence:** `PROXY_URL` → dashboard setting → `ALL_PROXY` → `HTTPS_PROXY` → `HTTP_PROXY`. The standard variables are also read in their lower-case spellings.
+**Precedence:** `PROXY_URL` → dashboard setting → `ALL_PROXY` → `HTTPS_PROXY` → `HTTP_PROXY` → `detectSystemProxy()` system fallback → direct. The standard variables are also read in their lower-case spellings. The final fallback reads the OS-wide proxy (`server/src/lib/proxy.ts:52-414`, `resolveProxySource` / `detectSystemProxy`): macOS `scutil --proxy` (HTTPEnable/HTTPProxy or SOCKSEnable/SOCKSProxy), Windows registry `HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings` (`ProxyEnable` + `ProxyServer`), Linux GNOME `gsettings` (`org.gnome.system.proxy` `mode == 'manual'` plus `org.gnome.system.proxy.http` host/port). This is last-resort only (commit `86368ac`); best-effort and never throws — failure falls through to direct. Per-key proxy overrides (`withKeyProxy` `AsyncLocalStorage`, `#590`) ride request-scoped and win over the global proxy for that request but still respect `NO_PROXY` / local bypass / disabled / per-platform bypass.
-In Docker, `127.0.0.1` is the container, not your machine — see [03-outbound-proxies.md](03-outbound-proxies.md).
+In Docker, `127.0.0.1` is the container, not your machine — see [03-outbound-proxies.md](03-outbound-proxies.md). Fetch-Relay loopback guard: `http` is only allowed when the relay hostname is loopback (`isLoopbackRelayHostname` — `localhost`, `127.0.0.1`, `::1`/`[::1]`, `127.*`); otherwise `fetchRelayUrlError()` requires `https`.
## Request body & media limits
@@ -99,9 +103,11 @@ In Docker, `127.0.0.1` is the container, not your machine — see [03-outbound-p
| `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). |
+| `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). When `TRUST_PROXY` is set, the logged IP is the real client from `X-Forwarded-For`. |
| `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. |
+| `QUOTA_OBSERVATIONS_RETENTION_DAYS` | `30` | Age bound for the provider quota observation audit trail (`provider_quota_observations` behind `provider_quota_state`, `.env.example:230-233`, `server/src/services/request-retention.ts:22-24`). Only the newest row per pool is ever read (indexed seek via `20260901_000002` composite index; previously window-functioned entire log). History older than this is pruned daily. `0` disables age pruning. Split from analytics retention in `77e0ecc`. |
+| `QUOTA_OBSERVATIONS_MAX_ROWS` | `200000` | Count bound for the same audit trail (`QUOTA_OBSERVATIONS_MAX_ROWS=200000`, `.env.example:230-233`). Keeps the newest N rows, pruning the excess daily via `ORDER BY created_at DESC, rowid DESC LIMIT … OFFSET maxRows`. `0` disables count pruning. Together the two knobs are `getQuotaObservationRetentionConfig()`; pruned on the daily gate (24h interval, or next 60s tick while backlog remains) in budgeted chunks of `5k` rows / `250ms` (`QUOTA_OBSERVATIONS_PRUNE_CHUNK` / `QUOTA_OBSERVATIONS_PRUNE_BUDGET_MS`, `server/src/services/request-retention.ts:89-90`, refined in `4a8f095` from 20k/870ms). The count bound is far above live pool count, so keeping newest row per pool is guaranteed. |
| `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. |
@@ -116,3 +122,9 @@ In Docker, `127.0.0.1` is the container, not your machine — see [03-outbound-p
| `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. |
+
+## Idempotency
+
+| Variable | Default | Purpose |
+| --- | --- | --- |
+| `IDEMPOTENCY_TTL_MS` | `86400000` (24h) | Replay window for completed `Idempotency-Key` claims (`server/src/services/idempotency.ts:36,40-42`, `.env.example` not yet listed — `24*60*60*1000`). Read per call via `envNum()` so tests can flip it live; non-finite/negative → fallback. Only a SHA-256 hash of the caller's key is stored (`hashIdempotencyKey`, never raw key), bound to a fingerprint `SHA-256(model+messages+temperature+top_p+max_tokens+tools+tool_choice)`. Same key + same fingerprint → replay original `200` + body at zero provider cost with `X-Routed-Via: idempotency`; same key + different fingerprint → `409 idempotency_key_conflict`. Applies to non-streaming `POST /v1/chat/completions` only (`stream:true` always bypassed; `finish_reason: length` truncated turns not stored). A duplicate arriving while the original is still in-flight is **NOT deduped** — only completed responses are claimable, so both attempts execute (commit `95bc46f` corrected the header to say so; deliberately out of scope vs a pending-claim with short TTL that could wedge a key — `server/src/services/idempotency.ts:16-20`). Expired rows swept lazily per `key_hash` on next `storeIdempotencyResult` (`DELETE … WHERE expires_at_ms <= ?`). |
diff --git a/docs/env/02-security-and-keys.md b/docs/en/env/02-security-and-keys.md
similarity index 96%
rename from docs/env/02-security-and-keys.md
rename to docs/en/env/02-security-and-keys.md
index e5ea5b65..1313819b 100644
--- a/docs/env/02-security-and-keys.md
+++ b/docs/en/env/02-security-and-keys.md
@@ -2,7 +2,7 @@
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).
+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)
diff --git a/docs/en/env/03-outbound-proxies.md b/docs/en/env/03-outbound-proxies.md
new file mode 100644
index 00000000..65644998
--- /dev/null
+++ b/docs/en/env/03-outbound-proxies.md
@@ -0,0 +1,159 @@
+# 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), the container-networking notes in [`docs/install.md`](../install/01-install.md), the proxy transports in [`../proxy/01-fetch-relay.md`](../proxy/01-fetch-relay.md) / [`../proxy/OVERVIEW.md`](../proxy/OVERVIEW.md) (`server/src/lib/proxy.ts:52-414`, `server/src/lib/config.ts:95-110` for `TRUST_PROXY`).
+
+- [Proxy chain precedence](#proxy-chain-precedence)
+- [Fetch Relay transport](#fetch-relay-transport)
+- [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. Resolution is centralized in `resolveProxySource()` (`server/src/lib/proxy.ts:124-143`) — when several sources are present, this is who wins:
+
+```
+PROXY_URL → dashboard setting (proxy_url) → ALL_PROXY → HTTPS_PROXY → HTTP_PROXY → detectSystemProxy() → direct
+```
+
+`PROXY_MODE` (`server/src/lib/proxy.ts:52` `PROXY_MODES = ['forward','fetch-relay']`, `.env.example:70-78`) selects *how* the winning URL is used, not its position in the chain: `forward` (default) is the ordinary forward proxy (HTTP/SOCKS via undici `ProxyAgent` / `SocksProxyAgent`); `fetch-relay` (opt-in) interprets the same winning URL as an application-layer relay endpoint that forwards with `Fetch-Relay-Target` / `Fetch-Relay-Authorization` headers (`server/src/lib/proxy.ts:53-54,875-900`). A legacy `PROXY_URL` or ambient standard var without an explicit `PROXY_MODE=fetch-relay` always stays `forward` regardless of a saved dashboard mode (`server/src/lib/proxy.ts:310-312,377-382`). See [`../proxy/01-fetch-relay.md`](../proxy/01-fetch-relay.md) for the relay contract (owned by another writer; link assumes it will exist).
+
+`PROXY_URL` stays highest; the dashboard beats the generic environment variables; the final fallback is system auto-detect (commit `86368ac`, closes #353/#1069) — reads the OS-wide proxy so the app works without duplicating OS config. Never per request; evaluated once at boot and on `PUT /api/settings/proxy`, and again via `restoreProxySettings()`. Best-effort and never throws — failure falls through to direct.
+
+The standard variables are also read in their lower-case spellings (`all_proxy`, `https_proxy`, `http_proxy`) via `readEnv()` (`server/src/lib/proxy.ts:109-112`).
+
+| Variable | Role in the chain |
+| --- | --- |
+| `PROXY_URL` | Explicit FreeLLMAPI proxy setting; highest precedence. Checked via `readEnv('PROXY_URL')` (upper- or lower-case). |
+| Dashboard setting | Keys → Outbound proxy (`getSetting('proxy_url')`); beats the generic environment variables — a proxy deliberately typed into the UI must not be silently overridden by a machine-wide `ALL_PROXY` exported for curl/git. |
+| `ALL_PROXY` | Standard catch-all proxy variable. |
+| `HTTPS_PROXY` / `HTTP_PROXY` | Conventional per-scheme variables, lowest of the explicit env vars. |
+| `detectSystemProxy()` system fallback | Last-resort only (`server/src/lib/proxy.ts:52-414`, `detectSystemProxy` / `parseScutilProxy` / `parseRegProxy` / `parseGsettingsProxy`): macOS `scutil --proxy` (`HTTPEnable`/`HTTPProxy`/`HTTPPort` or `SOCKSEnable`/`SOCKSProxy`/`SOCKSPort`), Windows registry `HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings` (`ProxyEnable` + `ProxyServer`, `http=` entry preferred), Linux GNOME `gsettings` (`org.gnome.system.proxy` `mode == 'manual'` plus `org.gnome.system.proxy.http` host/port). `execFileSync` 2s timeout, never throws, failure → direct. Source labels `system(macOS)` / `system(Windows)` / `system(GNOME)`. |
+
+## Fetch Relay transport (summary)
+
+For the full application-layer Fetch Relay transport (`PROXY_MODE=fetch-relay`, `PROXY_URL` as relay URL, `FETCH_RELAY_TOKEN` bearer), see [`../proxy/01-fetch-relay.md`](../proxy/01-fetch-relay.md). The forward proxy (`PROXY_MODE=forward`, default) is the traditional `http`/`https`/`socks` CONNECT/SOCKS path documented below; the relay is opt-in and uses `Fetch-Relay-Target`/`Fetch-Relay-Authorization` hop headers, encrypted-at-rest token handling (`encodeFetchRelayToken` → `encrypt()` JSON envelope), `FETCH_RELAY_TOKEN` env precedence over DB (`readEnv('FETCH_RELAY_TOKEN') || dbValue`), `isLoopbackRelayHostname` loopback guard, and the `examples/fetch-relay-worker/` Cloudflare Worker reference. `PROXY_MODE` and `FETCH_RELAY_TOKEN` are documented in detail in the proxy domain and in [01-variables.md](01-variables.md#outbound-proxies) — this page keeps the forward-proxy chain, scheme support, per-key overrides, `NO_PROXY`, loopback guard, and Docker gotchas.
+
+## Per-key proxy overrides
+
+`#590` — each API key can route through its own exit IP (geo-ban / risk-control avoidance). The override rides request-scoped `AsyncLocalStorage` (`perKeyProxyStore`, `withKeyProxy(proxyUrl, fn)` `server/src/lib/proxy.ts:15-20`, `dispatchFetch` `821-841`):
+
+- `resolvePerKeyDispatcher()` keeps a bounded LRU map (`PER_KEY_CACHE_MAX = 32`, evicts oldest; failed builds cached briefly `PER_KEY_FAILURE_TTL_MS = 30s`) keyed by the key's proxy URL — unlike the global dispatcher (TTL 30s), a per-key entry cannot go stale because the URL is the key.
+- A per-key override says *which* proxy to use, not *that* the request must be proxied — the same bypasses still apply: global `proxy_enabled == false`, `proxy_bypass` per-platform list, `NO_PROXY`, and local/LAN destinations still go direct. Failure to build a per-key dispatcher falls through to the global proxy or direct.
+- Configured per key in the dashboard/API (`proxy_url` on the key row); same `http`/`https`/`socks*` schemes and redaction apply.
+
+## 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
+```
+
+> **Fetch-Relay note:** when `PROXY_MODE=fetch-relay` (`server/src/lib/proxy.ts:52` `PROXY_MODES`), the winning URL is treated as an application-layer relay endpoint and must be `http`/`https` — SOCKS schemes are rejected at boot by `enforceRelayUrlPolicy()` (`server/src/lib/proxy.ts:339-350`), and plain `http` is only allowed for loopback relays (`isLoopbackRelayHostname` — `localhost`, `127.0.0.1`, `::1`/`[::1]`, `127.*`, `fetchRelayUrlError()` `server/src/lib/proxy.ts:71-81`). Encrypted-at-rest token handling and env precedence (`FETCH_RELAY_TOKEN` → `readEnv('FETCH_RELAY_TOKEN') || dbValue`, `encodeFetchRelayToken`/`decodeFetchRelayToken` `389-417`) are detailed in [01-variables.md](01-variables.md#outbound-proxies) and [`../proxy/01-fetch-relay.md`](../proxy/01-fetch-relay.md).
+
+## NO_PROXY bypasses
+
+`NO_PROXY` lists hosts that must be reached directly, bypassing whichever proxy won above (`parseNoProxy` / `noProxyMatches` `server/src/lib/proxy.ts:223-251`):
+
+```env
+NO_PROXY=localhost,127.0.0.1,.internal.corp
+```
+
+- Comma-separated entries, trimmed, lower-cased, `*.` prefix stripped to `.`.
+- A bare domain also covers its subdomains (`example.com` matches `api.example.com`); a leading `.` explicitly covers the suffix.
+- A `host:port` entry narrows to that port (bare `host` compared).
+- Trailing dot (FQDN form) and IPv6 brackets are ignored for matching.
+- The special value `*` disables the proxy entirely (matches any host).
+
+Parsed once in `applyProxyUrl()` from `readEnv('NO_PROXY')` (`server/src/lib/proxy.ts:313`).
+
+## Loopback and LAN guard
+
+`shouldBypassProxy(url, platform)` (`server/src/lib/proxy.ts:472-486`) returns direct when any holds:
+
+- proxy disabled globally (`applyProxyEnabled(false)` / `_proxyEnabled`);
+- `platform` listed in `proxy_bypass` (`applyProxyBypass`);
+- `NO_PROXY` matches the upstream hostname;
+- upstream hostname is loopback or private/LAN and `FREEAPI_PROXY_LOCAL_DESTINATIONS` is not set (`server/src/lib/proxy.ts:262-263,314`).
+
+By default **local and LAN destinations always bypass the proxy** — a remote proxy has no route back to `localhost`/`127.0.0.0/8`/`::1`/`0.0.0.0` or RFC1918/ULA/CGNAT addresses, and an IP literal must go on the wire as SOCKS ATYP `0x01` no matter what `socks5h` promises, so Tor logs “giving Tor only an IP address” and may refuse. That is the right default for local Ollama / llama.cpp / LM Studio.
+
+Set `FREEAPI_PROXY_LOCAL_DESTINATIONS=true` (checked case-insensitive `1|true|yes`) only when proxying a local address *is* the point — e.g. `ssh -D` dynamic tunnel where `http://127.0.0.1:11434` through SOCKS should resolve at the remote end.
+
+### Fetch-Relay loopback hostnames
+
+A Fetch Relay carries the provider API key *and* the relay token inside the forwarded request, so the hop to the relay must be encrypted. `fetchRelayUrlError()` (`server/src/lib/proxy.ts:71-81`) allows `http` only for loopback relay hostnames:
+
+```ts
+isLoopbackRelayHostname(hostname): localhost, 127.0.0.1, ::1, [::1], 127.* // server/src/lib/proxy.ts:59-66
+```
+
+Otherwise `https` is required; plaintext to a remote host earns `Fetch Relay URL must use https, or http only for a loopback relay.` at boot. The same guard is shared by the settings validator so the dashboard and headless installs agree.
+
+> **Callout — inbound vs outbound proxy.**
+> The outbound chain above (`PROXY_URL`, dashboard, `ALL_PROXY`, … `detectSystemProxy()`, per-key proxy, `NO_PROXY`, loopback guard) steers **FreeLLMAPI → provider** traffic. `TRUST_PROXY` steers the opposite direction — **client → FreeLLMAPI** — by telling Express whether to trust `X-Forwarded-For` / `X-Forwarded-Proto` from a reverse proxy (Caddy/nginx/Traefik). They are independent knobs; setting one does not imply the other. See `server/src/lib/config.ts:95-110` `parseTrustProxy()` vs `server/src/lib/proxy.ts:52-414` outbound chain.
+
+See also [`../proxy/OVERVIEW.md`](../proxy/OVERVIEW.md) for the full transport scope.
+
+## 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))"
+```
+
+## TRUST_PROXY: inbound vs outbound
+
+> **Inbound vs outbound — different directions.**
+> Outbound (`PROXY_URL`, dashboard, `ALL_PROXY`, `HTTPS_PROXY`, `HTTP_PROXY`, `detectSystemProxy()`, per-key proxy, `NO_PROXY`, loopback guard) controls **FreeLLMAPI → provider** egress. `TRUST_PROXY` controls **client → FreeLLMAPI** ingress: whether Express trusts `X-Forwarded-For` / `X-Forwarded-Proto` from a reverse proxy so Analytics and the per-IP rate limiters see the real client. One does not imply the other.
+>
+> | Outbound | `PROXY_URL` / `ALL_PROXY` / `detectSystemProxy()` etc. | `server/src/lib/proxy.ts:52-414` | Provider-bound traffic |
+> | Inbound | `TRUST_PROXY` (`false\|true\|<hops>\|addr/CIDR`, `.env.example:314`) | `server/src/lib/config.ts:95-110` `parseTrustProxy()` → Express `trust proxy` | Client IP for `REQUEST_ANALYTICS_LOG_CLIENT` + `PROXY_RATE_LIMIT_RPM` / `ADMIN_RATE_LIMIT_RPM` |
+
+`TRUST_PROXY` (`server/src/lib/config.ts:95-110`, `.env.example:306-315`) is forwarded to Express `trust proxy` in `server/src/app.ts`:
+
+| `TRUST_PROXY` value | `trustProxy` | Effect |
+| --- | --- | --- |
+| unset / empty / `false` / `no` / `0` | `false` | **Do not trust** forwarded headers — `X-Forwarded-For` ignored, direct callers cannot spoof `clientIp`; analytics + limiters count the socket peer. **Default, safe without a reverse proxy.** |
+| `true` / `yes` | `true` | Trust every hop — only on fully trusted network. |
+| non-negative integer e.g. `1` | `1` (number) | Trust that many hops from socket peer — Express idiom `trust proxy: 1` for one proxy in front. `0` → `false`. |
+| comma-separated addresses/CIDRs e.g. `100.64.0.0/10,192.168.1.10` | `string[]` | Trust only those proxy addresses/CIDRs. |
+
+When trusted, `client-context` (`server/src/lib/client-context.ts`) and limiters read the left-most untrusted `X-Forwarded-For` entry, so Caddy/nginx/Traefik is not counted as client. When untrusted, socket peer is client regardless of `X-Forwarded-For` — safe default for direct installs. Commit `46ea0de` (#1041, closes #1024). Also see [`../proxy/OVERVIEW.md`](../proxy/OVERVIEW.md) and [01-variables.md](01-variables.md#rate-limits).
+
+## Related inbound rate-limit knobs
+
+Despite the shared “proxy” name, these two variables throttle *inbound* traffic to FreeLLMAPI itself, not outbound provider calls. They count the **real client IP** when `TRUST_PROXY` is set, otherwise the socket peer:
+
+| 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/en/env/CHANGELOG.md b/docs/en/env/CHANGELOG.md
new file mode 100644
index 00000000..e56cacb7
--- /dev/null
+++ b/docs/en/env/CHANGELOG.md
@@ -0,0 +1,25 @@
+# Changelog
+
+Revision history for `docs/env/`, listing the commits that shaped the runtime configuration surface documented here. Most recent first.
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `46ea0de` | 2026-09-02 | feat(proxy): honor TRUST_PROXY for reverse-proxied client IPs (#1041) — adds `TRUST_PROXY` (`false\|true\|<hops>\|addr/CIDR`, `.env.example:314`, `server/src/lib/config.ts:95-110` `parseTrustProxy`) forwarded to Express `trust proxy` so Analytics + `PROXY_RATE_LIMIT_RPM`/`ADMIN_RATE_LIMIT_RPM` see real client IP; default `false` (no spoof). |
+| `4a8f095` | 2026-09-01 | Prune the quota observation log in 5k-row chunks (#1124) — quota audit trail refinement: chunk `20k→5k` rows (`QUOTA_OBSERVATIONS_PRUNE_CHUNK`) to keep each 60s tick near `250ms` budget (`QUOTA_OBSERVATIONS_PRUNE_BUDGET_MS`, `server/src/services/request-retention.ts:89-90`), backlog drains one chunk per minute until `done`. |
+| `77e0ecc` | 2026-09-01 | perf: stop the quota panel from ranking the whole observation log on every poll (#1123) — introduces `QUOTA_OBSERVATIONS_RETENTION_DAYS=30` / `QUOTA_OBSERVATIONS_MAX_ROWS=200000` (`.env.example:230-233`, `server/src/services/request-retention.ts:22-24` `DEFAULT_QUOTA_OBSERVATIONS_*`), audit trail behind `provider_quota_state` (only newest row per pool read via indexed seek `20260901_000002`), pruned daily by age+count in budgeted chunks, client `staleTime 5s→30s` (`/api/health` 4.9s→12ms). |
+| `36b877d` | 2026-09-01 | feat(proxy): Idempotency-Key support — stop client retries from double-spending free-tier quota (#1095) — introduces `IDEMPOTENCY_TTL_MS=24h` (`server/src/services/idempotency.ts:36,40-42` `idempotencyTtlMs()` → `24*60*60*1000`, `envNum` guard), hash `sha256(key)` + fingerprint `sha256(model+messages+…)` , `409` on conflict, non-streaming `POST /v1/chat/completions` only, in-flight NOT deduped. |
+| `95bc46f` | 2026-09-01 | docs(idempotency): the in-flight window is not deduplicated, say so (#1110) — corrects `server/src/services/idempotency.ts:16-20` header: duplicate while original still running is `miss` (both execute), no pending-claim state; deliberately out of scope vs wedged key. |
+| `86368ac` | 2026-09-01 | feat(proxy): auto-detect system-wide proxy settings as a last-resort fallback (#838) — adds `detectSystemProxy()` (`server/src/lib/proxy.ts:52-414` `scutil --proxy` / registry `ProxyEnable+ProxyServer` / `gsettings` GNOME `manual`+`http host/port`) at end of `PROXY_URL→dashboard→ALL_PROXY→HTTPS_PROXY→HTTP_PROXY→detectSystemProxy()→direct` chain (`resolveProxySource`), closes #353/#1069, best-effort 2s timeout, never throws. |
+| `56eb257` | 2026-08-26 | Add an opt-in Fetch Relay outbound transport (#975) — adds `PROXY_MODE` (`forward` default, `fetch-relay` opt-in, `.env.example:76`, `server/src/lib/proxy.ts:52` `PROXY_MODES`) and `FETCH_RELAY_TOKEN` (bearer, encrypted at rest, empty=unauthenticated, `FETCH_RELAY_TOKEN` env precedence over DB, `.env.example:78`, `server/src/lib/proxy.ts:389-417`, `isLoopbackRelayHostname` / `fetchRelayUrlError` loopback guard, `Fetch-Relay-Target/Authorization` headers), cross-links to `../proxy/01-fetch-relay.md`. |
+| `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/en/env/OVERVIEW.md
similarity index 80%
rename from docs/env/OVERVIEW.md
rename to docs/en/env/OVERVIEW.md
index 35e800d9..b566cd63 100644
--- a/docs/env/OVERVIEW.md
+++ b/docs/en/env/OVERVIEW.md
@@ -2,9 +2,9 @@
## 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.
+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).
+For getting an install running in the first place, see [Install & deploy](../install/01-install.md).
## File index
@@ -16,6 +16,6 @@ For getting an install running in the first place, see [Install & deploy](../ins
## 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.
+- 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/en/fallback/01-named-chains.md
similarity index 100%
rename from docs/fallback/01-named-chains.md
rename to docs/en/fallback/01-named-chains.md
diff --git a/docs/fallback/CHANGELOG.md b/docs/en/fallback/CHANGELOG.md
similarity index 100%
rename from docs/fallback/CHANGELOG.md
rename to docs/en/fallback/CHANGELOG.md
diff --git a/docs/fallback/OVERVIEW.md b/docs/en/fallback/OVERVIEW.md
similarity index 100%
rename from docs/fallback/OVERVIEW.md
rename to docs/en/fallback/OVERVIEW.md
diff --git a/docs/en/glossary/01-glossary.md b/docs/en/glossary/01-glossary.md
new file mode 100644
index 00000000..2db58ea9
--- /dev/null
+++ b/docs/en/glossary/01-glossary.md
@@ -0,0 +1,18 @@
+# Glossary
+
+| Term | Meaning |
+| --- | --- |
+| **Headroom** | Remaining quota for a model/key before rate limit: `1 − max(RPM/RPD/TPM/TPD used)`. `0`=exhausted, `1`=full. Tunable via `HEADROOM_RAMP_START`/`HEADROOM_FLOOR` (`../architecture/01-routing-and-bandit-scoring.md`). |
+| **RPD / TPD** | Requests / tokens per day — daily quota windows (`ratelimit.ts:modelWindowUsedFraction`, 5s TTL). |
+| **RPM / TPM** | Requests / tokens per minute — short-window quota. |
+| **Pool key** | Shared quota pool identifier (`provider-quota.ts:inferQuotaPoolKey`), e.g. `openrouter::free`, `google::project`, `custom::key123`. Keys in the same pool share one allowance. |
+| **Least-remaining** | Key selection strategy (`c4c0221`) that picks the key with the most remaining quota in the pool (`services/router.ts:getKeySelectionStrategy`), skipping `::account` pools. |
+| **`auto:<name>`** | Named fallback chain exposed as a selectable model in `GET /v1/models` (`cc1e985`) — e.g. `auto:fast` routes only through that chain. |
+| **Model-age gate** | Catalog sync rule: new models are `premium` for 30 days then become `free` on the next signed sync (`services/catalog-sync.ts`). |
+| **Bandit router** | Thompson-sampling router (`services/router.ts` + `scoring.ts`) that balances reliability/speed/intelligence/headroom posteriors with 10% explore. |
+| **In-flight window** | Concurrent request deduplication window — **not** deduplicated for idempotency (`95bc46f`, `services/idempotency.ts:16-20`) — a concurrent retry with the same `Idempotency-Key` may race. |
+| **TRUST_PROXY** | Env var (`.env.example:314`, `lib/config.ts:95-110`) forwarded to Express `trust proxy` so analytics/rate limiting see real client IP via `X-Forwarded-For`/`Proto`. Default `false` (no spoof). |
+| **`FREEAPI_SHOT`** | Desktop capture mode flag in `desktop/src/main.ts` for screenshots. |
+| **`freellmapi-…`** | Pooled fallback chain identifier — the gateway's single logical model that fans out over the fallback ladder. |
+
+See also: [Architecture](../architecture/OVERVIEW.md), [Routing & bandit scoring](../architecture/01-routing-and-bandit-scoring.md), [Quota & cooldown](../architecture/02-quota-and-cooldown-engine.md).
diff --git a/docs/en/glossary/CHANGELOG.md b/docs/en/glossary/CHANGELOG.md
new file mode 100644
index 00000000..2414b5b9
--- /dev/null
+++ b/docs/en/glossary/CHANGELOG.md
@@ -0,0 +1,8 @@
+# Changelog — glossary
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `688a88a` | 2026-09-02 | Create glossary domain — terms: headroom, RPD/TPD, pool key, least-remaining, auto:<name>, model-age gate, bandit, TRUST_PROXY, FREEAPI_SHOT |
+| `eb19dcf` | 2026-09-02 | Fix glossary broken link `../architecture` → `architecture` (glossary lives in docs/ itself) |
+
+Regenerate: `git log --oneline -- docs/glossary/`
diff --git a/docs/en/glossary/OVERVIEW.md b/docs/en/glossary/OVERVIEW.md
new file mode 100644
index 00000000..9cb9f5ff
--- /dev/null
+++ b/docs/en/glossary/OVERVIEW.md
@@ -0,0 +1,17 @@
+# Glossary Domain — Overview & File Index
+
+## Scope
+
+This domain holds the glossary of recurring terms used across the FreeLLMAPI documentation — routing headroom, quota windows, pool keys, bandit concepts, and product-specific identifiers. It is the single place to define terms that otherwise scatter across `architecture/`, `env/`, and `fallback/` deep-dives.
+
+## File Index
+
+| File | Description |
+| --- | --- |
+| [01-glossary.md](01-glossary.md) | Glossary of recurring terms: headroom, RPD/TPD, pool key, `auto:<name>`, model-age gate, bandit, `TRUST_PROXY`, `FREEAPI_SHOT`, and cross-links to the architecture deep-dives. |
+| [CHANGELOG.md](CHANGELOG.md) | Doc revision history for this domain. |
+
+## Navigation
+
+- ← [Documentation root](../README.md)
+- ↑ [Docs index](../OVERVIEW.md)
diff --git a/docs/en/install/01-install.md b/docs/en/install/01-install.md
new file mode 100644
index 00000000..f3fdc2b3
--- /dev/null
+++ b/docs/en/install/01-install.md
@@ -0,0 +1,381 @@
+**English** · [简体中文](../../zh-cn/install/OVERVIEW.md)
+
+# Install & deploy
+
+[← Back to README](../README.md) · [Documentation index](../README.md)
+
+Everything about getting FreeLLMAPI running: the one-liner, Docker Compose, local development, declarative config, production builds, the desktop app, where your data lives, and how to reset a password, read the logs, or uninstall.
+
+- [Quick start (one-liner)](#quick-start-one-liner)
+- [Docker Compose](#docker-compose)
+- [Local development](#local-development)
+- [Declarative startup config](#declarative-startup-config)
+- [Docker image & operations](#docker-image--operations)
+- [Desktop app](#desktop-app)
+- [Credentials and where your data lives](#credentials-and-where-your-data-lives)
+- [FAQ: passwords, logs, uninstall](#faq-passwords-logs-uninstall)
+
+## Quick start (one-liner)
+
+Docker required — sets up `~/freellmapi`, generates an encryption key, pulls the image, and starts the container:
+
+```bash
+curl -fsSL https://freellmapi.co/install.sh | bash
+```
+
+Prefer to read before you pipe to bash? [The script is here](https://freellmapi.co/install.sh). Re-running it is safe: your `.env` (and encryption key) is preserved and the container updates to `:latest`. Override the defaults with `FREELLMAPI_DIR`, `PORT`, or `HOST_BIND` env vars.
+
+On Windows, the easiest path is the desktop **[`.exe` installer from Releases](https://github.com/tashfeenahmed/freellmapi/releases/latest)** ([below](#desktop-app)); the Docker steps work in WSL or any bash shell.
+
+On Android, see the experimental [Termux installation guide](02-android-termux.md). It uses Node's built-in SQLite driver and does not require the Android NDK.
+
+Open http://localhost:3001, add your provider keys on the **Keys** page, reorder the **Fallback Chain** to taste, and grab your unified API key from the **Keys** page header. That unified key is what you point your OpenAI SDK at.
+
+Your install keeps itself updated from the signed catalog feed. The current full catalog is listed at [freellmapi.co/models](https://freellmapi.co/models.html).
+
+## Docker Compose
+
+Runs the API and dashboard together on port 3001 and persists SQLite in a named volume.
+
+**Prerequisites:** Docker, Docker Compose, OpenSSL.
+
+*On macOS / Linux (Bash):*
+```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
+```
+
+*On Windows (PowerShell):*
+```powershell
+git clone https://github.com/tashfeenahmed/freellmapi.git
+cd freellmapi
+
+$Bytes = New-Object Byte[] 32
+[Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($Bytes)
+$ENCRYPTION_KEY = -join ($Bytes | ForEach-Object { "{0:x2}" -f $_ })
+"ENCRYPTION_KEY=$ENCRYPTION_KEY`nPORT=3001" | Out-File -Encoding utf8 .env
+docker compose up -d
+```
+
+> **Reaching it from another machine?** By default the container is published only on `127.0.0.1`, so `http://<server-ip>:3001` won't load from another device (the page just hangs). To expose it on your LAN — e.g. a Raspberry Pi at `http://192.168.1.x:3001` — start it with `HOST_BIND=0.0.0.0`:
+>
+> ```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.
+
+> **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, 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`).
+> - **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 of these 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))"
+> ```
+
+## Local development
+
+**Prerequisites:** Node.js 20+, npm.
+
+*On macOS / Linux (Bash):*
+```bash
+git clone https://github.com/tashfeenahmed/freellmapi.git
+cd freellmapi
+npm install
+ENCRYPTION_KEY="$(node -e 'console.log(require("crypto").randomBytes(32).toString("hex"))')"
+printf "ENCRYPTION_KEY=%s\nPORT=3001\n" "$ENCRYPTION_KEY" > .env
+npm run dev
+```
+
+*On Windows (PowerShell):*
+```powershell
+git clone https://github.com/tashfeenahmed/freellmapi.git
+cd freellmapi
+npm install
+$ENCRYPTION_KEY = node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
+"ENCRYPTION_KEY=$ENCRYPTION_KEY`nPORT=3001" | Out-File -Encoding utf8 .env
+npm run dev
+```
+
+`ENCRYPTION_KEY` is required for startup. When `NODE_ENV` is not `production`
+and it is unset, the server auto-generates a development key and saves it to a
+`.encryption-key` file (0600) next to the SQLite database, not inside it. Older
+installs that kept the key in the database are migrated to this file on first
+boot. Do not rely on that fallback with real provider keys; set `ENCRYPTION_KEY`.
+
+### Rotating the encryption key
+
+Stored secrets are AES-256-GCM, so simply changing `ENCRYPTION_KEY` does not
+re-encrypt anything — it makes every provider key, per-key proxy override,
+client-profile credential and saved Fetch Relay token fail to decrypt at once.
+Re-encrypt them first, with the server stopped:
+
+```bash
+# 1. Generate the new key
+NEW_KEY="$(node -e 'console.log(require("crypto").randomBytes(32).toString("hex"))')"
+
+# 2. Preview (reads only, writes nothing)
+cd server
+ENCRYPTION_KEY=<old key> npm run rotate-encryption-key -- \
+ --new-key "$NEW_KEY" --dry-run
+
+# 3. Rotate for real
+ENCRYPTION_KEY=<old key> npm run rotate-encryption-key -- --new-key "$NEW_KEY"
+```
+
+`--old-key <hex>` overrides the key read from `ENCRYPTION_KEY`, and
+`--db <path>` points at a database somewhere other than `server/data`. Nothing
+is written unless every value decrypts, so a wrong old key aborts with a
+non-zero exit and an untouched database.
+
+Then put the new key in `.env` (`ENCRYPTION_KEY=$NEW_KEY`) and restart. Under
+Docker, run the command inside the container against the mounted database and
+restart the container with the updated `.env`. Take a copy of the database file
+before rotating.
+
+Request analytics are retained for 90 days or 100000 request rows by default,
+whichever limit prunes first. Set `REQUEST_ANALYTICS_RETENTION_DAYS=0` or
+`REQUEST_ANALYTICS_MAX_ROWS=0` in `.env` to disable either retention limit.
+
+Open http://localhost:5173 (the Vite dev UI), add your provider keys on the **Keys** page, reorder the **Fallback Chain** to taste, and grab your unified API key from the **Keys** page header. That unified key is what you point your OpenAI SDK at.
+
+> **Reaching the dev UI from another device on your LAN?** Use `npm run dev:lan` — it passes `--host` through to Vite, which then prints a `Network: http://<your-ip>:5173` URL you can open from a phone or another machine. (Plain `npm run dev -- --host` does *not* work here: the root `dev` script is a `concurrently` wrapper, so the flag never reaches Vite.) API calls go through Vite's dev proxy, so no extra server config is needed.
+
+For a production build without Docker:
+
+```bash
+npm run build
+node server/dist/index.js # server + dashboard both served on :3001
+```
+
+## Declarative startup config
+
+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 in `FREEAPI_CONFIG_JSON`. The config is idempotent: existing keys,
+custom providers, model edits, fallback rows, and routing settings are updated
+instead of duplicated.
+
+```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 }
+ ]
+}
+```
+
+## Docker image & operations
+
+FreeLLMAPI publishes a single production image that contains 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
+```
+
+The image is multi-arch (`linux/amd64` + `linux/arm64`, so it runs on a Raspberry Pi). Published tags: `latest` (default branch), `v*.*.*` (git release tags), and `sha-<commit>`.
+
+The included `docker-compose.yml` is the recommended install path:
+
+```bash
+docker compose up -d
+docker compose logs -f freellmapi
+```
+
+By default the container's port is bound to `127.0.0.1` (localhost only). To reach the dashboard/API from another machine on your network, publish it on all interfaces with `HOST_BIND=0.0.0.0 docker compose up -d` — only on a trusted LAN, since the proxy is single-user.
+
+Plain HTTP over a LAN address works as-is: the security headers that only apply to HTTPS (`upgrade-insecure-requests`, `Cross-Origin-Opener-Policy`, `Origin-Agent-Cluster`) are emitted only when the request actually arrived over TLS — or over loopback, which browsers already treat as a secure context. Behind an HTTPS reverse proxy they come back on automatically, as long as the proxy forwards `X-Forwarded-Proto`. `CSP_UPGRADE_INSECURE_REQUESTS=true|false` overrides the upgrade directive if your setup needs it.
+
+SQLite data is stored in the `freellmapi-data` volume at `/app/server/data`.
+Keep the same `.env` `ENCRYPTION_KEY` and volume when upgrading, because
+provider keys are encrypted at rest. If your host only persists a specific
+directory, set `FREEAPI_DB_PATH=/that/path/freellmapi.db`.
+
+On hosts with ephemeral disks, configure an encrypted backup target:
+
+```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
+FREEAPI_DB_BACKUP_INTERVAL_MS=300000
+```
+
+When the 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. If `FREEAPI_DB_BACKUP_KEY` is omitted, the app uses
+`ENCRYPTION_KEY` for the backup envelope too.
+
+More Docker operations and examples live in [docker/README.md](../../../docker/README.md).
+
+## Desktop app
+
+A native menu-bar app lives in [`desktop/`](../desktop): the entire router +
+dashboard running locally from your tray, with a glass popover showing live
+request stats.
+
+![FreeLLMAPI desktop app](../../../repo-assets/desktop.png)
+
+**[Download from Releases](https://github.com/tashfeenahmed/freellmapi/releases/latest)** — the macOS `.dmg` and the Windows `.exe` installer are built and attached to every release by the [`desktop-release`](../../../.github/workflows/desktop-release.yml) workflow. Or build it from this repo in a few minutes:
+
+> **Note for Windows users building from source:** Building the desktop app requires compiling native SQLite modules for Electron. You must have [Visual Studio Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) installed (specifically the "Desktop development with C++" workload) and Python installed before running `npm install`.
+
+```bash
+npm install
+npm install --prefix desktop # install desktop dependencies
+npm run desktop:dist # macOS → desktop/dist-electron/FreeLLMAPI-…-arm64.dmg
+npm run desktop:dist:win # Windows → "desktop/dist-electron/FreeLLMAPI Setup ….exe"
+```
+
+> Locally built apps are unsigned, so Windows SmartScreen may warn on first run
+> ("More info" → "Run anyway"); the macOS build launches without Gatekeeper prompts.
+> Full instructions in [desktop/README.md](../../../desktop/README.md).
+
+## Credentials and where your data lives
+
+The desktop app has **no username or password to set up**. Unlike the server
+(which gates its dashboard behind an email + password account), the desktop
+build signs the dashboard in automatically with a hidden local account, so
+you're never prompted for credentials and never need one.
+
+The only credential you need is your **unified API key** — the
+`freellmapi-…` token your OpenAI/Anthropic client points at. Get it from:
+
+- the tray popover — click the tray icon, then **Copy Key**, or
+- the dashboard **Keys** page header (tray → **Open Dashboard**).
+
+You do not need to open or edit `freeapi.db` by hand.
+
+Your settings and data live in one folder per OS (copy it to migrate to
+another machine or into a container):
+
+| OS | Location |
+|----|----------|
+| Windows | `%APPDATA%\FreeLLMAPI\` (e.g. `C:\Users\<you>\AppData\Roaming\FreeLLMAPI\`) |
+| macOS | `~/Library/Application Support/FreeLLMAPI/` |
+| Linux | `~/.config/FreeLLMAPI/` |
+
+That folder holds `freeapi.db` (all keys, models, settings, encrypted at rest),
+`config.json` (window/theme/port/LAN preferences) and `logs/freeapi.log` (what
+the app would print to a terminal if it had one). Copy the first two to move an
+install. For the server (non-desktop) deployment, the equivalent state is the
+`.env` file and the SQLite DB at `server/data/freeapi.db` (or wherever
+`FREEAPI_DB_PATH` points).
+
+## FAQ: passwords, logs, uninstall
+
+### I forgot my dashboard password
+
+**Desktop app — there is no password.** The dashboard signs itself in with a
+hidden local account, so there is nothing to remember and nothing to reset. If
+you cannot see the dashboard, open it from the tray icon → **Open Dashboard**.
+
+**Server installs** (Docker, one-liner, `npm run dev`) do have an email +
+password account, and there is no email delivery to send a reset link to. The
+flow is a one-time code printed to the server log:
+
+1. On the login page, click **Forgot password?**, then **Send reset code**.
+2. Read the code from the server log (see below). It looks like this:
+
+ ```
+ Password-reset code: HWNHPU5QGZ
+ Enter this code on the reset form to set a new password.
+ ```
+
+3. Type it into the reset form together with your new password.
+
+The code is valid for **15 minutes**, and requesting a new one invalidates the
+previous code. Requests are rate-limited, so ask for one code and wait for it
+rather than clicking repeatedly.
+
+### Where are the logs?
+
+| Install method | Where the log goes |
+|----------------|--------------------|
+| Docker Compose | `docker compose logs -f freellmapi` |
+| Plain Docker | `docker logs -f <container>` (`docker ps` lists the name) |
+| One-liner install | `cd ~/freellmapi && docker compose logs -f freellmapi` |
+| `npm run dev` / `node server/dist/index.js` | the terminal the server is running in |
+| Desktop app | `<data dir>/logs/freeapi.log` — tray icon → right-click → **Open Logs Folder** |
+
+The desktop app has no terminal attached, so it also tees everything it prints
+to a file: `freeapi.log` in the `logs` folder inside the data directory listed
+[above](#credentials-and-where-your-data-lives) — for example
+`~/Library/Application Support/FreeLLMAPI/logs/freeapi.log` on macOS. It keeps
+the current file plus one rotated `freeapi.log.1`, 1 MB each. Open it in any
+text editor; the reset code above appears there too.
+
+### How do I uninstall?
+
+Removing the app never removes your data directory — deleting that is a
+separate, deliberate step, which is also what makes it safe to reinstall over
+the top.
+
+**Desktop app**
+
+1. Quit from the tray menu (**Quit FreeLLMAPI**). If you turned on *Start at
+ login* in the popover, switch it off first so no stale login item is left.
+2. Remove the application:
+ - **macOS** — drag `FreeLLMAPI.app` from `/Applications` to the Trash.
+ - **Windows** — *Settings → Apps → Installed apps → FreeLLMAPI → Uninstall*.
+ - **Linux** — delete the AppImage, `sudo apt remove freellmapi` for the `.deb`, or `sudo dnf remove freellmapi` for the `.rpm`.
+3. Delete the data directory to remove your keys, settings and logs for good:
+ - **Windows** — `%APPDATA%\FreeLLMAPI\`
+ - **macOS** — `~/Library/Application Support/FreeLLMAPI/`
+ - **Linux** — `~/.config/FreeLLMAPI/`
+
+**Docker**
+
+```bash
+docker compose down -v # -v also drops the freellmapi-data volume
+docker image rm ghcr.io/tashfeenahmed/freellmapi:latest
+rm -rf ~/freellmapi # the one-liner's directory: .env + compose file
+```
+
+Leave off `-v` if you want to keep the database for a later reinstall.
+
+**From source** — delete the checkout. The state that matters is `.env` and
+`server/data/freeapi.db` (or wherever `FREEAPI_DB_PATH` points), so back those
+up first if you plan to come back.
diff --git a/docs/install/android-termux.md b/docs/en/install/02-android-termux.md
similarity index 100%
rename from docs/install/android-termux.md
rename to docs/en/install/02-android-termux.md
diff --git a/docs/install/CHANGELOG.md b/docs/en/install/CHANGELOG.md
similarity index 100%
rename from docs/install/CHANGELOG.md
rename to docs/en/install/CHANGELOG.md
diff --git a/docs/en/install/OVERVIEW.md b/docs/en/install/OVERVIEW.md
new file mode 100644
index 00000000..63a7a338
--- /dev/null
+++ b/docs/en/install/OVERVIEW.md
@@ -0,0 +1,14 @@
+# Install guides overview
+
+## Scope
+
+This domain covers all installation paths for FreeLLMAPI — standard and platform-specific.
+
+Start with [Install & deploy](01-install.md) for the standard paths: the one-liner Docker quick start, Docker Compose, local development, declarative startup config, the Docker image, and the desktop app. The guides below cover unusual platforms or form factors.
+
+## Guides
+
+| File | Description |
+| --- | --- |
+| [01-install.md](01-install.md) | Install & deploy: one-liner quick start, Docker Compose, local development, declarative startup config, the Docker image, desktop app, and data locations. |
+| [02-android-termux.md](02-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/en/logs/01-server-logs-viewer.md
similarity index 100%
rename from docs/logs/01-server-logs-viewer.md
rename to docs/en/logs/01-server-logs-viewer.md
diff --git a/docs/logs/CHANGELOG.md b/docs/en/logs/CHANGELOG.md
similarity index 100%
rename from docs/logs/CHANGELOG.md
rename to docs/en/logs/CHANGELOG.md
diff --git a/docs/logs/OVERVIEW.md b/docs/en/logs/OVERVIEW.md
similarity index 91%
rename from docs/logs/OVERVIEW.md
rename to docs/en/logs/OVERVIEW.md
index 9d9714d5..4b086c6d 100644
--- a/docs/logs/OVERVIEW.md
+++ b/docs/en/logs/OVERVIEW.md
@@ -21,4 +21,4 @@ logger), see the [Observability deep-dive](../architecture/06-observability.md).
## 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
+- [../../zh-cn/logs/](../../zh-cn/logs/) — Simplified Chinese mirror (when translated).
\ No newline at end of file
diff --git a/docs/providers/01-supported-platforms.md b/docs/en/providers/01-supported-platforms.md
similarity index 97%
rename from docs/providers/01-supported-platforms.md
rename to docs/en/providers/01-supported-platforms.md
index 5b134105..a322a1a3 100644
--- a/docs/providers/01-supported-platforms.md
+++ b/docs/en/providers/01-supported-platforms.md
@@ -1,6 +1,6 @@
# 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 **43 members**:
+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 **43 members**:
- **41 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 **42 entries** in the registry map,
diff --git a/docs/providers/02-quotas-and-cooldowns.md b/docs/en/providers/02-quotas-and-cooldowns.md
similarity index 93%
rename from docs/providers/02-quotas-and-cooldowns.md
rename to docs/en/providers/02-quotas-and-cooldowns.md
index 45a1e153..9620446a 100644
--- a/docs/providers/02-quotas-and-cooldowns.md
+++ b/docs/en/providers/02-quotas-and-cooldowns.md
@@ -1,6 +1,6 @@
# 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).
+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)
@@ -57,7 +57,7 @@ Before #798, a provider that stated exactly when to come back got the same heuri
- 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).
+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)
diff --git a/docs/providers/03-adding-a-new-provider.md b/docs/en/providers/03-adding-a-new-provider.md
similarity index 81%
rename from docs/providers/03-adding-a-new-provider.md
rename to docs/en/providers/03-adding-a-new-provider.md
index 58f73270..c0f536bc 100644
--- a/docs/providers/03-adding-a-new-provider.md
+++ b/docs/en/providers/03-adding-a-new-provider.md
@@ -1,10 +1,10 @@
# Adding a new provider
-A contributor walkthrough that mirrors how the existing 41 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.
+A contributor walkthrough that mirrors how the existing 41 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.
+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
@@ -59,7 +59,7 @@ If the platform publishes no limits, set `null` rather than guessing; the unknow
## 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).
+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
diff --git a/docs/providers/CHANGELOG.md b/docs/en/providers/CHANGELOG.md
similarity index 100%
rename from docs/providers/CHANGELOG.md
rename to docs/en/providers/CHANGELOG.md
diff --git a/docs/providers/OVERVIEW.md b/docs/en/providers/OVERVIEW.md
similarity index 66%
rename from docs/providers/OVERVIEW.md
rename to docs/en/providers/OVERVIEW.md
index 0372fe53..6c6543b3 100644
--- a/docs/providers/OVERVIEW.md
+++ b/docs/en/providers/OVERVIEW.md
@@ -4,7 +4,7 @@
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.
+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
@@ -16,6 +16,6 @@ The authoritative sources are [`shared/types.ts`](../../shared/types.ts) (the `P
## Conventions
-- Adapters live in [`server/src/providers/`](../../server/src/providers/); every platform registered there appears on `/v1` routing immediately — no separate enable step.
+- 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/fetch-relay.md b/docs/en/proxy/01-fetch-relay.md
similarity index 97%
rename from docs/fetch-relay.md
rename to docs/en/proxy/01-fetch-relay.md
index c4aab3ff..48b15f2c 100644
--- a/docs/fetch-relay.md
+++ b/docs/en/proxy/01-fetch-relay.md
@@ -54,7 +54,7 @@ credentials or complete target URLs, and stream rather than buffer bodies.
## Cloudflare Worker reference
-[`examples/fetch-relay-worker`](../examples/fetch-relay-worker/README.md)
+[`examples/fetch-relay-worker`](../../../examples/fetch-relay-worker/README.md)
contains a provider-agnostic, single-file Worker. It keeps no target-site list:
each request carries its complete public HTTP(S) target in `Fetch-Relay-Target`.
The implementation authenticates with a Cloudflare secret, blocks obvious SSRF
diff --git a/docs/en/proxy/CHANGELOG.md b/docs/en/proxy/CHANGELOG.md
new file mode 100644
index 00000000..6688ad2e
--- /dev/null
+++ b/docs/en/proxy/CHANGELOG.md
@@ -0,0 +1,12 @@
+# Proxy Domain — Changelog
+
+Revision history for `docs/proxy/`, derived from git commits touching the outbound proxy and Fetch Relay surface. Most recent first.
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `46ea0de` | 2026-09-02 | feat(proxy): honor `TRUST_PROXY` for reverse-proxied client IPs (#1041) — adds `TRUST_PROXY` (`false\|true\|<hops>\|addr/CIDR`, `.env.example:306-315`, `server/src/lib/config.ts:95-112` `parseTrustProxy`) forwarded to Express `trust proxy` so Analytics + `PROXY_RATE_LIMIT_RPM`/`ADMIN_RATE_LIMIT_RPM` see real client IP behind Caddy/nginx/Traefik; default `false` (no spoof). |
+| `86368ac` | 2026-09-01 | feat(proxy): auto-detect system-wide proxy settings as a last-resort fallback (#838) — adds `detectSystemProxy()` (`server/src/lib/proxy.ts:52-414` — `scutil --proxy` on macOS, Windows registry `ProxyEnable`+`ProxyServer`, GNOME `gsettings` `manual` + `http host/port` on Linux) at end of `PROXY_URL → dashboard → ALL_PROXY → HTTPS_PROXY → HTTP_PROXY → detectSystemProxy() → direct` chain (`resolveProxySource`), closes #353/#1069, best-effort 2s timeout, never throws. |
+| `56eb257` | 2026-08-31 | Add an opt-in Fetch Relay outbound transport (#975) — adds `PROXY_MODE` (`forward` default, `fetch-relay` opt-in, `.env.example:74-78`, `server/src/lib/proxy.ts:52` `PROXY_MODES`) and `FETCH_RELAY_TOKEN` (bearer, encrypted at rest, empty=unauthenticated but not recommended, env precedence over dashboard, `.env.example:78`, `server/src/lib/proxy.ts:389-417`, `isLoopbackRelayHostname`/`fetchRelayUrlError` loopback-https guard, `Fetch-Relay-Target`/`Fetch-Relay-Authorization` headers, `fetchRelayFetch` streaming + manual redirect, `examples/fetch-relay-worker/` Cloudflare Worker reference); initial `docs/fetch-relay.md` (now `docs/proxy/01-fetch-relay.md`) with protocol, security contract, and Worker details. |
+| `ac0a9ce` | 2026-08-22 | docs(env): add runtime configuration reference domain — initial outbound proxy documentation in `docs/env/03-outbound-proxies.md` (precedence `PROXY_URL → dashboard → ALL_PROXY → HTTPS_PROXY → HTTP_PROXY`, scheme support `http`/`https`/`socks4`/`socks4a`/`socks5`/`socks5h`, `NO_PROXY` bypasses, Docker `host.docker.internal` gotcha, inbound rate-limit knobs), scaffolded `docs/env/` domain with `OVERVIEW.md` + `CHANGELOG.md`. |
+
+Regenerate with `git log --oneline -- docs/proxy/ docs/fetch-relay.md docs/env/03-outbound-proxies.md` and `git log --oneline --grep=proxy --grep=relay --grep=TRUST_PROXY`.
diff --git a/docs/en/proxy/OVERVIEW.md b/docs/en/proxy/OVERVIEW.md
new file mode 100644
index 00000000..ab73b2b7
--- /dev/null
+++ b/docs/en/proxy/OVERVIEW.md
@@ -0,0 +1,31 @@
+# Proxy Domain — Overview & File Index
+
+## Scope
+
+This domain documents FreeLLMAPI's outbound proxy transports and the related inbound `TRUST_PROXY` handling. Provider-bound traffic can leave the gateway through two transports:
+
+- **Forward proxy** (`forward` mode, default) — a traditional CONNECT/SOCKS proxy via `PROXY_URL` (explicit `PROXY_URL` → dashboard Keys → Outbound proxy setting → `ALL_PROXY` → `HTTPS_PROXY` → `HTTP_PROXY`, with lower-case spellings also read), scheme support `http`/`https`/`socks4`/`socks4a`/`socks5`/`socks5h` (`h`/`a` resolve DNS at the proxy), `NO_PROXY` bypasses, per-key overrides, and the Docker `host.docker.internal` gotcha. When nothing is configured, the chain now falls through to **system auto-detect** (`detectSystemProxy` in `server/src/lib/proxy.ts:52-414` — `scutil --proxy` on macOS, Windows Internet Options registry `ProxyEnable`/`ProxyServer`, GNOME `gsettings` `manual` + `http host/port` on Linux) as a last-resort fallback (best-effort, 2s timeout, never throws).
+- **Fetch Relay** (`fetch-relay` mode, opt-in) — an application-layer relay such as a Cloudflare Worker (`FreeLLMAPI -> Relay -> provider`), selected with `PROXY_MODE=fetch-relay` + `PROXY_URL` (relay URL) + `FETCH_RELAY_TOKEN` bearer (`Fetch-Relay-Target`/`Fetch-Relay-Authorization` hop headers, encrypted at rest, `FETCH_RELAY_TOKEN` env precedence, loopback guard, streaming without buffering or auto-redirect) — see [01-fetch-relay.md](01-fetch-relay.md).
+
+For inbound traffic, `TRUST_PROXY` (`server/src/lib/config.ts:95` `parseTrustProxy`) controls Express `trust proxy` (`false` default — do not trust `X-Forwarded-For`/`X-Forwarded-Proto`; `true` — trust all; `<hops>` number — trust that many hops from the socket peer; comma-separated `addr/CIDR` list — trust only those) so analytics and `PROXY_RATE_LIMIT_RPM`/`ADMIN_RATE_LIMIT_RPM` see the real client IP behind a reverse proxy (Caddy/nginx/Traefik).
+
+Related: the full `.env` surface is in [`../env/01-variables.md`](../env/01-variables.md) and the forward-proxy chain is expanded in [`../env/03-outbound-proxies.md`](../env/03-outbound-proxies.md); provider routing and failover that consumes the proxy lives in [`../architecture/`](../architecture/OVERVIEW.md); the Cloudflare Worker reference is in [`../../../examples/fetch-relay-worker/README.md`](../../../examples/fetch-relay-worker/README.md).
+
+## File index
+
+| File | Description |
+| --- | --- |
+| [01-fetch-relay.md](01-fetch-relay.md) | Fetch Relay transport: `FreeLLMAPI -> Fetch Relay -> provider`, `PROXY_MODE=fetch-relay` (`forward` default), `PROXY_URL` as relay URL, `FETCH_RELAY_TOKEN` (encrypted at rest, env precedence, empty=unauthenticated), `Fetch-Relay-Authorization: Bearer <relay-token>` + `Fetch-Relay-Target: <provider-url>` hop headers, loopback-https guard, streaming/manual-redirect, Cloudflare Worker (`examples/fetch-relay-worker/`) reference. |
+| [CHANGELOG.md](CHANGELOG.md) | Doc revision history for this domain. |
+
+## Conventions
+
+- Sources: [`.env.example`](../../../.env.example) proxy block (lines 70-80: `PROXY_MODE`, `PROXY_URL`, `FETCH_RELAY_TOKEN`), [`server/src/lib/proxy.ts`](../../../server/src/lib/proxy.ts) (`PROXY_MODES`, `detectSystemProxy` `scutil`/`registry`/`gsettings`, `fetchRelayFetch`, `isLoopbackRelayHostname`/`fetchRelayUrlError`), [`server/src/lib/config.ts`](../../../server/src/lib/config.ts) (`parseTrustProxy` at line 95), [`examples/fetch-relay-worker/README.md`](../../../examples/fetch-relay-worker/README.md).
+- `forward` remains the default `PROXY_MODE`; `fetch-relay` overwrites caller-supplied `Fetch-Relay-*` headers, strips them before fetching the target, rejects local/metadata destinations and relay loops, handles redirects manually, avoids cookies, never logs credentials, and streams rather than buffers bodies.
+
+## Navigation
+
+- ← [Documentation root](../README.md)
+- ↔ [Environment domain](../env/OVERVIEW.md)
+- Outbound proxy detail: [`../env/03-outbound-proxies.md`](../env/03-outbound-proxies.md)
+- Worker reference: [`../../../examples/fetch-relay-worker/README.md`](../../../examples/fetch-relay-worker/README.md)
diff --git a/docs/testing/01-running-tests.md b/docs/en/testing/01-running-tests.md
similarity index 78%
rename from docs/testing/01-running-tests.md
rename to docs/en/testing/01-running-tests.md
index 85e484ed..f70c9c64 100644
--- a/docs/testing/01-running-tests.md
+++ b/docs/en/testing/01-running-tests.md
@@ -2,7 +2,7 @@
## Root chain
-`npm test` at the repo root runs, in order ([package.json](../../package.json)):
+`npm test` at the repo root runs, in order ([package.json](../../../package.json)):
| Step | Command | What it covers |
| --- | --- | --- |
@@ -24,7 +24,7 @@ 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/`.
+`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
@@ -46,7 +46,7 @@ npm run check:i18n -w client # scripts/check-i18n.mjs
## 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:
+[`.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`
diff --git a/docs/testing/02-server-suite.md b/docs/en/testing/02-server-suite.md
similarity index 84%
rename from docs/testing/02-server-suite.md
rename to docs/en/testing/02-server-suite.md
index 04ffab94..1c1240a0 100644
--- a/docs/testing/02-server-suite.md
+++ b/docs/en/testing/02-server-suite.md
@@ -2,7 +2,7 @@
## Layout
-All server tests live under [`server/src/__tests__/`](../../server/src/__tests__), mirroring `src/`:
+All server tests live under [`server/src/__tests__/`](../../../server/src/__tests__), mirroring `src/`:
| Directory | Contents |
| --- | --- |
@@ -22,11 +22,11 @@ All server tests live under [`server/src/__tests__/`](../../server/src/__tests__
- **`--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.
+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.
+[`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()`.
diff --git a/docs/testing/03-compatibility-suite.md b/docs/en/testing/03-compatibility-suite.md
similarity index 78%
rename from docs/testing/03-compatibility-suite.md
rename to docs/en/testing/03-compatibility-suite.md
index f1e18538..65e267e9 100644
--- a/docs/testing/03-compatibility-suite.md
+++ b/docs/en/testing/03-compatibility-suite.md
@@ -8,7 +8,7 @@ The coding-agent compatibility suite (commit `19168ac`, #629, 2026-07-27) proves
### 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:
+[`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;
@@ -16,7 +16,7 @@ The coding-agent compatibility suite (commit `19168ac`, #629, 2026-07-27) proves
### 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.
+[`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
@@ -24,7 +24,7 @@ The `cli/` workspace (added in the same commit, tested by the root chain) genera
### 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.
+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
diff --git a/docs/testing/CHANGELOG.md b/docs/en/testing/CHANGELOG.md
similarity index 100%
rename from docs/testing/CHANGELOG.md
rename to docs/en/testing/CHANGELOG.md
diff --git a/docs/testing/OVERVIEW.md b/docs/en/testing/OVERVIEW.md
similarity index 80%
rename from docs/testing/OVERVIEW.md
rename to docs/en/testing/OVERVIEW.md
index 738f25c9..c1ad8e70 100644
--- a/docs/testing/OVERVIEW.md
+++ b/docs/en/testing/OVERVIEW.md
@@ -4,7 +4,7 @@
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__).
+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
diff --git a/docs/en/troubleshooting/01-common-issues.md b/docs/en/troubleshooting/01-common-issues.md
new file mode 100644
index 00000000..7551b029
--- /dev/null
+++ b/docs/en/troubleshooting/01-common-issues.md
@@ -0,0 +1,71 @@
+# Common issues
+
+## Docker container cannot reach providers
+
+**Symptom:** `ECONNREFUSED` or timeouts to `127.0.0.1:11434` (Ollama) or `localhost` from inside the container, but the host can reach them.
+
+**Cause:** `127.0.0.1` inside the container is the container itself, not the host. See `deployment/01-docker.md` container-cannot-reach-providers gotcha.
+
+**Fix:** Use `host.docker.internal` (Docker Desktop) or `172.17.0.1` / host's LAN IP (Linux), and ensure the proxy (Clash/v2rayN/sing-box) listens on `0.0.0.0` not `127.0.0.1`. Compose `host-gateway` mapping: `extra_hosts: ["host.docker.internal:host-gateway"]`.
+
+**Diagnose:** `docker exec freellmapi curl -v http://host.docker.internal:11434/api/tags`.
+
+## Empty chain `400`
+
+**Symptom:** `POST /v1/chat/completions` returns `400 active chain is empty` (or fallback ladder empty).
+
+**Cause:** The active fallback chain exists but has no models enabled since `e852ff1`/`b3bf20f` — empty chains are now authoritative, not silently falling back to the catalog.
+
+**Fix:** Open `Fallback` page → enable models in the active chain, or set `profiles.auto_include_new_models=1`, or switch active profile. See `fallback/01-named-chains.md`.
+
+## Fetch-relay loopback guard
+
+**Symptom:** `fetchRelayUrlError` or `isLoopbackRelayHostname` 400 when using `PROXY_MODE=fetch-relay`.
+
+**Cause:** Loopback `PROXY_URL` (`127.0.0.1`, `::1`) is blocked by `enforceRelayUrlPolicy` unless explicitly allowed; SOCKS is rejected for fetch-relay (only `http`/`https`, `http` only for loopback).
+
+**Fix:** Use a public `https://relay.example.workers.dev` URL. For local testing, check `server/src/lib/proxy.ts:339-350` policy. See `proxy/01-fetch-relay.md`.
+
+## Idempotency `409` conflict
+
+**Symptom:** `409 Idempotency-Key already used with different request` on retry.
+
+**Cause:** The same `Idempotency-Key` was sent with a different fingerprint (`model`/`messages`/`temperature`/`top_p`/`max_tokens`/`tools`/`tool_choice` differ). See `api/02-idempotency.md`.
+
+**Fix:** Use a fresh UUID per distinct request, or replay the identical body. In-flight window is NOT deduped (`95bc46f`) — a concurrent retry with the same key may still race.
+
+## Quota panels show stale or ranking delay
+
+**Symptom:** Quota panel slow to update or shows many rows.
+
+**Fix:** `QUOTA_OBSERVATIONS_RETENTION_DAYS=30` / `QUOTA_OBSERVATIONS_MAX_ROWS=200000` prune daily in `5k`/`250ms` chunks (`4a8f095`); ensure the DB is on a fast volume. Check `server/src/services/request-retention.ts:68-137` and `provider-quota.ts:532-586` correlated `LIMIT 1` seek.
+
+## Password-reset code not visible (desktop)
+
+**Symptom:** `POST /api/auth/forgot-password` prints a one-time code but the desktop app shows nothing.
+
+**Cause:** Finder/Explorer-launched Electron has no attached `stdout`.
+
+**Fix:** Open tray → `Open Logs Folder` → `freeapi.log` (`desktop/src/logger.ts` tee, `installFileLogger` before server boot). Or use `docker logs`.
+
+## Update-check shows no update / unsigned build won't auto-update
+
+**Symptom:** Dashboard checker shows `latest > running` but `Squirrel.Mac` refuses, or DMG auto-update fails.
+
+**Cause:** `Squirrel.Mac` verifies code signature. An unsigned local `npm run dist` without certs produces an app but no valid update feed (`desktop/02-logging-and-updates.md`). DMG needs re-stamp via `refresh-mac-update-metadata.mjs` after `Apple stapler`.
+
+**Fix:** Download the signed release from GitHub Releases, or sign with `CSC_*` / `APPLE_ID`.
+
+## Reverse proxy `TRUST_PROXY` not seeing real client IP
+
+**Symptom:** Analytics / rate limiting shows `127.0.0.1` instead of real client.
+
+**Cause:** `TRUST_PROXY` defaults `false` (no spoof).
+
+**Fix:** `TRUST_PROXY=1` for single reverse proxy (Caddy/nginx/Traefik on same host), or CIDR list (`TRUST_PROXY=100.64.0.0/10,192.168.1.10`). See `env/01-variables.md` `TRUST_PROXY` + `server/src/lib/config.ts:95-110` `parseTrustProxy()`.
+
+## Related
+
+- [Desktop](../desktop/OVERVIEW.md) — `freeapi.log` rotation.
+- [Proxy transports](../proxy/OVERVIEW.md) — fetch-relay protocol.
+- [Env vars](../env/01-variables.md) — all knobs.
diff --git a/docs/en/troubleshooting/CHANGELOG.md b/docs/en/troubleshooting/CHANGELOG.md
new file mode 100644
index 00000000..0d9e8786
--- /dev/null
+++ b/docs/en/troubleshooting/CHANGELOG.md
@@ -0,0 +1,12 @@
+# Changelog — troubleshooting
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `8bd3acd` | 2026-09-02 | Idempotency `409` — fingerprint/ TTL documented |
+| `e852ff1` | 2026-08-23 | Empty chain authoritative `400` — `activeChainOrThrow` |
+| `86368ac` | 2026-09-01 | System proxy auto-detect `scutil`/`registry`/`gsettings` |
+| `56eb257` | 2026-08-31 | Fetch Relay `PROXY_MODE`/`FETCH_RELAY_TOKEN` loopback guard |
+| `46ea0de` | 2026-09-02 | `TRUST_PROXY` forwarded headers |
+| `90aaa5b` | 2026-08-24 | Desktop `freeapi.log` password-reset visibility |
+
+Regenerate: `git log --oneline -- docs/troubleshooting/`
diff --git a/docs/en/troubleshooting/OVERVIEW.md b/docs/en/troubleshooting/OVERVIEW.md
new file mode 100644
index 00000000..84cd5134
--- /dev/null
+++ b/docs/en/troubleshooting/OVERVIEW.md
@@ -0,0 +1,17 @@
+# Troubleshooting Domain — Overview & File Index
+
+## Scope
+
+This domain consolidates debug tips that are otherwise scattered across `deployment/01-docker.md`, `fallback/01-named-chains.md`, `env/03-outbound-proxies.md`, and `api/02-idempotency.md`. If a provider call returns an unexpected status or the gateway behaves differently behind a reverse proxy or on a dev machine, start here.
+
+## File Index
+
+| File | Description |
+| --- | --- |
+| [01-common-issues.md](01-common-issues.md) | Docker container cannot reach providers, empty chain `400`, fetch-relay loopback guard, idempotency `409`, quota panels, update-check, password-reset code not visible. |
+| [CHANGELOG.md](CHANGELOG.md) | Doc revision history for this domain. |
+
+## Navigation
+
+- ← [Documentation root](../README.md)
+- ↑ [Docs index](../OVERVIEW.md)
diff --git a/docs/env/03-outbound-proxies.md b/docs/env/03-outbound-proxies.md
deleted file mode 100644
index 098d2101..00000000
--- a/docs/env/03-outbound-proxies.md
+++ /dev/null
@@ -1,88 +0,0 @@
-# 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
deleted file mode 100644
index 7b9f62fd..00000000
--- a/docs/env/CHANGELOG.md
+++ /dev/null
@@ -1,18 +0,0 @@
-# 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/i18n/CHANGELOG.md b/docs/i18n/CHANGELOG.md
deleted file mode 100644
index 86df9d12..00000000
--- a/docs/i18n/CHANGELOG.md
+++ /dev/null
@@ -1,23 +0,0 @@
-# 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
deleted file mode 100644
index efffdaaa..00000000
--- a/docs/i18n/OVERVIEW.md
+++ /dev/null
@@ -1,39 +0,0 @@
-# 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
deleted file mode 100644
index 7e470b76..00000000
--- a/docs/i18n/README.md
+++ /dev/null
@@ -1,75 +0,0 @@
-# Translated documentation
-
-English is the source of truth. Everything in this directory is a translation of
-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 [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.
-
-## Layout
-
-One directory per locale, named with the same code the dashboard uses
-(`zh-CN`, `pt-BR`, `fr`, and so on):
-
-```
-docs/i18n/<locale>/README.md translation of /README.md
-docs/i18n/<locale>/docs/README.md translation of /docs/README.md
-docs/i18n/<locale>/docs/install.md translation of /docs/install.md
-```
-
-The mirror is deliberate. Given any translated file you can find its English
-original by deleting `docs/i18n/<locale>/` from the path, and the reverse works
-too.
-
-## Status
-
-| Page | zh-CN |
-| --- | --- |
-| `README.md` | ✅ |
-| `docs/README.md` | ✅ |
-| `docs/install.md` | ✅ |
-| `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
-and leave it, rather than shipping a stale translation of a 300-line reference
-that someone will trust and act on.
-
-## Adding a language
-
-1. Create `docs/i18n/<locale>/` and translate `README.md` first. It is the page
- almost everyone reads, and on its own it is a complete contribution.
-2. Add a link to the language bar at the top of `/README.md`, and to the bar in
- every other translated README.
-3. Add a column to the status table above.
-
-## Rules that keep this maintainable
-
-- **Translate prose, not markup.** Badges, HTML tables, image tags, code blocks,
- 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/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
- README from under it.
-- **Keep the numbers in sync or leave them out.** Provider counts and token
- totals move. If you are not going to update them, write around them.
-- **Match the dashboard.** If a term appears in the UI, use whatever the locale's
- JSON file already uses. Consistency between the README and the app the reader
- is about to open matters more than any individual word choice.
-
-## When English changes
-
-Nothing enforces this automatically, and nothing should: a stale translation is
-better than a blocked release. If you change the root README substantially,
-open an issue tagged `i18n` so translators know there is work waiting. If you
-maintain a translation, watching that label is the easiest way to keep up.
diff --git a/docs/i18n/zh-CN/OVERVIEW.md b/docs/i18n/zh-CN/OVERVIEW.md
deleted file mode 100644
index 48e0c688..00000000
--- a/docs/i18n/zh-CN/OVERVIEW.md
+++ /dev/null
@@ -1,44 +0,0 @@
-# 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/docs/README.md b/docs/i18n/zh-CN/docs/README.md
deleted file mode 100644
index 742464e0..00000000
--- a/docs/i18n/zh-CN/docs/README.md
+++ /dev/null
@@ -1,32 +0,0 @@
-[English](../../../README.md) · **简体中文**
-
-# FreeLLMAPI 文档
-
-根目录的 [README](../README.md) 是产品总览,详细指南在这里。
-
-> **翻译状态:** 「安装与部署」和「API 参考」已翻译成中文。其余三篇指南目前只有英文版,
-> 链接直接指向英文原文。完整状态见 [这里](../../README.md#status)。想认领其中一篇,欢迎提 PR。
-
-## 指南
-
-- **[安装与部署](install.md)** —— 快速开始、Docker Compose、本地开发、声明式启动配置、Docker 镜像、备份、桌面应用,以及你的数据存放在哪里。
-- **[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)** —— 路由器如何工作、路由与运维细节、哪些还不支持、诚实的局限性说明,以及各提供方的服务条款审查。
-
-## 更多
-
-- [在 Android 上用 Termux 安装](../../../install/android-termux.md) —— 实验性的本地安装方式,使用 Node 内置的 SQLite 驱动。
-- [Docker 部署](../../../../docker/README.md) —— 容器配置与持久化存储。
-- [桌面应用](../../../../desktop/README.md) —— 构建和打包 Electron 应用。
-- [贡献者指南](../../../../CONTRIBUTING.md) —— 开发流程、测试要求和贡献政策。
-- [数据库迁移](../../../../server/src/db/README.md) —— 创建、应用、查看和回滚 schema 迁移。
-- [翻译指南](../../01-translating.md) —— 仪表盘字符串的规则,以及中文术语约定。
-
-## docs 目录里的站点资源
-
-- [`index.html`](../../../index.html) —— 项目落地页。
-- [`install.sh`](../../../install.sh) —— Unix 下的 Docker 引导脚本。
-- [`install.ps1`](../../../install.ps1) —— PowerShell 引导脚本。
-- [`success.html`](../../../success.html) —— 安装成功页。
diff --git a/docs/install.md b/docs/install.md
index 9b0ece25..4764eb35 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -1,381 +1,3 @@
-**English** · [简体中文](i18n/zh-CN/docs/install.md)
+# Moved
-# Install & deploy
-
-[← Back to README](../README.md) · [Documentation index](README.md)
-
-Everything about getting FreeLLMAPI running: the one-liner, Docker Compose, local development, declarative config, production builds, the desktop app, where your data lives, and how to reset a password, read the logs, or uninstall.
-
-- [Quick start (one-liner)](#quick-start-one-liner)
-- [Docker Compose](#docker-compose)
-- [Local development](#local-development)
-- [Declarative startup config](#declarative-startup-config)
-- [Docker image & operations](#docker-image--operations)
-- [Desktop app](#desktop-app)
-- [Credentials and where your data lives](#credentials-and-where-your-data-lives)
-- [FAQ: passwords, logs, uninstall](#faq-passwords-logs-uninstall)
-
-## Quick start (one-liner)
-
-Docker required — sets up `~/freellmapi`, generates an encryption key, pulls the image, and starts the container:
-
-```bash
-curl -fsSL https://freellmapi.co/install.sh | bash
-```
-
-Prefer to read before you pipe to bash? [The script is here](https://freellmapi.co/install.sh). Re-running it is safe: your `.env` (and encryption key) is preserved and the container updates to `:latest`. Override the defaults with `FREELLMAPI_DIR`, `PORT`, or `HOST_BIND` env vars.
-
-On Windows, the easiest path is the desktop **[`.exe` installer from Releases](https://github.com/tashfeenahmed/freellmapi/releases/latest)** ([below](#desktop-app)); the Docker steps work in WSL or any bash shell.
-
-On Android, see the experimental [Termux installation guide](install/android-termux.md). It uses Node's built-in SQLite driver and does not require the Android NDK.
-
-Open http://localhost:3001, add your provider keys on the **Keys** page, reorder the **Fallback Chain** to taste, and grab your unified API key from the **Keys** page header. That unified key is what you point your OpenAI SDK at.
-
-Your install keeps itself updated from the signed catalog feed. The current full catalog is listed at [freellmapi.co/models](https://freellmapi.co/models.html).
-
-## Docker Compose
-
-Runs the API and dashboard together on port 3001 and persists SQLite in a named volume.
-
-**Prerequisites:** Docker, Docker Compose, OpenSSL.
-
-*On macOS / Linux (Bash):*
-```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
-```
-
-*On Windows (PowerShell):*
-```powershell
-git clone https://github.com/tashfeenahmed/freellmapi.git
-cd freellmapi
-
-$Bytes = New-Object Byte[] 32
-[Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($Bytes)
-$ENCRYPTION_KEY = -join ($Bytes | ForEach-Object { "{0:x2}" -f $_ })
-"ENCRYPTION_KEY=$ENCRYPTION_KEY`nPORT=3001" | Out-File -Encoding utf8 .env
-docker compose up -d
-```
-
-> **Reaching it from another machine?** By default the container is published only on `127.0.0.1`, so `http://<server-ip>:3001` won't load from another device (the page just hangs). To expose it on your LAN — e.g. a Raspberry Pi at `http://192.168.1.x:3001` — start it with `HOST_BIND=0.0.0.0`:
->
-> ```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.
-
-> **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, 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`).
-> - **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 of these 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))"
-> ```
-
-## Local development
-
-**Prerequisites:** Node.js 20+, npm.
-
-*On macOS / Linux (Bash):*
-```bash
-git clone https://github.com/tashfeenahmed/freellmapi.git
-cd freellmapi
-npm install
-ENCRYPTION_KEY="$(node -e 'console.log(require("crypto").randomBytes(32).toString("hex"))')"
-printf "ENCRYPTION_KEY=%s\nPORT=3001\n" "$ENCRYPTION_KEY" > .env
-npm run dev
-```
-
-*On Windows (PowerShell):*
-```powershell
-git clone https://github.com/tashfeenahmed/freellmapi.git
-cd freellmapi
-npm install
-$ENCRYPTION_KEY = node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
-"ENCRYPTION_KEY=$ENCRYPTION_KEY`nPORT=3001" | Out-File -Encoding utf8 .env
-npm run dev
-```
-
-`ENCRYPTION_KEY` is required for startup. When `NODE_ENV` is not `production`
-and it is unset, the server auto-generates a development key and saves it to a
-`.encryption-key` file (0600) next to the SQLite database, not inside it. Older
-installs that kept the key in the database are migrated to this file on first
-boot. Do not rely on that fallback with real provider keys; set `ENCRYPTION_KEY`.
-
-### Rotating the encryption key
-
-Stored secrets are AES-256-GCM, so simply changing `ENCRYPTION_KEY` does not
-re-encrypt anything — it makes every provider key, per-key proxy override,
-client-profile credential and saved Fetch Relay token fail to decrypt at once.
-Re-encrypt them first, with the server stopped:
-
-```bash
-# 1. Generate the new key
-NEW_KEY="$(node -e 'console.log(require("crypto").randomBytes(32).toString("hex"))')"
-
-# 2. Preview (reads only, writes nothing)
-cd server
-ENCRYPTION_KEY=<old key> npm run rotate-encryption-key -- \
- --new-key "$NEW_KEY" --dry-run
-
-# 3. Rotate for real
-ENCRYPTION_KEY=<old key> npm run rotate-encryption-key -- --new-key "$NEW_KEY"
-```
-
-`--old-key <hex>` overrides the key read from `ENCRYPTION_KEY`, and
-`--db <path>` points at a database somewhere other than `server/data`. Nothing
-is written unless every value decrypts, so a wrong old key aborts with a
-non-zero exit and an untouched database.
-
-Then put the new key in `.env` (`ENCRYPTION_KEY=$NEW_KEY`) and restart. Under
-Docker, run the command inside the container against the mounted database and
-restart the container with the updated `.env`. Take a copy of the database file
-before rotating.
-
-Request analytics are retained for 90 days or 100000 request rows by default,
-whichever limit prunes first. Set `REQUEST_ANALYTICS_RETENTION_DAYS=0` or
-`REQUEST_ANALYTICS_MAX_ROWS=0` in `.env` to disable either retention limit.
-
-Open http://localhost:5173 (the Vite dev UI), add your provider keys on the **Keys** page, reorder the **Fallback Chain** to taste, and grab your unified API key from the **Keys** page header. That unified key is what you point your OpenAI SDK at.
-
-> **Reaching the dev UI from another device on your LAN?** Use `npm run dev:lan` — it passes `--host` through to Vite, which then prints a `Network: http://<your-ip>:5173` URL you can open from a phone or another machine. (Plain `npm run dev -- --host` does *not* work here: the root `dev` script is a `concurrently` wrapper, so the flag never reaches Vite.) API calls go through Vite's dev proxy, so no extra server config is needed.
-
-For a production build without Docker:
-
-```bash
-npm run build
-node server/dist/index.js # server + dashboard both served on :3001
-```
-
-## Declarative startup config
-
-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 in `FREEAPI_CONFIG_JSON`. The config is idempotent: existing keys,
-custom providers, model edits, fallback rows, and routing settings are updated
-instead of duplicated.
-
-```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 }
- ]
-}
-```
-
-## Docker image & operations
-
-FreeLLMAPI publishes a single production image that contains 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
-```
-
-The image is multi-arch (`linux/amd64` + `linux/arm64`, so it runs on a Raspberry Pi). Published tags: `latest` (default branch), `v*.*.*` (git release tags), and `sha-<commit>`.
-
-The included `docker-compose.yml` is the recommended install path:
-
-```bash
-docker compose up -d
-docker compose logs -f freellmapi
-```
-
-By default the container's port is bound to `127.0.0.1` (localhost only). To reach the dashboard/API from another machine on your network, publish it on all interfaces with `HOST_BIND=0.0.0.0 docker compose up -d` — only on a trusted LAN, since the proxy is single-user.
-
-Plain HTTP over a LAN address works as-is: the security headers that only apply to HTTPS (`upgrade-insecure-requests`, `Cross-Origin-Opener-Policy`, `Origin-Agent-Cluster`) are emitted only when the request actually arrived over TLS — or over loopback, which browsers already treat as a secure context. Behind an HTTPS reverse proxy they come back on automatically, as long as the proxy forwards `X-Forwarded-Proto`. `CSP_UPGRADE_INSECURE_REQUESTS=true|false` overrides the upgrade directive if your setup needs it.
-
-SQLite data is stored in the `freellmapi-data` volume at `/app/server/data`.
-Keep the same `.env` `ENCRYPTION_KEY` and volume when upgrading, because
-provider keys are encrypted at rest. If your host only persists a specific
-directory, set `FREEAPI_DB_PATH=/that/path/freellmapi.db`.
-
-On hosts with ephemeral disks, configure an encrypted backup target:
-
-```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
-FREEAPI_DB_BACKUP_INTERVAL_MS=300000
-```
-
-When the 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. If `FREEAPI_DB_BACKUP_KEY` is omitted, the app uses
-`ENCRYPTION_KEY` for the backup envelope too.
-
-More Docker operations and examples live in [docker/README.md](../docker/README.md).
-
-## Desktop app
-
-A native menu-bar app lives in [`desktop/`](../desktop): the entire router +
-dashboard running locally from your tray, with a glass popover showing live
-request stats.
-
-![FreeLLMAPI desktop app](../repo-assets/desktop.png)
-
-**[Download from Releases](https://github.com/tashfeenahmed/freellmapi/releases/latest)** — the macOS `.dmg` and the Windows `.exe` installer are built and attached to every release by the [`desktop-release`](../.github/workflows/desktop-release.yml) workflow. Or build it from this repo in a few minutes:
-
-> **Note for Windows users building from source:** Building the desktop app requires compiling native SQLite modules for Electron. You must have [Visual Studio Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) installed (specifically the "Desktop development with C++" workload) and Python installed before running `npm install`.
-
-```bash
-npm install
-npm install --prefix desktop # install desktop dependencies
-npm run desktop:dist # macOS → desktop/dist-electron/FreeLLMAPI-…-arm64.dmg
-npm run desktop:dist:win # Windows → "desktop/dist-electron/FreeLLMAPI Setup ….exe"
-```
-
-> Locally built apps are unsigned, so Windows SmartScreen may warn on first run
-> ("More info" → "Run anyway"); the macOS build launches without Gatekeeper prompts.
-> Full instructions in [desktop/README.md](../desktop/README.md).
-
-## Credentials and where your data lives
-
-The desktop app has **no username or password to set up**. Unlike the server
-(which gates its dashboard behind an email + password account), the desktop
-build signs the dashboard in automatically with a hidden local account, so
-you're never prompted for credentials and never need one.
-
-The only credential you need is your **unified API key** — the
-`freellmapi-…` token your OpenAI/Anthropic client points at. Get it from:
-
-- the tray popover — click the tray icon, then **Copy Key**, or
-- the dashboard **Keys** page header (tray → **Open Dashboard**).
-
-You do not need to open or edit `freeapi.db` by hand.
-
-Your settings and data live in one folder per OS (copy it to migrate to
-another machine or into a container):
-
-| OS | Location |
-|----|----------|
-| Windows | `%APPDATA%\FreeLLMAPI\` (e.g. `C:\Users\<you>\AppData\Roaming\FreeLLMAPI\`) |
-| macOS | `~/Library/Application Support/FreeLLMAPI/` |
-| Linux | `~/.config/FreeLLMAPI/` |
-
-That folder holds `freeapi.db` (all keys, models, settings, encrypted at rest),
-`config.json` (window/theme/port/LAN preferences) and `logs/freeapi.log` (what
-the app would print to a terminal if it had one). Copy the first two to move an
-install. For the server (non-desktop) deployment, the equivalent state is the
-`.env` file and the SQLite DB at `server/data/freeapi.db` (or wherever
-`FREEAPI_DB_PATH` points).
-
-## FAQ: passwords, logs, uninstall
-
-### I forgot my dashboard password
-
-**Desktop app — there is no password.** The dashboard signs itself in with a
-hidden local account, so there is nothing to remember and nothing to reset. If
-you cannot see the dashboard, open it from the tray icon → **Open Dashboard**.
-
-**Server installs** (Docker, one-liner, `npm run dev`) do have an email +
-password account, and there is no email delivery to send a reset link to. The
-flow is a one-time code printed to the server log:
-
-1. On the login page, click **Forgot password?**, then **Send reset code**.
-2. Read the code from the server log (see below). It looks like this:
-
- ```
- Password-reset code: HWNHPU5QGZ
- Enter this code on the reset form to set a new password.
- ```
-
-3. Type it into the reset form together with your new password.
-
-The code is valid for **15 minutes**, and requesting a new one invalidates the
-previous code. Requests are rate-limited, so ask for one code and wait for it
-rather than clicking repeatedly.
-
-### Where are the logs?
-
-| Install method | Where the log goes |
-|----------------|--------------------|
-| Docker Compose | `docker compose logs -f freellmapi` |
-| Plain Docker | `docker logs -f <container>` (`docker ps` lists the name) |
-| One-liner install | `cd ~/freellmapi && docker compose logs -f freellmapi` |
-| `npm run dev` / `node server/dist/index.js` | the terminal the server is running in |
-| Desktop app | `<data dir>/logs/freeapi.log` — tray icon → right-click → **Open Logs Folder** |
-
-The desktop app has no terminal attached, so it also tees everything it prints
-to a file: `freeapi.log` in the `logs` folder inside the data directory listed
-[above](#credentials-and-where-your-data-lives) — for example
-`~/Library/Application Support/FreeLLMAPI/logs/freeapi.log` on macOS. It keeps
-the current file plus one rotated `freeapi.log.1`, 1 MB each. Open it in any
-text editor; the reset code above appears there too.
-
-### How do I uninstall?
-
-Removing the app never removes your data directory — deleting that is a
-separate, deliberate step, which is also what makes it safe to reinstall over
-the top.
-
-**Desktop app**
-
-1. Quit from the tray menu (**Quit FreeLLMAPI**). If you turned on *Start at
- login* in the popover, switch it off first so no stale login item is left.
-2. Remove the application:
- - **macOS** — drag `FreeLLMAPI.app` from `/Applications` to the Trash.
- - **Windows** — *Settings → Apps → Installed apps → FreeLLMAPI → Uninstall*.
- - **Linux** — delete the AppImage, `sudo apt remove freellmapi` for the `.deb`, or `sudo dnf remove freellmapi` for the `.rpm`.
-3. Delete the data directory to remove your keys, settings and logs for good:
- - **Windows** — `%APPDATA%\FreeLLMAPI\`
- - **macOS** — `~/Library/Application Support/FreeLLMAPI/`
- - **Linux** — `~/.config/FreeLLMAPI/`
-
-**Docker**
-
-```bash
-docker compose down -v # -v also drops the freellmapi-data volume
-docker image rm ghcr.io/tashfeenahmed/freellmapi:latest
-rm -rf ~/freellmapi # the one-liner's directory: .env + compose file
-```
-
-Leave off `-v` if you want to keep the database for a later reinstall.
-
-**From source** — delete the checkout. The state that matters is `.env` and
-`server/data/freeapi.db` (or wherever `FREEAPI_DB_PATH` points), so back those
-up first if you plan to come back.
+This page now lives at **[docs/en/install/01-install.md](en/install/01-install.md)** (中文: [docs/zh-cn/install/01-install.md](zh-cn/install/01-install.md)).
diff --git a/docs/install/OVERVIEW.md b/docs/install/OVERVIEW.md
deleted file mode 100644
index 1abcaa09..00000000
--- a/docs/install/OVERVIEW.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# 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/i18n/zh-CN/CHANGELOG.md b/docs/zh-cn/CHANGELOG.md
similarity index 100%
rename from docs/i18n/zh-CN/CHANGELOG.md
rename to docs/zh-cn/CHANGELOG.md
diff --git a/docs/zh-cn/OVERVIEW.md b/docs/zh-cn/OVERVIEW.md
new file mode 100644
index 00000000..1bb701c2
--- /dev/null
+++ b/docs/zh-cn/OVERVIEW.md
@@ -0,0 +1,50 @@
+# 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
+[../TRANSLATION.md](../TRANSLATION.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. |
+| [../en/README.md](../en/README.md) | [../en/README.md](../en/README.md) | Documentation index page listing every guide in the docs tree. |
+| [docs/install.md](../en/install/01-install.md) | [../../../docs/install.md](../en/install/01-install.md) | Installation guide covering Docker Compose, local setup, and desktop app installs. |
+| [../en/api/01-rest-api.md](../en/api/01-rest-api.md) | [../en/api/01-rest-api.md](../en/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 |
+| --- | --- | --- |
+| [../en/env/](../en/env/OVERVIEW.md) | [../../../../en/env/](../en/env/) | Runtime configuration surface: the full `.env` variable reference, encryption-key handling, and outbound proxy configuration. |
+| [../en/deployment/](../en/deployment/OVERVIEW.md) | [../../../../en/deployment/](../en/deployment/) | Docker operations: image, Compose quickstart, persistence, healthchecks, upgrades, and backups. |
+| [../en/providers/](../en/providers/OVERVIEW.md) | [../../../../en/providers/](../en/providers/) | Provider layer: supported platforms catalog, quotas/cooldowns/key health, and how to add a new provider. |
+| [../en/testing/](../en/testing/OVERVIEW.md) | [../../../../en/testing/](../en/testing/) | Test matrix across workspaces, server suite conventions, and the coding-agent compatibility suite. |
+| [../en/logs/](../en/logs/OVERVIEW.md) | [../../../../en/logs/](../en/logs/) | Live server log viewer in the dashboard: two-tier store, polling API, level counts, clear endpoint, env vars, redaction integration. |
+| [../en/architecture/](../en/architecture/OVERVIEW.md) | [../../../../en/architecture/](../en/architecture/) | Deep-dive server architecture: bandit router, quota/cooldown engine, streaming pipeline, degraded mode, catalog sync, observability. |
+| [../en/cli/](../en/cli/OVERVIEW.md) | [../../../../en/cli/](../en/cli/) | Setup CLI: `setup-*` generators, config-file merge layer, zero-persistence launchers and `doctor`. |
+| [../en/desktop/](../en/desktop/OVERVIEW.md) | [../../../../en/desktop/](../en/desktop/) | Desktop app: Electron shape, file logging and update delivery. |
+| [../en/fallback/](../en/fallback/OVERVIEW.md) | [../../../../en/fallback/](../en/fallback/) | Named fallback chains: lifecycle, `auto:<name>`, catalog-sync backfill. |
+| [../en/glossary/](../en/glossary/OVERVIEW.md) | [../../../../en/glossary/](../en/glossary/) | Glossary of recurring terms: headroom, RPD/TPD, pool key, `auto:<name>`, model-age gate. |
+| [../en/proxy/](../en/proxy/OVERVIEW.md) | [../../../../en/proxy/](../en/proxy/) | Outbound proxy transports: forward vs fetch-relay, system auto-detect. |
+| [../en/troubleshooting/](../en/troubleshooting/OVERVIEW.md) | [../../../../en/troubleshooting/](../en/troubleshooting/) | 常见问题:Docker 容器网络、空链 `400`、fetch-relay 环回防护、幂等 `409`、额度面板、更新检查、密码重置、反向代理 `TRUST_PROXY`。 |
+
+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/zh-cn/README.md b/docs/zh-cn/README.md
new file mode 100644
index 00000000..02cf107e
--- /dev/null
+++ b/docs/zh-cn/README.md
@@ -0,0 +1,32 @@
+[English](../en/README.md) · **简体中文**
+
+# FreeLLMAPI 文档
+
+根目录的 [README](../en/README.md) 是产品总览,详细指南在这里。
+
+> **翻译状态:** 「安装与部署」和「API 参考」已翻译成中文。其余三篇指南目前只有英文版,
+> 链接直接指向英文原文。完整状态见 [这里](../en/README.md#status)。想认领其中一篇,欢迎提 PR。
+
+## 指南
+
+- **[安装与部署](../en/install/01-install.md)** —— 快速开始、Docker Compose、本地开发、声明式启动配置、Docker 镜像、备份、桌面应用,以及你的数据存放在哪里。
+- **[API 参考](api/01-rest-api.md)** —— 聊天补全、`auto:*` 路由策略、流式、工具调用、视觉、Gemini 的 Google 搜索接地、嵌入、响应头,以及 Anthropic Messages 接口。
+- **[客户端与编程智能体](../en/clients/01-agent-clients.md)** —— 兼容 OpenAI 的客户端,Claude Code / Codex CLI / Cline / Continue / Aider / opencode / Cursor 的配方,MCP 服务,编辑器补全,以及上下文交接。
+- **[提示词压缩](../en/compression/01-compression-pipeline.md)** —— 请求侧的各种模式、安全保护、按请求的控制项、自定义工具输出过滤器、统计数据和预览 API。
+- **[架构与内部实现](../en/architecture/00-high-level-index.md)** —— 路由器如何工作、路由与运维细节、哪些还不支持、诚实的局限性说明,以及各提供方的服务条款审查。
+
+## 更多
+
+- [在 Android 上用 Termux 安装](../en/install/02-android-termux.md) —— 实验性的本地安装方式,使用 Node 内置的 SQLite 驱动。
+- [Docker 部署](../../docker/README.md) —— 容器配置与持久化存储。
+- [桌面应用](../../desktop/README.md) —— 构建和打包 Electron 应用。
+- [贡献者指南](../../CONTRIBUTING.md) —— 开发流程、测试要求和贡献政策。
+- [数据库迁移](../../server/src/db/README.md) —— 创建、应用、查看和回滚 schema 迁移。
+- [翻译指南](../TRANSLATION.md) —— 仪表盘字符串的规则,以及中文术语约定。
+
+## docs 目录里的站点资源
+
+- [`index.html`](../index.html) —— 项目落地页。
+- [`install.sh`](../install.sh) —— Unix 下的 Docker 引导脚本。
+- [`install.ps1`](../install.ps1) —— PowerShell 引导脚本。
+- [`success.html`](../success.html) —— 安装成功页。
diff --git a/docs/i18n/zh-CN/docs/api/01-rest-api.md b/docs/zh-cn/api/01-rest-api.md
similarity index 99%
rename from docs/i18n/zh-CN/docs/api/01-rest-api.md
rename to docs/zh-cn/api/01-rest-api.md
index 3d5bddcb..94f2ce0a 100644
--- a/docs/i18n/zh-CN/docs/api/01-rest-api.md
+++ b/docs/zh-cn/api/01-rest-api.md
@@ -1,4 +1,4 @@
-[English](../../../../api/01-rest-api.md) · **简体中文**
+[English](../../en/api/01-rest-api.md) · **简体中文**
# API 参考
diff --git a/docs/zh-cn/api/02-idempotency.md b/docs/zh-cn/api/02-idempotency.md
new file mode 100644
index 00000000..280e098d
--- /dev/null
+++ b/docs/zh-cn/api/02-idempotency.md
@@ -0,0 +1,5 @@
+# 02-idempotency — 幂等
+
+> TODO: 翻译待完成 — 参见 [English](../../en/api/02-idempotency.md)
+
+英文原文在 [`docs/en/api/02-idempotency.md`](../../en/api/02-idempotency.md)。
diff --git a/docs/i18n/zh-CN/docs/api/CHANGELOG.md b/docs/zh-cn/api/CHANGELOG.md
similarity index 82%
rename from docs/i18n/zh-CN/docs/api/CHANGELOG.md
rename to docs/zh-cn/api/CHANGELOG.md
index 60b16f54..f55b6be9 100644
--- a/docs/i18n/zh-CN/docs/api/CHANGELOG.md
+++ b/docs/zh-cn/api/CHANGELOG.md
@@ -1,4 +1,4 @@
-[English](../../../../api/CHANGELOG.md) · **简体中文**
+[English](../../en/api/CHANGELOG.md) · **简体中文**
# API 域 —— 变更日志
diff --git a/docs/i18n/zh-CN/docs/api/OVERVIEW.md b/docs/zh-cn/api/OVERVIEW.md
similarity index 91%
rename from docs/i18n/zh-CN/docs/api/OVERVIEW.md
rename to docs/zh-cn/api/OVERVIEW.md
index 650ae870..2beac55c 100644
--- a/docs/i18n/zh-CN/docs/api/OVERVIEW.md
+++ b/docs/zh-cn/api/OVERVIEW.md
@@ -1,4 +1,4 @@
-[English](../../../../api/OVERVIEW.md) · **简体中文**
+[English](../../en/api/OVERVIEW.md) · **简体中文**
# API 域 —— 概览与文件索引
diff --git a/docs/zh-cn/architecture/00-high-level-index.md b/docs/zh-cn/architecture/00-high-level-index.md
new file mode 100644
index 00000000..0528231e
--- /dev/null
+++ b/docs/zh-cn/architecture/00-high-level-index.md
@@ -0,0 +1,5 @@
+# 00-high-level-index — 高层索引
+
+> TODO: 翻译待完成 — 参见 [English](../../en/architecture/00-high-level-index.md)
+
+英文原文在 [`docs/en/architecture/00-high-level-index.md`](../../en/architecture/00-high-level-index.md)。
diff --git a/docs/i18n/zh-CN/docs/architecture/01-routing-and-bandit-scoring.md b/docs/zh-cn/architecture/01-routing-and-bandit-scoring.md
similarity index 98%
rename from docs/i18n/zh-CN/docs/architecture/01-routing-and-bandit-scoring.md
rename to docs/zh-cn/architecture/01-routing-and-bandit-scoring.md
index b6521dd4..206e1e32 100644
--- a/docs/i18n/zh-CN/docs/architecture/01-routing-and-bandit-scoring.md
+++ b/docs/zh-cn/architecture/01-routing-and-bandit-scoring.md
@@ -1,4 +1,4 @@
-[English](../../../../architecture/01-routing-and-bandit-scoring.md) · **简体中文**
+[English](../../en/architecture/01-routing-and-bandit-scoring.md) · **简体中文**
# 路由与老虎机评分 —— 深度剖析
diff --git a/docs/i18n/zh-CN/docs/architecture/02-quota-and-cooldown-engine.md b/docs/zh-cn/architecture/02-quota-and-cooldown-engine.md
similarity index 99%
rename from docs/i18n/zh-CN/docs/architecture/02-quota-and-cooldown-engine.md
rename to docs/zh-cn/architecture/02-quota-and-cooldown-engine.md
index b610d145..17d3bca4 100644
--- a/docs/i18n/zh-CN/docs/architecture/02-quota-and-cooldown-engine.md
+++ b/docs/zh-cn/architecture/02-quota-and-cooldown-engine.md
@@ -1,4 +1,4 @@
-[English](../../../../architecture/02-quota-and-cooldown-engine.md) · **简体中文**
+[English](../../en/architecture/02-quota-and-cooldown-engine.md) · **简体中文**
# 额度与冷却引擎 —— 深度剖析
diff --git a/docs/i18n/zh-CN/docs/architecture/03-streaming-pipeline.md b/docs/zh-cn/architecture/03-streaming-pipeline.md
similarity index 98%
rename from docs/i18n/zh-CN/docs/architecture/03-streaming-pipeline.md
rename to docs/zh-cn/architecture/03-streaming-pipeline.md
index b987f6d0..5680dd33 100644
--- a/docs/i18n/zh-CN/docs/architecture/03-streaming-pipeline.md
+++ b/docs/zh-cn/architecture/03-streaming-pipeline.md
@@ -1,4 +1,4 @@
-[English](../../../../architecture/03-streaming-pipeline.md) · **简体中文**
+[English](../../en/architecture/03-streaming-pipeline.md) · **简体中文**
# 流式管线 —— 深度剖析
diff --git a/docs/i18n/zh-CN/docs/architecture/04-degraded-mode-and-failover.md b/docs/zh-cn/architecture/04-degraded-mode-and-failover.md
similarity index 99%
rename from docs/i18n/zh-CN/docs/architecture/04-degraded-mode-and-failover.md
rename to docs/zh-cn/architecture/04-degraded-mode-and-failover.md
index df604912..778abda4 100644
--- a/docs/i18n/zh-CN/docs/architecture/04-degraded-mode-and-failover.md
+++ b/docs/zh-cn/architecture/04-degraded-mode-and-failover.md
@@ -1,4 +1,4 @@
-[English](../../../../architecture/04-degraded-mode-and-failover.md) · **简体中文**
+[English](../../en/architecture/04-degraded-mode-and-failover.md) · **简体中文**
# 降级模式与回退 —— 深度剖析
diff --git a/docs/i18n/zh-CN/docs/architecture/05-catalog-sync.md b/docs/zh-cn/architecture/05-catalog-sync.md
similarity index 99%
rename from docs/i18n/zh-CN/docs/architecture/05-catalog-sync.md
rename to docs/zh-cn/architecture/05-catalog-sync.md
index 05d3480f..db957ce2 100644
--- a/docs/i18n/zh-CN/docs/architecture/05-catalog-sync.md
+++ b/docs/zh-cn/architecture/05-catalog-sync.md
@@ -1,4 +1,4 @@
-[English](../../../../architecture/05-catalog-sync.md) · **简体中文**
+[English](../../en/architecture/05-catalog-sync.md) · **简体中文**
# 目录同步 —— 深度剖析
diff --git a/docs/i18n/zh-CN/docs/architecture/06-observability.md b/docs/zh-cn/architecture/06-observability.md
similarity index 99%
rename from docs/i18n/zh-CN/docs/architecture/06-observability.md
rename to docs/zh-cn/architecture/06-observability.md
index 9ac95727..38c7ff00 100644
--- a/docs/i18n/zh-CN/docs/architecture/06-observability.md
+++ b/docs/zh-cn/architecture/06-observability.md
@@ -1,4 +1,4 @@
-[English](../../../../architecture/06-observability.md) · **简体中文**
+[English](../../en/architecture/06-observability.md) · **简体中文**
# 可观测性 —— 深度剖析
diff --git a/docs/i18n/zh-CN/docs/architecture/CHANGELOG.md b/docs/zh-cn/architecture/CHANGELOG.md
similarity index 98%
rename from docs/i18n/zh-CN/docs/architecture/CHANGELOG.md
rename to docs/zh-cn/architecture/CHANGELOG.md
index d33a9f64..ae2709d6 100644
--- a/docs/i18n/zh-CN/docs/architecture/CHANGELOG.md
+++ b/docs/zh-cn/architecture/CHANGELOG.md
@@ -1,4 +1,4 @@
-[English](../../../../architecture/CHANGELOG.md) · **简体中文**
+[English](../../en/architecture/CHANGELOG.md) · **简体中文**
# 架构域 —— 变更日志
diff --git a/docs/i18n/zh-CN/docs/architecture/OVERVIEW.md b/docs/zh-cn/architecture/OVERVIEW.md
similarity index 85%
rename from docs/i18n/zh-CN/docs/architecture/OVERVIEW.md
rename to docs/zh-cn/architecture/OVERVIEW.md
index bea8503f..bd43e0ae 100644
--- a/docs/i18n/zh-CN/docs/architecture/OVERVIEW.md
+++ b/docs/zh-cn/architecture/OVERVIEW.md
@@ -1,8 +1,8 @@
-[English](../../../../architecture/OVERVIEW.md) · **简体中文**
+[English](../../en/architecture/OVERVIEW.md) · **简体中文**
# 架构域 —— 概览与文件索引
-本目录包含 FreeLLMAPI 服务端架构的深度文档。根目录的 [`architecture.md`](../../../../architecture.md) 仍是高层索引;这些文件把各子系统展开并给出实现细节。
+本目录包含 FreeLLMAPI 服务端架构的深度文档。根目录的 [`architecture.md`](../../en/architecture/00-high-level-index.md) 仍是高层索引;这些文件把各子系统展开并给出实现细节。
## 文件索引
@@ -19,4 +19,4 @@
## 导航
- ← [文档根目录](../README.md)
-- ↑ [高层架构索引](../../../../architecture.md)
\ No newline at end of file
+- ↑ [高层架构索引](../../en/architecture/00-high-level-index.md)
\ No newline at end of file
diff --git a/docs/zh-cn/cli/01-generators.md b/docs/zh-cn/cli/01-generators.md
new file mode 100644
index 00000000..5f96449a
--- /dev/null
+++ b/docs/zh-cn/cli/01-generators.md
@@ -0,0 +1,68 @@
+[English](../../en/cli/01-generators.md) · **简体中文**
+
+# 安装生成器
+
+## 用法
+
+```bash
+npx freellmapi setup-claude # 接入 Claude Code
+npx freellmapi setup-codex # 接入 Codex CLI
+npx freellmapi setup-dsh # 接入 DeepSeek Harness
+npx freellmapi setup-mimo # 接入 MiMo Code
+npx freellmapi setup-atomcode # 接入 AtomCode
+npx freellmapi --dry-run setup-claude # 预览而不写入
+npx freellmapi setup-claude --model gpt-4o # 固定模型
+```
+
+每个生成器(`cli/src/tools.ts:52-622`)都会拉取实时目录、对照未过滤目录解析 `--model`(`c942352`)、对已有配置做带时间戳的备份、在不覆盖无关键的前提下合并,并以 `0600` 权限写入。
+
+## 生成器一览
+
+| 命令 | 目标文件 | 协议 | 备注 |
+| --- | --- | --- | --- |
+| `setup-claude` | `~/.claude/settings.json` | Anthropic Messages | `ANTHROPIC_BASE_URL`/`AUTH_TOKEN`/`MODEL`、`CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1`、`launch` 零持久化启动器 |
+| `setup-codex` | `~/.codex/config.toml` | OpenAI Responses | `[model_providers.freellmapi]` `wire_api=responses`、`launch-codex` 启动器 |
+| `setup-cline` | `~/.config/Code/User/settings.json` | OpenAI Chat | Cline VS Code 扩展 |
+| `setup-continue` | `~/.continue/config.json` | OpenAI Chat | Continue 幽灵文本自动补全 |
+| `setup-aider` | `~/.aider.conf.yml` | OpenAI Chat | Aider 结对编程 |
+| `setup-opencode` | `~/.config/opencode/config.json` | OpenAI Chat | OpenCode 智能体 |
+| `setup-goose` | `~/.config/goose/config.yaml` | OpenAI Chat | Goose 智能体 |
+| `setup-qwen` | `~/.qwen/settings.json` | OpenAI/Gemini | Qwen Code,`/v1` 或原生 `/v1beta` |
+| `setup-roo` | `~/.config/roo/config.json` | OpenAI Chat | Roo Code |
+| `setup-kilo` | `~/.config/kilo/config.json` | OpenAI Chat | Kilo Code |
+| `setup-crush` | `~/.config/crush/config.json` | OpenAI Chat | Crush(charmbracelet) |
+| `setup-dsh` | `~/.dsh/config.json` | OpenAI Chat | DeepSeek Harness(#995) |
+| `setup-mimo` | `~/.config/mimocode/config.json` | OpenAI Chat | MiMo Code `~/.config/mimocode/config.json` `default_provider=freellmapi` + `[providers.freellmapi]` `type=openai` `base_url=/v1` `api_key` `model` `context_window`(#1003) |
+| `setup-atomcode` | `~/.atomcode/config.toml` | OpenAI Chat | AtomCode `default_provider=freellmapi` + `[providers.freellmapi]` TOML 保留其他提供方(#1025) |
+| `setup-cursor` | 仅指引 | OpenAI Chat | 手动 `Cursor Settings → Models → Add Model`(无文件) |
+| `setup-generic` | 仅指引 | OpenAI Chat | 任意 OpenAI 兼容客户端 |
+
+## 零持久化启动器
+
+```bash
+npx freellmapi launch # 仅在 env 中注入 FREELLMAPI_API_KEY + model 并启动 `claude`
+npx freellmapi launch-codex # 注入到 `codex --profile NAME`
+```
+
+这些命令不会写入配置文件;它们仅在子进程的环境变量中注入 `FREELLMAPI_API_KEY`/`FREELLMAPI_MODEL`。适用于临时或共享机器。
+
+## `freellmapi doctor`
+
+```bash
+npx freellmapi doctor
+```
+
+验证客户端请求是否到达本网关(检查已路由的 `Authorization` 头、目录、实时探针)。
+
+## 通用参数
+
+| 参数 | 作用 |
+| --- | --- |
+| `--dry-run` | 预览变更而不写入;显示 diff |
+| `--model <id>` | 固定到指定模型(对照未过滤目录解析) |
+| `--profile <name>` | 命名配置档(Codex `codex --profile NAME`、Claude `CLAUDE_CONFIG_DIR`) |
+
+## 相关
+
+- [配置文件](02-config-files.md) —— 合并策略、`tools.json`、新增生成器。
+- [客户端与编程智能体](../clients/01-agent-clients.md) —— 按智能体接入配方、无头 URL 令牌、MCP。
diff --git a/docs/zh-cn/cli/02-config-files.md b/docs/zh-cn/cli/02-config-files.md
new file mode 100644
index 00000000..0e52f6d4
--- /dev/null
+++ b/docs/zh-cn/cli/02-config-files.md
@@ -0,0 +1,40 @@
+[English](../../en/cli/02-config-files.md) · **简体中文**
+
+# 配置文件
+
+## 注册表 —— `cli/tools.json`
+
+`cli/tools.json` 是生成器清单的唯一事实来源。每个条目包含 `id`、`name`、`category`(`code`|`agent`)、`configType`(`file`|`guide`)、`protocol`(`Anthropic Messages`|`OpenAI Chat`|`OpenAI Responses`)、`baseUrlSupport`、`command`(`setup-*`)和 `docsUrl`。`client/src/data/agent-tools.json` 是仪表盘侧的副本(保持同步)。
+
+## `cli/src/config-files.ts` —— 合并层
+
+`cli/src/tools.ts` 中的每个 `Xxx()` 生成器都会返回一个 `Generation { files: { path, format, sensitive, value }[], notes }`。`config-files.ts` 按以下方式应用每个文件:
+
+- **JSON**(`settings.json`、`config.json`)—— 深度合并,保留无关键;写入时设 `0600`(`0o600`)。
+- **TOML**(Codex、AtomCode 的 `config.toml`)—— 结构化合并,保留其他 `[providers.*]` 表;Codex 的单文件 `~/.codex/config.toml` 使用 `[profiles.NAME]` 表,而不是按配置档分文件。
+- **YAML**(Goose 的 `config.yaml`)—— 类似合并。
+
+### 备份
+
+首次写入前,`config-files.ts` 会把已有文件复制为 `<path>.bak.<ISO 时间戳>`(例如 `settings.json.bak.2026-09-02T10-30-00-000Z`)。若文件原本不存在则不做备份。备份同样设为 `0600`。
+
+### Dry run
+
+`--dry-run` 在内存中执行合并、打印 diff 后退出,不触碰磁盘。
+
+### `tools.test.ts` 快照
+
+`cli/src/__snapshots__/tools.test.ts.snap` 固定了每个生成器的生成文件内容;改动生成器后请执行 `npm run test -- -u` 更新快照。
+
+## 新增生成器
+
+1. 在 `cli/tools.json` 中新增条目(`id`、`name`、`category`、`configType`、`protocol`、`baseUrlSupport`、`command`、`docsUrl`)。
+2. 在 `cli/src/tools.ts` 中新增 `function myTool(ctx: GenerateContext): Generation` —— 返回正确的 `path`/`format`/`value` 的 `files` 以及供 CLI 输出的 `notes`。使用辅助函数 `rootUrl()`/`v1Url()`/`primaryModel()`/`contextWindow()`。
+3. 在 `cli/src/tools.test.ts` 中新增快照用例。
+4. 在 [01-generators.md](01-generators.md) 表格与 `docs/clients/01-agent-clients.md` 章节中补充文档。
+5. 若仪表盘会列出它,需同步 `client/src/data/agent-tools.json`。
+
+## 相关
+
+- [生成器](01-generators.md) —— 全部 `setup-*` 命令与目标文件。
+- [客户端与编程智能体](../clients/01-agent-clients.md) —— 按智能体配方。
diff --git a/docs/zh-cn/cli/CHANGELOG.md b/docs/zh-cn/cli/CHANGELOG.md
new file mode 100644
index 00000000..db359ecf
--- /dev/null
+++ b/docs/zh-cn/cli/CHANGELOG.md
@@ -0,0 +1,15 @@
+[English](../../en/cli/CHANGELOG.md) · **简体中文**
+
+# 变更日志 —— CLI
+
+`docs/cli/` 的文档修订历史。最新在前。
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `ddaea9c` | 2026-08-24 | Add AtomCode to the agents catalog (#1025) — `atomcode()` `~/.atomcode/config.toml` |
+| `1585e76` | 2026-08-23 | Add MiMo Code to the agents catalog and describe every agent card (#1003) — `mimo()` `~/.config/mimocode/config.json` |
+| `1a0ce48` | 2026-08-23 | Configure DeepSeek Harness in one command — `setup-dsh` (#995) |
+| `c942352` | 2026-08-23 | Resolve --model against the unfiltered catalog before launching (#861) |
+| `19168ac` | 2026-07-27 | Add end-to-end coding-agent compatibility suite (#629) |
+
+Regenerate:`git log --oneline -- cli/`
diff --git a/docs/zh-cn/cli/OVERVIEW.md b/docs/zh-cn/cli/OVERVIEW.md
new file mode 100644
index 00000000..8dc5e1ef
--- /dev/null
+++ b/docs/zh-cn/cli/OVERVIEW.md
@@ -0,0 +1,24 @@
+[English](../../en/cli/OVERVIEW.md) · **简体中文**
+
+# CLI 域 —— 概览与文件索引
+
+## 范围
+
+本域文档记录 FreeLLMAPI 安装 CLI(`cli/`)—— 通过 `npx freellmapi` 一键将编程智能体接入本地网关的生成器集合。每个生成器(`setup-claude`、`setup-codex` 等)都会拉取实时目录、备份已有配置、绝不覆盖无关键,并为 `freellmapi launch` / `launch-codex` 零持久化启动器以及 `freellmapi doctor` 记录 `tools.json` 元数据。
+
+权威来源:[`cli/src/tools.ts`](../../../cli/src/tools.ts)(全部 `Xxx()` 生成器函数)、[`cli/tools.json`](../../../cli/tools.json)(注册表)、[`cli/src/config-files.ts`](../../../cli/src/config-files.ts)(合并 + `0600` + 带时间戳备份)、[`cli/README.md`](../../../cli/README.md)、[`client/src/data/agent-tools.json`](../../../client/src/data/agent-tools.json)。
+
+关于按智能体的一对一接入配方与 MCP/无头客户端的说明,见[客户端与编程智能体](../clients/OVERVIEW.md)。关于 CLI 注入的环境变量(`FREELLMAPI_API_KEY`、`FREELLMAPI_MODEL`),见 [env/](../env/OVERVIEW.md)。
+
+## 文件索引
+
+| 文件 | 说明 |
+| --- | --- |
+| [01-generators.md](01-generators.md) | 全部 `setup-*` 生成器(claude/codex/cline/continue/aider/opencode/goose/qwen/roo/kilo/crush/cursor/dsh/mimo/atomcode/generic)、目标文件、合并行为、`--model` 解析以及 `launch`/`launch-codex`/`doctor` 命令。 |
+| [02-config-files.md](02-config-files.md) | 配置文件层:`tools.json` 注册表、`config-files.ts` 合并策略(JSON/TOML/YAML)、`0600` 权限、带时间戳备份、`--dry-run` 以及如何新增生成器。 |
+| [CHANGELOG.md](CHANGELOG.md) | 本域文档修订历史。 |
+
+## 导航
+
+- ← [文档根目录](../README.md)
+- ↑ [文档索引](../OVERVIEW.md)
diff --git a/docs/i18n/zh-CN/docs/clients/01-agent-clients.md b/docs/zh-cn/clients/01-agent-clients.md
similarity index 99%
rename from docs/i18n/zh-CN/docs/clients/01-agent-clients.md
rename to docs/zh-cn/clients/01-agent-clients.md
index e43da22d..5c623d05 100644
--- a/docs/i18n/zh-CN/docs/clients/01-agent-clients.md
+++ b/docs/zh-cn/clients/01-agent-clients.md
@@ -1,4 +1,4 @@
-[English](../../../../clients/01-agent-clients.md) · **简体中文**
+[English](../../en/clients/01-agent-clients.md) · **简体中文**
# 客户端与编程智能体
diff --git a/docs/i18n/zh-CN/docs/clients/CHANGELOG.md b/docs/zh-cn/clients/CHANGELOG.md
similarity index 82%
rename from docs/i18n/zh-CN/docs/clients/CHANGELOG.md
rename to docs/zh-cn/clients/CHANGELOG.md
index 7d083145..e682250a 100644
--- a/docs/i18n/zh-CN/docs/clients/CHANGELOG.md
+++ b/docs/zh-cn/clients/CHANGELOG.md
@@ -1,4 +1,4 @@
-[English](../../../../clients/CHANGELOG.md) · **简体中文**
+[English](../../en/clients/CHANGELOG.md) · **简体中文**
# 客户端域 —— 变更日志
diff --git a/docs/i18n/zh-CN/docs/clients/OVERVIEW.md b/docs/zh-cn/clients/OVERVIEW.md
similarity index 90%
rename from docs/i18n/zh-CN/docs/clients/OVERVIEW.md
rename to docs/zh-cn/clients/OVERVIEW.md
index d2226f02..d8df2371 100644
--- a/docs/i18n/zh-CN/docs/clients/OVERVIEW.md
+++ b/docs/zh-cn/clients/OVERVIEW.md
@@ -1,4 +1,4 @@
-[English](../../../../clients/OVERVIEW.md) · **简体中文**
+[English](../../en/clients/OVERVIEW.md) · **简体中文**
# 客户端域 —— 概览与文件索引
diff --git a/docs/i18n/zh-CN/docs/compression/01-compression-pipeline.md b/docs/zh-cn/compression/01-compression-pipeline.md
similarity index 97%
rename from docs/i18n/zh-CN/docs/compression/01-compression-pipeline.md
rename to docs/zh-cn/compression/01-compression-pipeline.md
index bd141e3c..e7ba9c5c 100644
--- a/docs/i18n/zh-CN/docs/compression/01-compression-pipeline.md
+++ b/docs/zh-cn/compression/01-compression-pipeline.md
@@ -1,4 +1,4 @@
-[English](../../../../compression/01-compression-pipeline.md) · **简体中文**
+[English](../../en/compression/01-compression-pipeline.md) · **简体中文**
# 提示词压缩
diff --git a/docs/i18n/zh-CN/docs/compression/CHANGELOG.md b/docs/zh-cn/compression/CHANGELOG.md
similarity index 82%
rename from docs/i18n/zh-CN/docs/compression/CHANGELOG.md
rename to docs/zh-cn/compression/CHANGELOG.md
index 3dfac60b..212d8dc3 100644
--- a/docs/i18n/zh-CN/docs/compression/CHANGELOG.md
+++ b/docs/zh-cn/compression/CHANGELOG.md
@@ -1,4 +1,4 @@
-[English](../../../../compression/CHANGELOG.md) · **简体中文**
+[English](../../en/compression/CHANGELOG.md) · **简体中文**
# 压缩域 —— 变更日志
diff --git a/docs/i18n/zh-CN/docs/compression/OVERVIEW.md b/docs/zh-cn/compression/OVERVIEW.md
similarity index 89%
rename from docs/i18n/zh-CN/docs/compression/OVERVIEW.md
rename to docs/zh-cn/compression/OVERVIEW.md
index cb1fb55a..b1131d48 100644
--- a/docs/i18n/zh-CN/docs/compression/OVERVIEW.md
+++ b/docs/zh-cn/compression/OVERVIEW.md
@@ -1,4 +1,4 @@
-[English](../../../../compression/OVERVIEW.md) · **简体中文**
+[English](../../en/compression/OVERVIEW.md) · **简体中文**
# 压缩域 —— 概览与文件索引
diff --git a/docs/i18n/zh-CN/docs/deployment/01-docker.md b/docs/zh-cn/deployment/01-docker.md
similarity index 97%
rename from docs/i18n/zh-CN/docs/deployment/01-docker.md
rename to docs/zh-cn/deployment/01-docker.md
index c3ab50a4..42f6170b 100644
--- a/docs/i18n/zh-CN/docs/deployment/01-docker.md
+++ b/docs/zh-cn/deployment/01-docker.md
@@ -1,4 +1,4 @@
-[English](../../../../deployment/01-docker.md) · **简体中文**
+[English](../../en/deployment/01-docker.md) · **简体中文**
# Docker
@@ -23,7 +23,7 @@ docker pull ghcr.io/tashfeenahmed/freellmapi:latest # 或固定到某个发布
已发布的标签:`latest`(默认分支)、`v*.*.*`(git release 标签)和 `sha-<commit>`。镜像是多架构的(`linux/amd64` + `linux/arm64`,所以树莓派也能跑)。
-构建形态([Dockerfile](../../../../../Dockerfile)):
+构建形态([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`。
@@ -46,7 +46,7 @@ printf "ENCRYPTION_KEY=%s\nPORT=3001\n" "$ENCRYPTION_KEY" > .env
docker compose up -d
```
-Windows PowerShell 版本和 curl 一行命令引导见 [`docs/install.md`](../install.md#docker-compose)。然后跟踪日志:
+Windows PowerShell 版本和 curl 一行命令引导见 [`docs/install.md`](../../en/install/01-install.md#docker-compose)。然后跟踪日志:
```bash
docker compose logs -f freellmapi
diff --git a/docs/i18n/zh-CN/docs/deployment/02-updates-and-backup.md b/docs/zh-cn/deployment/02-updates-and-backup.md
similarity index 98%
rename from docs/i18n/zh-CN/docs/deployment/02-updates-and-backup.md
rename to docs/zh-cn/deployment/02-updates-and-backup.md
index a1eeb6bd..c4e9e6b3 100644
--- a/docs/i18n/zh-CN/docs/deployment/02-updates-and-backup.md
+++ b/docs/zh-cn/deployment/02-updates-and-backup.md
@@ -1,4 +1,4 @@
-[English](../../../../deployment/02-updates-and-backup.md) · **简体中文**
+[English](../../en/deployment/02-updates-and-backup.md) · **简体中文**
# 更新与备份
diff --git a/docs/i18n/zh-CN/docs/deployment/CHANGELOG.md b/docs/zh-cn/deployment/CHANGELOG.md
similarity index 100%
rename from docs/i18n/zh-CN/docs/deployment/CHANGELOG.md
rename to docs/zh-cn/deployment/CHANGELOG.md
diff --git a/docs/i18n/zh-CN/docs/deployment/OVERVIEW.md b/docs/zh-cn/deployment/OVERVIEW.md
similarity index 78%
rename from docs/i18n/zh-CN/docs/deployment/OVERVIEW.md
rename to docs/zh-cn/deployment/OVERVIEW.md
index 0d7dfdb3..4e1dd223 100644
--- a/docs/i18n/zh-CN/docs/deployment/OVERVIEW.md
+++ b/docs/zh-cn/deployment/OVERVIEW.md
@@ -1,12 +1,12 @@
-[English](../../../../deployment/OVERVIEW.md) · **简体中文**
+[English](../../en/deployment/OVERVIEW.md) · **简体中文**
# 部署总览
## 范围
-在 Docker 中运营 FreeLLMAPI:已发布的镜像、Compose 快速开始、持久化、健康检查、容器网络坑点,以及日常维护工作——升级、备份和声明式配置。内容取材自 [`Dockerfile`](../../../../../Dockerfile)、[`docker-compose.yml`](../../../../../docker-compose.yml)、[`.dockerignore`](../../../../../.dockerignore) 与 [`docs/install.md`](../install.md)。
+在 Docker 中运营 FreeLLMAPI:已发布的镜像、Compose 快速开始、持久化、健康检查、容器网络坑点,以及日常维护工作——升级、备份和声明式配置。内容取材自 [`Dockerfile`](../../../Dockerfile)、[`docker-compose.yml`](../../../docker-compose.yml)、[`.dockerignore`](../../../.dockerignore) 与 [`docs/install.md`](../../en/install/01-install.md)。
-Docker 之外的安装路径(一行命令脚本、本地开发、桌面应用)见「[安装与部署](../install.md)」。
+Docker 之外的安装路径(一行命令脚本、本地开发、桌面应用)见「[安装与部署](../../en/install/01-install.md)」。
## 文件索引
diff --git a/docs/zh-cn/desktop/01-desktop-app.md b/docs/zh-cn/desktop/01-desktop-app.md
new file mode 100644
index 00000000..247387d9
--- /dev/null
+++ b/docs/zh-cn/desktop/01-desktop-app.md
@@ -0,0 +1,61 @@
+[English](../../en/desktop/01-desktop-app.md) · **简体中文**
+
+# 桌面应用
+
+## 包清单
+
+`desktop/package.json` `[email protected]` —— Electron `38.8.6`、`[email protected]`、`[email protected]`、`[email protected]`。入口 `build/main.mjs`(`type: module`)。AppId `com.freellmapi.desktop`,发布 `github:tashfeenahmed/freellmapi`(`desktop/electron-builder.yml`)。`asar` + `client-dist` 位于 `extraResources`;按系统划分的签名目标(mac `dmg` `arm64` 经 `refresh-mac-update-metadata.mjs` 签名/公证/钉装、win `nsis`+`zip` `x64`、linux `AppImage`+`deb`+`tar.xz`+`rpm` `x64` 自 #981 `d8fae97` 起)。
+
+## 构建流水线
+
+```
+bundle:server → build:main / build:preload → stage:client → electron-builder
+```
+
+- `scripts/bundle-server.mjs` esbuild `define: { 'process.env.FREELLMAPI_COMMIT_SHA', 'process.env.FREELLMAPI_INSTALL_METHOD' }` 取自 `GITHUB_SHA`(40 位十六进制);在 `server-host.ts` 中镜像进运行时的 `process.env`,以便 `routes/update.ts` 正确解析。
+- `build/main.mjs` 打包 `src/main.ts`(`--platform=node --format=esm --external:electron --external:./server.mjs`),`build/preload` 对应 `preload.ts`/`preload-popover.ts`。
+- `scripts/stage-client.mjs` 将 `client/dist` 复制到 `build/client-dist` 或已打包应用中的 `Resources/client-dist`;开发环境经 `FREEAPI_REPO` 覆盖。
+
+## 运行时布局
+
+| 路径 | 说明 |
+| --- | --- |
+| `<userData>/freeapi.db` | SQLite 数据库(`freeapi.db` + WAL/`-shm`),与 Docker/Node 同一 schema |
+| `<userData>/config.json` | 端口(默认 `31415`)、`lanAccess`、主题/语言 |
+| `<userData>/logs/freeapi.log` | 1 MB + `freeapi.log.1` 轮转(`desktop/src/logger.ts`) |
+| `<userData>/backups` | 服务端转储(`services/backups.ts` `dataDir()`) |
+| `Resources/client-dist` | 已打包客户端;开发环境:经 `FREEAPI_REPO` 的 `client/dist` |
+
+`~/Library/Application Support/FreeLLMAPI`(macOS)、`%APPDATA%/FreeLLMAPI`(Windows)、`~/.config/FreeLLMAPI`(Linux)。
+
+## 内嵌 server-host
+
+`desktop/src/server-host.ts` 是**唯一**允许引入 `server/src/*` 的模块(`desktop/README.md`)。它经 `bundle-server.mjs` 打包服务端,并重新导出 DB 单例(`getDb`、`getUnifiedApiKey`)以避免主包中出现第二份拷贝。
+
+启动序列与 `server/src/index.ts` 逐步骤镜像(#949);`__tests__/server-host-boot.test.ts` 交叉校验该列表,使 `index.ts` 新增的步骤不会在桌面端静默遗漏(`startBackupScheduler` 曾被遗漏):
+
+`installLogRedaction` → `installProcessSafetyNet` → `initDb` → `ensureSessionToken` → `restoreProxySettings`/`flushProxyCache` → `startHealthChecker`/`checkAllKeys` → `startCatalogSync` → `startCooldownProbe` → `startCustomModelSync` → `startBackupScheduler` → `cleanupExpiredCooldowns` → `startWakeDetect` → `createApp` → `listenWithScan`(端口 `31415`,冲突时扫描 `+50`,持久化到 `config.json`)。
+
+刻意**未**镜像:`restoreDbBackupIfNeeded`/`startDbBackupPump`(`FREEAPI_DB_BACKUP_*` 仅环境变量, 已打包应用不继承 shell 环境)。
+
+`listenWithScan` 默认绑定 `127.0.0.1`;`lanAccess` → `0.0.0.0`(需重启)。
+
+## 主进程连线(`desktop/src/main.ts`)
+
+- 单实例锁(`app.requestSingleInstanceLock`);二次启动聚焦已有窗口。
+- 来自 `FREEAPI_REPO` 开发路径的 `userData` 覆盖。
+- `installFileLogger` 顺序 —— 必须在服务器将要发出的任何 `console.log` 之前运行。
+- 来自系统的主题/语言镜像。
+- `FREEAPI_SHOT` 截图捕获模式。
+
+## 托盘 / 悬浮窗 / 窗口
+
+- `desktop/src/tray.ts` —— 菜单栏图标、`打开日志文件夹` / `打开备份文件夹`(`logger.ts:openLogsFolder`/`openBackupsFolder` 经 `shell.openPath`)、`打开 FreeLLMAPI`、退出。
+- `desktop/src/popover.ts` —— 用于快捷访问的悬浮窗。
+- `desktop/src/window.ts` —— 主 BrowserWindow 外观。
+
+## 相关
+
+- [日志与更新](02-logging-and-updates.md) —— `freeapi.log` 轮转、更新分发、签名。
+- [安装与部署](../install/01-install.md) —— 桌面端 vs Docker vs 本地开发。
+- [日志查看器](../logs/01-server-logs-viewer.md) —— 桌面日志抽头所供给的轮询 API。
diff --git a/docs/zh-cn/desktop/02-logging-and-updates.md b/docs/zh-cn/desktop/02-logging-and-updates.md
new file mode 100644
index 00000000..007431fd
--- /dev/null
+++ b/docs/zh-cn/desktop/02-logging-and-updates.md
@@ -0,0 +1,52 @@
+[English](../../en/desktop/02-logging-and-updates.md) · **简体中文**
+
+# 日志与更新 —— 桌面端
+
+## 为何存在 `freeapi.log`(#824)
+
+内嵌服务器把运行输出打印到 `console` —— 包括 `POST /api/auth/forgot-password` 打印且别处永不显示的一次性密码重置码。服务器运维者可从 `docker logs` 或终端读到它。从 Finder/Explorer 启动的 Electron 应用没有附带的 `stdout`,因此该码曾不可见,重置流程也就永远无法完成。于是 `desktop/src/logger.ts` 把 `console` 分流到 `<userData>/logs/freeapi.log`(90aaa5b)。
+
+## `logger.ts` —— `FileSink` + 轮转
+
+- `LOG_NAME=freeapi.log`、`PREVIOUS_NAME=freeapi.log.1`、`MAX_LOG_BYTES=1 MB`(`desktop/src/logger.ts:18-21`)。两个文件,各 1 MB —— 足够记录一次重置或异常启动,又小到不会占用磁盘。
+- `createFileSink(dir, maxBytes=1M)` —— 追加到 `freeapi.log`,超过 `maxBytes` 时轮转到 `freeapi.log.1`(在**将要**跨过上限的那次写入前轮转,空文件永不轮转)。同步 `fs.writeSync`,因此应用退出前一刻打印的码已落盘。每次文件系统调用均被包装 —— 日志永不使应用崩溃。
+- `installFileLogger(dir=logsDir())` —— 包装 `console.log/info/warn/error`,前缀 `ISO 时间戳 [level]`,同时转发到原始 console **与** `sink.write`。幂等(`installed` 标志)。`process.on('exit', () => sink.close())`。桌面端唯一的仪表盘日志供给就是此抽头(#993 与 `server/src/lib/server-logs.ts` 协调 —— 服务端的内存环 + 数据库持久化 `warn`/`error`)。
+- `openLogsFolder()` / `openBackupsFolder()` —— `fs.mkdirSync(..., { recursive: true })` 后 `shell.openPath`;先创建目录,即使尚未写入任何内容也能正确揭示。托盘 → “打开日志文件夹” / “打开备份文件夹”。
+
+```ts
+// 顺序很重要 —— 在任何服务端 console 输出前安装
+import { installFileLogger } from './logger.js';
+installFileLogger(); // 在 createApp / 服务端启动之前
+```
+
+## 托盘可发现性
+
+托盘菜单同时暴露两个文件夹;`openBackupsFolder` 解析到 `<userData>/backups`(`server/src/services/backups.ts` `dataDir()` 写入转储之处)。仪表盘的备份面板显示相对于该目录的路径。
+
+## 更新分发
+
+### Electron-builder 发布
+
+`desktop/electron-builder.yml` `publish: { provider: github, owner: tashfeenahmed, repo: freellmapi }` —— 产物(`dmg`、`nsis`、`zip`、`AppImage`、`deb`、`tar.xz`、`rpm`)在 `desktop-release.yml` 上上传(`*.rpm` 通配自 d8fae97)。按渠道生成 `latest.yml` / `latest-mac.yml`。
+
+### 构建标识
+
+`scripts/bundle-server.mjs` `define: { 'process.env.FREELLMAPI_COMMIT_SHA': JSON.stringify(GITHUB_SHA), 'process.env.FREELLMAPI_INSTALL_METHOD': '"desktop"' }` —— 构建时戳记的 40 位十六进制 SHA,在 `server-host.ts` 中镜像进运行时的 `process.env`,以便 `server/src/routes/update.ts` 解析运行中提交 vs `GET /api/update` 可用版本。`FREEAPI_VERSION` 取自 `app.getVersion()`(`0.9.2`)。
+
+### 仪表盘内检查器
+
+仪表盘轮询 `GET /api/update`(检查器 #635/#703)—— 当 `latest > running` 时展示横幅及发行说明。桌面端与 Docker/Node 共享同一检查器;桌面端额外经 Squirrel 提供自动更新。
+
+### macOS 签名 / 公证
+
+经 `electron-builder` 签名 + 公证(#373/#1035):`CSC_*`、`APPLE_ID` 密钥位于 `desktop-release.yml`。票据钉装后经 `scripts/refresh-mac-update-metadata.mjs` 对 DMG 重戳(`latest-mac.yml` 的 `sha512` 必须匹配已钉装的 DMG,而非钉装前)。
+
+### 为何未签名构建无法自动更新
+
+`Squirrel.Mac` 在应用更新前校验代码签名。未签名的 `dmg`(无证书的本地 `npm run dist`)能产生有效应用,却没有有效更新源 —— 自动更新器会拉取 `latest-mac.yml` 随后拒绝应用。需手动下载。
+
+## 相关
+
+- [桌面应用](01-desktop-app.md) —— 包清单、构建流水线、运行时布局。
+- [日志查看器](../logs/01-server-logs-viewer.md) —— 桌面抽头所供给的轮询 API。
+- [可观测性](../architecture/06-observability.md) —— 服务端存储内部(环 + 数据库)。
diff --git a/docs/zh-cn/desktop/CHANGELOG.md b/docs/zh-cn/desktop/CHANGELOG.md
new file mode 100644
index 00000000..1f60dc46
--- /dev/null
+++ b/docs/zh-cn/desktop/CHANGELOG.md
@@ -0,0 +1,18 @@
+[English](../../en/desktop/CHANGELOG.md) · **简体中文**
+
+# 变更日志 —— 桌面端
+
+`docs/desktop/` 的文档修订历史。最新在前。
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| `90aaa5b` | 2026-08-24 | Desktop log file plus a passwords, logs and uninstall FAQ (#1002) — `desktop/src/logger.ts` `FileSink` + rotation + tray open folders |
+| `4774cf0` | 2026-08-23 | Bring the desktop boot sequence up to server parity and bump to 0.8.7 (#1017) — `server-host.ts` mirrors `index.ts` steps, cross-checked by `server-host-boot.test.ts` |
+| `73178f3` | 2026-08-23 | Fix: outlive the reverse proxy's idle connection pool (#1116) — keepAlive path touches server-host |
+| `d8fae97` | 2026-08-23 | Add an rpm target to the Linux desktop build (#981) — `electron-builder.yml` `rpm x64` beside `deb` |
+| `3b6f40e` | 2026-08-23 | Bump desktop to v0.9.0 (#1044) — version bump |
+| `9196ed0` | 2026-08-23 | Mac builds are signed and notarized — closes #373 #943 (#1035) |
+| `e70d130` | 2026-08-23 | Notarize the DMG itself, not just the app inside it (#1036) |
+| `c8e05f0` | 2026-08-23 | Bump desktop to v0.9.1 (#1115) |
+
+Regenerate:`git log --oneline -- desktop/`
diff --git a/docs/zh-cn/desktop/OVERVIEW.md b/docs/zh-cn/desktop/OVERVIEW.md
new file mode 100644
index 00000000..d934c480
--- /dev/null
+++ b/docs/zh-cn/desktop/OVERVIEW.md
@@ -0,0 +1,45 @@
+[English](../../en/desktop/OVERVIEW.md) · **简体中文**
+
+# 桌面应用域 —— 概览与文件索引
+
+## 范围
+
+本域文档记录 FreeLLMAPI 桌面应用 —— 一个精简的 Electron 菜单栏工具(`desktop/`),它把整个路由器与仪表盘打包进单一本地进程。该应用从 Finder/Explorer 启动时没有附带的 `stdout`,因此操作输出(包括一次性密码重置码)原本会丢失;它把服务器钉在扫描到的环回端口、为仪表盘铸造隐藏的机器用户(`desktop@localhost`),并暴露托盘、悬浮窗与更新管道——这些在 Docker 或纯 Node 流程中并不存在。
+
+权威来源:[`desktop/package.json`](../../../desktop/package.json)(版本 `0.9.2`、`[email protected]`、`[email protected]`、scripts)、[`desktop/electron-builder.yml`](../../../desktop/electron-builder.yml)(AppId `com.freellmapi.desktop`、发布方 `github:tashfeenahmed/freellmapi`、`asar` + `client-dist` extraResources、按系统划分的签名目标)、[`desktop/src/logger.ts`](../../../desktop/src/logger.ts)(在 `<userData>/logs/freeapi.log` 的文件分流,1 MB 轮转、同步永不崩溃包装)、[`desktop/src/server-host.ts`](../../../desktop/src/server-host.ts)(唯一允许引入 `server/src/*` 的模块,`startServer`/`ensureSessionToken`/`listenWithScan`,启动一致性与 `server/src/index.ts` 经 `__tests__/server-host-boot.test.ts` 交叉校验)、[`desktop/src/main.ts`](../../../desktop/src/main.ts)(单实例锁、`userData` 覆盖、`installFileLogger` 顺序、主题/语言镜像、局域网开关、`FREEAPI_SHOT`)、[`desktop/src/config.ts`](../../../desktop/src/config.ts)、[`desktop/src/tray.ts`](../../../desktop/src/tray.ts)、[`desktop/src/window.ts`](../../../desktop/src/window.ts)、[`desktop/src/popover.ts`](../../../desktop/src/popover.ts)、[`desktop/scripts/bundle-server.mjs`](../../../desktop/scripts/bundle-server.mjs)(为 `FREELLMAPI_COMMIT_SHA` + `FREELLMAPI_INSTALL_METHOD` 的 esbuild `define`)、以及 [`desktop/scripts/refresh-mac-update-metadata.mjs`](../../../desktop/scripts/refresh-mac-update-metadata.mjs)(票据钉装后对 DMG 的重新戳记)。
+
+从用户视角的安装 —— 快速开始、Docker vs 本地开发 vs 桌面端、数据位置与 FAQ —— 见[安装与部署](../install/01-install.md)。镜像/Compose 路径见 [deployment/](../deployment/OVERVIEW.md)。关于桌面嵌入器所供给的仪表盘日志查看器,见 [logs/](../logs/OVERVIEW.md) 及 [architecture/06-observability.md](../architecture/06-observability.md) 中的内部说明。
+
+## 文件索引
+
+| 文件 | 说明 |
+| --- | --- |
+| [01-desktop-app.md](01-desktop-app.md) | Electron 应用形态:包清单、构建流水线(`bundle:server` → `build:main`/`build:preload` → `stage:client` → `electron-builder`)、运行时布局(`<userData>/freeapi.db`、`config.json`、`client-dist` 位于 `extraResources`)、内嵌 `server-host` 启动序列及其一致性守卫、主进程连线(单实例、`userData` 覆盖、主题/语言、托盘/悬浮窗/仪表盘、局域网开关、`FREEAPI_SHOT` 截图)、窗口外观以及按系统划分的打包/签名目标。 |
+| [02-logging-and-updates.md](02-logging-and-updates.md) | 文件日志与更新分发:`freeapi.log` 为何存在(#824 密码重置故事)、`logger.ts` `FileSink` + 轮转 + `installFileLogger`/`openLogsFolder`/`openBackupsFolder`、在脱敏抽头之下的顺序(桌面端唯一的仪表盘日志供给,#993)、托盘可发现性,以及更新面(`electron-builder` `publish` + `latest.yml`、`FREELLMAPI_COMMIT_SHA` `define` 镜像进 `process.env`、`FREEAPI_VERSION` 取自 `app.getVersion()`、仪表盘内检查器 #635/#703、macOS 签名/公证 #373/#1035、票据钉装后 DMG 重戳,以及为何未签名构建无法经 `Squirrel.Mac` 自动更新)。 |
+| [CHANGELOG.md](CHANGELOG.md) | 本域文档修订历史,播种自与桌面相关的提交。 |
+
+## 速览
+
+| 方面 | 取值 |
+| --- | --- |
+| 包 | `freellmapi-desktop` `0.9.2` 位于 [`desktop/package.json`](../../../desktop/package.json) |
+| 入口 | `build/main.mjs`(`type: module`,Electron `38.8.6`) |
+| 数据库 + 配置 | `<userData>/freeapi.db` + `<userData>/config.json`(macOS 上为 `~/Library/Application Support/FreeLLMAPI`,Windows 上为 `%APPDATA%/FreeLLMAPI`) |
+| 日志文件 | `<userData>/logs/freeapi.log`(1 MB,轮转至 `freeapi.log.1`,同步分流 —— [`desktop/src/logger.ts`](../../../desktop/src/logger.ts)) |
+| 备份 | `<userData>/backups`(托盘 → 打开备份文件夹;服务端经 `services/backups.ts` 写入) |
+| 默认端口 | `31415` 于 `127.0.0.1`;冲突时扫描 `+50`,持久化到 `config.json`;`lanAccess` → `0.0.0.0`(需重启) |
+| 客户端包 | `Resources/client-dist`(已打包)或开发环境中来自 monorepo 的 `client/dist`(`FREEAPI_REPO` 覆盖) |
+| 构建标识 | `bundle-server.mjs` `define: { 'process.env.FREELLMAPI_COMMIT_SHA', 'process.env.FREELLMAPI_INSTALL_METHOD' }` 由 `GITHUB_SHA`(40 位十六进制)戳记,并在 `server-host.ts` 中镜像进运行时的 `process.env`,以便 `routes/update.ts` 正确解析 |
+| 打包目标 | mac `dmg` `arm64`(已签名、已公证、已钉装)、win `nsis` + `zip` `x64`、linux `AppImage`+`deb`+`tar.xz`+`rpm` `x64`(`rpm` 自 #981 `d8fae97` 起) |
+
+## 相关
+
+- [桌面端 README](../../../desktop/README.md) —— 前置条件、`npm run desktop:dist`/`desktop:dev`、原生重建说明。
+- [安装与部署](../install/01-install.md) —— 桌面端与 Docker/本地开发并列、数据位置表、卸载/FAQ。
+- [部署](../deployment/OVERVIEW.md) —— Docker 镜像/Compose 运维(另一种安装形态)。
+- [日志查看器](../logs/01-server-logs-viewer.md) 与 [可观测性](../architecture/06-observability.md) —— 桌面日志抽头所供给的轮询 API 与存储内部。
+
+## 导航
+
+- ← [文档根目录](../README.md)
+- ↑ [文档索引](../OVERVIEW.md)
diff --git a/docs/i18n/zh-CN/docs/env/01-variables.md b/docs/zh-cn/env/01-variables.md
similarity index 98%
rename from docs/i18n/zh-CN/docs/env/01-variables.md
rename to docs/zh-cn/env/01-variables.md
index 30c4df10..d3c1baf8 100644
--- a/docs/i18n/zh-CN/docs/env/01-variables.md
+++ b/docs/zh-cn/env/01-variables.md
@@ -1,8 +1,8 @@
-[English](../../../../env/01-variables.md) · **简体中文**
+[English](../../en/env/01-variables.md) · **简体中文**
# 环境变量参考
-FreeLLMAPI 从 `.env` 读取的全部变量,按主题分组。默认值和说明仅依据 [`.env.example`](../../../../../.env.example) 中的注释与取值推导而来。在 `.env.example` 中以注释形式出现的变量是可选的;此处列出的是它们文档记载的默认值。
+FreeLLMAPI 从 `.env` 读取的全部变量,按主题分组。默认值和说明仅依据 [`.env.example`](../../../.env.example) 中的注释与取值推导而来。在 `.env.example` 中以注释形式出现的变量是可选的;此处列出的是它们文档记载的默认值。
- [服务器与绑定](#服务器与绑定)
- [出站代理(本地目的地)](#出站代理本地目的地)
diff --git a/docs/i18n/zh-CN/docs/env/02-security-and-keys.md b/docs/zh-cn/env/02-security-and-keys.md
similarity index 95%
rename from docs/i18n/zh-CN/docs/env/02-security-and-keys.md
rename to docs/zh-cn/env/02-security-and-keys.md
index 19e71bbb..f56a1fb0 100644
--- a/docs/i18n/zh-CN/docs/env/02-security-and-keys.md
+++ b/docs/zh-cn/env/02-security-and-keys.md
@@ -1,10 +1,10 @@
-[English](../../../../env/02-security-and-keys.md) · **简体中文**
+[English](../../en/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)。
+来源:[`.env.example`](../../../.env.example)(密钥生命周期注释)、[`server/src/lib/crypto.ts`](../../../server/src/lib/crypto.ts) 与 [`server/src/db/index.ts`](../../../server/src/db/index.ts)。
- [加密密钥一览](#加密密钥一览)
- [密钥解析优先级](#密钥解析优先级)
diff --git a/docs/i18n/zh-CN/docs/env/03-outbound-proxies.md b/docs/zh-cn/env/03-outbound-proxies.md
similarity index 93%
rename from docs/i18n/zh-CN/docs/env/03-outbound-proxies.md
rename to docs/zh-cn/env/03-outbound-proxies.md
index 78f9e3e1..a0bd33b9 100644
--- a/docs/i18n/zh-CN/docs/env/03-outbound-proxies.md
+++ b/docs/zh-cn/env/03-outbound-proxies.md
@@ -1,10 +1,10 @@
-[English](../../../../env/03-outbound-proxies.md) · **简体中文**
+[English](../../en/env/03-outbound-proxies.md) · **简体中文**
# 出站代理
FreeLLMAPI 如何把发往提供方的流量经由代理转发、多个变量同时设置时谁说了算,以及随之而来的 Docker 网络坑点。
-来源:[`.env.example`](../../../../../.env.example)(代理配置块)、[`docker-compose.yml`](../../../../../docker-compose.yml),以及 [`docs/install.md`](../install.md) 中的容器网络说明。
+来源:[`.env.example`](../../../.env.example)(代理配置块)、[`docker-compose.yml`](../../../docker-compose.yml),以及 [`docs/install.md`](../../en/install/01-install.md) 中的容器网络说明。
- [代理链优先级](#代理链优先级)
- [协议支持](#协议支持)
diff --git a/docs/i18n/zh-CN/docs/env/CHANGELOG.md b/docs/zh-cn/env/CHANGELOG.md
similarity index 100%
rename from docs/i18n/zh-CN/docs/env/CHANGELOG.md
rename to docs/zh-cn/env/CHANGELOG.md
diff --git a/docs/i18n/zh-CN/docs/env/OVERVIEW.md b/docs/zh-cn/env/OVERVIEW.md
similarity index 79%
rename from docs/i18n/zh-CN/docs/env/OVERVIEW.md
rename to docs/zh-cn/env/OVERVIEW.md
index 250d7174..d7449f66 100644
--- a/docs/i18n/zh-CN/docs/env/OVERVIEW.md
+++ b/docs/zh-cn/env/OVERVIEW.md
@@ -1,12 +1,12 @@
-[English](../../../../env/OVERVIEW.md) · **简体中文**
+[English](../../en/env/OVERVIEW.md) · **简体中文**
# 环境变量配置总览
## 范围
-本域文档描述 FreeLLMAPI 的运行时配置面:服务器从 `.env` 读取的每一个变量、提供方 API 密钥如何静态加密存储,以及出站流量如何经由代理转发。唯一的权威来源是仓库根目录的 [`.env.example`](../../../../../.env.example);这里的参考内容均由它(及其描述的代码路径)推导而来,绝不编造取值。
+本域文档描述 FreeLLMAPI 的运行时配置面:服务器从 `.env` 读取的每一个变量、提供方 API 密钥如何静态加密存储,以及出站流量如何经由代理转发。唯一的权威来源是仓库根目录的 [`.env.example`](../../../.env.example);这里的参考内容均由它(及其描述的代码路径)推导而来,绝不编造取值。
-如果是第一次把安装跑起来,请看[安装与部署](../install.md)。
+如果是第一次把安装跑起来,请看[安装与部署](../../en/install/01-install.md)。
## 文件索引
@@ -18,6 +18,6 @@
## 约定
-- 变量由 [`server/src/env.ts`](../../../../../server/src/env.ts) 通过 dotenv 加载;`FREEAPI_ENV_PATH` 可为嵌入式场景指定另一处 `.env` 位置。
+- 变量由 [`server/src/env.ts`](../../../server/src/env.ts) 通过 dotenv 加载;`FREEAPI_ENV_PATH` 可为嵌入式场景指定另一处 `.env` 位置。
- `.env.example` 中被注释掉的行是可选变量;未注释的行自带生效的默认值。
- 凡是也能在运行时从仪表盘修改的变量,都会注明对应的运行时设置键,且该设置键始终优先于环境变量的取值。
diff --git a/docs/zh-cn/fallback/01-named-chains.md b/docs/zh-cn/fallback/01-named-chains.md
new file mode 100644
index 00000000..a0431118
--- /dev/null
+++ b/docs/zh-cn/fallback/01-named-chains.md
@@ -0,0 +1,60 @@
+[English](../../en/fallback/01-named-chains.md) · **简体中文**
+
+# 命名回退链
+
+> **来源:** `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`
+
+*回退链*是路由器为一次请求可尝试的有序模型集合。同一时刻只有一条链处于**活跃**状态;`plain auto` 始终跟随活跃链。链的存储位置取决于安装是否使用命名配置档:
+
+- **无配置档(旧版安装):** 全局 `fallback_config` 表。
+- **命名配置档:** `profiles` 表加上每个链内模型的 `profile_models` 行,每行带有 `priority` 与 `enabled`。
+
+在仪表盘的**回退**页面上创建、重命名、删除以及切换活跃链。配置档名称使用拉丁字母、数字、连字符与下划线(最多 20 个字符),且不得与保留的路由关键词冲突(`auto`、`smart`、`fast`、`cheap`、`budget`、`intelligence`、`speed`、`active`、`default`)。
+
+## 生命周期:空链拒绝
+
+当命名配置档作为活跃链时,`auto` **不是**对整个目录的放行。路由器会解析活跃链,若其中没有已启用的模型,则**抛出面向客户端的 `400`**,而非静默回落到全局表:
+
+```
+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>".
+```
+
+该拒绝仅在配置档处于活跃时触发。未使用配置档的旧版安装仍保持普通的“所有模型已耗尽”路径——路由器执行(可能为空的)全局链并返回正常的耗尽错误。要点在于:空链必须表示“不允许任何模型”,而非“允许全部”。历史见[提交](#提交)。
+
+`activeChainOrThrow`(`router.ts`)是唯一的关口:`auto`、未知的 `auto:` 后缀以及空模型字符串都会经过它。它也是 `GET /api/fallback` 与 `/token-usage` 所读取的内容,因此仪表盘与路由器对活跃链包含什么永远不会产生分歧。
+
+## `GET /v1/models` 中的 `auto:<name>`
+
+每个自定义路由配置档都会作为可发现的模型 ID `auto:<name>`(`cc1e985`)向客户端公示。`GET /v1/models` 会列出每个命名链及其最大上下文与可用性,连同普通的 OpenAI 形态目录以及 Claude 家族的发现 ID。客户端可通过发送 `model="auto:coding"` 按请求切换链——无需改动仪表盘,无需轮换密钥。未知链名会返回清晰的 `400`,而非静默使用活跃链。
+
+由于命名链的行来自 `profile_models`(而非全局 `fallback_config`),两套安装可以通过同一个统一密钥运行完全不同的模型集合——链由请求的 `model` 字段选择,而非由账户决定。
+
+## 目录同步与精选链
+
+全新的配置档默认为 **“从空开始”**——其 `profile_models` 集合初始为空,并退出目录同步的回填。这是命名链的全部意义:操作者手动挑选“这三个模型,按此顺序”,网关便不再自行猜测。
+
+`profiles.auto_include_new_models` 标志(`b3bf20f`)控制例外:
+
+- **`auto_include_new_models = 0`(默认):** 目录同步永不回填链。链保持操作者放入时的原样。在精选的编程/视觉链上关闭此项,可防止新发现的模型悄悄出现在链中。
+- **`auto_include_new_models = 1`:** 每个新同步的模型都会追加到链末尾(下一个优先级,继承模型的全局 `enabled` 状态)。在需要随目录增长的“兜底”配置档上使用。
+
+同步会执行 `autoIncludeNewModelsForProfiles`,该函数仅触及设置了标志的配置档——精选链永不被改动。
+
+## 按行启用 / 禁用
+
+`PUT /api/fallback` 会向活跃链写入完整的链替换,而 **全部启用 / 全部禁用** 操作(`b3bf20f`)会一次性翻转所有行。`chain_enabled` 仅是读取时的标记:被禁用的行仍会消耗提供方的免费额度,仍计入额度池,只是会在所有已启用行之后排序,并被 `activeChainOrThrow` 的“是否有已启用?”检查跳过。这正是让手写(“从空开始”)链可用的关键:页面呈现为“目录减去我关闭的部分”,排在显式添加的行之后。
+
+## 注释,而非全局表
+
+`fallback_config` 现在**仅**是未配置任何配置档的安装的链。一旦存在配置档,其 `profile_models` 即为权威,全局表会被绕过。把全局表当作空 `profile_models` 集合的回退,正是 `e852ff1` 修复的错误——在此之前, freshly 创建的“从空开始”配置档会把整个目录渲染为已启用,因为每个消费者都把零行解读为“未配置链”并悄悄回落到 `fallback_config`。
+
+## 提交
+
+| 提交 | 变更 |
+|--------|--------|
+| `e852ff1` | **回退链即其自身,空与否皆然。** `activeChainOrThrow` 即使在没有已启用行时也会返回活跃配置档的链,而非回落到全局 `fallback_config`。空的精选链现在以 `400` 拒绝,而非静默地在整个目录上路由。 |
+| `b3bf20f` | **让手写的链保持手写。** 链可从空开始;新增的 `auto_include_new_models` 标志阻止目录同步回填精选链;路由表获得 全部启用 / 全部禁用。关闭 #895。 |
+| `8bb2004` | **回退页面上的命名链管理器。** 用于创建、重命名与删除命名链的折叠手风琴,暴露客户端发送的 `auto:<name>` ID。关联 #895 #960。 |
+| `cc1e985` | **将命名链列为 `auto:<name>` 模型。** 每个自定义路由配置档在 `GET /v1/models` 中以 `auto:<name>` 形式出现,并附带其最大上下文与可用性。关联 #895 #880 #960。 |
diff --git a/docs/zh-cn/fallback/CHANGELOG.md b/docs/zh-cn/fallback/CHANGELOG.md
new file mode 100644
index 00000000..20631c8d
--- /dev/null
+++ b/docs/zh-cn/fallback/CHANGELOG.md
@@ -0,0 +1,16 @@
+[English](../../en/fallback/CHANGELOG.md) · **简体中文**
+
+# 回退域 —— 变更日志
+
+`docs/fallback/` 的文档修订历史,取自与回退相关的提交。
+
+## 2026-08-25
+
+- **docs(fallback): 搭建回退域** —— 新建 `docs/fallback/` 域,含 `OVERVIEW.md` + `CHANGELOG.md`,以及 `01-named-chains.md`,涵盖链生命周期、空链 `400` 拒绝(`activeChainOrThrow`)、`auto:<name>` 在 `GET /v1/models` 中的暴露,以及 `profiles.auto_include_new_models`,并附有权威的空链提交 `e852ff1`、`b3bf20f`、`8bb2004`、`cc1e985`。
+
+## 2026-08-23 —— 前置历史
+
+- **e852ff1** 让回退链表示其自身,空与否皆然 (#1023)
+- **b3bf20f** 让回退链可手工构建并保持原样 (#1004)
+- **8bb2004** 在回退页面新增命名链管理器 (#988)
+- **cc1e985** 将命名回退链列为 `auto:<name>` 模型 (#986)
diff --git a/docs/zh-cn/fallback/OVERVIEW.md b/docs/zh-cn/fallback/OVERVIEW.md
new file mode 100644
index 00000000..6640e37c
--- /dev/null
+++ b/docs/zh-cn/fallback/OVERVIEW.md
@@ -0,0 +1,23 @@
+[English](../../en/fallback/OVERVIEW.md) · **简体中文**
+
+# 回退域 —— 概览与文件索引
+
+本域文档描述 FreeLLMAPI 的命名回退链系统:链如何存储、路由器如何解析活跃链(为空时拒绝)、命名链如何以 `auto:<name>` 形式暴露给客户端,以及目录同步如何与精选链交互。根目录 [`README.md`](../README.md) 与 [`OVERVIEW.md`](../OVERVIEW.md) 将其索引为操作者控制路由器可用模型的主要机制。
+
+## 文件索引
+
+| 文件 | 范围 |
+|------|-------|
+| [`01-named-chains.md`](01-named-chains.md) | 链生命周期、空链拒绝、`auto:<name>` 路由、`profiles.auto_include_new_models`,以及使空链具有权威性的提交。 |
+| [`CHANGELOG.md`](CHANGELOG.md) | 本域文档修订历史。 |
+
+## 导航
+
+- ← [文档根目录](../README.md)
+- 深度剖析:[`01-named-chains.md`](01-named-chains.md)
+
+## 相关
+
+- [../architecture/](../architecture/) —— 执行已解析链的路由器、评分与故障转移内部实现。
+- [../api/](../api/) —— 向客户端暴露命名链的 `auto:*` 路由策略与 `GET /v1/models` 接口。
+- [../providers/](../providers/) —— 为链中每一跳提供门控的按密钥额度记账与冷却。
diff --git a/docs/zh-cn/glossary/01-glossary.md b/docs/zh-cn/glossary/01-glossary.md
new file mode 100644
index 00000000..f0127e9f
--- /dev/null
+++ b/docs/zh-cn/glossary/01-glossary.md
@@ -0,0 +1,20 @@
+[English](../../en/glossary/01-glossary.md) · **简体中文**
+
+# 术语表
+
+| 术语 | 含义 |
+| --- | --- |
+| **余量(Headroom)** | 模型/密钥在触及限流前的剩余额度:`1 − max(RPM/RPD/TPM/TPD 已用)`。`0`=已耗尽,`1`=满额。可通过 `HEADROOM_RAMP_START`/`HEADROOM_FLOOR` 调节(见 `../architecture/01-routing-and-bandit-scoring.md`)。 |
+| **RPD / TPD** | 每日请求数 / 每日词元数 —— 每日额度窗口(`ratelimit.ts:modelWindowUsedFraction`,5 秒 TTL)。 |
+| **RPM / TPM** | 每分钟请求数 / 每分钟词元数 —— 短窗口额度。 |
+| **池键(Pool key)** | 共享额度池标识符(`provider-quota.ts:inferQuotaPoolKey`),例如 `openrouter::free`、`google::project`、`custom::key123`。同一池中的密钥共享同一额度。 |
+| **最少剩余(Least-remaining)** | 密钥选择策略(`c4c0221`),挑选池中剩余额度最多的密钥(`services/router.ts:getKeySelectionStrategy`),跳过 `::account` 池。 |
+| **`auto:<name>`** | 命名回退链以可选模型形式暴露在 `GET /v1/models` 中(`cc1e985`)——例如 `auto:fast` 仅通过该链路由。 |
+| **模型年龄闸(Model-age gate)** | 目录同步规则:新模型在 30 天内为 `premium`,随后在下一次签名同步时变为 `free`(`services/catalog-sync.ts`)。 |
+| **老虎机路由(Bandit router)** | Thompson 采样路由器(`services/router.ts` + `scoring.ts`),在可靠性/速度/智能/余量后验之间权衡,并保留 10% 探索。 |
+| **在途窗口(In-flight window)** | 并发请求去重窗口 —— **不**为幂等去重(`95bc46f`,`services/idempotency.ts:16-20`)—— 使用相同 `Idempotency-Key` 的并发重试可能产生竞态。 |
+| **TRUST_PROXY** | 环境变量(`.env.example:314`,`lib/config.ts:95-110`),转发给 Express `trust proxy`,以便分析/限流通过 `X-Forwarded-For`/`Proto` 看到真实客户端 IP。默认 `false`(不信任伪造)。 |
+| **`FREEAPI_SHOT`** | 桌面端截图模式标志,位于 `desktop/src/main.ts`。 |
+| **`freellmapi-…`** | 汇聚回退链标识符 —— 网关的单一逻辑模型,经由回退阶梯扇出。 |
+
+另见:[架构](../architecture/OVERVIEW.md)、[路由与老虎机评分](../architecture/01-routing-and-bandit-scoring.md)、[额度与冷却引擎](../architecture/02-quota-and-cooldown-engine.md)。
diff --git a/docs/zh-cn/glossary/CHANGELOG.md b/docs/zh-cn/glossary/CHANGELOG.md
new file mode 100644
index 00000000..fb56a796
--- /dev/null
+++ b/docs/zh-cn/glossary/CHANGELOG.md
@@ -0,0 +1,10 @@
+[English](../../en/glossary/CHANGELOG.md) · **简体中文**
+
+# 术语表 —— 变更日志
+
+| 提交 | 日期 | 摘要 |
+| --- | --- | --- |
+| `688a88a` | 2026-09-02 | 创建术语表域 —— 术语:余量、RPD/TPD、池键、最少剩余、auto:<name>、模型年龄闸、老虎机、TRUST_PROXY、FREEAPI_SHOT |
+| `eb19dcf` | 2026-09-02 | 修复术语表失效链接 `../architecture` → `architecture`(术语表位于 docs/ 自身) |
+
+重新生成:`git log --oneline -- docs/glossary/`
diff --git a/docs/zh-cn/glossary/OVERVIEW.md b/docs/zh-cn/glossary/OVERVIEW.md
new file mode 100644
index 00000000..b5af624c
--- /dev/null
+++ b/docs/zh-cn/glossary/OVERVIEW.md
@@ -0,0 +1,19 @@
+[English](../../en/glossary/OVERVIEW.md) · **简体中文**
+
+# 术语表域 —— 概览与文件索引
+
+## 范围
+
+本域收录 FreeLLMAPI 文档中反复出现的术语表——路由余量、额度窗口、池键、老虎机概念以及产品专属标识。它是定义那些否则会散落在 `architecture/`、`env/` 与 `fallback/` 深度文档中的术语的唯一位置。
+
+## 文件索引
+
+| 文件 | 说明 |
+| --- | --- |
+| [01-glossary.md](01-glossary.md) | 常用术语表:余量、RPD/TPD、池键、`auto:<name>`、模型年龄闸、老虎机、`TRUST_PROXY`、`FREEAPI_SHOT`,并交叉链接到架构深度文档。 |
+| [CHANGELOG.md](CHANGELOG.md) | 本域文档修订历史。 |
+
+## 导航
+
+- ← [文档根目录](../README.md)
+- ↑ [文档索引](../OVERVIEW.md)
diff --git a/docs/i18n/zh-CN/docs/install.md b/docs/zh-cn/install/01-install.md
similarity index 94%
rename from docs/i18n/zh-CN/docs/install.md
rename to docs/zh-cn/install/01-install.md
index c724839a..48026aac 100644
--- a/docs/i18n/zh-CN/docs/install.md
+++ b/docs/zh-cn/install/01-install.md
@@ -1,8 +1,8 @@
-[English](../../../install.md) · **简体中文**
+[English](../../en/install/01-install.md) · **简体中文**
# 安装与部署
-[← 返回 README](../README.md) · [文档索引](README.md)
+[← 返回 README](../../en/README.md) · [文档索引](../../en/README.md)
把 FreeLLMAPI 跑起来所需的一切:一行命令、Docker Compose、本地开发、声明式配置、生产构建、桌面应用,以及你的数据存放在哪里。
@@ -26,7 +26,7 @@ curl -fsSL https://freellmapi.co/install.sh | bash
在 Windows 上,最省事的方式是桌面版 **[Releases 里的 `.exe` 安装包](https://github.com/tashfeenahmed/freellmapi/releases/latest)**(见[下文](#桌面应用));上面的 Docker 步骤在 WSL 或任意 bash shell 里同样可用。
-在 Android 上,参见实验性的 [Termux 安装指南](../../../install/android-termux.md)。它使用 Node 内置的 SQLite 驱动,不需要 Android NDK。
+在 Android 上,参见实验性的 [Termux 安装指南](../../en/install/02-android-termux.md)。它使用 Node 内置的 SQLite 驱动,不需要 Android NDK。
打开 http://localhost:3001 ,在 **密钥** 页添加你的提供方密钥,按喜好调整 **回退链** 的顺序,然后在 **密钥** 页顶部拿到你的统一 API 密钥。这个统一密钥就是你的 OpenAI SDK 要指向的东西。
@@ -219,15 +219,15 @@ FREEAPI_DB_BACKUP_INTERVAL_MS=300000
启动时如果数据库文件不存在,FreeLLMAPI 会先恢复备份,再执行迁移。服务运行期间,它会定期上传一份新的加密备份。如果没有设置 `FREEAPI_DB_BACKUP_KEY`,备份信封也会使用 `ENCRYPTION_KEY`。
-更多 Docker 运维内容和示例在 [docker/README.md](../../../../docker/README.md)。
+更多 Docker 运维内容和示例在 [docker/../../en/README.md](../../../docker/README.md)。
## 桌面应用
-[`desktop/`](../../../../desktop) 里有一个原生的菜单栏应用:整个路由器加仪表盘就在你的托盘里本地运行,还有一个玻璃质感的悬浮窗显示实时请求统计。
+[`desktop/`](../../../desktop) 里有一个原生的菜单栏应用:整个路由器加仪表盘就在你的托盘里本地运行,还有一个玻璃质感的悬浮窗显示实时请求统计。
-![FreeLLMAPI 桌面应用](../../../../repo-assets/desktop.png)
+![FreeLLMAPI 桌面应用](../../../repo-assets/desktop.png)
-**[从 Releases 下载](https://github.com/tashfeenahmed/freellmapi/releases/latest)** —— macOS 的 `.dmg` 和 Windows 的 `.exe` 安装包由 [`desktop-release`](../../../../.github/workflows/desktop-release.yml) 工作流在每个版本发布时构建并附带。你也可以花几分钟从本仓库自己构建:
+**[从 Releases 下载](https://github.com/tashfeenahmed/freellmapi/releases/latest)** —— macOS 的 `.dmg` 和 Windows 的 `.exe` 安装包由 [`desktop-release`](../../../.github/workflows/desktop-release.yml) 工作流在每个版本发布时构建并附带。你也可以花几分钟从本仓库自己构建:
> **Windows 用户从源码构建的注意事项:** 构建桌面应用需要为 Electron 编译原生 SQLite 模块。在执行 `npm install` 之前,你必须先装好 [Visual Studio Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/)(具体来说是「使用 C++ 的桌面开发」工作负载)以及 Python。
@@ -239,7 +239,7 @@ npm run desktop:dist:win # Windows → "desktop/dist-electron/FreeLLMAPI Se
```
> 本地构建出来的应用没有签名,所以 Windows SmartScreen 首次运行时可能会警告(点「更多信息」→「仍要运行」);macOS 构建则不会触发 Gatekeeper 提示。
-> 完整说明见 [desktop/README.md](../../../../desktop/README.md)。
+> 完整说明见 [desktop/../../en/README.md](../../en/desktop/../../en/README.md)。
## 凭据与数据存放位置
diff --git a/docs/zh-cn/install/02-android-termux.md b/docs/zh-cn/install/02-android-termux.md
new file mode 100644
index 00000000..b5253a4e
--- /dev/null
+++ b/docs/zh-cn/install/02-android-termux.md
@@ -0,0 +1,5 @@
+# 02-android-termux — Termux
+
+> TODO: 翻译待完成 — 参见 [English](../../en/install/02-android-termux.md)
+
+英文原文在 [`docs/en/install/02-android-termux.md`](../../en/install/02-android-termux.md)。
diff --git a/docs/zh-cn/install/CHANGELOG.md b/docs/zh-cn/install/CHANGELOG.md
new file mode 100644
index 00000000..fb7f987c
--- /dev/null
+++ b/docs/zh-cn/install/CHANGELOG.md
@@ -0,0 +1,5 @@
+# Changelog — install (zh-cn)
+
+| Commit | Date | Summary |
+| --- | --- | --- |
+| — | — | 占位,待翻译 |
diff --git a/docs/zh-cn/install/OVERVIEW.md b/docs/zh-cn/install/OVERVIEW.md
new file mode 100644
index 00000000..5e0dee45
--- /dev/null
+++ b/docs/zh-cn/install/OVERVIEW.md
@@ -0,0 +1,3 @@
+# install — 占位
+
+> TODO: 翻译待完成 — 参见 [English](../../en/install/OVERVIEW.md)
diff --git a/docs/i18n/zh-CN/docs/logs/01-server-logs-viewer.md b/docs/zh-cn/logs/01-server-logs-viewer.md
similarity index 98%
rename from docs/i18n/zh-CN/docs/logs/01-server-logs-viewer.md
rename to docs/zh-cn/logs/01-server-logs-viewer.md
index cf8009ff..f7d47b3d 100644
--- a/docs/i18n/zh-CN/docs/logs/01-server-logs-viewer.md
+++ b/docs/zh-cn/logs/01-server-logs-viewer.md
@@ -1,4 +1,4 @@
-[English](../../../../logs/01-server-logs-viewer.md) · **简体中文**
+[English](../../en/logs/01-server-logs-viewer.md) · **简体中文**
# 服务器日志查看器
diff --git a/docs/i18n/zh-CN/docs/logs/CHANGELOG.md b/docs/zh-cn/logs/CHANGELOG.md
similarity index 83%
rename from docs/i18n/zh-CN/docs/logs/CHANGELOG.md
rename to docs/zh-cn/logs/CHANGELOG.md
index 1968de40..cf367600 100644
--- a/docs/i18n/zh-CN/docs/logs/CHANGELOG.md
+++ b/docs/zh-cn/logs/CHANGELOG.md
@@ -1,4 +1,4 @@
-[English](../../../../logs/CHANGELOG.md) · **简体中文**
+[English](../../en/logs/CHANGELOG.md) · **简体中文**
# 变更日志
diff --git a/docs/i18n/zh-CN/docs/logs/OVERVIEW.md b/docs/zh-cn/logs/OVERVIEW.md
similarity index 85%
rename from docs/i18n/zh-CN/docs/logs/OVERVIEW.md
rename to docs/zh-cn/logs/OVERVIEW.md
index f9d2ca91..e567abcf 100644
--- a/docs/i18n/zh-CN/docs/logs/OVERVIEW.md
+++ b/docs/zh-cn/logs/OVERVIEW.md
@@ -1,4 +1,4 @@
-[English](../../../../logs/OVERVIEW.md) · **简体中文**
+[English](../../en/logs/OVERVIEW.md) · **简体中文**
# 日志域
diff --git a/docs/i18n/zh-CN/docs/providers/01-supported-platforms.md b/docs/zh-cn/providers/01-supported-platforms.md
similarity index 95%
rename from docs/i18n/zh-CN/docs/providers/01-supported-platforms.md
rename to docs/zh-cn/providers/01-supported-platforms.md
index 421b622e..d8518cf4 100644
--- a/docs/i18n/zh-CN/docs/providers/01-supported-platforms.md
+++ b/docs/zh-cn/providers/01-supported-platforms.md
@@ -1,8 +1,8 @@
-[English](../../../../providers/01-supported-platforms.md) · **简体中文**
+[English](../../en/providers/01-supported-platforms.md) · **简体中文**
# 支持的平台
-[`shared/types.ts`(第 59 行)](../../../../../shared/types.ts) 中的 `Platform` 联合类型是平台身份的唯一事实来源;[`server/src/providers/index.ts`](../../../../../server/src/providers/index.ts) 中的运行时注册表必须与它保持一致。联合类型目前声明了 **41 个成员**:
+[`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 个条目**;
diff --git a/docs/i18n/zh-CN/docs/providers/02-quotas-and-cooldowns.md b/docs/zh-cn/providers/02-quotas-and-cooldowns.md
similarity index 91%
rename from docs/i18n/zh-CN/docs/providers/02-quotas-and-cooldowns.md
rename to docs/zh-cn/providers/02-quotas-and-cooldowns.md
index 47fd5da2..f8c5960d 100644
--- a/docs/i18n/zh-CN/docs/providers/02-quotas-and-cooldowns.md
+++ b/docs/zh-cn/providers/02-quotas-and-cooldowns.md
@@ -1,8 +1,8 @@
-[English](../../../../providers/02-quotas-and-cooldowns.md) · **简体中文**
+[English](../../en/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) 中共享的退避解析器。
+免费额度以特定的、被计量的方式耗尽:每分钟和每日的请求上限、词元预算、并发限制,以及直接的额度枯竭。网关把这一切建模出来,让路由器不再把回退尝试浪费在明知已经花光的密钥上。相关机制位于 [`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)
@@ -59,7 +59,7 @@
- 自然语言:锚定的短语如 "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)。
+只保留数字——正文从不保留——因此没有任何多余的东西进入日志或尝试轨迹。测试:[`server/src/__tests__/providers/stated-retry.test.ts`](../../../server/src/__tests__/providers/stated-retry.test.ts)。
## 健康检查不得燃烧计量额度(#882)
diff --git a/docs/i18n/zh-CN/docs/providers/03-adding-a-new-provider.md b/docs/zh-cn/providers/03-adding-a-new-provider.md
similarity index 79%
rename from docs/i18n/zh-CN/docs/providers/03-adding-a-new-provider.md
rename to docs/zh-cn/providers/03-adding-a-new-provider.md
index d249b014..d1e8854f 100644
--- a/docs/i18n/zh-CN/docs/providers/03-adding-a-new-provider.md
+++ b/docs/zh-cn/providers/03-adding-a-new-provider.md
@@ -1,12 +1,12 @@
-[English](../../../../providers/03-adding-a-new-provider.md) · **简体中文**
+[English](../../en/providers/03-adding-a-new-provider.md) · **简体中文**
# 添加新提供方
-一篇贡献者走查,与现有 37 个内置平台的接入方式如出一辙。阅读时请把 [`server/src/providers/index.ts`](../../../../../server/src/providers/index.ts) 放在手边——它既是注册表,也是各平台取舍判断的最好文档。
+一篇贡献者走查,与现有 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 枚举决定用户可以为哪些平台登记密钥。
+在 [`shared/types.ts`](../../../shared/types.ts)(第 59 行)的 `Platform` 联合中加入 id,并附注释写明你能够辩护的免费额度事实:什么免费、循环发放还是促销、要不要信用卡、有没有注册墙。联合必须与 [`server/src/routes/keys.ts`](../../../server/src/routes/keys.ts) 的 `PLATFORMS` 白名单保持同步——那个 zod 枚举决定用户可以为哪些平台登记密钥。
## 2. 选择适配器
@@ -61,7 +61,7 @@ register(new OpenAICompatProvider({
## 6. 测试
-在 [`server/src/__tests__/providers/`](../../../../../server/src/__tests__/providers/) 下按照既有模式补测试(一批 OpenAI 兼容注册参见 `cn-providers.test.ts`):断言出站请求的形状(URL、鉴权头的位置、请求头)、响应归一化,以及你引入的任何怪癖处理。在仓库根目录用 `npm test` 跑完整链路——见 [docs/testing](../testing/OVERVIEW.md)。
+在 [`server/src/__tests__/providers/`](../../../server/src/__tests__/providers/) 下按照既有模式补测试(一批 OpenAI 兼容注册参见 `cn-providers.test.ts`):断言出站请求的形状(URL、鉴权头的位置、请求头)、响应归一化,以及你引入的任何怪癖处理。在仓库根目录用 `npm test` 跑完整链路——见 [docs/testing](../testing/OVERVIEW.md)。
## 清单
diff --git a/docs/i18n/zh-CN/docs/providers/CHANGELOG.md b/docs/zh-cn/providers/CHANGELOG.md
similarity index 100%
rename from docs/i18n/zh-CN/docs/providers/CHANGELOG.md
rename to docs/zh-cn/providers/CHANGELOG.md
diff --git a/docs/i18n/zh-CN/docs/providers/OVERVIEW.md b/docs/zh-cn/providers/OVERVIEW.md
similarity index 63%
rename from docs/i18n/zh-CN/docs/providers/OVERVIEW.md
rename to docs/zh-cn/providers/OVERVIEW.md
index 3870cf6c..efdaba88 100644
--- a/docs/i18n/zh-CN/docs/providers/OVERVIEW.md
+++ b/docs/zh-cn/providers/OVERVIEW.md
@@ -1,4 +1,4 @@
-[English](../../../../providers/OVERVIEW.md) · **简体中文**
+[English](../../en/providers/OVERVIEW.md) · **简体中文**
# 提供方集成总览
@@ -6,7 +6,7 @@
本域文档描述 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);目录实际跟踪的平台比类型联合声明的要少,因为联合中的部分成员已退役,或者由用户自定义而非由目录管理。
+权威来源是 [`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 的提供方表格](../../en/README.md);目录实际跟踪的平台比类型联合声明的要少,因为联合中的部分成员已退役,或者由用户自定义而非由目录管理。
## 文件索引
@@ -18,6 +18,6 @@
## 约定
-- 适配器位于 [`server/src/providers/`](../../../../../server/src/providers/);在那里注册的每个平台立即出现在 `/v1` 路由上——没有单独的启用步骤。
+- 适配器位于 [`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/zh-cn/proxy/01-fetch-relay.md b/docs/zh-cn/proxy/01-fetch-relay.md
new file mode 100644
index 00000000..01e6ae07
--- /dev/null
+++ b/docs/zh-cn/proxy/01-fetch-relay.md
@@ -0,0 +1,41 @@
+[English](../../en/proxy/01-fetch-relay.md) · **简体中文**
+
+# Fetch Relay 传输
+
+FreeLLMAPI 可将发往提供方的 HTTP 请求经由应用层的 Fetch Relay 路由,例如 Cloudflare Worker。与 CONNECT/SOCKS 正向代理不同,中继收到的是普通的已鉴权 HTTP 请求,再去拉取目标并把响应流式传回。
+
+```text
+FreeLLMAPI -> Fetch Relay -> 提供方
+```
+
+在 **密钥 -> 出站代理** 下选择 `fetch-relay`,填入 Relay URL 与令牌,或为无界面安装做如下配置:
+
+```dotenv
+PROXY_MODE=fetch-relay
+PROXY_URL=https://relay.example.workers.dev
+FETCH_RELAY_TOKEN=generate-a-long-random-token
+```
+
+`forward` 仍是默认值。现有的 `PROXY_URL`、`ALL_PROXY`、`HTTPS_PROXY`、`HTTP_PROXY`、SOCKS、按密钥代理、绕过以及 `NO_PROXY` 行为保持不变,除非显式选择了 `fetch-relay`。
+
+## 协议
+
+FreeLLMAPI 将原始方法、正文、提供方请求头以及取消信号发送到 `PROXY_URL`,并附带两个跳间控制头:
+
+```http
+Fetch-Relay-Authorization: Bearer <relay-token>
+Fetch-Relay-Target: https://api.provider.example/v1/chat/completions
+Authorization: Bearer <provider-key>
+```
+
+Relay 鉴权与提供方鉴权是刻意分离的。不支持查询字符串与 `{url}` 兼容格式。FreeLLMAPI 会覆盖调用方传入的 Relay 控制头,不缓冲响应体,并要求手动处理重定向,以免重定向意外变成对提供方的直连请求。
+
+仪表盘保存的 Relay 令牌会在静态存储时加密,且设置接口永不回显。支持空令牌以实现有意的未鉴权中继,但不推荐。在无界面部署中,`FETCH_RELAY_TOKEN` 环境变量优先于仪表盘保存的值。
+
+## 安全契约
+
+Relay 可以看到提供方凭据与请求内容。请仅使用由您信任的操作者控制的 Relay。生产环境的 Relay 应当对每个请求做鉴权,在请求目标前移除所有 `Fetch-Relay-*` 头,拒绝本地与元数据目的地,手动处理重定向,避免 Cookie,永不记录凭据或完整的目标 URL,且流式而非缓冲请求体。
+
+## Cloudflare Worker 参考
+
+[`examples/fetch-relay-worker`](../../../examples/fetch-relay-worker/README.md) 包含一个与提供方无关的单文件 Worker。它不维护目标站点列表:每个请求都在 `Fetch-Relay-Target` 中携带完整的公开 HTTP(S) 目标。实现通过 Cloudflare 密钥做鉴权,拦截明显的 SSRF 目的地与中继回环,剥离跳间头与 Cookie,不跟随重定向而是暴露重定向位置,并输出经过脱敏的结构化日志。
diff --git a/docs/zh-cn/proxy/CHANGELOG.md b/docs/zh-cn/proxy/CHANGELOG.md
new file mode 100644
index 00000000..a60ac179
--- /dev/null
+++ b/docs/zh-cn/proxy/CHANGELOG.md
@@ -0,0 +1,14 @@
+[English](../../en/proxy/CHANGELOG.md) · **简体中文**
+
+# 代理域 —— 变更日志
+
+`docs/proxy/` 的文档修订历史,取自触及出站代理与 Fetch Relay 的提交。最近的在前。
+
+| 提交 | 日期 | 摘要 |
+| --- | --- | --- |
+| `46ea0de` | 2026-09-02 | feat(proxy): 为反向代理后的客户端 IP 适配 `TRUST_PROXY` (#1041) —— 新增 `TRUST_PROXY`(`false\|true\|<hops>\|addr/CIDR`,`.env.example:306-315`,`server/src/lib/config.ts:95-112` 的 `parseTrustProxy`)并转发给 Express `trust proxy`,使分析与 `PROXY_RATE_LIMIT_RPM`/`ADMIN_RATE_LIMIT_RPM` 在 Caddy/nginx/Traefik 之后能看到真实客户端 IP;默认 `false`(不信任伪造)。 |
+| `86368ac` | 2026-09-01 | feat(proxy): 作为最后兜底自动检测系统级代理设置 (#838) —— 新增 `detectSystemProxy()`(`server/src/lib/proxy.ts:52-414` —— macOS 上 `scutil --proxy`,Windows 注册表 `ProxyEnable`+`ProxyServer`,Linux 上 GNOME `gsettings` `manual` + `http host/port`)位于 `PROXY_URL → 仪表盘 → ALL_PROXY → HTTPS_PROXY → HTTP_PROXY → detectSystemProxy() → 直连` 链末尾(`resolveProxySource`),关闭 #353/#1069,尽力而为,2 秒超时,永不抛异常。 |
+| `56eb257` | 2026-08-31 | 按需启用的 Fetch Relay 出站传输 (#975) —— 新增 `PROXY_MODE`(`forward` 默认,`fetch-relay` 按需启用,`.env.example:74-78`,`server/src/lib/proxy.ts:52` 的 `PROXY_MODES`)与 `FETCH_RELAY_TOKEN`(bearer,静态加密,空值表示未鉴权但不推荐,环境变量优先于仪表盘,`.env.example:78`,`server/src/lib/proxy.ts:389-417`,`isLoopbackRelayHostname`/`fetchRelayUrlError` 回环-https 防护,`Fetch-Relay-Target`/`Fetch-Relay-Authorization` 头,`fetchRelayFetch` 流式 + 手动重定向,`examples/fetch-relay-worker/` Cloudflare Worker 参考);初始 `docs/fetch-relay.md`(现为 `docs/proxy/01-fetch-relay.md`)包含协议、安全契约与 Worker 详情。 |
+| `ac0a9ce` | 2026-08-22 | docs(env): 新增运行时配置参考域 —— 在 `docs/env/03-outbound-proxies.md` 中首次加入出站代理文档(优先级 `PROXY_URL → 仪表盘 → ALL_PROXY → HTTPS_PROXY → HTTP_PROXY`,协议支持 `http`/`https`/`socks4`/`socks4a`/`socks5`/`socks5h`,`NO_PROXY` 绕过,Docker `host.docker.internal` 坑点,入站限流旋钮),搭建 `docs/env/` 域脚手架,含 `OVERVIEW.md` + `CHANGELOG.md`。 |
+
+使用 `git log --oneline -- docs/proxy/ docs/fetch-relay.md docs/env/03-outbound-proxies.md` 与 `git log --oneline --grep=proxy --grep=relay --grep=TRUST_PROXY` 重新生成。
diff --git a/docs/zh-cn/proxy/OVERVIEW.md b/docs/zh-cn/proxy/OVERVIEW.md
new file mode 100644
index 00000000..d407433c
--- /dev/null
+++ b/docs/zh-cn/proxy/OVERVIEW.md
@@ -0,0 +1,33 @@
+[English](../../en/proxy/OVERVIEW.md) · **简体中文**
+
+# 代理域 —— 概览与文件索引
+
+## 范围
+
+本域文档描述 FreeLLMAPI 的出站代理传输方式以及相关的入站 `TRUST_PROXY` 处理。发往提供方的流量可通过两种传输方式离开网关:
+
+- **正向代理**(`forward` 模式,默认)—— 传统的 CONNECT/SOCKS 代理,经由 `PROXY_URL`(显式 `PROXY_URL` → 仪表盘 密钥 → 出站代理设置 → `ALL_PROXY` → `HTTPS_PROXY` → `HTTP_PROXY`,小写拼写同样会被读取),支持协议 `http`/`https`/`socks4`/`socks4a`/`socks5`/`socks5h`(带 `h`/`a` 的表示在代理端而非本地解析 DNS),`NO_PROXY` 直连豁免,按密钥覆盖,以及 Docker `host.docker.internal` 坑点。未做任何配置时,链会回落到**系统自动检测**(`server/src/lib/proxy.ts:52-414` 中的 `detectSystemProxy` —— macOS 上 `scutil --proxy`,Windows Internet Options 注册表 `ProxyEnable`/`ProxyServer`,Linux 上 GNOME `gsettings` `manual` + `http host/port`)作为最后的兜底(尽力而为,2 秒超时,永不抛异常)。
+- **Fetch Relay**(`fetch-relay` 模式,按需启用)—— 应用层中继,例如 Cloudflare Worker(`FreeLLMAPI -> Relay -> 提供方`),通过 `PROXY_MODE=fetch-relay` + `PROXY_URL`(中继 URL)+ `FETCH_RELAY_TOKEN` bearer(`Fetch-Relay-Target`/`Fetch-Relay-Authorization` 跳间头,静态加密,`FETCH_RELAY_TOKEN` 环境变量优先,回环防护,无缓冲流式且不自动重定向)启用 —— 见 [01-fetch-relay.md](01-fetch-relay.md)。
+
+入站流量方面,`TRUST_PROXY`(`server/src/lib/config.ts:95` 的 `parseTrustProxy`)控制 Express 的 `trust proxy`(`false` 默认 —— 不信任 `X-Forwarded-For`/`X-Forwarded-Proto`;`true` —— 信任全部;`<hops>` 数字 —— 信任距套接字对端指定跳数;逗号分隔的 `addr/CIDR` 列表 —— 仅信任这些),以便在反向代理(Caddy/nginx/Traefik)之后,分析与 `PROXY_RATE_LIMIT_RPM`/`ADMIN_RATE_LIMIT_RPM` 能看到真实客户端 IP。
+
+相关:完整的 `.env` 全貌见 [`../env/01-variables.md`](../env/01-variables.md),正向代理链在 [`../env/03-outbound-proxies.md`](../env/03-outbound-proxies.md) 中展开;消费该代理的提供方路由与故障转移位于 [`../architecture/`](../architecture/OVERVIEW.md);Cloudflare Worker 参考见 [`../../../examples/fetch-relay-worker/README.md`](../../../examples/fetch-relay-worker/README.md)。
+
+## 文件索引
+
+| 文件 | 说明 |
+| --- | --- |
+| [01-fetch-relay.md](01-fetch-relay.md) | Fetch Relay 传输:`FreeLLMAPI -> Fetch Relay -> 提供方`,`PROXY_MODE=fetch-relay`(`forward` 为默认),`PROXY_URL` 作为中继 URL,`FETCH_RELAY_TOKEN`(静态加密,环境变量优先,空值表示未鉴权),`Fetch-Relay-Authorization: Bearer <relay-token>` + `Fetch-Relay-Target: <provider-url>` 跳间头,回环-https 防护,流式/手动重定向,Cloudflare Worker(`examples/fetch-relay-worker/`)参考。 |
+| [CHANGELOG.md](CHANGELOG.md) | 本域文档修订历史。 |
+
+## 约定
+
+- 来源:[`.env.example`](../../../.env.example) 代理配置块(70–80 行:`PROXY_MODE`、`PROXY_URL`、`FETCH_RELAY_TOKEN`),[`server/src/lib/proxy.ts`](../../../server/src/lib/proxy.ts)(`PROXY_MODES`、`detectSystemProxy` `scutil`/`registry`/`gsettings`、`fetchRelayFetch`、`isLoopbackRelayHostname`/`fetchRelayUrlError`),[`server/src/lib/config.ts`](../../../server/src/lib/config.ts)(95 行的 `parseTrustProxy`),[`examples/fetch-relay-worker/README.md`](../../../examples/fetch-relay-worker/README.md)。
+- `forward` 仍是默认的 `PROXY_MODE`;`fetch-relay` 会覆盖调用方传入的 `Fetch-Relay-*` 头,在请求目标前剥离它们,拒绝本地/元数据目的地与中继回环,手动处理重定向,避免 Cookie,永不记录凭据,流式而非缓冲响应体。
+
+## 导航
+
+- ← [文档根目录](../README.md)
+- ↔ [环境变量域](../env/OVERVIEW.md)
+- 出站代理详情:[`../env/03-outbound-proxies.md`](../env/03-outbound-proxies.md)
+- Worker 参考:[`../../../examples/fetch-relay-worker/README.md`](../../../examples/fetch-relay-worker/README.md)
diff --git a/docs/i18n/zh-CN/docs/testing/01-running-tests.md b/docs/zh-cn/testing/01-running-tests.md
similarity index 75%
rename from docs/i18n/zh-CN/docs/testing/01-running-tests.md
rename to docs/zh-cn/testing/01-running-tests.md
index 52c7f910..a791f62f 100644
--- a/docs/i18n/zh-CN/docs/testing/01-running-tests.md
+++ b/docs/zh-cn/testing/01-running-tests.md
@@ -1,10 +1,10 @@
-[English](../../../../testing/01-running-tests.md) · **简体中文**
+[English](../../en/testing/01-running-tests.md) · **简体中文**
# 运行测试
## 根链
-仓库根目录的 `npm test` 按顺序运行([package.json](../../../../../package.json)):
+仓库根目录的 `npm test` 按顺序运行([package.json](../../../package.json)):
| 步骤 | 命令 | 覆盖内容 |
| --- | --- | --- |
@@ -26,7 +26,7 @@ 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/` 下面的任何东西之后都要跑它。
+`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
@@ -48,7 +48,7 @@ npm run check:i18n -w client # scripts/check-i18n.mjs
## 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。步骤按顺序:
+[`.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`
diff --git a/docs/i18n/zh-CN/docs/testing/02-server-suite.md b/docs/zh-cn/testing/02-server-suite.md
similarity index 83%
rename from docs/i18n/zh-CN/docs/testing/02-server-suite.md
rename to docs/zh-cn/testing/02-server-suite.md
index 4114f169..43d0393a 100644
--- a/docs/i18n/zh-CN/docs/testing/02-server-suite.md
+++ b/docs/zh-cn/testing/02-server-suite.md
@@ -1,10 +1,10 @@
-[English](../../../../testing/02-server-suite.md) · **简体中文**
+[English](../../en/testing/02-server-suite.md) · **简体中文**
# 服务器套件
## 布局
-所有服务器测试位于 [`server/src/__tests__/`](../../../../../server/src/__tests__) 下,与 `src/` 镜像:
+所有服务器测试位于 [`server/src/__tests__/`](../../../server/src/__tests__) 下,与 `src/` 镜像:
| 目录 | 内容 |
| --- | --- |
@@ -24,11 +24,11 @@
- **`--pool=forks`** 把每个测试文件隔离在全新进程里。套件操纵真实状态——better-sqlite3 数据库、`process.env`、模块级缓存(冷却映射、健康调度器)——这些绝不能在文件之间泄漏。
- **`--fileParallelism=false`** 让文件串行执行,共享资源(端口、临时数据目录)就不会在并发执行的文件之间相撞。
-代价是挂钟时间;回报是约 2300 个测试的套件是确定性的。client 工作区不需要这些:它的[独立 vitest 配置](../../../../../client/vitest.config.ts)主要是为了避免加载 React/Tailwind 的 vite 插件,其测试就是默认 node 环境里的普通 TypeScript。
+代价是挂钟时间;回报是约 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` 依然合法,因为类型导入会在制造循环之前就被擦除。
+[`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 --git a/docs/i18n/zh-CN/docs/testing/03-compatibility-suite.md b/docs/zh-cn/testing/03-compatibility-suite.md
similarity index 74%
rename from docs/i18n/zh-CN/docs/testing/03-compatibility-suite.md
rename to docs/zh-cn/testing/03-compatibility-suite.md
index 97efa880..c804a687 100644
--- a/docs/i18n/zh-CN/docs/testing/03-compatibility-suite.md
+++ b/docs/zh-cn/testing/03-compatibility-suite.md
@@ -1,4 +1,4 @@
-[English](../../../../testing/03-compatibility-suite.md) · **简体中文**
+[English](../../en/testing/03-compatibility-suite.md) · **简体中文**
# 兼容性套件
@@ -10,7 +10,7 @@
### 原生 Gemini `/v1beta` 端面
-[`server/src/__tests__/routes/gemini.test.ts`](../../../../../server/src/__tests__/routes/gemini.test.ts) 经 HTTP 驱动组装完成的 Express 应用:
+[`server/src/__tests__/routes/gemini.test.ts`](../../../server/src/__tests__/routes/gemini.test.ts) 经 HTTP 驱动组装完成的 Express 应用:
- 模型发现、`generateContent`(JSON 与 SSE 流式)、`countTokens`;
- Gemini 的 schema 方言与上游提供方之间的工具/思考/结构化输出翻译;
@@ -18,7 +18,7 @@
### 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` 词汇表。
+[`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
@@ -26,7 +26,7 @@
### 客户端分类与 URL 令牌
-客户端分类器测试(`server/src/__tests__/lib/client-context.test.ts` 及同侪)钉住喂给仪表盘「智能体」页和按智能体分析的识别逻辑;[`routes/url-tokens.test.ts`](../../../../../server/src/__tests__/routes/url-tokens.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 令牌,校验过程防时序攻击。
## 它证明了什么
diff --git a/docs/i18n/zh-CN/docs/testing/CHANGELOG.md b/docs/zh-cn/testing/CHANGELOG.md
similarity index 100%
rename from docs/i18n/zh-CN/docs/testing/CHANGELOG.md
rename to docs/zh-cn/testing/CHANGELOG.md
diff --git a/docs/i18n/zh-CN/docs/testing/OVERVIEW.md b/docs/zh-cn/testing/OVERVIEW.md
similarity index 75%
rename from docs/i18n/zh-CN/docs/testing/OVERVIEW.md
rename to docs/zh-cn/testing/OVERVIEW.md
index bb13970b..51d18ad4 100644
--- a/docs/i18n/zh-CN/docs/testing/OVERVIEW.md
+++ b/docs/zh-cn/testing/OVERVIEW.md
@@ -1,4 +1,4 @@
-[English](../../../../testing/OVERVIEW.md) · **简体中文**
+[English](../../en/testing/OVERVIEW.md) · **简体中文**
# 测试总览
@@ -6,7 +6,7 @@
本域文档描述 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__) 下的各个套件本身。
+来源:根目录 [`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__) 下的各个套件本身。
## 文件索引
diff --git a/docs/zh-cn/troubleshooting/01-common-issues.md b/docs/zh-cn/troubleshooting/01-common-issues.md
new file mode 100644
index 00000000..0194308c
--- /dev/null
+++ b/docs/zh-cn/troubleshooting/01-common-issues.md
@@ -0,0 +1,73 @@
+[English](../../en/troubleshooting/01-common-issues.md) · **简体中文**
+
+# 常见问题
+
+## Docker 容器无法访问提供方
+
+**现象:** 容器内访问 `127.0.0.1:11434`(Ollama)或 `localhost` 时出现 `ECONNREFUSED` 或超时,宿主机却可达。
+
+**原因:** 容器内的 `127.0.0.1` 指向容器本身,而非宿主机。参见 `deployment/01-docker.md` 中 container-cannot-reach-providers 坑点。
+
+**修复:** 在 Docker Desktop 上使用 `host.docker.internal`,Linux 上使用 `172.17.0.1` 或宿主机局域网 IP,并确保代理(Clash / v2rayN / sing-box)监听 `0.0.0.0` 而非 `127.0.0.1`。Compose 的 `host-gateway` 映射:`extra_hosts: ["host.docker.internal:host-gateway"]`。
+
+**诊断:** `docker exec freellmapi curl -v http://host.docker.internal:11434/api/tags`。
+
+## 空链 `400`
+
+**现象:** `POST /v1/chat/completions` 返回 `400 active chain is empty`(或 fallback ladder empty)。
+
+**原因:** 活跃的回退链存在但未启用任何模型——自 `e852ff1` / `b3bf20f` 起,空链被视为权威配置,不再静默回退到目录全量。
+
+**修复:** 打开 `Fallback` 页面 → 在活跃链中启用模型,或设置 `profiles.auto_include_new_models=1`,或切换活跃 profile。参见 `fallback/01-named-chains.md`。
+
+## Fetch Relay 环回防护
+
+**现象:** 使用 `PROXY_MODE=fetch-relay` 时返回 `fetchRelayUrlError` 或 `isLoopbackRelayHostname` 400。
+
+**原因:** 环回 `PROXY_URL`(`127.0.0.1`、`::1`)被 `enforceRelayUrlPolicy` 拦截,除非显式放行;fetch-relay 拒绝 SOCKS(仅支持 `http` / `https`,且 `http` 仅允许环回)。
+
+**修复:** 使用公开的 `https://relay.example.workers.dev` URL。本地测试时检查 `server/src/lib/proxy.ts:339-350` 中的策略。参见 `proxy/01-fetch-relay.md`。
+
+## 幂等 `409` 冲突
+
+**现象:** 重试时返回 `409 Idempotency-Key already used with different request`。
+
+**原因:** 同一个 `Idempotency-Key` 携带了不同的指纹(`model` / `messages` / `temperature` / `top_p` / `max_tokens` / `tools` / `tool_choice` 有差异)。参见 `api/02-idempotency.md`。
+
+**修复:** 为每个不同的请求使用全新的 UUID,或重放完全相同的请求体。进行中窗口不会去重(`95bc46f`)—— 使用相同 key 的并发重试仍可能竞态。
+
+## 额度面板显示陈旧或排序延迟
+
+**现象:** 额度面板更新缓慢或显示大量行。
+
+**修复:** `QUOTA_OBSERVATIONS_RETENTION_DAYS=30` / `QUOTA_OBSERVATIONS_MAX_ROWS=200000` 会以 `5k` / `250ms` 为块每日清理(`4a8f095`);请确保数据库位于高速卷上。检查 `server/src/services/request-retention.ts:68-137` 与 `provider-quota.ts:532-586` 中相关的 `LIMIT 1` 索引查找。
+
+## 密码重置验证码不可见(桌面端)
+
+**现象:** `POST /api/auth/forgot-password` 在控制台打印了一次性验证码,但桌面应用未显示。
+
+**原因:** 从 Finder / Explorer 启动的 Electron 没有附加 `stdout`。
+
+**修复:** 打开托盘 → `Open Logs Folder` → `freeapi.log`(`desktop/src/logger.ts` 的 tee,`installFileLogger` 在 server 启动前安装)。或使用 `docker logs`。
+
+## 更新检查显示无更新 / 未签名构建无法自动更新
+
+**现象:** 仪表盘检查器显示 `latest > running`,但 `Squirrel.Mac` 拒绝更新,或 DMG 自动更新失败。
+
+**原因:** `Squirrel.Mac` 会校验代码签名。未带证书的本地 `npm run dist` 能产出应用,但不会产生有效的更新源(`desktop/02-logging-and-updates.md`)。DMG 在 `Apple stapler` 公证后需经 `refresh-mac-update-metadata.mjs` 重新盖戳。
+
+**修复:** 从 GitHub Releases 下载已签名的发布包,或使用 `CSC_*` / `APPLE_ID` 进行签名。
+
+## 反向代理 `TRUST_PROXY` 未获取到真实客户端 IP
+
+**现象:** 分析 / 限流显示 `127.0.0.1` 而非真实客户端。
+
+**原因:** `TRUST_PROXY` 默认 `false`(防伪造)。
+
+**修复:** 单个反向代理(与宿主机同机的 Caddy / nginx / Traefik)设为 `TRUST_PROXY=1`,或使用 CIDR 列表(`TRUST_PROXY=100.64.0.0/10,192.168.1.10`)。参见 `env/01-variables.md` 中 `TRUST_PROXY` 与 `server/src/lib/config.ts:95-110` 的 `parseTrustProxy()`。
+
+## 相关
+
+- [桌面端](../desktop/OVERVIEW.md) — `freeapi.log` 轮转。
+- [代理传输](../proxy/OVERVIEW.md) — fetch-relay 协议。
+- [环境变量](../env/01-variables.md) — 全部配置项。
diff --git a/docs/zh-cn/troubleshooting/CHANGELOG.md b/docs/zh-cn/troubleshooting/CHANGELOG.md
new file mode 100644
index 00000000..01c3173f
--- /dev/null
+++ b/docs/zh-cn/troubleshooting/CHANGELOG.md
@@ -0,0 +1,16 @@
+[English](../../en/troubleshooting/CHANGELOG.md) · **简体中文**
+
+# 故障排查域 —— 变更日志
+
+`docs/troubleshooting/` 的文档修订历史。最新在前。
+
+| 提交 | 日期 | 摘要 |
+| --- | --- | --- |
+| `8bd3acd` | 2026-09-02 | 幂等 `409`—— 指纹 / TTL 已文档化 |
+| `e852ff1` | 2026-08-23 | 空链权威 `400`—— `activeChainOrThrow` |
+| `86368ac` | 2026-09-01 | 系统代理自动探测 `scutil` / `registry` / `gsettings` |
+| `56eb257` | 2026-08-31 | Fetch Relay `PROXY_MODE` / `FETCH_RELAY_TOKEN` 环回防护 |
+| `46ea0de` | 2026-09-02 | `TRUST_PROXY` 转发头 |
+| `90aaa5b` | 2026-08-24 | 桌面端 `freeapi.log` 密码重置可见性 |
+
+重新生成:`git log --oneline -- docs/troubleshooting/`
diff --git a/docs/zh-cn/troubleshooting/OVERVIEW.md b/docs/zh-cn/troubleshooting/OVERVIEW.md
new file mode 100644
index 00000000..2db91af1
--- /dev/null
+++ b/docs/zh-cn/troubleshooting/OVERVIEW.md
@@ -0,0 +1,19 @@
+[English](../../en/troubleshooting/OVERVIEW.md) · **简体中文**
+
+# 故障排查域 —— 概览与文件索引
+
+## 范围
+
+本域汇总了原本分散在 `deployment/01-docker.md`、`fallback/01-named-chains.md`、`env/03-outbound-proxies.md` 与 `api/02-idempotency.md` 各处的排障技巧。如果提供方调用返回了非预期状态码,或网关在反向代理之后或开发机上的行为与预期不符,请从这里开始排查。
+
+## 文件索引
+
+| 文件 | 说明 |
+| --- | --- |
+| [01-common-issues.md](01-common-issues.md) | Docker 容器无法访问提供方、空链 `400`、fetch-relay 环回防护、幂等 `409`、额度面板、更新检查、密码重置验证码不可见。 |
+| [CHANGELOG.md](CHANGELOG.md) | 本域文档修订历史。 |
+
+## 导航
+
+- ← [文档根目录](../README.md)
+- ↑ [文档索引](../OVERVIEW.md)
diff --git a/examples/fetch-relay-worker/README.md b/examples/fetch-relay-worker/README.md
index 13e430fe..80164334 100644
--- a/examples/fetch-relay-worker/README.md
+++ b/examples/fetch-relay-worker/README.md
@@ -1,7 +1,7 @@
# Universal Fetch Relay Worker
This provider-agnostic, single-file Cloudflare Worker implements the protocol
-documented in [`docs/fetch-relay.md`](../../docs/fetch-relay.md). It stores no
+documented in [`docs/en/proxy/01-fetch-relay.md`](../../docs/en/proxy/01-fetch-relay.md). It stores no
target-site or LLM-provider configuration. Each request supplies its complete
public HTTP(S) target through `Fetch-Relay-Target`.