diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 99e9674d..390c9377 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -18,19 +18,25 @@ while thirty-five commits landed on `main` without it.
## What this repository is
-A set of crates, not an application. `bin/twcore` is a complete gateway
-binary and the thing to run when you want to see behavior:
+A set of crates, and the `twcore` binary built from them. `bin/twcore` is
+a complete gateway and the thing to run when you want to see behavior:
```bash
-cargo run -p twcore -- init # write a commented config.yaml
+cargo run -p twcore -- init # write an initial config.yaml
cargo run -p twcore -- check # validate only, don't start
cargo run -p twcore -- serve # start the gateway and control plane
```
-Both editions depend on these crates — the desktop app
-([ThinkWatch Lite](https://github.com/ThinkWatchProject/ThinkWatch-Lite))
-and the server edition. A change here reaches both, so "it works for my
-case" is not the bar.
+Two products are built on these crates.
+[ThinkWatch Lite](https://github.com/ThinkWatchProject/ThinkWatch-Lite),
+the desktop app, bundles `twcore` as its gateway and can also connect to
+one running on a server.
+[ThinkWatch Enterprise](https://github.com/ThinkWatchProject/ThinkWatch)
+depends on exactly three of the crates, `tw-dialect`, `tw-guard` and
+`tw-breaker`, and CI checks that it still compiles against every change
+to them. A change here reaches every installation of the app and every
+server running `twcore`, and a change to those three crates reaches
+ThinkWatch Enterprise as well, so "it works for my case" is not the bar.
What is *not* here: adopting AI clients, editing their MCP servers and
scanning their configuration. Those change files on the machine the
@@ -189,7 +195,7 @@ The desktop app pins `tw-api` (and the few other crates it uses:
and bundles the binary from that release. Those two have to come from one
commit: the binary speaks a protocol, and the app compiles a mirror of it.
-On macOS, Apple Silicon only, deliberately. An Intel user downloading a
+On macOS, Apple silicon only, deliberately. An Intel user downloading a
file that will not open is worse served than one who finds no download
at all; supporting them means a universal binary, which is its own
decision.
diff --git a/README.md b/README.md
index ba0d0c5d..5da54f42 100644
--- a/README.md
+++ b/README.md
@@ -1,120 +1,283 @@
-
-
-
+
+
+
+
+
# ThinkWatch Core
**[English](README.md) | [中文](README.zh-CN.md)**
-**The shared core of a local AI API gateway.** Routing, forwarding, observability,
-cost accounting, and a set of data-plane guards — used by both the desktop app
-(ThinkWatch Lite) and the server edition.
+ThinkWatch Core is a set of Rust crates and the `twcore` gateway binary built
+from them. Claude Code, Codex and other clients of the Anthropic, OpenAI and
+Gemini APIs send their requests to `twcore`, which routes each request by rule,
+fails over to another upstream before the response begins, records what each
+request cost, redacts secrets before a request is sent, and inspects the tool
+calls an upstream returns.
-**This repository is not an application you install.** It is a set of crates.
-If you want something that runs, `bin/twcore` is a complete, self-contained
-gateway binary.
+`twcore` runs as the local gateway inside
+[ThinkWatch Lite](https://github.com/ThinkWatchProject/ThinkWatch-Lite), the
+desktop app for macOS, Windows and Linux, or as a standalone gateway on a Linux
+server, which ThinkWatch Lite connects to over an encrypted control channel.
+[ThinkWatch Enterprise](https://github.com/ThinkWatchProject/ThinkWatch)
+depends on three of the crates: `tw-dialect`, `tw-guard` and `tw-breaker`.
-```
-cargo run -p twcore -- init # write a commented config.yaml
-cargo run -p twcore -- check # validate only, don't start
-cargo run -p twcore -- serve # start the gateway and control plane
+Documentation: [configuration reference](docs/config.md) ·
+[running core on a server](docs/server.md) ·
+[thinkwat.ch/core](https://thinkwat.ch/core/)
+
+## Features
+
+- **Rule-based routing.** Named rules match on the requested model (glob
+ patterns), the gateway key, the API format, the estimated input token count,
+ `max_tokens`, and whether a request uses tools, images, extended thinking,
+ prompt caching or streaming. A matching rule sends the request to an upstream
+ or a group, rewrites parameters (the model, `max_tokens`, thinking), or
+ refuses it with a stated reason. A group chooses among its upstreams in order
+ (`fallback`), by manual selection (`select`), in rotation (`load-balance`), by
+ measured time to first byte (`url-test`) or by price (`cheapest`).
+- **Failover.** Until the first byte of a response reaches the client, a failed
+ upstream is replaced by the next candidate without the client noticing, and
+ every attempt is recorded with the request. A stream that breaks after that
+ point ends with an error event, so the client does not take it for a complete
+ answer. An upstream that fails three times in a row is set aside for a minute
+ before it is tried again.
+- **Format conversion.** Clients can use Anthropic Messages, OpenAI Chat
+ Completions, OpenAI Responses or Gemini, independently of the format the
+ upstream speaks; when the two differ, requests, responses and streams are
+ converted. An upstream can be a provider's API, a relay such as OpenRouter, a
+ local model server or a ChatGPT account.
+- **Cost accounting.** The token usage of every request, cache reads and writes
+ included, is priced against a public price table that is refreshed daily, or
+ against a price sheet for upstreams that charge differently (a multiplier or
+ per-model prices). An upstream such as a local model can be marked as free.
+ Usage that cannot be priced is labelled unknown rather than counted as zero,
+ and each request records its cost and where the price came from.
+- **Protections.** Five protections apply to every request, whatever the
+ upstream, each in off, observe or enforce mode. In enforce mode, outbound
+ redaction replaces credentials such as API keys, private keys and the
+ passwords in connection strings with placeholders before a request is sent,
+ and restores them where the response repeats them; tool-call inspection can
+ cut the response off when an upstream returns a tool call that matches a rule
+ for dangerous commands; hidden-character detection refuses requests that
+ carry Unicode tag characters or bidirectional controls; content filtering can
+ refuse requests that match a keyword or regular-expression rule; and the
+ output limit cuts an answer off at a set number of characters. In observe
+ mode a protection records what it finds and changes nothing. Every protection
+ starts in observe mode except the output limit, which starts off. Built-in
+ rules can be turned off one at a time, and custom rules added.
+- **Request history and live events.** Every request is stored in a local
+ SQLite database with the rule it matched, each upstream attempt, its usage and
+ its cost. The control plane streams events as requests start and finish, and a
+ dry run shows where a request would be routed, and why, without sending it.
+- **One configuration file.** All settings are kept in `config.yaml`. A change,
+ whether made in an editor, with `twcore config` or through the control plane,
+ takes effect within a second once it validates; a change that does not
+ validate is refused and the previous configuration keeps serving. The last
+ fifty versions are kept, and any of them can be restored.
+
+## Install
+
+### Prebuilt binaries
+
+Each [release](https://github.com/ThinkWatchProject/ThinkWatch-Core/releases/latest)
+provides `twcore` for five platforms, every file with a `.sha256` checksum:
+
+| Platform | File |
+|---|---|
+| macOS, Apple silicon | `twcore-aarch64-apple-darwin` |
+| Windows, x64 | `twcore-x86_64-pc-windows-msvc.exe` |
+| Windows, ARM64 | `twcore-aarch64-pc-windows-msvc.exe` |
+| Linux, x86_64 | `twcore-x86_64-unknown-linux-gnu`, or `twcore-x86_64-unknown-linux-gnu.tar.gz` with the systemd unit |
+| Linux, aarch64 | `twcore-aarch64-unknown-linux-gnu`, or `twcore-aarch64-unknown-linux-gnu.tar.gz` with the systemd unit |
+
+To verify a download, run `sha256sum -c .sha256` (on macOS,
+`shasum -a 256 -c .sha256`) in the directory that holds both files. The
+Linux builds require glibc 2.35 or later (Ubuntu 22.04, Debian 12 or later).
+A desktop needs no separate download: ThinkWatch Lite includes `twcore` and
+updates it together with the app.
+
+### Linux server
+
+```sh
+curl -fsSL https://raw.githubusercontent.com/ThinkWatchProject/ThinkWatch-Core/main/scripts/install.sh | sudo sh
```
-Every field of `config.yaml` is described in the
-[configuration reference](docs/config.md). To run `twcore` on a Linux server
-and manage it from the desktop app, see
-[Running core on a server](docs/server.md).
-
-## What it does
-
-Point a client (Claude Code, Codex, and friends) at a local port, and:
-
-- **Route by rule** to different upstreams — conditions can be the model name,
- the client, context length, whether tools are present; actions are switching
- upstream, rewriting parameters, or refusing outright.
-- **Fail over mid-flight** — before the first byte an upstream can be swapped
- transparently; after it, the only honest thing left is to report what happened.
-- **Make cost visible** — token usage, cache hits, priced against a public
- price table that refreshes daily, with price sheets for upstreams that
- charge differently. What cannot be priced is labelled *unknown* rather
- than given an invented number.
-- **Redact outbound** — secrets in a request are replaced with placeholders
- before they reach a relay, and restored when the model echoes them back.
-- **Inspect inbound** — tool calls returned by an upstream are checked against
- a rule set; a dangerous one can be cut off mid-frame.
+The script installs `twcore` as a systemd service. The steps that follow are
+summarized under [Server deployment](#server-deployment) and described in full
+in [Running core on a server](docs/server.md).
-## Crate layers
+### From source
+
+Building requires a stable Rust toolchain, 1.85 or later.
+```sh
+git clone https://github.com/ThinkWatchProject/ThinkWatch-Core.git
+cd ThinkWatch-Core
+cargo build --release -p twcore # produces target/release/twcore
```
-tw-dialect · tw-guard · tw-breaker ← shared with the server edition
-tw-types · tw-engine · tw-pricing · tw-yaml · tw-secret · tw-watch ← domain logic
-tw-config · tw-store · tw-observe ← assembly
-tw-gateway · tw-control · tw-link ← data plane / control plane
+
+To run it from the checkout:
+
+```sh
+cargo run -p twcore -- init # write an initial config.yaml
+cargo run -p twcore -- check # validate the configuration without starting
+cargo run -p twcore -- serve # start the gateway and the control plane
```
-The server edition depends on the top layer and nothing else: format
-conversion and usage parsing (tw-dialect), redaction and tool-call inspection
-(tw-guard), and the circuit-breaker state machine (tw-breaker). Those three
-depend only on each other — a test enforces it, and CI builds the server
-edition against every change to them. A component only one side uses lives
-on that side, not here.
+`twcore` keeps its configuration and data in `~/.thinkwatch`
+(`%APPDATA%\ThinkWatch` on Windows), or in the directory named by
+`THINKWATCH_HOME`. Every field of `config.yaml` is described in the
+[configuration reference](docs/config.md).
-Adopting AI clients (pointing their configuration at the gateway), editing
-their MCP servers and scanning their configuration live in the desktop app:
-they change files on the machine the app runs on, which need not be the one
-running core. Core only issues a client its own gateway key.
+## Server deployment
-Everything below is the single-machine implementation (SQLite, unix socket)
-and is deliberately **not** shared: single-machine SQLite and multi-tenant
-Postgres are different enough that forcing one abstraction over both would
-serve neither.
+`twcore` can run as a systemd service on Linux (x86_64, aarch64). A single
+command installs the binary, a dedicated user and the service unit; ThinkWatch
+Lite on macOS, Windows and Linux connects to it through the remote control
+port.
-## Development
+```sh
+curl -fsSL https://raw.githubusercontent.com/ThinkWatchProject/ThinkWatch-Core/main/scripts/install.sh | sudo sh
+```
+
+The script checks the download against its SHA-256 checksum, installs
+`/usr/local/bin/twcore`, creates the system user `thinkwatch` with the data
+directory `/var/lib/thinkwatch`, and installs `twcore.service`. When there is no
+configuration yet, it runs `twcore init` as that user, which writes a
+`config.yaml` with a gateway key, the control key, and the remote control port
+disabled on a random port between 20000 and 32000. The script does not start
+the service. It installs the latest release; to install a particular one,
+append `-s -- --version ` to `sudo sh`.
+
+Commands that read the configuration run as the service user, with its data
+directory:
+
+```sh
+alias twc='sudo -u thinkwatch THINKWATCH_HOME=/var/lib/thinkwatch twcore'
+twc remote enable --allow 192.168.1.0/24 # open the remote control port to this network
+twc check # validate config.yaml
+sudo systemctl enable --now twcore # start the service, now and at boot
+twc control-key # the key for ThinkWatch Lite on stdout; address and port on stderr
```
-cargo test --workspace # unit and integration tests
-scripts/smoke.sh # from a clean slate, exercise every path on the real binary
+
+For clients on other machines to use the gateway, set
+`listen.gateway.bind: all` in `config.yaml` and list their networks in
+`listen.gateway.allow_from`. Upstreams can be written under `providers` or
+added later from ThinkWatch Lite. In ThinkWatch Lite,
+**Settings → Connection → Add remote connection** takes a name, the server's
+address, the control port and the key. The app connects only to a core that
+speaks its control-plane protocol version, so the server runs the core version
+the app includes, which can be older than the latest release. When the
+versions differ, the app shows both, and `twcore upgrade --version` switches
+the server to the version the app needs, whether newer or older:
+
+```sh
+sudo twcore upgrade --version --restart # install the version the app needs and restart the service
+sudo twcore upgrade --check # compare with the latest release; change nothing
+sudo twcore upgrade --restart # install the latest release and restart the service
```
-`scripts/smoke.sh` touches nothing of yours — `HOME` and `THINKWATCH_HOME` both
-point at a temporary directory that is deleted when it finishes.
+Neither port uses TLS: the control port is encrypted and authenticated by its
+handshake, and the gateway port carries plain HTTP, so both should be reachable
+only from trusted networks. [Running core on a server](docs/server.md) covers
+the complete procedure, including secrets in `/etc/thinkwatch/env`, network
+exposure and uninstalling. Every field of `config.yaml` is described in the
+[configuration reference](docs/config.md).
+
+## Crate layers
+
+The workspace holds sixteen crates and the `twcore` binary in `bin/twcore`.
+It divides the crates in two: the three that ThinkWatch Enterprise depends
+on, and the crates of the gateway that `twcore` runs, which ThinkWatch
+Enterprise does not use. Within the second part, the crates are grouped by
+role. No crate depends on a group below its own.
+
+| Group | Crates |
+|---|---|
+| Shared with ThinkWatch Enterprise | `tw-dialect` · `tw-guard` · `tw-breaker` |
+| Domain logic | `tw-types` · `tw-engine` · `tw-pricing` · `tw-yaml` · `tw-secret` · `tw-watch` |
+| Control-plane contract | `tw-api` · `tw-link` |
+| Assembly | `tw-config` · `tw-store` · `tw-observe` |
+| Data plane and control plane | `tw-gateway` · `tw-control` |
+
+ThinkWatch Enterprise depends on the first group and nothing else: format
+conversion and usage parsing (`tw-dialect`), redaction, tool-call inspection
+and the other protections (`tw-guard`), and the circuit-breaker state machine
+(`tw-breaker`). These three crates depend only on one another; a test enforces
+this, and CI checks that ThinkWatch Enterprise compiles against every change to
+them. A component that only one product uses lives in that product's
+repository.
+
+ThinkWatch Lite pins `tw-api`, `tw-types`, `tw-yaml`, `tw-guard`, `tw-watch`
+and `tw-link` to a release tag and bundles the `twcore` binary from the same
+release. Pointing AI clients at the gateway, editing their MCP servers and
+scanning their configuration files are done in ThinkWatch Lite: they change
+files on the machine the app runs on, which need not be the machine running
+`twcore`. `twcore` only issues each client its own gateway key.
-## The control plane
+The last two groups implement a single `twcore` process: request history in
+SQLite, the configuration in one YAML file, and a control plane reached over a
+local channel or the remote control port. They are deliberately not shared.
+ThinkWatch Enterprise is multi-tenant and keeps its state in PostgreSQL, Redis
+and ClickHouse, and one abstraction over both designs would serve neither.
-The control plane listens on a unix socket (a loopback port on Windows).
-Every connection starts with a handshake —
-`Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s`, implemented in `tw-link` — keyed by
-`listen.control.key` in `config.yaml`. `twcore serve` writes that key before it
-starts listening (into a new configuration, or as one added line in an existing
-one). HTTP runs inside the encrypted channel, so curl cannot talk to it;
+## Control plane
+
+The control plane is an HTTP API carried inside an encrypted channel. It
+listens on a unix socket on macOS and Linux and on a loopback port on Windows;
+the optional remote control port, `listen.control.remote`, adds a network
+listener for ThinkWatch Lite on another machine. Every connection, on every
+transport, begins with the same handshake,
+`Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s` (implemented in `tw-link`), keyed by
+`listen.control.key` in `config.yaml`; no TLS certificates are involved.
+`twcore serve` writes the key before it starts listening, into a new
+configuration or as one added line in an existing one.
+
+As HTTP runs inside the channel, curl cannot reach the control plane;
`twcore call` can:
```
-twcore control-key # print the key the desktop app connects with
+twcore control-key # print the key ThinkWatch Lite connects with
twcore control-key --rotate # replace it; connections made with the old key are closed
twcore call /status
twcore call -X POST -d '{"model":"claude-sonnet-4-5","route":"default"}' /dryrun
```
-The configuration text the control plane hands out has the key masked, and a
+The configuration text the control plane returns has the key masked, and a
write through the control plane cannot change it.
-A desktop app on another machine connects through the remote control port,
-`listen.control.remote`. It is opened in addition to the local channel, with the
+The remote control port is opened in addition to the local channel, with the
same key and handshake:
```
twcore remote enable --allow 192.168.1.0/24 # the port is picked at random the first time
twcore remote disable
-twcore control-key # prints the key; the address and port go to stderr
+twcore control-key # the key on stdout; the address and port on stderr
+```
+
+Connections from sources outside `allow_from` are closed without a reply, and
+the server's own loopback address is not admitted automatically. A source that
+fails the handshake five times within a minute is ignored for a minute, and at
+most 32 remote connections are open at a time. A remote connection cannot stop
+core, take the diagnostic bundle or change `listen.control`.
+
+## Development
+
+```
+cargo test --workspace # unit and integration tests
+scripts/smoke.sh # run every path on the real binary, from a clean state
```
-Sources outside `allow_from` are closed without a reply, a source that fails the
-handshake five times in a minute is ignored for a minute, and a remote connection
-cannot stop the core, take the diagnostic bundle, or change `listen.control`.
+`scripts/smoke.sh` leaves the user's own configuration untouched: `HOME` and
+`THINKWATCH_HOME` both point at a temporary directory that is deleted when the
+script finishes. [CONTRIBUTING.md](CONTRIBUTING.md) lists the checks a pull
+request has to pass and describes the configuration reference, the price list
+and the release process.
## License
-MIT
+[MIT](LICENSE)
diff --git a/README.zh-CN.md b/README.zh-CN.md
index deb1ca02..8d44b9d9 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -1,103 +1,158 @@
-
-
-
+
+
+
+
+
# ThinkWatch Core
**[English](README.md) | [中文](README.zh-CN.md)**
-**一个本地 AI API 网关的共用核心层。**路由、转发、观测、计价,以及一组
-数据面的安全守卫 —— 桌面版(ThinkWatch Lite)和服务端版本都用它。
+ThinkWatch Core 是一组 Rust crate,以及由它们构建的网关二进制 `twcore`。Claude Code、Codex 以及其他使用 Anthropic、OpenAI、Gemini 接口的客户端经由 `twcore` 发出请求;它按规则路由每个请求,在响应开始前故障转移到其他上游,记录每个请求的费用,在请求发出前脱敏其中的密钥,并审查上游返回的工具调用。
-**这个仓库不是一个装上就能用的应用**,它是一组 crate。想要跑得起来的东西,
-`bin/twcore` 是一个完整的、可独立运行的网关二进制。
+`twcore` 既作为本机网关运行在桌面应用 [ThinkWatch Lite](https://github.com/ThinkWatchProject/ThinkWatch-Lite)(macOS、Windows、Linux)中,也可以作为独立网关部署在 Linux 服务器上,由 ThinkWatch Lite 通过加密的控制通道连接。[ThinkWatch 企业版](https://github.com/ThinkWatchProject/ThinkWatch)依赖其中三个 crate:`tw-dialect`、`tw-guard` 和 `tw-breaker`。
-```
-cargo run -p twcore -- init # 生成一份带注释的 config.yaml
-cargo run -p twcore -- check # 只校验,不启动
-cargo run -p twcore -- serve # 起网关和控制面
-```
+文档:[配置手册](docs/config.zh-CN.md) · [在服务器上运行 core](docs/server.zh-CN.md) · [thinkwat.ch/zh-CN/core](https://thinkwat.ch/zh-CN/core/)
-`config.yaml` 的每个字段见[配置手册](docs/config.zh-CN.md)。在 Linux 服务器上运行
-`twcore`、由桌面应用远程管理,见[在服务器上运行 core](docs/server.zh-CN.md)。
+## 功能
-## 它做什么
+- **按规则路由**。具名规则可按以下条件匹配:请求的模型(支持通配符)、网关密钥、接口格式、估算的输入 token 数、`max_tokens`,以及请求是否使用工具、图片、扩展思考、提示缓存或流式输出。命中的规则把请求交给一个上游或策略组、改写参数(模型、`max_tokens`、思考),或附带原因拒绝请求。策略组按顺序(`fallback`)、手动指定(`select`)、轮流(`load-balance`)、按实测首字节时间(`url-test`)或按价格(`cheapest`)选择上游。
+- **故障转移**。响应的首字节到达客户端之前,失败的上游由下一个候选替换,客户端不会察觉,每次尝试都随请求记录。在此之后中断的流以一个错误事件结束,客户端不会把它当作完整的回答。连续失败三次的上游暂停使用一分钟,之后再次尝试。
+- **格式转换**。客户端可以使用 Anthropic Messages、OpenAI Chat Completions、OpenAI Responses 或 Gemini 格式,与上游使用的格式无关;两者不同时,请求、响应和流式输出都会转换。上游可以是服务商的 API、OpenRouter 等中转站、本地模型服务或 ChatGPT 账号。
+- **费用核算**。每个请求的 token 用量(含缓存读写)按每日刷新的公开价目表计价;收费方式不同的上游可以选用自定义价目表(倍率或逐模型价格),本地模型等上游可以设为不计费。无法计价的用量标为「未知」,不计作零;每个请求保存其费用及价格来源。
+- **防护**。五项防护作用于所有请求,不区分上游,各有关闭、观察、拦截三档。在拦截档下:出站脱敏在请求发出前把 API 密钥、私钥、连接串中的口令等凭据替换为占位符,并在响应回显时还原;工具调用审查在上游返回的工具调用命中危险命令规则时可以切断响应;隐藏字符检测拒绝带有 Unicode 标签字符或双向控制符的请求;内容过滤可以拒绝命中关键词或正则规则的请求;输出长度在回答超过设定的字符数时将其切断。在观察档下,防护只记录发现的内容,不改变任何行为。除输出长度出厂为关闭外,其余各项出厂均为观察。内置规则可以逐条停用,也可以添加自定义规则。
+- **请求记录与实时事件**。每个请求连同命中的规则、每次上游尝试、用量和费用保存在本机的 SQLite 数据库中。控制面在请求开始和结束时推送事件;试算可以在不发出请求的情况下说明请求会被路由到哪里及其原因。
+- **单一配置文件**。全部设置保存在 `config.yaml` 中。无论改动来自编辑器、`twcore config` 还是控制面,通过校验后都在一秒内生效;未通过校验的改动被拒绝,原配置继续生效。最近五十个版本都会保留,可以恢复其中任一版本。
-把客户端(Claude Code、Codex 之类)指向本地的一个端口,然后:
+## 安装
-- **按规则路由**到不同上游 —— 条件可以是模型名、客户端、上下文长度、
- 有没有工具调用;动作是换上游、改参数、或者直接拒绝。
-- **流式故障转移** —— 首字节之前可以透明换一家;首字节之后唯一诚实的
- 做法是如实报告发生了什么。
-- **看得见成本** —— token 用量、缓存命中,按每天刷新的公开价目表计价;
- 价格不同的上游可以选用自定义价目表。
- **算不出价钱的明确标「未知」,而不是编一个数字。**
-- **出站脱敏** —— 发给中转站之前,把请求里的密钥换成占位符;模型回显时
- 再换回来。
-- **入站审查** —— 上游返回的工具调用过一遍规则,高危的可以在那一帧上切断。
+### 预编译二进制
-## crate 分层
+每个 [Release](https://github.com/ThinkWatchProject/ThinkWatch-Core/releases/latest) 都提供以下五个平台的 `twcore`,每个文件都附带 `.sha256` 校验文件:
+
+| 平台 | 文件 |
+|---|---|
+| macOS,Apple silicon | `twcore-aarch64-apple-darwin` |
+| Windows,x64 | `twcore-x86_64-pc-windows-msvc.exe` |
+| Windows,ARM64 | `twcore-aarch64-pc-windows-msvc.exe` |
+| Linux,x86_64 | `twcore-x86_64-unknown-linux-gnu`,或附带 systemd 服务单元的 `twcore-x86_64-unknown-linux-gnu.tar.gz` |
+| Linux,aarch64 | `twcore-aarch64-unknown-linux-gnu`,或附带 systemd 服务单元的 `twcore-aarch64-unknown-linux-gnu.tar.gz` |
+
+校验下载时,在两个文件所在的目录中执行 `sha256sum -c <文件>.sha256`(macOS 上为 `shasum -a 256 -c <文件>.sha256`)。Linux 版本需要 glibc 2.35 或更新(Ubuntu 22.04、Debian 12 及以后)。桌面上无需单独下载:ThinkWatch Lite 自带 `twcore`,并随应用一同更新。
+### Linux 服务器
+
+```sh
+curl -fsSL https://raw.githubusercontent.com/ThinkWatchProject/ThinkWatch-Core/main/scripts/install.sh | sudo sh
```
-tw-dialect · tw-guard · tw-breaker ← 与服务端版本共用
-tw-types · tw-engine · tw-pricing · tw-yaml · tw-secret · tw-watch ← 领域逻辑
-tw-config · tw-store · tw-observe ← 装配
-tw-gateway · tw-control · tw-link ← 数据面 / 控制面
+
+脚本把 `twcore` 安装为 systemd 服务。后续步骤概述于[服务器部署](#服务器部署),完整说明见[在服务器上运行 core](docs/server.zh-CN.md)。
+
+### 从源码构建
+
+需要 Rust 稳定版工具链,1.85 或更新。
+
+```sh
+git clone https://github.com/ThinkWatchProject/ThinkWatch-Core.git
+cd ThinkWatch-Core
+cargo build --release -p twcore # 生成 target/release/twcore
```
-服务端版本只依赖最上面一层:格式转换与用量解析(tw-dialect)、脱敏与工具调用
-审查(tw-guard)、熔断状态机(tw-breaker)。这三个只依赖彼此 —— 有测试守着,
-CI 也会拿服务端版本对着每一次改动编译一遍。只有一方在用的东西住在那一方,
-不放在这里。
+在源码目录中直接运行:
+
+```sh
+cargo run -p twcore -- init # 生成初始的 config.yaml
+cargo run -p twcore -- check # 只校验配置,不启动
+cargo run -p twcore -- serve # 启动网关和控制面
+```
-接管 AI 客户端(把它们的配置指向网关)、改它们的 MCP 服务器、扫描它们的配置
-都在桌面版里做:改的是桌面版所在那台机器上的文件,那台机器不一定跑着 core。
-core 只负责给一个客户端发它自己的网关密钥。
+`twcore` 的配置和数据存放在 `~/.thinkwatch`(Windows 上为 `%APPDATA%\ThinkWatch`),设置了 `THINKWATCH_HOME` 时存放在它指定的目录。`config.yaml` 的每个字段见[配置手册](docs/config.zh-CN.md)。
-下面三层是单机的实现(SQLite、unix socket),**有意不共用** —— 单机 SQLite
-和多租户 Postgres 差得太远,强行统一只会造出一个两边都别扭的抽象。
+## 服务器部署
-## 开发
+twcore 可以作为 systemd 服务运行在 Linux(x86_64、aarch64)上。一条命令即可安装二进制、专用用户和服务单元;各平台的 ThinkWatch Lite 通过远程控制端口连接它。
+
+```sh
+curl -fsSL https://raw.githubusercontent.com/ThinkWatchProject/ThinkWatch-Core/main/scripts/install.sh | sudo sh
+```
+
+脚本按 SHA-256 校验下载的文件,安装 `/usr/local/bin/twcore`,创建系统用户 `thinkwatch` 及其数据目录 `/var/lib/thinkwatch`,并安装 `twcore.service`。尚无配置时,脚本以该用户执行 `twcore init`,生成的 `config.yaml` 包含一把网关密钥、控制密钥,以及处于关闭状态的远程控制端口(端口号在 20000–32000 之间随机选取)。脚本不会启动服务。脚本安装最新版本;安装指定版本时,在 `sudo sh` 后加上 `-s -- --version <版本>`。
+
+读取配置的命令须以服务用户的身份、使用服务的数据目录执行:
+```sh
+alias twc='sudo -u thinkwatch THINKWATCH_HOME=/var/lib/thinkwatch twcore'
+
+twc remote enable --allow 192.168.1.0/24 # 对这个网段开放远程控制端口
+twc check # 校验 config.yaml
+sudo systemctl enable --now twcore # 立即启动服务,并随系统启动
+twc control-key # 标准输出是 ThinkWatch Lite 所需的密钥,地址和端口在标准错误
```
-cargo test --workspace # 单元与集成测试
-scripts/smoke.sh # 从零起,在真二进制上把每条路走一遍
+
+要让其他机器上的客户端使用网关,在 `config.yaml` 中设置 `listen.gateway.bind: all`,并在 `listen.gateway.allow_from` 中列出它们所在的网段。上游可以写在 `providers` 下,也可以之后在 ThinkWatch Lite 中添加。在 ThinkWatch Lite 中打开 **设置 → 连接 → 添加远程连接**,填写名称、服务器地址、控制端口和密钥。应用只连接控制面协议版本与自身相同的 core,因此服务器上运行的须是应用内置的 core 版本,它可能比最新版本旧。版本不一致时,应用显示双方的版本;`twcore upgrade --version` 可以把服务器切换到应用需要的版本,无论新旧:
+
+```sh
+sudo twcore upgrade --version <版本> --restart # 安装应用需要的版本并重启服务
+sudo twcore upgrade --check # 与最新 Release 比对,不做任何改动
+sudo twcore upgrade --restart # 安装最新 Release 并重启服务
```
-`scripts/smoke.sh` 不碰你自己的任何东西 —— `HOME` 和 `THINKWATCH_HOME`
-都指向一个临时目录,跑完就删。
+两个端口都不使用 TLS:控制端口由握手完成加密和鉴权,网关端口以明文 HTTP 传输请求,因此两者都只应对可信网络开放。完整步骤见[在服务器上运行 core](docs/server.zh-CN.md),包括 `/etc/thinkwatch/env` 中的密钥、网络暴露和卸载;`config.yaml` 的每个字段见[配置手册](docs/config.zh-CN.md)。
+
+## crate 分层
+
+工作区共有十六个 crate,`twcore` 二进制位于 `bin/twcore`。这些 crate 分为两部分:ThinkWatch 企业版依赖的三个 crate,以及 `twcore` 所运行网关的其余 crate(ThinkWatch 企业版不使用)。第二部分再按职责分组。任何 crate 都不依赖排在其所在组下方的组。
+
+| 分组 | crate |
+|---|---|
+| 与 ThinkWatch 企业版共用 | `tw-dialect` · `tw-guard` · `tw-breaker` |
+| 领域逻辑 | `tw-types` · `tw-engine` · `tw-pricing` · `tw-yaml` · `tw-secret` · `tw-watch` |
+| 控制面契约 | `tw-api` · `tw-link` |
+| 装配 | `tw-config` · `tw-store` · `tw-observe` |
+| 数据面与控制面 | `tw-gateway` · `tw-control` |
+
+ThinkWatch 企业版只依赖第一组,不依赖其他 crate:格式转换与用量解析(`tw-dialect`),脱敏、工具调用审查及其他防护(`tw-guard`),以及熔断状态机(`tw-breaker`)。这三个 crate 只相互依赖,由测试保证;CI 会针对它们的每一次改动检查 ThinkWatch 企业版能否编译。只有一方使用的组件放在那一方的仓库中。
+
+ThinkWatch Lite 把 `tw-api`、`tw-types`、`tw-yaml`、`tw-guard`、`tw-watch` 和 `tw-link` 固定在某个 Release 的 tag 上,并打包同一 Release 的 `twcore`。接管 AI 客户端(把其配置指向网关)、编辑其 MCP 服务器和扫描其配置文件都在 ThinkWatch Lite 中完成:这些操作修改的是应用所在机器上的文件,而这台机器不一定运行着 `twcore`。`twcore` 只负责为每个客户端签发专用的网关密钥。
+
+最后两组实现的是单个 `twcore` 进程:请求记录保存在 SQLite 中,配置保存在一个 YAML 文件中,控制面经本机通道或远程控制端口访问。这两组有意不共用:ThinkWatch 企业版是多租户的,其状态保存在 PostgreSQL、Redis 和 ClickHouse 中,两种设计差异很大,用一个抽象同时覆盖两者,对双方都不合适。
## 控制面
-控制面听在一个 unix socket 上(Windows 上是一个回环端口)。每条连接先握手
-(`Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s`,实现在 `tw-link`),钥匙是
-`config.yaml` 里的 `listen.control.key`。`twcore serve` 在开始监听之前写好它
-(新配置自带;旧配置只补这一行)。HTTP 跑在加密的通道里面,curl 连不上,
-用 `twcore call`:
+控制面是运行在加密通道内的 HTTP 接口。它在 macOS 和 Linux 上监听 unix socket,在 Windows 上监听回环端口;可选的远程控制端口(`listen.control.remote`)另开一个网络监听,供其他机器上的 ThinkWatch Lite 连接。每种通道上的每条连接都以同一个握手开始:`Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s`(实现在 `tw-link` 中),密钥为 `config.yaml` 中的 `listen.control.key`,不涉及 TLS 证书。`twcore serve` 在开始监听前写入该密钥:新配置直接包含,已有的配置只补这一行。
+
+HTTP 运行在加密通道内,curl 无法访问控制面,需使用 `twcore call`:
```
-twcore control-key # 打印桌面端连接用的钥匙
-twcore control-key --rotate # 换一把;用旧钥匙建的连接随即断开
+twcore control-key # 打印 ThinkWatch Lite 连接所用的密钥
+twcore control-key --rotate # 更换密钥;用旧密钥建立的连接随即断开
twcore call /status
twcore call -X POST -d '{"model":"claude-sonnet-4-5","route":"default"}' /dryrun
```
-控制面发出去的配置原文里钥匙是打码的,经控制面的写入也改不了它。
+控制面返回的配置原文中,密钥经过打码;经控制面的写入也无法修改它。
-另一台机器上的桌面端经远程控制端口(`listen.control.remote`)连进来。它是在本机
-通道之外另开的,钥匙和握手都一样:
+远程控制端口在本机通道之外另行开放,使用同一把密钥和同一个握手:
```
-twcore remote enable --allow 192.168.1.0/24 # 端口第一次随机挑
+twcore remote enable --allow 192.168.1.0/24 # 端口在第一次开启时随机选取
twcore remote disable
-twcore control-key # 标准输出是钥匙,地址和端口在标准错误
+twcore control-key # 标准输出是密钥,地址和端口在标准错误
+```
+
+来自 `allow_from` 之外的连接直接关闭,不回复任何字节;服务器本机的回环地址不会自动放行。同一来源一分钟内握手失败五次后,接下来一分钟内的连接一律忽略;远程连接最多同时存在 32 条。远程连接不能停止 core、不能生成诊断包,也不能修改 `listen.control`。
+
+## 开发
+
+```
+cargo test --workspace # 单元测试与集成测试
+scripts/smoke.sh # 从空白状态起,用真实的二进制把每条路径运行一遍
```
-`allow_from` 之外的来源直接关掉、不回任何字节;同一来源一分钟内握手失败五次,
-之后一分钟不理它;远程连接不能关 core、不能取诊断包、不能改 `listen.control`。
+`scripts/smoke.sh` 不会改动用户自己的配置:`HOME` 和 `THINKWATCH_HOME` 都指向一个临时目录,运行结束后删除。提交 PR 前须通过的检查,以及配置手册、价目表和发版流程的说明,见 [CONTRIBUTING.md](CONTRIBUTING.md)。
-## License
+## 许可证
-MIT
+[MIT](LICENSE)