diff --git a/README.md b/README.md index a20033d8..bbb4d866 100644 --- a/README.md +++ b/README.md @@ -10,151 +10,69 @@ **[English](README.md) | [中文](README.zh-CN.md)** -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. - -`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 four of the crates: `tw-dialect`, `tw-guard`, `tw-breaker` and -`tw-bedrock`. +ThinkWatch Core is the gateway engine behind ThinkWatch: a set of Rust crates +and the `twcore` binary built from them. Claude Code, Codex and other clients of +the Anthropic, OpenAI and Gemini APIs point at `twcore` once. From then on, +credentials can be kept out of outgoing requests, the tool calls that come back +are checked, and every request is recorded with where it went and what it cost. `twcore` runs inside the +desktop app [ThinkWatch Lite](https://github.com/ThinkWatchProject/ThinkWatch-Lite) +or on its own on a Linux server, and +[ThinkWatch Enterprise](https://github.com/ThinkWatchProject/ThinkWatch) builds +on four of its crates. 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, its - cost, the time its first token arrived and its generation speed. 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. +## Highlights + +- **Connect once, switch freely.** Clients keep one address and one key; + changing upstreams or models happens in the gateway, with no client change or + restart. Anthropic Messages, OpenAI Chat Completions, OpenAI Responses and + Gemini are converted in both directions, streams included. +- **Outbound redaction.** Outbound redaction can replace API keys, + private keys and connection-string passwords with placeholders before a + request leaves, and restore them where the answer repeats them, so a relay + never sees the real values. +- **Tool calls are checked.** Tool-call inspection can cut off an answer whose + tool call matches a dangerous-command rule; hidden-character detection, a + content filter and an output limit complete the five protections. All start + in observe mode (the output limit starts off) and change nothing until set to + enforce. +- **Every request is traceable.** Each request is stored with the rule that + chose its upstream, every attempt, any format conversion, usage, cost and + where its price came from, time to first token and generation speed. A dry + run shows where a request would go without sending it, and a stored request + can be replayed against another upstream for comparison. +- **Routing and failover.** Rules match on model, key, format, size, tools, + images, thinking and more, and send requests to an upstream or a group (in + order, manual, rotation, lowest latency, lowest cost). Until the first byte + of the response reaches the client, a failing upstream is replaced by the + next candidate and set aside for a time that depends on the reason it gives. +- **Many kinds of upstream.** Provider API keys, any compatible endpoint, relays + such as OpenRouter, local models, Amazon Bedrock, and ChatGPT or Z.ai + accounts. Health checks and warm-ups are answered locally by default, at no cost. +- **Honest cost.** Usage, cache reads and writes included, is priced from a + daily-refreshed public price table or a custom price sheet. Estimated costs + are marked as such, and usage that cannot be priced is counted separately, + never as zero. +- **One file, applied live.** All settings live in `config.yaml`; a change from + an editor, the CLI or the control plane applies within a second once it + validates, and the last fifty versions 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. +**Desktop.** [ThinkWatch Lite](https://github.com/ThinkWatchProject/ThinkWatch-Lite) +includes `twcore` and updates it with the app; nothing else to download. -### Linux server +**Linux server** (x86_64 or aarch64, glibc 2.35+: Ubuntu 22.04, Debian 12 or +later). One command installs `twcore` as a systemd service with its own user: ```sh curl -fsSL https://raw.githubusercontent.com/ThinkWatchProject/ThinkWatch-Core/main/scripts/install.sh | sudo sh ``` -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). - -### 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 -``` - -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 -``` - -`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). - -## Server deployment - -`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. - -```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: +The script does not start the service. Then, as the service user: ```sh alias twc='sudo -u thinkwatch THINKWATCH_HOME=/var/lib/thinkwatch twcore' @@ -165,120 +83,84 @@ 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 ``` -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 -``` - -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 seventeen crates and the `twcore` binary in `bin/twcore`. -It divides the crates in two: the four 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` · `tw-bedrock` | -| 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` | +In ThinkWatch Lite, **Settings → Connection → Add remote connection** takes the +address, control port and key. The app connects only to the core version it +includes; `sudo twcore upgrade --version --restart` switches the +server to it. Neither port uses TLS, so keep both on trusted networks. +[Running core on a server](docs/server.md) covers secrets, network exposure, +upgrades and uninstalling. -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`), the circuit-breaker state machine -(`tw-breaker`), and what only Amazon Bedrock needs on the wire: SigV4 signing, -eventstream unframing, its addresses and its model catalog (`tw-bedrock`). -These four 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. +**Prebuilt binaries** for macOS (Apple silicon), Windows (x64, ARM64) and Linux +(x86_64, aarch64) are attached to every +[release](https://github.com/ThinkWatchProject/ThinkWatch-Core/releases/latest), +each with a `.sha256` checksum; the Linux `.tar.gz` includes the systemd unit. -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 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. +`twcore` keeps its configuration and data in `~/.thinkwatch` +(`%APPDATA%\ThinkWatch` on Windows), or in `THINKWATCH_HOME`. Every field is in +the [configuration reference](docs/config.md). ## 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; +The control plane is an HTTP API inside an encrypted channel: a unix socket +(a loopback port on Windows), plus the optional remote port. Every connection +starts with a `Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s` handshake keyed by +`listen.control.key`; there are no certificates. curl cannot reach it; `twcore call` can: ``` -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 +twcore control-key --rotate # replace the key; connections made with the old key are closed ``` -The configuration text the control plane returns has the key masked, and a -write through the control plane cannot change it. - -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 # the key on stdout; the address and port on stderr -``` +The remote port admits only sources in `allow_from`, at most 32 connections at +a time, and cannot stop core, take the diagnostic bundle or change +`listen.control`. -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`. +## Crates -## Development +| Crate | Role | +|---|---| +| `tw-dialect` | Conversion between the four API formats; usage parsing | +| `tw-guard` | The five protections: redaction, tool-call inspection, hidden characters, content filter, output limit | +| `tw-breaker` | Circuit-breaker state machine | +| `tw-bedrock` | Amazon Bedrock on the wire: SigV4 signing, eventstream, addresses, model catalog | +| `tw-types` | Messages for people: stable code, arguments, English sentence | +| `tw-engine` | Routing rules and groups | +| `tw-pricing` | Price table, price sheets, measured / estimated / unpriced cost | +| `tw-yaml` | Minimal edits to the original YAML text | +| `tw-secret` | Environment and command-sourced credentials, masking | +| `tw-watch` | Debounced directory watching | +| `tw-api` | Control-plane contract: types and client | +| `tw-link` | Control-channel handshake and encryption | +| `tw-config` | Configuration schema, loading and validation | +| `tw-store` | Request history and runtime state on SQLite | +| `tw-observe` | Event bus | +| `tw-gateway` | Data plane: the life of a request | +| `tw-control` | Control-plane server | + +ThinkWatch Enterprise depends only on the first four, which depend only on one +another; CI checks that Enterprise compiles against every change to them. +ThinkWatch Lite pins `tw-api`, `tw-types`, `tw-yaml`, `tw-guard`, `tw-watch` and +`tw-link` to a release tag and bundles the `twcore` of the same release. Setting +up AI clients and scanning their configuration happen in Lite, on the machine +it runs on; `twcore` issues each client its own gateway key. The binary lives +in `bin/twcore`. + +## Build and test + +Requires a recent stable Rust toolchain (1.94.1 or later). -``` -cargo test --workspace # unit and integration tests -scripts/smoke.sh # run every path on the real binary, from a clean state +```sh +cargo build --release -p twcore # target/release/twcore +cargo run -p twcore -- init # write an initial config.yaml +cargo run -p twcore -- serve # start the gateway and the control plane +cargo test --workspace # unit and integration tests +scripts/smoke.sh # every path on the real binary, in a temporary HOME ``` -`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. +[CONTRIBUTING.md](CONTRIBUTING.md) lists the checks a pull request has to pass +and describes the configuration reference, the price list and releases. ## License diff --git a/README.zh-CN.md b/README.zh-CN.md index 066e9ef9..06d2189f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -10,77 +10,32 @@ **[English](README.md) | [中文](README.zh-CN.md)** -ThinkWatch Core 是一组 Rust crate,以及由它们构建的网关二进制 `twcore`。Claude Code、Codex 以及其他使用 Anthropic、OpenAI、Gemini 接口的客户端经由 `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` 和 `tw-bedrock`。 +ThinkWatch Core 是 ThinkWatch 的网关引擎,由一组 Rust crate 及其构建的 `twcore` 二进制组成。Claude Code、Codex 以及其他使用 Anthropic、OpenAI、Gemini 接口的客户端只需指向 `twcore` 一次;请求发出前可替换其中的凭据,上游返回的工具调用经过审查,每个请求的去向与费用都有记录。`twcore` 既运行在桌面应用 [ThinkWatch Lite](https://github.com/ThinkWatchProject/ThinkWatch-Lite) 中,也可以独立部署在 Linux 服务器上;[ThinkWatch 企业版](https://github.com/ThinkWatchProject/ThinkWatch)建立在其中四个 crate 之上。 文档:[配置手册](docs/config.zh-CN.md) · [在服务器上运行 core](docs/server.zh-CN.md) · [thinkwat.ch/zh-CN/core](https://thinkwat.ch/zh-CN/core/) -## 功能 +## 主要特性 -- **按规则路由**。具名规则可按以下条件匹配:请求的模型(支持通配符)、网关密钥、接口格式、估算的输入 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 标签字符或双向控制符的请求;内容过滤可以拒绝命中关键词或正则规则的请求;输出长度在回答超过设定的字符数时将其切断。在观察档下,防护只记录发现的内容,不改变任何行为。除输出长度出厂为关闭外,其余各项出厂均为观察。内置规则可以逐条停用,也可以添加自定义规则。 -- **请求记录与实时事件**。每个请求连同命中的规则、每次上游尝试、用量、费用、第一个 token 到达的时刻和生成速度保存在本机的 SQLite 数据库中。控制面在请求开始和结束时推送事件;试算可以在不发出请求的情况下说明请求会被路由到哪里及其原因。 -- **单一配置文件**。全部设置保存在 `config.yaml` 中。无论改动来自编辑器、`twcore config` 还是控制面,通过校验后都在一秒内生效;未通过校验的改动被拒绝,原配置继续生效。最近五十个版本都会保留,可以恢复其中任一版本。 +- **一次接入,随时切换**。客户端只保留一个地址和一把密钥,更换上游或模型都在网关中完成,客户端无需改配置或重启。Anthropic Messages、OpenAI Chat Completions、OpenAI Responses 与 Gemini 四种格式双向转换,流式输出同样适用。 +- **出站脱敏**。出站脱敏可在请求发出前把 API 密钥、私钥和连接串中的口令替换为占位符,并在回答回显时还原,中转站因此看不到真实的值。 +- **审查工具调用**。上游返回的工具调用命中危险命令规则时,工具调用审查可以切断回答;另有隐藏字符检测、内容过滤和输出长度,共五项防护。出厂时除输出长度为关闭外均为观察档,切换到拦截档之前不改变任何请求。 +- **每个请求都可追溯**。每个请求连同决定其去向的规则、每次尝试、格式转换、用量、费用及价格来源、首 token 时间和生成速度一并保存。试算可以在不发出请求的情况下说明请求会被送往何处;已保存的请求可以对另一个上游重放,以便对比。 +- **路由与故障转移**。规则可按模型、密钥、格式、请求大小、工具、图片、思考等条件匹配,把请求交给一个上游或策略组(按顺序、手动指定、轮流、最低延迟、最低价格)。响应的首字节到达客户端之前,失败的上游由下一个候选替换,并按其给出的失败原因暂停相应的时间。 +- **多种上游**。服务商的 API 密钥、任意兼容接口、OpenRouter 等中转站、本地模型、Amazon Bedrock,以及 ChatGPT 和 Z.ai 账号。连通性检查和预热请求默认在本地应答,不产生费用。 +- **如实计费**。用量(含缓存读写)按每日刷新的公开价目表或自定义价目表计价。估算的费用会标明,无法计价的用量单独统计,不计作零。 +- **单一配置,即改即生效**。全部设置保存在 `config.yaml` 中;无论改动来自编辑器、命令行还是控制面,通过校验后一秒内生效,最近五十个版本均可恢复。 ## 安装 -### 预编译二进制 - -每个 [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 -``` - -脚本把 `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 -``` - -在源码目录中直接运行: - -```sh -cargo run -p twcore -- init # 生成初始的 config.yaml -cargo run -p twcore -- check # 只校验配置,不启动 -cargo run -p twcore -- serve # 启动网关和控制面 -``` - -`twcore` 的配置和数据存放在 `~/.thinkwatch`(Windows 上为 `%APPDATA%\ThinkWatch`),设置了 `THINKWATCH_HOME` 时存放在它指定的目录。`config.yaml` 的每个字段见[配置手册](docs/config.zh-CN.md)。 +**桌面**。[ThinkWatch Lite](https://github.com/ThinkWatchProject/ThinkWatch-Lite) 自带 `twcore`,并随应用一同更新,无需另行下载。 -## 服务器部署 - -twcore 可以作为 systemd 服务运行在 Linux(x86_64、aarch64)上。一条命令即可安装二进制、专用用户和服务单元;各平台的 ThinkWatch Lite 通过远程控制端口连接它。 +**Linux 服务器**(x86_64 或 aarch64,glibc 2.35 及以上:Ubuntu 22.04、Debian 12 或更新)。一条命令即可把 `twcore` 安装为使用专用用户的 systemd 服务: ```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' @@ -91,67 +46,61 @@ sudo systemctl enable --now twcore # 立即启动服务,并随系统 twc control-key # 标准输出是 ThinkWatch Lite 所需的密钥,地址和端口在标准错误 ``` -要让其他机器上的客户端使用网关,在 `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 并重启服务 -``` - -两个端口都不使用 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-bedrock` | -| 领域逻辑 | `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`),以及只有 Amazon Bedrock 需要的线上处理:SigV4 签名、eventstream 拆帧、地址与模型目录(`tw-bedrock`)。这四个 crate 只相互依赖,由测试保证;CI 会针对它们的每一次改动检查 ThinkWatch 企业版能否编译。只有一方使用的组件放在那一方的仓库中。 +在 ThinkWatch Lite 中打开 **设置 → 连接 → 添加远程连接**,填写地址、控制端口和密钥。应用只连接与其内置版本相同的 core,`sudo twcore upgrade --version <版本> --restart` 可以把服务器切换到该版本。两个端口都不使用 TLS,只应对可信网络开放。密钥的存放、网络暴露、升级与卸载见[在服务器上运行 core](docs/server.zh-CN.md)。 -ThinkWatch Lite 把 `tw-api`、`tw-types`、`tw-yaml`、`tw-guard`、`tw-watch` 和 `tw-link` 固定在某个 Release 的 tag 上,并打包同一 Release 的 `twcore`。接管 AI 客户端(把其配置指向网关)、编辑其 MCP 服务器和扫描其配置文件都在 ThinkWatch Lite 中完成:这些操作修改的是应用所在机器上的文件,而这台机器不一定运行着 `twcore`。`twcore` 只负责为每个客户端签发专用的网关密钥。 +**预编译二进制**:每个 [Release](https://github.com/ThinkWatchProject/ThinkWatch-Core/releases/latest) 都提供 macOS(Apple silicon)、Windows(x64、ARM64)和 Linux(x86_64、aarch64)版本,均附 `.sha256` 校验文件;Linux 的 `.tar.gz` 包含 systemd 服务单元。 -最后两组实现的是单个 `twcore` 进程:请求记录保存在 SQLite 中,配置保存在一个 YAML 文件中,控制面经本机通道或远程控制端口访问。这两组有意不共用:ThinkWatch 企业版是多租户的,其状态保存在 PostgreSQL、Redis 和 ClickHouse 中,两种设计差异很大,用一个抽象同时覆盖两者,对双方都不合适。 +`twcore` 的配置和数据存放在 `~/.thinkwatch`(Windows 上为 `%APPDATA%\ThinkWatch`),设置了 `THINKWATCH_HOME` 时存放在它指定的目录。每个字段的说明见[配置手册](docs/config.zh-CN.md)。 ## 控制面 -控制面是运行在加密通道内的 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`: +控制面是运行在加密通道内的 HTTP 接口,经 unix socket(Windows 上为回环端口)以及可选的远程端口访问。每条连接都以 `Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s` 握手开始,密钥为 `listen.control.key`,不涉及证书。curl 无法访问控制面,需使用 `twcore call`: ``` -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 +twcore control-key --rotate # 更换密钥;用旧密钥建立的连接随即断开 ``` -控制面返回的配置原文中,密钥经过打码;经控制面的写入也无法修改它。 +远程端口只接受 `allow_from` 中的来源,最多同时保持 32 条连接,且不能停止 core、生成诊断包或修改 `listen.control`。 -远程控制端口在本机通道之外另行开放,使用同一把密钥和同一个握手: - -``` -twcore remote enable --allow 192.168.1.0/24 # 端口在第一次开启时随机选取 -twcore remote disable -twcore control-key # 标准输出是密钥,地址和端口在标准错误 -``` +## crate 一览 -来自 `allow_from` 之外的连接直接关闭,不回复任何字节;服务器本机的回环地址不会自动放行。同一来源一分钟内握手失败五次后,接下来一分钟内的连接一律忽略;远程连接最多同时存在 32 条。远程连接不能停止 core、不能生成诊断包,也不能修改 `listen.control`。 - -## 开发 +| crate | 职责 | +|---|---| +| `tw-dialect` | 四种接口格式之间的转换,用量解析 | +| `tw-guard` | 五项防护:出站脱敏、工具调用审查、隐藏字符、内容过滤、输出长度 | +| `tw-breaker` | 熔断状态机 | +| `tw-bedrock` | Amazon Bedrock 的线上处理:SigV4 签名、eventstream、地址、模型目录 | +| `tw-types` | 给人看的消息:稳定的消息码、参数与英文句子 | +| `tw-engine` | 路由规则与策略组 | +| `tw-pricing` | 公开价目表、自定义价目表,实测/估算/无法计价三种费用 | +| `tw-yaml` | 在 YAML 原文上做最小改动 | +| `tw-secret` | 从环境变量或命令取得凭据,以及打码 | +| `tw-watch` | 带防抖的目录监视 | +| `tw-api` | 控制面契约:类型与客户端 | +| `tw-link` | 控制通道的握手与加密 | +| `tw-config` | 配置的结构、加载与校验 | +| `tw-store` | 基于 SQLite 的请求记录与运行时状态 | +| `tw-observe` | 事件总线 | +| `tw-gateway` | 数据面:一个请求的完整生命周期 | +| `tw-control` | 控制面服务 | + +ThinkWatch 企业版只依赖前四个 crate,这四个 crate 也只相互依赖;CI 会针对它们的每一次改动检查企业版能否编译。ThinkWatch Lite 把 `tw-api`、`tw-types`、`tw-yaml`、`tw-guard`、`tw-watch` 和 `tw-link` 固定在某个 Release 的 tag 上,并打包同一 Release 的 `twcore`。接管 AI 客户端和扫描其配置在 Lite 中完成,作用于应用所在的机器;`twcore` 只为每个客户端签发专用的网关密钥。二进制的源码位于 `bin/twcore`。 + +## 构建与测试 + +需要较新的 Rust 稳定版工具链(1.94.1 或更新)。 -``` -cargo test --workspace # 单元测试与集成测试 -scripts/smoke.sh # 从空白状态起,用真实的二进制把每条路径运行一遍 +```sh +cargo build --release -p twcore # 生成 target/release/twcore +cargo run -p twcore -- init # 生成初始的 config.yaml +cargo run -p twcore -- serve # 启动网关和控制面 +cargo test --workspace # 单元测试与集成测试 +scripts/smoke.sh # 在临时 HOME 中用真实的二进制把每条路径运行一遍 ``` -`scripts/smoke.sh` 不会改动用户自己的配置:`HOME` 和 `THINKWATCH_HOME` 都指向一个临时目录,运行结束后删除。提交 PR 前须通过的检查,以及配置手册、价目表和发版流程的说明,见 [CONTRIBUTING.md](CONTRIBUTING.md)。 +提交 PR 前须通过的检查,以及配置手册、价目表和发版流程的说明,见 [CONTRIBUTING.md](CONTRIBUTING.md)。 ## 许可证