mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
feat(admin): add bulk proxy management and opt-in anonymous access
This commit is contained in:
1 parent
159d7fdf0f
commit
0d05fe9393
17 files changed
+872
-48
No files matched your search
+1
-1
@@ -53,7 +53,7 @@ go build -o opencode2api ./cmd/opencode2api
|
||||
Prima di avviare il servizio, modifica `config.json`:
|
||||
|
||||
1. Sostituisci `server_keys` con una tua API key locale.
|
||||
2. Configura le chiavi Zen o Go. In alternativa, imposta `anonymous: true` e lascia vuoti entrambi gli array delle chiavi upstream.
|
||||
2. Prima dell'avvio, inserisci una Zen API Key (consigliata) in `zen_keys` oppure una chiave Go in `go_keys`. L'esempio disabilita l'accesso anonimo (`anonymous: false`) e lascia vuoti entrambi gli array; anche una connessione Go in abbonamento già salvata soddisfa il requisito. Il canale anonimo potrebbe essere fortemente bloccato a monte: preferisci una Zen API Key.
|
||||
3. Sostituisci `webui.password`. La configurazione di esempio abilita la WebUI con l'utente `admin`.
|
||||
|
||||
```bash
|
||||
|
||||
@@ -11,7 +11,7 @@ The executable includes the WebUI. Running the service requires no Node.js runti
|
||||
- JSON and SSE responses across all three inference protocols.
|
||||
- Text, images, reasoning, function tools, tool calls, and tool results; file content where the target protocol can represent it.
|
||||
- Separate Zen and Go key pools, configurable tier preference, retries, and session affinity.
|
||||
- Optional anonymous Zen access with the OpenCode `public` credential.
|
||||
- Opt-in anonymous Zen access with the OpenCode `public` credential; disabled by default because upstream blocking can make it unavailable.
|
||||
- Optional userspace Cloudflare WARP egress for free-model traffic, without TUN or root.
|
||||
- Direct, HTTP, HTTPS, SOCKS5, and SOCKS5H connections, including a proxy file.
|
||||
- Dynamic model discovery, native protocol metadata, and disk caches.
|
||||
@@ -53,9 +53,11 @@ go build -o opencode2api ./cmd/opencode2api
|
||||
Before starting, edit `config.json`:
|
||||
|
||||
1. Replace `server_keys` with your own local API key.
|
||||
2. Optionally supply Zen or Go keys. The example enables the anonymous free lane and leaves both upstream key arrays empty.
|
||||
2. Supply a Zen API Key in `zen_keys` (recommended), or a Go key in `go_keys`. The example leaves both arrays empty and disables anonymous access, so configure an upstream credential before starting. An existing Go subscription connection also satisfies this requirement.
|
||||
3. Replace `webui.password`. The example enables the WebUI with username `admin`.
|
||||
|
||||
**Anonymous traffic may be heavily blocked upstream. Prefer a Zen API Key.** Anonymous access is off by default in the configuration and WebUI; existing configurations that explicitly set `anonymous: true` keep that choice. Enable it deliberately only if you accept that free requests may still fail.
|
||||
|
||||
```bash
|
||||
./opencode2api -config config.json
|
||||
```
|
||||
@@ -223,6 +225,8 @@ Each `/v1/models` entry also carries `cost` (USD per million tokens: `input`, `o
|
||||
|
||||
### Anonymous access and fallback
|
||||
|
||||
**Anonymous traffic may be heavily blocked upstream. Prefer a Zen API Key.** The built-in default and example configuration set `anonymous: false`; the WebUI does not opt you in automatically or change an existing explicit `true` value.
|
||||
|
||||
With `anonymous: true`, either condition makes a model eligible for the anonymous Zen lane:
|
||||
|
||||
- Its ID contains `free`, case-insensitively.
|
||||
@@ -248,7 +252,7 @@ Known OpenCode title requests are identified before prompt and message shaping,
|
||||
|
||||
When only anonymous access is configured, `/v1/models` exposes only models eligible for that lane.
|
||||
|
||||
Free models never need a Zen key: with `anonymous: true` they are served by the public lane, and a configured key is only their fallback. To keep keys but expose free models only, set `models.free_only: true`. Paid models then disappear from `/v1/models`, direct requests for them are rejected, and rotation aliases keep only free members; free models may still fall back to the configured keys.
|
||||
An eligible free model can be attempted without a Zen key only when anonymous access is explicitly enabled; eligibility does not guarantee upstream access. To keep authenticated keys but expose free models only, set `models.free_only: true`. Paid models then disappear from `/v1/models`, direct requests for them are rejected, and rotation aliases keep only free members; free models use the configured keys when anonymous access is off, or may fall back to them when it is on.
|
||||
|
||||
### WARP egress for free models
|
||||
|
||||
@@ -319,7 +323,7 @@ Cooldowns grow exponentially up to eight times `performance.failure_cooldown_sec
|
||||
|
||||
## Configuration reference
|
||||
|
||||
See [config.example.json](config.example.json) for a complete starting configuration. JSON supports `//` and `/* ... */` comments; unknown fields and invalid values are rejected.
|
||||
See [config.example.json](config.example.json) for a starting configuration; add an upstream credential before starting. The configuration-file loader supports `//` and `/* ... */` comments, which are not part of standard JSON; management API bodies must be standard JSON. Unknown fields, including `_comment`, and invalid values are rejected.
|
||||
|
||||
### Keys, listeners, and routing
|
||||
|
||||
@@ -327,8 +331,8 @@ See [config.example.json](config.example.json) for a complete starting configura
|
||||
| --------------------------- | --------------------------------------------------------------------------- |
|
||||
| `listen` | `127.0.0.1:8080`. |
|
||||
| `server_keys` | At least one local key is required. |
|
||||
| `zen_keys`, `go_keys` | At least one upstream key is required unless anonymous access is enabled. |
|
||||
| `anonymous` | `false`. |
|
||||
| `zen_keys`, `go_keys` | At least one upstream key or saved `go_subscription` connection is required unless anonymous access is explicitly enabled. |
|
||||
| `anonymous` | `false`; opt-in only. Upstream blocking may make this lane unavailable; prefer a Zen API Key. |
|
||||
| `warp.enabled` | `false`; free-lane traffic leaves through Cloudflare WARP and no proxy. |
|
||||
| `warp.pool_size` | `2`; upper bound on WARP exits (half pre-registered in the background; the active ring follows concurrency), 1–32. |
|
||||
| `warp.stack` | `ipv6`; `ipv6`, `ipv4`, or `dual`. |
|
||||
@@ -465,6 +469,7 @@ The management listener serves the UI and `/api/*` routes. Authentication uses o
|
||||
| `GET /api/monitor` | Request, token, upstream, and resource statistics. |
|
||||
| `GET /api/debug/models` | Model routes, key fingerprints, and metadata diagnostics. |
|
||||
| `POST /api/debug/inference` | Run a Playground request. |
|
||||
| `POST /api/proxies/check` | Check one saved or draft proxy's connectivity to the configured Zen upstream. |
|
||||
| `GET /api/logs`, `GET /api/logs/stream` | Recent logs or a live SSE subscription. |
|
||||
|
||||
Playground requests require a session and `X-CSRF-Token` and are limited to 12 per minute per client IP:
|
||||
@@ -486,6 +491,34 @@ The server forces `stream: false`. Use `{"mode":"selected","tier":"zen","id":"KE
|
||||
|
||||
After execution, the management endpoint returns HTTP 200 with the actual result in `ok`, `http_status`, `request_id`, `route`, and `response`. Selected-key results also include `selected_key` and `key_test`: `usable`, `rejected`, `rate_limited`, `transport_error`, `upstream_error`, `request_error`, or `unavailable`. Invalid management input, authentication, CSRF, and throttling retain their own HTTP error statuses.
|
||||
|
||||
### Bulk proxy management
|
||||
|
||||
The WebUI can import multiple inline proxies, check selected entries, and stage selected entries for removal. Checks call `POST /api/proxies/check` once per proxy, with a login session, `X-CSRF-Token`, and exactly one of these standard JSON bodies:
|
||||
|
||||
```json
|
||||
{"id":"SAVED_PROXY_ID"}
|
||||
```
|
||||
|
||||
```json
|
||||
{"value":"https://proxy.example:8443"}
|
||||
```
|
||||
|
||||
Use the masked entry ID from `GET /api/config` for an existing proxy, or `value` for an unsaved draft. Results return HTTP 200 with `ok`, `state`, and `reason`; `latency_ms` and upstream `status` may also be present. Invalid management requests, authentication, CSRF, and concurrency limits use their own HTTP error statuses. Each check has a 20-second timeout. The WebUI runs at most four checks concurrently; the server accepts at most eight and rejects excess checks without queuing.
|
||||
|
||||
**This checks only proxy-to-Zen connectivity, not inference, key validity, or quota.** It sends an unauthenticated `GET` to the configured `upstream.zen` URL plus `/v1/models` through an isolated Bun client using only the selected proxy. No Zen/Go key, anonymous `public` credential, or OAuth token is sent, no inference is performed, redirects are not followed, and WARP is not used. It works with `anonymous: false` without enabling anonymous access.
|
||||
|
||||
| `state` | Meaning / cleanup guidance |
|
||||
| ------- | -------------------------- |
|
||||
| `available` | The upstream responded with HTTP 200–399 or 401. A 401 means the endpoint was reached but requires authentication (`authentication_required`), not that a key was validated. |
|
||||
| `unavailable` | A confirmed proxy-side connection refusal or DNS failure (`proxy_unreachable`), or proxy CONNECT HTTP 407 (`proxy_authentication_required`); eligible for unavailable-only selection for this check, not proof of permanent failure. |
|
||||
| `limited` | The upstream returned 429; this is not evidence that the proxy is broken. |
|
||||
| `rejected` | The upstream responded with 403 or another error status, excluding 401 and 429 (`upstream_responded`), or the proxy rejected the tunnel (`proxy_tunnel_rejected`); this is not evidence that the proxy is broken. An origin HTTP 407 is not classified as proxy authentication failure. |
|
||||
| `inconclusive` | A timeout, other transport failure, or unavailable check prerequisite; do not treat this as a confirmed broken proxy. |
|
||||
|
||||
Checks do not change production proxy health, key cooldowns, or bindings. A result describes this connection attempt, not permanent proxy health; upstream rejection, rate limiting, and timeouts must not be selected for cleanup as confirmed proxy failures.
|
||||
|
||||
Removal is staged in the WebUI and takes effect only after saving the full configuration through `PUT /api/config`; checking does not delete anything. Proxies supplied by `proxyfile` are managed in that source file, not in the inline-proxy table.
|
||||
|
||||
### Go subscription sign-in
|
||||
|
||||
In **Models & Quota** (`/#model-quotas`), select **Sign in to Go in your browser**, open the displayed official OpenCode Device OAuth link, and enter the displayed `user_code`. Authorize the request you initiated; the WebUI schedules backend polling to complete sign-in. No token pasting, local credential-file import, or callback URL submission is required. If the account has multiple organizations, select the organization with the Go subscription in the WebUI.
|
||||
|
||||
+2
-2
@@ -55,7 +55,7 @@ go build -o opencode2api ./cmd/opencode2api
|
||||
Trước khi khởi động, hãy sửa `config.json`:
|
||||
|
||||
1. Thay `server_keys` bằng API key cục bộ của bạn.
|
||||
2. Tùy chọn: thêm key Zen hoặc Go; ví dụ đã bật làn ẩn danh và để trống cả hai mảng key thượng nguồn.
|
||||
2. Điền Zen API Key (khuyến nghị) vào `zen_keys` hoặc Go key vào `go_keys` trước khi khởi động. Cấu hình mẫu tắt truy cập ẩn danh (`anonymous: false`) và để trống cả hai mảng key; một kết nối thuê bao Go đã lưu cũng đáp ứng yêu cầu này. Làn ẩn danh có thể bị chặn mạnh ở thượng nguồn, nên ưu tiên Zen API Key.
|
||||
3. Thay `webui.password`. File mẫu bật WebUI với tài khoản `admin`.
|
||||
|
||||
```bash
|
||||
@@ -573,4 +573,4 @@ Các quan sát được lưu theo URL upstream, mô hình và giao thức gốc,
|
||||
|
||||
SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
Dự án này là phần mềm tự do: bạn có thể phân phối lại và sửa đổi theo Giấy phép Công cộng GNU phiên bản 3 do Free Software Foundation công bố, hoặc phiên bản 3 hoặc mới hơn (tuỳ chọn của bạn). Phần mềm được cung cấp nguyên trạng, không kèm bảo đảm. Xem [LICENSE](LICENSE) để biết đầy đủ điều khoản.
|
||||
Dự án này là phần mềm tự do: bạn có thể phân phối lại và sửa đổi theo Giấy phép Công cộng GNU phiên bản 3 do Free Software Foundation công bố, hoặc phiên bản 3 hoặc mới hơn (tuỳ chọn của bạn). Phần mềm được cung cấp nguyên trạng, không kèm bảo đảm. Xem [LICENSE](LICENSE) để biết đầy đủ điều khoản.
|
||||
+23
-8
@@ -11,7 +11,7 @@ WebUI 内嵌在可执行文件中,运行服务无需 Node.js 或数据库。
|
||||
- 三种推理协议之间的普通 JSON 响应与 SSE 流式转换。
|
||||
- 文本、图片、reasoning、函数工具、工具调用和工具结果;目标协议允许时支持文件内容转换。
|
||||
- 独立的 Zen / Go Key 池,可配置优先级、重试和会话亲和性。
|
||||
- 使用 OpenCode `public` 凭证的可选 Zen 匿名通道。
|
||||
- 使用 OpenCode `public` 凭证的可选 Zen 匿名通道,默认关闭,上游封堵可能使其不可用。
|
||||
- 可选的用户态 Cloudflare WARP 出口,免费模型流量无需 TUN 或 root 权限。
|
||||
- 直连、HTTP、HTTPS、SOCKS5、SOCKS5H 连接,以及代理文件。
|
||||
- 动态模型发现、原生协议与能力信息、磁盘缓存。
|
||||
@@ -53,9 +53,11 @@ go build -o opencode2api ./cmd/opencode2api
|
||||
启动前编辑 `config.json`:
|
||||
|
||||
1. 将 `server_keys` 替换为自己的本地 API Key。
|
||||
2. 可选:填入 Zen 或 Go Key;示例已启用匿名通道,并清空两个上游 Key 数组。
|
||||
2. 在 `zen_keys` 填入 Zen API Key(推荐),或在 `go_keys` 填入 Go Key。示例关闭匿名通道,且两个上游 Key 数组为空,必须先配置上游凭证才能启动;已有的 Go 订阅连接也满足此要求。
|
||||
3. 替换 `webui.password`。示例配置启用了 WebUI,用户名为 `admin`。
|
||||
|
||||
**匿名通道可能已被上游重点封堵,优先使用 Zen API Key。** 配置与 WebUI 默认关闭匿名访问;已有配置中明确设置的 `anonymous: true` 不会被自动改为关闭。只有接受免费请求仍可能失败时,才主动开启。
|
||||
|
||||
```bash
|
||||
./opencode2api -config config.json
|
||||
```
|
||||
@@ -223,6 +225,8 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答
|
||||
|
||||
### 匿名通道与回退
|
||||
|
||||
**匿名通道可能已被上游重点封堵,优先使用 Zen API Key。** 内置默认值与示例均为 `anonymous: false`,WebUI 不自动启用匿名通道,也不修改已有配置中明确设置的 `true`。
|
||||
|
||||
启用 `anonymous: true` 后,满足以下任一条件的模型可以进入 Zen 匿名通道:
|
||||
|
||||
- 模型 ID 包含 `free`,不区分大小写。
|
||||
@@ -232,7 +236,7 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答
|
||||
|
||||
路由顺序:
|
||||
|
||||
1. 符合条件的模型最多尝试 `performance.max_anonymous_exits` 个可用匿名代理,每个代理一次;每个代理先走 v2 `/inference`,再走 v1 `/zen`。
|
||||
1. 符合条件的模型最多尝试 `performance.max_anonymous_exits` 个可用匿名代理,每个代理一次;仅使用 v2 `/inference`,免费模型的 v1 `/zen` 回退已停用。
|
||||
2. 按 `prefer` 顺序尝试认证通道,仅包含已配置 Key 且可以提供该模型的 Tier。
|
||||
3. 每个认证 Tier 分别使用 `retry.max_attempts` 预算。
|
||||
|
||||
@@ -248,7 +252,7 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答
|
||||
|
||||
只有匿名通道可用时,`/v1/models` 仅展示符合匿名条件的模型。
|
||||
|
||||
免费模型不需要 Zen Key:启用 `anonymous: true` 后由匿名通道提供,已配置的 Key 只作为回退。如果想保留 Key 但只暴露免费模型,设置 `models.free_only: true`:付费模型不再出现在 `/v1/models`,直接请求会被拒绝,轮转别名只保留免费成员;免费模型仍可回退到已配置的 Key。
|
||||
只有明确启用匿名通道后,符合条件的免费模型才可尝试不使用 Zen Key,但这不保证上游允许访问。如果想保留认证 Key 但只暴露免费模型,设置 `models.free_only: true`:付费模型不再出现在 `/v1/models`,直接请求会被拒绝,轮转别名只保留免费成员;匿名关闭时免费模型使用已配置的 Key,开启时也可回退到这些 Key。
|
||||
|
||||
### 免费模型 WARP 出口
|
||||
|
||||
@@ -319,7 +323,7 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K
|
||||
|
||||
## 配置参考
|
||||
|
||||
完整起始配置见 [config.example.json](config.example.json)。配置支持 `//` 和 `/* ... */` 注释,未知字段和无效取值会被拒绝。
|
||||
起始配置见 [config.example.json](config.example.json),启动前须添加上游凭证。配置文件读取器支持非标准 JSON 的 `//` 和 `/* ... */` 注释;管理接口请求体仍须使用标准 JSON。未知字段(包括 `_comment`)和无效取值会被拒绝。
|
||||
|
||||
### Key、监听地址与路由
|
||||
|
||||
@@ -327,8 +331,8 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K
|
||||
| --------------------------- | ------------------------------------------------------------------------------------- |
|
||||
| `listen` | `127.0.0.1:8080`。 |
|
||||
| `server_keys` | 至少一个本地 Key。 |
|
||||
| `zen_keys`、`go_keys` | 未启用匿名模式时,至少需要一个上游 Key。 |
|
||||
| `anonymous` | `false`。 |
|
||||
| `zen_keys`、`go_keys` | 未明确启用匿名模式时,至少需要一个上游 Key 或已有的 `go_subscription` 连接。 |
|
||||
| `anonymous` | `false`;须主动开启,上游封堵可能使其不可用,优先使用 Zen API Key。 |
|
||||
| `warp.enabled` | `false`;免费通道流量通过 Cloudflare WARP 出口,不使用代理。 |
|
||||
| `warp.pool_size` | `2`;WARP 出口上限(后台预注册一半,活跃出口按并发调整),1–32。 |
|
||||
| `warp.stack` | `ipv6`;可选 `ipv6`、`ipv4`、`dual`。 |
|
||||
@@ -336,7 +340,7 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K
|
||||
| `prefer` | `go`;可选 `go`、`zen`。 |
|
||||
| `upstream.zen` | `https://opencode.ai/zen`。 |
|
||||
| `upstream.go` | `https://opencode.ai/zen/go`。 |
|
||||
| `upstream.anonymous` | `https://opencode.ai/inference`;匿名通道优先使用,失败后回退到 `/zen`。 |
|
||||
| `upstream.anonymous` | `https://opencode.ai/inference`;匿名通道仅使用此地址,已停用 v1 `/zen` 回退。 |
|
||||
| `proxies` | 两个代理来源都为空时,使用 `["direct"]`。 |
|
||||
| `proxyfile` | 可选;相对路径基于配置文件所在目录解析。 |
|
||||
| `models.refresh_seconds` | `300`;最小为 1。 |
|
||||
@@ -459,6 +463,7 @@ pool+http://127.0.0.1:7891
|
||||
| `GET /api/monitor` | 请求、Token、上游和资源统计。 |
|
||||
| `GET /api/debug/models` | 模型路由、Key 指纹和 metadata 诊断。 |
|
||||
| `POST /api/debug/inference` | 执行 Playground 请求。 |
|
||||
| `POST /api/proxies/check` | 检查一个已保存或草稿代理到 Zen 上游的连通性。 |
|
||||
| `GET /api/logs`、`GET /api/logs/stream` | 最近日志或 SSE 实时订阅。 |
|
||||
|
||||
Playground 需要已登录的 Session 和 `X-CSRF-Token`,每个客户端 IP 每分钟最多 12 次:
|
||||
@@ -480,6 +485,16 @@ Playground 需要已登录的 Session 和 `X-CSRF-Token`,每个客户端 IP
|
||||
|
||||
执行后,管理接口返回 HTTP 200,实际结果位于 `ok`、`http_status`、`request_id`、`route` 和 `response`。指定 Key 时还返回 `selected_key` 与 `key_test`,其值包括 `usable`、`rejected`、`rate_limited`、`transport_error`、`upstream_error`、`request_error`、`unavailable`。管理请求格式、认证、CSRF 和限速错误仍返回各自对应的 HTTP 状态。
|
||||
|
||||
### 批量代理管理
|
||||
|
||||
WebUI 支持批量导入内联代理、检查选中条目和暂存批量移除。检查逐条调用 `POST /api/proxies/check`,需要管理登录和 `X-CSRF-Token`;请求体二选一:`{"id":"SAVED_PROXY_ID"}`(`GET /api/config` 返回的已保存代理 ID)或 `{"value":"https://proxy.example:8443"}`(草稿地址)。前端最多四个并发,后端最多八个,超出立即拒绝、不排队;每次检查限时 20 秒。
|
||||
|
||||
**仅检查代理到 Zen 的连通性,不验证推理、Key 或额度。** 请求通过指定代理的独立 Bun 客户端向配置的 `upstream.zen` 加 `/v1/models` 发送无认证 GET,不带 Zen/Go Key、`public` 或 OAuth 凭证,不发推理、不跟随重定向、不走 WARP,也不修改正式健康、冷却或绑定状态。`anonymous: false` 时仍可检查,不会擅自启用匿名推理。
|
||||
|
||||
成功执行检查后返回 HTTP 200,结果包含 `ok`、`state`、`reason`,以及可用时的 `status`、`latency_ms`。`available` 表示上游返回 200–399 或 401(401 仅表示到站后需要认证);`unavailable` 仅限本次确认的代理端拒绝连接、DNS 失败或代理 407;429 为 `limited`,上游 403 等错误为 `rejected`,超时及其他不能定位的错误为 `inconclusive`。后三种状态不得当作确认损坏代理批量清理;本次不可用也不代表永久故障。
|
||||
|
||||
移除只暂存在页面中,仍须通过 `PUT /api/config` 保存完整配置后才生效,检查本身不会删除代理。`proxyfile` 提供的代理在来源文件管理,不加入内联代理表格。
|
||||
|
||||
### Go 订阅登录
|
||||
|
||||
在「模型与额度」页面(`/#model-quotas`)点击「浏览器登录 Go 订阅」,打开页面显示的 OpenCode 官方 Device OAuth 链接,输入显示的 `user_code`。确认这是自己发起的授权后完成登录;WebUI 按间隔请求后端轮询并完成授权交换,无需手贴 Token、导入本机凭证文件或提交回调 URL。账号关联多个组织时,在 WebUI 选择 Go 订阅所在的组织。
|
||||
|
||||
+2
-1
@@ -3,7 +3,8 @@
|
||||
"server_keys": ["change-this-local-key"],
|
||||
"zen_keys": [],
|
||||
"go_keys": [],
|
||||
"anonymous": true,
|
||||
// Anonymous traffic may be heavily blocked upstream. Prefer a Zen API Key.
|
||||
"anonymous": false,
|
||||
"warp": {
|
||||
"enabled": false,
|
||||
"pool_size": 2,
|
||||
|
||||
@@ -1,6 +1,38 @@
|
||||
# 管理控制台:模型轮转、Go 额度与 API Key
|
||||
# 管理控制台:模型轮转、Go 额度、API Key 与代理
|
||||
|
||||
本文说明三个新增管理页面的使用方式、配置和错误处理。
|
||||
本文说明管理页面的使用方式、配置和错误处理。
|
||||
|
||||
## 匿名通道默认关闭
|
||||
|
||||
**匿名通道可能已被上游重点封堵,优先使用 Zen API Key。** 配置和 WebUI 默认 `anonymous: false`;已有配置中明确设置的 `true` 保持不变,不会被自动关闭。示例的上游 Key 数组为空,启动前应先填入 Zen API Key(推荐)或 Go Key;已有的 Go 订阅连接也可满足上游凭证要求。不要为了检查代理而开启匿名推理。
|
||||
|
||||
## 批量代理管理
|
||||
|
||||
「Proxy 节点」页可批量导入内联代理、检查选中条目和暂存批量移除。代理文件 `proxyfile` 的条目在来源文件管理,不加入内联代理表格。移除不会立即修改运行时,仍需保存完整配置(`PUT /api/config`);检查本身不删除任何条目。
|
||||
|
||||
检查接口为 `POST /api/proxies/check`,需要管理 Session 与 `X-CSRF-Token`,请求体二选一:
|
||||
|
||||
```json
|
||||
{"id":"SAVED_PROXY_ID"}
|
||||
```
|
||||
|
||||
```json
|
||||
{"value":"https://proxy.example:8443"}
|
||||
```
|
||||
|
||||
`id` 使用 `GET /api/config` 返回的已保存代理 ID;`value` 用于草稿地址。前端最多四个并发,服务端最多八个,超出立即拒绝、不排队;单次检查限时 20 秒。检查正常执行时返回 HTTP 200,包含 `ok`、`state`、`reason` 及可用时的 `status`、`latency_ms`;请求格式、认证、CSRF 和并发限制错误使用各自的 HTTP 错误状态。
|
||||
|
||||
**只检查代理到配置的 Zen 上游的连通性,不验证推理、Key 或额度。** 独立 Bun 客户端仅通过选中代理向 `upstream.zen` 加 `/v1/models` 发送无认证 GET,不带任何 Zen/Go Key、`public` 或 OAuth 凭证,不发推理、不跟随重定向、不走 WARP,也不改变正式代理健康、Key 冷却或绑定。匿名关闭时仍可检查,不会私自启用匿名推理。
|
||||
|
||||
| `state` | 含义与清理建议 |
|
||||
| ------- | -------------- |
|
||||
| `available` | 上游返回 200–399 或 401。401 的 `authentication_required` 表示已到站、需要认证,不代表验证了 Key。 |
|
||||
| `unavailable` | 仅本次可确认的代理端拒绝连接、DNS 失败(`proxy_unreachable`)或代理 407(`proxy_authentication_required`),可加入不可用筛选,不代表永久故障。 |
|
||||
| `limited` | 上游返回 429,不等于代理损坏。 |
|
||||
| `rejected` | 上游返回 403 等错误,不等于代理损坏。 |
|
||||
| `inconclusive` | 超时、其他不能定位的传输错误或检查前提不满足,不能确认代理损坏。 |
|
||||
|
||||
只允许将 `unavailable` 作为本次确认不可用的清理筛选;不要把 `limited`、`rejected` 或 `inconclusive` 一并选为损坏代理。正式推理仍可能因模型、凭证、额度或上游策略失败。
|
||||
|
||||
## 模型与额度
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"opencode2api/internal/config"
|
||||
"opencode2api/internal/httpx"
|
||||
)
|
||||
|
||||
func (a *Server) handleCheckProxy(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
var input SecretInput
|
||||
if err := decodeAdminJSON(w, r, &input); err != nil {
|
||||
writeAdminError(w, http.StatusBadRequest, "invalid_request", "provide exactly one proxy id or value")
|
||||
return
|
||||
}
|
||||
input.ID = strings.TrimSpace(input.ID)
|
||||
input.Value = strings.TrimSpace(input.Value)
|
||||
if (input.ID == "") == (input.Value == "") || len(input.Value) > 16<<10 {
|
||||
writeAdminError(w, http.StatusBadRequest, "invalid_proxy", "provide exactly one proxy id or value of at most 16 KiB")
|
||||
return
|
||||
}
|
||||
value := input.Value
|
||||
if input.ID != "" {
|
||||
for _, existing := range a.manager.Config().Proxies {
|
||||
if config.Fingerprint(existing) == input.ID {
|
||||
value = existing
|
||||
break
|
||||
}
|
||||
}
|
||||
if value == "" {
|
||||
writeAdminError(w, http.StatusBadRequest, "unknown_proxy_id", "proxy id is unknown or stale; reload the configuration")
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := config.ValidateProxyEntry(value); err != nil {
|
||||
writeAdminError(w, http.StatusBadRequest, "invalid_proxy", "proxy must be direct or an HTTP, HTTPS, SOCKS5 or SOCKS5H URL")
|
||||
return
|
||||
}
|
||||
select {
|
||||
case a.proxyChecks <- struct{}{}:
|
||||
defer func() { <-a.proxyChecks }()
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
default:
|
||||
w.Header().Set("Retry-After", "1")
|
||||
writeAdminError(w, http.StatusTooManyRequests, "proxy_checks_busy", "too many proxy checks; retry shortly")
|
||||
return
|
||||
}
|
||||
httpx.WriteJSON(w, http.StatusOK, a.manager.CheckProxy(r.Context(), value))
|
||||
}
|
||||
@@ -41,6 +41,7 @@ type Server struct {
|
||||
goAuthMu sync.Mutex
|
||||
goAuth map[string]*goAuthAttempt
|
||||
goAuthClient *goauth.Client
|
||||
proxyChecks chan struct{}
|
||||
}
|
||||
|
||||
// New returns a Server for manager, reporting to monitor and logs.
|
||||
@@ -49,6 +50,7 @@ func New(manager *gateway.RuntimeController, monitor *telemetry.Metrics, logs *t
|
||||
manager: manager, monitor: monitor, logs: logs, logger: logger, sessions: make(map[string]adminSession),
|
||||
attempts: make(map[string]loginWindow), debugAttempts: make(map[string]loginWindow),
|
||||
goAuth: make(map[string]*goAuthAttempt), goAuthClient: goauth.NewClient(nil),
|
||||
proxyChecks: make(chan struct{}, 8),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +68,7 @@ func (a *Server) Handler() http.Handler {
|
||||
mux.Handle("PUT /api/config", a.authenticate(a.csrf(http.HandlerFunc(a.handlePutConfig))))
|
||||
mux.Handle("POST /api/config/reload", a.authenticate(a.csrf(http.HandlerFunc(a.handleReload))))
|
||||
mux.Handle("POST /api/config/reveal", a.authenticate(a.csrf(http.HandlerFunc(a.handleReveal))))
|
||||
mux.Handle("POST /api/proxies/check", a.authenticate(a.csrf(http.HandlerFunc(a.handleCheckProxy))))
|
||||
mux.Handle("PUT /api/account", a.authenticate(a.csrf(http.HandlerFunc(a.handleAccount))))
|
||||
mux.Handle("GET /api/monitor", a.authenticate(http.HandlerFunc(a.handleMonitor)))
|
||||
mux.Handle("GET /api/debug/models", a.authenticate(http.HandlerFunc(a.handleDebugModels)))
|
||||
|
||||
@@ -336,6 +336,7 @@ func Load(path string) (Config, error) {
|
||||
}
|
||||
cfg := Config{
|
||||
Listen: "127.0.0.1:8080",
|
||||
Anonymous: false,
|
||||
Warp: WarpConfig{PoolSize: 2, Stack: string(warp.DefaultStack)},
|
||||
Upstream: UpstreamConfig{Zen: "https://opencode.ai/zen", Go: "https://opencode.ai/zen/go", Anonymous: "https://opencode.ai/inference"},
|
||||
Retry: RetryConfig{MaxAttempts: 3, TimeoutSeconds: 300},
|
||||
@@ -435,7 +436,7 @@ func Normalize(path string, cfg Config) (Config, error) {
|
||||
return Config{}, errors.New("at least one server key must remain enabled")
|
||||
}
|
||||
if !cfg.Anonymous && len(cfg.ZenKeys) == 0 && len(cfg.GoKeys) == 0 && cfg.GoSubscription == nil {
|
||||
return Config{}, errors.New("zen_keys or go_keys must contain at least one upstream key unless anonymous is enabled")
|
||||
return Config{}, errors.New("configure a Zen API Key (zen_keys), a Go key (go_keys), or a Go subscription (go_subscription); anonymous access is disabled by default and may be blocked upstream")
|
||||
}
|
||||
if cfg.Retry.MaxAttempts < 1 {
|
||||
return Config{}, errors.New("retry.max_attempts must be at least 1")
|
||||
@@ -487,18 +488,8 @@ func Normalize(path string, cfg Config) (Config, error) {
|
||||
}
|
||||
}
|
||||
for _, raw := range cfg.RuntimeProxies() {
|
||||
if raw == "direct" {
|
||||
continue
|
||||
}
|
||||
clean, _ := ParseProxyEntry(raw)
|
||||
u, err := url.Parse(clean)
|
||||
if err != nil || u.Host == "" {
|
||||
return Config{}, fmt.Errorf("invalid proxy URL %q", RedactURL(raw))
|
||||
}
|
||||
switch strings.ToLower(u.Scheme) {
|
||||
case "http", "https", "socks5", "socks5h":
|
||||
default:
|
||||
return Config{}, fmt.Errorf("unsupported proxy scheme %q", u.Scheme)
|
||||
if err := ValidateProxyEntry(raw); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
}
|
||||
if err := cfg.Models.AnonymousBackoff.Normalize(); err != nil {
|
||||
|
||||
@@ -35,6 +35,23 @@ func ParseProxyEntry(raw string) (clean string, pool bool) {
|
||||
return trimmed, pool
|
||||
}
|
||||
|
||||
func ValidateProxyEntry(raw string) error {
|
||||
if raw == "direct" {
|
||||
return nil
|
||||
}
|
||||
clean, _ := ParseProxyEntry(raw)
|
||||
parsed, err := url.Parse(clean)
|
||||
if err != nil || parsed.Host == "" || parsed.Hostname() == "" {
|
||||
return fmt.Errorf("invalid proxy URL %q", RedactURL(raw))
|
||||
}
|
||||
switch strings.ToLower(parsed.Scheme) {
|
||||
case "http", "https", "socks5", "socks5h":
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unsupported proxy scheme %q", parsed.Scheme)
|
||||
}
|
||||
}
|
||||
|
||||
// resolveProxyFiles trims cfg.Proxies in place and stores the runtime proxy
|
||||
// list: those proxies followed by the entries of cfg.ProxyFile (resolved
|
||||
// against the directory of configPath when relative), deduplicated, or
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"runtime"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"opencode2api/internal/config"
|
||||
"opencode2api/internal/httpx"
|
||||
"opencode2api/internal/models"
|
||||
)
|
||||
|
||||
type ProxyCheckResult struct {
|
||||
OK bool `json:"ok"`
|
||||
State string `json:"state"`
|
||||
Reason string `json:"reason"`
|
||||
LatencyMS int64 `json:"latency_ms"`
|
||||
Status int `json:"status,omitempty"`
|
||||
}
|
||||
|
||||
func (m *RuntimeController) CheckProxy(parent context.Context, value string) (result ProxyCheckResult) {
|
||||
started := time.Now()
|
||||
result = ProxyCheckResult{State: "inconclusive", Reason: "transport_error"}
|
||||
defer func() { result.LatencyMS = time.Since(started).Milliseconds() }()
|
||||
runtime := m.current.Load()
|
||||
if runtime == nil {
|
||||
result.Reason = "runtime_unavailable"
|
||||
return result
|
||||
}
|
||||
if err := config.ValidateProxyEntry(value); err != nil {
|
||||
result.Reason = "invalid_proxy"
|
||||
return result
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(parent, 20*time.Second)
|
||||
defer cancel()
|
||||
performance := runtime.config.Performance
|
||||
performance.ConnectTimeoutSeconds = min(max(performance.ConnectTimeoutSeconds, 1), 10)
|
||||
performance.MaxIdleConns = 1
|
||||
performance.MaxIdleConnsPerHost = 1
|
||||
performance.MaxConnsPerHost = 1
|
||||
pool, err := transportPool([]string{value}, performance, 20*time.Second)
|
||||
if err != nil {
|
||||
return result
|
||||
}
|
||||
proxy := pool.items[0]
|
||||
defer proxy.client.CloseIdleConnections()
|
||||
defer proxy.bun.CloseIdleConnections()
|
||||
client := proxy.bun
|
||||
client.CheckRedirect = func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }
|
||||
target, err := url.Parse(runtime.config.Upstream.Zen)
|
||||
if err != nil || target.Host == "" {
|
||||
result.Reason = "runtime_unavailable"
|
||||
return result
|
||||
}
|
||||
target.User = nil
|
||||
target.Path = strings.TrimRight(target.Path, "/") + "/v1/models"
|
||||
target.RawPath, target.RawQuery, target.Fragment = "", "", ""
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target.String(), nil)
|
||||
if err != nil {
|
||||
return result
|
||||
}
|
||||
req.Close = true
|
||||
req.Header.Set("Accept", "application/json")
|
||||
userAgent := httpx.V2UserAgent()
|
||||
if models.IsV1Upstream(runtime.config.Upstream.Zen) {
|
||||
userAgent = httpx.V1UserAgent()
|
||||
}
|
||||
req.Header.Set("User-Agent", userAgent)
|
||||
req.Header.Set("x-opencode-client", "cli")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return proxyCheckFailure(ctx, value, err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
return proxyCheckStatus(resp.StatusCode)
|
||||
}
|
||||
|
||||
func proxyCheckStatus(status int) ProxyCheckResult {
|
||||
result := ProxyCheckResult{State: "rejected", Reason: "upstream_responded", Status: status}
|
||||
switch {
|
||||
case status == http.StatusTooManyRequests:
|
||||
result.State, result.Reason = "limited", "rate_limited"
|
||||
case status == http.StatusUnauthorized:
|
||||
result.OK, result.State, result.Reason = true, "available", "authentication_required"
|
||||
case status >= 200 && status < 400:
|
||||
result.OK, result.State, result.Reason = true, "available", "ok"
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func proxyCheckFailure(ctx context.Context, value string, err error) ProxyCheckResult {
|
||||
result := ProxyCheckResult{State: "inconclusive", Reason: "transport_error"}
|
||||
if errors.Is(ctx.Err(), context.Canceled) {
|
||||
result.Reason = "canceled"
|
||||
return result
|
||||
}
|
||||
var timeout net.Error
|
||||
if errors.Is(ctx.Err(), context.DeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &timeout) && timeout.Timeout()) {
|
||||
result.Reason = "check_timeout"
|
||||
return result
|
||||
}
|
||||
var connectError *httpx.ProxyConnectError
|
||||
if errors.As(err, &connectError) {
|
||||
if connectError.StatusCode == http.StatusProxyAuthRequired {
|
||||
result.State, result.Reason, result.Status = "unavailable", "proxy_authentication_required", connectError.StatusCode
|
||||
return result
|
||||
}
|
||||
if connectError.StatusCode == http.StatusTooManyRequests {
|
||||
return proxyCheckStatus(connectError.StatusCode)
|
||||
}
|
||||
result.State, result.Reason, result.Status = "rejected", "proxy_tunnel_rejected", connectError.StatusCode
|
||||
return result
|
||||
}
|
||||
clean, _ := config.ParseProxyEntry(value)
|
||||
if clean == "direct" {
|
||||
return result
|
||||
}
|
||||
var routeError *net.OpError
|
||||
if !errors.As(err, &routeError) || (routeError.Op != "proxyconnect" && routeError.Op != "socks connect") {
|
||||
return result
|
||||
}
|
||||
var dialError *net.OpError
|
||||
if !errors.As(routeError.Err, &dialError) || dialError.Op != "dial" {
|
||||
return result
|
||||
}
|
||||
var dnsError *net.DNSError
|
||||
refused := errors.Is(dialError, syscall.ECONNREFUSED)
|
||||
if runtime.GOOS == "windows" {
|
||||
const windowsConnectionRefused = syscall.Errno(10061)
|
||||
refused = refused || errors.Is(dialError, windowsConnectionRefused)
|
||||
}
|
||||
if refused || (errors.As(dialError, &dnsError) && dnsError.IsNotFound) {
|
||||
result.State, result.Reason = "unavailable", "proxy_unreachable"
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -23,6 +23,14 @@ import (
|
||||
// http.DefaultTransport.
|
||||
const bunHandshakeTimeout = 10 * time.Second
|
||||
|
||||
type ProxyConnectError struct {
|
||||
StatusCode int
|
||||
}
|
||||
|
||||
func (err *ProxyConnectError) Error() string {
|
||||
return fmt.Sprintf("proxy refused CONNECT: HTTP %d", err.StatusCode)
|
||||
}
|
||||
|
||||
// bunClientHello returns the ClientHello of Bun's fetch, captured from Bun
|
||||
// 1.4.3. Bun links its own BoringSSL, so the hello is the same on every
|
||||
// platform: JA4 t13d1713h1, no GREASE, no padding, http/1.1 as the only ALPN
|
||||
@@ -189,7 +197,7 @@ func httpConnect(conn net.Conn, user *url.Userinfo, addr string) (net.Conn, erro
|
||||
return conn, err
|
||||
}
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return conn, fmt.Errorf("proxy refused CONNECT: %s", resp.Status)
|
||||
return conn, &ProxyConnectError{StatusCode: resp.StatusCode}
|
||||
}
|
||||
if reader.Buffered() > 0 {
|
||||
return &bufferedConn{Conn: conn, reader: reader}, nil
|
||||
|
||||
@@ -1,4 +1,40 @@
|
||||
/* Page layouts: login, dashboards, charts, logs, playground and rotation. */
|
||||
.config-warning {
|
||||
padding: var(--sp-3);
|
||||
border: 1px solid var(--warn);
|
||||
border-radius: var(--r-sm);
|
||||
background: var(--warn-bg);
|
||||
color: var(--warn);
|
||||
font-size: var(--fs-sm);
|
||||
}
|
||||
|
||||
.proxy-actions,
|
||||
.proxy-pager,
|
||||
.proxy-row-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
margin-block: var(--sp-3);
|
||||
}
|
||||
|
||||
.proxy-row-actions { flex-wrap: nowrap; margin: 0; }
|
||||
.proxy-search { max-width: 460px; }
|
||||
.proxy-table-wrap { max-height: 60vh; overflow: auto; margin-block: var(--sp-3); }
|
||||
.proxy-table { min-width: 820px; table-layout: fixed; }
|
||||
.proxy-table thead th { position: sticky; top: 0; z-index: 1; background: var(--surface); }
|
||||
.proxy-table th:first-child { width: 70px; }
|
||||
.proxy-table th:nth-child(2) { width: 25%; }
|
||||
.proxy-table th:nth-child(3) { width: 29%; }
|
||||
.proxy-table th:nth-child(4) { width: 18%; }
|
||||
.proxy-table th:nth-child(5) { width: 80px; }
|
||||
.proxy-table th:last-child { width: 120px; }
|
||||
.proxy-table td { vertical-align: middle; }
|
||||
.proxy-address { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.proxy-reason { color: var(--text-2); font-size: var(--fs-xs); overflow-wrap: anywhere; }
|
||||
.proxy-page-select { display: inline-flex; align-items: center; gap: var(--sp-1); }
|
||||
.proxy-table input[type="checkbox"] { width: auto; margin: 0; }
|
||||
|
||||
.login-view {
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
|
||||
+38
-1
@@ -877,6 +877,7 @@
|
||||
<input id="c-anonymous" type="checkbox" />
|
||||
<span data-i18n="config.secrets.anonymous">启用 Zen 匿名通道</span>
|
||||
</label>
|
||||
<p class="config-warning" data-i18n="config.secrets.anonymousWarning">匿名通道默认关闭,可能已被上游重点封堵。建议优先配置 Zen API Key;启用匿名不保证可用,也不会自动修改当前设置。</p>
|
||||
</div>
|
||||
<div class="field full">
|
||||
<label for="server_keys-new">Server Keys</label>
|
||||
@@ -916,7 +917,43 @@
|
||||
<h2 class="section-title" data-i18n="config.proxy.title">Proxy 节点</h2>
|
||||
</div>
|
||||
</div>
|
||||
<div id="proxies-chips" class="chips"></div>
|
||||
<p class="config-warning" data-i18n="config.proxy.warning">仅检查指定代理到 Zen 的无认证连通性,不发模型推理、不验证额度、不使用上游 Key,也不依赖匿名通道开关。401 表示已到达上游且需认证;上游拒绝或限流不代表代理永久损坏,只有确认代理故障才会进入「选中确认故障」。</p>
|
||||
<p class="section-caption" data-i18n="config.proxy.scope">检查与移除仅管理下列内联代理和新增草稿;proxyfile 条目请在文件中管理。移除需保存后生效,绑定验证失败时不会自动删除绑定。</p>
|
||||
<div class="proxy-actions">
|
||||
<button id="proxies-check-filtered" type="button" class="btn btn-sm" data-i18n="config.proxy.checkFiltered">检查筛选结果</button>
|
||||
<button id="proxies-check-selected" type="button" class="btn btn-sm" data-i18n="config.proxy.checkSelected">检查所选</button>
|
||||
<button id="proxies-stop" type="button" class="btn btn-sm hidden" data-i18n="config.proxy.stop">停止检查</button>
|
||||
<button id="proxies-select-filtered" type="button" class="btn btn-sm btn-ghost" data-i18n="config.proxy.selectFiltered">全选筛选结果</button>
|
||||
<button id="proxies-select-unavailable" type="button" class="btn btn-sm btn-ghost" data-i18n="config.proxy.selectUnavailable">选中确认故障</button>
|
||||
<button id="proxies-clear-selection" type="button" class="btn btn-sm btn-ghost" data-i18n="config.proxy.clearSelection">取消选择</button>
|
||||
<button id="proxies-delete-selected" type="button" class="btn btn-sm btn-danger" data-i18n="config.proxy.deleteSelected">移除所选代理</button>
|
||||
</div>
|
||||
<div class="field proxy-search">
|
||||
<label for="proxies-search" data-i18n="config.proxy.search">搜索代理地址(不搜索认证信息)</label>
|
||||
<input id="proxies-search" type="search" autocomplete="off" />
|
||||
</div>
|
||||
<p id="proxies-summary" class="section-caption" role="status" aria-live="polite"></p>
|
||||
<p id="proxies-progress" class="section-caption" role="status" aria-live="polite"></p>
|
||||
<div class="table-wrap proxy-table-wrap">
|
||||
<table id="proxies-table" class="table proxy-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th><label class="proxy-page-select"><input id="proxies-select-page" type="checkbox" /><span data-i18n="config.proxy.selectPage">本页</span></label></th>
|
||||
<th data-i18n="config.proxy.address">代理地址</th>
|
||||
<th data-i18n="config.proxy.result">检查结果</th>
|
||||
<th data-i18n="config.proxy.response">上游响应</th>
|
||||
<th data-i18n="config.proxy.latency">耗时</th>
|
||||
<th data-i18n="config.proxy.actions">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="proxies-rows"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="proxy-pager">
|
||||
<button id="proxies-prev" type="button" class="btn btn-sm" data-i18n="diag.pager.prev">上一页</button>
|
||||
<span id="proxies-page" class="section-caption"></span>
|
||||
<button id="proxies-next" type="button" class="btn btn-sm" data-i18n="diag.pager.next">下一页</button>
|
||||
</div>
|
||||
<div class="form-grid">
|
||||
<div class="field">
|
||||
<label for="proxies-new" data-i18n="config.proxy.add">新增 Proxy(每行一个)</label>
|
||||
|
||||
@@ -268,11 +268,63 @@ const DICTIONARY = {
|
||||
"Sensitive values are masked by default; a cleared value only takes effect after saving.",
|
||||
"config.secrets.reveal": "Reveal after re-verification",
|
||||
"config.secrets.anonymous": "Enable the Zen anonymous channel",
|
||||
"config.secrets.anonymousWarning": "Anonymous access is disabled by default and may be heavily blocked upstream. Prefer a Zen API key. Enabling anonymous access does not guarantee availability or automatically change your current settings.",
|
||||
"config.secrets.add": "One key per line",
|
||||
"config.proxy.title": "Proxy nodes",
|
||||
"config.proxy.caption":
|
||||
"Supports direct, HTTP(S), and SOCKS URLs. Suffix an entry with #pool to mark it as a rotating proxy pool: the gateway then opens a fresh connection per attempt, skips its cooldown and health eviction, and retries it up to retry.max_attempts times.",
|
||||
"config.proxy.add": "Add proxies (one per line)",
|
||||
"config.proxy.warning": "Checks only test unauthenticated connectivity from the specified proxy to Zen. They do not send inference, verify quota, use upstream keys, or depend on the anonymous-access switch. HTTP 401 means the upstream was reached and requires authentication. Upstream rejection or rate limiting does not prove a permanent proxy fault; only confirmed proxy faults enter Select confirmed failures.",
|
||||
"config.proxy.scope": "Checks and removals apply only to the inline proxies and drafts below. Manage proxyfile entries in that file. Removals take effect after saving; validation never silently removes proxy bindings.",
|
||||
"config.proxy.checkFiltered": "Check filtered results",
|
||||
"config.proxy.checkSelected": "Check selected",
|
||||
"config.proxy.stop": "Stop checks",
|
||||
"config.proxy.selectFiltered": "Select all filtered results",
|
||||
"config.proxy.selectUnavailable": "Select confirmed failures",
|
||||
"config.proxy.clearSelection": "Clear selection",
|
||||
"config.proxy.deleteSelected": "Remove selected proxies",
|
||||
"config.proxy.search": "Search proxy addresses (not credentials)",
|
||||
"config.proxy.selectPage": "This page",
|
||||
"config.proxy.address": "Proxy address",
|
||||
"config.proxy.result": "Check result",
|
||||
"config.proxy.response": "Upstream response",
|
||||
"config.proxy.latency": "Duration",
|
||||
"config.proxy.actions": "Actions",
|
||||
"config.proxy.unchecked": "Not checked",
|
||||
"config.proxy.checking": "Checking…",
|
||||
"config.proxy.available": "Reachable for this check",
|
||||
"config.proxy.unavailable": "Confirmed proxy fault",
|
||||
"config.proxy.limited": "Temporarily rate limited",
|
||||
"config.proxy.rejected": "Rejected by upstream",
|
||||
"config.proxy.inconclusive": "Inconclusive",
|
||||
"config.proxy.invalid": "Invalid proxy address",
|
||||
"config.proxy.summary": "{0} total · {1} filtered · {2} selected · {3} checked · {4} confirmed failures",
|
||||
"config.proxy.progress": "This batch: {0} / {1}; at most 4 concurrent checks",
|
||||
"config.proxy.page": "Page {0} / {1} · at most 50 rows per page",
|
||||
"config.proxy.noMatch": "No matching proxies",
|
||||
"config.proxy.empty": "No inline proxies. Add drafts below; manage proxyfile entries in that file.",
|
||||
"config.proxy.select": "Select proxy",
|
||||
"config.proxy.check": "Check",
|
||||
"config.proxy.removeTitle": "Remove proxies",
|
||||
"config.proxy.removeConfirm": "Remove the {0} selected proxies? Changes take effect after saving. Existing bindings may cause validation to reject the change; bindings are not removed automatically.",
|
||||
"config.proxy.checkTitle": "Confirm proxy connectivity checks",
|
||||
"config.proxy.checkConfirm": "Check connectivity from {0} specified proxies to Zen? No model inference or upstream keys are used and no quota is verified. Upstream rejection or rate limiting does not prove a permanent proxy fault.",
|
||||
"config.proxy.start": "Start checks",
|
||||
"config.proxy.reason.responded": "The upstream responded",
|
||||
"config.proxy.reason.authenticationRequired": "Reached the upstream; authentication is required",
|
||||
"config.proxy.reason.unreachable": "Cannot connect to the proxy",
|
||||
"config.proxy.reason.authentication": "Proxy authentication is required",
|
||||
"config.proxy.reason.rateLimited": "Temporarily rate limited upstream; retry later",
|
||||
"config.proxy.reason.rejected": "The upstream rejected the connectivity check; a proxy fault is not confirmed",
|
||||
"config.proxy.reason.tunnelRejected": "The proxy tunnel request was rejected; a proxy fault is not confirmed",
|
||||
"config.proxy.reason.timeout": "The check timed out; a proxy fault is not confirmed",
|
||||
"config.proxy.reason.transport": "Transport failed; a proxy fault is not confirmed",
|
||||
"config.proxy.reason.canceled": "The check was canceled",
|
||||
"config.proxy.reason.tooLarge": "The upstream reply exceeded the size limit",
|
||||
"config.proxy.reason.invalidResponse": "Invalid check response",
|
||||
"config.proxy.reason.runtimeUnavailable": "The gateway runtime is unavailable; retry later",
|
||||
"config.proxy.reason.invalidProxy": "Invalid proxy address; check its configuration",
|
||||
"config.proxy.reason.management": "The management request failed or was rate limited. Retry; this does not prove a proxy fault.",
|
||||
"config.warp.title": "WARP egress",
|
||||
"config.warp.caption":
|
||||
"While enabled, free-model traffic (anonymous channel, free-model Zen keys, free-model probes) leaves through a userspace Cloudflare WARP tunnel and never through a proxy; Go-plan and paid models keep their proxy bindings. An exit answered with 429/403 is retired and re-registered in the background, and a free-model request keeps rotating exits until retry.max_attempts is spent before the last 429 reaches the client.",
|
||||
|
||||
+69
-13
@@ -1,15 +1,16 @@
|
||||
// Page: 配置中心 — masked config editing with validation, hot reload and reveal.
|
||||
import { api } from "../api.js";
|
||||
import { loadConfig, loadDebugModels } from "../data.js";
|
||||
import { api, hasSession } from "../api.js";
|
||||
import * as store from "../store.js";
|
||||
import { t, onChange } from "../i18n.js";
|
||||
import { $, $$, bindTabs, el, openDialog, toast } from "../ui.js";
|
||||
import { fillProxies, initProxies, lockProxies, proxyInputs, resetProxies, stopChecks } from "./proxies.js";
|
||||
|
||||
// A long proxy list is rendered collapsed: the first CHIP_RENDER_LIMIT chips
|
||||
// plus a toggle. A single flex-wrap row with thousands of chips is what froze
|
||||
// the config page on large pools.
|
||||
const CHIP_RENDER_LIMIT = 100;
|
||||
const expandedChips = new Set();
|
||||
let mutation = null;
|
||||
|
||||
function renderChips(name) {
|
||||
const host = $(`#${name}-chips`);
|
||||
@@ -61,6 +62,7 @@ function renderRestartNotice(value) {
|
||||
}
|
||||
|
||||
function secretInputs(name) {
|
||||
if (name === "proxies") return proxyInputs();
|
||||
const kept = [...$(`#${name}-chips`).children]
|
||||
.filter((node) => node.dataset.id !== undefined)
|
||||
.map((node) => ({ id: node.dataset.id }));
|
||||
@@ -110,14 +112,34 @@ function fillConfig(value) {
|
||||
$("#c-level").value = value.logging.level;
|
||||
$("#c-ring").value = value.logging.ring_size;
|
||||
$("#c-dump-bodies").checked = !!value.logging.dump_request_bodies;
|
||||
["server_keys", "zen_keys", "go_keys", "proxies"].forEach(renderChips);
|
||||
["server_keys", "zen_keys", "go_keys"].forEach(renderChips);
|
||||
fillProxies(value.proxies || []);
|
||||
renderRestartNotice(value);
|
||||
}
|
||||
|
||||
function lockConfig(value) {
|
||||
lockProxies(value);
|
||||
$$("#config-form .sticky-actions button").forEach((button) => (button.disabled = value));
|
||||
}
|
||||
|
||||
function currentMutation(operation) {
|
||||
return mutation === operation && hasSession();
|
||||
}
|
||||
|
||||
async function refreshDebug(operation) {
|
||||
const value = await api("/api/debug/models", { signal: operation.controller.signal });
|
||||
if (!currentMutation(operation)) return;
|
||||
if (value.last_inference) store.set("lastPlayground", value.last_inference);
|
||||
store.set("debug", value);
|
||||
}
|
||||
|
||||
async function save(event) {
|
||||
event.preventDefault();
|
||||
const current = store.get("config");
|
||||
if (!current) return;
|
||||
if (!current || mutation || !hasSession()) return;
|
||||
const operation = { controller: new AbortController() };
|
||||
mutation = operation;
|
||||
lockConfig(true);
|
||||
try {
|
||||
const update = {
|
||||
listen: $("#c-listen").value,
|
||||
@@ -168,12 +190,17 @@ async function save(event) {
|
||||
session_ttl_minutes: numberValue("#c-session"),
|
||||
},
|
||||
};
|
||||
const result = await api("/api/config", { method: "PUT", body: JSON.stringify(update) });
|
||||
const result = await api("/api/config", {
|
||||
method: "PUT", body: JSON.stringify(update), signal: operation.controller.signal,
|
||||
});
|
||||
if (!currentMutation(operation)) return;
|
||||
fillProxies(result.config.proxies || [], true);
|
||||
store.set("config", result.config);
|
||||
["server_keys", "zen_keys", "go_keys", "proxies"].forEach(
|
||||
["server_keys", "zen_keys", "go_keys"].forEach(
|
||||
(name) => ($(`#${name}-new`).value = ""),
|
||||
);
|
||||
await loadDebugModels();
|
||||
await refreshDebug(operation);
|
||||
if (!currentMutation(operation)) return;
|
||||
toast(
|
||||
result.result.restart_required
|
||||
? t(
|
||||
@@ -184,22 +211,43 @@ async function save(event) {
|
||||
: t("配置已保存并立即应用", "toast.config.saved"),
|
||||
);
|
||||
} catch (error) {
|
||||
toast(error.message, true);
|
||||
if (currentMutation(operation) && error.name !== "AbortError") toast(error.message, true);
|
||||
} finally {
|
||||
if (mutation === operation) {
|
||||
mutation = null;
|
||||
lockConfig(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function reload() {
|
||||
if (mutation || !hasSession()) return;
|
||||
const operation = { controller: new AbortController() };
|
||||
mutation = operation;
|
||||
lockConfig(true);
|
||||
try {
|
||||
const result = await api("/api/config/reload", { method: "POST", body: "{}" });
|
||||
await loadConfig();
|
||||
await loadDebugModels();
|
||||
const result = await api("/api/config/reload", {
|
||||
method: "POST", body: "{}", signal: operation.controller.signal,
|
||||
});
|
||||
if (!currentMutation(operation)) return;
|
||||
const value = await api("/api/config", { signal: operation.controller.signal });
|
||||
if (!currentMutation(operation)) return;
|
||||
fillProxies(value.proxies || [], true);
|
||||
store.set("config", value);
|
||||
await refreshDebug(operation);
|
||||
if (!currentMutation(operation)) return;
|
||||
toast(
|
||||
result.restart_required
|
||||
? t("磁盘配置已重载,监听字段需重启", "toast.config.reloadedRestart")
|
||||
: t("磁盘配置已重载", "toast.config.reloaded"),
|
||||
);
|
||||
} catch (error) {
|
||||
toast(error.message, true);
|
||||
if (currentMutation(operation) && error.name !== "AbortError") toast(error.message, true);
|
||||
} finally {
|
||||
if (mutation === operation) {
|
||||
mutation = null;
|
||||
lockConfig(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,9 +293,17 @@ export default {
|
||||
id: "config",
|
||||
title: "配置中心",
|
||||
sub: "验证后原子保存,并热应用可变字段。",
|
||||
hide: stopChecks,
|
||||
reset() {
|
||||
mutation?.controller.abort();
|
||||
mutation = null;
|
||||
lockConfig(false);
|
||||
resetProxies();
|
||||
},
|
||||
init() {
|
||||
store.on("config", fillConfig);
|
||||
bindTabs($("#page-config"));
|
||||
initProxies();
|
||||
bindTabs($("#page-config"), (id) => { if (id !== "proxies") stopChecks(); });
|
||||
$("#config-form").addEventListener("submit", save);
|
||||
$("#reload-config").addEventListener("click", reload);
|
||||
$("#reveal").addEventListener("click", reveal);
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
import { api, hasSession } from "../api.js";
|
||||
import { t, onChange } from "../i18n.js";
|
||||
import { $, confirmDialog, el, emptyRow } from "../ui.js";
|
||||
|
||||
const pageSize = 50;
|
||||
const verdicts = ["available", "unavailable", "limited", "rejected", "inconclusive"];
|
||||
let saved = [];
|
||||
let drafts = [];
|
||||
let list = [];
|
||||
let filtered = [];
|
||||
let page = 0;
|
||||
let selected = new Set();
|
||||
let removed = new Set();
|
||||
let counts = {};
|
||||
let visibleNodes = new Map();
|
||||
let run = null;
|
||||
let locked = false;
|
||||
let generation = 0;
|
||||
|
||||
function stateLabel(state) {
|
||||
const labels = {
|
||||
unchecked: ["未检查", "unchecked"],
|
||||
checking: ["检查中…", "checking"],
|
||||
available: ["本次可连通", "available"],
|
||||
unavailable: ["确认代理故障", "unavailable"],
|
||||
limited: ["暂时限流", "limited"],
|
||||
rejected: ["上游拒绝", "rejected"],
|
||||
inconclusive: ["无法判定", "inconclusive"],
|
||||
};
|
||||
const [fallback, key] = labels[state];
|
||||
return t(fallback, `config.proxy.${key}`);
|
||||
}
|
||||
|
||||
function reasonLabel(reason) {
|
||||
const reasons = {
|
||||
ok: ["上游已响应", "responded"],
|
||||
upstream_responded: ["上游已响应", "responded"],
|
||||
authentication_required: ["已到达上游,需要认证", "authenticationRequired"],
|
||||
proxy_unreachable: ["无法连接代理", "unreachable"],
|
||||
proxy_authentication_required: ["代理需要认证", "authentication"],
|
||||
rate_limited: ["上游暂时限流,请稍后重试", "rateLimited"],
|
||||
upstream_rejected: ["上游拒绝连接检查,不能确认代理故障", "rejected"],
|
||||
proxy_tunnel_rejected: ["代理隧道请求被拒绝,不能确认代理故障", "tunnelRejected"],
|
||||
check_timeout: ["检查超时,无法确认代理故障", "timeout"],
|
||||
transport_error: ["传输失败,无法确认代理故障", "transport"],
|
||||
canceled: ["检查已取消", "canceled"],
|
||||
response_too_large: ["上游回复过大", "tooLarge"],
|
||||
invalid_response: ["检查回复格式无效", "invalidResponse"],
|
||||
runtime_unavailable: ["网关运行时暂不可用,请稍后重试", "runtimeUnavailable"],
|
||||
invalid_proxy: ["代理地址无效,请检查配置", "invalidProxy"],
|
||||
management_error: ["管理请求失败或暂时限流,请重试;这不代表代理故障", "management"],
|
||||
};
|
||||
const [fallback, key] = Object.hasOwn(reasons, reason) ? reasons[reason] : reasons.invalid_response;
|
||||
return t(fallback, `config.proxy.reason.${key}`);
|
||||
}
|
||||
|
||||
function draftDisplay(value) {
|
||||
const pooled = /^pool\+/i.test(value) || /#pool$/i.test(value);
|
||||
const clean = value.replace(/^pool\+/i, "").replace(/#pool$/i, "");
|
||||
if (clean === "direct") return `direct${pooled ? "#pool" : ""}`;
|
||||
try {
|
||||
const address = new URL(clean);
|
||||
if (!["http:", "https:", "socks5:", "socks5h:"].includes(address.protocol) || !address.host)
|
||||
return t("无效代理地址", "config.proxy.invalid");
|
||||
const masked = address.username || address.password ? "***@" : "";
|
||||
return `${address.protocol}//${masked}${address.host}${pooled ? "#pool" : ""}`;
|
||||
} catch {
|
||||
return t("无效代理地址", "config.proxy.invalid");
|
||||
}
|
||||
}
|
||||
|
||||
function newRow(input, display) {
|
||||
return { input, display, state: "unchecked", result: null };
|
||||
}
|
||||
|
||||
function applySearch() {
|
||||
const query = $("#proxies-search").value.trim().toLowerCase();
|
||||
filtered = query ? list.filter((row) => row.display.toLowerCase().includes(query)) : list;
|
||||
page = Math.max(0, Math.min(page, Math.ceil(filtered.length / pageSize) - 1));
|
||||
}
|
||||
|
||||
function rebuild() {
|
||||
list = saved.concat(drafts);
|
||||
const current = new Set(list);
|
||||
selected = new Set([...selected].filter((row) => current.has(row)));
|
||||
counts = {};
|
||||
for (const row of list) counts[row.state] = (counts[row.state] || 0) + 1;
|
||||
applySearch();
|
||||
render();
|
||||
}
|
||||
|
||||
function syncDrafts() {
|
||||
const previous = new Map(drafts.map((row) => [row.input.value, row]));
|
||||
const values = [...new Set($("#proxies-new").value.split(/\r?\n/).map((value) => value.trim()).filter(Boolean))];
|
||||
drafts = values.map((value) => previous.get(value) || newRow({ value }, draftDisplay(value)));
|
||||
}
|
||||
|
||||
export function fillProxies(values, replace = false) {
|
||||
stopChecks();
|
||||
const previous = new Map(saved.map((row) => [row.input.id, row]));
|
||||
if (replace) {
|
||||
removed.clear();
|
||||
selected.clear();
|
||||
drafts = [];
|
||||
$("#proxies-new").value = "";
|
||||
}
|
||||
saved = values.filter((item) => !removed.has(item.id)).map((item) => {
|
||||
const row = previous.get(item.id) || newRow({ id: item.id }, item.display);
|
||||
row.display = item.display;
|
||||
return row;
|
||||
});
|
||||
rebuild();
|
||||
}
|
||||
|
||||
export function proxyInputs() {
|
||||
return list.map((row) => ({ ...row.input }));
|
||||
}
|
||||
|
||||
export function lockProxies(value) {
|
||||
locked = value;
|
||||
if (locked) stopChecks();
|
||||
refreshControls();
|
||||
}
|
||||
|
||||
export function resetProxies() {
|
||||
generation++;
|
||||
stopChecks();
|
||||
locked = false;
|
||||
saved = [];
|
||||
drafts = [];
|
||||
removed.clear();
|
||||
selected.clear();
|
||||
page = 0;
|
||||
$("#proxies-search").value = "";
|
||||
$("#proxies-new").value = "";
|
||||
rebuild();
|
||||
}
|
||||
|
||||
function refreshControls() {
|
||||
const busy = locked || !!run;
|
||||
const checked = verdicts.reduce((total, state) => total + (counts[state] || 0), 0);
|
||||
$("#proxies-summary").textContent = t(
|
||||
"共 {0} 条 · 筛选 {1} 条 · 已选 {2} 条 · 已检查 {3} 条 · 确认故障 {4} 条",
|
||||
"config.proxy.summary", list.length, filtered.length, selected.size, checked, counts.unavailable || 0,
|
||||
);
|
||||
$("#proxies-progress").textContent = run
|
||||
? t("本次检查:{0} / {1};最多并发 4 条", "config.proxy.progress", run.completed, run.targets.length)
|
||||
: "";
|
||||
$("#proxies-check-filtered").disabled = busy || !filtered.length;
|
||||
$("#proxies-check-selected").disabled = busy || !selected.size;
|
||||
$("#proxies-select-filtered").disabled = busy || !filtered.length;
|
||||
$("#proxies-select-unavailable").disabled = busy || !counts.unavailable;
|
||||
$("#proxies-clear-selection").disabled = busy || !selected.size;
|
||||
$("#proxies-delete-selected").disabled = busy || !selected.size;
|
||||
$("#proxies-stop").classList.toggle("hidden", !run);
|
||||
$("#proxies-new").disabled = busy;
|
||||
$("#c-proxyfile").disabled = locked;
|
||||
$("#proxies-search").disabled = locked;
|
||||
$("#proxies-table").setAttribute("aria-busy", run ? "true" : "false");
|
||||
const pages = Math.max(1, Math.ceil(filtered.length / pageSize));
|
||||
$("#proxies-page").textContent = t("第 {0} / {1} 页 · 每页最多 50 条", "config.proxy.page", page + 1, pages);
|
||||
$("#proxies-prev").disabled = locked || page === 0;
|
||||
$("#proxies-next").disabled = locked || page + 1 >= pages;
|
||||
const checkedVisible = [...visibleNodes.keys()].filter((row) => selected.has(row)).length;
|
||||
const checkbox = $("#proxies-select-page");
|
||||
checkbox.checked = visibleNodes.size > 0 && checkedVisible === visibleNodes.size;
|
||||
checkbox.indeterminate = checkedVisible > 0 && checkedVisible < visibleNodes.size;
|
||||
checkbox.disabled = busy || !visibleNodes.size;
|
||||
for (const [row, nodes] of visibleNodes) {
|
||||
nodes.checkbox.checked = selected.has(row);
|
||||
nodes.checkbox.disabled = busy;
|
||||
nodes.check.disabled = busy;
|
||||
nodes.remove.disabled = busy;
|
||||
}
|
||||
}
|
||||
|
||||
function renderResult(row) {
|
||||
const nodes = visibleNodes.get(row);
|
||||
if (!nodes) return;
|
||||
const tone = row.state === "available" ? "ok" : row.state === "unavailable" ? "bad" : "warn";
|
||||
nodes.status.replaceChildren(el("span", { class: row.state === "unchecked" ? "" : tone, text: stateLabel(row.state) }));
|
||||
if (row.result) {
|
||||
nodes.status.append(el("div", { class: "proxy-reason", text: reasonLabel(row.result.reason) }));
|
||||
}
|
||||
nodes.response.textContent = row.result?.status ? `HTTP ${row.result.status}` : "—";
|
||||
nodes.latency.textContent = row.result?.latency_ms != null ? `${row.result.latency_ms} ms` : "—";
|
||||
}
|
||||
|
||||
function render() {
|
||||
const host = $("#proxies-rows");
|
||||
host.replaceChildren();
|
||||
visibleNodes = new Map();
|
||||
const entries = filtered.slice(page * pageSize, (page + 1) * pageSize);
|
||||
if (!entries.length)
|
||||
emptyRow(host, 6, list.length
|
||||
? t("没有匹配的代理", "config.proxy.noMatch")
|
||||
: t("暂无内联代理;可在下方新增。proxyfile 中的条目请在文件中管理。", "config.proxy.empty"));
|
||||
for (const row of entries) {
|
||||
const checkbox = el("input", { type: "checkbox", "aria-label": t("选择代理", "config.proxy.select") });
|
||||
checkbox.addEventListener("change", () => {
|
||||
if (checkbox.checked) selected.add(row);
|
||||
else selected.delete(row);
|
||||
refreshControls();
|
||||
});
|
||||
const status = el("td");
|
||||
const response = el("td", { class: "mono" });
|
||||
const latency = el("td", { class: "num" });
|
||||
const check = el("button", {
|
||||
type: "button", class: "btn btn-sm btn-ghost", text: t("检查", "config.proxy.check"),
|
||||
onclick: () => checkRows([row]),
|
||||
});
|
||||
const remove = el("button", {
|
||||
type: "button", class: "btn btn-sm btn-ghost", text: t("移除", "common.remove"),
|
||||
onclick: () => removeRows([row]),
|
||||
});
|
||||
visibleNodes.set(row, { checkbox, status, response, latency, check, remove });
|
||||
host.append(el("tr", {}, [
|
||||
el("td", {}, [checkbox]), el("td", { class: "mono proxy-address", text: row.display, title: row.display }),
|
||||
status, response, latency, el("td", {}, [el("div", { class: "proxy-row-actions" }, [check, remove])]),
|
||||
]));
|
||||
renderResult(row);
|
||||
}
|
||||
refreshControls();
|
||||
}
|
||||
|
||||
async function removeRows(targets) {
|
||||
if (locked || run || !targets.length) return;
|
||||
const operation = generation;
|
||||
const accepted = await confirmDialog({
|
||||
title: t("移除代理", "config.proxy.removeTitle"),
|
||||
message: t("移除所选 {0} 条代理?保存后生效;存在绑定时可能被配置验证拒绝,不会自动删除绑定。", "config.proxy.removeConfirm", targets.length),
|
||||
confirmLabel: t("移除", "common.remove"), danger: true,
|
||||
});
|
||||
if (!accepted || operation !== generation || !hasSession() || locked || run) return;
|
||||
const deleting = new Set(targets);
|
||||
for (const row of targets) if (row.input.id) removed.add(row.input.id);
|
||||
saved = saved.filter((row) => !deleting.has(row));
|
||||
drafts = drafts.filter((row) => !deleting.has(row));
|
||||
$("#proxies-new").value = drafts.map((row) => row.input.value).join("\n");
|
||||
rebuild();
|
||||
}
|
||||
|
||||
function setResult(row, state, result) {
|
||||
counts[row.state] = (counts[row.state] || 0) - 1;
|
||||
counts[state] = (counts[state] || 0) + 1;
|
||||
row.state = state;
|
||||
row.result = result;
|
||||
renderResult(row);
|
||||
}
|
||||
|
||||
export function stopChecks() {
|
||||
if (!run) return;
|
||||
const previous = run;
|
||||
run = null;
|
||||
previous.controller.abort();
|
||||
for (const row of previous.inFlight) setResult(row, "unchecked", null);
|
||||
refreshControls();
|
||||
}
|
||||
|
||||
async function checkRows(targets) {
|
||||
if (locked || run || !targets.length || !hasSession()) return;
|
||||
const active = {
|
||||
controller: new AbortController(), targets: targets.slice(), next: 0, completed: 0,
|
||||
inFlight: new Set(), generation,
|
||||
};
|
||||
run = active;
|
||||
refreshControls();
|
||||
const accepted = await confirmDialog({
|
||||
title: t("确认代理连通性检查", "config.proxy.checkTitle"),
|
||||
message: t("将检查 {0} 条指定代理到 Zen 的连通性,不发送模型推理、不使用上游 Key,也不验证额度。上游拒绝或限流不能证明代理永久损坏。是否继续?", "config.proxy.checkConfirm", targets.length),
|
||||
confirmLabel: t("开始检查", "config.proxy.start"),
|
||||
});
|
||||
if (run !== active || active.generation !== generation || !hasSession()) return;
|
||||
if (!accepted) {
|
||||
stopChecks();
|
||||
return;
|
||||
}
|
||||
const worker = async () => {
|
||||
while (run === active && active.next < active.targets.length) {
|
||||
const row = active.targets[active.next++];
|
||||
active.inFlight.add(row);
|
||||
setResult(row, "checking", null);
|
||||
try {
|
||||
const result = await api("/api/proxies/check", {
|
||||
method: "POST", body: JSON.stringify(row.input), signal: active.controller.signal,
|
||||
});
|
||||
if (run !== active || active.generation !== generation || !hasSession()) return;
|
||||
if (!result || !verdicts.includes(result.state) || result.ok !== (result.state === "available")) {
|
||||
setResult(row, "inconclusive", { reason: "invalid_response" });
|
||||
} else {
|
||||
setResult(row, result.state, {
|
||||
reason: result.reason,
|
||||
latency_ms: Number.isFinite(result.latency_ms) && result.latency_ms >= 0 ? Math.round(result.latency_ms) : null,
|
||||
status: Number.isInteger(result.status) && result.status >= 100 && result.status <= 599 ? result.status : null,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
if (run !== active || active.generation !== generation || !hasSession()) return;
|
||||
setResult(row, "inconclusive", { reason: "management_error" });
|
||||
}
|
||||
active.inFlight.delete(row);
|
||||
active.completed++;
|
||||
refreshControls();
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(4, active.targets.length) }, worker));
|
||||
if (run === active) {
|
||||
run = null;
|
||||
refreshControls();
|
||||
}
|
||||
}
|
||||
|
||||
export function initProxies() {
|
||||
$("#proxies-new").addEventListener("input", () => {
|
||||
if (locked || run) return;
|
||||
syncDrafts();
|
||||
rebuild();
|
||||
});
|
||||
$("#proxies-search").addEventListener("input", () => { page = 0; applySearch(); render(); });
|
||||
$("#proxies-search").addEventListener("keydown", (event) => { if (event.key === "Enter") event.preventDefault(); });
|
||||
$("#proxies-prev").addEventListener("click", () => { page--; render(); });
|
||||
$("#proxies-next").addEventListener("click", () => { page++; render(); });
|
||||
$("#proxies-select-page").addEventListener("change", (event) => {
|
||||
for (const row of visibleNodes.keys()) {
|
||||
if (event.target.checked) selected.add(row);
|
||||
else selected.delete(row);
|
||||
}
|
||||
refreshControls();
|
||||
});
|
||||
$("#proxies-select-filtered").addEventListener("click", () => {
|
||||
for (const row of filtered) selected.add(row);
|
||||
refreshControls();
|
||||
});
|
||||
$("#proxies-select-unavailable").addEventListener("click", () => {
|
||||
selected = new Set(list.filter((row) => row.state === "unavailable"));
|
||||
refreshControls();
|
||||
});
|
||||
$("#proxies-clear-selection").addEventListener("click", () => { selected.clear(); refreshControls(); });
|
||||
$("#proxies-delete-selected").addEventListener("click", () => removeRows([...selected]));
|
||||
$("#proxies-check-filtered").addEventListener("click", () => checkRows(filtered));
|
||||
$("#proxies-check-selected").addEventListener("click", () => checkRows([...selected]));
|
||||
$("#proxies-stop").addEventListener("click", stopChecks);
|
||||
onChange(() => {
|
||||
for (const row of drafts) row.display = draftDisplay(row.input.value);
|
||||
applySearch();
|
||||
render();
|
||||
});
|
||||
rebuild();
|
||||
}
|
||||
Reference in new issue
Block a user