refactor: strip paid tiers, webui, rotation, and docker; optimize anonymous free concurrency

This commit is contained in:
Jason Xu committed 2026-10-18 00:54:33 +08:00
1 parent 83d623d541
commit 80a8da3195
65 files changed
+648 -11927

No files matched your search

-13
View File
@@ -1,13 +0,0 @@
*
!cmd/
!cmd/**
!internal/
!internal/**
!go.mod
!go.sum
!webui/
!webui/**
!config.example.json
!docker-entrypoint.sh
!Dockerfile
!LICENSE
+1 -12
View File
@@ -34,16 +34,13 @@ jobs:
run: go build -trimpath ./cmd/opencode2api
format:
name: Formatting and WebUI syntax
name: Go formatting
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
- uses: actions/setup-node@v4
with:
node-version: "22"
- name: Check Go formatting
shell: bash
run: |
@@ -52,11 +49,3 @@ jobs:
printf '%s\n' "$unformatted"
exit 1
fi
- name: Check WebUI syntax
shell: bash
run: |
for f in webui/js/*.js webui/js/pages/*.js; do
node --input-type=module --check < "$f" || { echo "syntax error: $f" >&2; exit 1; }
done
- name: Check container entrypoint syntax
run: sh -n docker-entrypoint.sh
+2 -58
View File
@@ -1,4 +1,4 @@
name: Release binaries and GHCR image
name: Release binaries
on:
push:
@@ -24,7 +24,6 @@ jobs:
runs-on: ubuntu-latest
outputs:
release_tag: ${{ steps.metadata.outputs.release_tag }}
image_name: ${{ steps.metadata.outputs.image_name }}
steps:
- name: Resolve release metadata
id: metadata
@@ -42,7 +41,6 @@ jobs:
exit 1
fi
echo "release_tag=$release_tag" >> "$GITHUB_OUTPUT"
echo "image_name=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_OUTPUT"
verify:
name: Verify source
@@ -148,63 +146,9 @@ jobs:
dist/${{ steps.metadata.outputs.package_name }}.${{ matrix.archive }}.sha256
if-no-files-found: error
container:
name: Publish GHCR image
needs: [prepare, verify]
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Check out source
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Generate image metadata
id: image_metadata
uses: docker/metadata-action@v5
with:
images: ${{ needs.prepare.outputs.image_name }}
tags: |
type=raw,value=${{ needs.prepare.outputs.release_tag }}
type=semver,pattern={{version}},value=${{ needs.prepare.outputs.release_tag }}
type=semver,pattern={{major}}.{{minor}},value=${{ needs.prepare.outputs.release_tag }},enable=${{ !contains(needs.prepare.outputs.release_tag, '-') }}
type=semver,pattern={{major}},value=${{ needs.prepare.outputs.release_tag }},enable=${{ !contains(needs.prepare.outputs.release_tag, '-') }}
labels: |
org.opencontainers.image.title=opencode2api
org.opencontainers.image.description=OpenAI-compatible API gateway for OpenCode Zen and Go
org.opencontainers.image.licenses=GPL-3.0-or-later
- name: Build and push image
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.image_metadata.outputs.tags }}
labels: ${{ steps.image_metadata.outputs.labels }}
build-args: |
VERSION=${{ needs.prepare.outputs.release_tag }}
cache-from: type=gha,scope=container
cache-to: type=gha,mode=max,scope=container
provenance: mode=max
sbom: true
release:
name: Publish GitHub Release
needs: [prepare, build, container]
needs: [prepare, build]
runs-on: ubuntu-latest
permissions:
contents: write
-51
View File
@@ -1,51 +0,0 @@
FROM --platform=$BUILDPLATFORM golang:1.24-alpine AS builder
ARG TARGETOS
ARG TARGETARCH
ARG VERSION=dev
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 \
GOOS="${TARGETOS:-linux}" \
GOARCH="${TARGETARCH:-amd64}" \
go build \
-trimpath \
-ldflags="-s -w -X main.version=${VERSION}" \
-o /out/opencode2api ./cmd/opencode2api
FROM alpine:3.22
RUN apk add --no-cache ca-certificates su-exec tzdata \
&& addgroup -S opencode2api \
&& adduser -S -G opencode2api -h /var/lib/opencode2api opencode2api \
&& mkdir -p /app /var/lib/opencode2api \
&& chown -R opencode2api:opencode2api /app /var/lib/opencode2api
COPY --from=builder /out/opencode2api /usr/local/bin/opencode2api
COPY --chmod=0755 docker-entrypoint.sh /usr/local/bin/docker-entrypoint
COPY --chown=opencode2api:opencode2api config.example.json /app/config.example.json
COPY LICENSE /usr/share/licenses/opencode2api/LICENSE
LABEL org.opencontainers.image.licenses="GPL-3.0-or-later"
# LISTEN_ADDRESS / WEBUI_LISTEN_ADDRESS are intentionally unset: config.json is
# authoritative. Export them to override the configured listen addresses.
ENV CONFIG_PATH=/var/lib/opencode2api/config.json \
CONFIG_SEED_PATH= \
LISTEN_ADDRESS= \
WEBUI_LISTEN_ADDRESS= \
STATE_DIR=/var/lib/opencode2api
WORKDIR /app
EXPOSE 8080 8081
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD wget -q -O /dev/null http://127.0.0.1:8080/healthz || exit 1
ENTRYPOINT ["/usr/local/bin/docker-entrypoint"]
+13 -28
View File
@@ -1,4 +1,4 @@
// Command opencode2api starts the API gateway and its management interface.
// Command opencode2api starts the anonymous free-tier API gateway.
package main
import (
@@ -11,7 +11,6 @@ import (
"syscall"
"time"
adminui "opencode2api/internal/admin"
"opencode2api/internal/buildinfo"
"opencode2api/internal/config"
"opencode2api/internal/gateway"
@@ -25,7 +24,6 @@ func main() {
buildinfo.Version = version
configPath := flag.String("config", "config.json", "path to config.json")
listen := flag.String("listen", "", "override the configured API listen address")
webListen := flag.String("web-listen", "", "override the configured WebUI listen address")
flag.Parse()
cfg, err := config.Load(*configPath)
@@ -36,20 +34,16 @@ func main() {
if *listen != "" {
cfg.Listen = *listen
}
if *webListen != "" {
cfg.WebUI.Listen = *webListen
}
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
level := new(slog.LevelVar)
telemetry.SetLogLevel(level, cfg.Logging.Level)
hub := telemetry.NewLogHub(cfg.Logging.RingSize)
redactor := config.NewSecretRedactor()
redactor.Replace(cfg)
logger := telemetry.NewStructuredLogger(level, hub, redactor)
logger := telemetry.NewStructuredLogger(level, redactor)
monitor := telemetry.NewMonitor()
manager, err := gateway.NewRuntimeManager(ctx, *configPath, cfg, logger, monitor, hub, redactor, level)
manager, err := gateway.NewRuntimeManager(ctx, *configPath, cfg, logger, monitor, redactor, level)
if err != nil {
logger.Error("failed to initialize runtime", "component", "runtime", "event", "runtime_initialization_failed", "error", err)
os.Exit(1)
@@ -57,34 +51,25 @@ func main() {
defer manager.Shutdown()
apiServer := &http.Server{
Addr: cfg.Listen, Handler: manager.Handler(), ReadHeaderTimeout: 15 * time.Second, IdleTimeout: 120 * time.Second,
}
servers := []*http.Server{apiServer}
go serveHTTP(cancel, logger, apiServer, "api")
if cfg.WebUI.Enabled {
admin := adminui.New(manager, monitor, hub, logger)
webServer := &http.Server{
Addr: cfg.WebUI.Listen, Handler: admin.Handler(), ReadHeaderTimeout: 15 * time.Second, IdleTimeout: 120 * time.Second,
}
servers = append(servers, webServer)
go serveHTTP(cancel, logger, webServer, "webui")
Addr: cfg.Listen,
Handler: manager.Handler(),
ReadHeaderTimeout: 15 * time.Second,
IdleTimeout: 120 * time.Second,
}
go serveHTTP(cancel, logger, apiServer)
<-ctx.Done()
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 15*time.Second)
defer shutdownCancel()
for _, server := range servers {
if err := server.Shutdown(shutdownCtx); err != nil {
logger.Error("graceful shutdown failed", "component", "server", "event", "shutdown_failed", "address", server.Addr, "error", err)
}
if err := apiServer.Shutdown(shutdownCtx); err != nil {
logger.Error("graceful shutdown failed", "component", "server", "event", "shutdown_failed", "address", apiServer.Addr, "error", err)
}
}
func serveHTTP(cancel context.CancelFunc, logger *slog.Logger, server *http.Server, component string) {
logger.Info("server listening", "component", component, "event", "server_started", "address", server.Addr, "version", buildinfo.Version)
func serveHTTP(cancel context.CancelFunc, logger *slog.Logger, server *http.Server) {
logger.Info("server listening", "component", "api", "event", "server_started", "address", server.Addr, "version", buildinfo.Version)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Error("server stopped unexpectedly", "component", component, "event", "server_failed", "address", server.Addr, "error", err)
logger.Error("server stopped unexpectedly", "component", "api", "event", "server_failed", "address", server.Addr, "error", err)
cancel()
}
}
-32
View File
@@ -1,32 +0,0 @@
services:
opencode2api:
image: ghcr.io/jasonxu114514/opencode2api:${OPENCODE2API_VERSION:-latest}
pull_policy: always
restart: unless-stopped
read_only: true
security_opt:
- no-new-privileges:true
environment:
CONFIG_PATH: /var/lib/opencode2api/config.json
CONFIG_SEED_PATH: /run/config/opencode2api.json
# Empty defers to the listen addresses in config.json. Export
# OPENCODE2API_LISTEN / OPENCODE2API_WEBUI_LISTEN to override them.
LISTEN_ADDRESS: ${OPENCODE2API_LISTEN:-}
WEBUI_LISTEN_ADDRESS: ${OPENCODE2API_WEBUI_LISTEN:-}
ports:
- "${OPENCODE2API_PORT:-8080}:8080"
- "${OPENCODE2API_WEBUI_PORT:-8081}:8081"
configs:
- source: opencode2api_config
target: /run/config/opencode2api.json
volumes:
- opencode2api-state:/var/lib/opencode2api
tmpfs:
- /tmp
configs:
opencode2api_config:
file: ./config.json
volumes:
opencode2api-state:
+3 -28
View File
@@ -1,14 +1,10 @@
{
"listen": "127.0.0.1:8080",
"server_keys": ["change-this-local-key"],
"zen_keys": ["sk-your-zen-key"],
"go_keys": [],
"anonymous": false,
"proxies": ["direct"],
"proxyfile": "",
"upstream": {
"zen": "https://opencode.ai/zen",
"go": "https://opencode.ai/zen/go",
"anonymous": "https://opencode.ai/inference"
},
"retry": {
@@ -17,12 +13,11 @@
},
"models": {
"refresh_seconds": 300,
"protocols": {},
"free_only": false
"protocols": {}
},
"performance": {
"max_idle_conns": 2048,
"max_idle_conns_per_host": 256,
"max_idle_conns": 4096,
"max_idle_conns_per_host": 1024,
"max_conns_per_host": 0,
"idle_conn_timeout_seconds": 120,
"connect_timeout_seconds": 5,
@@ -32,30 +27,10 @@
},
"logging": {
"level": "info",
"ring_size": 2000,
"dump_request_bodies": false
},
"webui": {
"enabled": true,
"listen": "0.0.0.0:8081",
"username": "admin",
"password": "change-this-admin-password",
"session_ttl_minutes": 720
},
"prefer": "go",
"reasoning": {
"effort": "high",
"effort_by_model": {}
},
"rotation": {
"sota": {
"alias": "sota",
"order": ["deepseek-v4.1-flash", "glm-5.3", "grok-4.6", "kimi-k3", "qwen3.8-max"]
},
"sweet": {
"alias": "sweet",
"order": []
},
"first_output_seconds": 30
}
}
-53
View File
@@ -1,53 +0,0 @@
#!/bin/sh
set -eu
state_dir=${STATE_DIR:-/var/lib/opencode2api}
config_path=${CONFIG_PATH:-$state_dir/config.json}
config_seed_path=${CONFIG_SEED_PATH:-}
# Empty means "defer to config.json". Only an explicitly provided value becomes
# a command-line override, so the file stays authoritative as documented.
listen_address=${LISTEN_ADDRESS:-}
webui_listen_address=${WEBUI_LISTEN_ADDRESS:-}
if [ "$(id -u)" = "0" ]; then
mkdir -p "$state_dir"
chown opencode2api:opencode2api "$state_dir"
exec su-exec opencode2api:opencode2api "$0" "$@"
fi
if [ "$#" -gt 0 ]; then
exec "$@"
fi
# The example config binds the API to loopback, which is unreachable from
# outside a container through published ports. Rewrite only that exact default
# while seeding; any other address is left exactly as the operator wrote it.
seed_container_listen() {
if grep -q '"listen"[[:space:]]*:[[:space:]]*"127.0.0.1:8080"' "$1"; then
sed -i 's|"listen"[[:space:]]*:[[:space:]]*"127.0.0.1:8080"|"listen": "0.0.0.0:8080"|' "$1"
printf '%s\n' "Seeded $1 with listen 0.0.0.0:8080 so it is reachable through published ports."
fi
}
if [ ! -f "$config_path" ]; then
mkdir -p "$(dirname "$config_path")"
if [ -n "$config_seed_path" ] && [ -f "$config_seed_path" ]; then
cp "$config_seed_path" "$config_path"
seed_container_listen "$config_path"
printf '%s\n' "Initialized $config_path from $config_seed_path."
else
cp /app/config.example.json "$config_path"
seed_container_listen "$config_path"
printf '%s\n' \
"config.json not found; created $config_path. Set API keys or enable anonymous mode, and change the WebUI password before use."
fi
fi
set -- /usr/local/bin/opencode2api -config "$config_path"
if [ -n "$listen_address" ]; then
set -- "$@" -listen "$listen_address"
fi
if [ -n "$webui_listen_address" ]; then
set -- "$@" -web-listen "$webui_listen_address"
fi
exec "$@"
-90
View File
@@ -1,90 +0,0 @@
# 管理控制台:模型轮转、Go 额度与 API Key
本文说明三个新增管理页面的使用方式、配置和错误处理。
## 模型与额度
管理页面 `/#model-quotas`,登录后读取 `GET /api/model-quotas`。
- 模型来自网关同步的 OpenCode Go 目录,支持搜索和复制模型 ID。
- 额度由网关使用已配置的 Go Key 查询 `https://opencode.ai/zen/go/v1/usage`。浏览器不会收到上游 Key。
- 显示 5 小时、每周、每月窗口的剩余百分比和重置时间。接口只提供共享套餐窗口,不提供独立的逐模型余额,不推算金额或可用次数。多个 Key 的额度不相加。
- 成功响应缓存 60 秒,失败缓存 15 秒;失败时保留上次成功结果并明确标记历史数据。没有成功数据时显示未知。
- 页面打开期间每 60 秒查询一次;离开页面或隐藏浏览器时停止周期查询。手动刷新也受服务端缓存约束。
依据:[OpenCode 官方额度接口源码](https://github.com/anomalyco/opencode/blob/dev/packages/console/app/src/routes/zen/go/v1/usage.ts)。该接口未列入正式 API 文档,若响应格式变化,会显示查询异常而非虚构额度。
## API Key 管理
管理页面 `/#api-keys`,支持列表、生成、自定义、重命名、启用、停用、删除和创建后复制环境变量。
- 管理的是网关的 `server_keys`,不修改 OpenCode Go 的上游 Key。
- 自动生成 192 位随机密钥;自定义密钥为 16–256 位英文字母、数字、`-`、`_` 或 `.`。
- 列表只显示名称、尾码、状态、用量和创建时间。创建后可复制完整密钥及环境变量。
- 用量按认证命中的 Key 统计请求数和 token,分近 1 小时和累计两个窗口;`GET /api/monitor` 的 `usage.server_keys` 给出同一份数据,各项之和等于聚合口径。Playground 调试流量单独归入 `playground`,不计入任何 Key。与其他监控数据一样只存于内存:热重载保留,进程重启后清零。
- 变更热应用;停用和删除后,新请求返回 401。在途请求可以完成。至少保留一个启用的 Key。
- 所有管理接口需要登录,写操作需要 CSRF Token。
- 元数据以 `server_key_metadata` 保存在原配置中,按 Key 指纹关联;已有 `server_keys` 自动兼容。
- 当前未实现按 Key 单独分配模型权限、用量配额或过期时间。
## 验证和构建
```bash
go test ./...
go test -race ./...
go vet ./...
for f in webui/js/*.js webui/js/pages/*.js; do node --input-type=module --check < "$f"; done
go build -trimpath -o opencode2api ./cmd/opencode2api
```
升级前请备份程序、配置及轮转状态,再停止服务并替换可执行文件。旧版本不认识新增的 `server_key_metadata` 和 `rotation` 字段;回退时应同时恢复旧程序和旧配置。
## SOTA / 甜点模型轮转
管理页:`/#rotation`。调用时继续使用 网关的 Base URL(默认
`http://127.0.0.1:8080/v1`)和已有 API Key,将 `model` 设为 `sota` 或
`sweet`。两个别名列入 `/v1/models`,支持 Chat Completions、Responses 和
Messages,以及这三种协议的流式输出。真实模型 ID 的原有调用路径保持不变。
- SOTA 固定成员:`deepseek-v4.1-flash`、`glm-5.3`、`grok-4.6`、`kimi-k3`、
`qwen3.8-max`,默认按上述顺序。
- 甜点组包含其余 Go 可用模型,初次以 `glm-5.3-flash` 为首,随后按名称排序。
新模型追加在末尾;下架或协议不受支持的模型保留在列表,但不参与调用。
- 每组共享一个当前模型。成功后保持位置;失败切换后,下次从新位置开始。
并发请求通过位置版本号避免旧请求把游标移回去;手动切换不打断在途回答。
- 普通错误每模型最多 3 次(包含首次),每请求最多消耗 3 个普通错误模型预算。
模型耗尽重试后暂停 15 秒。分组请求不使用原有 Key 重试、跨 Tier 降级、
自动重定向或 stale-reasoning 补发,也不因单个模型故障暂停整个 Go Key。
- 429 或明确额度错误直接跳到下一模型,不新增普通错误模型计数;已经发生的
普通错误仍计数。允许遍历整组,同一请求不重复模型。暂停时间采用 Retry-After,
未提供时为 60 秒。共享套餐额度只用于展示,不能保证换模型后就有余额。
- 整体超时沿用 `retry.timeout_seconds`。`rotation.first_output_seconds` 默认
30 秒,限制每次等待首个有效输出的时间,不限制已经开始的正常流式回答。
- 流式 start/role/usage 前导事件会等到有效输出或正常结束后再提交。提交前错误
可重试;提交后中断会保留已输出内容、追加协议对应的 SSE 错误并结束,随后
推进当前位置,下一次请求使用下一个模型。不会在同一响应里拼接替代答案。
调用方取消不会触发暂停或切换。
- 响应 JSON / SSE 的 `model` 保持请求别名,`X-Resolved-Model` 标记实际模型。
用量按实际上游模型记录。轮转日志与管理页面仅保留分类后的错误原因,
不记录上游错误正文、请求正文或密钥。最近保留 100 条尝试和每组 30 条切换。
配置保存于 `config.json` 的 `rotation` 字段:`sota` / `sweet` 各有 `alias`
和 `order`;状态单独原子写入 `config.json.rotation.json`(0600),包括当前
位置、版本、动态追加的顺序、暂停期限和最近记录。修改 Key 或其他配置时
沿用同一个轮转状态管理器。页面展示状态写入失败提示,首次无法写入则拒绝启动。
管理接口均需要现有管理 Session,写入另需 CSRF:
- `GET /api/rotation`:分组配置、可用状态、暂停期限、切换和尝试记录。
- `PUT /api/rotation`:提交 `sota` / `sweet` 的 `alias`、完整 `order`,以及
`first_output_seconds`;别名不得重复或与真实模型 ID 冲突,成员不得跨组。
- `POST /api/rotation/current`:`{"group":"sota","model":"glm-5.3"}`;立即
修改当前模型并解除该模型的临时暂停。
验证:`go test -race ./...`、`go vet ./...`、`for f in webui/js/*.js webui/js/pages/*.js; do node --input-type=module --check < "$f"; done`。
模拟上游测试覆盖 9 次普通错误上限、超过 3 个额度跳过、混合错误预算、
Retry-After、单个模型故障不影响 Key、三种入口协议的跨协议转换、成功保持、
别名发现与用量归属、畸形响应、输出前错误、首个输出超时、输出后故障、
调用方取消、在途回答不受手动切换影响、并发版本保护、下架和重启恢复。
上线前建议使用独立配置及端口验证管理登录、CSRF、页面排序与保存、别名冲突、
Key 配置热更新和真实 Go 请求。测试与正式配置、凭证、日志及运行状态不应提交到仓库。
-4
View File
@@ -1,7 +1,3 @@
module opencode2api
go 1.24
require golang.org/x/crypto v0.41.0
require golang.org/x/sys v0.35.0 // indirect
-4
View File
@@ -1,4 +0,0 @@
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
-187
View File
@@ -1,187 +0,0 @@
package admin
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"net/http"
"strings"
"time"
"opencode2api/internal/config"
"opencode2api/internal/httpx"
"opencode2api/internal/telemetry"
)
type APIKeyView struct {
ID string `json:"id"`
Name string `json:"name"`
Display string `json:"display"`
Enabled bool `json:"enabled"`
CreatedAt *time.Time `json:"created_at,omitempty"`
Usage APIKeyUsage `json:"usage"`
}
// APIKeyUsage is in-memory like the rest of the monitor: it restarts from zero
// with the process and survives hot reloads.
type APIKeyUsage struct {
Lifetime telemetry.ServerKeyUsage `json:"lifetime"`
Window telemetry.ServerKeyUsage `json:"last_hour"`
}
func (a *Server) apiKeyViews(cfg config.Config) []APIKeyView {
lifetime, window := a.monitor.ServerKeyUsage()
items := make([]APIKeyView, 0, len(cfg.ServerKeys))
for i, key := range cfg.ServerKeys {
id := config.Fingerprint(key)
meta := cfg.ServerKeyMetadata[id]
name := meta.Name
if name == "" {
name = fmt.Sprintf("已有 Key %d", i+1)
}
item := APIKeyView{
ID: id, Name: name, Display: config.MaskValue(key), Enabled: !meta.Disabled,
Usage: APIKeyUsage{Lifetime: lifetime[id], Window: window[id]},
}
if !meta.CreatedAt.IsZero() {
created := meta.CreatedAt
item.CreatedAt = &created
}
items = append(items, item)
}
return items
}
func (a *Server) handleListAPIKeys(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Cache-Control", "no-store")
httpx.WriteJSON(w, http.StatusOK, map[string]any{"keys": a.apiKeyViews(a.manager.Config())})
}
func validateKeyName(name string) error {
if name == "" || len([]rune(name)) > 80 {
return errors.New("名称需为 1–80 个字符")
}
return nil
}
func addAPIKey(cfg *config.Config, name, key string) error {
if err := validateKeyName(name); err != nil {
return err
}
if len(key) < 16 || len(key) > 256 {
return errors.New("自定义 Key 需为 16–256 位")
}
for _, ch := range key {
if !((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '-' || ch == '_' || ch == '.') {
return errors.New("Key 仅支持英文字母、数字、短横线、下划线和点")
}
}
if len(cfg.ServerKeys) >= 200 {
return errors.New("最多创建 200 个 API Key")
}
id := config.Fingerprint(key)
for _, existing := range cfg.ServerKeys {
if config.Fingerprint(existing) == id {
return errors.New("此 API Key 已存在")
}
}
if cfg.ServerKeyMetadata == nil {
cfg.ServerKeyMetadata = map[string]config.ServerKeyMetadata{}
}
cfg.ServerKeys = append(cfg.ServerKeys, key)
cfg.ServerKeyMetadata[id] = config.ServerKeyMetadata{Name: name, CreatedAt: time.Now().UTC()}
return nil
}
func (a *Server) handleCreateAPIKey(w http.ResponseWriter, r *http.Request) {
var input struct {
Name string `json:"name"`
Value string `json:"value"`
}
if err := decodeAdminJSON(w, r, &input); err != nil {
writeAdminError(w, 400, "invalid_request", err.Error())
return
}
key := input.Value
if key == "" {
var random [24]byte
if _, err := rand.Read(random[:]); err != nil {
writeAdminError(w, 500, "generation_failed", "无法生成密钥")
return
}
key = "sk-local-" + hex.EncodeToString(random[:])
}
_, err := a.manager.Update(func(cfg *config.Config) error { return addAPIKey(cfg, strings.TrimSpace(input.Name), key) })
if err != nil {
writeAdminError(w, 400, "key_create_failed", a.manager.Redact(err.Error()))
return
}
w.Header().Set("Cache-Control", "no-store")
httpx.WriteJSON(w, 201, map[string]any{"key": key, "keys": a.apiKeyViews(a.manager.Config())})
}
func changeAPIKey(cfg *config.Config, id string, name *string, enabled *bool, remove bool) error {
index := -1
for i, key := range cfg.ServerKeys {
if config.Fingerprint(key) == id {
index = i
break
}
}
if index < 0 {
return errors.New("API Key 不存在,请刷新列表")
}
if cfg.ServerKeyMetadata == nil {
cfg.ServerKeyMetadata = map[string]config.ServerKeyMetadata{}
}
if remove {
cfg.ServerKeys = append(cfg.ServerKeys[:index], cfg.ServerKeys[index+1:]...)
delete(cfg.ServerKeyMetadata, id)
} else {
meta := cfg.ServerKeyMetadata[id]
if name != nil {
value := strings.TrimSpace(*name)
if err := validateKeyName(value); err != nil {
return err
}
meta.Name = value
}
if enabled != nil {
meta.Disabled = !*enabled
}
cfg.ServerKeyMetadata[id] = meta
}
if cfg.FirstEnabledServerKey() == "" {
return errors.New("至少保留一个启用的 API Key,请先创建替代密钥")
}
return nil
}
func (a *Server) handleUpdateAPIKey(w http.ResponseWriter, r *http.Request) {
var input struct {
Name *string `json:"name"`
Enabled *bool `json:"enabled"`
}
if err := decodeAdminJSON(w, r, &input); err != nil {
writeAdminError(w, 400, "invalid_request", err.Error())
return
}
_, err := a.manager.Update(func(cfg *config.Config) error {
return changeAPIKey(cfg, r.PathValue("id"), input.Name, input.Enabled, false)
})
if err != nil {
writeAdminError(w, 400, "key_update_failed", a.manager.Redact(err.Error()))
return
}
a.handleListAPIKeys(w, r)
}
func (a *Server) handleDeleteAPIKey(w http.ResponseWriter, r *http.Request) {
_, err := a.manager.Update(func(cfg *config.Config) error { return changeAPIKey(cfg, r.PathValue("id"), nil, nil, true) })
if err != nil {
writeAdminError(w, 400, "key_delete_failed", a.manager.Redact(err.Error()))
return
}
a.handleListAPIKeys(w, r)
}
-270
View File
@@ -1,270 +0,0 @@
package admin
import (
"context"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"net"
"net/http"
"net/url"
"strings"
"time"
"opencode2api/internal/config"
"opencode2api/internal/httpx"
)
const adminCookieName = "opencode2api_session"
type adminSession struct {
Username string
AuthVersion string
CSRF string
Expires time.Time
}
type loginWindow struct {
Started time.Time
Count int
}
func (a *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
client := clientIP(r)
if !a.allowLogin(client) {
writeAdminError(w, http.StatusTooManyRequests, "rate_limited", "too many login attempts; try again later")
return
}
var input struct {
Username string `json:"username"`
Password string `json:"password"`
}
if err := decodeAdminJSON(w, r, &input); err != nil {
writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error())
return
}
cfg := a.manager.Config()
usernameMatch := len(input.Username) == len(cfg.WebUI.Username) && subtle.ConstantTimeCompare([]byte(input.Username), []byte(cfg.WebUI.Username)) == 1
passwordMatch := config.VerifyPassword(cfg.WebUI.PasswordHash, input.Password)
if !usernameMatch || !passwordMatch {
a.recordLoginFailure(client)
a.logger.Warn("admin login failed", "component", "auth", "event", "login_failed", "client_ip", client)
writeAdminError(w, http.StatusUnauthorized, "invalid_credentials", "invalid username or password")
return
}
token, err := randomToken(32)
if err != nil {
writeAdminError(w, http.StatusInternalServerError, "internal_error", "could not create session")
return
}
csrf, err := randomToken(24)
if err != nil {
writeAdminError(w, http.StatusInternalServerError, "internal_error", "could not create session")
return
}
expires := time.Now().Add(time.Duration(cfg.WebUI.SessionTTLMinutes) * time.Minute)
a.mu.Lock()
delete(a.attempts, client)
a.cleanupSessionsLocked(time.Now())
if len(a.sessions) >= 2048 {
a.removeEarliestSessionLocked()
}
a.sessions[tokenDigest(token)] = adminSession{Username: cfg.WebUI.Username, AuthVersion: config.Fingerprint(cfg.WebUI.PasswordHash), CSRF: csrf, Expires: expires}
a.mu.Unlock()
http.SetCookie(w, &http.Cookie{Name: adminCookieName, Value: token, Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, Expires: expires, MaxAge: int(time.Until(expires).Seconds()), Secure: requestIsSecure(r)})
w.Header().Set("Cache-Control", "no-store")
a.logger.Info("admin login succeeded", "component", "auth", "event", "login_succeeded", "client_ip", client)
httpx.WriteJSON(w, http.StatusOK, map[string]any{"username": cfg.WebUI.Username, "csrf_token": csrf, "expires_at": expires.UTC()})
}
func (a *Server) handleSession(w http.ResponseWriter, r *http.Request) {
session, _ := sessionFromContext(r)
w.Header().Set("Cache-Control", "no-store")
httpx.WriteJSON(w, http.StatusOK, map[string]any{"authenticated": true, "username": session.Username, "csrf_token": session.CSRF, "expires_at": session.Expires.UTC()})
}
func (a *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
cookie, _ := r.Cookie(adminCookieName)
if cookie != nil {
a.mu.Lock()
delete(a.sessions, tokenDigest(cookie.Value))
a.mu.Unlock()
}
http.SetCookie(w, &http.Cookie{Name: adminCookieName, Value: "", Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1, Secure: requestIsSecure(r)})
w.WriteHeader(http.StatusNoContent)
}
type sessionContextKey struct{}
func (a *Server) authenticate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(adminCookieName)
if err != nil || cookie.Value == "" {
writeAdminError(w, http.StatusUnauthorized, "authentication_required", "login required")
return
}
now := time.Now()
a.mu.Lock()
session, ok := a.sessions[tokenDigest(cookie.Value)]
if ok && now.After(session.Expires) {
delete(a.sessions, tokenDigest(cookie.Value))
ok = false
}
a.mu.Unlock()
if !ok {
writeAdminError(w, http.StatusUnauthorized, "authentication_required", "session expired or invalid")
return
}
cfg := a.manager.Config()
if session.Username != cfg.WebUI.Username || session.AuthVersion != config.Fingerprint(cfg.WebUI.PasswordHash) {
writeAdminError(w, http.StatusUnauthorized, "authentication_required", "session is no longer valid")
return
}
r = r.WithContext(context.WithValue(r.Context(), sessionContextKey{}, session))
next.ServeHTTP(w, r)
})
}
func sessionFromContext(r *http.Request) (adminSession, bool) {
session, ok := r.Context().Value(sessionContextKey{}).(adminSession)
return session, ok
}
func (a *Server) csrf(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, ok := sessionFromContext(r)
if !ok || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-CSRF-Token")), []byte(session.CSRF)) != 1 {
writeAdminError(w, http.StatusForbidden, "csrf_failed", "invalid CSRF token")
return
}
if origin := r.Header.Get("Origin"); origin != "" {
parsed, err := url.Parse(origin)
expectedScheme := "http"
if requestIsSecure(r) {
expectedScheme = "https"
}
if err != nil || !strings.EqualFold(parsed.Host, r.Host) || !strings.EqualFold(parsed.Scheme, expectedScheme) {
writeAdminError(w, http.StatusForbidden, "origin_failed", "request origin does not match this server")
return
}
}
next.ServeHTTP(w, r)
})
}
func (a *Server) handleAccount(w http.ResponseWriter, r *http.Request) {
var input struct {
CurrentPassword string `json:"current_password"`
Username string `json:"username"`
NewPassword string `json:"new_password"`
}
if err := decodeAdminJSON(w, r, &input); err != nil {
writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error())
return
}
cfg := a.manager.Config()
if !config.VerifyPassword(cfg.WebUI.PasswordHash, input.CurrentPassword) {
writeAdminError(w, http.StatusForbidden, "verification_failed", "current password is incorrect")
return
}
if username := strings.TrimSpace(input.Username); username != "" {
cfg.WebUI.Username = username
}
if input.NewPassword != "" {
cfg.WebUI.Password = input.NewPassword
}
if _, err := a.manager.Apply(cfg, true); err != nil {
writeAdminError(w, http.StatusBadRequest, "account_update_failed", err.Error())
return
}
a.mu.Lock()
a.sessions = make(map[string]adminSession)
a.mu.Unlock()
http.SetCookie(w, &http.Cookie{Name: adminCookieName, Value: "", Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1, Secure: requestIsSecure(r)})
a.logger.Info("admin account updated", "component", "auth", "event", "account_updated", "client_ip", clientIP(r))
httpx.WriteJSON(w, http.StatusOK, map[string]any{"updated": true, "reauthenticate": true})
}
func (a *Server) allowLogin(client string) bool {
a.mu.Lock()
defer a.mu.Unlock()
now := time.Now()
if len(a.attempts) > 1024 {
for address, candidate := range a.attempts {
if now.Sub(candidate.Started) > 5*time.Minute {
delete(a.attempts, address)
}
}
}
if _, exists := a.attempts[client]; !exists && len(a.attempts) >= 4096 {
return false
}
window := a.attempts[client]
if window.Started.IsZero() || now.Sub(window.Started) > 5*time.Minute {
return true
}
return window.Count < 5
}
func (a *Server) recordLoginFailure(client string) {
a.mu.Lock()
defer a.mu.Unlock()
now := time.Now()
window := a.attempts[client]
if window.Started.IsZero() || now.Sub(window.Started) > 5*time.Minute {
window = loginWindow{Started: now}
}
window.Count++
a.attempts[client] = window
}
func (a *Server) cleanupSessionsLocked(now time.Time) {
for token, session := range a.sessions {
if now.After(session.Expires) {
delete(a.sessions, token)
}
}
}
func (a *Server) removeEarliestSessionLocked() {
var earliestToken string
var earliest time.Time
for token, session := range a.sessions {
if earliestToken == "" || session.Expires.Before(earliest) {
earliestToken, earliest = token, session.Expires
}
}
if earliestToken != "" {
delete(a.sessions, earliestToken)
}
}
func randomToken(length int) (string, error) {
data := make([]byte, length)
if _, err := rand.Read(data); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(data), nil
}
func tokenDigest(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
func clientIP(r *http.Request) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err == nil {
return host
}
return r.RemoteAddr
}
func requestIsSecure(r *http.Request) bool {
if r == nil {
return false
}
return r.TLS != nil || strings.EqualFold(strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")), "https")
}
-46
View File
@@ -1,46 +0,0 @@
package admin
import (
"net/http"
"opencode2api/internal/httpx"
)
func (a *Server) handleAvailability(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
httpx.WriteJSON(w, http.StatusOK, map[string]any{"models": a.manager.AvailabilitySnapshot()})
}
func (a *Server) handleRestoreModel(w http.ResponseWriter, r *http.Request) {
var input struct {
Model string `json:"model"`
}
if err := decodeAdminJSON(w, r, &input); err != nil {
writeAdminError(w, 400, "invalid_request", err.Error())
return
}
if err := a.manager.RestoreModel(input.Model); err != nil {
writeAdminError(w, 400, "restore_failed", a.manager.Redact(err.Error()))
return
}
a.handleAvailability(w, r)
}
func (a *Server) handleManualModel(w http.ResponseWriter, r *http.Request) {
var input struct {
Model string `json:"model"`
Manual *bool `json:"manual"`
}
if err := decodeAdminJSON(w, r, &input); err != nil {
writeAdminError(w, 400, "invalid_request", err.Error())
return
}
if input.Manual == nil {
writeAdminError(w, 400, "invalid_request", "manual is required")
return
}
if err := a.manager.SetManualModel(input.Model, *input.Manual); err != nil {
writeAdminError(w, 400, "manual_failed", a.manager.Redact(err.Error()))
return
}
a.handleAvailability(w, r)
}
-270
View File
@@ -1,270 +0,0 @@
package admin
import (
"bytes"
"encoding/json"
"net/http"
"strings"
"time"
"opencode2api/internal/config"
"opencode2api/internal/gateway"
"opencode2api/internal/httpx"
"opencode2api/internal/jsonutil"
modelcatalog "opencode2api/internal/models"
"opencode2api/internal/protocol"
"opencode2api/internal/telemetry"
)
// DebugKeySelection tells the Playground whether to use normal routing or to
// exercise one explicitly chosen upstream key.
type DebugKeySelection struct {
Mode string `json:"mode,omitempty"`
Tier config.Tier `json:"tier,omitempty"`
ID string `json:"id,omitempty"`
}
type DebugInferenceRequest struct {
Protocol protocol.Protocol `json:"protocol"`
Key DebugKeySelection `json:"key,omitempty"`
Request map[string]any `json:"request"`
}
type DebugInferenceResult struct {
OK bool `json:"ok"`
HTTPStatus int `json:"http_status"`
DurationMS int64 `json:"duration_ms"`
RequestID string `json:"request_id,omitempty"`
Route modelcatalog.RouteDiagnostic `json:"route"`
SelectedKey *gateway.DebugKeyView `json:"selected_key,omitempty"`
KeyTest string `json:"key_test,omitempty"`
Response any `json:"response"`
}
func (a *Server) handleDebugModels(w http.ResponseWriter, _ *http.Request) {
models, metadata := a.manager.DebugModels()
catalog := a.manager.Resources().Models
keys := a.manager.DebugKeys()
a.mu.Lock()
last := a.lastInference
a.mu.Unlock()
w.Header().Set("Cache-Control", "no-store")
httpx.WriteJSON(w, http.StatusOK, map[string]any{"models": models, "keys": keys, "metadata": metadata, "catalog": catalog, "last_inference": last})
}
func (a *Server) handleDebugInference(w http.ResponseWriter, r *http.Request) {
if !a.allowDebug(clientIP(r)) {
writeAdminError(w, http.StatusTooManyRequests, "debug_rate_limited", "too many Playground requests; retry in one minute")
return
}
var input DebugInferenceRequest
if err := decodeAdminJSON(w, r, &input); err != nil {
writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error())
return
}
if !protocol.Valid(input.Protocol) {
writeAdminError(w, http.StatusBadRequest, "invalid_protocol", "protocol must be chat, responses, or anthropic")
return
}
if input.Request == nil {
writeAdminError(w, http.StatusBadRequest, "invalid_request", "request must be a JSON object")
return
}
payload := jsonutil.CloneMap(input.Request)
payload["stream"] = false
model := jsonutil.StringAt(payload, "model")
if model == "" {
writeAdminError(w, http.StatusBadRequest, "invalid_request", "request.model is required")
return
}
if input.Key.Mode == "" {
input.Key.Mode = "auto"
}
if input.Key.Mode != "auto" && input.Key.Mode != "selected" {
writeAdminError(w, http.StatusBadRequest, "invalid_key_mode", "key.mode must be auto or selected")
return
}
var selectedKey *gateway.DebugKeyView
if input.Key.Mode == "selected" {
selectedKey = a.manager.DebugKey(input.Key.Tier, input.Key.ID)
if selectedKey == nil {
writeAdminError(w, http.StatusBadRequest, "unknown_key_id", "selected key is not configured")
return
}
}
route := a.manager.DebugRoute(model, input.Protocol)
if selectedKey != nil {
selected, routeErr := a.manager.DebugRouteForTier(model, selectedKey.Tier)
if routeErr != nil {
writeAdminError(w, http.StatusBadRequest, "model_unavailable_for_key_tier", routeErr.Error())
return
}
route = selected
}
encoded, err := json.Marshal(payload)
if err != nil {
writeAdminError(w, http.StatusBadRequest, "invalid_request", "request contains unsupported JSON values")
return
}
path := protocol.Path(input.Protocol)
trace := &telemetry.RequestMeta{}
ctx := telemetry.WithRequestMeta(gateway.WithDiagnosticRequest(r.Context()), trace)
request, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://gateway.local"+path, bytes.NewReader(encoded))
if err != nil {
writeAdminError(w, http.StatusInternalServerError, "debug_request_failed", "could not construct Gateway request")
return
}
cfg := a.manager.Config()
if cfg.FirstEnabledServerKey() == "" {
writeAdminError(w, http.StatusServiceUnavailable, "debug_unavailable", "no local server key is configured")
return
}
request.Header.Set("Authorization", "Bearer "+cfg.FirstEnabledServerKey())
if selectedKey != nil {
request = request.WithContext(gateway.WithDebugKeyOverride(request.Context(), gateway.DebugKeyOverride{Tier: selectedKey.Tier, KeyID: selectedKey.ID}))
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
recorder := newDebugResponseRecorder()
started := time.Now()
a.manager.Handler().ServeHTTP(recorder, request)
duration := time.Since(started)
requestID := recorder.Header().Get("x-request-id")
if trace.Channel != "" {
route.Anonymous = trace.Anonymous
route.Tier = config.Tier(trace.Tier)
route.KeyID = trace.KeyID
route.Channel = trace.Channel
route.Attempts = trace.Attempts
route.NativeProtocol = trace.Protocol
}
var raw any
if json.Unmarshal(recorder.body.Bytes(), &raw) != nil {
raw = recorder.body.String()
}
raw = sanitizeDebugValue(raw, a.manager.Redact)
keyTest := ""
if selectedKey != nil {
if current := a.manager.DebugKey(selectedKey.Tier, selectedKey.ID); current != nil {
selectedKey = current
}
keyTest = classifyKeyTest(recorder.status, trace.AttemptOutcome)
}
result := DebugInferenceResult{
OK: recorder.status >= 200 && recorder.status < 300, HTTPStatus: recorder.status,
DurationMS: max(duration.Milliseconds(), 0), RequestID: requestID, Route: route,
SelectedKey: selectedKey, KeyTest: keyTest, Response: raw,
}
a.mu.Lock()
a.lastInference = &result
a.mu.Unlock()
w.Header().Set("Cache-Control", "no-store")
httpx.WriteJSON(w, http.StatusOK, result)
}
type debugResponseRecorder struct {
header http.Header
body bytes.Buffer
status int
}
func newDebugResponseRecorder() *debugResponseRecorder {
return &debugResponseRecorder{header: make(http.Header), status: http.StatusOK}
}
func (recorder *debugResponseRecorder) Header() http.Header { return recorder.header }
func (recorder *debugResponseRecorder) WriteHeader(status int) {
if recorder.status != http.StatusOK || status == http.StatusOK {
return
}
recorder.status = status
}
func (recorder *debugResponseRecorder) Write(data []byte) (int, error) {
return recorder.body.Write(data)
}
func sanitizeDebugValue(value any, redact func(string) string) any {
switch current := value.(type) {
case map[string]any:
result := make(map[string]any, len(current))
for key, item := range current {
lower := strings.ToLower(key)
if sensitiveDebugKey(lower) {
result[key] = "***"
continue
}
result[key] = sanitizeDebugValue(item, redact)
}
return result
case []any:
result := make([]any, len(current))
for index, item := range current {
result[index] = sanitizeDebugValue(item, redact)
}
return result
case string:
return redact(current)
default:
return value
}
}
func (a *Server) allowDebug(client string) bool {
a.mu.Lock()
defer a.mu.Unlock()
now := time.Now()
window := a.debugAttempts[client]
if window.Started.IsZero() || now.Sub(window.Started) >= time.Minute {
window = loginWindow{Started: now}
}
if window.Count >= 12 {
return false
}
window.Count++
a.debugAttempts[client] = window
if len(a.debugAttempts) > 4096 {
for key, candidate := range a.debugAttempts {
if now.Sub(candidate.Started) >= time.Minute {
delete(a.debugAttempts, key)
}
}
}
return true
}
// classifyKeyTest turns a per-key diagnostic into a verdict about that key.
// Only statuses that are unambiguous about the credential are reported as key
// problems: a 4xx request-shape error says nothing about the key, and a 5xx may
// be entirely unrelated to it.
func classifyKeyTest(status int, attemptOutcome string) string {
switch {
case attemptOutcome == "transport_error":
return "transport_error"
case status >= 200 && status < 300:
return "usable"
case status == http.StatusUnauthorized || status == http.StatusForbidden:
return "rejected"
case status == http.StatusTooManyRequests:
return "rate_limited"
case status == 0:
return "unavailable"
case status >= 500:
return "upstream_error"
default:
return "request_error"
}
}
func sensitiveDebugKey(key string) bool {
for _, hint := range []string{
"authorization", "cookie", "password", "secret", "api_key", "api-key", "x-api-key",
"access_token", "refresh_token", "set-cookie", "credential",
} {
if strings.Contains(key, hint) {
return true
}
}
return false
}
-171
View File
@@ -1,171 +0,0 @@
package admin
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
"time"
"opencode2api/internal/config"
"opencode2api/internal/httpx"
)
type quotaWindow struct {
Status string `json:"status"`
UsedPercent float64 `json:"used_percent"`
RemainingPercent float64 `json:"remaining_percent"`
ResetsAt time.Time `json:"resets_at"`
}
type quotaAccount struct {
ID string `json:"id"`
Display string `json:"display"`
Status string `json:"status"`
Error string `json:"error,omitempty"`
FetchedAt *time.Time `json:"fetched_at,omitempty"`
CheckedAt time.Time `json:"checked_at"`
Windows map[string]quotaWindow `json:"windows,omitempty"`
}
type quotaCacheEntry struct {
Account quotaAccount
Expires time.Time
}
// The first-party endpoint returns subscription-wide percentages, not balances
// for individual models. Never infer model dollars or sum keys' shared quotas.
// Reference: anomalyco/opencode packages/console/app/src/routes/zen/go/v1/usage.ts
func decodeQuota(reader io.Reader) (map[string]quotaWindow, error) {
var body struct {
Usage map[string]struct {
Status string `json:"status"`
Percent *float64 `json:"percent"`
ResetsAt time.Time `json:"resetsAt"`
} `json:"usage"`
}
if err := json.NewDecoder(io.LimitReader(reader, 1<<20)).Decode(&body); err != nil {
return nil, errors.New("OpenCode 返回的额度格式无法识别")
}
result := map[string]quotaWindow{}
for _, name := range []string{"rolling", "weekly", "monthly"} {
item, ok := body.Usage[name]
if !ok || item.Percent == nil || *item.Percent < 0 || *item.Percent > 100 || item.ResetsAt.IsZero() || (item.Status != "ok" && item.Status != "rate-limited") {
return nil, errors.New("OpenCode 返回的额度窗口不完整")
}
result[name] = quotaWindow{Status: item.Status, UsedPercent: *item.Percent, RemainingPercent: 100 - *item.Percent, ResetsAt: item.ResetsAt}
}
return result, nil
}
func fetchQuota(ctx context.Context, endpoint, key string) (map[string]quotaWindow, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, errors.New("额度查询地址无效")
}
req.Header.Set("Authorization", "Bearer "+key)
req.Header.Set("User-Agent", "opencode2api-admin/1.0")
req.Header.Set("Accept", "application/json")
req.Header.Set("x-opencode-session", "opencode2api-quota-"+config.Fingerprint(key))
client := &http.Client{Timeout: 12 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }}
resp, err := client.Do(req)
if err != nil {
return nil, errors.New("暂时无法连接 OpenCode,请稍后刷新")
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
switch resp.StatusCode {
case 401:
return nil, errors.New("Go API Key 无效或已被撤销")
case 403:
return nil, errors.New("此 Key 未获准读取 Go 套餐额度")
case 429:
return nil, errors.New("额度查询过于频繁,请稍后刷新")
default:
return nil, fmt.Errorf("OpenCode 额度接口返回 HTTP %d", resp.StatusCode)
}
}
return decodeQuota(resp.Body)
}
func refreshQuota(ctx context.Context, endpoint, key string, previous quotaCacheEntry) quotaCacheEntry {
now := time.Now().UTC()
account := previous.Account
account.ID, account.Display = config.Fingerprint(key), config.MaskValue(key)
account.CheckedAt = now
windows, err := fetchQuota(ctx, endpoint, key)
if err != nil {
account.Status, account.Error = "unavailable", err.Error()
if account.FetchedAt != nil {
account.Status = "stale"
}
return quotaCacheEntry{Account: account, Expires: now.Add(15 * time.Second)}
}
account.Status, account.Error, account.Windows = "ok", "", windows
account.FetchedAt = &now
return quotaCacheEntry{Account: account, Expires: now.Add(60 * time.Second)}
}
func (a *Server) handleModelQuotas(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
cfg := a.manager.Config()
endpoint := strings.TrimRight(cfg.Upstream.Go, "/") + "/v1/usage"
accounts := make([]quotaAccount, len(cfg.GoKeys))
// Coalesce refreshes from multiple browser tabs; at most four upstream
// queries run at a time. The cache is pruned when upstream credentials change.
a.quotaMu.Lock()
if a.quotaCache == nil {
a.quotaCache = map[string]quotaCacheEntry{}
}
entries := make([]quotaCacheEntry, len(cfg.GoKeys))
var wg sync.WaitGroup
sem := make(chan struct{}, 4)
for i, key := range cfg.GoKeys {
cacheID := endpoint + "|" + config.Fingerprint(key)
previous := a.quotaCache[cacheID]
if time.Now().Before(previous.Expires) {
entries[i] = previous
continue
}
wg.Add(1)
go func(i int, key string, previous quotaCacheEntry) {
defer wg.Done()
select {
case sem <- struct{}{}:
defer func() { <-sem }()
case <-r.Context().Done():
return
}
entries[i] = refreshQuota(r.Context(), endpoint, key, previous)
}(i, key, previous)
}
wg.Wait()
newCache := map[string]quotaCacheEntry{}
for i, key := range cfg.GoKeys {
newCache[endpoint+"|"+config.Fingerprint(key)] = entries[i]
accounts[i] = entries[i].Account
}
a.quotaCache = newCache
a.quotaMu.Unlock()
all, _ := a.manager.DebugModels()
type modelView struct {
ID string `json:"id"`
Protocol string `json:"protocol"`
}
models := []modelView{}
for _, model := range all {
if model.AvailableGo && model.RouteError == "" {
protocol := model.NativeProtocols[config.TierGo]
models = append(models, modelView{ID: model.Model, Protocol: string(protocol)})
}
}
httpx.WriteJSON(w, 200, map[string]any{
"models": models, "accounts": accounts, "scope": "shared_subscription", "source": endpoint,
"cache_seconds": 60, "catalog": a.manager.Resources().Models,
"note": "OpenCode 返回套餐共享额度,未提供逐模型独立余额;多个 Go Key 可能属于同一套餐,不能相加。百分比由上游取整。",
})
}
-63
View File
@@ -1,63 +0,0 @@
package admin
import (
"fmt"
"net/http"
"opencode2api/internal/config"
"opencode2api/internal/httpx"
"slices"
)
func (a *Server) handleRotation(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
httpx.WriteJSON(w, 200, a.manager.RotationSnapshot())
}
func (a *Server) handleSaveRotation(w http.ResponseWriter, r *http.Request) {
var input config.RotationConfig
if err := decodeAdminJSON(w, r, &input); err != nil {
writeAdminError(w, 400, "invalid_request", err.Error())
return
}
_, err := a.manager.Update(func(cfg *config.Config) error {
if err := input.Validate(nil); err != nil {
return err
}
state := a.manager.RotationSnapshot()
for i, g := range state.Groups {
order := input.SOTA.Order
if i == 1 {
order = input.Sweet.Order
}
if len(order) != len(g.Order) {
return fmt.Errorf("模型列表已更新,请刷新后重新排序")
}
for _, v := range order {
if !slices.Contains(g.Order, v) {
return fmt.Errorf("只能调整组内模型的顺序")
}
}
}
cfg.Rotation = input
return nil
})
if err != nil {
writeAdminError(w, 400, "rotation_rejected", a.manager.Redact(err.Error()))
return
}
a.handleRotation(w, r)
}
func (a *Server) handleSelectRotation(w http.ResponseWriter, r *http.Request) {
var input struct {
Group string `json:"group"`
Model string `json:"model"`
}
if err := decodeAdminJSON(w, r, &input); err != nil {
writeAdminError(w, 400, "invalid_request", err.Error())
return
}
if err := a.manager.SelectRotation(input.Group, input.Model); err != nil {
writeAdminError(w, 400, "rotation_rejected", a.manager.Redact(err.Error()))
return
}
a.handleRotation(w, r)
}
-395
View File
@@ -1,395 +0,0 @@
// Package admin serves configuration, authentication, diagnostics, and the WebUI.
package admin
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"log/slog"
"net/http"
"strconv"
"strings"
"sync"
"time"
"opencode2api/internal/buildinfo"
"opencode2api/internal/config"
"opencode2api/internal/gateway"
"opencode2api/internal/httpx"
"opencode2api/internal/telemetry"
"opencode2api/webui"
)
type Server struct {
manager *gateway.RuntimeManager
monitor *telemetry.Monitor
logs *telemetry.LogHub
logger *slog.Logger
mu sync.Mutex
sessions map[string]adminSession
attempts map[string]loginWindow
debugAttempts map[string]loginWindow
lastInference *DebugInferenceResult
quotaMu sync.Mutex
quotaCache map[string]quotaCacheEntry
}
func New(manager *gateway.RuntimeManager, monitor *telemetry.Monitor, logs *telemetry.LogHub, logger *slog.Logger) *Server {
return &Server{
manager: manager, monitor: monitor, logs: logs, logger: logger, sessions: make(map[string]adminSession),
attempts: make(map[string]loginWindow), debugAttempts: make(map[string]loginWindow),
}
}
func (a *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /api/auth/login", a.handleLogin)
mux.Handle("GET /api/auth/session", a.authenticate(http.HandlerFunc(a.handleSession)))
mux.Handle("POST /api/auth/logout", a.authenticate(a.csrf(http.HandlerFunc(a.handleLogout))))
mux.Handle("GET /api/config", a.authenticate(http.HandlerFunc(a.handleGetConfig)))
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("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)))
mux.Handle("GET /api/models/availability", a.authenticate(http.HandlerFunc(a.handleAvailability)))
mux.Handle("POST /api/models/restore", a.authenticate(a.csrf(http.HandlerFunc(a.handleRestoreModel))))
mux.Handle("POST /api/models/manual", a.authenticate(a.csrf(http.HandlerFunc(a.handleManualModel))))
mux.Handle("GET /api/rotation", a.authenticate(http.HandlerFunc(a.handleRotation)))
mux.Handle("PUT /api/rotation", a.authenticate(a.csrf(http.HandlerFunc(a.handleSaveRotation))))
mux.Handle("POST /api/rotation/current", a.authenticate(a.csrf(http.HandlerFunc(a.handleSelectRotation))))
mux.Handle("GET /api/model-quotas", a.authenticate(http.HandlerFunc(a.handleModelQuotas)))
mux.Handle("GET /api/api-keys", a.authenticate(http.HandlerFunc(a.handleListAPIKeys)))
mux.Handle("POST /api/api-keys", a.authenticate(a.csrf(http.HandlerFunc(a.handleCreateAPIKey))))
mux.Handle("PATCH /api/api-keys/{id}", a.authenticate(a.csrf(http.HandlerFunc(a.handleUpdateAPIKey))))
mux.Handle("DELETE /api/api-keys/{id}", a.authenticate(a.csrf(http.HandlerFunc(a.handleDeleteAPIKey))))
mux.Handle("POST /api/debug/inference", a.authenticate(a.csrf(http.HandlerFunc(a.handleDebugInference))))
mux.Handle("GET /api/logs", a.authenticate(http.HandlerFunc(a.handleLogs)))
mux.Handle("GET /api/logs/stream", a.authenticate(http.HandlerFunc(a.handleLogStream)))
mux.Handle("/", a.staticHandler())
return a.securityHeaders(telemetry.Recover(a.logger, mux))
}
func (a *Server) staticHandler() http.Handler {
assets := webui.Assets
files := http.FileServer(http.FS(assets))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api/") {
writeAdminError(w, http.StatusNotFound, "not_found", "management endpoint not found")
return
}
if r.URL.Path != "/" && r.URL.Path != "/index.html" {
if _, err := fs.Stat(assets, strings.TrimPrefix(r.URL.Path, "/")); err != nil {
r.URL.Path = "/"
}
}
files.ServeHTTP(w, r)
})
}
func (a *Server) securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self'; script-src 'self'; connect-src 'self'; img-src 'self' data:")
w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
w.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
next.ServeHTTP(w, r)
})
}
type SecretView struct {
ID string `json:"id"`
Display string `json:"display"`
}
type ConfigView struct {
Listen string `json:"listen"`
ServerKeys []SecretView `json:"server_keys"`
ZenKeys []SecretView `json:"zen_keys"`
GoKeys []SecretView `json:"go_keys"`
Anonymous bool `json:"anonymous"`
Proxies []SecretView `json:"proxies"`
ProxyFile string `json:"proxyfile"`
Upstream config.UpstreamConfig `json:"upstream"`
Retry config.RetryConfig `json:"retry"`
Models config.ModelsConfig `json:"models"`
Performance config.PerformanceConfig `json:"performance"`
Logging config.LoggingConfig `json:"logging"`
Prefer config.Tier `json:"prefer"`
Reasoning config.ReasoningConfig `json:"reasoning"`
WebUI WebUIView `json:"webui"`
Effective EffectiveView `json:"effective"`
Restart []string `json:"restart_required_fields,omitempty"`
}
type EffectiveView struct {
Listen string `json:"listen"`
WebUIListen string `json:"webui_listen"`
WebUIEnabled bool `json:"webui_enabled"`
}
type WebUIView struct {
Enabled bool `json:"enabled"`
Listen string `json:"listen"`
Username string `json:"username"`
SessionTTLMinutes int `json:"session_ttl_minutes"`
}
type SecretInput struct {
ID string `json:"id,omitempty"`
Value string `json:"value,omitempty"`
}
type ConfigUpdate struct {
Listen string `json:"listen"`
ServerKeys []SecretInput `json:"server_keys"`
ZenKeys []SecretInput `json:"zen_keys"`
GoKeys []SecretInput `json:"go_keys"`
Anonymous bool `json:"anonymous"`
Proxies []SecretInput `json:"proxies"`
ProxyFile string `json:"proxyfile"`
Upstream config.UpstreamConfig `json:"upstream"`
Retry config.RetryConfig `json:"retry"`
Models config.ModelsConfig `json:"models"`
Performance config.PerformanceConfig `json:"performance"`
Logging config.LoggingConfig `json:"logging"`
Prefer config.Tier `json:"prefer"`
// A pointer distinguishes an omitted field (legacy clients should keep the
// current reasoning configuration) from an explicit empty object (clear it).
Reasoning *config.ReasoningConfig `json:"reasoning,omitempty"`
WebUI WebUIView `json:"webui"`
}
func (a *Server) handleGetConfig(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Cache-Control", "no-store")
httpx.WriteJSON(w, http.StatusOK, a.configView())
}
func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) {
var update ConfigUpdate
if err := decodeAdminJSON(w, r, &update); err != nil {
writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error())
return
}
current := a.manager.Config()
serverKeys, err := resolveSecrets(update.ServerKeys, current.ServerKeys)
if err != nil {
writeAdminError(w, http.StatusBadRequest, "invalid_server_keys", err.Error())
return
}
zenKeys, err := resolveSecrets(update.ZenKeys, current.ZenKeys)
if err != nil {
writeAdminError(w, http.StatusBadRequest, "invalid_zen_keys", err.Error())
return
}
goKeys, err := resolveSecrets(update.GoKeys, current.GoKeys)
if err != nil {
writeAdminError(w, http.StatusBadRequest, "invalid_go_keys", err.Error())
return
}
proxies, err := resolveSecrets(update.Proxies, current.Proxies)
if err != nil {
writeAdminError(w, http.StatusBadRequest, "invalid_proxies", err.Error())
return
}
reasoning := current.Reasoning
if update.Reasoning != nil {
reasoning = *update.Reasoning
}
candidate := config.Config{
ServerKeyMetadata: current.ServerKeyMetadata,
Rotation: current.Rotation,
Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Proxies: proxies, ProxyFile: update.ProxyFile,
Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer,
Reasoning: reasoning,
WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes},
}
result, err := a.manager.Apply(candidate, true)
if err != nil {
a.logger.Warn("configuration update rejected", "component", "config", "event", "config_rejected", "error", err)
writeAdminError(w, http.StatusBadRequest, "configuration_rejected", err.Error())
return
}
httpx.WriteJSON(w, http.StatusOK, map[string]any{"result": result, "config": a.configView()})
}
func (a *Server) handleReload(w http.ResponseWriter, _ *http.Request) {
result, err := a.manager.Reload()
if err != nil {
writeAdminError(w, http.StatusBadRequest, "reload_failed", err.Error())
return
}
httpx.WriteJSON(w, http.StatusOK, result)
}
func (a *Server) handleReveal(w http.ResponseWriter, r *http.Request) {
var input struct {
Password string `json:"password"`
}
if err := decodeAdminJSON(w, r, &input); err != nil {
writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error())
return
}
cfg := a.manager.Config()
if !config.VerifyPassword(cfg.WebUI.PasswordHash, input.Password) {
writeAdminError(w, http.StatusForbidden, "verification_failed", "password verification failed")
return
}
w.Header().Set("Cache-Control", "no-store")
a.logger.Info("sensitive configuration revealed", "component", "auth", "event", "secrets_revealed", "client_ip", clientIP(r))
httpx.WriteJSON(w, http.StatusOK, map[string]any{"server_keys": cfg.ServerKeys, "zen_keys": cfg.ZenKeys, "go_keys": cfg.GoKeys, "proxies": cfg.Proxies})
}
func (a *Server) handleMonitor(w http.ResponseWriter, _ *http.Request) {
metrics := a.monitor.Snapshot()
httpx.WriteJSON(w, http.StatusOK, map[string]any{
"version": buildinfo.Version, "metrics": metrics, "usage": metrics.Usage, "upstream": metrics.Upstream, "resources": a.manager.Resources(),
})
}
func (a *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
after, _ := strconv.ParseUint(r.URL.Query().Get("after"), 10, 64)
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
events, gap := a.logs.Recent(after, limit)
httpx.WriteJSON(w, http.StatusOK, map[string]any{"events": events, "gap": gap})
}
func (a *Server) handleLogStream(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
writeAdminError(w, http.StatusInternalServerError, "stream_unsupported", "streaming is unavailable")
return
}
w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
w.Header().Set("Cache-Control", "no-cache, no-store")
w.Header().Set("X-Accel-Buffering", "no")
after, _ := strconv.ParseUint(r.Header.Get("Last-Event-ID"), 10, 64)
if queryAfter, err := strconv.ParseUint(r.URL.Query().Get("after"), 10, 64); err == nil && queryAfter > after {
after = queryAfter
}
recent, gap := a.logs.Recent(after, 2000)
if gap {
_ = httpx.WriteSSE(w, "gap", 0, map[string]any{"message": "older log events have expired"})
}
for _, event := range recent {
if err := httpx.WriteSSE(w, "log", event.Sequence, event); err != nil {
return
}
after = event.Sequence
}
flusher.Flush()
stream, unsubscribe := a.logs.Subscribe()
defer unsubscribe()
cookie, _ := r.Cookie(adminCookieName)
keepAlive := time.NewTicker(20 * time.Second)
defer keepAlive.Stop()
for {
select {
case <-r.Context().Done():
return
case event := <-stream:
if after > 0 && event.Sequence > after+1 {
_ = httpx.WriteSSE(w, "gap", 0, map[string]any{"message": "slow client missed log events", "after": after, "next": event.Sequence})
}
if err := httpx.WriteSSE(w, "log", event.Sequence, event); err != nil {
return
}
after = event.Sequence
flusher.Flush()
case <-keepAlive.C:
if cookie == nil || !a.sessionTokenValid(cookie.Value) {
return
}
_, _ = io.WriteString(w, ": keepalive\n\n")
flusher.Flush()
}
}
}
func (a *Server) sessionTokenValid(token string) bool {
a.mu.Lock()
session, ok := a.sessions[tokenDigest(token)]
if ok && time.Now().After(session.Expires) {
delete(a.sessions, tokenDigest(token))
ok = false
}
a.mu.Unlock()
if !ok {
return false
}
cfg := a.manager.Config()
return session.Username == cfg.WebUI.Username && session.AuthVersion == config.Fingerprint(cfg.WebUI.PasswordHash)
}
func (a *Server) configView() ConfigView {
cfg := a.manager.Config()
effective, restart := a.manager.RestartStatus()
return ConfigView{
Listen: cfg.Listen, ServerKeys: maskSecrets(cfg.ServerKeys, false), ZenKeys: maskSecrets(cfg.ZenKeys, false), GoKeys: maskSecrets(cfg.GoKeys, false), Anonymous: cfg.Anonymous,
Proxies: maskSecrets(cfg.Proxies, true), ProxyFile: cfg.ProxyFile, Upstream: cfg.Upstream, Retry: cfg.Retry, Models: cfg.Models,
Performance: cfg.Performance, Logging: cfg.Logging, Prefer: cfg.Prefer, Reasoning: cfg.Reasoning,
WebUI: WebUIView{Enabled: cfg.WebUI.Enabled, Listen: cfg.WebUI.Listen, Username: cfg.WebUI.Username, SessionTTLMinutes: cfg.WebUI.SessionTTLMinutes},
Effective: EffectiveView{Listen: effective.API, WebUIListen: effective.WebUI, WebUIEnabled: effective.WebUIEnabled},
Restart: restart,
}
}
func maskSecrets(values []string, proxy bool) []SecretView {
result := make([]SecretView, 0, len(values))
for _, value := range values {
display := config.MaskValue(value)
if proxy {
display = config.RedactURL(value)
}
result = append(result, SecretView{ID: config.Fingerprint(value), Display: display})
}
return result
}
func resolveSecrets(inputs []SecretInput, existing []string) ([]string, error) {
known := make(map[string]string, len(existing))
for _, value := range existing {
known[config.Fingerprint(value)] = value
}
result := make([]string, 0, len(inputs))
for _, input := range inputs {
switch {
case strings.TrimSpace(input.Value) != "":
result = append(result, strings.TrimSpace(input.Value))
case input.ID != "":
value, ok := known[input.ID]
if !ok {
return nil, fmt.Errorf("unknown or stale secret id %q", input.ID)
}
result = append(result, value)
default:
return nil, errors.New("each item must contain id or value")
}
}
return result, nil
}
func decodeAdminJSON(w http.ResponseWriter, r *http.Request, target any) error {
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 2<<20))
decoder.DisallowUnknownFields()
if err := decoder.Decode(target); err != nil {
return err
}
var extra any
if err := decoder.Decode(&extra); err != io.EOF {
if err == nil {
return errors.New("multiple JSON values")
}
return err
}
return nil
}
func writeAdminError(w http.ResponseWriter, status int, code, message string) {
httpx.WriteJSON(w, status, map[string]any{"error": map[string]string{"code": code, "message": message}})
}
+37 -153
View File
@@ -1,4 +1,4 @@
// Package config loads, validates, persists, and redacts service configuration.
// Package config loads, validates, and redacts service configuration.
package config
import (
@@ -16,13 +16,9 @@ import (
)
type Config struct {
Rotation RotationConfig `json:"rotation"`
Listen string `json:"listen"`
ServerKeys []string `json:"server_keys"`
ServerKeyMetadata map[string]ServerKeyMetadata `json:"server_key_metadata,omitempty"`
ZenKeys []string `json:"zen_keys"`
GoKeys []string `json:"go_keys"`
Anonymous bool `json:"anonymous"`
Proxies []string `json:"proxies"`
ProxyFile string `json:"proxyfile"`
Upstream UpstreamConfig `json:"upstream"`
@@ -30,33 +26,22 @@ type Config struct {
Models ModelsConfig `json:"models"`
Performance PerformanceConfig `json:"performance"`
Logging LoggingConfig `json:"logging"`
WebUI WebUIConfig `json:"webui"`
Prefer Tier `json:"prefer"`
Reasoning ReasoningConfig `json:"reasoning"`
effectiveProxies []string
enabledKeySet map[string]string
}
// ReasoningConfig forces a thinking level for requests that do not state one.
//
// Effort is the default for every model; EffortByModel overrides it for the
// model IDs it names. A level a client sends explicitly (Anthropic's
// output_config.effort / top-level effort, or Chat's reasoning_effort) always
// wins, so a forced level only replaces a value that would otherwise have been
// derived from thinking.budget_tokens or left unset.
type ReasoningConfig struct {
// omitempty keeps a saved configuration free of the fields the operator
// never set, matching how the rest of the optional surface is persisted.
Effort string `json:"effort,omitempty"`
EffortByModel map[string]string `json:"effort_by_model,omitempty"`
}
type UpstreamConfig struct {
// Zen is the legacy /zen/v1 free-tier origin (default https://opencode.ai/zen),
// tried first before falling back to Anonymous.
Zen string `json:"zen"`
Go string `json:"go"`
// Anonymous is the base URL used by the keyless free-tier lane. Upstream
// moved keyless inference off /zen onto its own host, so the anonymous lane
// no longer shares the Zen base with the keyed lanes.
// Anonymous is the /inference free-tier origin (default https://opencode.ai/inference).
Anonymous string `json:"anonymous"`
}
@@ -68,27 +53,11 @@ type RetryConfig struct {
type ModelsConfig struct {
RefreshSeconds int `json:"refresh_seconds"`
Protocols map[string]string `json:"protocols"`
// FreeOnly limits discovery and routing to free models, even when Zen or
// Go keys could serve paid ones. Free models may still fall back to keys.
FreeOnly bool `json:"free_only"`
}
type LoggingConfig struct {
Level string `json:"level"`
RingSize int `json:"ring_size"`
// DumpRequestBodies logs the exact bytes sent upstream (redacted, capped)
// so retry and translation problems can be diagnosed without patching the
// binary. Off by default: the bodies contain conversation content.
DumpRequestBodies bool `json:"dump_request_bodies"`
}
type WebUIConfig struct {
Enabled bool `json:"enabled"`
Listen string `json:"listen"`
Username string `json:"username"`
Password string `json:"password,omitempty"`
PasswordHash string `json:"password_hash,omitempty"`
SessionTTLMinutes int `json:"session_ttl_minutes"`
Level string `json:"level"`
DumpRequestBodies bool `json:"dump_request_bodies"`
}
type PerformanceConfig struct {
@@ -102,19 +71,6 @@ type PerformanceConfig struct {
FirstEventTimeoutSeconds int `json:"first_event_timeout_seconds"`
}
// AttemptTimeout bounds how long a single upstream attempt may wait for
// response headers before it is abandoned and the next node is tried. Values
// <= 0 keep the historical behavior of using the request-level retry timeout,
// so existing configs are unaffected. The result never exceeds requestTimeout.
// It bounds the whole attempt up to the response being released (dial, request
// write, headers and, when enabled, the first SSE event); an established
// stream keeps flowing under the request-level timeout.
//
// The bound is installed on the shared transports as the header wait and on
// each attempt's context, so it covers every attempt in both the anonymous and
// the authenticated loops. Without it, one hung exit can consume the entire
// request budget by itself, and the attempts that follow are fired against an
// already-expired context.
func (cfg PerformanceConfig) AttemptTimeout(requestTimeout time.Duration) time.Duration {
if cfg.AttemptTimeoutSeconds > 0 {
attempt := time.Duration(cfg.AttemptTimeoutSeconds) * time.Second
@@ -137,16 +93,13 @@ func Load(path string) (Config, error) {
}
cfg := Config{
Listen: "127.0.0.1:8080",
Upstream: UpstreamConfig{Zen: "https://opencode.ai/zen", Go: "https://opencode.ai/zen/go", Anonymous: "https://opencode.ai/inference"},
Upstream: UpstreamConfig{Zen: "https://opencode.ai/zen", Anonymous: "https://opencode.ai/inference"},
Retry: RetryConfig{MaxAttempts: 3, TimeoutSeconds: 300},
Models: ModelsConfig{RefreshSeconds: 300, Protocols: map[string]string{}},
Performance: PerformanceConfig{MaxIdleConns: 2048, MaxIdleConnsPerHost: 256, MaxConnsPerHost: 0, IdleConnTimeoutSeconds: 120, ConnectTimeoutSeconds: 5, FailureCooldownSeconds: 15},
Logging: LoggingConfig{Level: "info", RingSize: 2000},
WebUI: WebUIConfig{Listen: "0.0.0.0:8081", SessionTTLMinutes: 720},
Prefer: TierGo,
Performance: PerformanceConfig{MaxIdleConns: 4096, MaxIdleConnsPerHost: 1024, MaxConnsPerHost: 0, IdleConnTimeoutSeconds: 120, ConnectTimeoutSeconds: 5, FailureCooldownSeconds: 15},
Logging: LoggingConfig{Level: "info"},
}
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
if err := dec.Decode(&cfg); err != nil {
return Config{}, fmt.Errorf("parse %s: %w", path, err)
}
@@ -156,33 +109,24 @@ func Load(path string) (Config, error) {
return Normalize(path, cfg)
}
// Normalize resolves external inputs and validates a Config supplied by
// either the JSON file or the authenticated management API.
func Normalize(path string, cfg Config) (Config, error) {
cfg.Rotation.Defaults()
if err := cfg.Rotation.Validate(nil); err != nil {
return Config{}, err
}
trimList(&cfg.ServerKeys)
trimList(&cfg.ZenKeys)
trimList(&cfg.GoKeys)
cfg.ProxyFile = strings.TrimSpace(cfg.ProxyFile)
if err := resolveProxyFiles(path, &cfg); err != nil {
return Config{}, err
}
if cfg.Prefer != TierZen && cfg.Prefer != TierGo {
return Config{}, errors.New("prefer must be \"zen\" or \"go\"")
}
if cfg.Listen == "" {
return Config{}, errors.New("listen must not be empty")
}
cfg.Upstream.Zen = strings.TrimSpace(cfg.Upstream.Zen)
cfg.Upstream.Go = strings.TrimSpace(cfg.Upstream.Go)
if cfg.Upstream.Zen == "" {
cfg.Upstream.Zen = "https://opencode.ai/zen"
}
cfg.Upstream.Anonymous = strings.TrimSpace(cfg.Upstream.Anonymous)
if cfg.Upstream.Anonymous == "" {
cfg.Upstream.Anonymous = "https://opencode.ai/inference"
}
for name, raw := range map[string]string{"upstream.zen": cfg.Upstream.Zen, "upstream.go": cfg.Upstream.Go, "upstream.anonymous": cfg.Upstream.Anonymous} {
for name, raw := range map[string]string{"upstream.zen": cfg.Upstream.Zen, "upstream.anonymous": cfg.Upstream.Anonymous} {
u, err := url.Parse(strings.TrimSpace(raw))
if err != nil || u.Host == "" || (strings.ToLower(u.Scheme) != "http" && strings.ToLower(u.Scheme) != "https") {
return Config{}, fmt.Errorf("%s must be an http or https URL", name)
@@ -191,11 +135,14 @@ func Normalize(path string, cfg Config) (Config, error) {
if len(cfg.ServerKeys) == 0 {
return Config{}, errors.New("server_keys must contain at least one local key")
}
if cfg.FirstEnabledServerKey() == "" {
return Config{}, errors.New("至少保留一个启用的 API Key")
cfg.enabledKeySet = make(map[string]string, len(cfg.ServerKeys))
for _, key := range cfg.ServerKeys {
if cfg.ServerKeyEnabled(key) {
cfg.enabledKeySet[key] = Fingerprint(key)
}
}
if !cfg.Anonymous && len(cfg.ZenKeys) == 0 && len(cfg.GoKeys) == 0 {
return Config{}, errors.New("zen_keys or go_keys must contain at least one upstream key unless anonymous is enabled")
if len(cfg.enabledKeySet) == 0 {
return Config{}, errors.New("at least one server_keys entry must be enabled")
}
if cfg.Retry.MaxAttempts < 1 {
return Config{}, errors.New("retry.max_attempts must be at least 1")
@@ -218,41 +165,19 @@ func Normalize(path string, cfg Config) (Config, error) {
if cfg.Logging.Level != "debug" && cfg.Logging.Level != "info" && cfg.Logging.Level != "warn" && cfg.Logging.Level != "error" {
return Config{}, errors.New("logging.level must be debug, info, warn, or error")
}
if cfg.Logging.RingSize < 100 || cfg.Logging.RingSize > 50000 {
return Config{}, errors.New("logging.ring_size must be between 100 and 50000")
}
if cfg.WebUI.Password != "" && len(cfg.WebUI.Password) < 10 {
return Config{}, errors.New("webui.password must contain at least 10 characters")
}
if cfg.WebUI.Enabled {
cfg.WebUI.Listen = strings.TrimSpace(cfg.WebUI.Listen)
cfg.WebUI.Username = strings.TrimSpace(cfg.WebUI.Username)
if cfg.WebUI.Listen == "" {
return Config{}, errors.New("webui.listen must not be empty when webui is enabled")
}
if cfg.WebUI.Username == "" {
return Config{}, errors.New("webui.username must not be empty when webui is enabled")
}
if cfg.WebUI.Password == "" && cfg.WebUI.PasswordHash == "" {
return Config{}, errors.New("webui.password is required for first-time setup")
}
if cfg.WebUI.SessionTTLMinutes < 5 || cfg.WebUI.SessionTTLMinutes > 10080 {
return Config{}, errors.New("webui.session_ttl_minutes must be between 5 and 10080")
}
}
for _, raw := range cfg.RuntimeProxies() {
if raw == "direct" {
continue
}
clean, _ := ParseProxyEntry(raw)
u, err := url.Parse(clean)
if err != nil || u.Host == "" {
pu, err := url.Parse(clean)
if err != nil || pu.Host == "" {
return Config{}, fmt.Errorf("invalid proxy URL %q", RedactURL(raw))
}
switch strings.ToLower(u.Scheme) {
switch strings.ToLower(pu.Scheme) {
case "http", "https", "socks5", "socks5h":
default:
return Config{}, fmt.Errorf("unsupported proxy scheme %q", u.Scheme)
return Config{}, fmt.Errorf("unsupported proxy scheme %q", pu.Scheme)
}
}
for model, protocol := range cfg.Models.Protocols {
@@ -266,21 +191,11 @@ func Normalize(path string, cfg Config) (Config, error) {
return cfg, nil
}
// normalizeReasoning validates and canonicalizes the forced thinking level.
//
// Levels are stored lowercased so the hot path can compare them without
// allocating. An empty value means "not forced", which is the default and keeps
// the feature absent for existing configurations.
func normalizeReasoning(cfg *Config) error {
cfg.Reasoning.Effort = strings.ToLower(strings.TrimSpace(cfg.Reasoning.Effort))
if err := validateEffort("reasoning.effort", cfg.Reasoning.Effort); err != nil {
return err
}
if cfg.Reasoning.EffortByModel == nil {
return nil
}
// An empty map is the same as an absent one, and writing nil back keeps a
// saved configuration free of a field the user never set.
if len(cfg.Reasoning.EffortByModel) == 0 {
cfg.Reasoning.EffortByModel = nil
return nil
@@ -301,8 +216,6 @@ func normalizeReasoning(cfg *Config) error {
return nil
}
// validateEffort accepts the levels the OpenAI and Anthropic surfaces define
// plus an empty string, which means "not forced".
func validateEffort(name, value string) error {
switch value {
case "", "auto", "minimal", "low", "medium", "high", "xhigh", "max", "none":
@@ -312,8 +225,6 @@ func validateEffort(name, value string) error {
}
}
// ForcedEffort returns the level the operator forced for a model, or an empty
// string when none applies. A stored level is already lowercase.
func (cfg Config) ForcedEffort(model string) string {
if effort, ok := cfg.Reasoning.EffortByModel[model]; ok {
return effort
@@ -321,9 +232,18 @@ func (cfg Config) ForcedEffort(model string) string {
return cfg.Reasoning.Effort
}
// RuntimeProxies returns the resolved proxy list, including proxyfile entries.
// Config.Proxies intentionally remains the list stored in config.json so a
// save never duplicates values loaded from proxyfile.
// AuthenticateKey checks whether candidate is an enabled server key in O(1)
// average time and returns its fingerprint if valid.
func (cfg Config) AuthenticateKey(candidate string) (string, bool) {
if candidate == "" {
return "", false
}
if fp, ok := cfg.enabledKeySet[candidate]; ok {
return fp, true
}
return "", false
}
func (cfg Config) RuntimeProxies() []string {
if len(cfg.effectiveProxies) > 0 {
return cfg.effectiveProxies
@@ -333,39 +253,3 @@ func (cfg Config) RuntimeProxies() []string {
}
return []string{"direct"}
}
// PasswordForSave ensures resolved-only data is excluded. The method is kept
// separate to make accidental persistence of effective proxy values obvious.
func (cfg *Config) PasswordForSave() {
cfg.effectiveProxies = nil
}
func Clone(cfg Config) Config {
cfg.Rotation.SOTA.Order = append([]string(nil), cfg.Rotation.SOTA.Order...)
cfg.Rotation.Sweet.Order = append([]string(nil), cfg.Rotation.Sweet.Order...)
cfg.ServerKeys = append([]string(nil), cfg.ServerKeys...)
metadata := make(map[string]ServerKeyMetadata, len(cfg.ServerKeyMetadata))
for id, item := range cfg.ServerKeyMetadata {
metadata[id] = item
}
cfg.ServerKeyMetadata = metadata
cfg.ZenKeys = append([]string(nil), cfg.ZenKeys...)
cfg.GoKeys = append([]string(nil), cfg.GoKeys...)
cfg.Proxies = append([]string(nil), cfg.Proxies...)
cfg.effectiveProxies = append([]string(nil), cfg.effectiveProxies...)
if cfg.Models.Protocols != nil {
protocols := make(map[string]string, len(cfg.Models.Protocols))
for key, value := range cfg.Models.Protocols {
protocols[key] = value
}
cfg.Models.Protocols = protocols
}
if cfg.Reasoning.EffortByModel != nil {
efforts := make(map[string]string, len(cfg.Reasoning.EffortByModel))
for model, effort := range cfg.Reasoning.EffortByModel {
efforts[model] = effort
}
cfg.Reasoning.EffortByModel = efforts
}
return cfg
}
-69
View File
@@ -1,69 +0,0 @@
package config
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strconv"
"strings"
"golang.org/x/crypto/argon2"
)
const (
argonMemory = 64 * 1024
argonIterations = 3
argonParallelism = 2
argonSaltLength = 16
argonKeyLength = 32
)
func HashPassword(password string) (string, error) {
if len(password) < 10 {
return "", errors.New("webui password must contain at least 10 characters")
}
salt := make([]byte, argonSaltLength)
if _, err := rand.Read(salt); err != nil {
return "", err
}
hash := argon2.IDKey([]byte(password), salt, argonIterations, argonMemory, argonParallelism, argonKeyLength)
return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s", argonMemory, argonIterations, argonParallelism,
base64.RawStdEncoding.EncodeToString(salt), base64.RawStdEncoding.EncodeToString(hash)), nil
}
func VerifyPassword(encoded, password string) bool {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" {
return false
}
parameters := strings.Split(parts[3], ",")
if len(parameters) != 3 {
return false
}
memory, err1 := parseArgonParameter(parameters[0], "m")
iterations, err2 := parseArgonParameter(parameters[1], "t")
parallelism, err3 := parseArgonParameter(parameters[2], "p")
if err1 != nil || err2 != nil || err3 != nil || memory < 8*parallelism || memory > 256*1024 || iterations < 1 || iterations > 10 || parallelism < 1 || parallelism > 16 {
return false
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil || len(salt) < 8 || len(salt) > 64 {
return false
}
expected, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil || len(expected) < 16 || len(expected) > 64 {
return false
}
actual := argon2.IDKey([]byte(password), salt, uint32(iterations), uint32(memory), uint8(parallelism), uint32(len(expected)))
return subtle.ConstantTimeCompare(actual, expected) == 1
}
func parseArgonParameter(value, name string) (uint64, error) {
prefix := name + "="
if !strings.HasPrefix(value, prefix) {
return 0, errors.New("invalid parameter")
}
return strconv.ParseUint(strings.TrimPrefix(value, prefix), 10, 32)
}
-93
View File
@@ -1,93 +0,0 @@
package config
import (
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
)
// SaveAtomic writes normalized JSON and keeps the preceding file as
// config.json.bak. The temporary file is created beside the target so the
// final rename stays on the same filesystem.
func SaveAtomic(path string, cfg Config) error {
cfg.PasswordForSave()
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return fmt.Errorf("encode config: %w", err)
}
data = append(data, '\n')
dir := filepath.Dir(path)
temp, err := os.CreateTemp(dir, ".config-*.tmp")
if err != nil {
return fmt.Errorf("create temporary config: %w", err)
}
tempPath := temp.Name()
defer os.Remove(tempPath)
if _, err = temp.Write(data); err == nil {
err = temp.Sync()
}
closeErr := temp.Close()
if err == nil {
err = closeErr
}
if err != nil {
return fmt.Errorf("write temporary config: %w", err)
}
if info, statErr := os.Stat(path); statErr == nil {
_ = os.Chmod(tempPath, info.Mode().Perm())
}
backup := path + ".bak"
if runtime.GOOS == "windows" {
_ = os.Remove(backup)
if _, statErr := os.Stat(path); statErr == nil {
if err := os.Rename(path, backup); err != nil {
return fmt.Errorf("backup config: %w", err)
}
}
if err := os.Rename(tempPath, path); err != nil {
_ = os.Rename(backup, path)
return fmt.Errorf("replace config: %w", err)
}
return nil
}
if _, statErr := os.Stat(path); statErr == nil {
if err := copyFile(path, backup); err != nil {
return fmt.Errorf("backup config: %w", err)
}
}
if err := os.Rename(tempPath, path); err != nil {
return fmt.Errorf("replace config: %w", err)
}
return nil
}
func copyFile(source, target string) error {
in, err := os.Open(source)
if err != nil {
return err
}
defer in.Close()
mode := os.FileMode(0600)
if info, statErr := in.Stat(); statErr == nil {
mode = info.Mode().Perm()
}
out, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode)
if err != nil {
return err
}
_ = out.Chmod(mode)
_, copyErr := io.Copy(out, in)
syncErr := out.Sync()
closeErr := out.Close()
if copyErr != nil {
return copyErr
}
if syncErr != nil {
return syncErr
}
return closeErr
}
+2 -11
View File
@@ -19,7 +19,6 @@ func TestParseProxyEntry(t *testing.T) {
{"socks5h://127.0.0.1:1080#pool", "socks5h://127.0.0.1:1080", true},
{"pool+http://127.0.0.1:7890", "http://127.0.0.1:7890", true},
{"pool+socks5://127.0.0.1:1080", "socks5://127.0.0.1:1080", true},
// A fragment that is not the pool marker belongs to the proxy URL.
{"http://127.0.0.1:7890#other", "http://127.0.0.1:7890#other", false},
}
for _, tc := range cases {
@@ -31,8 +30,6 @@ func TestParseProxyEntry(t *testing.T) {
}
func TestRedactURLKeepsPoolMarker(t *testing.T) {
// url.User("***") percent-escapes the asterisks; that is the existing
// RedactURL shape for every proxy, so the expectation mirrors it.
const masked = "http://%2A%2A%2A@127.0.0.1:7890#pool"
if got := RedactURL("http://user:pass@127.0.0.1:7890#pool"); got != masked {
t.Errorf("pool URL redacted as %q, want %q", got, masked)
@@ -45,8 +42,6 @@ func TestRedactURLKeepsPoolMarker(t *testing.T) {
}
}
// The same endpoint listed statically and as a pool is two distinct routes and
// must survive deduplication; an exact repeat must not.
func TestResolveProxyFilesKeepsPoolVariantOfSameEndpoint(t *testing.T) {
cfg := Config{Proxies: []string{
"http://127.0.0.1:7890",
@@ -68,20 +63,16 @@ func TestResolveProxyFilesKeepsPoolVariantOfSameEndpoint(t *testing.T) {
}
}
// A pool entry must validate against the clean URL, and its credentials must
// stay redactable after the marker is stripped.
func TestNormalizeAcceptsPoolProxy(t *testing.T) {
cfg := Config{
Listen: "127.0.0.1:8080",
ServerKeys: []string{"local-key"},
Anonymous: true,
Proxies: []string{"http://user:secret@127.0.0.1:7890#pool", "direct"},
Upstream: UpstreamConfig{Zen: "https://opencode.ai/zen", Go: "https://opencode.ai/zen/go", Anonymous: "https://opencode.ai/inference"},
Upstream: UpstreamConfig{Zen: "https://opencode.ai/zen", Anonymous: "https://opencode.ai/inference"},
Retry: RetryConfig{MaxAttempts: 3, TimeoutSeconds: 300},
Models: ModelsConfig{RefreshSeconds: 300, Protocols: map[string]string{}},
Performance: PerformanceConfig{MaxIdleConns: 10, MaxIdleConnsPerHost: 10, IdleConnTimeoutSeconds: 30, ConnectTimeoutSeconds: 5, FailureCooldownSeconds: 15},
Logging: LoggingConfig{Level: "info", RingSize: 100},
Prefer: TierGo,
Logging: LoggingConfig{Level: "info"},
}
normalized, err := Normalize("config.json", cfg)
if err != nil {
-63
View File
@@ -1,63 +0,0 @@
package config
import (
"fmt"
"regexp"
"slices"
)
var SOTAModels = []string{"deepseek-v4.1-flash", "glm-5.3", "grok-4.6", "kimi-k3", "qwen3.8-max"}
type RotationGroup struct {
Alias string `json:"alias"`
Order []string `json:"order"`
}
type RotationConfig struct {
SOTA RotationGroup `json:"sota"`
Sweet RotationGroup `json:"sweet"`
FirstOutputSeconds int `json:"first_output_seconds"`
}
func IsSOTA(model string) bool { return slices.Contains(SOTAModels, model) }
func (c *RotationConfig) Defaults() {
if c.SOTA.Alias == "" {
c.SOTA.Alias = "sota"
}
if c.Sweet.Alias == "" {
c.Sweet.Alias = "sweet"
}
if len(c.SOTA.Order) == 0 {
c.SOTA.Order = slices.Clone(SOTAModels)
}
if c.FirstOutputSeconds == 0 {
c.FirstOutputSeconds = 30
}
}
func (c RotationConfig) Validate(realModels []string) error {
if c.FirstOutputSeconds < 1 || c.FirstOutputSeconds > 300 {
return fmt.Errorf("首个有效输出超时需为 1–300 秒")
}
if c.SOTA.Alias == c.Sweet.Alias {
return fmt.Errorf("两个分组的别名不能相同")
}
valid := regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
for i, g := range []RotationGroup{c.SOTA, c.Sweet} {
if !valid.MatchString(g.Alias) {
return fmt.Errorf("别名需为 1–64 位英文字母、数字、点、短横线或下划线")
}
if slices.Contains(realModels, g.Alias) || IsSOTA(g.Alias) || slices.Contains(c.Sweet.Order, g.Alias) {
return fmt.Errorf("别名不能与真实模型 ID 相同")
}
seen := map[string]bool{}
for _, model := range g.Order {
if model == "" || seen[model] || IsSOTA(model) != (i == 0) {
return fmt.Errorf("模型顺序包含重复、空值或不属于该分组的模型")
}
seen[model] = true
}
if i == 0 && len(g.Order) != len(SOTAModels) {
return fmt.Errorf("SOTA 组必须包含指定的五个模型")
}
}
return nil
}
+5 -20
View File
@@ -46,14 +46,9 @@ func NewSecretRedactor() *SecretRedactor {
}
func (r *SecretRedactor) Replace(cfg Config) {
values := make([]string, 0, len(cfg.ServerKeys)+len(cfg.ZenKeys)+len(cfg.GoKeys)+2)
values := make([]string, 0, len(cfg.ServerKeys)+len(cfg.RuntimeProxies())*2+4)
values = append(values, cfg.ServerKeys...)
values = append(values, cfg.ZenKeys...)
values = append(values, cfg.GoKeys...)
if cfg.WebUI.Password != "" {
values = append(values, cfg.WebUI.Password)
}
for _, value := range []string{cfg.Upstream.Zen, cfg.Upstream.Go, cfg.Upstream.Anonymous} {
for _, value := range []string{cfg.Upstream.Zen, cfg.Upstream.Anonymous} {
if parsed, err := url.Parse(value); err == nil && parsed.User != nil {
values = append(values, value, parsed.User.Username())
if password, ok := parsed.User.Password(); ok {
@@ -78,8 +73,9 @@ func (r *SecretRedactor) Replace(cfg Config) {
}
func (r *SecretRedactor) String(value string) string {
for _, secret := range r.values.Load().([]string) {
if len(secret) >= 4 {
secrets, _ := r.values.Load().([]string)
for _, secret := range secrets {
if len(secret) >= 4 && strings.Contains(value, secret) {
value = strings.ReplaceAll(value, secret, "***")
}
}
@@ -90,14 +86,3 @@ func Fingerprint(value string) string {
sum := sha256.Sum256([]byte(value))
return hex.EncodeToString(sum[:])[:10]
}
// keyDisplayID is intentionally separate from secretFingerprint. The latter
// is an internal stable identifier used by session/config bookkeeping; this
// value is safe for logs and the operator UI and shows only the key suffix.
func KeyDisplayID(value string) string {
runes := []rune(value)
if len(runes) <= 5 {
return string(runes)
}
return string(runes[len(runes)-5:])
}
-8
View File
@@ -1,8 +0,0 @@
package config
type Tier string
const (
TierZen Tier = "zen"
TierGo Tier = "go"
)
-36
View File
@@ -2,9 +2,6 @@ package gateway
import (
"context"
"errors"
"time"
"opencode2api/internal/models"
@@ -24,38 +21,6 @@ func (m *RuntimeManager) AvailabilitySnapshot() []models.Availability {
return items
}
func (m *RuntimeManager) RestoreModel(model string) error {
m.updateMu.Lock()
defer m.updateMu.Unlock()
r := m.current.Load()
if r == nil {
return errors.New("gateway runtime is unavailable")
}
for _, item := range m.AvailabilitySnapshot() {
if item.Model == model {
return r.availability.Restore(model, time.Now().UTC())
}
}
return errors.New("unknown free model")
}
// SetManualModel switches a free model between manual and automatic control.
// Manual models stay enabled and are excluded from automatic probing.
func (m *RuntimeManager) SetManualModel(model string, manual bool) error {
m.updateMu.Lock()
defer m.updateMu.Unlock()
r := m.current.Load()
if r == nil {
return errors.New("gateway runtime is unavailable")
}
for _, item := range m.AvailabilitySnapshot() {
if item.Model == model {
return r.availability.SetManual(model, manual, time.Now().UTC())
}
}
return errors.New("unknown free model")
}
func (m *RuntimeManager) startAvailabilityChecks() {
ctx, cancel := context.WithCancel(m.root)
m.availabilityCancel = cancel
@@ -93,7 +58,6 @@ func (m *RuntimeManager) checkFreeModels(ctx context.Context) {
if !result.attempted || ctx.Err() != nil {
continue
}
// Config changes may replace credentials or endpoints during a probe.
m.updateMu.Lock()
if m.current.Load() == r {
if err := r.availability.Record(item.Model, item.Generation, result.success, result.reason, result.channel, time.Now().UTC(), result.effort); err != nil {
+88 -197
View File
@@ -1,10 +1,9 @@
// Package gateway routes inference requests through managed upstream pools.
// Package gateway routes inference requests through the anonymous free-tier pool.
package gateway
import (
"bytes"
"context"
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
@@ -12,6 +11,7 @@ import (
"log/slog"
"net/http"
"strings"
"sync"
"time"
"opencode2api/internal/config"
@@ -19,7 +19,6 @@ import (
"opencode2api/internal/jsonutil"
"opencode2api/internal/models"
wire "opencode2api/internal/protocol"
"opencode2api/internal/rotation"
"opencode2api/internal/telemetry"
)
@@ -27,9 +26,12 @@ const maxRequestBody = 32 << 20
const anonymousZenKey = "public"
// attemptDeadline is the per-attempt context deadline. It is armed only when
// attempt_timeout_seconds is set: otherwise the request-level budget already
// bounds the single attempt it would cover.
var requestBufferPool = sync.Pool{
New: func() any {
return bytes.NewBuffer(make([]byte, 0, 16<<10))
},
}
func attemptDeadline(cfg config.Config) time.Duration {
if cfg.Performance.AttemptTimeoutSeconds <= 0 {
return 0
@@ -37,62 +39,38 @@ func attemptDeadline(cfg config.Config) time.Duration {
return cfg.Performance.AttemptTimeout(time.Duration(cfg.Retry.TimeoutSeconds) * time.Second)
}
// statusClientClosedRequest is nginx's 499: the client went away before the
// gateway could answer, so the failure is neither upstream nor ours.
const statusClientClosedRequest = 499
// proxyUnavailableMessage is returned when every attempt died on the proxy
// route itself, so operators look at their proxies instead of the upstream.
const proxyUnavailableMessage = "all proxies are unavailable; the upstream could not be reached"
type Gateway struct {
rotation *rotation.Manager
cfg config.Config
logger *slog.Logger
transports *transportPool
zenNodes *nodePool
goNodes *nodePool
anonymous *anonymousPool
catalog *models.Catalog
monitor *telemetry.Monitor
availability *models.AvailabilityStore
// attemptTimeout bounds a whole upstream attempt (dial + write + headers +
// first event), not just the header wait. Zero keeps the legacy behavior.
cfg config.Config
logger *slog.Logger
transports *transportPool
anonymous *anonymousPool
catalog *models.Catalog
monitor *telemetry.Monitor
availability *models.AvailabilityStore
redactor *config.SecretRedactor
attemptTimeout time.Duration
}
func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Monitor) (*Gateway, error) {
cfg.Rotation.Defaults()
rotationManager, err := rotation.New("", cfg.Rotation)
if err != nil {
return nil, err
}
func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Monitor, redactor *config.SecretRedactor) (*Gateway, error) {
transports, err := newTransportPool(cfg.RuntimeProxies(), cfg.Performance, cfg.Performance.AttemptTimeout(time.Duration(cfg.Retry.TimeoutSeconds)*time.Second))
if err != nil {
return nil, err
}
cooldown := time.Duration(cfg.Performance.FailureCooldownSeconds) * time.Second
zenNodes, err := newNodePool(cfg.ZenKeys, transports, cooldown)
if err != nil {
return nil, fmt.Errorf("zen node pool: %w", err)
}
goNodes, err := newNodePool(cfg.GoKeys, transports, cooldown)
if err != nil {
return nil, fmt.Errorf("go node pool: %w", err)
}
catalog := models.NewCatalog(cfg.Prefer, cfg.Models.Protocols)
catalog := models.NewCatalog(cfg.Models.Protocols)
catalog.SetRefreshInterval(time.Duration(cfg.Models.RefreshSeconds) * time.Second)
catalog.SetFreeOnly(cfg.Models.FreeOnly)
return &Gateway{
cfg: cfg,
rotation: rotationManager,
logger: logger,
transports: transports,
zenNodes: zenNodes,
goNodes: goNodes,
anonymous: newAnonymousPool(cfg.Anonymous, transports, cooldown),
anonymous: newAnonymousPool(transports, cooldown),
catalog: catalog,
monitor: monitor,
redactor: redactor,
attemptTimeout: attemptDeadline(cfg),
}, nil
}
@@ -110,22 +88,17 @@ func (g *Gateway) Handler() http.Handler {
func (g *Gateway) authenticate(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
candidates := []string{strings.TrimSpace(r.Header.Get("x-api-key"))}
if auth := r.Header.Get("Authorization"); strings.HasPrefix(strings.ToLower(auth), "bearer ") {
candidates = append(candidates, strings.TrimSpace(auth[7:]))
var keyFP string
var ok bool
if apiKey := strings.TrimSpace(r.Header.Get("x-api-key")); apiKey != "" {
keyFP, ok = g.cfg.AuthenticateKey(apiKey)
}
matched := ""
for _, key := range g.cfg.ServerKeys {
if !g.cfg.ServerKeyEnabled(key) {
continue
}
for _, candidate := range candidates {
if len(candidate) == len(key) && subtle.ConstantTimeCompare([]byte(candidate), []byte(key)) == 1 {
matched = key
}
if !ok {
if auth := r.Header.Get("Authorization"); len(auth) > 7 && strings.EqualFold(auth[:7], "bearer ") {
keyFP, ok = g.cfg.AuthenticateKey(strings.TrimSpace(auth[7:]))
}
}
if matched == "" {
if !ok {
protocol := wire.Chat
if r.URL.Path == "/v1/messages" {
protocol = wire.Anthropic
@@ -134,24 +107,37 @@ func (g *Gateway) authenticate(next http.HandlerFunc) http.HandlerFunc {
return
}
if meta := telemetry.MetaFromRequest(r); meta != nil {
// The Playground borrows the first enabled key to pass this check, so
// its traffic gets its own bucket instead of being billed to that key.
meta.ServerKeyID = config.Fingerprint(matched)
if isDiagnosticRequest(r.Context()) {
meta.ServerKeyID = telemetry.PlaygroundServerKey
}
meta.ServerKeyID = keyFP
}
next(w, r)
}
}
func readRequestBody(w http.ResponseWriter, r *http.Request) ([]byte, func(), error) {
buf := requestBufferPool.Get().(*bytes.Buffer)
buf.Reset()
release := func() {
if buf.Cap() <= 1<<20 {
requestBufferPool.Put(buf)
}
}
_, err := buf.ReadFrom(http.MaxBytesReader(w, r.Body, maxRequestBody))
if err != nil {
release()
return nil, nil, err
}
return buf.Bytes(), release, nil
}
func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxRequestBody))
body, releaseBody, err := readRequestBody(w, r)
if err != nil {
wire.WriteError(w, external, http.StatusBadRequest, "request body is too large or unreadable", "invalid_request_error", "")
return
}
defer releaseBody()
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
wire.WriteError(w, external, http.StatusBadRequest, "request body must be a JSON object", "invalid_request_error", "")
@@ -166,42 +152,27 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
wire.WriteError(w, external, http.StatusBadRequest, "model is required", "invalid_request_error", "model")
return
}
if id := g.rotation.GroupID(model); id != "" {
g.handleRotation(w, r, external, payload, id, model)
return
}
if !g.catalog.Supported(model) {
wire.WriteError(w, external, http.StatusBadRequest, "the model uses an upstream protocol that opencode2api does not expose", "invalid_request_error", "model")
return
}
route, err := g.catalog.Route(model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous)
if override, selected := debugKeyOverrideFrom(r.Context()); selected {
// A per-key diagnostic must not silently be served by another key,
// another tier or the anonymous lane.
route, err = g.catalog.RouteForTier(model, override.Tier, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0)
}
route, err := g.catalog.Route(model)
if err != nil {
wire.WriteError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "model")
return
}
if meta != nil {
meta.Tier = string(route.Tier)
meta.Protocol = route.Protocol
}
// A System One model has no message-shaped equivalent, so a decision
// payload submitted on a message endpoint is relayed verbatim instead of
// being converted. This keeps the model reachable for clients that can
// only address /v1/chat/completions or /v1/responses — for example a
// gateway whose OpenAI platform pins every request to Responses.
if route.Protocol == wire.SystemOne {
if len(jsonutil.MapAt(payload, "questions")) == 0 || payload["state"] == nil {
wire.WriteError(w, external, http.StatusBadRequest, "this model uses System One decisions, not chat; send state and typed questions to /v1/systemone", "invalid_request_error", "model")
return
}
g.forwardSystemOne(w, r, body, payload, model, route)
g.forwardSystemOne(w, r, append([]byte(nil), body...), payload, model, route)
return
}
bodies, err := g.prepareRouteBodies(external, route, payload)
preparedBody, err := g.prepareRouteBody(external, route, payload)
if err != nil {
wire.WriteError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "")
return
@@ -214,32 +185,21 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
stream := jsonutil.BoolAt(payload, "stream")
requestCtx, cancel := context.WithTimeout(r.Context(), time.Duration(g.cfg.Retry.TimeoutSeconds)*time.Second)
defer cancel()
resp, upstreamRoute, err := g.doUpstream(requestCtx, route, bodies, ids)
resp, err := g.doUpstream(requestCtx, route, preparedBody, ids)
if err != nil {
finalTier := route.Tier
if meta != nil && meta.Tier != "" {
finalTier = config.Tier(meta.Tier)
}
keyID, channel, anonymous := requestCredential(requestCtx)
// A downstream disconnect is not an upstream failure: report the
// real cause so telemetry and clients see a cancel, not a 502.
if !errors.Is(err, context.DeadlineExceeded) && wire.ClientCanceled(r.Context(), err) {
g.logger.Debug("client canceled before upstream response", "component", "upstream", "event", "request_canceled", "request_id", ids.Request, "tier", finalTier, "key_id", keyID, "channel", channel, "anonymous", anonymous)
g.logger.Debug("client canceled before upstream response", "component", "upstream", "event", "request_canceled", "request_id", ids.Request)
if meta != nil {
meta.Outcome = "client_canceled"
}
wire.WriteError(w, external, statusClientClosedRequest, "client closed request", "client_canceled", ids.Request)
return
}
g.logger.Warn("all upstream attempts failed", "component", "upstream", "event", "request_failed", "request_id", ids.Request, "tier", finalTier, "key_id", keyID, "channel", channel, "anonymous", anonymous, "error", err)
// The request never reached the upstream because the proxy route
// failed; report that instead of blaming the upstream with a 502.
g.logger.Warn("all upstream attempts failed", "component", "upstream", "event", "request_failed", "request_id", ids.Request, "error", err)
if errors.Is(err, errProxyUnavailable) {
wire.WriteError(w, external, http.StatusServiceUnavailable, proxyUnavailableMessage, "proxy_error", ids.Request)
return
}
// An exhausted request budget is a timeout, not a bad gateway: the
// distinction matters to clients that retry on 502.
if errors.Is(err, context.DeadlineExceeded) {
wire.WriteError(w, external, http.StatusGatewayTimeout, "upstream request timed out", "upstream_timeout", ids.Request)
return
@@ -248,10 +208,6 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
return
}
defer resp.Body.Close()
if meta != nil {
meta.Tier = string(upstreamRoute.Tier)
meta.Protocol = upstreamRoute.Protocol
}
w.Header().Set("x-request-id", ids.Request)
if resp.StatusCode/100 != 2 {
copyErrorResponse(w, external, resp, ids.Request)
@@ -273,13 +229,13 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("X-Accel-Buffering", "no")
w.WriteHeader(resp.StatusCode)
streamBody := wire.RenameStreamReader(resp.Body, upstreamRoute.Protocol, legacyAnonymousReadTool, toolAlias)
streamBody := wire.RenameStreamReader(resp.Body, route.Protocol, legacyAnonymousReadTool, toolAlias)
var usage wire.Usage
var usageReported bool
if external == upstreamRoute.Protocol {
usage, usageReported, err = wire.ForwardStream(r.Context(), w, streamBody, upstreamRoute.Protocol, model)
if external == route.Protocol {
usage, usageReported, err = wire.ForwardStream(r.Context(), w, streamBody, route.Protocol, model)
} else {
usage, usageReported, err = wire.TranscodeStream(r.Context(), w, streamBody, upstreamRoute.Protocol, external, model)
usage, usageReported, err = wire.TranscodeStream(r.Context(), w, streamBody, route.Protocol, external, model)
}
if meta != nil {
meta.Usage, meta.UsageReported = usage, usageReported
@@ -291,7 +247,7 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
}
}
if err != nil && !errors.Is(err, context.Canceled) {
g.logger.Warn("downstream stream ended with an error", "component", "stream", "event", "stream_failed", "request_id", ids.Request, "model", model, "tier", upstreamRoute.Tier, "error", err)
g.logger.Warn("downstream stream ended with an error", "component", "stream", "event", "stream_failed", "request_id", ids.Request, "model", model, "error", err)
}
return
}
@@ -300,28 +256,20 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
wire.WriteError(w, external, http.StatusBadGateway, "failed to read upstream response", "upstream_error", ids.Request)
return
}
if upstreamRoute.Anonymous || (meta != nil && meta.Shaped) {
// Key-tier shaped requests were force-streamed like the
// anonymous lane; collapse the same way.
// The anonymous lane is served streaming (see prepareAnonymousBody);
// collapse the events back into the single document this
// non-streaming client asked for.
collapsed, err := wire.CollapseStream(bytes.NewReader(responseBody), upstreamRoute.Protocol, model)
if err != nil {
g.logger.Warn("anonymous stream collapse failed", "component", "conversion", "event", "anonymous_collapse_failed", "request_id", ids.Request, "model", model, "source_protocol", upstreamRoute.Protocol, "error", err)
wire.WriteError(w, external, http.StatusBadGateway, "unsupported upstream response", "upstream_error", ids.Request)
return
}
responseBody = collapsed
collapsed, err := wire.CollapseStream(bytes.NewReader(responseBody), route.Protocol, model)
if err != nil {
g.logger.Warn("anonymous stream collapse failed", "component", "conversion", "event", "anonymous_collapse_failed", "request_id", ids.Request, "model", model, "source_protocol", route.Protocol, "error", err)
wire.WriteError(w, external, http.StatusBadGateway, "unsupported upstream response", "upstream_error", ids.Request)
return
}
responseBody = wire.RenameResponseTool(responseBody, upstreamRoute.Protocol, legacyAnonymousReadTool, toolAlias)
if usage, reported := wire.ResponseUsage(upstreamRoute.Protocol, responseBody); meta != nil {
responseBody = wire.RenameResponseTool(collapsed, route.Protocol, legacyAnonymousReadTool, toolAlias)
if usage, reported := wire.ResponseUsage(route.Protocol, responseBody); meta != nil {
meta.Usage, meta.UsageReported = usage, reported
}
if external != upstreamRoute.Protocol {
responseBody, err = wire.ConvertResponse(upstreamRoute.Protocol, external, responseBody)
if external != route.Protocol {
responseBody, err = wire.ConvertResponse(route.Protocol, external, responseBody)
if err != nil {
g.logger.Warn("response protocol conversion failed", "component", "conversion", "event", "response_conversion_failed", "request_id", ids.Request, "model", model, "source_protocol", upstreamRoute.Protocol, "target_protocol", external, "error", err)
g.logger.Warn("response protocol conversion failed", "component", "conversion", "event", "response_conversion_failed", "request_id", ids.Request, "model", model, "source_protocol", route.Protocol, "target_protocol", external, "error", err)
wire.WriteError(w, external, http.StatusBadGateway, "unsupported upstream response", "upstream_error", ids.Request)
return
}
@@ -332,16 +280,14 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
}
}
// handleSystemOne serves System One decision requests on their own endpoint.
// Only models whose upstream protocol is System One can be served here; a chat
// or responses model belongs on its own endpoint, where the bridge can convert
// it.
func (g *Gateway) handleSystemOne(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxRequestBody))
body, releaseBody, err := readRequestBody(w, r)
if err != nil {
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, "request body is too large or unreadable", "invalid_request_error", "")
return
}
defer releaseBody()
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, "request body must be a JSON object", "invalid_request_error", "")
@@ -359,7 +305,7 @@ func (g *Gateway) handleSystemOne(w http.ResponseWriter, r *http.Request) {
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, "the model uses an upstream protocol that opencode2api does not expose", "invalid_request_error", "model")
return
}
route, err := g.catalog.Route(model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous)
route, err := g.catalog.Route(model)
if err != nil {
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, err.Error(), "invalid_request_error", "model")
return
@@ -368,28 +314,15 @@ func (g *Gateway) handleSystemOne(w http.ResponseWriter, r *http.Request) {
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, fmt.Sprintf("the model does not use the %s protocol", wire.SystemOne), "invalid_request_error", "model")
return
}
g.forwardSystemOne(w, r, body, payload, model, route)
g.forwardSystemOne(w, r, append([]byte(nil), body...), payload, model, route)
}
// forwardSystemOne relays a System One decision payload verbatim to the
// upstream systemone endpoint and returns the typed answer document unchanged.
// The payload pairs a free-form state with typed questions, which no
// message-shaped upstream protocol accepts, so it is never translated. Answers
// are non-streaming today; a streaming upstream reply is still relayed.
func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body []byte, payload map[string]any, model string, route models.Route) {
meta := telemetry.MetaFromRequest(r)
if meta != nil {
meta.Model = model
meta.Tier = string(route.Tier)
meta.Protocol = route.Protocol
}
// One verbatim body serves every tier: a decision payload has no per-tier
// encoding, so no protocol conversion is attempted.
bodies := make(map[config.Tier][]byte, len(route.KeyTiers)+1)
bodies[route.Tier] = body
for _, tier := range route.KeyTiers {
bodies[tier] = body
}
ids := identity.DeriveRequestIDs(r, payload)
if meta != nil {
meta.Request = ids.Request
@@ -397,22 +330,17 @@ func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body
}
requestCtx, cancel := context.WithTimeout(r.Context(), time.Duration(g.cfg.Retry.TimeoutSeconds)*time.Second)
defer cancel()
resp, upstreamRoute, err := g.doUpstream(requestCtx, route, bodies, ids)
resp, err := g.doUpstream(requestCtx, route, body, ids)
if err != nil {
finalTier := route.Tier
if meta != nil && meta.Tier != "" {
finalTier = config.Tier(meta.Tier)
}
keyID, channel, anonymous := requestCredential(requestCtx)
if !errors.Is(err, context.DeadlineExceeded) && wire.ClientCanceled(r.Context(), err) {
g.logger.Debug("client canceled before upstream response", "component", "upstream", "event", "request_canceled", "request_id", ids.Request, "tier", finalTier, "key_id", keyID, "channel", channel, "anonymous", anonymous)
g.logger.Debug("client canceled before upstream response", "component", "upstream", "event", "request_canceled", "request_id", ids.Request)
if meta != nil {
meta.Outcome = "client_canceled"
}
wire.WriteError(w, wire.SystemOne, statusClientClosedRequest, "client closed request", "client_canceled", ids.Request)
return
}
g.logger.Warn("all upstream attempts failed", "component", "upstream", "event", "request_failed", "request_id", ids.Request, "tier", finalTier, "key_id", keyID, "channel", channel, "anonymous", anonymous, "error", err)
g.logger.Warn("all upstream attempts failed", "component", "upstream", "event", "request_failed", "request_id", ids.Request, "error", err)
if errors.Is(err, errProxyUnavailable) {
wire.WriteError(w, wire.SystemOne, http.StatusServiceUnavailable, proxyUnavailableMessage, "proxy_error", ids.Request)
return
@@ -425,10 +353,6 @@ func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body
return
}
defer resp.Body.Close()
if meta != nil {
meta.Tier = string(upstreamRoute.Tier)
meta.Protocol = upstreamRoute.Protocol
}
w.Header().Set("x-request-id", ids.Request)
if resp.StatusCode/100 != 2 {
copyErrorResponse(w, wire.SystemOne, resp, ids.Request)
@@ -449,7 +373,7 @@ func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body
wire.WriteError(w, wire.SystemOne, http.StatusBadGateway, "failed to read upstream response", "upstream_error", ids.Request)
return
}
if usage, reported := wire.ResponseUsage(upstreamRoute.Protocol, responseBody); meta != nil {
if usage, reported := wire.ResponseUsage(route.Protocol, responseBody); meta != nil {
meta.Usage, meta.UsageReported = usage, reported
}
w.Header().Set("Content-Type", "application/json")
@@ -457,52 +381,19 @@ func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body
_, _ = w.Write(responseBody)
}
func (g *Gateway) prepareRouteBodies(from wire.Protocol, route models.Route, input map[string]any) (map[config.Tier][]byte, error) {
tiers := make([]config.Tier, 0, len(route.KeyTiers)+1)
seen := make(map[config.Tier]bool, len(route.KeyTiers)+1)
addTier := func(tier config.Tier) {
if tier != config.TierZen && tier != config.TierGo || seen[tier] {
return
}
seen[tier] = true
tiers = append(tiers, tier)
func (g *Gateway) prepareRouteBody(from wire.Protocol, route models.Route, input map[string]any) ([]byte, error) {
upstreamPayload, err := wire.PrepareRequest(from, route.Protocol, input, g.cfg.Upstream.Zen)
if err != nil {
return nil, fmt.Errorf("prepare upstream request: %w", err)
}
addTier(route.Tier)
for _, tier := range route.KeyTiers {
addTier(tier)
if effort := g.resolvedEffort(jsonutil.StringAt(upstreamPayload, "model"), route.Protocol); effort != "" {
wire.ForcedEffort(route.Protocol, upstreamPayload, effort)
}
if len(tiers) == 0 {
return nil, errors.New("no usable upstream tier")
encoded, err := json.Marshal(upstreamPayload)
if err != nil {
return nil, errors.New("request contains unsupported JSON values")
}
bodies := make(map[config.Tier][]byte, len(tiers))
for _, tier := range tiers {
protocol := route.ProtocolFor(tier)
baseURL := g.cfg.Upstream.Zen
if tier == config.TierGo {
baseURL = g.cfg.Upstream.Go
}
upstreamPayload, err := wire.PrepareRequest(from, protocol, input, baseURL)
if err != nil {
if tier != route.Tier {
// A fallback tier may use a stricter wire format than the
// preferred tier. Do not reject a request before the preferred
// upstream has even been tried; that tier is attempted only if
// the request actually falls back.
g.logger.Debug("skipping fallback tier with incompatible request shape", "component", "conversion", "event", "fallback_tier_skipped", "model", jsonutil.StringAt(input, "model"), "tier", tier, "protocol", protocol, "error", err)
continue
}
return nil, fmt.Errorf("prepare %s upstream request: %w", tier, err)
}
if effort := g.resolvedEffort(jsonutil.StringAt(upstreamPayload, "model"), tier, protocol); effort != "" {
wire.ForcedEffort(protocol, upstreamPayload, effort)
}
encoded, err := json.Marshal(upstreamPayload)
if err != nil {
return nil, errors.New("request contains unsupported JSON values")
}
bodies[tier] = encoded
}
return bodies, nil
return encoded, nil
}
func copyErrorResponse(w http.ResponseWriter, protocol wire.Protocol, resp *http.Response, requestID string) {
+5 -51
View File
@@ -6,7 +6,6 @@ import (
"time"
"opencode2api/internal/buildinfo"
"opencode2api/internal/config"
"opencode2api/internal/httpx"
modelcatalog "opencode2api/internal/models"
wire "opencode2api/internal/protocol"
@@ -17,7 +16,6 @@ type healthResponse struct {
Ready bool `json:"ready"`
Version string `json:"version"`
Models healthModels `json:"models"`
Keys healthKeys `json:"keys"`
Proxies healthProxies `json:"proxies"`
Issues []string `json:"issues,omitempty"`
}
@@ -26,21 +24,12 @@ type healthModels struct {
Status string `json:"status"`
Total int `json:"total"`
Exposed int `json:"exposed"`
Zen int `json:"zen"`
Go int `json:"go"`
LastRefresh *time.Time `json:"last_refresh,omitempty"`
StaleAfterSeconds int `json:"stale_after_seconds"`
CacheSource string `json:"cache_source,omitempty"`
Stale bool `json:"stale"`
}
type healthKeys struct {
Zen int `json:"zen"`
Go int `json:"go"`
Total int `json:"total"`
Anonymous bool `json:"anonymous"`
}
type healthProxies struct {
Total int `json:"total"`
Healthy int `json:"healthy"`
@@ -50,12 +39,11 @@ type healthProxies struct {
func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) {
_, models := g.availableModels()
proxyTotal, proxyHealthy := g.transports.healthCounts()
zenKeys, goKeys := g.zenNodes.Len(), g.goNodes.Len()
staleAfter := max(2*time.Duration(g.cfg.Models.RefreshSeconds)*time.Second, time.Minute)
modelStatus := "ready"
var lastRefresh *time.Time
issues := make([]string, 0, 3)
issues := make([]string, 0, 2)
if models.UpdatedAt.IsZero() {
modelStatus = "pending"
issues = append(issues, "model_catalog_pending")
@@ -70,9 +58,6 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) {
issues = append(issues, "model_catalog_stale")
}
}
if zenKeys+goKeys == 0 && !g.cfg.Anonymous {
issues = append(issues, "no_upstream_keys")
}
if proxyHealthy == 0 {
issues = append(issues, "no_healthy_proxies")
}
@@ -98,14 +83,11 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) {
Status: modelStatus,
Total: models.Total,
Exposed: models.Exposed,
Zen: models.Zen,
Go: models.Go,
LastRefresh: lastRefresh,
StaleAfterSeconds: int(staleAfter / time.Second),
CacheSource: models.CacheSource,
Stale: models.Stale,
},
Keys: healthKeys{Zen: zenKeys, Go: goKeys, Total: zenKeys + goKeys, Anonymous: g.cfg.Anonymous},
Proxies: healthProxies{
Total: proxyTotal,
Healthy: proxyHealthy,
@@ -116,19 +98,14 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) {
}
func (g *Gateway) availableModels() ([]modelcatalog.Route, modelcatalog.CatalogSnapshot) {
return g.catalog.AvailableModels(g.zenNodes.Len() > 0, g.goNodes.Len() > 0, g.cfg.Anonymous)
return g.catalog.AvailableModels()
}
// reasoningLevels are the effort values the gateway accepts and forwards, from
// lowest to highest. "auto" and "none" are gateway controls, not levels.
var reasoningLevels = []string{"minimal", "low", "medium", "high", "xhigh", "max"}
// reasoningEfforts lists the levels a reasoning model can be asked for. When an
// "auto" probe has found the highest level the upstream accepts, the list stops
// there so clients do not offer levels that would be rejected.
func (g *Gateway) reasoningEfforts(model string, route modelcatalog.Route) []string {
if g.cfg.ForcedEffort(model) == "auto" {
if ceiling := slices.Index(reasoningLevels, g.resolvedEffort(model, route.Tier, route.Protocol)); ceiling >= 0 {
if ceiling := slices.Index(reasoningLevels, g.resolvedEffort(model, route.Protocol)); ceiling >= 0 {
return slices.Clone(reasoningLevels[:ceiling+1])
}
}
@@ -141,9 +118,7 @@ func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) {
data := make([]map[string]any, 0, len(routes))
for _, route := range routes {
model := route.ID
// Tier-scoped metadata: the advertised context window must match
// the tier that will serve the request (anonymous ⇒ Zen).
md := g.catalog.MetadataForTier(model, route.Tier)
md := g.catalog.MetadataFor(model)
entry := map[string]any{
"id": model, "object": "model", "created": now, "owned_by": "opencode",
"metadata": md,
@@ -154,8 +129,6 @@ func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) {
} else {
entry["supported_endpoints"] = []string{"/v1/chat/completions", "/v1/responses", "/v1/messages"}
}
// Top-level OpenAI-standard fields: discovery clients (jcode, Pi, …)
// read context/reasoning at the top level of each model entry.
if md.ContextWindow > 0 {
entry["context_window"] = md.ContextWindow
entry["context_length"] = md.ContextWindow
@@ -171,16 +144,13 @@ func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) {
entry["supports_reasoning"] = true
efforts := g.reasoningEfforts(model, route)
entry["reasoning_efforts"] = efforts
// OpenClaw and similar harnesses read effort levels from compat
// rather than inferring them, and otherwise offer only off/max.
entry["compat"] = map[string]any{"supportsReasoningEffort": true, "supportedReasoningEfforts": efforts}
if effort := g.resolvedEffort(model, route.Tier, route.Protocol); effort != "" && effort != "none" {
if effort := g.resolvedEffort(model, route.Protocol); effort != "" && effort != "none" {
entry["default_reasoning_effort"] = effort
}
}
if md.Cost != nil {
cost := map[string]any{}
// Camel-case aliases match OpenClaw's model cost shape.
for _, field := range []struct {
names []string
value *float64
@@ -207,21 +177,5 @@ func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) {
}
data = append(data, entry)
}
for _, group := range g.rotation.Snapshot().Groups {
if g.goNodes.Len() == 0 {
continue
}
available := false
for _, model := range group.Order {
if route, err := g.catalog.RouteForTier(model, config.TierGo, false, true); err == nil && route.Protocol != wire.SystemOne {
available = true
break
}
}
if !available {
continue
}
data = append(data, map[string]any{"id": group.Alias, "object": "model", "created": now, "owned_by": "opencode-go-rotation"})
}
httpx.WriteJSON(w, http.StatusOK, map[string]any{"object": "list", "data": data})
}
+35 -281
View File
@@ -7,13 +7,11 @@ import (
"fmt"
"hash/fnv"
"io"
rand "math/rand/v2"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
@@ -36,8 +34,8 @@ type transportPool struct {
}
// anonymousPool gives the shared OpenCode "public" credential an independent
// cooldown per proxy. Unlike key nodes, anonymous nodes are never rebound:
// changing proxy is the failover mechanism because Zen rate-limits them by IP.
// cooldown per proxy. Changing proxy is the failover mechanism because
// OpenCode rate-limits anonymous requests by exit IP.
type anonymousPool struct {
nodes []*anonymousNode
next atomic.Uint64
@@ -51,16 +49,19 @@ type anonymousNode struct {
cooldownUntil atomic.Int64
}
const maxStackCursorNodes = 64
type anonymousCursor struct {
pool *anonymousPool
start int
offset int
used []bool
pool *anonymousPool
start int
offset int
usedBuf [maxStackCursorNodes]bool
used []bool
}
func newAnonymousPool(enabled bool, transports *transportPool, cooldown time.Duration) *anonymousPool {
func newAnonymousPool(transports *transportPool, cooldown time.Duration) *anonymousPool {
pool := &anonymousPool{cooldown: cooldown}
if !enabled || transports == nil {
if transports == nil {
return pool
}
pool.nodes = make([]*anonymousNode, 0, len(transports.items))
@@ -99,20 +100,17 @@ func (p *anonymousPool) CursorFor(affinity string) anonymousCursor {
return anonymousCursor{pool: p, start: start}
}
// Next visits each healthy, non-cooling static proxy at most once per cursor.
// When the pool contains rotating proxy-pool transports (#pool), it continues
// cycling through them after the first pass so retry.max_attempts can draw a
// fresh upstream connection (and new exit IP) on every attempt. If all static
// proxies are currently cooling or marked unhealthy, Next falls back to the
// earliest-expiring node not yet tried by this cursor instead of returning nil
// immediately.
func (c *anonymousCursor) Next() *anonymousNode {
if c.pool == nil || len(c.pool.nodes) == 0 {
return nil
}
n := len(c.pool.nodes)
if c.used == nil {
c.used = make([]bool, n)
if n <= maxStackCursorNodes {
c.used = c.usedBuf[:n]
} else {
c.used = make([]bool, n)
}
}
now := time.Now().UnixNano()
for c.offset < n {
@@ -160,14 +158,14 @@ func (p *anonymousPool) MarkSuccess(node *anonymousNode) {
if node == nil {
return
}
node.failures.Store(0)
node.cooldownUntil.Store(0)
if node.failures.Load() != 0 {
node.failures.Store(0)
}
if node.cooldownUntil.Load() != 0 {
node.cooldownUntil.Store(0)
}
}
// RestoreProxy clears cooldowns for anonymous nodes bound to a recovered
// proxy, mirroring nodePool.RestoreProxy for key nodes. Without this, an
// outage-era cooldown survives the proxy's recovery and the anonymous lane
// stays skipped even though the route is healthy again.
func (p *anonymousPool) RestoreProxy(proxy *proxyTransport) int {
if p == nil || proxy == nil {
return 0
@@ -187,13 +185,6 @@ func (p *anonymousPool) RestoreProxy(proxy *proxyTransport) int {
return cleared
}
// maxAnonymousRetryAfterMultiplier bounds an upstream Retry-After on the
// anonymous lane to the same 8x ceiling as its exponential backoff. The lane
// is rate limited per exit IP and, unlike key lanes, has no earliest-expiry
// fallback: a quota response asking for hours would keep the exit skipped long
// after a network change gave it a fresh allowance. Key lanes keep honoring
// Retry-After in full, since their cursor already falls back to the node that
// recovers first.
const maxAnonymousRetryAfterMultiplier = 8
func (p *anonymousPool) MarkFailure(node *anonymousNode, resp *http.Response, err error) {
@@ -244,14 +235,11 @@ func newTransportPool(proxies []string, cfg config.PerformanceConfig, responseHe
transport.MaxConnsPerHost = cfg.MaxConnsPerHost
transport.IdleConnTimeout = time.Duration(cfg.IdleConnTimeoutSeconds) * time.Second
transport.ResponseHeaderTimeout = responseHeaderTimeout
transport.WriteBufferSize = 64 << 10
transport.ReadBufferSize = 64 << 10
transport.ForceAttemptHTTP2 = !isPool
transport.DisableKeepAlives = isPool
if isPool {
// Cloning DefaultTransport after its first dial inherits the
// already-configured HTTP/2 ALPN and TLSNextProto map, which ignores
// DisableKeepAlives and req.Close and multiplexes every request over
// one CONNECT tunnel. An explicit empty TLSNextProto map and HTTP/1.1
// ALPN force a brand-new TCP + CONNECT tunnel per attempt.
transport.TLSNextProto = make(map[string]func(authority string, c *tls.Conn) http.RoundTripper)
if transport.TLSClientConfig == nil {
transport.TLSClientConfig = &tls.Config{NextProtos: []string{"http/1.1"}}
@@ -260,6 +248,14 @@ func newTransportPool(proxies []string, cfg config.PerformanceConfig, responseHe
tlsCfg.NextProtos = []string{"http/1.1"}
transport.TLSClientConfig = tlsCfg
}
} else {
if transport.TLSClientConfig == nil {
transport.TLSClientConfig = &tls.Config{ClientSessionCache: tls.NewLRUClientSessionCache(256)}
} else if transport.TLSClientConfig.ClientSessionCache == nil {
tlsCfg := transport.TLSClientConfig.Clone()
tlsCfg.ClientSessionCache = tls.NewLRUClientSessionCache(256)
transport.TLSClientConfig = tlsCfg
}
}
transport.DialContext = (&net.Dialer{
Timeout: time.Duration(cfg.ConnectTimeoutSeconds) * time.Second,
@@ -288,10 +284,6 @@ type proxyHealthResult struct {
wasHealthy bool
}
// CheckHealth concurrently rechecks only proxies already marked unhealthy.
// Healthy proxies are skipped before a check is claimed. Any HTTP response
// from the test URL proves that the route is reachable; only a timeout or
// connection refusal keeps the proxy unhealthy.
func (p *transportPool) CheckHealth(ctx context.Context, target string, timeout time.Duration) []proxyHealthResult {
results := make(chan proxyHealthResult, len(p.items))
checks := 0
@@ -299,16 +291,14 @@ func (p *transportPool) CheckHealth(ctx context.Context, target string, timeout
if proxy.pool || proxy.healthy.Load() || !proxy.checking.CompareAndSwap(false, true) {
continue
}
// A real request may have restored the proxy between the first health
// read and claiming this check.
if proxy.healthy.Load() {
proxy.checking.Store(false)
continue
}
checks++
go func() {
go func(proxy *proxyTransport) {
results <- p.checkClaimedProxy(ctx, proxy, target, timeout)
}()
}(proxy)
}
out := make([]proxyHealthResult, 0, checks)
for range checks {
@@ -317,7 +307,6 @@ func (p *transportPool) CheckHealth(ctx context.Context, target string, timeout
return out
}
// checkClaimedProxy performs a check after the caller has acquired checking.
func (p *transportPool) checkClaimedProxy(ctx context.Context, proxy *proxyTransport, target string, timeout time.Duration) proxyHealthResult {
defer proxy.checking.Store(false)
checkCtx, cancel := context.WithTimeout(ctx, timeout)
@@ -342,12 +331,9 @@ func (p *transportPool) checkClaimedProxy(ctx context.Context, proxy *proxyTrans
return result
}
// isProxyFailure deliberately recognizes only failures that say the proxy
// route is unavailable. HTTP responses and unrelated transport/protocol errors
// must not evict a proxy.
func isProxyFailure(err error) bool {
if errors.Is(err, errFirstEventTimeout) || upstreamAccepted(err) {
return false // The upstream accepted HTTP; slow generation is not a broken proxy.
return false
}
if err == nil {
return false
@@ -359,238 +345,6 @@ func isProxyFailure(err error) bool {
return errors.As(err, &timeout) && timeout.Timeout()
}
// upstreamNode keeps a key stable while allowing its proxy binding to change
// atomically when a proxy becomes unavailable.
type upstreamNode struct {
key string
index int
preferredProxy int
proxyIndex atomic.Int64
failures atomic.Uint32
cooldownUntil atomic.Int64
}
type nodePool struct {
nodes []*upstreamNode
transports *transportPool
next atomic.Uint64
cooldown time.Duration
bindingsMu sync.Mutex
bindingCount []int
}
// newNodePool distributes keys over proxies in round-robin order. When there
// are fewer keys than proxies, the remaining proxies are intentionally idle and
// can take over a key immediately if an active proxy fails.
func newNodePool(keys []string, transports *transportPool, cooldown time.Duration) (*nodePool, error) {
if transports == nil || len(transports.items) == 0 {
return nil, fmt.Errorf("at least one proxy transport is required")
}
pool := &nodePool{
nodes: make([]*upstreamNode, 0, len(keys)),
transports: transports,
cooldown: cooldown,
bindingCount: make([]int, len(transports.items)),
}
if len(keys) == 0 {
return pool, nil
}
for i, key := range keys {
proxyIndex := i % len(transports.items)
node := &upstreamNode{key: key, index: i, preferredProxy: proxyIndex}
node.proxyIndex.Store(int64(proxyIndex))
pool.nodes = append(pool.nodes, node)
pool.bindingCount[proxyIndex]++
}
return pool, nil
}
// RestoreProxy moves keys that were originally assigned to a recovered proxy
// back to it. Proxies without an original key simply become healthy failover
// candidates again.
func (p *nodePool) RestoreProxy(recoveredProxy int) int {
if p == nil || p.transports == nil || recoveredProxy < 0 || recoveredProxy >= len(p.transports.items) {
return 0
}
p.bindingsMu.Lock()
defer p.bindingsMu.Unlock()
moved := 0
for _, node := range p.nodes {
current := int(node.proxyIndex.Load())
if node.preferredProxy != recoveredProxy || current == recoveredProxy {
continue
}
if current >= 0 && current < len(p.bindingCount) {
p.bindingCount[current]--
}
p.bindingCount[recoveredProxy]++
node.proxyIndex.Store(int64(recoveredProxy))
node.failures.Store(0)
node.cooldownUntil.Store(0)
moved++
}
return moved
}
func (p *nodePool) Len() int { return len(p.nodes) }
// NodeByID resolves a node by its stable fingerprint. Callers only ever hold
// the fingerprint, never the key value, so the lookup cannot leak a secret.
func (p *nodePool) NodeByID(id string) *upstreamNode {
if p == nil || id == "" {
return nil
}
for _, node := range p.nodes {
if config.Fingerprint(node.key) == id {
return node
}
}
return nil
}
func (p *nodePool) Proxy(node *upstreamNode) *proxyTransport {
if p == nil || node == nil || p.transports == nil {
return nil
}
index := int(node.proxyIndex.Load())
if index < 0 || index >= len(p.transports.items) {
return nil
}
return p.transports.items[index]
}
// RebindProxy moves every key currently using failedProxy to the least-loaded
// healthy proxy. Empty proxies are selected in configuration order; otherwise
// one of the least-loaded proxies is chosen at random. If every alternative is
// currently unhealthy, it still attempts the least-loaded alternative.
func (p *nodePool) RebindProxy(failedProxy int) int {
if p == nil || p.transports == nil || len(p.transports.items) < 2 || failedProxy < 0 || failedProxy >= len(p.transports.items) {
return 0
}
p.bindingsMu.Lock()
defer p.bindingsMu.Unlock()
moved := 0
for _, node := range p.nodes {
if int(node.proxyIndex.Load()) != failedProxy {
continue
}
target := p.replacementLocked(failedProxy, true)
if target < 0 {
target = p.replacementLocked(failedProxy, false)
}
if target < 0 {
continue
}
p.bindingCount[failedProxy]--
p.bindingCount[target]++
node.proxyIndex.Store(int64(target))
node.failures.Store(0)
node.cooldownUntil.Store(0)
moved++
}
return moved
}
func (p *nodePool) replacementLocked(failedProxy int, healthyOnly bool) int {
minimum := int(^uint(0) >> 1)
candidates := make([]int, 0, len(p.transports.items)-1)
for i := range p.transports.items {
if i == failedProxy || healthyOnly && !p.transports.items[i].healthy.Load() {
continue
}
count := p.bindingCount[i]
if count == 0 {
return i
}
if count < minimum {
minimum = count
candidates = candidates[:0]
candidates = append(candidates, i)
} else if count == minimum {
candidates = append(candidates, i)
}
}
if len(candidates) == 0 {
return -1
}
return candidates[rand.IntN(len(candidates))]
}
type nodeCursor struct {
pool *nodePool
next int
}
// Cursor reserves a different starting node for each concurrent request.
// Selection is delayed until Next, so a node marked failed by the preceding
// attempt is immediately skipped. Both Cursor and Next allocate no memory.
func (p *nodePool) Cursor() nodeCursor {
if len(p.nodes) == 0 {
return nodeCursor{pool: p}
}
return nodeCursor{pool: p, next: int((p.next.Add(1) - 1) % uint64(len(p.nodes)))}
}
// CursorFor returns a cursor whose first choice is stable for the supplied
// affinity key. This keeps every turn in a conversation on the same upstream
// key while retaining Next's cooldown-aware failover behavior. Empty affinity
// keys keep the round-robin behavior used by background tasks.
func (p *nodePool) CursorFor(affinity string) nodeCursor {
if affinity == "" || len(p.nodes) == 0 {
return p.Cursor()
}
hash := fnv.New64a()
_, _ = hash.Write([]byte(affinity))
return nodeCursor{pool: p, next: int(hash.Sum64() % uint64(len(p.nodes)))}
}
func (c *nodeCursor) Next() *upstreamNode {
if c.pool == nil || len(c.pool.nodes) == 0 {
return nil
}
now := time.Now().UnixNano()
choice := -1
var earliest int64
for offset := 0; offset < len(c.pool.nodes); offset++ {
i := (c.next + offset) % len(c.pool.nodes)
until := c.pool.nodes[i].cooldownUntil.Load()
if until <= now {
choice = i
break
}
if choice == -1 || until < earliest {
choice, earliest = i, until
}
}
if choice < 0 {
return nil
}
c.next = (choice + 1) % len(c.pool.nodes)
return c.pool.nodes[choice]
}
func (p *nodePool) MarkSuccess(node *upstreamNode) {
node.failures.Store(0)
node.cooldownUntil.Store(0)
}
func (p *nodePool) MarkFailure(node *upstreamNode, resp *http.Response, err error) {
if err == nil && resp != nil && resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusTooManyRequests && resp.StatusCode < 500 {
return
}
failures := node.failures.Add(1)
multiplier := time.Duration(1 << min(failures-1, 3))
delay := p.cooldown * multiplier
if resp != nil {
if retryAfter := parseRetryAfter(resp.Header.Get("Retry-After")); retryAfter > delay {
delay = retryAfter
}
}
node.cooldownUntil.Store(time.Now().Add(delay).UnixNano())
}
func parseRetryAfter(value string) time.Duration {
if seconds, err := strconv.Atoi(strings.TrimSpace(value)); err == nil && seconds > 0 {
return time.Duration(seconds) * time.Second
+14 -30
View File
@@ -9,7 +9,6 @@ import (
"strings"
"time"
"opencode2api/internal/config"
"opencode2api/internal/identity"
"opencode2api/internal/jsonutil"
"opencode2api/internal/models"
@@ -22,19 +21,17 @@ type probeResult struct {
effort models.EffortProbe
}
func (g *Gateway) resolvedEffort(model string, tier config.Tier, protocol wire.Protocol) string {
func (g *Gateway) resolvedEffort(model string, protocol wire.Protocol) string {
effort := g.cfg.ForcedEffort(model)
if effort != "auto" {
return effort
}
// Only the free Zen lane is actively probed. Never transfer observations
// to a different protocol/tier, or guess a level for an unprobed model.
if tier != config.TierZen || protocol == wire.SystemOne || g.availability == nil || !g.catalog.IsFreeModel(model) {
if protocol == wire.SystemOne || g.availability == nil || !g.catalog.IsFreeModel(model) {
return ""
}
item := g.availability.Get(model)
if !g.catalog.MetadataForTier(model, tier).Reasoning || item.AutoEffort.Effort == "none" {
return "" // Do not inject reasoning into a model that only accepted the baseline.
if !g.catalog.MetadataFor(model).Reasoning || item.AutoEffort.Effort == "none" {
return ""
}
if item.Disabled || item.AutoEffort.Protocol != string(protocol) || time.Since(item.EffortCheckedAt) > 2*models.FreeModelCheckInterval {
return ""
@@ -44,7 +41,6 @@ func (g *Gateway) resolvedEffort(model string, tier config.Tier, protocol wire.P
func probePayload(model string, protocol wire.Protocol, effort string, legacy bool) ([]byte, error) {
if protocol == wire.SystemOne {
// TypeSafe's native boolean type is "noul", not JSON Schema boolean.
return json.Marshal(map[string]any{"model": model, "state": "1 + 1 = 2", "questions": map[string]any{
"arithmetic": map[string]any{"type": "noul", "instructions": "Is 1 + 1 equal to 2?"},
}})
@@ -69,30 +65,24 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult
if !g.catalog.IsFreeModel(model) {
return probeResult{reason: "not_free"}
}
d := g.catalog.Diagnostic(model, wire.Chat, g.zenNodes.Len() > 0, false, g.cfg.Anonymous)
protocol := d.NativeProtocols[config.TierZen]
if !d.AvailableZen || !g.catalog.Supported(model) {
if !g.catalog.Supported(model) {
return probeResult{reason: "unsupported_probe"}
}
route, err := g.catalog.Route(model)
if err != nil {
return probeResult{reason: "unsupported_probe"}
}
protocol := route.Protocol
ids := identity.RequestIDs{Session: identity.CanonicalSessionID("availability:" + model), Project: "opencode2api:default-project"}
type lane struct {
key, name, baseURL string
client *http.Client
}
var lanes []lane
if g.cfg.Anonymous {
cursor := g.anonymous.CursorFor(ids.Session)
if node := cursor.Next(); node != nil {
// Prefer the legacy /zen/v1 lane before falling back to /inference.
for _, baseURL := range g.anonymousUpstreams() {
lanes = append(lanes, lane{anonymousZenKey, "anonymous", baseURL, node.proxy.client})
}
}
}
cursor := g.zenNodes.CursorFor(ids.Session)
cursor := g.anonymous.CursorFor(ids.Session)
if node := cursor.Next(); node != nil {
if proxy := g.zenNodes.Proxy(node); proxy != nil {
lanes = append(lanes, lane{node.key, "zen", g.cfg.Upstream.Zen, proxy.client})
for _, baseURL := range g.anonymousUpstreams() {
lanes = append(lanes, lane{anonymousZenKey, "anonymous", baseURL, node.proxy.client})
}
}
result := probeResult{reason: "no_probe_channel"}
@@ -108,12 +98,11 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult
result.channel = lane.name
if result.success {
if g.cfg.ForcedEffort(model) == "auto" && protocol != wire.SystemOne {
if !g.catalog.MetadataForTier(model, config.TierZen).Reasoning {
if !g.catalog.MetadataFor(model).Reasoning {
result.effort = models.EffortProbe{Effort: "none", Protocol: string(protocol)}
} else {
for _, effort := range []string{"max", "xhigh", "high", "medium", "low", "minimal", "none"} {
if effort == "none" {
// Baseline already succeeded without an effort field.
result.effort = models.EffortProbe{Effort: "none", Protocol: string(protocol)}
break
}
@@ -122,13 +111,9 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult
result.effort = models.EffortProbe{Effort: effort, Protocol: string(protocol)}
break
}
// A rate limit or timeout gives no evidence that a lower
// reasoning level is required. Keep previous observations.
if !trial.effortRejected {
break
}
// Once higher levels were explicitly rejected, do not
// retain an older ceiling if the next trial is inconclusive.
result.effort = models.EffortProbe{Reset: true}
}
}
@@ -139,7 +124,6 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult
inconclusive = result.reason
}
}
// One lane's auth/transient failure cannot establish global unavailability.
if inconclusive != "" {
result.reason = inconclusive
}
+20 -101
View File
@@ -17,31 +17,19 @@ const (
proxyHealthCheckTimeout = 10 * time.Second
)
// syncProxyResult updates proxy health from real traffic. Only timeouts and
// connection refusals mark a proxy unavailable. Any HTTP response — including
// 4xx/5xx — proves the route is reachable and restores a proxy evicted by an
// earlier transient failure, so a rate-limited exit is never blamed on the
// proxy route itself.
func (g *Gateway) syncProxyResult(ctx context.Context, proxy *proxyTransport, status int, err error) bool {
if proxy == nil || proxy.pool {
return false
}
if isProxyFailure(err) {
g.rebindFailedProxy(proxy)
wasHealthy := proxy.healthy.Swap(false)
if wasHealthy {
g.logger.Warn("proxy became unavailable", "component", "proxy", "event", "proxy_unavailable", "proxy", config.RedactURL(proxy.name))
}
g.verifyProxyAfterError(ctx, proxy, status)
return true
}
if status >= 200 && status < 400 {
wasHealthy := proxy.healthy.Swap(true)
if !wasHealthy {
g.restoreProxy(proxy)
}
return false
}
if err == nil && status >= 400 && status < 600 {
// Receiving an HTTP status from the upstream proves the proxy route
// itself is reachable; restore an unhealthy flag left by an earlier
// transient timeout instead of keeping the route evicted.
if status >= 200 && status < 600 && err == nil {
wasHealthy := proxy.healthy.Swap(true)
if !wasHealthy {
g.restoreProxy(proxy)
@@ -50,7 +38,6 @@ func (g *Gateway) syncProxyResult(ctx context.Context, proxy *proxyTransport, st
}
if err != nil {
g.verifyProxyAfterError(ctx, proxy, status)
return false
}
return false
}
@@ -59,8 +46,6 @@ func (g *Gateway) verifyProxyAfterError(ctx context.Context, proxy *proxyTranspo
if !proxy.checking.CompareAndSwap(false, true) {
return
}
// The client request may finish or be cancelled while the verification is
// running. Keep its values but give the proxy check an independent timeout.
checkCtx := context.WithoutCancel(ctx)
go func() {
result := g.transports.checkClaimedProxy(checkCtx, proxy, proxyHealthCheckURL, proxyHealthCheckTimeout)
@@ -68,36 +53,14 @@ func (g *Gateway) verifyProxyAfterError(ctx context.Context, proxy *proxyTranspo
}()
}
func (g *Gateway) rebindFailedProxy(proxy *proxyTransport) (zenMoved, goMoved int) {
func (g *Gateway) restoreProxy(proxy *proxyTransport) {
if proxy == nil {
return 0, 0
return
}
wasHealthy := proxy.healthy.Swap(false)
return g.rebindUnavailableProxy(proxy, wasHealthy)
}
func (g *Gateway) rebindUnavailableProxy(proxy *proxyTransport, wasHealthy bool) (zenMoved, goMoved int) {
zenMoved = g.zenNodes.RebindProxy(proxy.index)
goMoved = g.goNodes.RebindProxy(proxy.index)
if wasHealthy || zenMoved+goMoved > 0 {
g.logger.Warn("proxy became unavailable", "component", "proxy", "event", "proxy_unavailable", "proxy", config.RedactURL(proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved)
}
return zenMoved, goMoved
}
func (g *Gateway) restoreProxy(proxy *proxyTransport) (zenMoved, goMoved int) {
if proxy == nil {
return 0, 0
}
zenMoved = g.zenNodes.RestoreProxy(proxy.index)
goMoved = g.goNodes.RestoreProxy(proxy.index)
// The anonymous lane carries its own per-proxy cooldowns; key recovery
// alone would leave it skipped after an outage-era failure.
anonCleared := g.anonymous.RestoreProxy(proxy)
if zenMoved+goMoved > 0 || anonCleared > 0 {
g.logger.Info("proxy connectivity restored", "component", "proxy", "event", "proxy_restored", "proxy", config.RedactURL(proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved, "anonymous_cleared", anonCleared)
if anonCleared > 0 {
g.logger.Info("proxy connectivity restored", "component", "proxy", "event", "proxy_restored", "proxy", config.RedactURL(proxy.name), "anonymous_cleared", anonCleared)
}
return zenMoved, goMoved
}
func (g *Gateway) StartProxyHealthChecks(ctx context.Context) {
@@ -133,25 +96,21 @@ func (g *Gateway) applyProxyHealthResult(result proxyHealthResult, source string
g.logger.Debug("proxy health check was inconclusive", "component", "proxy", "event", "health_check_inconclusive", "source", source, "upstream_status", upstreamStatus, "proxy", config.RedactURL(result.proxy.name), "error", result.err)
return
}
if g.transports.hasHealthy() {
zenMoved, goMoved := g.rebindUnavailableProxy(result.proxy, result.wasHealthy)
if result.wasHealthy || zenMoved+goMoved > 0 {
g.logger.Warn("proxy health check failed", "component", "proxy", "event", "health_check_failed", "source", source, "upstream_status", upstreamStatus, "proxy", config.RedactURL(result.proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved, "error", result.err)
return
}
if g.transports.hasHealthy() && result.wasHealthy {
g.logger.Warn("proxy health check failed", "component", "proxy", "event", "health_check_failed", "source", source, "upstream_status", upstreamStatus, "proxy", config.RedactURL(result.proxy.name), "error", result.err)
return
}
g.logger.Debug("proxy health check is still failing", "component", "proxy", "event", "health_check_still_failing", "source", source, "upstream_status", upstreamStatus, "proxy", config.RedactURL(result.proxy.name), "error", result.err)
}
func (g *Gateway) StartModelRefresh(ctx context.Context) {
refresh := func() {
var zen, goModels []string
var zen []string
var capabilities modelcatalog.Capabilities
var capabilitiesErr error
var wg sync.WaitGroup
wg.Add(3)
go func() { defer wg.Done(); zen = g.refreshZen(ctx) }()
go func() { defer wg.Done(); goModels = g.refreshTier(ctx, g.cfg.Upstream.Go, g.goNodes) }()
wg.Add(2)
go func() { defer wg.Done(); zen = g.refreshAnonymousTier(ctx) }()
go func() {
defer wg.Done()
capabilityCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
@@ -165,9 +124,8 @@ func (g *Gateway) StartModelRefresh(ctx context.Context) {
if capabilitiesErr != nil {
g.logger.Warn("OpenCode capability catalog refresh failed", "component", "models", "event", "capability_refresh_failed", "error", capabilitiesErr)
}
if zen != nil || goModels != nil {
g.catalog.ReplaceWithCapabilities(zen, goModels, capabilities.Protocols, capabilities.Unsupported, capabilities.Metadata)
g.syncRotation()
if zen != nil {
g.catalog.ReplaceWithCapabilities(zen, capabilities.Protocols, capabilities.Unsupported, capabilities.Metadata)
if ctx.Err() == nil {
if err := g.catalog.SaveCache(); err != nil {
g.logger.Warn("model catalog cache write failed", "component", "models", "event", "catalog_cache_write_failed", "error", err)
@@ -212,17 +170,7 @@ func (g *Gateway) refreshProtocolCapabilities(ctx context.Context) (modelcatalog
return modelcatalog.Capabilities{}, lastErr
}
func (g *Gateway) refreshZen(ctx context.Context) []string {
if models := g.refreshTier(ctx, g.cfg.Upstream.Zen, g.zenNodes); models != nil {
return models
}
if !g.cfg.Anonymous {
return nil
}
return g.refreshAnonymousTier(ctx, g.cfg.Upstream.Anonymous)
}
func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []string {
func (g *Gateway) refreshAnonymousTier(ctx context.Context) []string {
cursor := g.anonymous.CursorFor("")
limit := g.anonymous.Len()
if g.anonymous.HasPool() && g.cfg.Retry.MaxAttempts > limit {
@@ -237,8 +185,6 @@ func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []strin
var models []string
var status int
var err error
// Prefer the legacy /zen/v1 models listing before falling back to the
// configured anonymous upstream.
for _, upstream := range g.anonymousUpstreams() {
models, status, err = modelcatalog.FetchModels(refreshCtx, node.proxy.client, upstream, anonymousZenKey)
if err == nil {
@@ -252,35 +198,8 @@ func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []strin
return models
}
g.anonymous.MarkFailure(node, nil, err)
g.logger.Debug("anonymous model catalog refresh attempt failed", "component", "models", "event", "anonymous_refresh_attempt_failed", "upstream", config.RedactURL(base), "attempt", attempt, "proxy", config.RedactURL(node.proxy.name), "error", err)
g.logger.Debug("anonymous model catalog refresh attempt failed", "component", "models", "event", "anonymous_refresh_attempt_failed", "attempt", attempt, "proxy", config.RedactURL(node.proxy.name), "error", err)
}
g.logger.Warn("anonymous model catalog refresh failed", "component", "models", "event", "anonymous_refresh_failed", "upstream", config.RedactURL(base))
return nil
}
func (g *Gateway) refreshTier(ctx context.Context, base string, nodes *nodePool) []string {
cursor := nodes.Cursor()
for attempt := 0; attempt < g.cfg.Retry.MaxAttempts; attempt++ {
node := cursor.Next()
if node == nil {
return nil
}
refreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
proxy := nodes.Proxy(node)
if proxy == nil {
cancel()
return nil
}
models, status, err := modelcatalog.FetchModels(refreshCtx, proxy.client, base, node.key)
g.syncProxyResult(refreshCtx, proxy, status, err)
cancel()
if err == nil {
nodes.MarkSuccess(node)
return models
}
nodes.MarkFailure(node, nil, err)
g.logger.Debug("model catalog refresh attempt failed", "component", "models", "event", "refresh_attempt_failed", "upstream", config.RedactURL(base), "attempt", attempt+1, "error", err)
}
g.logger.Warn("model catalog refresh failed", "component", "models", "event", "refresh_failed", "upstream", config.RedactURL(base))
g.logger.Warn("anonymous model catalog refresh failed", "component", "models", "event", "anonymous_refresh_failed")
return nil
}
-367
View File
@@ -1,367 +0,0 @@
package gateway
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
"opencode2api/internal/config"
"opencode2api/internal/identity"
"opencode2api/internal/jsonutil"
"opencode2api/internal/models"
wire "opencode2api/internal/protocol"
"opencode2api/internal/rotation"
"opencode2api/internal/telemetry"
)
func (g *Gateway) syncRotation() {
available := map[string]bool{}
for _, model := range g.catalog.List() {
if route, err := g.catalog.RouteForTier(model, config.TierGo, false, g.goNodes.Len() > 0); err == nil && route.Protocol != wire.SystemOne {
available[model] = true
}
}
g.rotation.Sync(available)
}
func (m *RuntimeManager) RotationSnapshot() rotation.Snapshot {
r := m.current.Load()
r.gateway.syncRotation()
return m.rotation.Snapshot()
}
func (m *RuntimeManager) SelectRotation(id, model string) error {
m.updateMu.Lock()
defer m.updateMu.Unlock()
m.current.Load().gateway.syncRotation()
return m.rotation.Manual(id, model)
}
// Explicit quota markers only: ordinary provider errors must keep their budget.
func quotaError(status int, body string) bool {
if status == 429 {
return true
}
body = strings.ToLower(body)
for _, marker := range []string{"insufficient_quota", "quota_exceeded", "quota exceeded", "quota exhausted", "rate_limit", "rate limit", "rate-limit", "usage_limit", "usage limit", "insufficient balance", "credit balance is too low", "额度不足", "配额已用尽"} {
if strings.Contains(body, marker) {
return true
}
}
return false
}
type groupAttempt struct {
err error
quota, committed bool
pause time.Duration
reason string
}
func (g *Gateway) handleRotation(w http.ResponseWriter, r *http.Request, external wire.Protocol, payload map[string]any, id, alias string) {
g.syncRotation()
ctx, cancel := context.WithTimeout(r.Context(), time.Duration(g.cfg.Retry.TimeoutSeconds)*time.Second)
defer cancel()
ids := identity.DeriveRequestIDs(r, payload)
meta := telemetry.MetaFromRequest(r)
if meta != nil {
meta.Request = ids.Request
meta.Session = ids.Session
meta.ModelAlias = alias
}
visited := map[string]bool{}
ordinaryModels, total := 0, 0
for ctx.Err() == nil {
token, ok := g.rotation.Select(id, visited)
if !ok {
break
}
visited[token.Model] = true
route, err := g.catalog.RouteForTier(token.Model, config.TierGo, false, g.goNodes.Len() > 0)
if err != nil {
continue
}
counted := false
for n := 1; n <= 3 && ctx.Err() == nil; n++ {
total++
if meta != nil {
meta.Model = token.Model
meta.Tier = "go"
meta.Protocol = route.Protocol
meta.Attempts = total
meta.Usage = wire.Usage{}
meta.UsageReported = false
}
result := g.rotationAttempt(ctx, w, r, external, payload, alias, route, ids, total)
outcome := result.reason
if result.err == nil {
outcome = "success"
}
var clientWrite *wire.ClientWriteError
canceled := r.Context().Err() != nil || errors.As(result.err, &clientWrite)
if canceled {
outcome = "client_canceled"
if meta != nil {
meta.Outcome = outcome
}
}
g.rotation.Record(rotation.Attempt{Request: ids.Request, Alias: alias, Model: token.Model, Number: total, Outcome: outcome})
if state := g.rotation.Snapshot(); state.PersistenceError != "" {
g.logger.Error("rotation state persistence failed", "component", "rotation", "event", "rotation_persistence_failed")
}
g.logger.Info("model rotation attempt", "component", "rotation", "event", "rotation_attempt", "request_id", ids.Request, "alias", alias, "model", token.Model, "attempt", total, "reason", outcome)
if canceled {
return
}
if result.err == nil {
return
}
if result.committed {
if meta != nil {
meta.Outcome = "stream_error"
}
pause := 15 * time.Second
if result.quota {
pause = result.pause
}
g.rotation.Fail(token, pause, result.reason)
return
}
if ctx.Err() != nil {
g.rotation.Fail(token, 15*time.Second, "request_timeout")
break
}
if result.quota {
g.rotation.Fail(token, result.pause, result.reason)
break
}
if !counted {
ordinaryModels++
counted = true
}
if n == 3 {
g.rotation.Fail(token, 15*time.Second, result.reason)
}
}
if ordinaryModels >= 3 {
break
}
}
if r.Context().Err() != nil {
return
}
status := http.StatusServiceUnavailable
message := "该分组暂无可用模型(已暂停、下架、额度不足或重试次数已用尽),请稍后重试"
if ctx.Err() != nil {
status = http.StatusGatewayTimeout
message = "分组请求整体超时"
}
wire.WriteError(w, external, status, message, "rotation_unavailable", ids.Request)
}
func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter, original *http.Request, external wire.Protocol, payload map[string]any, alias string, route models.Route, ids identity.RequestIDs, attempt int) groupAttempt {
result := groupAttempt{reason: "upstream_error", pause: 60 * time.Second}
ctx, cancel := context.WithCancel(parent)
defer cancel()
seconds := g.rotation.Snapshot().FirstOutputSeconds
timer := time.AfterFunc(time.Duration(seconds)*time.Second, cancel)
defer timer.Stop()
copyPayload := make(map[string]any, len(payload))
for k, v := range payload {
copyPayload[k] = v
}
copyPayload["model"] = route.ID
bodies, err := g.prepareRouteBodies(external, route, copyPayload)
if err != nil {
result.err = err
result.reason = "request_conversion_error"
return result
}
body, toolAlias, shaped := g.shapeKeyBody(bodies[config.TierGo], route, config.TierGo)
if meta := telemetry.MetaFromContext(parent); meta != nil {
meta.ToolAlias = toolAlias
}
cursor := g.goNodes.CursorFor(ids.Session)
var node *upstreamNode
// Each group attempt is exactly one HTTP call. Key selection may change,
// but there is no nested retry, stale-reasoning replay, or model-wide key ban.
for n := 0; n < attempt; n++ {
node = cursor.Next()
}
if node == nil {
result.err = errors.New("no Go key")
return result
}
proxy := g.goNodes.Proxy(node)
if proxy == nil {
result.err = errors.New("no proxy")
return result
}
req, err := newUpstreamRequest(ctx, g.cfg.Upstream.Go, route.Protocol, body, ids, node.key)
if err != nil {
result.err = err
return result
}
// A reused connection must not cause net/http to implicitly replay POSTs.
req.GetBody = nil
client := *proxy.client
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
setRequestCredential(parent, config.TierGo, config.KeyDisplayID(node.key), "key", false, proxy)
started := time.Now()
resp, err := client.Do(req)
g.recordUpstreamAttempt(parent, route, ids, attempt, config.KeyDisplayID(node.key), "key", false, proxy, resp, err, time.Since(started))
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
result.err = err
result.reason = "transport_error"
if ctx.Err() != nil {
result.reason = "first_output_timeout"
}
return result
}
retryAfter := resp.Header.Get("Retry-After")
if pause := parseRetryAfter(retryAfter); pause > 0 {
result.pause = pause
} else if strings.TrimSpace(retryAfter) == "0" {
result.pause = 0
} else if _, err := http.ParseTime(retryAfter); err == nil {
result.pause = 0
}
if resp.StatusCode/100 != 2 {
b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
result.err = fmt.Errorf("upstream HTTP %d", resp.StatusCode)
result.quota = quotaError(resp.StatusCode, string(b))
result.reason = fmt.Sprintf("http_%d", resp.StatusCode)
if result.quota {
result.reason = "quota_or_rate_limit"
}
return result
}
stream := jsonutil.BoolAt(payload, "stream")
ready := func() error {
if !timer.Stop() || ctx.Err() != nil {
return context.DeadlineExceeded
}
w.Header().Set("X-Resolved-Model", route.ID)
w.Header().Set("x-request-id", ids.Request)
w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("X-Accel-Buffering", "no")
return nil
}
meta := telemetry.MetaFromContext(parent)
if stream {
if meta != nil {
meta.Stream = true
}
if g.monitor != nil {
g.monitor.BeginStream()
defer g.monitor.EndStream()
}
streamBody := wire.RenameStreamReader(resp.Body, route.Protocol, legacyAnonymousReadTool, toolAlias)
usage, reported, committed, err := wire.RotationStream(original.Context(), w, streamBody, route.Protocol, external, alias, ready)
if meta != nil {
meta.Usage = usage
meta.UsageReported = reported
}
result.err = err
result.committed = committed
result.reason = "stream_error"
var failure *wire.StreamFailure
if errors.As(err, &failure) {
result.quota = quotaError(0, failure.Type+" "+failure.Message)
}
if result.quota {
result.reason = "quota_or_rate_limit"
} else if !committed && ctx.Err() != nil {
result.reason = "first_output_timeout"
}
return result
}
b, err := io.ReadAll(io.LimitReader(resp.Body, (64<<20)+1))
if err == nil && len(b) > 64<<20 {
err = errors.New("response exceeds size limit")
}
if err != nil {
result.err = err
result.reason = "response_read_error"
return result
}
if !timer.Stop() || ctx.Err() != nil {
result.err = context.DeadlineExceeded
result.reason = "first_output_timeout"
return result
}
if shaped {
b, err = wire.CollapseStream(bytes.NewReader(b), route.Protocol, route.ID)
}
if err == nil {
b = wire.RenameResponseTool(b, route.Protocol, legacyAnonymousReadTool, toolAlias)
}
var document map[string]any
if err == nil {
err = json.Unmarshal(b, &document)
}
if err == nil && document == nil {
err = errors.New("empty upstream response")
}
if err == nil && document["error"] != nil {
result.quota = quotaError(0, string(b))
err = errors.New("upstream error envelope")
}
if err == nil {
valid := false
switch route.Protocol {
case wire.Chat:
_, valid = document["choices"].([]any)
case wire.Anthropic:
_, valid = document["content"].([]any)
case wire.Responses:
_, valid = document["output"].([]any)
}
if !valid {
err = errors.New("invalid response schema")
}
}
if err == nil && external != route.Protocol {
b, err = wire.ConvertResponse(route.Protocol, external, b)
}
if err != nil {
result.err = err
result.reason = "response_conversion_error"
if result.quota {
result.reason = "quota_or_rate_limit"
}
return result
}
if meta != nil {
meta.Usage, meta.UsageReported = wire.ResponseUsage(external, b)
}
document = nil
if err = json.Unmarshal(b, &document); err != nil {
result.err = err
result.reason = "response_conversion_error"
return result
}
document["model"] = alias
b, err = json.Marshal(document)
if err != nil {
result.err = err
return result
}
w.Header().Set("X-Resolved-Model", route.ID)
w.Header().Set("x-request-id", ids.Request)
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(b)
if err != nil {
result.err = &wire.ClientWriteError{Err: err}
}
result.committed = true
return result
}
+3 -331
View File
@@ -8,12 +8,9 @@ import (
"os"
"sync"
"sync/atomic"
"time"
"opencode2api/internal/config"
modelcatalog "opencode2api/internal/models"
"opencode2api/internal/protocol"
"opencode2api/internal/rotation"
"opencode2api/internal/telemetry"
)
@@ -25,42 +22,24 @@ type gatewayRuntime struct {
cancel context.CancelFunc
}
type ApplyResult struct {
Applied bool `json:"applied"`
RestartRequired bool `json:"restart_required"`
RestartFields []string `json:"restart_fields,omitempty"`
}
type RuntimeManager struct {
rotation *rotation.Manager
configPath string
root context.Context
logger *slog.Logger
monitor *telemetry.Monitor
hub *telemetry.LogHub
redactor *config.SecretRedactor
level *slog.LevelVar
current atomic.Pointer[gatewayRuntime]
updateMu sync.Mutex
effective effectiveListeners
metadata *modelcatalog.PricingStore
availabilityCancel context.CancelFunc
}
type effectiveListeners struct {
API string
WebUI string
WebUIEnabled bool
}
func NewRuntimeManager(root context.Context, configPath string, cfg config.Config, logger *slog.Logger, monitor *telemetry.Monitor, hub *telemetry.LogHub, redactor *config.SecretRedactor, level *slog.LevelVar) (*RuntimeManager, error) {
func NewRuntimeManager(root context.Context, configPath string, cfg config.Config, logger *slog.Logger, monitor *telemetry.Monitor, redactor *config.SecretRedactor, level *slog.LevelVar) (*RuntimeManager, error) {
manager := &RuntimeManager{
configPath: configPath, root: root, logger: logger, monitor: monitor, hub: hub, redactor: redactor, level: level,
effective: effectiveListeners{API: cfg.Listen, WebUI: cfg.WebUI.Listen, WebUIEnabled: cfg.WebUI.Enabled},
configPath: configPath, root: root, logger: logger, monitor: monitor, redactor: redactor, level: level,
}
manager.metadata = modelcatalog.NewPricingStore(configPath, logger)
// models.dev refreshes ride the active runtime's healthy proxy transports
// and fall back to the store's direct client when none are available.
manager.metadata.SetClientProvider(func() []*http.Client {
runtime := manager.current.Load()
if runtime == nil || runtime.gateway == nil || runtime.gateway.transports == nil {
@@ -74,26 +53,6 @@ func NewRuntimeManager(root context.Context, configPath string, cfg config.Confi
}
return clients
})
if cfg.WebUI.Password != "" {
hash, err := config.HashPassword(cfg.WebUI.Password)
if err != nil {
return nil, fmt.Errorf("hash webui password: %w", err)
}
cfg.WebUI.PasswordHash = hash
cfg.WebUI.Password = ""
if err := config.SaveAtomic(configPath, cfg); err != nil {
return nil, fmt.Errorf("persist webui password migration: %w", err)
}
// The automatically-created backup contains the one-time plaintext
// bootstrap password and must not be retained.
_ = os.Remove(configPath + ".bak")
}
cfg.Rotation.Defaults()
rotationManager, err := rotation.New(configPath+".rotation.json", cfg.Rotation)
if err != nil {
return nil, err
}
manager.rotation = rotationManager
runtime, err := manager.build(cfg)
if err != nil {
return nil, err
@@ -103,10 +62,6 @@ func NewRuntimeManager(root context.Context, configPath string, cfg config.Confi
manager.logger.Warn("model catalog cache ignored", "component", "models", "event", "catalog_cache_load_failed", "path", modelcatalog.CatalogCachePath(configPath), "error", err)
}
}
if err := cfg.Rotation.Validate(runtime.gateway.catalog.List()); err != nil {
return nil, err
}
runtime.gateway.syncRotation()
manager.current.Store(runtime)
manager.redactor.Replace(cfg)
telemetry.SetLogLevel(manager.level, cfg.Logging.Level)
@@ -117,11 +72,10 @@ func NewRuntimeManager(root context.Context, configPath string, cfg config.Confi
}
func (m *RuntimeManager) build(cfg config.Config) (*gatewayRuntime, error) {
gateway, err := New(cfg, m.logger, m.monitor)
gateway, err := New(cfg, m.logger, m.monitor, m.redactor)
if err != nil {
return nil, err
}
gateway.rotation = m.rotation
availabilityPath := ""
if m.configPath != "" {
availabilityPath = m.configPath + "." + config.Fingerprint(cfg.Upstream.Zen) + ".availability.json"
@@ -141,8 +95,6 @@ func (m *RuntimeManager) build(cfg config.Config) (*gatewayRuntime, error) {
}
func (m *RuntimeManager) start(runtime *gatewayRuntime) {
// Store the context through a lightweight wrapper so cancel stops catalog
// and proxy checks while in-flight HTTP requests continue on the old pools.
runtimeCtx, cancel := context.WithCancel(m.root)
runtime.cancel = cancel
runtime.gateway.StartProxyHealthChecks(runtimeCtx)
@@ -161,124 +113,6 @@ func (m *RuntimeManager) Handler() http.Handler {
return telemetry.Middleware(m.monitor, m.logger, dynamic)
}
// Redact removes configured credentials from diagnostic output.
func (m *RuntimeManager) Redact(value string) string {
return m.redactor.String(value)
}
func (m *RuntimeManager) Config() config.Config {
runtime := m.current.Load()
if runtime == nil {
return config.Config{}
}
return config.Clone(runtime.config)
}
func (m *RuntimeManager) RestartStatus() (effectiveListeners, []string) {
cfg := m.Config()
fields := make([]string, 0, 3)
if cfg.Listen != m.effective.API {
fields = append(fields, "listen")
}
if cfg.WebUI.Listen != m.effective.WebUI {
fields = append(fields, "webui.listen")
}
if cfg.WebUI.Enabled != m.effective.WebUIEnabled {
fields = append(fields, "webui.enabled")
}
return m.effective, fields
}
func (m *RuntimeManager) Apply(candidate config.Config, persist bool) (ApplyResult, error) {
m.updateMu.Lock()
defer m.updateMu.Unlock()
return m.applyLocked(candidate, persist)
}
// Update serializes read-modify-write operations against the latest config.
func (m *RuntimeManager) Update(change func(*config.Config) error) (ApplyResult, error) {
m.updateMu.Lock()
defer m.updateMu.Unlock()
candidate := m.Config()
if err := change(&candidate); err != nil {
return ApplyResult{}, err
}
return m.applyLocked(candidate, true)
}
func (m *RuntimeManager) applyLocked(candidate config.Config, persist bool) (ApplyResult, error) {
current := m.current.Load()
hadPlaintextPassword := candidate.WebUI.Password != ""
if hadPlaintextPassword {
hash, err := config.HashPassword(candidate.WebUI.Password)
if err != nil {
return ApplyResult{}, err
}
candidate.WebUI.PasswordHash = hash
candidate.WebUI.Password = ""
}
normalized, err := config.Normalize(m.configPath, candidate)
if err != nil {
return ApplyResult{}, err
}
next, err := m.build(normalized)
if err != nil {
return ApplyResult{}, fmt.Errorf("initialize runtime: %w", err)
}
if current != nil {
next.gateway.catalog.CopyState(current.gateway.catalog)
}
if err := normalized.Rotation.Validate(next.gateway.catalog.List()); err != nil {
return ApplyResult{}, err
}
if persist || hadPlaintextPassword {
if err := config.SaveAtomic(m.configPath, normalized); err != nil {
next.cancel()
return ApplyResult{}, err
}
}
result := ApplyResult{Applied: true}
if normalized.Listen != m.effective.API {
result.RestartFields = append(result.RestartFields, "listen")
}
if normalized.WebUI.Listen != m.effective.WebUI {
result.RestartFields = append(result.RestartFields, "webui.listen")
}
if normalized.WebUI.Enabled != m.effective.WebUIEnabled {
result.RestartFields = append(result.RestartFields, "webui.enabled")
}
result.RestartRequired = len(result.RestartFields) > 0
m.redactor.Replace(normalized)
telemetry.SetLogLevel(m.level, normalized.Logging.Level)
if current == nil || normalized.Logging.RingSize != current.config.Logging.RingSize {
m.hub.Resize(normalized.Logging.RingSize)
}
m.rotation.Configure(normalized.Rotation)
next.gateway.syncRotation()
m.start(next)
previous := m.current.Swap(next)
if previous != nil {
previous.cancel()
}
m.logger.Info("configuration applied", "component", "config", "event", "config_applied", "restart_required", result.RestartRequired, "restart_fields", result.RestartFields)
return result, nil
}
func (m *RuntimeManager) Reload() (ApplyResult, error) {
cfg, err := config.Load(m.configPath)
if err != nil {
return ApplyResult{}, err
}
hadPlaintextPassword := cfg.WebUI.Password != ""
result, err := m.Apply(cfg, false)
if err == nil && hadPlaintextPassword {
_ = os.Remove(m.configPath + ".bak")
}
return result, err
}
func (m *RuntimeManager) Shutdown() {
if m.availabilityCancel != nil {
m.availabilityCancel()
@@ -287,165 +121,3 @@ func (m *RuntimeManager) Shutdown() {
current.cancel()
}
}
type ResourceSnapshot struct {
Models modelcatalog.CatalogSnapshot `json:"models"`
Keys []KeyStatus `json:"keys"`
Proxies []ProxyStatus `json:"proxies"`
Anonymous bool `json:"anonymous"`
Metadata modelcatalog.MetadataSnapshot `json:"metadata"`
}
type KeyStatus struct {
ID string `json:"id"`
Tier string `json:"tier"`
Index int `json:"index"`
ProxyIndex int `json:"proxy_index"`
Failures uint32 `json:"failures"`
CooldownUntil *time.Time `json:"cooldown_until,omitempty"`
}
type ProxyStatus struct {
Index int `json:"index"`
Address string `json:"address"`
Healthy bool `json:"healthy"`
Checking bool `json:"checking"`
ZenKeys int `json:"zen_keys"`
GoKeys int `json:"go_keys"`
Anonymous bool `json:"anonymous"`
}
func (m *RuntimeManager) Resources() ResourceSnapshot {
runtime := m.current.Load()
if runtime == nil {
return ResourceSnapshot{}
}
gateway := runtime.gateway
_, models := gateway.availableModels()
result := ResourceSnapshot{Models: models, Anonymous: gateway.cfg.Anonymous}
result.Metadata = gateway.catalog.MetadataSnapshot()
result.Keys = append(result.Keys, keyStatuses("zen", gateway.zenNodes)...)
result.Keys = append(result.Keys, keyStatuses("go", gateway.goNodes)...)
gateway.zenNodes.bindingsMu.Lock()
zenBindings := append([]int(nil), gateway.zenNodes.bindingCount...)
gateway.zenNodes.bindingsMu.Unlock()
gateway.goNodes.bindingsMu.Lock()
goBindings := append([]int(nil), gateway.goNodes.bindingCount...)
gateway.goNodes.bindingsMu.Unlock()
for _, proxy := range gateway.transports.items {
status := ProxyStatus{Index: proxy.index, Address: config.RedactURL(proxy.name), Healthy: proxy.healthy.Load(), Checking: proxy.checking.Load(), Anonymous: gateway.cfg.Anonymous}
if proxy.index < len(zenBindings) {
status.ZenKeys = zenBindings[proxy.index]
}
if proxy.index < len(goBindings) {
status.GoKeys = goBindings[proxy.index]
}
result.Proxies = append(result.Proxies, status)
}
return result
}
func (m *RuntimeManager) DebugModels() ([]modelcatalog.RouteDiagnostic, modelcatalog.MetadataSnapshot) {
runtime := m.current.Load()
if runtime == nil {
return nil, modelcatalog.MetadataSnapshot{}
}
gateway := runtime.gateway
models := gateway.catalog.List()
result := make([]modelcatalog.RouteDiagnostic, 0, len(models))
for _, model := range models {
result = append(result, gateway.catalog.Diagnostic(model, "", len(gateway.cfg.ZenKeys) > 0, len(gateway.cfg.GoKeys) > 0, gateway.cfg.Anonymous))
}
metadata := gateway.catalog.MetadataSnapshot()
return result, metadata
}
func (m *RuntimeManager) DebugRoute(model string, requested protocol.Protocol) modelcatalog.RouteDiagnostic {
runtime := m.current.Load()
if runtime == nil {
return modelcatalog.RouteDiagnostic{Model: model, RequestedProtocol: requested, RouteError: "gateway runtime is unavailable"}
}
gateway := runtime.gateway
return gateway.catalog.Diagnostic(model, requested, len(gateway.cfg.ZenKeys) > 0, len(gateway.cfg.GoKeys) > 0, gateway.cfg.Anonymous)
}
// DebugKeyView is the operator-facing view of one configured upstream key. It
// carries only the redacted suffix and the stable fingerprint, never the value.
type DebugKeyView struct {
ID string `json:"id"`
Tier config.Tier `json:"tier"`
Display string `json:"display"`
Index int `json:"index"`
Failures uint32 `json:"failures"`
CooldownUntil *time.Time `json:"cooldown_until,omitempty"`
}
// DebugKeys lists every configured upstream key per tier so the Playground can
// offer an explicit per-key test target.
func (m *RuntimeManager) DebugKeys() map[string][]DebugKeyView {
result := map[string][]DebugKeyView{"zen": {}, "go": {}}
runtime := m.current.Load()
if runtime == nil {
return result
}
appendKeys := func(tier config.Tier, nodes []*upstreamNode) {
for _, node := range nodes {
view := DebugKeyView{
ID: config.Fingerprint(node.key), Tier: tier, Display: config.MaskValue(node.key),
Index: node.index, Failures: node.failures.Load(),
}
if until := node.cooldownUntil.Load(); until > time.Now().UnixNano() {
value := time.Unix(0, until).UTC()
view.CooldownUntil = &value
}
result[string(tier)] = append(result[string(tier)], view)
}
}
appendKeys(config.TierZen, runtime.gateway.zenNodes.nodes)
appendKeys(config.TierGo, runtime.gateway.goNodes.nodes)
return result
}
func (m *RuntimeManager) DebugKey(tier config.Tier, id string) *DebugKeyView {
for _, view := range m.DebugKeys()[string(tier)] {
if view.ID == id {
selected := view
return &selected
}
}
return nil
}
// DebugRouteForTier reports the route a diagnostic against one tier would take.
func (m *RuntimeManager) DebugRouteForTier(model string, tier config.Tier) (modelcatalog.RouteDiagnostic, error) {
runtime := m.current.Load()
if runtime == nil {
return modelcatalog.RouteDiagnostic{Model: model, RouteError: "gateway runtime is unavailable"}, fmt.Errorf("gateway runtime is unavailable")
}
gateway := runtime.gateway
hasZen, hasGo := len(gateway.cfg.ZenKeys) > 0, len(gateway.cfg.GoKeys) > 0
diagnostic := gateway.catalog.Diagnostic(model, "", hasZen, hasGo, false)
route, err := gateway.catalog.RouteForTier(model, tier, hasZen, hasGo)
if err != nil {
diagnostic.RouteError = err.Error()
return diagnostic, err
}
diagnostic.RouteError = ""
diagnostic.Tier, diagnostic.Anonymous = route.Tier, false
diagnostic.KeyTiers = []config.Tier{tier}
diagnostic.NativeProtocol, diagnostic.NativeProtocols = route.Protocol, route.Protocols
return diagnostic, nil
}
func keyStatuses(tier string, pool *nodePool) []KeyStatus {
result := make([]KeyStatus, 0, len(pool.nodes))
for _, node := range pool.nodes {
status := KeyStatus{ID: config.KeyDisplayID(node.key), Tier: tier, Index: node.index, ProxyIndex: int(node.proxyIndex.Load()), Failures: node.failures.Load()}
if until := node.cooldownUntil.Load(); until > time.Now().UnixNano() {
value := time.Unix(0, until).UTC()
status.CooldownUntil = &value
}
result = append(result, status)
}
return result
}
+81 -594
View File
@@ -11,7 +11,6 @@ import (
"fmt"
"io"
"net/http"
"sort"
"strconv"
"strings"
"sync"
@@ -26,108 +25,54 @@ import (
"opencode2api/internal/telemetry"
)
// DebugKeyOverride pins one inference request to a single configured upstream
// key so the Playground can exercise that key in isolation.
type DebugKeyOverride struct {
Tier config.Tier
KeyID string
}
type debugKeyOverrideContextKey struct{}
type diagnosticContextKey struct{}
func WithDiagnosticRequest(ctx context.Context) context.Context {
return context.WithValue(ctx, diagnosticContextKey{}, true)
}
func isDiagnosticRequest(ctx context.Context) bool {
diagnostic, _ := ctx.Value(diagnosticContextKey{}).(bool)
return diagnostic
}
func WithDebugKeyOverride(ctx context.Context, override DebugKeyOverride) context.Context {
return context.WithValue(WithDiagnosticRequest(ctx), debugKeyOverrideContextKey{}, override)
}
func debugKeyOverrideFrom(ctx context.Context) (DebugKeyOverride, bool) {
override, ok := ctx.Value(debugKeyOverrideContextKey{}).(DebugKeyOverride)
return override, ok && override.KeyID != ""
}
func (g *Gateway) doUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs) (*http.Response, models.Route, error) {
resp, effectiveRoute, attempts, err := g.doUpstreamTiers(ctx, route, bodies, ids, 0)
if _, selected := debugKeyOverrideFrom(ctx); selected {
return resp, effectiveRoute, err
}
func (g *Gateway) doUpstream(ctx context.Context, route models.Route, body []byte, ids identity.RequestIDs) (*http.Response, error) {
g.dumpOutboundBody(route, body, ids, 0)
resp, err, attempts := g.doAnonymousUpstream(ctx, route, body, ids, 0)
if err != nil || resp == nil || resp.StatusCode != http.StatusBadRequest {
return resp, effectiveRoute, err
return resp, err
}
origBody := resp.Body
errBody, readErr := io.ReadAll(io.LimitReader(origBody, 1<<20))
// The original network body is always closed here: the retry path below
// reuses the connection, otherwise downstream receives a fresh in-memory
// reader over the cached bytes.
httpx.DrainAndClose(origBody)
if readErr != nil {
resp.Body = io.NopCloser(bytes.NewReader(errBody))
return resp, effectiveRoute, nil
return resp, nil
}
// Restore the body so downstream error handling still sees the original
// payload when no retry happens below.
resp.Body = io.NopCloser(bytes.NewReader(errBody))
// Log a capped snippet of the upstream error body so the 400 class is
// visible without dumping full payloads. Bodies stay out of attempt
// records; the hub redactor scrubs configured secrets from log output.
if len(errBody) > 0 {
redactor := config.NewSecretRedactor()
redactor.Replace(g.cfg)
snippet := redactor.String(string(errBody))
snippet := string(errBody)
if g.redactor != nil {
snippet = g.redactor.String(snippet)
}
if len(snippet) > 240 {
snippet = snippet[:240]
}
g.logger.Info("upstream error returned or retried", "component", "upstream", "event", "upstream_error_body", "request_id", ids.Request, "model", route.ID, "status", resp.StatusCode, "snippet", snippet)
}
if !isStaleReasoningReference(errBody) {
return resp, effectiveRoute, nil
return resp, nil
}
stripped, changed := stripStaleReasoningInputs(effectiveRoute, bodies)
stripped, changed := stripStaleReasoningInput(route, body)
if !changed {
return resp, effectiveRoute, nil
return resp, nil
}
// The referenced reasoning items belong to an upstream chain this session
// can no longer address (e.g. an interrupted stream). Replay once without
// them instead of failing the client request outright. Attempt numbering
// continues from the first round so monitoring never shows duplicate attempt
// numbers for one request.
//
// The client's session is deliberately preserved: it carries key/proxy
// affinity and upstream session correlation. Minting a fresh session made
// the replay land on a different node with a cold prompt cache and detached
// the reply from the chain the client still holds; the stale references are
// already removed from the payload itself.
g.logger.Info("retrying upstream without stale reasoning references", "component", "upstream", "event", "reasoning_reference_retry", "request_id", ids.Request, "model", route.ID, "tier", effectiveRoute.Tier, "attempt_offset", attempts)
retryResp, retryRoute, _, retryErr := g.doUpstreamTiers(ctx, effectiveRoute, stripped, ids, attempts)
g.logger.Info("retrying upstream without stale reasoning references", "component", "upstream", "event", "reasoning_reference_retry", "request_id", ids.Request, "model", route.ID, "attempt_offset", attempts)
g.dumpOutboundBody(route, stripped, ids, attempts)
retryResp, retryErr, _ := g.doAnonymousUpstream(ctx, route, stripped, ids, attempts)
if retryErr != nil || retryResp == nil || retryResp.StatusCode/100 != 2 {
retryStatus := 0
if retryResp != nil {
retryStatus = retryResp.StatusCode
httpx.DrainAndClose(retryResp.Body)
}
g.logger.Warn("reasoning reference retry failed; returning original error", "component", "upstream", "event", "reasoning_reference_retry_failed", "request_id", ids.Request, "model", route.ID, "tier", effectiveRoute.Tier, "error", retryErr, "retry_status", retryStatus)
g.logger.Warn("reasoning reference retry failed; returning original error", "component", "upstream", "event", "reasoning_reference_retry_failed", "request_id", ids.Request, "model", route.ID, "error", retryErr, "retry_status", retryStatus)
fallback := *resp
fallback.Body = io.NopCloser(bytes.NewReader(errBody))
return &fallback, effectiveRoute, nil
return &fallback, nil
}
return retryResp, retryRoute, nil
return retryResp, nil
}
// isStaleReasoningReference reports whether an upstream 400 body describes a
// reasoning item/reference the server no longer recognizes, such as
// "Referenced reasoning item 'rs_...' was not found or has expired".
// Generic validation errors that merely mention reasoning (e.g. "unknown
// reasoning field") must NOT match, so both the target phrase and the
// gone/expired marker are required.
func isStaleReasoningReference(body []byte) bool {
text := strings.ToLower(string(body))
if !strings.Contains(text, "reasoning item") && !strings.Contains(text, "reasoning reference") {
@@ -141,134 +86,49 @@ func isStaleReasoningReference(body []byte) bool {
return false
}
// stripStaleReasoningInputs removes server-issued reasoning references from
// Responses-protocol upstream payloads: replayed "reasoning" input items and
// any previous_response_id chain link. Other tiers/protocols are passed
// through untouched. It reports whether any payload actually changed.
func stripStaleReasoningInputs(route models.Route, bodies map[config.Tier][]byte) (map[config.Tier][]byte, bool) {
func stripStaleReasoningInput(route models.Route, body []byte) ([]byte, bool) {
if len(body) == 0 || route.Protocol != wire.Responses {
return body, false
}
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
return body, false
}
changed := false
out := make(map[config.Tier][]byte, len(bodies))
for tier, body := range bodies {
if len(body) == 0 || route.ProtocolFor(tier) != wire.Responses {
out[tier] = body
continue
}
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
out[tier] = body
continue
}
tierChanged := false
if _, ok := payload["previous_response_id"]; ok {
delete(payload, "previous_response_id")
tierChanged = true
}
if raw, ok := payload["input"].([]any); ok {
kept := make([]any, 0, len(raw))
for _, item := range raw {
if m, ok := item.(map[string]any); ok && jsonutil.StringAt(m, "type") == "reasoning" {
tierChanged = true
continue
}
kept = append(kept, item)
}
if tierChanged {
payload["input"] = kept
}
}
if !tierChanged {
out[tier] = body
continue
}
encoded, err := json.Marshal(payload)
if err != nil {
out[tier] = body
continue
}
out[tier] = encoded
if _, ok := payload["previous_response_id"]; ok {
delete(payload, "previous_response_id")
changed = true
}
return out, changed
}
func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, models.Route, int, error) {
var lastResponse *http.Response
var lastErr error
effectiveRoute := route
attempts := attemptOffset
g.dumpOutboundBodies(route, bodies, ids, attemptOffset)
if override, selected := debugKeyOverrideFrom(ctx); selected {
resp, err, used := g.doSelectedKeyUpstream(ctx, route, bodies, ids, override, attemptOffset)
return resp, route, used, err
}
if route.Anonymous {
resp, err, used := g.doAnonymousUpstream(ctx, route, bodies, ids, attempts)
attempts += used
if err == nil && resp != nil && resp.StatusCode/100 == 2 {
return resp, route, attempts, nil
}
lastResponse, lastErr = resp, err
if len(route.KeyTiers) > 0 {
g.logger.Debug("anonymous request did not succeed; entering preferred key tiers", "component", "upstream", "event", "anonymous_fallback", "request_id", ids.Request, "attempts", attempts, "key_tiers", route.KeyTiers)
}
}
if ctx.Err() != nil {
// The anonymous phase already consumed the request budget. Entering the
// authenticated tiers here would only fire instant attempts against a
// dead context, cooling keys that were never really tried.
if lastResponse != nil {
return lastResponse, effectiveRoute, attempts, nil
}
if lastErr == nil {
lastErr = ctx.Err()
}
return nil, effectiveRoute, attempts, lastErr
}
keyTiers := route.KeyTiers
if !route.Anonymous && len(keyTiers) == 0 && (route.Tier == config.TierZen || route.Tier == config.TierGo) {
keyTiers = []config.Tier{route.Tier}
}
for _, tier := range keyTiers {
keyRoute := route
keyRoute.Tier = tier
keyRoute.Anonymous = false
keyRoute.Protocol = route.ProtocolFor(tier)
effectiveRoute = keyRoute
resp, err, used := g.doKeyUpstream(ctx, keyRoute, bodies, ids, attempts)
attempts += used
if err == nil && resp != nil && resp.StatusCode/100 == 2 {
if lastResponse != nil {
httpx.DrainAndClose(lastResponse.Body)
if raw, ok := payload["input"].([]any); ok {
kept := make([]any, 0, len(raw))
for _, item := range raw {
if m, ok := item.(map[string]any); ok && jsonutil.StringAt(m, "type") == "reasoning" {
changed = true
continue
}
return resp, keyRoute, attempts, nil
kept = append(kept, item)
}
if resp != nil {
if lastResponse != nil {
httpx.DrainAndClose(lastResponse.Body)
}
lastResponse = resp
}
if err != nil {
lastErr = err
if changed {
payload["input"] = kept
}
}
if lastResponse != nil {
return lastResponse, effectiveRoute, attempts, nil
if !changed {
return body, false
}
if lastErr == nil {
lastErr = errors.New("no usable upstream route")
encoded, err := json.Marshal(payload)
if err != nil {
return body, false
}
return nil, effectiveRoute, attempts, lastErr
return encoded, true
}
// doAnonymousUpstream tries every currently available proxy at most once. For
// each proxy it prefers the legacy /zen/v1 lane (LegacyZenBase) before falling
// back to the newer /inference upstream (Upstream.Anonymous). Any failure,
// including an HTTP error response, advances to the next upstream or proxy.
// Only a successful response ends the anonymous phase; exhausting the proxy
// cursor returns control to the preferred authenticated tiers.
func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) {
// each proxy it prefers the legacy /zen/v1 lane before falling back to the
// /inference upstream.
func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, rawBody []byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) {
if len(rawBody) == 0 {
return nil, errors.New("no prepared request body"), 0
}
var lastResponse *http.Response
var lastErr error
cursor := g.anonymous.CursorFor(ids.Session)
@@ -278,16 +138,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
}
proxies := 0
attempts := 0
rawBody := bodies[config.TierZen]
if len(rawBody) == 0 {
return nil, errors.New("no prepared Zen request body"), 0
}
// The anonymous free tier only serves agent-shaped streaming requests
// carrying the required tool definitions (anything else is rejected with 403
// FreeTierError). Normalize the wire body per upstream gate (legacy /zen/v1
// vs /inference); the gateway collapses the stream back when the downstream
// client asked for a plain JSON reply. Key tiers keep their original bodies.
protocol := route.ProtocolFor(config.TierZen)
protocol := route.Protocol
upstreams := g.anonymousUpstreams()
preparedBodies := make([][]byte, len(upstreams))
toolAliases := make([]string, len(upstreams))
@@ -296,9 +147,6 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
}
for proxies < limit {
if ctx.Err() != nil {
// The request-level budget is already gone. Stop scanning instead
// of firing attempts that cannot succeed and then recording them
// as failures against proxies that were never really tried.
if lastErr == nil {
lastErr = ctx.Err()
}
@@ -321,8 +169,10 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
attempts++
if meta := telemetry.MetaFromContext(ctx); meta != nil {
meta.Attempts = attemptOffset + attempts
meta.Tier = string(config.TierZen)
meta.ToolAlias = toolAliases[index]
if node.proxy != nil {
meta.Proxy = config.RedactURL(node.proxy.name)
}
}
if lastResponse != nil {
httpx.DrainAndClose(lastResponse.Body)
@@ -335,14 +185,10 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
if node.proxy.pool {
req.Close = true
}
setRequestCredential(ctx, config.TierZen, "anonymous", "anonymous", true, node.proxy)
started := time.Now()
resp, err := doInferenceAttempt(node.proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout)
duration := time.Since(started)
if ctx.Err() != nil {
// The parent budget expired while this attempt was in flight. Its
// outcome says nothing about this proxy, so record nothing and stop
// scanning.
lastResponse, lastErr = resp, err
if lastErr == nil && lastResponse == nil {
lastErr = ctx.Err()
@@ -350,21 +196,21 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
break
}
nodeResp, nodeErr = resp, err
g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+attempts, "anonymous", "anonymous", true, node.proxy, resp, err, duration)
g.recordUpstreamAttempt(ctx, route, resp, err, duration)
if err == nil && resp.StatusCode/100 == 2 {
g.observeAnonymousResult(ctx, node, resp, nil)
g.logger.Debug("anonymous upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds())
g.logger.Debug("anonymous upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "upstream", config.RedactURL(baseURL), "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds())
return resp, nil, attempts
}
lastResponse = resp
lastErr = asProxyUnavailable(node.proxy, err)
if err != nil {
g.logger.Debug("anonymous transport attempt failed", "component", "upstream", "event", "anonymous_attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "duration_ms", duration.Milliseconds(), "error", err)
g.logger.Debug("anonymous transport attempt failed", "component", "upstream", "event", "anonymous_attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "upstream", config.RedactURL(baseURL), "proxy", config.RedactURL(node.proxy.name), "duration_ms", duration.Milliseconds(), "error", err)
if isProxyFailure(err) {
break
}
} else {
g.logger.Debug("anonymous upstream returned an error response; trying the next upstream or proxy", "component", "upstream", "event", "anonymous_attempt_response_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds())
g.logger.Debug("anonymous upstream returned an error response; trying the next upstream or proxy", "component", "upstream", "event", "anonymous_attempt_response_failed", "request_id", ids.Request, "attempt", attempts, "upstream", config.RedactURL(baseURL), "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds())
}
if index+1 < len(upstreams) && !node.proxy.healthy.Load() {
break
@@ -388,19 +234,21 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
}
// anonymousUpstreams returns the ordered base URLs for the keyless free-tier
// lane: the legacy /zen/v1 origin (models.LegacyZenBase) is tried first, and
// the configured /inference origin (Upstream.Anonymous) is kept as a fallback.
// lane: the legacy /zen/v1 origin (Upstream.Zen, defaulting to LegacyZenBase)
// is tried first, and the /inference origin (Upstream.Anonymous) is kept as a
// fallback.
func (g *Gateway) anonymousUpstreams() []string {
legacy := strings.TrimRight(models.LegacyZenBase, "/")
legacy := strings.TrimRight(g.cfg.Upstream.Zen, "/")
if legacy == "" {
legacy = strings.TrimRight(models.LegacyZenBase, "/")
}
primary := strings.TrimRight(g.cfg.Upstream.Anonymous, "/")
if primary == "" || strings.EqualFold(legacy, primary) {
return []string{models.LegacyZenBase}
return []string{legacy}
}
return []string{models.LegacyZenBase, g.cfg.Upstream.Anonymous}
return []string{legacy, g.cfg.Upstream.Anonymous}
}
// isLegacyZenUpstream reports whether baseURL targets the legacy /zen/v1
// gate rather than the newer /inference gate.
func isLegacyZenUpstream(baseURL string) bool {
trimmed := strings.ToLower(strings.TrimRight(strings.TrimSpace(baseURL), "/"))
if strings.EqualFold(trimmed, strings.TrimRight(models.LegacyZenBase, "/")) {
@@ -409,41 +257,12 @@ func isLegacyZenUpstream(baseURL string) bool {
return strings.HasSuffix(trimmed, "/zen")
}
// legacyAnonymousReadTool is the single tool name required by the legacy
// /zen/v1 free-tier gate. Unlike /inference, the /zen/v1 gate does not require
// a shell/edit/glob/grep toolset and does not validate tool descriptions or
// parameter schemas: a single tool named "read" is sufficient.
const legacyAnonymousReadTool = "read"
// legacyDeprecatedReadDescription is attached when the gateway must inject a
// placeholder "read" tool on the legacy /zen/v1 lane because the client
// request declared no read-related tool of its own. It explicitly tells the
// model that the tool is deprecated and must never be invoked.
const legacyDeprecatedReadDescription = "DEPRECATED: This tool is deprecated and disabled. Do NOT call or reference this tool under any circumstances; ignore it completely."
// anonymousCoreTools are the tool names the /inference free-tier gate expects
// on an agent-shaped request. Requests without a shell tool and a read tool are
// rejected with 403 FreeTierError.
//
// "shell" is the name OpenCode 2.x ships; the pre-2.x "bash" spelling is
// deliberately not injected on /inference because that gate validates the
// definition of every tool it recognises, and a "bash" definition the gateway
// synthesises does not match the one upstream expects. Since 2026-10-14 name
// presence is not enough on /inference either: the upstream compares each
// recognised tool's description and parameter schema against the official CLI's
// definitions byte-for-byte (minimal stand-ins 403), which is why the genuine
// definitions below are embedded. Tool order is irrelevant and extra client
// tools are allowed.
var anonymousCoreTools = []string{"shell", "edit", "glob", "grep", "read"}
// opencodeToolsJSON holds the genuine OpenCode tool definitions (description
// and JSON schema) captured from the official client. The /inference free-tier
// gate checks the definition of every tool whose name it recognises, so a
// synthesised stub — even one carrying the right name — is rejected with 403
// FreeTierError. The gateway therefore ships the real definitions for the
// /inference lane and uses them both for the tools it injects and for any
// same-named tool the downstream client declared.
//
//go:embed opencode_tools.json
var opencodeToolsJSON []byte
@@ -457,7 +276,6 @@ var (
opencodeTools map[string]opencodeToolDefinition
)
// knownOpencodeTool returns the genuine definition for an OpenCode tool name.
func knownOpencodeTool(name string) (opencodeToolDefinition, bool) {
opencodeToolsOnce.Do(func() {
definitions := map[string]opencodeToolDefinition{}
@@ -470,20 +288,6 @@ func knownOpencodeTool(name string) (opencodeToolDefinition, bool) {
return definition, ok
}
// prepareAnonymousBody returns a copy of body normalized for the anonymous
// free tier alongside any original client tool name that was aliased to "read"
// for the legacy /zen/v1 gate.
//
// On the legacy /zen/v1 gate (legacy == true), pre-injection of other tools is
// dropped: if the client declared a read-related tool (case-insensitive, e.g.
// "reAd", "Read_file", "readFile"), it is renamed in-place to "read" while
// keeping its original description and parameters, and its original name is
// returned so the gateway can restore it in the downstream response; if no
// read-related tool is present, a single deprecated "read" stub is injected.
//
// On the /inference gate (legacy == false), anonymousCoreTools with genuine
// CLI 2.x definitions are ensured. System One payloads are decision requests,
// not agent traffic, so they are forwarded verbatim.
func prepareAnonymousBody(body []byte, protocol wire.Protocol, legacy bool) ([]byte, string) {
if protocol == wire.SystemOne {
return body, ""
@@ -515,16 +319,11 @@ func prepareAnonymousBody(body []byte, protocol wire.Protocol, legacy bool) ([]b
}
encoded, err := json.Marshal(payload)
if err != nil {
// The alias is dropped with the failed re-encode: the body never left
// the gateway, so there is nothing downstream to restore.
return body, ""
}
return encoded, alias
}
// ensureAnonymousChatUsage keeps token usage available when a non-streaming
// request is forced onto the Chat SSE path. OpenAI-compatible Chat streams
// require stream_options.include_usage for the final usage event.
func ensureAnonymousChatUsage(payload map[string]any, protocol wire.Protocol) bool {
if protocol != wire.Chat {
return false
@@ -542,18 +341,6 @@ func ensureAnonymousChatUsage(payload map[string]any, protocol wire.Protocol) bo
return true
}
// ensureLegacyAnonymousReadTool satisfies the legacy /zen/v1 free-tier gate
// using only the single "read" tool requirement:
// 1. If the client already has an exact "read" tool, nothing is injected or
// renamed.
// 2. If the client has a read-related tool (case-insensitive match such as
// "reAd", "read_file", "ReadFile", etc.), that tool is renamed to "read"
// (preserving its client description and schema), any matching tool_choice
// or historical tool call in the request is rewritten to "read", and the
// client's original tool name is returned so responses can be restored.
// 3. If the client has no read-related tool at all, a single "read" stub tool
// is appended with a deprecated/ignore description so the model never
// invokes it.
func ensureLegacyAnonymousReadTool(payload map[string]any, protocol wire.Protocol) (string, bool) {
raw, exists := payload["tools"]
if !exists {
@@ -595,9 +382,6 @@ func ensureLegacyAnonymousReadTool(payload map[string]any, protocol wire.Protoco
return "", true
}
// isLegacyReadToolCandidate reports whether a client tool name represents a
// read-related tool (case-insensitive), such as "reAd", "read_file",
// "ReadFile", "file_read", or "view_file".
func isLegacyReadToolCandidate(name string) bool {
lower := strings.ToLower(strings.TrimSpace(name))
if lower == "" {
@@ -614,9 +398,6 @@ func isLegacyReadToolCandidate(name string) bool {
return strings.HasPrefix(lower, "read_") || strings.HasPrefix(lower, "read-") || strings.HasSuffix(lower, "_read") || strings.HasSuffix(lower, "-read")
}
// setAnonymousToolName updates the function name of a tool definition in-place
// while keeping all other client fields (description, parameters/input_schema,
// strict, etc.) intact.
func setAnonymousToolName(protocol wire.Protocol, item any, name string) {
entry, ok := item.(map[string]any)
if !ok {
@@ -631,9 +412,6 @@ func setAnonymousToolName(protocol wire.Protocol, item any, name string) {
entry["name"] = name
}
// rewriteLegacyRequestToolReferences renames any named tool_choice and
// assistant tool-call history entries from fromName to toName so the outbound
// request stays self-consistent after a client read tool is aliased to "read".
func rewriteLegacyRequestToolReferences(payload map[string]any, protocol wire.Protocol, fromName, toName string) {
if fromName == "" || fromName == toName {
return
@@ -680,10 +458,6 @@ func rewriteLegacyRequestToolReferences(payload map[string]any, protocol wire.Pr
}
}
// legacyDeprecatedReadTool builds the single placeholder "read" tool injected
// on the legacy /zen/v1 lane when the client request has no read-related tool
// of its own. Its description marks the tool as deprecated and instructs the
// model to ignore it completely.
func legacyDeprecatedReadTool(protocol wire.Protocol) map[string]any {
parameters := map[string]any{"type": "object", "properties": map[string]any{}}
switch protocol {
@@ -712,10 +486,6 @@ func legacyDeprecatedReadTool(protocol wire.Protocol) map[string]any {
}
}
// ensureAnonymousTools makes the tool list read as an OpenCode 2.x agent
// session on the /inference gate: every recognised OpenCode tool carries its
// genuine CLI 2.x definition and missing core tools are appended with genuine
// schemas; unrecognised client tools are left untouched.
func ensureAnonymousTools(payload map[string]any, protocol wire.Protocol) bool {
raw, exists := payload["tools"]
if !exists {
@@ -767,8 +537,6 @@ func anonymousToolName(protocol wire.Protocol, item any) string {
return jsonutil.StringAt(entry, "name")
}
// anonymousToolset returns the wire-shaped genuine CLI 2.x definitions for the
// given tool names on the /inference gate.
func anonymousToolset(protocol wire.Protocol, names []string) []any {
if names == nil {
names = anonymousCoreTools
@@ -782,10 +550,6 @@ func anonymousToolset(protocol wire.Protocol, names []string) []any {
return tools
}
// anonymousTool renders one core tool in the shape the given protocol expects,
// using the genuine OpenCode CLI 2.x definition whenever one is known.
// SystemOne payloads never reach this path (prepareAnonymousBody forwards them
// verbatim), so it falls back to the Responses/default shape.
func anonymousTool(protocol wire.Protocol, name string) map[string]any {
description := "Agent tool " + name
parameters := map[string]any{"type": "object", "properties": map[string]any{}}
@@ -821,248 +585,29 @@ func anonymousTool(protocol wire.Protocol, name string) map[string]any {
}
}
// requestBodyDumpLimit caps how much of an outbound body is written to the log.
const requestBodyDumpLimit = 64 << 10
// dumpOutboundBodies records the exact bytes about to be sent upstream when
// logging.dump_request_bodies is enabled. It exists so retry and translation
// problems (stale rs_* references, re-encoded history, tier re-encoding) can be
// diagnosed without patching the binary. Credentials travel in headers and never
// in the body. The logger redacts configured secrets, but conversation content
// can still be sensitive. Reference IDs are retained for replay diagnostics.
func (g *Gateway) dumpOutboundBodies(route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) {
if !g.cfg.Logging.DumpRequestBodies || len(bodies) == 0 {
func (g *Gateway) dumpOutboundBody(route models.Route, body []byte, ids identity.RequestIDs, attemptOffset int) {
if !g.cfg.Logging.DumpRequestBodies || len(body) == 0 {
return
}
phase := "initial"
if attemptOffset > 0 {
phase = "retry"
}
tiers := make([]string, 0, len(bodies))
for tier := range bodies {
tiers = append(tiers, string(tier))
}
sort.Strings(tiers)
for _, name := range tiers {
tier := config.Tier(name)
body := bodies[tier]
if len(body) == 0 {
continue
}
sum := sha256.Sum256(body)
truncated := len(body) > requestBodyDumpLimit
payload := body
if truncated {
payload = body[:requestBodyDumpLimit]
}
g.logger.Debug("outbound upstream request body", "component", "upstream", "event", "upstream_request_body",
"request_id", ids.Request, "model", route.ID, "tier", tier, "protocol", route.ProtocolFor(tier),
"phase", phase, "bytes", len(body), "sha256", hex.EncodeToString(sum[:8]),
"truncated", truncated, "body", string(payload))
}
}
// shapeKeyBody normalizes key-tier free-model wire bodies to agent shape
// (stream + required tools), mirroring the anonymous lane. Upstream now
// rejects non-agent-shaped free-tier requests on every lane with 403
// FreeTierError; paid models keep their original bodies. It reports the
// shaped body, any legacy "read" tool alias that must be restored in the
// response, and whether the body changed so the gateway can collapse the SSE
// stream a non-streaming client receives back.
func (g *Gateway) shapeKeyBody(body []byte, route models.Route, tier config.Tier) ([]byte, string, bool) {
if !g.catalog.IsFreeModel(route.ID) {
return body, "", false
}
baseURL := g.cfg.Upstream.Zen
if tier == config.TierGo {
baseURL = g.cfg.Upstream.Go
}
shaped, alias := prepareAnonymousBody(body, route.ProtocolFor(tier), isLegacyZenUpstream(baseURL))
return shaped, alias, !bytes.Equal(shaped, body)
}
// key. It performs no failover at all — no anonymous lane, no other key and no
// other tier — so the outcome describes that one key. It also leaves pool state
// untouched on purpose: a diagnostic request must never cool a production key or
// evict a proxy, which is exactly what made a bad Playground request degrade
// live traffic before.
func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, override DebugKeyOverride, attemptOffset int) (*http.Response, error, int) {
nodes := g.zenNodes
baseURL := g.cfg.Upstream.Zen
if override.Tier == config.TierGo {
nodes = g.goNodes
baseURL = g.cfg.Upstream.Go
}
node := nodes.NodeByID(override.KeyID)
if node == nil {
return nil, fmt.Errorf("selected %s key is no longer configured", override.Tier), 0
}
body := bodies[override.Tier]
if len(body) == 0 {
return nil, fmt.Errorf("no prepared %s request body", override.Tier), 0
}
shaped, alias, changed := g.shapeKeyBody(body, route, override.Tier)
if changed {
body = shaped
}
if meta := telemetry.MetaFromContext(ctx); meta != nil {
meta.Shaped = changed
meta.ToolAlias = alias
}
proxy := nodes.Proxy(node)
if proxy == nil {
return nil, errors.New("selected upstream key has no proxy binding"), 0
}
if meta := telemetry.MetaFromContext(ctx); meta != nil {
meta.Attempts = attemptOffset + 1
meta.Tier = string(override.Tier)
}
keyID := config.KeyDisplayID(node.key)
setRequestCredential(ctx, override.Tier, keyID, "key", false, proxy)
req, err := newUpstreamRequest(ctx, baseURL, route.ProtocolFor(override.Tier), body, ids, node.key)
if err != nil {
return nil, err, 0
}
if proxy.pool {
req.Close = true
}
started := time.Now()
resp, err := doInferenceAttempt(proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout)
duration := time.Since(started)
g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+1, keyID, "key", false, proxy, resp, err, duration)
if err != nil {
return nil, asProxyUnavailable(proxy, err), 1
}
return resp, nil, 1
}
func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) {
var lastResponse *http.Response
var lastErr error
nodes := g.zenNodes
baseURL := g.cfg.Upstream.Zen
if route.Tier == config.TierGo {
nodes = g.goNodes
baseURL = g.cfg.Upstream.Go
}
cursor := nodes.CursorFor(ids.Session)
if nodes.Len() == 0 {
return nil, fmt.Errorf("no %s nodes configured", route.Tier), 0
}
attempts := 0
body := bodies[route.Tier]
if len(body) == 0 {
return nil, fmt.Errorf("no prepared %s request body", route.Tier), 0
}
shaped, alias, changed := g.shapeKeyBody(body, route, route.Tier)
if changed {
body = shaped
}
if meta := telemetry.MetaFromContext(ctx); meta != nil {
meta.Shaped = changed
meta.ToolAlias = alias
}
for attempts < g.cfg.Retry.MaxAttempts {
if ctx.Err() != nil {
// Same guard as the anonymous loop: an exhausted request budget
// must not be spent rotating keys that were never really tried.
if lastErr == nil {
lastErr = ctx.Err()
}
break
}
node := cursor.Next()
if node == nil {
break
}
attempts++
// Keep the request-level trace synchronized with the attempt that is
// about to be sent. Only the redacted key suffix is retained.
if meta := telemetry.MetaFromContext(ctx); meta != nil {
meta.Attempts = attemptOffset + attempts
meta.Tier = string(route.Tier)
}
if lastResponse != nil {
httpx.DrainAndClose(lastResponse.Body)
lastResponse = nil
}
req, err := newUpstreamRequest(ctx, baseURL, route.Protocol, body, ids, node.key)
if err != nil {
return nil, err, attempts
}
proxy := nodes.Proxy(node)
if proxy == nil {
lastErr = errors.New("upstream key has no proxy binding")
break
}
if proxy.pool {
req.Close = true
}
keyID := config.KeyDisplayID(node.key)
setRequestCredential(ctx, route.Tier, keyID, "key", false, proxy)
attemptStarted := time.Now()
resp, err := doInferenceAttempt(proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout)
attemptDuration := time.Since(attemptStarted)
if ctx.Err() != nil {
// The request budget expired while this attempt was in flight. A
// cancelled context says nothing about the key or the proxy: without
// this guard the instant DeadlineExceeded would cool a healthy key
// and evict a healthy proxy from the pool.
lastResponse, lastErr = resp, err
if lastErr == nil && lastResponse == nil {
lastErr = ctx.Err()
}
break
}
g.observeKeyResult(ctx, nodes, node, proxy, resp, err)
g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+attempts, keyID, "key", false, proxy, resp, err, attemptDuration)
if err == nil && resp.StatusCode/100 == 2 {
g.logger.Debug("upstream accepted request", "component", "upstream", "event", "attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "proxy", config.RedactURL(proxy.name), "status", resp.StatusCode, "duration_ms", attemptDuration.Milliseconds())
return resp, nil, attempts
}
// Request-shape errors are deterministic and must leave this tier without
// rotating through unrelated keys. The outer route may still try the next
// tier in prefer order. Authentication, throttling, server, and transport
// failures remain retryable inside this tier.
if isNonRetryableClientResponse(resp, err) {
g.logger.Debug("upstream rejected a non-retryable request", "component", "upstream", "event", "attempt_rejected", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "status", resp.StatusCode, "proxy", config.RedactURL(proxy.name), "duration_ms", attemptDuration.Milliseconds())
return resp, nil, attempts
}
lastResponse = resp
lastErr = asProxyUnavailable(proxy, err)
if err != nil {
g.logger.Debug("upstream transport attempt failed", "component", "upstream", "event", "attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "proxy", config.RedactURL(proxy.name), "duration_ms", attemptDuration.Milliseconds(), "error", err)
} else {
g.logger.Debug("upstream returned a retryable response", "component", "upstream", "event", "attempt_retryable_response", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "status", resp.StatusCode, "proxy", config.RedactURL(proxy.name), "duration_ms", attemptDuration.Milliseconds())
}
}
if lastResponse != nil {
return lastResponse, nil, attempts
}
return nil, lastErr, attempts
}
// Diagnostics use the same routing and transports as production, but must not
// update cooldowns, health, or bindings, including after successful attempts.
func (g *Gateway) observeKeyResult(ctx context.Context, nodes *nodePool, node *upstreamNode, proxy *proxyTransport, resp *http.Response, err error) {
if isDiagnosticRequest(ctx) {
return
}
status := upstreamStatus(resp)
proxyFailed := g.syncProxyResult(ctx, proxy, status, err)
if err == nil && status/100 == 2 || isNonRetryableClientResponse(resp, err) {
nodes.MarkSuccess(node)
return
}
if !proxyFailed || nodes.Proxy(node) == proxy {
nodes.MarkFailure(node, resp, err)
sum := sha256.Sum256(body)
truncated := len(body) > requestBodyDumpLimit
payload := body
if truncated {
payload = body[:requestBodyDumpLimit]
}
g.logger.Debug("outbound upstream request body", "component", "upstream", "event", "upstream_request_body",
"request_id", ids.Request, "model", route.ID, "protocol", route.Protocol,
"phase", phase, "bytes", len(body), "sha256", hex.EncodeToString(sum[:8]),
"truncated", truncated, "body", string(payload))
}
func (g *Gateway) observeAnonymousResult(ctx context.Context, node *anonymousNode, resp *http.Response, err error) {
if isDiagnosticRequest(ctx) {
return
}
status := upstreamStatus(resp)
g.syncProxyResult(ctx, node.proxy, status, err)
if err == nil && status/100 == 2 {
@@ -1079,30 +624,7 @@ func upstreamStatus(resp *http.Response) int {
return resp.StatusCode
}
func setRequestCredential(ctx context.Context, tier config.Tier, keyID, channel string, anonymous bool, proxy *proxyTransport) {
meta := telemetry.MetaFromContext(ctx)
if meta == nil {
return
}
meta.Tier = string(tier)
meta.KeyID = keyID
meta.Channel = channel
meta.Anonymous = anonymous
meta.Proxy = ""
if proxy != nil {
meta.Proxy = config.RedactURL(proxy.name)
}
}
func requestCredential(ctx context.Context) (string, string, bool) {
meta := telemetry.MetaFromContext(ctx)
if meta == nil {
return "", "", false
}
return meta.KeyID, meta.Channel, meta.Anonymous
}
func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route models.Route, ids identity.RequestIDs, attempt int, keyID, channel string, anonymous bool, proxy *proxyTransport, resp *http.Response, err error, duration time.Duration) {
func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route models.Route, resp *http.Response, err error, duration time.Duration) {
status := upstreamStatus(resp)
success := err == nil && status >= 200 && status < 300
outcome := "retryable_failure"
@@ -1116,14 +638,7 @@ func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route models.Route,
if meta := telemetry.MetaFromContext(ctx); meta != nil {
meta.AttemptOutcome = outcome
meta.Protocol = route.Protocol
// Append a per-attempt leg (key:status:ms, anonymized for the
// public lane) so the request log shows the whole attempt chain
// at a glance. Only the redacted key suffix is retained.
label := keyID
if anonymous {
label = "anon"
}
leg := label + ":"
leg := "anon:"
if err != nil {
leg += classifyAttemptError(err)
} else {
@@ -1132,18 +647,9 @@ func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route models.Route,
leg += ":" + strconv.FormatInt(max(duration.Milliseconds(), 0), 10) + "ms"
meta.Legs = append(meta.Legs, leg)
}
if g.monitor == nil {
return
if g.monitor != nil {
g.monitor.RecordAttempt(success)
}
proxyName := "unavailable"
if proxy != nil {
proxyName = config.RedactURL(proxy.name)
}
g.monitor.RecordAttempt(telemetry.UpstreamAttempt{
Time: time.Now().UTC(), RequestID: ids.Request, Model: route.ID, Tier: string(route.Tier), Attempt: attempt,
KeyID: keyID, Channel: channel, Anonymous: anonymous, Proxy: proxyName, Status: status,
DurationMS: max(duration.Milliseconds(), 0), Success: success, Outcome: outcome,
})
}
func newUpstreamRequest(ctx context.Context, baseURL string, protocol wire.Protocol, body []byte, ids identity.RequestIDs, key string) (*http.Request, error) {
@@ -1159,18 +665,10 @@ func newUpstreamRequest(ctx context.Context, baseURL string, protocol wire.Proto
req.Header.Set("x-session-affinity", ids.Session)
req.Header.Set("X-Session-Id", ids.Session)
if isLegacyZenUpstream(baseURL) {
// The legacy /zen/v1 origin uses the pre-2.x OpenCode 1.18.x request
// shape from v1.3.7: the legacy User-Agent, x-opencode-request, and a
// canonical prj_* project id.
req.Header.Set("User-Agent", httpx.LegacyUserAgent())
req.Header.Set("x-opencode-request", ids.Request)
req.Header.Set("x-opencode-project", legacyProjectID(ids.Project))
} else {
// The newer /inference gate fingerprints the 2.x CLI header set: it
// wants the "opencode/<channel>/<version>/cli" User-Agent, both
// session headers set to the same descending-encoded id, and a bare
// 40-character hex x-opencode-project, and it rejects x-opencode-request
// and canonical prj_* project ids with 403 FreeTierError.
req.Header.Set("User-Agent", httpx.UserAgent())
req.Header.Set("x-opencode-session-id", ids.Session)
req.Header.Set("x-opencode-project", clientProjectID(ids.Project))
@@ -1183,17 +681,11 @@ func newUpstreamRequest(ctx context.Context, baseURL string, protocol wire.Proto
req.Header.Set("anthropic-version", "2023-06-01")
req.Header.Set("anthropic-beta", "interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14")
} else {
// The anonymous credential is the literal token "public". The 2026-10-14
// gate rejects keyless requests (an absent header used to pass) and is
// case-sensitive: "Bearer PUBLIC" 401s.
req.Header.Set("Authorization", "Bearer "+key)
}
return req, nil
}
// legacyProjectID renders the project header in the v1.3.7 canonical
// "prj_<24hex>" shape expected by the pre-2.x /zen/v1 origin, preserving an
// already-prefixed prj_* value verbatim.
func legacyProjectID(project string) string {
if strings.HasPrefix(project, "prj_") {
return project
@@ -1201,11 +693,6 @@ func legacyProjectID(project string) string {
return identity.StableID("prj", project)
}
// clientProjectID renders the project header the way the 2.x CLI does for the
// /inference gate: a bare 40-character lowercase hex id rather than the
// gateway's "prj_" prefixed stable id. The value itself is not checked
// upstream, only its shape, but hashing keeps one conversation pinned to one
// project.
func clientProjectID(project string) string {
sum := sha256.Sum256([]byte("opencode-project\x00" + project))
return hex.EncodeToString(sum[:20])
+44 -53
View File
@@ -2,9 +2,11 @@ package models
import (
"encoding/json"
"maps"
"os"
"path/filepath"
"sync"
"sync/atomic"
"time"
)
@@ -32,70 +34,64 @@ type Availability struct {
}
type AvailabilityStore struct {
mu sync.RWMutex
mu sync.Mutex
path string
items map[string]Availability
items atomic.Pointer[map[string]Availability]
}
func NewAvailabilityStore(path string) (*AvailabilityStore, error) {
s := &AvailabilityStore{path: path, items: map[string]Availability{}}
items := map[string]Availability{}
if path != "" {
b, err := os.ReadFile(path)
if err == nil {
if err = json.Unmarshal(b, &s.items); err != nil {
if err = json.Unmarshal(b, &items); err != nil {
return nil, err
}
} else if !os.IsNotExist(err) {
return nil, err
}
}
if s.items == nil {
s.items = map[string]Availability{}
if items == nil {
items = map[string]Availability{}
}
// Legacy probes used invalid session IDs and treated temporary errors as
// permanent failures. These records cannot establish model unavailability.
// The migration stays in memory and is re-derived on every load; the next
// explicit write persists it.
for model, item := range s.items {
for model, item := range items {
if item.ProbeVersion == 0 && item.Disabled {
item.Disabled = false
item.NextCheck = time.Time{}
item.Reason = "legacy_probe_recheck"
s.items[model] = item
items[model] = item
}
// Manual restores predate the manual lock flag. Preserve the
// operator's intent: a model left as manually_enabled stays under
// manual control instead of falling back under automatic probing.
if !item.Disabled && !item.Manual && item.Reason == "manually_enabled" {
item.Manual = true
s.items[model] = item
items[model] = item
}
}
s := &AvailabilityStore{path: path}
s.items.Store(&items)
return s, nil
}
func (s *AvailabilityStore) Get(model string) Availability {
s.mu.RLock()
defer s.mu.RUnlock()
item := s.items[model]
items := *s.items.Load()
item := items[model]
item.Model = model
return item
}
func (s *AvailabilityStore) Disabled(model string) bool { return s.Get(model).Disabled }
func (s *AvailabilityStore) Disabled(model string) bool {
items := *s.items.Load()
return items[model].Disabled
}
// SetManual switches a model between manual and automatic control. Manual
// mode keeps the model enabled and excludes it from automatic probing;
// switching back to automatic schedules a probe on the next check.
func (s *AvailabilityStore) SetManual(model string, manual bool, now time.Time) error {
s.mu.Lock()
defer s.mu.Unlock()
item, existed := s.items[model]
// Retried requests must not erase disable evidence or reset the schedule.
cur := *s.items.Load()
item := cur[model]
if item.Manual == manual {
return nil
}
previous := item
next := maps.Clone(cur)
item.Model = model
item.Manual = manual
item.Generation++
@@ -108,20 +104,14 @@ func (s *AvailabilityStore) SetManual(model string, manual bool, now time.Time)
item.Reason = "auto_probe"
item.NextCheck = time.Time{}
}
s.items[model] = item
if err := s.saveLocked(); err != nil {
if existed {
s.items[model] = previous
} else {
delete(s.items, model)
}
next[model] = item
if err := s.saveLocked(next); err != nil {
return err
}
s.items.Store(&next)
return nil
}
// A manual restore takes the model under manual control and invalidates
// results from probes that were already running.
func (s *AvailabilityStore) Restore(model string, now time.Time) error {
return s.SetManual(model, true, now)
}
@@ -129,13 +119,9 @@ func (s *AvailabilityStore) Restore(model string, now time.Time) error {
func (s *AvailabilityStore) Record(model string, generation uint64, success bool, reason, channel string, now time.Time, effort EffortProbe) error {
s.mu.Lock()
defer s.mu.Unlock()
item := s.items[model]
if item.Generation != generation {
return nil
}
// Manual control freezes the record: automatic probes must never
// overwrite a manually_enabled state (neither Disabled nor Reason).
if item.Manual {
cur := *s.items.Load()
item := cur[model]
if item.Generation != generation || item.Manual {
return nil
}
item.Model = model
@@ -144,18 +130,18 @@ func (s *AvailabilityStore) Record(model string, generation uint64, success bool
} else if reason == "model_unavailable" {
item.Disabled = true
} else if item.Disabled {
// An inconclusive recheck of a still-disabled model carries no new
// evidence. Keep the previous disable reason and backoff instead of
// resetting to an hourly retry with the transient error.
item.CheckedAt = now
item.ProbeVersion = 1
// A scheduled recheck has already reached NextCheck. Advance it to
// avoid probing on every scheduler tick after an inconclusive result.
if !item.NextCheck.After(now) {
item.NextCheck = now.Add(FailedModelCheckInterval)
}
s.items[model] = item
return s.saveLocked()
next := maps.Clone(cur)
next[model] = item
if err := s.saveLocked(next); err != nil {
return err
}
s.items.Store(&next)
return nil
}
item.CheckedAt, item.Reason, item.Channel = now, reason, channel
item.ProbeVersion = 1
@@ -169,15 +155,20 @@ func (s *AvailabilityStore) Record(model string, generation uint64, success bool
interval = FailedModelCheckInterval
}
item.NextCheck = now.Add(interval)
s.items[model] = item
return s.saveLocked()
next := maps.Clone(cur)
next[model] = item
if err := s.saveLocked(next); err != nil {
return err
}
s.items.Store(&next)
return nil
}
func (s *AvailabilityStore) saveLocked() error {
func (s *AvailabilityStore) saveLocked(items map[string]Availability) error {
if s.path == "" {
return nil
}
b, err := json.MarshalIndent(s.items, "", " ")
b, err := json.MarshalIndent(items, "", " ")
if err != nil {
return err
}
+38 -62
View File
@@ -13,67 +13,61 @@ import (
"sync"
"time"
"opencode2api/internal/config"
wire "opencode2api/internal/protocol"
)
const modelCatalogCacheSchemaVersion = 3
const modelCatalogCacheSchemaVersion = 4
var modelCatalogCacheWriteMu sync.Mutex
type modelCatalogCache struct {
SchemaVersion int `json:"schema_version"`
UpdatedAt time.Time `json:"updated_at"`
Zen []string `json:"zen"`
Go []string `json:"go"`
NativeProtocols map[config.Tier]map[string]wire.Protocol `json:"native_protocols"`
Unsupported map[config.Tier]map[string]bool `json:"unsupported"`
Metadata map[config.Tier]map[string]Metadata `json:"metadata,omitempty"`
SchemaVersion int `json:"schema_version"`
UpdatedAt time.Time `json:"updated_at"`
Zen []string `json:"zen"`
NativeProtocols map[string]wire.Protocol `json:"native_protocols"`
Unsupported map[string]bool `json:"unsupported"`
Metadata map[string]Metadata `json:"metadata,omitempty"`
}
// LoadCache installs a validated disk snapshot into a catalog. It deliberately
// changes only discovered state; configured protocol overrides and routing
// preferences stay owned by the current Config.
func (c *Catalog) LoadCache(path string) error {
cache, err := loadModelCatalogCache(path)
if err != nil {
return err
}
c.mu.Lock()
c.zen = toSet(cache.Zen)
c.goModels = toSet(cache.Go)
c.nativeProtocols = cloneTierProtocols(cache.NativeProtocols)
c.unsupported = cloneTierBools(cache.Unsupported)
c.modelMeta = cloneModelMeta(cache.Metadata)
c.updatedAt = cache.UpdatedAt.UTC()
c.cacheSource = "disk"
c.stale = true
if c.cachePath == "" {
c.cachePath = path
}
c.state.Store(&catalogState{
zen: toSet(cache.Zen),
nativeProtocols: cloneProtocols(cache.NativeProtocols),
unsupported: cloneBools(cache.Unsupported),
modelMeta: cloneMetadataMap(cache.Metadata),
sortedIDs: cache.Zen,
updatedAt: cache.UpdatedAt.UTC(),
cacheSource: "disk",
stale: true,
})
c.mu.Unlock()
return nil
}
// SaveCache snapshots only public model capability data. Credentials and
// proxy configuration are not part of modelCatalog and can never enter this
// file.
func (c *Catalog) SaveCache() error {
c.mu.RLock()
path := c.cachePath
cache := modelCatalogCache{
SchemaVersion: modelCatalogCacheSchemaVersion,
UpdatedAt: c.updatedAt.UTC(),
Zen: sortedSetKeys(c.zen),
Go: sortedSetKeys(c.goModels),
NativeProtocols: cloneTierProtocols(c.nativeProtocols),
Unsupported: cloneTierBools(c.unsupported),
Metadata: cloneModelMeta(c.modelMeta),
}
c.mu.RUnlock()
if path == "" {
return nil
}
s := c.state.Load()
cache := modelCatalogCache{
SchemaVersion: modelCatalogCacheSchemaVersion,
UpdatedAt: s.updatedAt.UTC(),
Zen: append([]string(nil), s.sortedIDs...),
NativeProtocols: cloneProtocols(s.nativeProtocols),
Unsupported: cloneBools(s.unsupported),
Metadata: cloneMetadataMap(s.modelMeta),
}
return saveModelCatalogCache(path, cache)
}
@@ -112,15 +106,21 @@ func loadModelCatalogCache(path string) (modelCatalogCache, error) {
return modelCatalogCache{}, errors.New("model catalog cache is missing updated_at")
}
cache.Zen = normalizeModelIDs(cache.Zen)
cache.Go = normalizeModelIDs(cache.Go)
if len(cache.Zen) == 0 && len(cache.Go) == 0 {
if len(cache.Zen) == 0 {
return modelCatalogCache{}, errors.New("model catalog cache is empty")
}
if err := validateCatalogCapabilities(cache.NativeProtocols, cache.Unsupported); err != nil {
return modelCatalogCache{}, err
for model, protocol := range cache.NativeProtocols {
if model == "" || !wire.Valid(protocol) {
return modelCatalogCache{}, fmt.Errorf("model catalog cache contains invalid protocol for %q", model)
}
}
cache.NativeProtocols = cloneTierProtocols(cache.NativeProtocols)
cache.Unsupported = cloneTierBools(cache.Unsupported)
for model := range cache.Unsupported {
if strings.TrimSpace(model) == "" {
return modelCatalogCache{}, errors.New("model catalog cache contains an empty unsupported model")
}
}
cache.NativeProtocols = cloneProtocols(cache.NativeProtocols)
cache.Unsupported = cloneBools(cache.Unsupported)
cache.UpdatedAt = cache.UpdatedAt.UTC()
return cache, nil
}
@@ -143,30 +143,6 @@ func normalizeModelIDs(items []string) []string {
return result
}
func validateCatalogCapabilities(native map[config.Tier]map[string]wire.Protocol, unsupported map[config.Tier]map[string]bool) error {
for tier, protocols := range native {
if tier != config.TierZen && tier != config.TierGo {
return fmt.Errorf("model catalog cache contains unknown tier %q", tier)
}
for model, protocol := range protocols {
if model == "" || !wire.Valid(protocol) {
return fmt.Errorf("model catalog cache contains invalid protocol for %q", model)
}
}
}
for tier, models := range unsupported {
if tier != config.TierZen && tier != config.TierGo {
return fmt.Errorf("model catalog cache contains unknown tier %q", tier)
}
for model := range models {
if strings.TrimSpace(model) == "" {
return errors.New("model catalog cache contains an empty unsupported model")
}
}
}
return nil
}
func saveModelCatalogCache(path string, cache modelCatalogCache) error {
if path == "" {
return nil
+112 -438
View File
@@ -2,76 +2,43 @@
package models
import (
"errors"
"fmt"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"opencode2api/internal/config"
wire "opencode2api/internal/protocol"
)
type Route struct {
ID string
Tier config.Tier
Protocol wire.Protocol
// Protocols is the native protocol for each possible upstream tier. Zen
// and Go intentionally do not share one global protocol: OpenCode's
// catalog currently exposes, for example, MiniMax through Chat on Zen and
// Messages on Go. The request must therefore be re-encoded when a retry
// crosses tiers.
Protocols map[config.Tier]wire.Protocol
Anonymous bool
// KeyTiers is the ordered authenticated fallback plan. Anonymous requests
// always start on Zen, then enter this list when the public credential does
// not succeed.
KeyTiers []config.Tier
}
type RouteDiagnostic struct {
Model string `json:"model"`
RequestedProtocol wire.Protocol `json:"requested_protocol,omitempty"`
NativeProtocol wire.Protocol `json:"native_protocol"`
NativeProtocols map[config.Tier]wire.Protocol `json:"native_protocols,omitempty"`
ProtocolSource string `json:"protocol_source"`
AvailableZen bool `json:"available_zen"`
AvailableGo bool `json:"available_go"`
Tier config.Tier `json:"tier,omitempty"`
Anonymous bool `json:"anonymous"`
KeyID string `json:"key_id,omitempty"`
Channel string `json:"channel,omitempty"`
Attempts int `json:"attempts,omitempty"`
KeyTiers []config.Tier `json:"key_tiers,omitempty"`
AnonymousEligibility AnonymousDecision `json:"anonymous_eligibility"`
RouteError string `json:"route_error,omitempty"`
type catalogState struct {
zen map[string]bool
nativeProtocols map[string]wire.Protocol
unsupported map[string]bool
modelMeta map[string]Metadata
sortedIDs []string
updatedAt time.Time
cacheSource string
stale bool
}
type Catalog struct {
mu sync.RWMutex
zen map[string]bool
goModels map[string]bool
protocols map[string]wire.Protocol
// nativeProtocols is populated from OpenCode's public model capability
// catalog. protocols remains the user-configured override map.
nativeProtocols map[config.Tier]map[string]wire.Protocol
unsupported map[config.Tier]map[string]bool
modelMeta map[config.Tier]map[string]Metadata
updatedAt time.Time
prefer config.Tier
pricing *PricingStore
availability *AvailabilityStore
cachePath string
cacheSource string
stale bool
refreshAfter time.Duration
freeOnly bool
state atomic.Pointer[catalogState]
protocols map[string]wire.Protocol
mu sync.RWMutex
pricing *PricingStore
availability *AvailabilityStore
cachePath string
refreshAfter time.Duration
}
type CatalogSnapshot struct {
Zen int `json:"zen"`
Go int `json:"go"`
Total int `json:"total"`
Exposed int `json:"exposed"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
@@ -79,20 +46,24 @@ type CatalogSnapshot struct {
Stale bool `json:"stale"`
}
func NewCatalog(prefer config.Tier, overrides map[string]string) *Catalog {
func NewCatalog(overrides map[string]string) *Catalog {
protocols := make(map[string]wire.Protocol, len(overrides))
for model, protocol := range overrides {
protocols[model] = wire.Protocol(protocol)
}
return &Catalog{
zen: map[string]bool{}, goModels: map[string]bool{}, protocols: protocols,
nativeProtocols: map[config.Tier]map[string]wire.Protocol{config.TierZen: {}, config.TierGo: {}},
unsupported: map[config.Tier]map[string]bool{config.TierZen: {}, config.TierGo: {}}, prefer: prefer,
cacheSource: "none",
c := &Catalog{
protocols: protocols,
}
c.state.Store(&catalogState{
zen: map[string]bool{},
nativeProtocols: map[string]wire.Protocol{},
unsupported: map[string]bool{},
modelMeta: map[string]Metadata{},
cacheSource: "none",
})
return c
}
// SetPricingStore connects routing decisions to the shared pricing metadata.
func (c *Catalog) SetPricingStore(store *PricingStore) {
c.mu.Lock()
c.pricing = store
@@ -105,17 +76,6 @@ func (c *Catalog) SetAvailabilityStore(store *AvailabilityStore) {
c.mu.Unlock()
}
// MetadataSnapshot reports pricing freshness without exposing the store.
func (c *Catalog) MetadataSnapshot() MetadataSnapshot {
c.mu.RLock()
store := c.pricing
c.mu.RUnlock()
if store == nil {
return MetadataSnapshot{}
}
return store.Snapshot()
}
func (c *Catalog) SetCachePath(path string) {
c.mu.Lock()
c.cachePath = path
@@ -128,223 +88,64 @@ func (c *Catalog) SetRefreshInterval(interval time.Duration) {
c.mu.Unlock()
}
// SetFreeOnly hides every model that is not free from discovery and routing.
func (c *Catalog) SetFreeOnly(enabled bool) {
c.mu.Lock()
c.freeOnly = enabled
c.mu.Unlock()
}
// freeOnlyErrorLocked rejects paid models while models.free_only is set. Both
// routing entry points check it, so /v1/models, inference, rotation aliases and
// diagnostics agree on what is exposed.
func (c *Catalog) freeOnlyErrorLocked(model string) error {
if c.freeOnly && !c.anonymousDecision(model).Allowed {
return fmt.Errorf("model %q is not free and models.free_only is enabled", model)
}
return nil
}
func (c *Catalog) Replace(zen, goModels []string) {
c.ReplaceWithCapabilities(zen, goModels, nil, nil, nil)
}
func (c *Catalog) ReplaceWithCapabilities(zen, goModels []string, native map[config.Tier]map[string]wire.Protocol, unsupported map[config.Tier]map[string]bool, metadata map[config.Tier]map[string]Metadata) {
func (c *Catalog) ReplaceWithCapabilities(zen []string, native map[string]wire.Protocol, unsupported map[string]bool, metadata map[string]Metadata) {
c.mu.Lock()
defer c.mu.Unlock()
if zen != nil {
c.zen = toSet(zen)
prev := c.state.Load()
next := &catalogState{
zen: prev.zen,
nativeProtocols: prev.nativeProtocols,
unsupported: prev.unsupported,
modelMeta: prev.modelMeta,
sortedIDs: prev.sortedIDs,
updatedAt: time.Now().UTC(),
cacheSource: "live",
stale: false,
}
if goModels != nil {
c.goModels = toSet(goModels)
if zen != nil {
next.zen = toSet(zen)
next.sortedIDs = sortedSetKeys(next.zen)
}
if native != nil {
for _, tier := range []config.Tier{config.TierZen, config.TierGo} {
if protocols, ok := native[tier]; ok {
c.nativeProtocols[tier] = cloneProtocols(protocols)
}
}
next.nativeProtocols = cloneProtocols(native)
}
if unsupported != nil {
for _, tier := range []config.Tier{config.TierZen, config.TierGo} {
if models, ok := unsupported[tier]; ok {
c.unsupported[tier] = cloneBools(models)
}
}
next.unsupported = cloneBools(unsupported)
}
if metadata != nil {
c.modelMeta = cloneModelMeta(metadata)
next.modelMeta = cloneMetadataMap(metadata)
}
c.updatedAt = time.Now().UTC()
c.cacheSource = "live"
c.stale = false
c.state.Store(next)
}
func (c *Catalog) CopyState(source *Catalog) {
if source == nil {
return
}
source.mu.RLock()
zen := make(map[string]bool, len(source.zen))
goModels := make(map[string]bool, len(source.goModels))
for model, available := range source.zen {
zen[model] = available
}
for model, available := range source.goModels {
goModels[model] = available
}
native := map[config.Tier]map[string]wire.Protocol{config.TierZen: {}, config.TierGo: {}}
unsupported := map[config.Tier]map[string]bool{config.TierZen: {}, config.TierGo: {}}
for _, tier := range []config.Tier{config.TierZen, config.TierGo} {
for model, protocol := range source.nativeProtocols[tier] {
native[tier][model] = protocol
}
for model, value := range source.unsupported[tier] {
unsupported[tier][model] = value
}
}
meta := cloneModelMeta(source.modelMeta)
updatedAt := source.updatedAt
cacheSource := source.cacheSource
stale := source.stale
source.mu.RUnlock()
c.mu.Lock()
c.zen, c.goModels, c.nativeProtocols, c.unsupported, c.updatedAt = zen, goModels, native, unsupported, updatedAt
c.modelMeta = meta
c.cacheSource, c.stale = cacheSource, stale
c.mu.Unlock()
}
func (c *Catalog) Route(model string, hasZenKeys, hasGoKeys, hasAnonymous bool) (Route, error) {
c.mu.RLock()
defer c.mu.RUnlock()
return c.routeLocked(model, hasZenKeys, hasGoKeys, hasAnonymous)
}
func (c *Catalog) routeLocked(model string, hasZenKeys, hasGoKeys, hasAnonymous bool) (Route, error) {
if c.availability != nil && c.availability.Disabled(model) {
return Route{}, fmt.Errorf("model %q is disabled after a failed availability check; restore it in the WebUI or wait for the next probe", model)
}
if err := c.freeOnlyErrorLocked(model); err != nil {
return Route{}, err
}
keyTiers := c.keyTierOrderLocked(model, hasZenKeys, hasGoKeys)
// OpenCode's public credential is a Zen-only lane. Every free model starts
// there, even if the current catalog only advertises it on Go: an upstream
// rejection will move the request into the authenticated fallback plan.
decision := c.anonymousDecision(model)
if hasAnonymous && decision.Allowed && (c.protocols[model] != "" || !c.unsupported[config.TierZen][model]) &&
(len(c.zen) == 0 && len(c.goModels) == 0 || c.zen[model] || c.goModels[model]) {
protocols := c.protocolsForLocked(model, keyTiers, true)
return Route{ID: model, Tier: config.TierZen, Protocol: protocols[config.TierZen], Protocols: protocols, Anonymous: true, KeyTiers: keyTiers}, nil
}
if len(keyTiers) > 0 {
protocols := c.protocolsForLocked(model, keyTiers, false)
return Route{ID: model, Tier: keyTiers[0], Protocol: protocols[keyTiers[0]], Protocols: protocols, KeyTiers: keyTiers}, nil
}
return Route{}, fmt.Errorf("model %q is not available in the configured Zen or Go pools", model)
}
func (r Route) ProtocolFor(tier config.Tier) wire.Protocol {
if protocol := r.Protocols[tier]; protocol != "" {
return protocol
}
return r.Protocol
}
func (c *Catalog) protocolsForLocked(model string, keyTiers []config.Tier, includeZen bool) map[config.Tier]wire.Protocol {
protocols := make(map[config.Tier]wire.Protocol, len(keyTiers)+1)
if includeZen {
protocols[config.TierZen] = c.protocolForLocked(model, config.TierZen)
}
for _, tier := range keyTiers {
protocols[tier] = c.protocolForLocked(model, tier)
}
return protocols
}
func (c *Catalog) protocolForLocked(model string, tier config.Tier) wire.Protocol {
if protocol := c.protocols[model]; protocol != "" {
return protocol
}
if protocol := c.nativeProtocols[tier][model]; protocol != "" {
return protocol
}
// The OpenCode capability catalog is authoritative when available. Chat is
// the only safe protocol-neutral fallback for an ID that has just appeared
// in /v1/models but is not present in the capability snapshot yet.
return wire.Chat
}
// keyTierOrderLocked builds an authenticated route in prefer order. A tier is
// included only when it has a key and advertises the model. Before the first
// successful catalog refresh, configured key pools remain usable so temporary
// discovery failures do not take the gateway offline.
func (c *Catalog) keyTierOrderLocked(model string, hasZenKeys, hasGoKeys bool) []config.Tier {
catalogPending := len(c.zen) == 0 && len(c.goModels) == 0
available := func(tier config.Tier) bool {
switch tier {
case config.TierZen:
return hasZenKeys && (catalogPending || c.zen[model]) && c.tierSupportedLocked(model, config.TierZen)
case config.TierGo:
return hasGoKeys && (catalogPending || c.goModels[model]) && c.tierSupportedLocked(model, config.TierGo)
default:
return false
}
}
order := []config.Tier{config.TierZen, config.TierGo}
if c.prefer == config.TierGo {
order[0], order[1] = order[1], order[0]
}
result := make([]config.Tier, 0, len(order))
for _, tier := range order {
if available(tier) {
result = append(result, tier)
}
}
return result
}
// RouteForTier builds a route pinned to one tier, used by the Playground's
// per-key diagnostics. It never selects the anonymous lane and never adds a
// fallback tier: the operator asked to exercise one configured key, so the
// result describes that key and nothing else.
func (c *Catalog) RouteForTier(model string, tier config.Tier, hasZenKeys, hasGoKeys bool) (Route, error) {
if tier != config.TierZen && tier != config.TierGo {
return Route{}, errors.New("selected key tier must be zen or go")
}
hasKeys := hasZenKeys
if tier == config.TierGo {
hasKeys = hasGoKeys
}
if !hasKeys {
return Route{}, fmt.Errorf("no %s key is configured", tier)
}
c.mu.RLock()
defer c.mu.RUnlock()
// Route resolves an anonymous free-tier route without acquiring locks on the
// catalog state (atomic pointer load).
func (c *Catalog) Route(model string) (Route, error) {
s := c.state.Load()
if c.availability != nil && c.availability.Disabled(model) {
return Route{}, fmt.Errorf("model %q is disabled after a failed availability check", model)
}
if err := c.freeOnlyErrorLocked(model); err != nil {
return Route{}, err
decision := c.anonymousDecision(model)
if !decision.Allowed {
return Route{}, fmt.Errorf("model %q is not available on the anonymous free tier", model)
}
catalogPending := len(c.zen) == 0 && len(c.goModels) == 0
advertised := c.zen[model]
if tier == config.TierGo {
advertised = c.goModels[model]
if c.protocols[model] == "" && s.unsupported[model] {
return Route{}, fmt.Errorf("model %q uses an unsupported upstream protocol", model)
}
if !catalogPending && !advertised {
return Route{}, fmt.Errorf("model %q is not available in the selected %s key tier", model, tier)
if len(s.zen) > 0 && !s.zen[model] {
return Route{}, fmt.Errorf("model %q is not available in the upstream catalog", model)
}
if !c.tierSupportedLocked(model, tier) {
return Route{}, fmt.Errorf("model %q uses an upstream protocol that is not available on the selected %s key tier", model, tier)
return Route{ID: model, Protocol: c.protocolFor(s, model)}, nil
}
func (c *Catalog) protocolFor(s *catalogState, model string) wire.Protocol {
if protocol := c.protocols[model]; protocol != "" {
return protocol
}
protocol := c.protocolForLocked(model, tier)
return Route{
ID: model, Tier: tier, Protocol: protocol,
Protocols: map[config.Tier]wire.Protocol{tier: protocol},
KeyTiers: []config.Tier{tier},
}, nil
if protocol := s.nativeProtocols[model]; protocol != "" {
return protocol
}
return wire.Chat
}
func (c *Catalog) anonymousDecision(model string) AnonymousDecision {
@@ -354,148 +155,74 @@ func (c *Catalog) anonymousDecision(model string) AnonymousDecision {
return AnonymousDecision{Allowed: isFreeModel(model), Source: "name_fallback_metadata_pending"}
}
// IsFreeModel reports whether the catalog considers the model free-tier
// (pricing metadata, falling back to the -free name convention). Key-tier
// shaping uses it so free models without "free" in the name are covered.
func (c *Catalog) IsFreeModel(model string) bool {
c.mu.RLock()
defer c.mu.RUnlock()
return c.anonymousDecision(model).Allowed
}
func (c *Catalog) Diagnostic(model string, requested wire.Protocol, hasZenKeys, hasGoKeys, hasAnonymous bool) RouteDiagnostic {
c.mu.RLock()
configured, explicit := c.protocols[model]
zen, goModel := c.zen[model], c.goModels[model]
nativeProtocols := map[config.Tier]wire.Protocol{
config.TierZen: c.protocolForLocked(model, config.TierZen),
config.TierGo: c.protocolForLocked(model, config.TierGo),
}
_, zenKnown := c.nativeProtocols[config.TierZen][model]
_, goKnown := c.nativeProtocols[config.TierGo][model]
c.mu.RUnlock()
source := "configured"
if !explicit {
source = "default"
if zenKnown || goKnown {
source = "upstream"
}
}
protocol := configured
if protocol == "" {
// Route() below selects the preferred available tier. This is only the
// fallback shown when no route can currently be built.
protocol = nativeProtocols[config.TierZen]
if c.prefer == config.TierGo {
protocol = nativeProtocols[config.TierGo]
}
}
diagnostic := RouteDiagnostic{
Model: model, RequestedProtocol: requested, NativeProtocol: protocol, NativeProtocols: nativeProtocols, ProtocolSource: source,
AvailableZen: zen, AvailableGo: goModel, AnonymousEligibility: c.anonymousDecision(model),
}
route, err := c.Route(model, hasZenKeys, hasGoKeys, hasAnonymous)
if err != nil {
diagnostic.RouteError = err.Error()
return diagnostic
}
diagnostic.NativeProtocol = route.Protocol
diagnostic.NativeProtocols = route.Protocols
diagnostic.Tier, diagnostic.Anonymous = route.Tier, route.Anonymous
diagnostic.KeyTiers = append([]config.Tier(nil), route.KeyTiers...)
return diagnostic
}
func isFreeModel(model string) bool {
return strings.Contains(strings.ToLower(model), "free")
}
func (c *Catalog) List() []string {
c.mu.RLock()
defer c.mu.RUnlock()
ids := c.modelIDsLocked()
models := ids[:0]
for _, model := range ids {
if c.supportedLocked(model) {
s := c.state.Load()
models := make([]string, 0, len(s.sortedIDs))
for _, model := range s.sortedIDs {
if c.supportedWith(s, model) {
models = append(models, model)
}
}
return models
}
func (c *Catalog) modelIDsLocked() []string {
seen := make(map[string]bool, len(c.zen)+len(c.goModels))
for model := range c.zen {
seen[model] = true
}
for model := range c.goModels {
seen[model] = true
}
return sortedSetKeys(seen)
}
func (c *Catalog) Snapshot() CatalogSnapshot {
c.mu.RLock()
defer c.mu.RUnlock()
return c.snapshotLocked(c.modelIDsLocked())
}
// AvailableModels provides discovery and readiness with the same route
// filtering, including configured key tiers and anonymous eligibility.
func (c *Catalog) AvailableModels(hasZenKeys, hasGoKeys, hasAnonymous bool) ([]Route, CatalogSnapshot) {
c.mu.RLock()
defer c.mu.RUnlock()
ids := c.modelIDsLocked()
routes := make([]Route, 0, len(ids))
for _, model := range ids {
if !c.supportedLocked(model) {
func (c *Catalog) AvailableModels() ([]Route, CatalogSnapshot) {
s := c.state.Load()
routes := make([]Route, 0, len(s.sortedIDs))
for _, model := range s.sortedIDs {
if !c.supportedWith(s, model) {
continue
}
if route, err := c.routeLocked(model, hasZenKeys, hasGoKeys, hasAnonymous); err == nil {
if route, err := c.Route(model); err == nil {
routes = append(routes, route)
}
}
snapshot := c.snapshotLocked(ids)
snapshot.Exposed = len(routes)
stale := s.stale
if !s.updatedAt.IsZero() && c.refreshAfter > 0 {
stale = stale || time.Since(s.updatedAt) > max(2*c.refreshAfter, time.Minute)
}
snapshot := CatalogSnapshot{
Total: len(s.sortedIDs),
Exposed: len(routes),
UpdatedAt: s.updatedAt,
CacheSource: s.cacheSource,
Stale: stale,
}
return routes, snapshot
}
func (c *Catalog) snapshotLocked(ids []string) CatalogSnapshot {
exposed := 0
for _, model := range ids {
if c.supportedLocked(model) {
exposed++
}
}
stale := c.stale
if !c.updatedAt.IsZero() && c.refreshAfter > 0 {
stale = stale || time.Since(c.updatedAt) > max(2*c.refreshAfter, time.Minute)
}
return CatalogSnapshot{
Zen: len(c.zen), Go: len(c.goModels), Total: len(ids), Exposed: exposed,
UpdatedAt: c.updatedAt, CacheSource: c.cacheSource, Stale: stale,
}
}
func (c *Catalog) Supported(model string) bool {
c.mu.RLock()
defer c.mu.RUnlock()
return c.supportedLocked(model)
return c.supportedWith(c.state.Load(), model)
}
// MetadataForTier returns the rich per-model metadata (context window,
// reasoning, tool call, modalities) captured from the opencode catalog for
// the tier that will actually serve the request. Same-named models can carry
// different limits per tier, so callers must pass route.Tier — never a
// tier-blind lookup. Anonymous routes always resolve to TierZen, which keeps
// the keyless path on Zen metadata. Limits the catalog omitted are filled from
// models.dev; capability flags always come from the catalog. The zero value is
// returned for models neither source describes (or before the first refresh).
func (c *Catalog) MetadataForTier(model string, tier config.Tier) Metadata {
c.mu.RLock()
md := c.modelMeta[tier][model]
func (c *Catalog) supportedWith(s *catalogState, model string) bool {
if len(s.zen) == 0 {
return true
}
if !s.zen[model] {
return false
}
if c.protocols[model] != "" {
return true
}
if s.unsupported[model] {
return false
}
return s.nativeProtocols[model] != ""
}
func (c *Catalog) MetadataFor(model string) Metadata {
s := c.state.Load()
md := s.modelMeta[model]
pricing := c.pricing
c.mu.RUnlock()
if pricing == nil {
return md
}
@@ -503,9 +230,6 @@ func (c *Catalog) MetadataForTier(model string, tier config.Tier) Metadata {
if !ok {
return md
}
// OpenCode's capability catalog is authoritative. Use models.dev limits
// only to fill fields it omitted so discovery clients still get per-model
// context and output limits.
if md.ContextWindow == 0 {
md.ContextWindow = price.ContextWindow
}
@@ -521,34 +245,6 @@ func (c *Catalog) MetadataForTier(model string, tier config.Tier) Metadata {
return md
}
func (c *Catalog) supportedLocked(model string) bool {
if len(c.zen) == 0 && len(c.goModels) == 0 {
return true
}
if c.zen[model] && c.tierSupportedLocked(model, config.TierZen) {
return true
}
if c.goModels[model] && c.tierSupportedLocked(model, config.TierGo) {
return true
}
return false
}
func (c *Catalog) tierSupportedLocked(model string, tier config.Tier) bool {
if c.protocols[model] != "" {
return true
}
if c.unsupported[tier][model] {
return false
}
if c.nativeProtocols[tier][model] != "" {
return true
}
// A pending catalog has no upstream capability snapshot to contradict a
// configured key, so retain the pre-refresh compatibility behavior.
return len(c.zen) == 0 && len(c.goModels) == 0
}
func toSet(items []string) map[string]bool {
out := make(map[string]bool, len(items))
for _, item := range items {
@@ -573,12 +269,10 @@ func cloneBools(source map[string]bool) map[string]bool {
return result
}
func cloneModelMeta(source map[config.Tier]map[string]Metadata) map[config.Tier]map[string]Metadata {
result := map[config.Tier]map[string]Metadata{config.TierZen: {}, config.TierGo: {}}
for _, tier := range []config.Tier{config.TierZen, config.TierGo} {
for id, md := range source[tier] {
result[tier][id] = md
}
func cloneMetadataMap(source map[string]Metadata) map[string]Metadata {
result := make(map[string]Metadata, len(source))
for id, md := range source {
result[id] = md
}
return result
}
@@ -593,23 +287,3 @@ func sortedSetKeys(source map[string]bool) []string {
sort.Strings(result)
return result
}
func cloneTierProtocols(source map[config.Tier]map[string]wire.Protocol) map[config.Tier]map[string]wire.Protocol {
result := map[config.Tier]map[string]wire.Protocol{config.TierZen: {}, config.TierGo: {}}
for _, tier := range []config.Tier{config.TierZen, config.TierGo} {
if protocols, ok := source[tier]; ok {
result[tier] = cloneProtocols(protocols)
}
}
return result
}
func cloneTierBools(source map[config.Tier]map[string]bool) map[config.Tier]map[string]bool {
result := map[config.Tier]map[string]bool{config.TierZen: {}, config.TierGo: {}}
for _, tier := range []config.Tier{config.TierZen, config.TierGo} {
if models, ok := source[tier]; ok {
result[tier] = cloneBools(models)
}
}
return result
}
+19 -50
View File
@@ -10,7 +10,6 @@ import (
"regexp"
"strings"
"opencode2api/internal/config"
"opencode2api/internal/httpx"
wire "opencode2api/internal/protocol"
)
@@ -18,7 +17,6 @@ import (
const (
CapabilitiesURL = "https://models.opencode.ai/api.json"
ZenDocsURL = "https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/web/src/content/docs/zen.mdx"
GoDocsURL = "https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/web/src/content/docs/go.mdx"
// LegacyZenBase is the legacy /zen console origin (serving /zen/v1/*) that
// still serves anonymous inference and the models listing alongside the newer
// /inference backend.
@@ -28,9 +26,9 @@ const (
var protocolDocEndpointPattern = regexp.MustCompile("\\|[^|]+\\|\\s*`?([^|`\\s]+)`?\\s*\\|\\s*`[^`]+/v1/(chat/completions|responses|messages|systemone)`")
type Capabilities struct {
Protocols map[config.Tier]map[string]wire.Protocol
Unsupported map[config.Tier]map[string]bool
Metadata map[config.Tier]map[string]Metadata
Protocols map[string]wire.Protocol
Unsupported map[string]bool
Metadata map[string]Metadata
}
type capabilityProvider struct {
@@ -61,10 +59,6 @@ type capabilityModelLimit struct {
Output int `json:"output"`
}
// Metadata carries the per-model capability fields surfaced through
// /v1/models so consumers (harnesses like Pi or jcode) get real context
// windows and feature flags from the catalog instead of guessing. It is
// purely additive: routing does not depend on any of these fields.
type Metadata struct {
ContextWindow int `json:"context_window,omitempty"`
MaxInput int `json:"max_input,omitempty"`
@@ -74,12 +68,9 @@ type Metadata struct {
StructuredOutput bool `json:"structured_output,omitempty"`
InputModalities []string `json:"input_modalities,omitempty"`
OutputModalities []string `json:"output_modalities,omitempty"`
// Cost is filled from models.dev at read time, in USD per million tokens.
Cost *Cost `json:"cost,omitempty"`
Cost *Cost `json:"cost,omitempty"`
}
// Cost is the published per-million-token price of a model. A nil field means
// the metadata did not state it.
type Cost struct {
Input *float64 `json:"input,omitempty"`
Output *float64 `json:"output,omitempty"`
@@ -109,10 +100,6 @@ type capabilityModelProvider struct {
NPM string `json:"npm"`
}
// fetchProtocolCapabilities reads OpenCode's machine-readable provider
// catalog. Unlike /v1/models, this source includes the SDK selected for each
// model, which is the upstream's protocol declaration. No model IDs are kept
// in this project.
func FetchCapabilities(ctx context.Context, client *http.Client, endpoint string) (Capabilities, error) {
if client == nil {
client = http.DefaultClient
@@ -137,13 +124,12 @@ func FetchCapabilities(ctx context.Context, client *http.Client, endpoint string
return Capabilities{}, err
}
result := Capabilities{
Protocols: map[config.Tier]map[string]wire.Protocol{config.TierZen: {}, config.TierGo: {}},
Unsupported: map[config.Tier]map[string]bool{config.TierZen: {}, config.TierGo: {}},
Metadata: map[config.Tier]map[string]Metadata{config.TierZen: {}, config.TierGo: {}},
Protocols: map[string]wire.Protocol{},
Unsupported: map[string]bool{},
Metadata: map[string]Metadata{},
}
for providerID, provider := range providers {
tier, ok := capabilityTier(providerID, provider.API)
if !ok {
if !isZenProvider(providerID, provider.API) {
continue
}
for modelID, model := range provider.Models {
@@ -155,35 +141,21 @@ func FetchCapabilities(ctx context.Context, client *http.Client, endpoint string
npm = model.Provider.NPM
}
if protocol, ok := protocolForSDK(npm); ok {
result.Protocols[tier][modelID] = protocol
result.Protocols[modelID] = protocol
} else {
result.Unsupported[tier][modelID] = true
result.Unsupported[modelID] = true
}
result.Metadata[tier][modelID] = model.metadata()
result.Metadata[modelID] = model.metadata()
}
}
// The machine catalog is the primary source. The upstream endpoint tables
// are a supplemental source for models whose provider inherits a default SDK
// but whose published endpoint is more specific (for example a Messages
// route). This remains data-driven: no model IDs are embedded here.
for _, doc := range []struct {
tier config.Tier
url string
}{
{config.TierZen, ZenDocsURL},
{config.TierGo, GoDocsURL},
} {
protocols, err := FetchProtocolDocs(ctx, client, doc.url)
if err != nil {
continue
}
if protocols, err := FetchProtocolDocs(ctx, client, ZenDocsURL); err == nil {
for modelID, protocol := range protocols {
result.Protocols[doc.tier][modelID] = protocol
delete(result.Unsupported[doc.tier], modelID)
result.Protocols[modelID] = protocol
delete(result.Unsupported, modelID)
}
}
if len(result.Protocols[config.TierZen]) == 0 && len(result.Protocols[config.TierGo]) == 0 && len(result.Unsupported[config.TierZen]) == 0 && len(result.Unsupported[config.TierGo]) == 0 {
return Capabilities{}, errors.New("OpenCode capability endpoint returned no Zen or Go models")
if len(result.Protocols) == 0 && len(result.Unsupported) == 0 {
return Capabilities{}, errors.New("OpenCode capability endpoint returned no Zen models")
}
return result, nil
}
@@ -238,15 +210,12 @@ func FetchProtocolDocs(ctx context.Context, client *http.Client, endpoint string
return result, nil
}
func capabilityTier(providerID, api string) (config.Tier, bool) {
func isZenProvider(providerID, api string) bool {
value := strings.ToLower(strings.TrimSpace(providerID + " " + api))
if strings.Contains(value, "opencode-go") || strings.Contains(value, "/go/") {
return config.TierGo, true
return false
}
if strings.Contains(value, "opencode") || strings.Contains(value, "/zen/") {
return config.TierZen, true
}
return "", false
return strings.Contains(value, "opencode") || strings.Contains(value, "/zen/")
}
func protocolForSDK(npm string) (wire.Protocol, bool) {
+32 -25
View File
@@ -14,6 +14,7 @@ import (
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"opencode2api/internal/httpx"
@@ -62,11 +63,15 @@ type modelMetadataCache struct {
Models map[string]Price `json:"models"`
}
type pricingState struct {
models map[string]Price
updatedAt time.Time
lastError string
}
type PricingStore struct {
mu sync.RWMutex
models map[string]Price
updatedAt time.Time
lastError string
mu sync.Mutex
state atomic.Pointer[pricingState]
cachePath string
endpoint string
client *http.Client
@@ -80,11 +85,15 @@ func NewPricingStore(configPath string, logger *slog.Logger) *PricingStore {
cachePath = configPath + ".models.dev.json"
}
store := &PricingStore{
models: make(map[string]Price), cachePath: cachePath, endpoint: modelsDevDefaultURL,
cachePath: cachePath, endpoint: modelsDevDefaultURL,
client: &http.Client{Timeout: modelsDevTimeout}, logger: logger,
}
store.state.Store(&pricingState{models: make(map[string]Price)})
if err := store.loadCache(); err != nil && !errors.Is(err, os.ErrNotExist) {
store.lastError = "load metadata cache: " + err.Error()
cur := store.state.Load()
next := *cur
next.lastError = "load metadata cache: " + err.Error()
store.state.Store(&next)
}
return store
}
@@ -99,9 +108,9 @@ func (store *PricingStore) SetClientProvider(provider func() []*http.Client) {
}
func (store *PricingStore) refreshClients() []*http.Client {
store.mu.RLock()
store.mu.Lock()
provider := store.clientProvider
store.mu.RUnlock()
store.mu.Unlock()
if provider == nil {
return []*http.Client{store.client}
}
@@ -160,7 +169,7 @@ func (store *PricingStore) Refresh(ctx context.Context) error {
}
}
store.mu.Lock()
store.models, store.updatedAt, store.lastError = models, now, ""
store.state.Store(&pricingState{models: models, updatedAt: now})
store.mu.Unlock()
return nil
}
@@ -192,16 +201,18 @@ func (store *PricingStore) fetch(ctx context.Context, client *http.Client) ([]by
func (store *PricingStore) recordError(err error) error {
store.mu.Lock()
store.lastError = err.Error()
cur := store.state.Load()
next := *cur
next.lastError = err.Error()
store.state.Store(&next)
store.mu.Unlock()
return err
}
func (store *PricingStore) Decide(model string) AnonymousDecision {
store.mu.RLock()
price, exists := store.models[model]
ready := !store.updatedAt.IsZero() && len(store.models) > 0
store.mu.RUnlock()
st := store.state.Load()
price, exists := st.models[model]
ready := !st.updatedAt.IsZero() && len(st.models) > 0
nameFree := isFreeModel(model)
fallback := func(source string) AnonymousDecision {
if nameFree {
@@ -245,18 +256,16 @@ func (store *PricingStore) Decide(model string) AnonymousDecision {
}
func (store *PricingStore) Price(model string) (Price, bool) {
store.mu.RLock()
defer store.mu.RUnlock()
price, ok := store.models[model]
st := store.state.Load()
price, ok := st.models[model]
return price, ok
}
func (store *PricingStore) Snapshot() MetadataSnapshot {
store.mu.RLock()
defer store.mu.RUnlock()
snapshot := MetadataSnapshot{Ready: !store.updatedAt.IsZero() && len(store.models) > 0, Models: len(store.models), LastError: store.lastError, CachePath: store.cachePath}
if !store.updatedAt.IsZero() {
updated := store.updatedAt.UTC()
st := store.state.Load()
snapshot := MetadataSnapshot{Ready: !st.updatedAt.IsZero() && len(st.models) > 0, Models: len(st.models), LastError: st.lastError, CachePath: store.cachePath}
if !st.updatedAt.IsZero() {
updated := st.updatedAt.UTC()
next := updated.Add(modelsDevRefresh)
snapshot.UpdatedAt, snapshot.NextRefresh = &updated, &next
snapshot.Stale = time.Since(updated) > modelsDevRefresh
@@ -281,7 +290,7 @@ func (store *PricingStore) loadCache() error {
if cache.UpdatedAt.IsZero() || len(cache.Models) == 0 {
return errors.New("metadata cache is empty or missing updated_at")
}
store.models, store.updatedAt = cache.Models, cache.UpdatedAt.UTC()
store.state.Store(&pricingState{models: cache.Models, updatedAt: cache.UpdatedAt.UTC()})
return nil
}
@@ -319,8 +328,6 @@ func decodeModelsDev(data []byte) (map[string]Price, error) {
for id, raw := range jsonutil.MapAt(provider, "models") {
model, _ := raw.(map[string]any)
modelID := jsonutil.FirstString(jsonutil.StringAt(model, "id"), id)
// Providers are sorted with OpenCode first, so keep its metadata
// for duplicate model IDs and use other OpenCode tiers to fill gaps.
if _, exists := result[modelID]; exists {
continue
}
-95
View File
@@ -1,95 +0,0 @@
package protocol
import (
"context"
"errors"
"fmt"
"io"
"net/http"
)
// StreamFailure carries upstream classification without exposing its raw text
// to the caller or diagnostics. It can be examined before committing a stream.
type StreamFailure struct{ Message, Type string }
func (e *StreamFailure) Error() string { return "upstream stream failed" }
type ClientWriteError struct{ Err error }
func (e *ClientWriteError) Error() string { return "downstream write failed" }
func (e *ClientWriteError) Unwrap() error { return e.Err }
// RotationStream holds role/start/usage events until useful content or a normal
// terminal event. Ready commits the chosen model and stops the first-output
// timer. Once committed, failures are emitted in-band and never replayed.
func RotationStream(ctx context.Context, w http.ResponseWriter, reader io.Reader, from, to Protocol, alias string, ready func() error) (usage Usage, reported, committed bool, result error) {
flusher, ok := w.(http.Flusher)
if !ok {
return usage, false, false, fmt.Errorf("streaming is unsupported")
}
parser := newStreamUsageObserver(from).parser
emitter := newBridgeStreamEmitter(w, flusher, to, alias)
pending := []bridgeStreamEvent{}
var upstreamFailure error
emit := func(event bridgeStreamEvent) error {
event.Model = "" // The emitter's model is the requested alias for the whole response.
if err := emitter.Emit(event); err != nil {
if errors.Is(err, errStreamUpstreamFailure) {
return err
}
return &ClientWriteError{err}
}
return nil
}
readErr := readSSE(reader, func(name, data string) error {
events, err := parser.Parse(name, data)
if err != nil {
return &StreamFailure{Type: "parse_error"}
}
for _, event := range events {
if event.Kind == "error" {
upstreamFailure = &StreamFailure{event.Error, event.ErrorType}
return upstreamFailure
}
if !committed {
effective := event.Kind == "text" || event.Kind == "reasoning" || event.Kind == "reasoning_signature" || event.Kind == "tool_start" || event.Kind == "tool_delta" || event.Kind == "done"
if !effective {
if len(pending) >= 256 {
return &StreamFailure{Type: "invalid_prelude"}
}
pending = append(pending, event)
continue
}
if err := ready(); err != nil {
return err
}
committed = true
for _, p := range pending {
if err := emit(p); err != nil {
return err
}
}
pending = nil
}
if err := emit(event); err != nil {
return err
}
if event.Kind == "done" {
return errStreamNormalTermination
}
}
return nil
})
usage, reported = emitter.usage, emitter.usageReported
if errors.Is(readErr, errStreamNormalTermination) {
return usage, reported, committed, nil
}
if readErr == nil {
readErr = &StreamFailure{Type: "unexpected_eof"}
}
var writeErr *ClientWriteError
if committed && ctx.Err() == nil && !errors.As(readErr, &writeErr) {
_ = emit(bridgeStreamEvent{Kind: "error", Error: "当前上游模型的输出中断;本次响应已结束,请重新发起请求。", ErrorType: "upstream_error"})
}
return usage, reported, committed, readErr
}
-294
View File
@@ -1,294 +0,0 @@
// Package rotation owns sticky, service-wide model selection. No network call
// runs under its lock. A generation prevents late requests undoing a switch.
package rotation
import (
"encoding/json"
"fmt"
"opencode2api/internal/config"
"os"
"path/filepath"
"slices"
"sort"
"sync"
"time"
)
type Attempt struct {
Time time.Time `json:"time"`
Request string `json:"request"`
Alias string `json:"alias"`
Model string `json:"model"`
Number int `json:"number"`
Outcome string `json:"outcome"`
}
type Switch struct {
Time time.Time `json:"time"`
From string `json:"from"`
To string `json:"to"`
Reason string `json:"reason"`
}
type Group struct {
ID string `json:"id"`
Alias string `json:"alias"`
Order []string `json:"order"`
Current string `json:"current"`
Generation uint64 `json:"generation"`
Paused map[string]time.Time `json:"paused"`
Available map[string]bool `json:"available"`
Switches []Switch `json:"switches"`
}
type Snapshot struct {
Groups []*Group `json:"groups"`
Attempts []Attempt `json:"attempts"`
PersistenceError string `json:"persistence_error,omitempty"`
FirstOutputSeconds int `json:"first_output_seconds"`
}
type Token struct {
Group, Model string
Generation uint64
}
type Manager struct {
mu sync.Mutex
path string
state Snapshot
cfg config.RotationConfig
}
func New(path string, cfg config.RotationConfig) (*Manager, error) {
m := &Manager{path: path}
if path != "" {
b, e := os.ReadFile(path)
if e == nil {
if e = json.Unmarshal(b, &m.state); e != nil {
return nil, fmt.Errorf("invalid rotation state: %w", e)
}
} else if !os.IsNotExist(e) {
return nil, e
}
}
if len(m.state.Groups) != 0 && (len(m.state.Groups) != 2 || m.state.Groups[0] == nil || m.state.Groups[1] == nil || m.state.Groups[0].ID != "sota" || m.state.Groups[1].ID != "sweet") {
return nil, fmt.Errorf("invalid rotation groups")
}
m.Configure(cfg)
if m.state.PersistenceError != "" {
return nil, fmt.Errorf("cannot persist rotation state")
}
return m, nil
}
func (m *Manager) Configure(cfg config.RotationConfig) {
m.mu.Lock()
defer m.mu.Unlock()
cfg.Defaults()
for i, c := range []config.RotationGroup{cfg.SOTA, cfg.Sweet} {
id := []string{"sota", "sweet"}[i]
if len(m.state.Groups) <= i {
m.state.Groups = append(m.state.Groups, &Group{ID: id})
}
g := m.state.Groups[i]
previous := m.cfg.SOTA
if i == 1 {
previous = m.cfg.Sweet
}
order := slices.Clone(g.Order)
if len(order) == 0 || !slices.Equal(previous.Order, c.Order) {
order = slices.Clone(c.Order)
for _, v := range g.Order {
if !slices.Contains(order, v) {
order = append(order, v)
}
}
}
if !slices.Equal(order, g.Order) || g.Alias != c.Alias {
g.Generation++
}
g.Order = order
g.Alias = c.Alias
if g.Paused == nil {
g.Paused = map[string]time.Time{}
}
if !slices.Contains(g.Order, g.Current) && len(g.Order) > 0 {
g.Current = g.Order[0]
g.Generation++
}
}
m.cfg = cfg
m.state.FirstOutputSeconds = cfg.FirstOutputSeconds
m.saveLocked()
}
func (m *Manager) Sync(available map[string]bool) {
m.mu.Lock()
defer m.mu.Unlock()
changed := false
for _, g := range m.state.Groups {
g.Available = map[string]bool{}
for model := range available {
if config.IsSOTA(model) == (g.ID == "sota") {
g.Available[model] = true
}
}
added := []string{}
for model := range g.Available {
if !slices.Contains(g.Order, model) {
added = append(added, model)
}
}
sort.Strings(added)
if len(g.Order) == 0 && slices.Contains(added, "glm-5.3-flash") {
added = append([]string{"glm-5.3-flash"}, slices.Delete(added, slices.Index(added, "glm-5.3-flash"), slices.Index(added, "glm-5.3-flash")+1)...)
}
if len(added) > 0 {
g.Order = append(g.Order, added...)
changed = true
}
if g.Current == "" && len(g.Order) > 0 {
g.Current = g.Order[0]
g.Generation++
changed = true
}
}
if changed {
m.saveLocked()
}
}
func (m *Manager) GroupID(alias string) string {
m.mu.Lock()
defer m.mu.Unlock()
for _, g := range m.state.Groups {
if g.Alias == alias {
return g.ID
}
}
return ""
}
func (m *Manager) Snapshot() Snapshot {
m.mu.Lock()
defer m.mu.Unlock()
b, _ := json.Marshal(m.state)
var s Snapshot
_ = json.Unmarshal(b, &s)
return s
}
func (m *Manager) group(id string) *Group {
for _, g := range m.state.Groups {
if g.ID == id {
return g
}
}
return nil
}
func usable(g *Group, model string) bool {
return g.Available[model] && !time.Now().Before(g.Paused[model])
}
func (m *Manager) Select(id string, visited map[string]bool) (Token, bool) {
m.mu.Lock()
defer m.mu.Unlock()
g := m.group(id)
if g == nil || len(g.Order) == 0 {
return Token{}, false
}
start := max(slices.Index(g.Order, g.Current), 0)
for n := 0; n < len(g.Order); n++ {
model := g.Order[(start+n)%len(g.Order)]
if visited[model] || !usable(g, model) {
continue
}
// A request-local skip must not change a newer, healthy global selection.
if !usable(g, g.Current) {
m.switchLocked(g, model, "当前模型暂停或已下架")
m.saveLocked()
}
return Token{g.ID, model, g.Generation}, true
}
return Token{}, false
}
func (m *Manager) switchLocked(g *Group, to, reason string) {
from := g.Current
g.Current = to
g.Generation++
g.Switches = append(g.Switches, Switch{time.Now().UTC(), from, to, reason})
if len(g.Switches) > 30 {
g.Switches = g.Switches[len(g.Switches)-30:]
}
}
func (m *Manager) Fail(t Token, pause time.Duration, reason string) {
m.mu.Lock()
defer m.mu.Unlock()
g := m.group(t.Group)
if g == nil {
return
}
until := time.Now().Add(pause).UTC()
if until.After(g.Paused[t.Model]) {
g.Paused[t.Model] = until
}
if g.Current == t.Model && g.Generation == t.Generation {
start := slices.Index(g.Order, t.Model)
next := t.Model
for n := 1; n < len(g.Order); n++ {
v := g.Order[(start+n)%len(g.Order)]
if usable(g, v) {
next = v
break
}
}
m.switchLocked(g, next, reason)
}
m.saveLocked()
}
func (m *Manager) Manual(id, model string) error {
m.mu.Lock()
defer m.mu.Unlock()
g := m.group(id)
if g == nil || !slices.Contains(g.Order, model) || !g.Available[model] {
return fmt.Errorf("请选择该组当前可用的 Go 模型")
}
delete(g.Paused, model)
m.switchLocked(g, model, "管理员手动切换")
m.saveLocked()
if m.state.PersistenceError != "" {
return fmt.Errorf("轮转状态保存失败")
}
return nil
}
func (m *Manager) Record(a Attempt) {
m.mu.Lock()
defer m.mu.Unlock()
a.Time = time.Now().UTC()
m.state.Attempts = append(m.state.Attempts, a)
if len(m.state.Attempts) > 100 {
m.state.Attempts = m.state.Attempts[len(m.state.Attempts)-100:]
}
m.saveLocked()
}
func (m *Manager) saveLocked() {
if m.path == "" {
return
}
m.state.PersistenceError = ""
if err := m.writeLocked(); err != nil {
m.state.PersistenceError = "轮转状态写入失败,请检查磁盘空间和文件权限"
}
}
func (m *Manager) writeLocked() error {
b, e := json.MarshalIndent(m.state, "", " ")
if e != nil {
return e
}
f, e := os.CreateTemp(filepath.Dir(m.path), ".rotation-*.tmp")
if e != nil {
return e
}
defer os.Remove(f.Name())
if _, e = f.Write(b); e == nil {
e = f.Sync()
}
ce := f.Close()
if e == nil {
e = ce
}
if e != nil {
return e
}
return os.Rename(f.Name(), m.path)
}
+49 -55
View File
@@ -12,38 +12,17 @@ import (
)
type RequestMeta struct {
ModelAlias string
Model string
Tier string
Protocol protocol.Protocol
Request string
// Session is the canonical upstream session (ses_...). All turns of one
// conversation share it, so per-session token burn is visible in logs
// and monitoring: every session draws from the same upstream IP bucket
// on the anonymous lane.
Session string
KeyID string
Channel string
Anonymous bool
Proxy string
Attempts int
Legs []string
Stop string
Tail string
Stream bool
// ServerKeyID is the fingerprint of the local server key the caller
// authenticated with, so usage can be split per caller. KeyID is the
// upstream account that served the request.
ServerKeyID string
// Shaped marks a key-tier free-model request whose wire body was
// normalized to agent shape (stream + required tools) like the anonymous
// lane. Non-streaming responses for shaped requests arrive as SSE
// and must be collapsed like anonymous ones.
Shaped bool
// ToolAlias holds the client's original read-related tool name (e.g.
// "reAd" or "read_file") when the legacy /zen/v1 shaper renamed it to
// "read" on the outbound wire. When non-empty, "read" tool calls in the
// upstream response are rewritten back to ToolAlias before returning.
Model string
Protocol protocol.Protocol
Request string
Session string
Proxy string
Attempts int
Legs []string
Stop string
Tail string
Stream bool
ServerKeyID string
ToolAlias string
Usage protocol.Usage
UsageReported bool
@@ -51,18 +30,12 @@ type RequestMeta struct {
Outcome string
}
// PlaygroundServerKey buckets admin Playground traffic, which authenticates
// with whichever server key is enabled first and is not that caller's usage.
const PlaygroundServerKey = "playground"
type requestMetaKey struct{}
// WithRequestMeta shares request-local outcomes across HTTP and gateway layers.
func WithRequestMeta(ctx context.Context, meta *RequestMeta) context.Context {
return context.WithValue(ctx, requestMetaKey{}, meta)
}
// MetaFromContext returns the request-local trace, or nil when it is absent.
func MetaFromContext(ctx context.Context) *RequestMeta {
meta, _ := ctx.Value(requestMetaKey{}).(*RequestMeta)
return meta
@@ -96,7 +69,9 @@ func (w *statusWriter) Write(data []byte) (int, error) {
}
func (w *statusWriter) Flush() {
_ = http.NewResponseController(w.ResponseWriter).Flush()
if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
flusher.Flush()
}
}
func (w *statusWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
@@ -108,37 +83,56 @@ func Middleware(monitor *Monitor, logger *slog.Logger, next http.Handler) http.H
return
}
started := time.Now()
meta := MetaFromRequest(r)
if meta == nil {
meta = &RequestMeta{}
r = r.WithContext(WithRequestMeta(r.Context(), meta))
}
meta := &RequestMeta{}
r = r.WithContext(WithRequestMeta(r.Context(), meta))
writer := &statusWriter{ResponseWriter: w}
monitor.active.Add(1)
if monitor != nil {
monitor.active.Add(1)
}
defer func() {
monitor.active.Add(-1)
if monitor != nil {
monitor.active.Add(-1)
}
status := writer.status
if status == 0 {
status = http.StatusOK
}
duration := time.Since(started)
monitor.Record(r.URL.Path, status, duration, meta)
if monitor != nil {
monitor.Record(status, meta)
}
outcome := meta.Outcome
if outcome == "" {
outcome = requestOutcome(status, meta.Channel)
outcome = requestOutcome(status, meta.Attempts > 0)
}
if meta.Channel != "" {
if meta.Attempts > 0 {
logger.Info("request routed", "component", "http", "event", "request_routed", "method", r.Method,
"path", r.URL.Path, "status", status, "duration_ms", duration.Milliseconds(), "request_id", meta.Request,
"model", meta.Model, "model_alias", meta.ModelAlias, "session", meta.Session, "server_key_id", meta.ServerKeyID, "tier", meta.Tier, "key_id", meta.KeyID,
"channel", meta.Channel, "anonymous", meta.Anonymous, "attempts", meta.Attempts, "legs", strings.Join(meta.Legs, " "), "stream", meta.Stream, "outcome", outcome,
"model", meta.Model, "session", meta.Session, "server_key_id", meta.ServerKeyID,
"proxy", meta.Proxy, "attempts", meta.Attempts, "legs", strings.Join(meta.Legs, " "), "stream", meta.Stream, "outcome", outcome,
"stop", meta.Stop, "in", meta.Usage.Input, "out", meta.Usage.Output, "reasoning_tokens", meta.Usage.Reasoning, "cached", meta.Usage.Cached, "tail", meta.Tail)
} else if logger.Enabled(r.Context(), slog.LevelDebug) {
logger.Debug("request completed", "component", "http", "event", "request_complete", "method", r.Method,
"path", r.URL.Path, "status", status, "duration_ms", duration.Milliseconds(), "bytes", writer.bytes,
"request_id", meta.Request, "model", meta.Model, "outcome", outcome)
}
logger.Debug("request completed", "component", "http", "event", "request_complete", "method", r.Method,
"path", r.URL.Path, "status", status, "duration_ms", duration.Milliseconds(), "bytes", writer.bytes,
"request_id", meta.Request, "model", meta.Model, "model_alias", meta.ModelAlias, "tier", meta.Tier, "key_id", meta.KeyID,
"channel", meta.Channel, "anonymous", meta.Anonymous, "attempts", meta.Attempts, "stream", meta.Stream, "outcome", outcome)
}()
next.ServeHTTP(writer, r)
})
}
func requestOutcome(status int, routed bool) string {
if !routed {
return "not_routed"
}
if status >= 200 && status < 400 {
return "success"
}
if status >= 400 && status < 500 {
return "client_error"
}
if status >= 500 {
return "server_error"
}
return "unknown"
}
+13 -204
View File
@@ -1,145 +1,26 @@
package telemetry
import (
"context"
"fmt"
"io"
"log/slog"
"os"
"strings"
"sync"
"time"
"opencode2api/internal/config"
)
type LogEvent struct {
Sequence uint64 `json:"sequence"`
Time time.Time `json:"time"`
Level string `json:"level"`
Message string `json:"message"`
Component string `json:"component,omitempty"`
Fields map[string]any `json:"fields,omitempty"`
func NewStructuredLogger(level *slog.LevelVar, redactor *config.SecretRedactor) *slog.Logger {
return newStructuredLogger(os.Stdout, level, redactor)
}
type logSubscriber struct {
ch chan LogEvent
}
type LogHub struct {
mu sync.RWMutex
buffer []LogEvent
start int
count int
next uint64
subscribers map[uint64]*logSubscriber
nextSub uint64
}
func NewLogHub(capacity int) *LogHub {
if capacity < 100 {
capacity = 100
}
return &LogHub{buffer: make([]LogEvent, capacity), subscribers: make(map[uint64]*logSubscriber)}
}
func (h *LogHub) Resize(capacity int) {
if capacity < 100 {
capacity = 100
}
h.mu.Lock()
if capacity == len(h.buffer) {
h.mu.Unlock()
return
}
keep := min(h.count, capacity)
next := make([]LogEvent, capacity)
for i := 0; i < keep; i++ {
source := (h.start + h.count - keep + i) % len(h.buffer)
next[i] = h.buffer[source]
}
h.buffer, h.start, h.count = next, 0, keep
h.mu.Unlock()
}
func (h *LogHub) Publish(event LogEvent) {
h.mu.Lock()
h.next++
event.Sequence = h.next
if h.count < len(h.buffer) {
index := (h.start + h.count) % len(h.buffer)
h.buffer[index] = event
h.count++
} else {
h.buffer[h.start] = event
h.start = (h.start + 1) % len(h.buffer)
}
for _, sub := range h.subscribers {
select {
case sub.ch <- event:
default:
// A slow browser must never block request processing. Its reconnect
// cursor will make the gap visible on the next subscription.
}
}
h.mu.Unlock()
}
func (h *LogHub) Recent(after uint64, limit int) ([]LogEvent, bool) {
h.mu.RLock()
defer h.mu.RUnlock()
if limit < 1 || limit > len(h.buffer) {
limit = len(h.buffer)
}
oldest := uint64(0)
if h.count > 0 {
oldest = h.buffer[h.start].Sequence
}
gap := after > 0 && oldest > 0 && after+1 < oldest
out := make([]LogEvent, 0, min(limit, h.count))
for i := 0; i < h.count; i++ {
event := h.buffer[(h.start+i)%len(h.buffer)]
if event.Sequence > after {
out = append(out, event)
}
}
if len(out) > limit {
out = out[len(out)-limit:]
}
return out, gap
}
func (h *LogHub) Subscribe() (<-chan LogEvent, func()) {
h.mu.Lock()
h.nextSub++
id := h.nextSub
sub := &logSubscriber{ch: make(chan LogEvent, 128)}
h.subscribers[id] = sub
h.mu.Unlock()
return sub.ch, func() {
h.mu.Lock()
delete(h.subscribers, id)
h.mu.Unlock()
}
}
type hubHandler struct {
base slog.Handler
hub *LogHub
redactor *config.SecretRedactor
attrs []slog.Attr
groups []string
}
func NewStructuredLogger(level *slog.LevelVar, hub *LogHub, redactor *config.SecretRedactor) *slog.Logger {
return newStructuredLogger(os.Stdout, level, hub, redactor)
}
func newStructuredLogger(output io.Writer, level *slog.LevelVar, hub *LogHub, redactor *config.SecretRedactor) *slog.Logger {
base := slog.NewJSONHandler(output, &slog.HandlerOptions{Level: level, ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
return sanitizeLogAttr(redactor, attr)
}})
return slog.New(&hubHandler{base: base, hub: hub, redactor: redactor})
func newStructuredLogger(output io.Writer, level *slog.LevelVar, redactor *config.SecretRedactor) *slog.Logger {
base := slog.NewJSONHandler(output, &slog.HandlerOptions{
Level: level,
ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
return sanitizeLogAttr(redactor, attr)
},
})
return slog.New(base)
}
func sanitizeLogAttr(redactor *config.SecretRedactor, attr slog.Attr) slog.Attr {
@@ -148,6 +29,9 @@ func sanitizeLogAttr(redactor *config.SecretRedactor, attr slog.Attr) slog.Attr
if strings.Contains(lower, "password") || strings.Contains(lower, "authorization") || strings.Contains(lower, "cookie") || strings.Contains(lower, "secret") {
return slog.String(attr.Key, "***")
}
if redactor == nil {
return attr
}
switch attr.Value.Kind() {
case slog.KindString:
attr.Value = slog.StringValue(redactor.String(attr.Value.String()))
@@ -159,81 +43,6 @@ func sanitizeLogAttr(redactor *config.SecretRedactor, attr slog.Attr) slog.Attr
return attr
}
func (h *hubHandler) Enabled(ctx context.Context, level slog.Level) bool {
return h.base.Enabled(ctx, level)
}
func (h *hubHandler) Handle(ctx context.Context, record slog.Record) error {
if err := h.base.Handle(ctx, record); err != nil {
return err
}
fields := make(map[string]any, record.NumAttrs()+len(h.attrs))
for _, attr := range h.attrs {
h.addAttr(fields, attr)
}
record.Attrs(func(attr slog.Attr) bool {
h.addAttr(fields, attr)
return true
})
component, _ := fields["component"].(string)
delete(fields, "component")
h.hub.Publish(LogEvent{
Time: record.Time.UTC(),
Level: strings.ToLower(record.Level.String()),
Message: h.redactor.String(record.Message),
Component: component,
Fields: fields,
})
return nil
}
func (h *hubHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
clone := *h
clone.base = h.base.WithAttrs(attrs)
clone.attrs = append(append([]slog.Attr(nil), h.attrs...), attrs...)
return &clone
}
func (h *hubHandler) WithGroup(name string) slog.Handler {
clone := *h
clone.base = h.base.WithGroup(name)
clone.groups = append(append([]string(nil), h.groups...), name)
return &clone
}
func (h *hubHandler) addAttr(fields map[string]any, attr slog.Attr) {
attr.Value = attr.Value.Resolve()
key := attr.Key
if len(h.groups) > 0 {
key = strings.Join(append(append([]string(nil), h.groups...), key), ".")
}
lower := strings.ToLower(key)
if strings.Contains(lower, "password") || strings.Contains(lower, "authorization") || strings.Contains(lower, "cookie") || strings.Contains(lower, "secret") {
fields[key] = "***"
return
}
var value any
switch attr.Value.Kind() {
case slog.KindString:
value = h.redactor.String(attr.Value.String())
case slog.KindInt64:
value = attr.Value.Int64()
case slog.KindUint64:
value = attr.Value.Uint64()
case slog.KindFloat64:
value = attr.Value.Float64()
case slog.KindBool:
value = attr.Value.Bool()
case slog.KindDuration:
value = attr.Value.Duration().String()
case slog.KindTime:
value = attr.Value.Time().UTC()
default:
value = h.redactor.String(fmt.Sprint(attr.Value.Any()))
}
fields[key] = value
}
func SetLogLevel(level *slog.LevelVar, value string) {
switch value {
case "debug":
+32 -675
View File
@@ -1,244 +1,12 @@
package telemetry
import (
"fmt"
"sync"
"sync/atomic"
"time"
"opencode2api/internal/protocol"
)
type metricBucket struct {
minute int64
total uint64
success uint64
errors uint64
duration uint64
histogram [11]uint64
endpoints map[string]uint64
models map[string]uint64
tiers map[string]uint64
statuses map[string]uint64
usageRequests uint64
usageReported uint64
tokens TokenCounts
usageModels map[string]TokenCounts
usageTiers map[string]TokenCounts
usageSessions map[string]TokenCounts
usageKeys map[string]ServerKeyUsage
}
func (b *metricBucket) reset(minute int64) {
*b = metricBucket{
minute: minute, endpoints: make(map[string]uint64), models: make(map[string]uint64),
tiers: make(map[string]uint64), statuses: make(map[string]uint64),
usageModels: make(map[string]TokenCounts), usageTiers: make(map[string]TokenCounts),
usageSessions: make(map[string]TokenCounts), usageKeys: make(map[string]ServerKeyUsage),
}
}
type TokenCounts struct {
Input uint64 `json:"input_tokens"`
Output uint64 `json:"output_tokens"`
Cached uint64 `json:"cached_tokens"`
Reasoning uint64 `json:"reasoning_tokens"`
Total uint64 `json:"total_tokens"`
}
type UsagePeriod struct {
Requests uint64 `json:"requests"`
Reported uint64 `json:"reported"`
Coverage float64 `json:"coverage"`
Tokens TokenCounts `json:"tokens"`
Models map[string]TokenCounts `json:"models"`
Tiers map[string]TokenCounts `json:"tiers"`
// Sessions maps canonical session ID to token burn. Sessions share one
// upstream IP bucket on the anonymous lane, so this shows which
// conversation is draining the daily budget.
Sessions map[string]TokenCounts `json:"sessions"`
// ServerKeys maps the local server key fingerprint (or "playground") to
// its share of Requests and Tokens, so the entries sum to the totals.
ServerKeys map[string]ServerKeyUsage `json:"server_keys"`
}
type ServerKeyUsage struct {
Requests uint64 `json:"requests"`
TokenCounts
}
type UsageSnapshot struct {
Lifetime UsagePeriod `json:"lifetime"`
Window UsagePeriod `json:"last_hour"`
}
type AttemptCounts struct {
Total uint64 `json:"total"`
Success uint64 `json:"success"`
Failed uint64 `json:"failed"`
}
type AttemptAggregate struct {
AttemptCounts
SuccessRate float64 `json:"success_rate"`
Tiers map[string]AttemptCounts `json:"tiers"`
Channels map[string]AttemptCounts `json:"channels"`
Keys map[string]AttemptCounts `json:"keys"`
}
type UpstreamAttempt struct {
Time time.Time `json:"time"`
RequestID string `json:"request_id"`
Model string `json:"model"`
Tier string `json:"tier"`
Attempt int `json:"attempt"`
KeyID string `json:"key_id"`
Channel string `json:"channel"`
Anonymous bool `json:"anonymous"`
Proxy string `json:"proxy_node"`
Status int `json:"status,omitempty"`
DurationMS int64 `json:"duration_ms"`
Success bool `json:"success"`
Outcome string `json:"outcome"`
}
// UpstreamRequest is the credential route that was actually used for one
// client inference request. It is kept separately from UpstreamAttempt,
// because a single request can try several keys before it succeeds.
type UpstreamRequest struct {
Time time.Time `json:"time"`
RequestID string `json:"request_id"`
Session string `json:"session,omitempty"`
ServerKeyID string `json:"server_key_id,omitempty"`
Model string `json:"model"`
Tier string `json:"tier,omitempty"`
KeyID string `json:"key_id,omitempty"`
Channel string `json:"channel"`
Anonymous bool `json:"anonymous"`
Proxy string `json:"proxy_node,omitempty"`
Attempts int `json:"attempts"`
Status int `json:"status"`
DurationMS int64 `json:"duration_ms"`
Success bool `json:"success"`
Outcome string `json:"outcome"`
}
type attemptBucket struct {
minute int64
aggregate AttemptAggregate
}
type UpstreamSnapshot struct {
Lifetime AttemptAggregate `json:"lifetime"`
Window AttemptAggregate `json:"last_hour"`
Requests []UpstreamRequest `json:"requests"`
Recent []UpstreamAttempt `json:"recent"`
}
const (
monitorRecentRequestCapacity = 10000
monitorRecentAttemptCapacity = 20000
monitorRecentOutputLimit = 500
)
type upstreamRequestRing struct {
items []UpstreamRequest
start int
count int
}
func newUpstreamRequestRing() upstreamRequestRing {
return upstreamRequestRing{items: make([]UpstreamRequest, monitorRecentRequestCapacity)}
}
func (ring *upstreamRequestRing) Add(value UpstreamRequest) {
if len(ring.items) == 0 {
ring.items = make([]UpstreamRequest, monitorRecentRequestCapacity)
}
index := (ring.start + ring.count) % len(ring.items)
if ring.count == len(ring.items) {
ring.items[index] = value
ring.start = (ring.start + 1) % len(ring.items)
return
}
ring.items[index] = value
ring.count++
}
func (ring *upstreamRequestRing) PruneBefore(cutoff time.Time) {
for ring.count > 0 && ring.items[ring.start].Time.Before(cutoff) {
ring.items[ring.start] = UpstreamRequest{}
ring.start = (ring.start + 1) % len(ring.items)
ring.count--
}
}
func (ring *upstreamRequestRing) Snapshot(cutoff time.Time, limit int) []UpstreamRequest {
if limit < 1 || ring.count == 0 {
return nil
}
result := make([]UpstreamRequest, 0, min(ring.count, limit))
for offset := 0; offset < ring.count; offset++ {
value := ring.items[(ring.start+offset)%len(ring.items)]
if !value.Time.Before(cutoff) {
result = append(result, value)
}
}
if len(result) > limit {
result = result[len(result)-limit:]
}
return result
}
type upstreamAttemptRing struct {
items []UpstreamAttempt
start int
count int
}
func newUpstreamAttemptRing() upstreamAttemptRing {
return upstreamAttemptRing{items: make([]UpstreamAttempt, monitorRecentAttemptCapacity)}
}
func (ring *upstreamAttemptRing) Add(value UpstreamAttempt) {
if len(ring.items) == 0 {
ring.items = make([]UpstreamAttempt, monitorRecentAttemptCapacity)
}
index := (ring.start + ring.count) % len(ring.items)
if ring.count == len(ring.items) {
ring.items[index] = value
ring.start = (ring.start + 1) % len(ring.items)
return
}
ring.items[index] = value
ring.count++
}
func (ring *upstreamAttemptRing) PruneBefore(cutoff time.Time) {
for ring.count > 0 && ring.items[ring.start].Time.Before(cutoff) {
ring.items[ring.start] = UpstreamAttempt{}
ring.start = (ring.start + 1) % len(ring.items)
ring.count--
}
}
func (ring *upstreamAttemptRing) Snapshot(cutoff time.Time, limit int) []UpstreamAttempt {
if limit < 1 || ring.count == 0 {
return nil
}
result := make([]UpstreamAttempt, 0, min(ring.count, limit))
for offset := 0; offset < ring.count; offset++ {
value := ring.items[(ring.start+offset)%len(ring.items)]
if !value.Time.Before(cutoff) {
result = append(result, value)
}
}
if len(result) > limit {
result = result[len(result)-limit:]
}
return result
}
// Monitor tracks lightweight lock-free runtime counters with zero lock contention
// on the request hot path.
type Monitor struct {
started time.Time
active atomic.Int64
@@ -246,463 +14,52 @@ type Monitor struct {
total atomic.Uint64
success atomic.Uint64
errors atomic.Uint64
mu sync.Mutex
buckets [60]metricBucket
lifetimeUsage UsagePeriod
sessionSeen map[string]int64
attemptLifetime AttemptAggregate
attemptBuckets [60]attemptBucket
recentRequests upstreamRequestRing
recentAttempts upstreamAttemptRing
attemptsTotal atomic.Uint64
attemptsSuccess atomic.Uint64
attemptsFailed atomic.Uint64
inputTokens atomic.Uint64
outputTokens atomic.Uint64
cachedTokens atomic.Uint64
reasoningTokens atomic.Uint64
}
func NewMonitor() *Monitor {
return &Monitor{
started: time.Now().UTC(),
lifetimeUsage: newUsagePeriod(),
sessionSeen: make(map[string]int64),
attemptLifetime: newAttemptAggregate(),
recentRequests: newUpstreamRequestRing(),
recentAttempts: newUpstreamAttemptRing(),
}
return &Monitor{started: time.Now().UTC()}
}
// BeginStream records a stream entering its response body phase.
func (m *Monitor) BeginStream() { m.activeStreams.Add(1) }
// EndStream releases a stream recorded by BeginStream.
func (m *Monitor) EndStream() { m.activeStreams.Add(-1) }
var latencyBounds = [...]uint64{50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000, 60000}
func (m *Monitor) Record(endpoint string, status int, duration time.Duration, meta *RequestMeta) {
success := requestSucceeded(status, meta)
func (m *Monitor) Record(status int, meta *RequestMeta) {
succeeded := status >= 200 && status < 400 && (meta == nil || meta.Outcome == "")
m.total.Add(1)
if success {
if succeeded {
m.success.Add(1)
} else {
m.errors.Add(1)
}
minute := time.Now().Unix() / 60
m.mu.Lock()
bucket := &m.buckets[minute%60]
if bucket.minute != minute {
bucket.reset(minute)
if meta != nil && meta.UsageReported {
if meta.Usage.Input > 0 {
m.inputTokens.Add(uint64(meta.Usage.Input))
}
if meta.Usage.Output > 0 {
m.outputTokens.Add(uint64(meta.Usage.Output))
}
if meta.Usage.Cached > 0 {
m.cachedTokens.Add(uint64(meta.Usage.Cached))
}
if meta.Usage.Reasoning > 0 {
m.reasoningTokens.Add(uint64(meta.Usage.Reasoning))
}
}
bucket.total++
}
func (m *Monitor) RecordAttempt(success bool) {
m.attemptsTotal.Add(1)
if success {
bucket.success++
m.attemptsSuccess.Add(1)
} else {
bucket.errors++
}
milliseconds := uint64(max(duration.Milliseconds(), 0))
bucket.duration += milliseconds
index := len(latencyBounds)
for i, bound := range latencyBounds {
if milliseconds <= bound {
index = i
break
}
}
bucket.histogram[index]++
bucket.endpoints[endpoint]++
bucket.statuses[fmt.Sprint(status)]++
if meta != nil {
if meta.Model != "" {
bucket.models[meta.Model]++
}
if meta.Tier != "" {
bucket.tiers[meta.Tier]++
bucket.usageRequests++
m.lifetimeUsage.Requests++
if meta.UsageReported {
bucket.usageReported++
m.lifetimeUsage.Reported++
}
tokens := tokenCounts(meta.Usage)
addTokenCounts(&bucket.tokens, tokens)
addTokenCounts(&m.lifetimeUsage.Tokens, tokens)
addTokenMap(bucket.usageModels, meta.Model, tokens)
addTokenMap(bucket.usageTiers, meta.Tier, tokens)
addTokenMap(m.lifetimeUsage.Models, meta.Model, tokens)
addTokenMap(m.lifetimeUsage.Tiers, meta.Tier, tokens)
addTokenMap(bucket.usageSessions, meta.Session, tokens)
m.addLifetimeSessionLocked(meta.Session, tokens)
addServerKeyUsage(bucket.usageKeys, meta.ServerKeyID, ServerKeyUsage{Requests: 1, TokenCounts: tokens})
addServerKeyUsage(m.lifetimeUsage.ServerKeys, meta.ServerKeyID, ServerKeyUsage{Requests: 1, TokenCounts: tokens})
}
if meta.Request != "" && meta.Model != "" {
request := UpstreamRequest{
Time: time.Now().UTC(), RequestID: meta.Request, Session: meta.Session, ServerKeyID: meta.ServerKeyID, Model: meta.Model, Tier: meta.Tier,
KeyID: meta.KeyID, Channel: meta.Channel, Anonymous: meta.Anonymous, Proxy: meta.Proxy,
Attempts: meta.Attempts, Status: status, DurationMS: max(duration.Milliseconds(), 0),
Success: success,
}
if request.Channel == "" {
request.Channel = "not_routed"
}
if request.Anonymous {
request.KeyID = "anonymous"
}
request.Outcome = requestOutcome(status, request.Channel)
if meta.Outcome != "" {
request.Outcome = meta.Outcome
}
m.recentRequests.PruneBefore(request.Time.Add(-time.Hour))
m.recentRequests.Add(request)
}
}
m.mu.Unlock()
}
// A stream can fail after HTTP headers have been sent. Preserve its HTTP
// status while using the terminal result for request success and error counts.
func requestSucceeded(status int, meta *RequestMeta) bool {
return status >= 200 && status < 400 && (meta == nil || meta.Outcome == "")
}
func requestOutcome(status int, channel string) string {
if channel == "" || channel == "not_routed" {
return "not_routed"
}
if status >= 200 && status < 400 {
return "success"
}
if status >= 400 && status < 500 {
return "client_error"
}
if status >= 500 {
return "server_error"
}
return "unknown"
}
func (m *Monitor) RecordAttempt(attempt UpstreamAttempt) {
if attempt.Time.IsZero() {
attempt.Time = time.Now().UTC()
} else {
attempt.Time = attempt.Time.UTC()
}
minute := attempt.Time.Unix() / 60
m.mu.Lock()
recordAttemptAggregate(&m.attemptLifetime, attempt)
bucket := &m.attemptBuckets[minute%60]
if bucket.minute != minute {
*bucket = attemptBucket{minute: minute, aggregate: newAttemptAggregate()}
}
recordAttemptAggregate(&bucket.aggregate, attempt)
m.recentAttempts.PruneBefore(attempt.Time.Add(-time.Hour))
m.recentAttempts.Add(attempt)
m.mu.Unlock()
}
type MonitorSnapshot struct {
StartedAt time.Time `json:"started_at"`
UptimeSeconds int64 `json:"uptime_seconds"`
Active int64 `json:"active_requests"`
ActiveStreams int64 `json:"active_streams"`
Lifetime MetricSummary `json:"lifetime"`
Window MetricSummary `json:"last_hour"`
Series []MetricSeries `json:"series"`
Endpoints map[string]uint64 `json:"endpoints"`
Models map[string]uint64 `json:"models"`
Tiers map[string]uint64 `json:"tiers"`
Statuses map[string]uint64 `json:"statuses"`
Usage UsageSnapshot `json:"usage"`
Upstream UpstreamSnapshot `json:"upstream"`
}
type MetricSummary struct {
Total uint64 `json:"total"`
Success uint64 `json:"success"`
Errors uint64 `json:"errors"`
SuccessRate float64 `json:"success_rate"`
AverageMS float64 `json:"average_ms,omitempty"`
P50MS uint64 `json:"p50_ms,omitempty"`
P95MS uint64 `json:"p95_ms,omitempty"`
P99MS uint64 `json:"p99_ms,omitempty"`
}
type MetricSeries struct {
Minute time.Time `json:"minute"`
Total uint64 `json:"total"`
Success uint64 `json:"success"`
Errors uint64 `json:"errors"`
InputTokens uint64 `json:"input_tokens"`
OutputTokens uint64 `json:"output_tokens"`
CachedTokens uint64 `json:"cached_tokens"`
ReasoningTokens uint64 `json:"reasoning_tokens"`
TotalTokens uint64 `json:"total_tokens"`
UsageReported uint64 `json:"usage_reported"`
}
// ServerKeyUsage returns per-server-key usage for the lifetime and the last
// hour. The API key list polls it, so it skips building a full Snapshot.
func (m *Monitor) ServerKeyUsage() (lifetime, window map[string]ServerKeyUsage) {
nowMinute := time.Now().Unix() / 60
lifetime, window = make(map[string]ServerKeyUsage), make(map[string]ServerKeyUsage)
m.mu.Lock()
defer m.mu.Unlock()
for key, value := range m.lifetimeUsage.ServerKeys {
lifetime[key] = value
}
for offset := int64(0); offset < 60; offset++ {
minute := nowMinute - offset
if bucket := &m.buckets[minute%60]; bucket.minute == minute {
for key, value := range bucket.usageKeys {
addServerKeyUsage(window, key, value)
}
}
}
return lifetime, window
}
func (m *Monitor) Snapshot() MonitorSnapshot {
nowMinute := time.Now().Unix() / 60
window := MetricSummary{}
var histogram [11]uint64
endpoints, models, tiers, statuses := map[string]uint64{}, map[string]uint64{}, map[string]uint64{}, map[string]uint64{}
series := make([]MetricSeries, 0, 60)
usageWindow := newUsagePeriod()
upstreamWindow := newAttemptAggregate()
var recentRequests []UpstreamRequest
var recentAttempts []UpstreamAttempt
m.mu.Lock()
for offset := int64(59); offset >= 0; offset-- {
minute := nowMinute - offset
bucket := &m.buckets[minute%60]
entry := MetricSeries{Minute: time.Unix(minute*60, 0).UTC()}
if bucket.minute == minute {
entry.Total, entry.Success, entry.Errors = bucket.total, bucket.success, bucket.errors
entry.InputTokens, entry.OutputTokens = bucket.tokens.Input, bucket.tokens.Output
entry.CachedTokens, entry.ReasoningTokens, entry.TotalTokens = bucket.tokens.Cached, bucket.tokens.Reasoning, bucket.tokens.Total
entry.UsageReported = bucket.usageReported
window.Total += bucket.total
window.Success += bucket.success
window.Errors += bucket.errors
window.AverageMS += float64(bucket.duration)
for i := range histogram {
histogram[i] += bucket.histogram[i]
}
mergeCounts(endpoints, bucket.endpoints)
mergeCounts(models, bucket.models)
mergeCounts(tiers, bucket.tiers)
mergeCounts(statuses, bucket.statuses)
usageWindow.Requests += bucket.usageRequests
usageWindow.Reported += bucket.usageReported
addTokenCounts(&usageWindow.Tokens, bucket.tokens)
mergeTokenMaps(usageWindow.Models, bucket.usageModels)
mergeTokenMaps(usageWindow.Tiers, bucket.usageTiers)
mergeTokenMaps(usageWindow.Sessions, bucket.usageSessions)
for key, value := range bucket.usageKeys {
addServerKeyUsage(usageWindow.ServerKeys, key, value)
}
}
attemptBucket := &m.attemptBuckets[minute%60]
if attemptBucket.minute == minute {
mergeAttemptAggregate(&upstreamWindow, attemptBucket.aggregate)
}
series = append(series, entry)
}
usageLifetime := cloneUsagePeriod(m.lifetimeUsage)
upstreamLifetime := cloneAttemptAggregate(m.attemptLifetime)
cutoff := time.Now().Add(-time.Hour)
m.recentRequests.PruneBefore(cutoff)
m.recentAttempts.PruneBefore(cutoff)
recentRequests = m.recentRequests.Snapshot(cutoff, monitorRecentOutputLimit)
recentAttempts = m.recentAttempts.Snapshot(cutoff, monitorRecentOutputLimit)
m.mu.Unlock()
finalizeUsagePeriod(&usageLifetime)
finalizeUsagePeriod(&usageWindow)
finalizeAttemptAggregate(&upstreamLifetime)
finalizeAttemptAggregate(&upstreamWindow)
if window.Total > 0 {
window.SuccessRate = float64(window.Success) / float64(window.Total)
window.AverageMS /= float64(window.Total)
window.P50MS = histogramPercentile(histogram, window.Total, 0.50)
window.P95MS = histogramPercentile(histogram, window.Total, 0.95)
window.P99MS = histogramPercentile(histogram, window.Total, 0.99)
}
lifetime := MetricSummary{Total: m.total.Load(), Success: m.success.Load(), Errors: m.errors.Load()}
if lifetime.Total > 0 {
lifetime.SuccessRate = float64(lifetime.Success) / float64(lifetime.Total)
}
return MonitorSnapshot{
StartedAt: m.started, UptimeSeconds: int64(time.Since(m.started).Seconds()), Active: m.active.Load(),
ActiveStreams: m.activeStreams.Load(), Lifetime: lifetime, Window: window, Series: series,
Endpoints: endpoints, Models: models, Tiers: tiers, Statuses: statuses,
Usage: UsageSnapshot{Lifetime: usageLifetime, Window: usageWindow},
Upstream: UpstreamSnapshot{Lifetime: upstreamLifetime, Window: upstreamWindow, Requests: recentRequests, Recent: recentAttempts},
m.attemptsFailed.Add(1)
}
}
func mergeCounts(target, source map[string]uint64) {
for key, value := range source {
target[key] += value
}
}
func newUsagePeriod() UsagePeriod {
return UsagePeriod{Models: make(map[string]TokenCounts), Tiers: make(map[string]TokenCounts), Sessions: make(map[string]TokenCounts), ServerKeys: make(map[string]ServerKeyUsage)}
}
func tokenCounts(usage protocol.Usage) TokenCounts {
return TokenCounts{
Input: uint64(max(usage.Input, 0)), Output: uint64(max(usage.Output, 0)),
Cached: uint64(max(usage.Cached, 0)), Reasoning: uint64(max(usage.Reasoning, 0)), Total: uint64(max(usage.Total, 0)),
}
}
func addTokenCounts(target *TokenCounts, source TokenCounts) {
target.Input += source.Input
target.Output += source.Output
target.Cached += source.Cached
target.Reasoning += source.Reasoning
target.Total += source.Total
}
func addTokenMap(target map[string]TokenCounts, key string, value TokenCounts) {
if key == "" {
return
}
current := target[key]
addTokenCounts(&current, value)
target[key] = current
}
func addServerKeyUsage(target map[string]ServerKeyUsage, key string, value ServerKeyUsage) {
if key == "" {
return
}
current := target[key]
current.Requests += value.Requests
addTokenCounts(&current.TokenCounts, value.TokenCounts)
target[key] = current
}
func mergeTokenMaps(target, source map[string]TokenCounts) {
for key, value := range source {
addTokenMap(target, key, value)
}
}
// maxLifetimeSessions bounds the lifetime per-session burn map. Session IDs
// are high-cardinality (one per conversation), so an unbounded map grows
// forever. When full, the least recently seen session is evicted: evicting the
// smallest total would drop the newest conversation first, so every new
// session would push out the previous one. Buckets and snapshots are
// short-lived and stay uncapped.
const maxLifetimeSessions = 500
func (m *Monitor) addLifetimeSessionLocked(session string, tokens TokenCounts) {
if session == "" {
return
}
if _, ok := m.lifetimeUsage.Sessions[session]; !ok && len(m.lifetimeUsage.Sessions) >= maxLifetimeSessions {
victim, oldest := "", int64(0)
for key, seen := range m.sessionSeen {
if victim == "" || seen < oldest {
victim, oldest = key, seen
}
}
delete(m.lifetimeUsage.Sessions, victim)
delete(m.sessionSeen, victim)
}
m.sessionSeen[session] = time.Now().UnixNano()
addTokenMap(m.lifetimeUsage.Sessions, session, tokens)
}
func cloneUsagePeriod(source UsagePeriod) UsagePeriod {
result := newUsagePeriod()
result.Requests, result.Reported, result.Tokens = source.Requests, source.Reported, source.Tokens
mergeTokenMaps(result.Models, source.Models)
mergeTokenMaps(result.Tiers, source.Tiers)
mergeTokenMaps(result.Sessions, source.Sessions)
for key, value := range source.ServerKeys {
addServerKeyUsage(result.ServerKeys, key, value)
}
return result
}
func finalizeUsagePeriod(period *UsagePeriod) {
if period.Requests > 0 {
period.Coverage = float64(period.Reported) / float64(period.Requests)
}
}
func newAttemptAggregate() AttemptAggregate {
return AttemptAggregate{
Tiers: make(map[string]AttemptCounts), Channels: make(map[string]AttemptCounts), Keys: make(map[string]AttemptCounts),
}
}
func recordAttemptAggregate(target *AttemptAggregate, attempt UpstreamAttempt) {
recordAttemptCounts(&target.AttemptCounts, attempt.Success)
addAttemptMap(target.Tiers, attempt.Tier, attempt.Success)
addAttemptMap(target.Channels, attempt.Channel, attempt.Success)
addAttemptMap(target.Keys, attempt.KeyID, attempt.Success)
}
func recordAttemptCounts(target *AttemptCounts, success bool) {
target.Total++
if success {
target.Success++
} else {
target.Failed++
}
}
func addAttemptMap(target map[string]AttemptCounts, key string, success bool) {
if key == "" {
return
}
current := target[key]
recordAttemptCounts(&current, success)
target[key] = current
}
func mergeAttemptAggregate(target *AttemptAggregate, source AttemptAggregate) {
target.Total += source.Total
target.Success += source.Success
target.Failed += source.Failed
mergeAttemptMaps(target.Tiers, source.Tiers)
mergeAttemptMaps(target.Channels, source.Channels)
mergeAttemptMaps(target.Keys, source.Keys)
}
func mergeAttemptMaps(target, source map[string]AttemptCounts) {
for key, value := range source {
current := target[key]
current.Total += value.Total
current.Success += value.Success
current.Failed += value.Failed
target[key] = current
}
}
func cloneAttemptAggregate(source AttemptAggregate) AttemptAggregate {
result := newAttemptAggregate()
mergeAttemptAggregate(&result, source)
return result
}
func finalizeAttemptAggregate(aggregate *AttemptAggregate) {
if aggregate.Total > 0 {
aggregate.SuccessRate = float64(aggregate.Success) / float64(aggregate.Total)
}
}
func histogramPercentile(histogram [11]uint64, total uint64, percentile float64) uint64 {
target := uint64(float64(total)*percentile + 0.999)
var count uint64
for i, value := range histogram {
count += value
if count >= target {
if i < len(latencyBounds) {
return latencyBounds[i]
}
return latencyBounds[len(latencyBounds)-1] + 1
}
}
return 0
}
-289
View File
@@ -1,289 +0,0 @@
/* Reset, typography, focus, skip link and the two-column application shell. */
* {
box-sizing: border-box;
}
html {
-webkit-text-size-adjust: 100%;
}
body {
margin: 0;
background: var(--bg);
color: var(--text-1);
font: var(--fs-base) / var(--lh-base) var(--font-sans);
-webkit-font-smoothing: antialiased;
}
h1,
h2,
h3,
h4,
p,
ul,
ol,
dl,
dd,
figure {
margin: 0;
}
button,
input,
select,
textarea {
font: inherit;
color: inherit;
}
button {
cursor: pointer;
}
a {
color: inherit;
}
code,
pre {
font-family: var(--font-mono);
}
.hidden {
display: none !important;
}
.mono {
font-family: var(--font-mono);
}
:focus-visible {
outline: 2px solid var(--text-1);
outline-offset: 2px;
}
.skip-link {
position: fixed;
top: -80px;
left: var(--sp-4);
z-index: 100;
padding: var(--sp-2) var(--sp-4);
background: var(--surface);
border: 1px solid var(--border-2);
border-radius: var(--r-md);
}
.skip-link:focus {
top: var(--sp-4);
}
.app {
display: grid;
grid-template-columns: var(--sidebar-w) minmax(0, 1fr);
min-height: 100vh;
}
.sidebar {
position: sticky;
top: 0;
height: 100vh;
display: flex;
flex-direction: column;
gap: var(--sp-5);
padding: var(--sp-5) var(--sp-3);
border-right: 1px solid var(--border-1);
background: var(--bg);
overflow-y: auto;
}
.brand {
display: flex;
align-items: center;
gap: var(--sp-2);
padding: 0 var(--sp-2);
}
.brand-name {
font-size: var(--fs-base);
font-weight: 600;
letter-spacing: -0.01em;
}
.nav {
display: grid;
gap: var(--sp-5);
min-width: 0;
}
.nav-group {
display: grid;
gap: 2px;
}
.nav-group-title {
padding: 0 var(--sp-2) var(--sp-1);
font-size: var(--fs-xs);
color: var(--text-3);
}
.nav-item {
display: block;
width: 100%;
padding: 7px var(--sp-2);
border: 0;
border-radius: var(--r-md);
background: transparent;
color: var(--text-2);
text-align: left;
font-size: var(--fs-base);
}
.nav-item:hover {
color: var(--text-1);
background: var(--bg-subtle);
}
.nav-item.active {
color: var(--text-1);
background: var(--bg-subtle);
font-weight: 500;
}
.sidebar-foot {
margin-top: auto;
padding: var(--sp-3) var(--sp-2) 0;
border-top: 1px solid var(--border-1);
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-3);
}
.sidebar-foot a {
text-decoration: none;
}
.sidebar-foot a:hover {
color: var(--text-1);
text-decoration: underline;
}
.content {
display: flex;
flex-direction: column;
min-width: 0;
}
.topbar {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: var(--sp-4);
width: 100%;
max-width: var(--content-max);
margin-inline: auto;
padding: var(--sp-6) var(--sp-8) var(--sp-4);
border-bottom: 1px solid var(--border-1);
}
.page-title {
font-size: var(--fs-2xl);
font-weight: 600;
letter-spacing: -0.02em;
line-height: 1.2;
}
.page-sub {
margin-top: var(--sp-1);
max-width: 640px;
font-size: var(--fs-sm);
color: var(--text-2);
}
.topbar-actions {
display: flex;
flex-shrink: 0;
gap: var(--sp-2);
}
main {
width: 100%;
max-width: var(--content-max);
margin-inline: auto;
padding: var(--sp-6) var(--sp-8) var(--sp-12);
}
@media (max-width: 980px) {
.app {
grid-template-columns: minmax(0, 1fr);
}
.sidebar {
position: static;
height: auto;
gap: var(--sp-3);
padding: var(--sp-3) var(--sp-4);
border-right: 0;
border-bottom: 1px solid var(--border-1);
overflow: visible;
}
.nav {
display: flex;
gap: var(--sp-4);
overflow-x: auto;
padding-bottom: var(--sp-1);
}
.nav-group {
display: flex;
align-items: center;
gap: 2px;
}
.nav-group-title {
display: none;
}
.nav-item {
width: auto;
white-space: nowrap;
}
.sidebar-foot {
display: none;
}
.topbar {
flex-direction: column;
align-items: stretch;
padding: var(--sp-5) var(--sp-4) var(--sp-3);
}
.topbar-actions {
justify-content: flex-end;
}
main {
padding: var(--sp-5) var(--sp-4) var(--sp-10);
}
}
@media (max-width: 680px) {
main {
padding-inline: var(--sp-3);
}
.topbar {
padding-inline: var(--sp-3);
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
-543
View File
@@ -1,543 +0,0 @@
/* Buttons, forms, sections, tables, status, chips, dialogs and shared primitives. */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
height: 36px;
padding: 0 14px;
border: 1px solid var(--border-2);
border-radius: var(--r-md);
background: var(--surface);
color: var(--text-1);
font-size: var(--fs-base);
font-weight: 500;
white-space: nowrap;
}
.btn:hover:not(:disabled) {
background: var(--bg-subtle);
}
.btn:disabled {
opacity: 0.5;
cursor: default;
}
.btn-primary {
border-color: var(--inverse-bg);
background: var(--inverse-bg);
color: var(--inverse-text);
}
.btn-primary:hover:not(:disabled) {
border-color: var(--inverse-hover);
background: var(--inverse-hover);
}
.btn-danger {
border-color: var(--border-2);
color: var(--bad);
}
.btn-danger:hover:not(:disabled) {
border-color: var(--bad);
background: var(--bad-bg);
}
.btn-ghost {
border-color: transparent;
background: transparent;
color: var(--text-2);
}
.btn-ghost:hover:not(:disabled) {
background: var(--bg-subtle);
color: var(--text-1);
}
.btn-sm {
height: 30px;
padding: 0 10px;
font-size: var(--fs-sm);
}
.btn-block {
width: 100%;
margin-top: var(--sp-2);
}
.lang-switch {
width: auto;
height: 30px;
padding: 0 8px;
border-color: transparent;
background: transparent;
appearance: none;
font-size: 16px;
line-height: 1;
text-align: center;
cursor: pointer;
}
.lang-switch:hover {
background: var(--bg-subtle);
}
.login-lang {
display: flex;
justify-content: flex-end;
margin-bottom: var(--sp-2);
}
.field {
display: grid;
gap: var(--sp-2);
margin: var(--sp-4) 0;
}
.field > label {
font-size: var(--fs-sm);
font-weight: 500;
color: var(--text-2);
}
input,
select,
textarea {
width: 100%;
min-width: 0;
padding: 8px 10px;
border: 1px solid var(--border-2);
border-radius: var(--r-md);
background: var(--surface);
outline: none;
}
input:focus,
select:focus,
textarea:focus {
border-color: var(--text-1);
box-shadow: 0 0 0 3px var(--focus-ring);
}
input:focus-visible,
select:focus-visible,
textarea:focus-visible {
outline: none;
}
textarea {
min-height: 92px;
resize: vertical;
font-family: var(--font-mono);
font-size: var(--fs-sm);
line-height: 1.55;
}
.check {
display: flex;
align-items: center;
gap: var(--sp-2);
cursor: pointer;
}
.check input {
width: auto;
flex-shrink: 0;
accent-color: var(--inverse-bg);
}
.form-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
column-gap: var(--sp-5);
}
.form-grid .full {
grid-column: 1 / -1;
}
.form-error {
min-height: 20px;
margin-top: var(--sp-2);
font-size: var(--fs-sm);
color: var(--bad);
}
.section {
padding: var(--sp-5);
border: 1px solid var(--border-1);
border-radius: var(--r-lg);
background: var(--surface);
}
.section-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: var(--sp-4);
margin-bottom: var(--sp-4);
}
.section-title {
font-size: var(--fs-lg);
font-weight: 600;
letter-spacing: -0.01em;
}
.section-caption {
margin-top: 2px;
font-size: var(--fs-sm);
color: var(--text-2);
}
.table-wrap {
overflow-x: auto;
}
.table {
width: 100%;
border-collapse: collapse;
font-size: var(--fs-sm);
}
.table th,
.table td {
padding: 8px 10px;
text-align: left;
vertical-align: baseline;
border-bottom: 1px solid var(--border-1);
overflow-wrap: anywhere;
}
.table th {
padding-block: 6px;
font-size: var(--fs-xs);
font-weight: 500;
color: var(--text-3);
}
.table tr:last-child td {
border-bottom: 0;
}
.table tbody tr:hover {
background: var(--bg-subtle);
}
.num {
text-align: right;
font-variant-numeric: tabular-nums;
}
.status {
display: inline-flex;
align-items: center;
gap: 6px;
}
.status::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
flex-shrink: 0;
}
.ok {
color: var(--ok);
}
.warn {
color: var(--warn);
}
.bad {
color: var(--bad);
}
.chips {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2);
margin: var(--sp-2) 0;
}
.chip {
display: inline-flex;
align-items: center;
gap: var(--sp-2);
padding: 3px 8px;
border: 1px solid var(--border-1);
border-radius: var(--r-sm);
background: var(--bg-subtle);
font-family: var(--font-mono);
font-size: var(--fs-xs);
}
.chip button {
padding: 0;
border: 0;
border-radius: 2px;
background: transparent;
color: var(--text-3);
font-size: var(--fs-base);
line-height: 1;
}
.chip button:hover {
color: var(--bad);
}
.code-card {
margin: var(--sp-3) 0;
border: 1px solid var(--border-1);
border-radius: var(--r-md);
background: var(--surface-2);
overflow: hidden;
}
.code-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-2);
padding: var(--sp-2) var(--sp-3);
border-bottom: 1px solid var(--border-1);
font-family: var(--font-mono);
font-size: var(--fs-xs);
color: var(--text-3);
}
.code-card pre {
margin: 0;
padding: var(--sp-3);
overflow-x: auto;
font-size: var(--fs-xs);
line-height: 1.6;
}
.notice {
padding: var(--sp-3) var(--sp-4);
border: 1px solid var(--warn);
border-radius: var(--r-md);
background: var(--warn-bg);
font-size: var(--fs-sm);
}
.toast {
position: fixed;
right: var(--sp-5);
bottom: var(--sp-5);
z-index: 60;
max-width: 360px;
padding: var(--sp-3) var(--sp-4);
border: 1px solid var(--border-2);
border-radius: var(--r-md);
background: var(--surface);
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.14);
font-size: var(--fs-sm);
}
.toast.bad-toast {
border-color: var(--bad);
}
.dialog-overlay {
position: fixed;
inset: 0;
z-index: 70;
display: grid;
place-items: center;
padding: var(--sp-4);
background: var(--overlay);
}
.dialog {
width: min(440px, 100%);
max-height: 84vh;
overflow: auto;
padding: var(--sp-5);
border: 1px solid var(--border-2);
border-radius: var(--r-lg);
background: var(--surface);
}
.dialog-lg {
width: min(720px, 100%);
}
.dialog-title {
font-size: var(--fs-lg);
font-weight: 600;
}
.dialog-text {
margin-top: var(--sp-2);
font-size: var(--fs-sm);
color: var(--text-2);
overflow-wrap: anywhere;
}
.dialog .field {
margin: var(--sp-3) 0 0;
}
.dialog pre {
margin: var(--sp-3) 0 0;
padding: var(--sp-3);
max-height: 50vh;
overflow: auto;
border: 1px solid var(--border-1);
border-radius: var(--r-md);
background: var(--surface-2);
font-size: var(--fs-xs);
line-height: 1.6;
}
.dialog-actions {
display: flex;
justify-content: flex-end;
gap: var(--sp-2);
margin-top: var(--sp-5);
}
.facts {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--sp-4) var(--sp-5);
}
.fact {
display: grid;
gap: 3px;
min-width: 0;
}
.fact-label {
font-size: var(--fs-xs);
color: var(--text-3);
}
.fact-value {
font-size: var(--fs-sm);
overflow-wrap: anywhere;
}
.empty {
padding: var(--sp-4) var(--sp-2);
color: var(--text-3);
font-size: var(--fs-sm);
}
.actions {
display: flex;
justify-content: flex-end;
gap: var(--sp-2);
margin-top: var(--sp-4);
}
.key-actions {
display: flex;
flex-wrap: wrap;
gap: var(--sp-1);
}
.filters {
display: grid;
grid-template-columns: 140px 160px minmax(180px, 1fr) auto;
gap: var(--sp-2);
margin-bottom: var(--sp-4);
}
progress {
width: 100%;
height: 8px;
border: 0;
border-radius: 999px;
background: var(--bg-subtle);
overflow: hidden;
appearance: none;
}
progress::-webkit-progress-bar {
background: var(--bg-subtle);
}
progress::-webkit-progress-value {
border-radius: 999px;
background: var(--inverse-bg);
}
progress::-moz-progress-bar {
border-radius: 999px;
background: var(--inverse-bg);
}
@media (max-width: 680px) {
.form-grid {
grid-template-columns: 1fr;
}
.form-grid .full {
grid-column: auto;
}
.filters {
grid-template-columns: 1fr 1fr;
}
.section-head {
flex-direction: column;
}
.dialog-actions {
flex-direction: column-reverse;
}
.dialog-actions .btn {
width: 100%;
}
}
.tabs {
display: flex;
gap: var(--sp-1);
border-bottom: 1px solid var(--border-1);
overflow-x: auto;
}
.tab {
padding: 7px var(--sp-3) 9px;
margin-bottom: -1px;
border: 0;
border-bottom: 2px solid transparent;
background: transparent;
color: var(--text-2);
font-size: var(--fs-base);
white-space: nowrap;
}
.tab:hover {
color: var(--text-1);
}
.tab.active {
color: var(--text-1);
border-bottom-color: var(--text-1);
font-weight: 500;
}
.sticky-actions {
position: sticky;
bottom: 0;
z-index: 5;
display: flex;
justify-content: flex-end;
gap: var(--sp-2);
margin-top: var(--sp-4);
padding: var(--sp-3) 0;
border-top: 1px solid var(--border-1);
background: var(--bg);
}
-379
View File
@@ -1,379 +0,0 @@
/* Page layouts: login, dashboards, charts, logs, playground and rotation. */
.login-view {
min-height: 100vh;
display: grid;
place-items: center;
padding: var(--sp-6);
}
.login-card {
width: min(380px, 100%);
padding: var(--sp-8);
border: 1px solid var(--border-1);
border-radius: var(--r-lg);
background: var(--surface);
}
.login-name {
margin-bottom: var(--sp-6);
font-size: var(--fs-2xl);
font-weight: 600;
letter-spacing: -0.02em;
}
.page {
display: grid;
gap: var(--sp-5);
align-content: start;
}
.split {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--sp-5);
align-items: start;
}
.stack {
display: grid;
gap: var(--sp-5);
align-content: start;
}
.metrics {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 1px;
border: 1px solid var(--border-1);
border-radius: var(--r-lg);
background: var(--border-1);
overflow: hidden;
}
.metric {
display: grid;
gap: var(--sp-1);
align-content: start;
padding: var(--sp-4) var(--sp-5);
background: var(--surface);
}
.metric-label {
font-size: var(--fs-sm);
color: var(--text-2);
}
.metric-value {
margin-top: var(--sp-1);
font-size: var(--fs-3xl);
font-weight: 600;
font-variant-numeric: tabular-nums;
letter-spacing: -0.02em;
line-height: 1.15;
}
.metric-note {
font-size: var(--fs-xs);
color: var(--text-3);
}
.breakdown {
display: grid;
gap: var(--sp-2);
align-content: start;
}
.breakdown h3 {
font-size: var(--fs-sm);
font-weight: 500;
color: var(--text-2);
}
.guide {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 1px;
border: 1px solid var(--border-1);
border-radius: var(--r-lg);
background: var(--border-1);
overflow: hidden;
}
.guide-step {
display: grid;
gap: var(--sp-2);
align-content: start;
min-height: 140px;
padding: var(--sp-5);
background: var(--surface);
}
.guide-step h3 {
font-size: var(--fs-base);
font-weight: 600;
}
.guide-step p {
font-size: var(--fs-sm);
color: var(--text-2);
}
.step-state {
margin-top: auto;
font-size: var(--fs-xs);
}
.trend {
display: flex;
align-items: flex-end;
gap: 2px;
height: 200px;
padding-top: var(--sp-4);
border-bottom: 1px solid var(--border-2);
}
.trend-bar {
flex: 1;
min-width: 2px;
border-radius: 2px 2px 0 0;
background: var(--text-3);
}
.trend-bar:hover {
background: var(--text-1);
}
.trend-meta {
display: flex;
justify-content: space-between;
gap: var(--sp-3);
margin-top: var(--sp-2);
font-size: var(--fs-xs);
color: var(--text-3);
}
.tier-row {
display: grid;
grid-template-columns: 64px minmax(0, 1fr) 88px;
align-items: center;
gap: var(--sp-3);
padding: var(--sp-2) 0;
font-size: var(--fs-sm);
}
.tier-track {
height: 8px;
border-radius: 999px;
background: var(--bg-subtle);
overflow: hidden;
}
.tier-fill {
height: 100%;
border-radius: 999px;
background: var(--inverse-bg);
}
.tier-value {
text-align: right;
font-variant-numeric: tabular-nums;
color: var(--text-2);
}
.quota-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: var(--sp-4);
}
.quota-card {
display: grid;
gap: var(--sp-2);
padding: var(--sp-4);
border: 1px solid var(--border-1);
border-radius: var(--r-md);
}
.quota-card h3 {
font-size: var(--fs-sm);
font-weight: 500;
color: var(--text-2);
}
.quota-value {
font-size: var(--fs-2xl);
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.quota-reset {
font-size: var(--fs-xs);
color: var(--text-3);
}
.quota-low progress::-webkit-progress-value {
background: var(--warn);
}
.quota-low progress::-moz-progress-bar {
background: var(--warn);
}
.quota-status {
margin: var(--sp-4) 0;
padding: var(--sp-3) var(--sp-4);
border: 1px solid var(--border-1);
border-radius: var(--r-md);
background: var(--surface-2);
font-size: var(--fs-sm);
color: var(--text-2);
}
.logs {
height: 62vh;
overflow: auto;
border: 1px solid var(--border-1);
border-radius: var(--r-md);
background: var(--surface-2);
font-family: var(--font-mono);
font-size: var(--fs-xs);
}
.log {
display: grid;
grid-template-columns: 84px 54px 110px minmax(180px, 1fr);
gap: var(--sp-3);
padding: 6px var(--sp-3);
border-bottom: 1px solid var(--border-1);
}
.log:hover {
background: var(--bg-subtle);
}
.log-time,
.log-fields {
color: var(--text-3);
}
.log-fields {
grid-column: 4;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.play-layout {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
gap: var(--sp-5);
align-items: start;
}
.json-editor {
min-height: 420px;
font-family: var(--font-mono);
font-size: var(--fs-xs);
line-height: 1.6;
background: var(--surface-2);
}
.key-env {
margin: var(--sp-3) 0;
padding: var(--sp-4);
border: 1px solid var(--border-1);
border-radius: var(--r-md);
background: var(--surface-2);
font-size: var(--fs-xs);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
#api-key-created {
border-color: var(--ok);
}
#account-form {
max-width: 660px;
}
.head-search {
max-width: 240px;
margin-left: auto;
}
.rotation-group .field {
max-width: 360px;
}
.rotation-current {
margin-top: var(--sp-2);
font-size: var(--fs-sm);
color: var(--text-2);
}
.rotation-actions {
display: flex;
flex-wrap: wrap;
gap: var(--sp-1);
}
.rotation-switches {
display: grid;
gap: var(--sp-1);
margin-top: var(--sp-4);
font-size: var(--fs-sm);
color: var(--text-2);
}
.rotation-switches h3 {
font-size: var(--fs-sm);
font-weight: 500;
color: var(--text-3);
}
#rotation-attempts td {
max-width: 280px;
overflow-wrap: anywhere;
}
@media (max-width: 980px) {
.metrics {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.split,
.play-layout {
grid-template-columns: 1fr;
}
}
@media (max-width: 680px) {
.metrics,
.guide,
.quota-grid,
.facts {
grid-template-columns: 1fr;
}
.json-editor {
min-height: 300px;
}
.head-search {
max-width: none;
width: 100%;
margin-left: 0;
}
.log {
grid-template-columns: 72px 48px minmax(0, 1fr);
}
.log-component {
display: none;
}
.log-fields {
grid-column: 1 / -1;
}
}
-84
View File
@@ -1,84 +0,0 @@
/* Design tokens: monochrome scale, semantic status colors, type and spacing. */
:root {
color-scheme: light;
--bg: #fafafa;
--bg-subtle: #f1f1f1;
--surface: #ffffff;
--surface-2: #fafafa;
--text-1: #0a0a0a;
--text-2: #5e5e5e;
--text-3: #8f8f8f;
--border-1: #e6e6e6;
--border-2: #d4d4d4;
--inverse-bg: #0a0a0a;
--inverse-text: #ffffff;
--inverse-hover: #333333;
--focus-ring: rgba(10, 10, 10, 0.14);
--overlay: rgba(0, 0, 0, 0.45);
--ok: #1a7f37;
--warn: #9a6700;
--warn-bg: #fff8c5;
--bad: #cf222e;
--bad-bg: #ffebe9;
--font-sans:
system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans",
"PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
--font-mono:
ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace;
--fs-xs: 12px;
--fs-sm: 13px;
--fs-base: 14px;
--fs-lg: 16px;
--fs-2xl: 24px;
--fs-3xl: 30px;
--lh-base: 1.6;
--sp-1: 4px;
--sp-2: 8px;
--sp-3: 12px;
--sp-4: 16px;
--sp-5: 20px;
--sp-6: 24px;
--sp-8: 32px;
--sp-10: 40px;
--sp-12: 48px;
--r-sm: 4px;
--r-md: 6px;
--r-lg: 10px;
--sidebar-w: 232px;
--content-max: 1280px;
}
@media (prefers-color-scheme: dark) {
:root {
color-scheme: dark;
--bg: #0a0a0a;
--bg-subtle: #171717;
--surface: #121212;
--surface-2: #0d0d0d;
--text-1: #ededed;
--text-2: #a0a0a0;
--text-3: #787878;
--border-1: #262626;
--border-2: #3a3a3a;
--inverse-bg: #ededed;
--inverse-text: #0a0a0a;
--inverse-hover: #cfcfcf;
--focus-ring: rgba(237, 237, 237, 0.18);
--overlay: rgba(0, 0, 0, 0.6);
--ok: #3fb950;
--warn: #d29922;
--warn-bg: rgba(210, 153, 34, 0.15);
--bad: #f85149;
--bad-bg: rgba(248, 81, 73, 0.15);
}
}
-11
View File
@@ -1,11 +0,0 @@
// Package webui embeds the static management interface.
package webui
import (
"embed"
)
// Assets contains the static management interface served by the admin listener.
//
//go:embed index.html css js
var Assets embed.FS
-1091
View File
File diff suppressed because it is too large. Load diff
-51
View File
@@ -1,51 +0,0 @@
// fetch wrapper: JSON handling, CSRF for writes, 401 routed to the login view.
import * as store from "./store.js";
import { t } from "./i18n.js";
let csrf = "";
let onUnauthorized = null;
export function setCsrf(value) {
csrf = value || "";
}
export function clearCsrf() {
csrf = "";
}
export function hasSession() {
return csrf !== "";
}
export function setUnauthorizedHandler(handler) {
onUnauthorized = handler;
}
export async function api(path, options = {}) {
const headers = { ...(options.headers || {}), Accept: "application/json" };
if (options.body) headers["Content-Type"] = "application/json";
if (csrf && !["GET", "HEAD"].includes((options.method || "GET").toUpperCase()))
headers["X-CSRF-Token"] = csrf;
const response = await fetch(path, { ...options, headers });
if (response.status === 204) return null;
const data = await response.json().catch(() => ({}));
if (!response.ok) {
// The login endpoint answers 401 for bad credentials: surface its message
// instead of treating the attempt as an expired session.
if (response.status === 401 && path !== "/api/auth/login") {
if (onUnauthorized) onUnauthorized();
throw new Error(t("登录已失效", "error.session"));
}
throw new Error(data.error?.message || `HTTP ${response.status}`);
}
return data;
}
// Client-facing API base derived from the configured listen address.
export function derivedAPIBase() {
const config = store.get("config");
const listen = config?.effective?.listen || config?.listen || ":8080";
const match = listen.match(/^\[.*\]:(\d+)$/) || listen.match(/:(\d+)$/);
const port = match?.[1] || "8080";
return `${location.protocol}//${location.hostname}:${port}`;
}
-26
View File
@@ -1,26 +0,0 @@
// Shared API loaders that populate the console store.
import { api } from "./api.js";
import * as store from "./store.js";
import { toast } from "./ui.js";
export async function refreshMonitor() {
try {
store.set("monitor", await api("/api/monitor"));
} catch {
// The 3s poll stays silent; transient failures surface in the log stream.
}
}
export async function loadConfig() {
store.set("config", await api("/api/config"));
}
export async function loadDebugModels() {
try {
const data = await api("/api/debug/models");
if (data.last_inference) store.set("lastPlayground", data.last_inference);
store.set("debug", data);
} catch (error) {
toast(error.message, true);
}
}
-1248
View File
File diff suppressed because it is too large. Load diff
-94
View File
@@ -1,94 +0,0 @@
// Live log stream: SSE connection, bounded buffer and rendering. The
// connection lifecycle is owned by the console shell.
import { $, el, timeOnly, toast } from "./ui.js";
import { t } from "./i18n.js";
let events = [];
let source = null;
let paused = false;
let visible = false;
let renderPending = false;
function render() {
const level = $("#log-level").value;
const component = $("#log-component").value.toLowerCase();
const query = $("#log-search").value.toLowerCase();
const rows = events
.filter(
(item) =>
(!level || item.level === level) &&
(!component || (item.component || "").toLowerCase().includes(component)) &&
(!query || JSON.stringify(item).toLowerCase().includes(query)),
)
.slice(-500);
const host = $("#log-list");
host.replaceChildren();
rows.forEach((item) => {
const levelClass =
item.level === "error" ? "bad" : item.level === "warn" ? "warn" : item.level === "info" ? "ok" : "";
host.append(
el("div", { class: "log" }, [
el("span", { class: "log-time", text: timeOnly(item.time) }),
el("span", { class: levelClass, text: item.level }),
el("span", { class: "log-component", text: item.component || "core" }),
el("span", { class: "log-message", text: item.message }),
el("span", { class: "log-fields", text: JSON.stringify(item.fields || {}) }),
]),
);
});
if (!rows.length) host.append(el("div", { class: "empty", text: t("等待日志事件…", "logs.waiting") }));
host.scrollTop = host.scrollHeight;
}
export function connect() {
disconnect();
// The server replays its recent ring on every subscribe; start from a clean
// buffer so a re-login does not duplicate the previous session's events.
events = [];
source = new EventSource("/api/logs/stream");
source.addEventListener("log", (event) => {
events.push(JSON.parse(event.data));
if (events.length > 2000) events.shift();
if (!paused && visible && !renderPending) {
renderPending = true;
requestAnimationFrame(() => {
renderPending = false;
render();
});
}
});
source.addEventListener("gap", () => toast(t("较早日志已从内存清除", "logs.gap"), true));
}
export function disconnect() {
if (source) source.close();
source = null;
}
// The stream tab reports its visibility so hidden panels skip rendering while
// the buffer keeps filling.
export function setVisible(value) {
visible = value;
if (visible) render();
}
export function bind() {
["#log-level", "#log-component", "#log-search"].forEach((selector) =>
$(selector).addEventListener("input", render),
);
$("#log-pause").addEventListener("click", () => {
paused = !paused;
syncPauseButton();
if (!paused) render();
});
}
// The button carries the opposite action of the current state, so it is
// rebuilt on every language switch.
export function syncPauseButton() {
$("#log-pause").textContent = paused
? t("继续", "logs.resume")
: t("暂停", "logs.pause");
}
export { render };
-136
View File
@@ -1,136 +0,0 @@
// Console shell: boot, login, navigation and shared data loading.
import { api, setCsrf, clearCsrf, setUnauthorizedHandler } from "./api.js";
import { refreshMonitor, loadConfig, loadDebugModels } from "./data.js";
import * as i18n from "./i18n.js";
import * as store from "./store.js";
import { $, $$, toast } from "./ui.js";
import * as logstream from "./logstream.js";
import overview from "./pages/overview.js";
import diagnostics from "./pages/diagnostics.js";
import access from "./pages/access.js";
import apiKeys from "./pages/api-keys.js";
import quotas from "./pages/model-quotas.js";
import rotation from "./pages/rotation.js";
import configPage from "./pages/config.js";
import account from "./pages/account.js";
const PAGES = [overview, diagnostics, access, apiKeys, quotas, rotation, configPage, account];
const byId = new Map(PAGES.map((page) => [page.id, page]));
// Hrefs from the previous 13-page layout keep working.
const HASH_ALIASES = {
guide: "overview",
usage: "overview",
playground: "diagnostics",
logs: "diagnostics",
availability: "model-quotas",
};
let current = null;
let monitorTimer = null;
function renderPageHeader(page) {
if (!page) return;
$("#page-title").textContent = i18n.t(page.title, `page.${page.id}.title`);
$("#page-sub").textContent = i18n.t(page.sub, `page.${page.id}.sub`);
}
function openPage(id) {
const page = byId.get(id);
if (!page) return;
current?.hide?.();
history.replaceState(null, "", `#${id}`);
$$(".nav-item").forEach((button) =>
button.classList.toggle("active", button.dataset.page === id),
);
$$(".page").forEach((node) => node.classList.toggle("hidden", node.id !== `page-${id}`));
renderPageHeader(page);
current = page;
page.show?.();
}
function showLogin() {
clearCsrf();
current?.hide?.();
current = null;
$("#app").classList.add("hidden");
$("#login").classList.remove("hidden");
clearInterval(monitorTimer);
monitorTimer = null;
logstream.disconnect();
for (const page of PAGES) page.reset?.();
}
async function enterConsole(session) {
setCsrf(session.csrf_token);
$("#login").classList.add("hidden");
$("#app").classList.remove("hidden");
await loadConfig();
await Promise.all([refreshMonitor(), loadDebugModels()]);
clearInterval(monitorTimer);
monitorTimer = setInterval(refreshMonitor, 3000);
logstream.connect();
const hash = location.hash.slice(1);
const id = byId.has(hash) ? hash : HASH_ALIASES[hash];
openPage(id && byId.has(id) ? id : "overview");
}
async function boot() {
try {
await enterConsole(await api("/api/auth/session"));
} catch {
showLogin();
}
}
setUnauthorizedHandler(showLogin);
store.on("monitor", (data) => {
const version = String(data.version || "");
$("#version").textContent = version.startsWith("v") || version === "dev" ? version : `v${version}`;
});
for (const page of PAGES) page.init?.();
$$(".nav-item").forEach((button) => {
button.addEventListener("click", () => openPage(button.dataset.page));
});
$("#refresh-now").addEventListener("click", async () => {
await Promise.all([refreshMonitor(), loadConfig(), loadDebugModels()]);
await current?.refresh?.();
toast(i18n.t("状态已刷新", "toast.refreshed"));
});
$("#logout").addEventListener("click", async () => {
try {
await api("/api/auth/logout", { method: "POST", body: "{}" });
} finally {
showLogin();
}
});
$("#login-form").addEventListener("submit", async (event) => {
event.preventDefault();
$("#login-error").textContent = "";
try {
const session = await api("/api/auth/login", {
method: "POST",
body: JSON.stringify({ username: $("#login-user").value, password: $("#login-pass").value }),
});
$("#login-pass").value = "";
await enterConsole(session);
} catch (error) {
$("#login-error").textContent = error.message;
}
});
i18n.onChange(() => {
renderPageHeader(current);
logstream.syncPauseButton();
logstream.render();
});
i18n.init();
boot();
-49
View File
@@ -1,49 +0,0 @@
// Page: 接入手册 — derived API base, protocol and SDK examples with copy buttons.
import { derivedAPIBase } from "../api.js";
import * as store from "../store.js";
import { $, el, copyText } from "../ui.js";
import { t, onChange } from "../i18n.js";
function codeCard(label, text) {
const copy = el("button", { type: "button", class: "btn btn-sm btn-ghost", text: t("复制", "common.copy") });
copy.addEventListener("click", () => copyText(text, t("示例已复制", "toast.example.copied")));
return el("div", { class: "code-card" }, [
el("div", { class: "code-head" }, [el("span", { text: label }), copy]),
el("pre", {}, [el("code", { text })]),
]);
}
function render() {
const config = store.get("config");
if (!config) return;
const base = derivedAPIBase();
const model = $("#access-model")?.value.trim() || "YOUR_MODEL";
$("#access-base-value").value = base;
const protocols = $("#access-protocol-examples");
const sdks = $("#access-sdk-examples");
protocols.replaceChildren();
sdks.replaceChildren();
const chat = `curl ${base}/v1/chat/completions \\\n -H "Authorization: Bearer YOUR_API_KEY" \\\n -H "Content-Type: application/json" \\\n -d '{"model":"${model}","messages":[{"role":"user","content":"Hello"}]}'`;
const responses = `curl ${base}/v1/responses \\\n -H "Authorization: Bearer YOUR_API_KEY" \\\n -H "Content-Type: application/json" \\\n -d '{"model":"${model}","input":"Hello"}'`;
const anthropic = `curl ${base}/v1/messages \\\n -H "x-api-key: YOUR_API_KEY" \\\n -H "anthropic-version: 2023-06-01" \\\n -H "Content-Type: application/json" \\\n -d '{"model":"${model}","max_tokens":512,"messages":[{"role":"user","content":"Hello"}]}'`;
protocols.append(
codeCard("Chat Completions", chat),
codeCard("Responses", responses),
codeCard("Anthropic Messages", anthropic),
);
const python = `from openai import OpenAI\n\nclient = OpenAI(base_url="${base}/v1", api_key="YOUR_API_KEY")\nresponse = client.chat.completions.create(\n model="${model}",\n messages=[{"role": "user", "content": "Hello"}],\n)\nprint(response.choices[0].message.content)`;
const javascript = `import OpenAI from "openai";\n\nconst client = new OpenAI({\n baseURL: "${base}/v1",\n apiKey: "YOUR_API_KEY",\n});\nconst response = await client.responses.create({\n model: "${model}",\n input: "Hello",\n});\nconsole.log(response.output_text);`;
sdks.append(codeCard("Python · OpenAI SDK", python), codeCard("JavaScript · OpenAI SDK", javascript));
}
export default {
id: "access",
title: "接入手册",
sub: "Chat、Responses、Anthropic 与 SDK 示例。",
init() {
store.on("config", render);
$("#access-model").addEventListener("input", render);
onChange(render);
},
show: render,
};
-29
View File
@@ -1,29 +0,0 @@
// Page: 账号安全 — update admin credentials; all sessions are revoked afterwards.
import { api } from "../api.js";
import { t } from "../i18n.js";
import { $, toast } from "../ui.js";
export default {
id: "account",
title: "账号安全",
sub: "更新账号后撤销全部管理会话。",
init() {
$("#account-form").addEventListener("submit", async (event) => {
event.preventDefault();
try {
await api("/api/account", {
method: "PUT",
body: JSON.stringify({
current_password: $("#a-current").value,
username: $("#a-user").value,
new_password: $("#a-new").value,
}),
});
toast(t("账号已更新,请重新登录", "toast.account.updated"));
setTimeout(() => location.reload(), 800);
} catch (error) {
toast(error.message, true);
}
});
},
};
-171
View File
@@ -1,171 +0,0 @@
// Page: API Key 管理 — create, rename, enable/disable and delete caller keys.
import { api, derivedAPIBase, hasSession } from "../api.js";
import { loadConfig } from "../data.js";
import * as store from "../store.js";
import { t, onChange } from "../i18n.js";
import { $, el, emptyRow, formatNumber, localTime, confirmDialog, copyText, promptDialog, toast } from "../ui.js";
let keysLoading = false;
let createdKey = "";
let lastKeys = null;
async function load() {
if (keysLoading) return;
keysLoading = true;
$("#api-key-refresh").disabled = true;
try {
const data = await api("/api/api-keys");
if (hasSession()) {
lastKeys = data.keys;
render(data.keys);
}
} catch (error) {
$("#api-key-status").textContent = t(
`读取失败:${error.message}`,
"apikeys.loadFailed",
error.message,
);
} finally {
keysLoading = false;
$("#api-key-refresh").disabled = false;
}
}
async function mutate(id, method, body, button) {
button.disabled = true;
try {
const data = await api(`/api/api-keys/${encodeURIComponent(id)}`, {
method,
...(body ? { body: JSON.stringify(body) } : {}),
});
if (!hasSession()) return;
lastKeys = data.keys;
render(data.keys);
await loadConfig();
toast(t("已保存并立即生效", "toast.apikeys.saved"));
} catch (error) {
toast(error.message, true);
} finally {
button.disabled = false;
}
}
function render(keys) {
keys = keys || [];
$("#api-key-count").textContent = t(`${keys.length} 个`, "apikeys.count", keys.length);
$("#api-key-status").textContent = t(
`${keys.filter((key) => key.enabled).length} 个已启用`,
"apikeys.enabledCount",
keys.filter((key) => key.enabled).length,
);
const host = $("#api-key-list");
host.replaceChildren();
for (const key of keys) {
const usage = key.usage || {};
const summary = (value = {}) =>
`${formatNumber(value.requests)} ${t("次", "apikeys.times")} · ${formatNumber(value.total_tokens)} tokens`;
const rename = el("button", { type: "button", class: "btn btn-sm btn-ghost", text: t("重命名", "common.rename") });
rename.addEventListener("click", async () => {
const name = await promptDialog({
title: t("重命名 API Key", "common.rename"),
label: t("密钥名称", "apikeys.namePrompt"),
value: key.name,
confirmLabel: t("保存", "common.save"),
});
if (name !== null) mutate(key.id, "PATCH", { name }, rename);
});
const toggle = el("button", {
type: "button",
class: "btn btn-sm btn-ghost",
text: key.enabled ? t("停用", "apikeys.disable") : t("启用", "apikeys.enable"),
});
toggle.addEventListener("click", () => mutate(key.id, "PATCH", { enabled: !key.enabled }, toggle));
const remove = el("button", { type: "button", class: "btn btn-sm btn-danger", text: t("删除", "common.delete") });
remove.addEventListener("click", async () => {
const ok = await confirmDialog({
title: t("删除 API Key", "common.delete"),
message: t(
`删除「${key.name}」后,使用它的应用将无法继续访问。确定删除?`,
"apikeys.confirmDelete",
key.name,
),
confirmLabel: t("删除", "common.delete"),
danger: true,
});
if (ok) mutate(key.id, "DELETE", null, remove);
});
host.append(
el("tr", {}, [
el("td", { text: key.name }),
el("td", { class: "mono", text: key.display }),
el("td", {
class: `status ${key.enabled ? "ok" : "warn"}`,
text: key.enabled ? t("已启用", "state.enabled") : t("已停用", "state.disabled"),
}),
el("td", { text: `${summary(usage.last_hour)} / ${summary(usage.lifetime)}` }),
el("td", { text: key.created_at ? localTime(key.created_at) : t("已有配置", "apikeys.col.legacy") }),
el("td", {}, [el("div", { class: "key-actions" }, [rename, toggle, remove])]),
]),
);
}
if (!keys.length) emptyRow(host, 6, t("暂无 API Key", "apikeys.empty"));
}
async function create(event) {
event.preventDefault();
const button = $("#api-key-create");
button.disabled = true;
try {
const data = await api("/api/api-keys", {
method: "POST",
body: JSON.stringify({ name: $("#api-key-name").value, value: $("#api-key-value").value }),
});
if (!hasSession()) return;
createdKey = data.key;
const goModels = store.get("debug")?.models?.filter((item) => item.available_go) || [];
const model =
goModels.find((item) => item.model === "glm-5.3-flash")?.model ||
goModels[0]?.model ||
"YOUR_MODEL";
$("#api-key-env").textContent = `OPENAI_API_KEY=${data.key}\nOPENAI_BASE_URL=${derivedAPIBase()}/v1\nOPENAI_MODEL=${model}`;
$("#api-key-created").classList.remove("hidden");
$("#api-key-form").reset();
lastKeys = data.keys;
render(data.keys);
await loadConfig();
toast(t("API Key 已创建", "toast.apikeys.created"));
} catch (error) {
toast(error.message, true);
} finally {
button.disabled = false;
}
}
function resetCreated() {
createdKey = "";
lastKeys = null;
$("#api-key-env").textContent = "";
$("#api-key-created").classList.add("hidden");
$("#api-key-value").value = "";
}
export default {
id: "api-keys",
title: "API Key 管理",
sub: "给每个调用方独立的访问密钥。",
init() {
$("#api-key-form").addEventListener("submit", create);
$("#api-key-refresh").addEventListener("click", load);
$("#api-key-dismiss").addEventListener("click", resetCreated);
$("#api-key-copy").addEventListener("click", () => copyText(createdKey));
$("#api-key-copy-env").addEventListener("click", () => copyText($("#api-key-env").textContent));
// Re-render the rows in place so the key that was just created stays on
// screen instead of being wiped by a reload.
onChange(() => {
if (lastKeys) render(lastKeys);
});
},
show: load,
refresh: load,
reset: resetCreated,
};
-219
View File
@@ -1,219 +0,0 @@
// Page: 配置中心 — masked config editing with validation, hot reload and reveal.
import { api } from "../api.js";
import { loadConfig, loadDebugModels } from "../data.js";
import * as store from "../store.js";
import { t, onChange } from "../i18n.js";
import { $, $$, bindTabs, el, openDialog, toast } from "../ui.js";
function renderChips(name) {
const host = $(`#${name}-chips`);
host.replaceChildren();
(store.get("config")?.[name] || []).forEach((item) => {
const remove = el("button", { type: "button", title: t("移除", "common.remove"), text: "×" });
const chip = el("span", { class: "chip", dataset: { id: item.id } });
remove.addEventListener("click", () => chip.remove());
chip.append(el("span", { text: item.display }), remove);
host.append(chip);
});
}
function renderRestartNotice(value) {
const notice = $("#restart-notice");
if (value?.restart_required_fields?.length) {
notice.textContent = t(
`已保存但尚未生效:${value.restart_required_fields.join(", ")}。当前 API ${value.effective.listen}、WebUI ${value.effective.webui_listen}。请重启进程。`,
"config.restartNotice",
value.restart_required_fields.join(", "),
value.effective.listen,
value.effective.webui_listen,
);
notice.classList.remove("hidden");
} else {
notice.classList.add("hidden");
}
}
function secretInputs(name) {
const kept = [...$(`#${name}-chips`).children].map((node) => ({ id: node.dataset.id }));
const added = $(`#${name}-new`)
.value.split(/\r?\n/)
.map((value) => value.trim())
.filter(Boolean)
.map((value) => ({ value }));
return kept.concat(added);
}
const numberValue = (selector) => Number($(selector).value);
function fillConfig(value) {
if (!value) return;
$("#c-listen").value = value.listen;
$("#c-prefer").value = value.prefer;
$("#c-web-listen").value = value.webui.listen;
$("#c-session").value = value.webui.session_ttl_minutes;
$("#c-web-enabled").checked = value.webui.enabled;
$("#c-anonymous").checked = !!value.anonymous;
$("#c-proxyfile").value = value.proxyfile;
$("#c-up-zen").value = value.upstream.zen;
$("#c-up-go").value = value.upstream.go;
$("#c-attempts").value = value.retry.max_attempts;
$("#c-timeout").value = value.retry.timeout_seconds;
$("#c-refresh").value = value.models.refresh_seconds;
$("#c-protocols").value = JSON.stringify(value.models.protocols || {}, null, 2);
$("#c-free-only").checked = !!value.models.free_only;
const reasoning = value.reasoning || {};
$("#c-reasoning-effort").value = reasoning.effort || "";
$("#c-reasoning-by-model").value = JSON.stringify(reasoning.effort_by_model || {}, null, 2);
$("#c-idle").value = value.performance.max_idle_conns;
$("#c-idle-host").value = value.performance.max_idle_conns_per_host;
$("#c-max-host").value = value.performance.max_conns_per_host;
$("#c-idle-timeout").value = value.performance.idle_conn_timeout_seconds;
$("#c-connect").value = value.performance.connect_timeout_seconds;
$("#c-cooldown").value = value.performance.failure_cooldown_seconds;
$("#c-attempt-timeout").value = value.performance.attempt_timeout_seconds;
$("#c-first-event-timeout").value = value.performance.first_event_timeout_seconds || 0;
$("#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);
renderRestartNotice(value);
}
async function save(event) {
event.preventDefault();
const current = store.get("config");
if (!current) return;
try {
const update = {
listen: $("#c-listen").value,
server_keys: secretInputs("server_keys"),
zen_keys: secretInputs("zen_keys"),
go_keys: secretInputs("go_keys"),
anonymous: $("#c-anonymous").checked,
proxies: secretInputs("proxies"),
proxyfile: $("#c-proxyfile").value,
prefer: $("#c-prefer").value,
upstream: { zen: $("#c-up-zen").value, go: $("#c-up-go").value },
retry: { max_attempts: numberValue("#c-attempts"), timeout_seconds: numberValue("#c-timeout") },
models: {
refresh_seconds: numberValue("#c-refresh"),
protocols: JSON.parse($("#c-protocols").value || "{}"),
free_only: $("#c-free-only").checked,
},
reasoning: {
effort: $("#c-reasoning-effort").value,
effort_by_model: JSON.parse($("#c-reasoning-by-model").value || "{}"),
},
performance: {
max_idle_conns: numberValue("#c-idle"),
max_idle_conns_per_host: numberValue("#c-idle-host"),
max_conns_per_host: numberValue("#c-max-host"),
idle_conn_timeout_seconds: numberValue("#c-idle-timeout"),
connect_timeout_seconds: numberValue("#c-connect"),
failure_cooldown_seconds: numberValue("#c-cooldown"),
attempt_timeout_seconds: numberValue("#c-attempt-timeout"),
first_event_timeout_seconds: numberValue("#c-first-event-timeout"),
},
logging: {
level: $("#c-level").value,
ring_size: numberValue("#c-ring"),
dump_request_bodies: $("#c-dump-bodies").checked,
},
webui: {
enabled: $("#c-web-enabled").checked,
listen: $("#c-web-listen").value,
username: current.webui.username,
session_ttl_minutes: numberValue("#c-session"),
},
};
const result = await api("/api/config", { method: "PUT", body: JSON.stringify(update) });
store.set("config", result.config);
["server_keys", "zen_keys", "go_keys", "proxies"].forEach(
(name) => ($(`#${name}-new`).value = ""),
);
await loadDebugModels();
toast(
result.result.restart_required
? t(
`已应用;${result.result.restart_fields.join(", ")} 需重启`,
"toast.config.restart",
result.result.restart_fields.join(", "),
)
: t("配置已保存并立即应用", "toast.config.saved"),
);
} catch (error) {
toast(error.message, true);
}
}
async function reload() {
try {
const result = await api("/api/config/reload", { method: "POST", body: "{}" });
await loadConfig();
await loadDebugModels();
toast(
result.restart_required
? t("磁盘配置已重载,监听字段需重启", "toast.config.reloadedRestart")
: t("磁盘配置已重载", "toast.config.reloaded"),
);
} catch (error) {
toast(error.message, true);
}
}
function reveal() {
const input = el("input", { type: "password", autocomplete: "current-password" });
const submit = async (close) => {
try {
const values = await api("/api/config/reveal", {
method: "POST",
body: JSON.stringify({ password: input.value }),
});
close();
openDialog({
title: t("敏感配置", "modal.title"),
size: "dialog-lg",
body: el("pre", { text: JSON.stringify(values, null, 2) }),
actions: [{ label: t("关闭", "modal.close") }],
});
} catch (error) {
toast(error.message, true);
}
};
const dialog = openDialog({
title: t("查看敏感配置", "modal.revealTitle"),
body: el("div", { class: "field" }, [
el("label", { text: t("请再次输入管理密码", "config.revealPrompt") }),
input,
]),
actions: [
{ label: t("取消", "common.cancel") },
{ label: t("查看", "common.view"), kind: "btn-primary", onClick: submit },
],
});
input.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
event.preventDefault();
submit(dialog.close);
}
});
}
export default {
id: "config",
title: "配置中心",
sub: "验证后原子保存,并热应用可变字段。",
init() {
store.on("config", fillConfig);
bindTabs($("#page-config"));
$("#config-form").addEventListener("submit", save);
$("#reload-config").addEventListener("click", reload);
$("#reveal").addEventListener("click", reveal);
onChange(() => {
const value = store.get("config");
if (value) renderRestartNotice(value);
// Update chip tooltips in place so pending unsaved chip removals survive a language switch.
$$(".chips .chip button").forEach((button) => (button.title = t("移除", "common.remove")));
});
},
};
-366
View File
@@ -1,366 +0,0 @@
// Page: 诊断 — request testing, routing, ledgers and the live event stream.
import { api } from "../api.js";
import { loadDebugModels } from "../data.js";
import * as logstream from "../logstream.js";
import * as store from "../store.js";
import { t, dateLocale, onChange } from "../i18n.js";
import {
$,
bindTabs,
copyText,
el,
emptyRow,
formatNumber,
renderFacts,
timeOnly,
toast,
} from "../ui.js";
const keyTestLabels = () => ({
usable: t("Key 可用", "play.key.usable"),
rejected: t("Key 被拒绝", "play.key.rejected"),
rate_limited: t("Key 已被接受但受到限流", "play.key.rateLimited"),
upstream_error: t("上游异常,无法判定 Key", "play.key.upstreamError"),
transport_error: t("网络或代理异常,无法判定 Key", "play.key.transportError"),
unavailable: t("Key 或运行时不可用", "play.key.unavailable"),
request_error: t("请求未成功", "play.key.requestError"),
});
function playgroundTemplate() {
const protocol = $("#play-protocol").value;
const model = $("#play-model").value || "YOUR_MODEL";
const prompt = t("用一句话说明这个模型的能力。", "playground.samplePrompt");
if (protocol === "responses") return { model, input: prompt };
if (protocol === "anthropic")
return {
model,
max_tokens: 512,
messages: [{ role: "user", content: prompt }],
};
return { model, messages: [{ role: "user", content: prompt }] };
}
function resetTemplate() {
$("#play-request").value = JSON.stringify(playgroundTemplate(), null, 2);
}
function renderKeys() {
const select = $("#play-key");
const selected = select.value;
select.replaceChildren();
select.append(el("option", { value: "auto", text: t("自动路由(匿名 / Tier 回退 / Key 轮询)", "playground.key.auto") }));
const keys = store.get("debug")?.keys || {};
for (const [tier, label] of [
["zen", "Zen Keys"],
["go", "Go Keys"],
]) {
const items = keys[tier] || [];
if (!items.length) continue;
const group = el("optgroup", { label });
for (const item of items) {
const cooling = item.cooldown_until
? t(
` · 冷却至 ${new Date(item.cooldown_until).toLocaleTimeString(dateLocale(), { hour12: false })}`,
"playground.key.cooling",
new Date(item.cooldown_until).toLocaleTimeString(dateLocale(), { hour12: false }),
)
: "";
group.append(
el("option", {
value: `${tier}:${item.id}`,
text: `${tier.toUpperCase()} · ${item.display} · ${item.id}${cooling}`,
}),
);
}
select.append(group);
}
if (selected && [...select.options].some((option) => option.value === selected)) select.value = selected;
else select.value = "auto";
}
function renderModels() {
const select = $("#play-model");
const selected = select.value;
select.replaceChildren();
(store.get("debug")?.models || []).forEach((item) => {
select.append(el("option", { value: item.model, text: item.model }));
});
if (selected && [...select.options].some((option) => option.value === selected)) select.value = selected;
if (!$("#play-request").value.trim()) resetTemplate();
renderKeys();
}
function showResult(result) {
const keyTest = result.key_test ? keyTestLabels()[result.key_test] || result.key_test : "";
const state = $("#play-state");
state.textContent = result.ok
? t(`请求成功 · HTTP ${result.http_status}`, "play.state.ok", result.http_status)
: t(`请求失败 · HTTP ${result.http_status}`, "play.state.failed", result.http_status);
state.className = `section-caption ${result.ok ? "ok" : "bad"}`;
const route = result.route || {};
const eligibility = route.anonymous_eligibility || {};
const selected = result.selected_key;
const routeLabel = route.tier
? `${route.tier} / ${route.anonymous ? "anonymous" : route.key_id || "key"}`
: t("未路由", "play.route.none");
renderFacts($("#play-facts"), [
[t("HTTP 状态", "play.httpStatus"), result.http_status, result.ok ? "ok" : "bad"],
[t("耗时", "common.duration"), `${result.duration_ms} ms`],
["Request ID", result.request_id || "—"],
[
t("测试模式", "play.mode"),
selected
? t(`指定 ${selected.tier.toUpperCase()} Key`, "play.mode.selected", selected.tier.toUpperCase())
: t("自动路由", "play.mode.auto"),
],
[t("测试 Key", "play.testedKey"), selected ? `${selected.display} · ${selected.id}` : "—"],
[
t("Key 判断", "play.keyVerdict"),
keyTest || t("自动路由未单独判定", "play.keyVerdict.none"),
result.key_test === "usable" ? "ok" : result.key_test ? "bad" : "",
],
[t("实际路由", "play.actualRoute"), routeLabel],
[t("原生协议", "play.nativeProtocol"), route.native_protocol || "—"],
[
t("匿名判断", "play.anonymousVerdict"),
t(
`${eligibility.allowed ? "允许" : "拒绝"} · ${eligibility.source || "—"}`,
eligibility.allowed ? "play.eligibility.allowed" : "play.eligibility.denied",
eligibility.source || "—",
),
eligibility.allowed ? "ok" : "warn",
],
]);
$("#play-output").textContent = JSON.stringify(result.response, null, 2);
}
async function run(event) {
event.preventDefault();
let request;
try {
request = JSON.parse($("#play-request").value);
} catch (error) {
toast(t(`请求 JSON 无效:${error.message}`, "toast.play.invalidJson", error.message), true);
return;
}
const keyValue = $("#play-key").value;
const key =
keyValue === "auto"
? { mode: "auto" }
: { mode: "selected", tier: keyValue.split(":")[0], id: keyValue.split(":").slice(1).join(":") };
$("#play-run").disabled = true;
$("#play-state").textContent =
key.mode === "selected"
? t("指定 Key 测试进行中…", "play.state.testingKey")
: t("Gateway 请求进行中…", "play.state.running");
try {
store.set(
"lastPlayground",
await api("/api/debug/inference", {
method: "POST",
body: JSON.stringify({ protocol: $("#play-protocol").value, key, request }),
}),
);
} catch (error) {
toast(error.message, true);
$("#play-state").textContent = t("诊断入口请求失败", "play.state.failedToCall");
} finally {
$("#play-run").disabled = false;
}
}
function renderRequests() {
const host = $("#upstream-requests");
host.replaceChildren();
(store.get("monitor")?.upstream?.requests || [])
.slice(-100)
.reverse()
.forEach((request) => {
const terminal = {
stream_error: t("流式响应失败", "diag.streamError"),
client_canceled: t("客户端已取消", "diag.clientCanceled"),
};
const result = terminal[request.outcome]
? `HTTP ${request.status} · ${terminal[request.outcome]}`
: request.status || request.outcome;
host.append(
el("tr", {}, [
el("td", { class: "mono", text: timeOnly(request.time) }),
el("td", { class: "mono", text: request.request_id }),
el("td", { text: request.model }),
el("td", { text: request.tier || "—" }),
el("td", { text: request.channel }),
el("td", { text: request.key_id || "—" }),
el("td", { class: "num", text: request.attempts }),
el("td", { class: request.success ? "ok" : "bad", text: result }),
el("td", { class: "num", text: `${request.duration_ms} ms` }),
]),
);
});
if (!host.children.length) emptyRow(host, 9, t("尚无请求路由", "diag.noRequests"));
}
function renderAttempts() {
const host = $("#upstream-attempts");
host.replaceChildren();
(store.get("monitor")?.upstream?.recent || [])
.slice(-100)
.reverse()
.forEach((attempt) => {
host.append(
el("tr", {}, [
el("td", { class: "mono", text: timeOnly(attempt.time) }),
el("td", { class: "mono", text: attempt.request_id }),
el("td", { text: attempt.model }),
el("td", { text: `${attempt.tier} / ${attempt.channel}` }),
el("td", { text: attempt.key_id }),
el("td", { text: attempt.proxy_node }),
el("td", { class: attempt.success ? "ok" : "bad", text: attempt.status || attempt.outcome }),
el("td", { class: "num", text: `${attempt.duration_ms} ms` }),
]),
);
});
if (!host.children.length) emptyRow(host, 8, t("尚无上游尝试", "diag.noAttempts"));
}
function renderMetadata() {
const monitor = store.get("monitor");
const debug = store.get("debug");
const metadata = debug?.metadata || monitor?.resources?.metadata || {};
const stamp = (value) => new Date(value).toLocaleString(dateLocale(), { hour12: false });
renderFacts($("#metadata-facts"), [
[
t("就绪", "diag.ready"),
metadata.ready ? t("是", "common.yes") : t("否", "common.no"),
metadata.ready ? "ok" : "warn",
],
[t("模型数", "diag.modelCount"), formatNumber(metadata.models)],
[
t("更新时间", "diag.updatedAt"),
metadata.updated_at ? stamp(metadata.updated_at) : t("尚未更新", "diag.notUpdated"),
],
[t("是否过期", "diag.stale"), metadata.stale ? t("是", "common.yes") : t("否", "common.no"), metadata.stale ? "warn" : "ok"],
[t("下次刷新", "diag.nextRefresh"), metadata.next_refresh ? stamp(metadata.next_refresh) : "—"],
[
t("最近错误", "diag.lastError"),
metadata.last_error || t("无", "common.none"),
metadata.last_error ? "bad" : "ok",
],
]);
}
function renderRouteModels() {
const debug = store.get("debug");
const host = $("#diagnostic-models");
if (!host || !debug) return;
const query = $("#diagnostic-model-search").value.trim().toLowerCase();
host.replaceChildren();
(debug.models || [])
.filter((item) => !query || item.model.toLowerCase().includes(query))
.forEach((item) => {
const eligibility = item.anonymous_eligibility || {};
const plan = [...(item.anonymous ? ["anonymous"] : []), ...(item.key_tiers || [])];
host.append(
el("tr", {}, [
el("td", { class: "mono", text: item.model }),
el("td", { text: `${item.native_protocol} · ${item.protocol_source}` }),
el("td", {
class: item.route_error ? "bad" : "",
text: item.route_error || (plan.length ? plan.join(" → ") : "—"),
}),
el("td", {
class: eligibility.allowed ? "ok" : "warn",
text: eligibility.allowed ? t("允许", "common.allowed") : t("拒绝", "common.denied"),
}),
el("td", { text: eligibility.source || "—" }),
el("td", {
class: "num",
text: `${eligibility.input_cost == null ? "?" : eligibility.input_cost} / ${
eligibility.output_cost == null ? "?" : eligibility.output_cost
}`,
}),
]),
);
});
if (!host.children.length) emptyRow(host, 6, t("没有匹配模型", "diag.noMatch"));
}
let activeTab = "playground";
function renderLedger() {
renderRequests();
renderAttempts();
}
function renderRoute() {
renderMetadata();
renderRouteModels();
}
export default {
id: "diagnostics",
title: "诊断",
sub: "请求测试、路由资格与运行流水。",
init() {
bindTabs($("#page-diagnostics"), (id) => {
activeTab = id;
logstream.setVisible(id === "logs");
if (id === "playground") {
if (!store.get("debug")) loadDebugModels();
renderModels();
}
if (id === "ledger") renderLedger();
if (id === "route") renderRoute();
});
logstream.bind();
$("#play-protocol").addEventListener("change", resetTemplate);
$("#play-model").addEventListener("change", () => {
try {
const request = JSON.parse($("#play-request").value);
request.model = $("#play-model").value;
$("#play-request").value = JSON.stringify(request, null, 2);
} catch {
resetTemplate();
}
});
$("#play-reset").addEventListener("click", resetTemplate);
$("#play-form").addEventListener("submit", run);
$("#play-copy").addEventListener("click", () =>
copyText($("#play-output").textContent, t("原始响应已复制", "toast.play.copied")),
);
$("#diagnostic-model-search").addEventListener("input", renderRouteModels);
store.on("debug", () => {
renderModels();
renderRoute();
});
store.on("monitor", () => {
renderLedger();
renderMetadata();
});
store.on("lastPlayground", (value) => {
if (value) showResult(value);
});
// The module owns every string it renders, so a language switch rebuilds it.
onChange(() => {
renderModels();
renderLedger();
renderMetadata();
renderRoute();
const last = store.get("lastPlayground");
if (last) showResult(last);
});
},
show() {
if (!store.get("debug")) loadDebugModels();
renderModels();
renderLedger();
renderRoute();
if (activeTab === "logs") logstream.setVisible(true);
},
hide() {
logstream.setVisible(false);
},
refresh() {
if (activeTab === "logs") logstream.render();
},
};
-283
View File
@@ -1,283 +0,0 @@
// Page: 模型与额度 — Go quota windows and free model availability.
import { api, hasSession } from "../api.js";
import { loadDebugModels } from "../data.js";
import { t, onChange } from "../i18n.js";
import { $, bindTabs, copyText, el, emptyRow, localTime } from "../ui.js";
const windows = () => [
["rolling", t("5 小时窗口", "quotas.window.hour")],
["weekly", t("每周窗口", "quotas.window.week")],
["monthly", t("每月窗口", "quotas.window.month")],
];
let data = null;
let timer = null;
let loading = false;
let activeTab = "quota";
async function load() {
if (loading) return;
loading = true;
$("#quota-refresh").disabled = true;
$("#quota-refresh").textContent = t("读取中…", "quotas.loading");
try {
const value = await api("/api/model-quotas");
if (!hasSession()) return;
data = value;
const select = $("#quota-account");
const selected = select.value;
select.replaceChildren();
for (const account of value.accounts || []) {
select.append(el("option", { value: account.id, text: `Go Key ${account.display}` }));
}
if ([...select.options].some((option) => option.value === selected)) select.value = selected;
if (!select.options.length)
select.append(el("option", { value: "", text: t("尚未配置 Go Key", "quotas.noKey") }));
render();
} catch (error) {
$("#quota-status").textContent = t(
`查询失败:${error.message}。已有显示仅为上次查询结果。`,
"quotas.queryFailed",
error.message,
);
} finally {
loading = false;
$("#quota-refresh").disabled = false;
$("#quota-refresh").textContent = t("刷新额度", "quotas.refresh");
}
}
function render() {
if (!data) return;
const account = (data.accounts || []).find((item) => item.id === $("#quota-account").value);
const stale = account?.status === "stale";
const cards = $("#quota-cards");
cards.replaceChildren();
$("#quota-status").textContent = !account
? t("请先在配置中心添加 OpenCode Go Key。", "quotas.addKeyFirst")
: account.error
? stale
? t("{0};下方显示上次成功数据,当前额度未知。", "quotas.staleError", account.error)
: t("{0};当前额度未知。", "quotas.error", account.error)
: t("已连接 OpenCode · 共享套餐额度。多个 Key 的额度不相加。", "quotas.connected");
$("#quota-updated").textContent = account?.fetched_at
? t(
`${stale ? "上次成功查询" : "额度更新时间"}:${localTime(account.fetched_at)} · 缓存 60 秒 · 来源:OpenCode Go /v1/usage`,
stale ? "quotas.lastSuccess" : "quotas.updated",
localTime(account.fetched_at),
)
: "";
for (const [id, label] of windows()) {
const item = account?.windows?.[id];
const progress = el("progress", { max: 100, "aria-label": t(`${label}剩余额度`, "quotas.window.aria", label) });
progress.value = item ? item.remaining_percent : 0;
cards.append(
el("div", { class: `quota-card${item?.remaining_percent < 20 ? " quota-low" : ""}` }, [
el("h3", { text: label }),
el("div", {
class: "quota-value",
text: item ? `≈ ${item.remaining_percent}%` : t("未知", "common.unknown"),
}),
progress,
el("div", {
class: "quota-reset",
text: item
? `${stale ? t("历史剩余", "quotas.remainingHistory") : t("剩余", "quotas.remaining")} · ${
item.status === "rate-limited" ? t("已限额 · ", "quotas.rateLimited") : ""
}${t("重置于 {0}", "quotas.resetsAt", localTime(item.resets_at))}`
: t("等待上游额度数据", "quotas.waiting"),
}),
]),
);
}
const query = $("#quota-model-search").value.trim().toLowerCase();
const allModels = data.models || [];
const models = allModels.filter((model) => model.id.toLowerCase().includes(query));
$("#quota-model-count").textContent = `${models.length} / ${allModels.length}`;
const catalog = data.catalog;
const catalogUpdated =
catalog?.updated_at && !catalog.updated_at.startsWith("0001-")
? localTime(catalog.updated_at)
: t("尚未就绪", "common.notReady");
$("#quota-catalog-status").textContent = `${catalog?.stale ? t("模型目录暂未更新,显示缓存 · ", "quotas.catalogStale") : ""}${t(
`目录更新时间:${catalogUpdated}`,
"quotas.catalogUpdated",
catalogUpdated,
)}`;
const host = $("#quota-models");
host.replaceChildren();
for (const model of models) {
const copy = el("button", { class: "btn btn-sm btn-ghost", text: t("复制名称", "quotas.copyName") });
copy.addEventListener("click", () => copyText(model.id));
const row = el("tr", {}, [
el("td", { class: "mono", text: model.id }),
el("td", {
text:
{ chat: "Chat Completions", responses: "Responses", anthropic: "Messages" }[model.protocol] ||
model.protocol,
}),
]);
for (const [id] of windows()) {
const item = account?.windows?.[id];
row.append(
el("td", {
class: "num",
text: item
? `≈ ${item.remaining_percent}%${stale ? t("(历史)", "quotas.history") : ""}`
: t("未知", "common.unknown"),
}),
);
}
row.append(el("td", {}, [copy]));
host.append(row);
}
if (!models.length)
emptyRow(
host,
6,
allModels.length
? t("没有匹配的模型", "diag.noMatch")
: t("模型目录尚未就绪,请稍后刷新", "quotas.catalogPending"),
);
}
const date = (value) =>
value && !value.startsWith("0001-") ? localTime(value) : t("待探测", "availability.pending");
async function loadAvailability() {
try {
const value = await api("/api/models/availability");
$("#availability-error").textContent = "";
const host = $("#availability-models");
host.replaceChildren();
for (const item of value.models) {
const restore = el("button", {
type: "button",
class: "btn btn-sm btn-ghost",
text: t("恢复启用", "availability.restore"),
disabled: !item.disabled,
});
const toggle = el("button", {
type: "button",
class: "btn btn-sm btn-ghost",
text: item.manual
? t("切回自动", "availability.switchAuto")
: t("切为手动", "availability.switchManual"),
});
const run = async (path, body) => {
restore.disabled = true;
toggle.disabled = true;
try {
await api(path, { method: "POST", body: JSON.stringify(body) });
await loadAvailability();
await loadDebugModels();
} catch (error) {
$("#availability-error").textContent = error.message;
restore.disabled = !item.disabled;
toggle.disabled = false;
}
};
restore.addEventListener("click", () => run("/api/models/restore", { model: item.model }));
toggle.addEventListener("click", () =>
run("/api/models/manual", { model: item.model, manual: !item.manual }),
);
host.append(
el("tr", {}, [
el("td", { class: "mono", text: item.model }),
el("td", {
class: item.disabled ? "warn" : "ok",
text: item.disabled ? t("已禁用", "state.disabled") : t("已启用", "state.enabled"),
}),
el("td", {
text:
[item.channel, item.reason].filter(Boolean).join(" / ") ||
t("待探测", "availability.pending"),
}),
el("td", {
text: item.manual
? t("手动", "availability.manual")
: t("自动", "availability.auto"),
}),
el("td", {
text: item.auto_effort?.effort
? `${item.auto_effort.effort}(${date(item.effort_checked_at)})`
: t("未验证", "availability.unverified"),
}),
el("td", { class: "mono", text: date(item.checked_at) }),
el("td", {
class: "mono",
text: item.manual
? t("手动控制,不自动探测", "availability.manualControl")
: date(item.next_check),
}),
el("td", {}, [el("div", { class: "key-actions" }, [restore, toggle])]),
]),
);
}
if (!value.models.length)
$("#availability-error").textContent = t(
"当前模型目录中没有符合免费资格的模型。",
"availability.noneEligible",
);
} catch (error) {
$("#availability-error").textContent = error.message;
}
}
function startPolling() {
clearInterval(timer);
timer = setInterval(() => {
if (!document.hidden) load();
}, 60000);
}
function stopPolling() {
clearInterval(timer);
timer = null;
}
export default {
id: "model-quotas",
title: "模型与额度",
sub: "共享套餐额度与免费模型探测状态。",
init() {
bindTabs($("#page-model-quotas"), (id) => {
activeTab = id;
if (id === "quota") {
load();
startPolling();
} else {
stopPolling();
loadAvailability();
}
});
$("#quota-refresh").addEventListener("click", load);
$("#quota-account").addEventListener("change", render);
$("#quota-model-search").addEventListener("input", render);
$("#availability-refresh").addEventListener("click", loadAvailability);
// Only the rows are rebuilt: a refresh button that is mid-request keeps its
// disabled state and its "读取中…" label.
onChange(() => {
if (!loading) $("#quota-refresh").textContent = t("刷新额度", "quotas.refresh");
const emptyOpt = $("#quota-account")?.querySelector('option[value=""]');
if (emptyOpt) emptyOpt.textContent = t("尚未配置 Go Key", "quotas.noKey");
if (activeTab === "quota") render();
else loadAvailability();
});
},
show() {
if (activeTab === "quota") {
load();
startPolling();
} else {
loadAvailability();
}
},
hide() {
stopPolling();
},
refresh() {
if (activeTab === "quota") load();
else loadAvailability();
},
};
-235
View File
@@ -1,235 +0,0 @@
// Page: 概览 — readiness checklist, metrics, resources and token usage.
import * as store from "../store.js";
import { $, bindTabs, el, emptyRow, formatNumber, timeOnly } from "../ui.js";
import { t, onChange } from "../i18n.js";
function renderChecklist() {
const config = store.get("config");
const monitor = store.get("monitor");
if (!config || !monitor) return;
const resources = monitor.resources;
const models = resources.models || {};
const modelDescription = models.stale
? t(
`目录来自${models.cache_source || "磁盘"}快取,等待后台刷新。`,
"guide.models.cached",
models.cache_source || "磁盘",
)
: t("上游目录已完成首次刷新且有可暴露模型。", "guide.models.ready");
const checks = [
[
t("配置本地 Key", "guide.step.serverkey"),
t("客户端使用 Server Key 访问 Gateway。", "guide.step.serverkey.desc"),
(config.server_keys || []).length > 0,
],
[
t("选择上游通道", "guide.step.upstream"),
t("至少有 Zen / Go Key,或启用匿名通道。", "guide.step.upstream.desc"),
(config.zen_keys || []).length + (config.go_keys || []).length > 0 || config.anonymous,
],
[
t("检查 Proxy", "guide.step.proxy"),
t("至少一个代理节点健康。", "guide.step.proxy.desc"),
(resources.proxies || []).some((proxy) => proxy.healthy),
],
[
t("等待模型目录", "guide.step.models"),
modelDescription,
models.exposed > 0 && !!models.updated_at,
],
];
const card = $("#overview-checklist");
const ready = checks.every(([, , done]) => done);
card.classList.toggle("hidden", ready);
if (ready) return;
const host = $("#guide-steps");
host.replaceChildren();
checks.forEach(([title, description, done]) => {
host.append(
el("article", { class: "guide-step" }, [
el("h3", { text: title }),
el("p", { text: description }),
el("div", {
class: `step-state ${done ? "ok" : "warn"}`,
text: done ? t("✓ 已就绪", "guide.done") : t("○ 待处理", "guide.todo"),
}),
]),
);
});
}
function renderResources(resources) {
const proxies = $("#proxy-table");
proxies.replaceChildren();
(resources.proxies || []).forEach((proxy) => {
proxies.append(
el("tr", {}, [
el("td", { text: proxy.address }),
el("td", {
class: `status ${proxy.healthy ? "ok" : "bad"}`,
text: proxy.healthy ? t("正常", "state.healthy") : t("不可用", "state.unavailable"),
}),
el("td", {
text: `Z ${proxy.zen_keys} · G ${proxy.go_keys} · A ${
proxy.anonymous ? t("开", "common.on") : t("关", "common.off")
}`,
}),
]),
);
});
if (!proxies.children.length) emptyRow(proxies, 3);
const keys = $("#key-table");
keys.replaceChildren();
if (resources.anonymous) {
keys.append(
el("tr", {}, [
el("td", { text: "anonymous" }),
el("td", { text: "zen" }),
el("td", { class: "status ok", text: t("已启用", "state.enabled") }),
]),
);
}
(resources.keys || []).forEach((key) => {
keys.append(
el("tr", {}, [
el("td", { text: key.id }),
el("td", { text: key.tier }),
el("td", {
class: `status ${key.cooldown_until ? "warn" : "ok"}`,
text: key.cooldown_until ? t("冷却中", "state.cooling") : t("可用", "state.available"),
}),
]),
);
});
if (!keys.children.length) emptyRow(keys, 3);
}
function renderBreakdowns(metrics) {
const host = $("#breakdowns");
host.replaceChildren();
[
[t("端点", "breakdown.endpoint"), metrics.endpoints],
[t("状态码", "breakdown.status"), metrics.statuses],
[t("模型", "breakdown.model"), metrics.models],
["Tier", metrics.tiers],
].forEach(([title, data]) => {
const body = el("tbody");
Object.entries(data || {})
.sort((a, b) => b[1] - a[1])
.slice(0, 10)
.forEach(([key, value]) => {
body.append(el("tr", {}, [el("td", { text: key }), el("td", { class: "num", text: value })]));
});
if (!body.children.length) emptyRow(body, 2, t("暂无请求", "breakdown.empty"));
host.append(
el("div", { class: "breakdown" }, [
el("h3", { text: title }),
el("div", { class: "table-wrap" }, [el("table", { class: "table" }, [body])]),
]),
);
});
}
function renderSummary(monitor) {
const metrics = monitor.metrics;
$("#m-total").textContent = formatNumber(metrics.last_hour.total);
$("#m-rate").textContent = `${((metrics.last_hour.success_rate || 0) * 100).toFixed(1)}%`;
$("#m-p95").textContent = `${metrics.last_hour.p95_ms || 0} ms`;
$("#m-active").textContent = `${metrics.active_requests || 0} / ${metrics.active_streams || 0}`;
renderResources(monitor.resources);
renderBreakdowns(metrics);
}
function renderTrend(metrics) {
const trend = $("#usage-trend");
const series = metrics?.series || [];
const maximum = Math.max(1, ...series.map((point) => point.total_tokens || 0));
trend.replaceChildren();
series.forEach((point) => {
const bar = el("div", { class: "trend-bar" });
bar.style.height = `${Math.max(2, Math.round(((point.total_tokens || 0) / maximum) * 100))}%`;
bar.title = `${timeOnly(point.minute)} · input ${formatNumber(point.input_tokens)} · output ${formatNumber(point.output_tokens)} · total ${formatNumber(point.total_tokens)}`;
trend.append(bar);
});
$("#usage-trend-meta").textContent = series.length
? t(
`峰值 ${formatNumber(maximum)} tokens / 分钟 · 近 ${series.length} 分钟`,
"usage.trend.peak",
formatNumber(maximum),
series.length,
)
: t("尚无趋势数据", "usage.trend.empty");
}
function renderUsageModels(usage) {
const host = $("#usage-models");
host.replaceChildren();
Object.entries(usage.models || {})
.sort((a, b) => (b[1].total_tokens || 0) - (a[1].total_tokens || 0))
.slice(0, 15)
.forEach(([model, value]) => {
host.append(
el("tr", {}, [
el("td", { class: "mono", text: model }),
el("td", { class: "num", text: formatNumber(value.input_tokens) }),
el("td", { class: "num", text: formatNumber(value.output_tokens) }),
el("td", { class: "num", text: formatNumber(value.total_tokens) }),
]),
);
});
if (!host.children.length) emptyRow(host, 4, t("尚无 Token 用量", "usage.empty.models"));
}
function renderTiers(usage) {
const host = $("#usage-tiers");
const entries = Object.entries(usage.tiers || {}).sort(
(a, b) => (b[1].total_tokens || 0) - (a[1].total_tokens || 0),
);
const total = Math.max(1, ...entries.map(([, value]) => value.total_tokens || 0));
host.replaceChildren();
entries.forEach(([tier, value]) => {
const fill = el("div", { class: "tier-fill" });
fill.style.width = `${Math.round(((value.total_tokens || 0) / total) * 100)}%`;
host.append(
el("div", { class: "tier-row" }, [
el("strong", { text: tier }),
el("div", { class: "tier-track" }, [fill]),
el("span", { class: "tier-value", text: formatNumber(value.total_tokens) }),
]),
);
});
if (!entries.length) host.append(el("div", { class: "empty", text: t("尚无 Tier 用量", "usage.empty.tiers") }));
}
function renderUsage(monitor) {
const usage = monitor.usage?.last_hour || {};
const tokens = usage.tokens || {};
$("#u-coverage").textContent = `${((usage.coverage || 0) * 100).toFixed(1)}%`;
$("#u-total").textContent = formatNumber(tokens.total_tokens);
$("#u-cached").textContent = formatNumber(tokens.cached_tokens);
$("#u-reasoning").textContent = formatNumber(tokens.reasoning_tokens);
renderTrend(monitor.metrics);
renderUsageModels(usage);
renderTiers(usage);
}
function render() {
renderChecklist();
const monitor = store.get("monitor");
if (!monitor) return;
renderSummary(monitor);
renderUsage(monitor);
}
export default {
id: "overview",
title: "概览",
sub: "运行指标、Token 用量与资源状态。",
init() {
bindTabs($("#page-overview"));
store.on("monitor", render);
store.on("config", renderChecklist);
onChange(render);
},
show: render,
};
-254
View File
@@ -1,254 +0,0 @@
// Page: 模型轮转 — sota/sweet alias groups, ordering, manual switch and attempts.
import { api, hasSession } from "../api.js";
import { t, onChange } from "../i18n.js";
import { $, el, emptyRow, localTime, toast } from "../ui.js";
const reasons = () => ({
success: t("成功", "rotation.reason.success"),
client_canceled: t("调用方取消", "rotation.reason.clientCanceled"),
quota_or_rate_limit: t("额度不足 / 限流", "rotation.reason.quota"),
transport_error: t("连接错误", "rotation.reason.transport"),
first_output_timeout: t("首个输出超时", "rotation.reason.firstOutputTimeout"),
stream_error: t("输出中断", "rotation.reason.streamError"),
response_read_error: t("读取响应失败", "rotation.reason.readError"),
response_conversion_error: t("响应解析或转换失败", "rotation.reason.conversionError"),
request_conversion_error: t("请求转换失败", "rotation.reason.requestConversion"),
upstream_error: t("上游错误", "rotation.reason.upstreamError"),
});
let data = null;
let dirty = false;
// The persisted rotation state serializes nil maps and slices as JSON null;
// normalize them before anything renders against them.
function normalize(value) {
for (const group of value.groups || []) {
group.order = group.order || [];
group.available = group.available || {};
group.paused = group.paused || {};
group.switches = group.switches || [];
}
value.attempts = value.attempts || [];
return value;
}
async function load() {
try {
const value = await api("/api/rotation");
if (!hasSession()) return;
data = normalize(value);
dirty = false;
render();
} catch (error) {
toast(error.message, true);
}
}
function renderGroup(group) {
const reasonMap = reasons();
const aliasInput = el("input", {
id: `rotation-alias-${group.id}`,
value: group.alias,
required: true,
maxlength: 64,
});
aliasInput.addEventListener("input", () => {
group.alias = aliasInput.value;
dirty = true;
});
const table = el("table", { class: "table" }, [
el("thead", {}, [
el(
"tr",
{},
[
t("顺序", "rotation.col.order"),
t("模型", "common.model"),
t("状态 / 恢复时间", "rotation.col.state"),
t("操作", "common.action"),
].map((text) => el("th", { text })),
),
]),
]);
const body = el("tbody");
table.append(body);
group.order.forEach((model, index) => {
const row = el("tr", {}, [
el("td", { class: "num", text: String(index + 1) }),
el("td", { class: "mono", text: model }),
]);
const until = group.paused[model];
const paused = until && new Date(until) > new Date();
row.append(
el("td", {
text: !group.available[model]
? t("已下架 / 暂不可用", "rotation.unavailable")
: paused
? t(`暂停至 ${localTime(until)}`, "rotation.pausedUntil", localTime(until))
: model === group.current
? t("当前使用", "rotation.inUse")
: t("可用", "state.available"),
}),
);
const actions = el("div", { class: "rotation-actions" });
for (const [text, delta] of [
[t("上移", "rotation.moveUp"), -1],
[t("下移", "rotation.moveDown"), 1],
]) {
const button = el("button", {
type: "button",
class: "btn btn-sm btn-ghost",
text,
"aria-label": `${model} ${text}`,
disabled: index + delta < 0 || index + delta >= group.order.length,
});
button.addEventListener("click", () => {
[group.order[index], group.order[index + delta]] = [
group.order[index + delta],
group.order[index],
];
data.first_output_seconds = Number($("#rotation-timeout").value);
dirty = true;
render();
});
actions.append(button);
}
const select = el("button", {
type: "button",
class: "btn btn-sm btn-ghost",
text: t("设为当前", "rotation.setCurrent"),
"aria-label": t(`使用 ${model}`, "rotation.useModel", model),
disabled: !group.available[model],
});
select.addEventListener("click", async () => {
select.disabled = true;
try {
const result = normalize(
await api("/api/rotation/current", {
method: "POST",
body: JSON.stringify({ group: group.id, model }),
}),
);
// Keep unsaved alias/order edits while refreshing operational state.
for (const item of data.groups) {
const live = result.groups.find((entry) => entry.id === item.id);
Object.assign(item, { current: live.current, paused: live.paused, switches: live.switches });
}
data.persistence_error = result.persistence_error;
render();
toast(t("当前模型已切换", "toast.rotation.switched"));
} catch (error) {
select.disabled = false;
toast(error.message, true);
}
});
actions.append(select);
row.append(el("td", {}, [actions]));
body.append(row);
});
if (!group.order.length) emptyRow(body, 4, t("等待 Go 模型目录", "rotation.waitingCatalog"));
const recent = el("div", { class: "rotation-switches" }, [
el("h3", { text: t("最近切换", "rotation.recentSwitches") }),
]);
for (const item of (group.switches || []).slice(-5).reverse()) {
recent.append(
el("p", {
text: `${localTime(item.time)} · ${item.from} → ${item.to} · ${
reasonMap[item.reason] || item.reason
}`,
}),
);
}
if (!group.switches?.length)
recent.append(el("p", { text: t("尚无切换记录", "rotation.noSwitches") }));
return el("section", { class: "section rotation-group" }, [
el("h2", { class: "section-title", text: group.id === "sota" ? "SOTA" : t("甜点", "rotation.sweet") }),
el("div", { class: "field" }, [
el("label", { for: `rotation-alias-${group.id}`, text: t("调用别名", "rotation.aliasLabel") }),
aliasInput,
]),
el("p", {
class: "rotation-current",
text: t(
`当前模型:${group.current || t("等待可用模型", "rotation.waitingModel")}`,
"rotation.current",
group.current || t("等待可用模型", "rotation.waitingModel"),
),
}),
el("div", { class: "table-wrap" }, [table]),
recent,
]);
}
function render() {
if (!data) return;
const reasonMap = reasons();
$("#rotation-status").textContent =
data.persistence_error ||
t("状态已更新 · 两组独立轮转,所有调用方共享当前位置。", "rotation.status");
$("#rotation-timeout").value = data.first_output_seconds;
const host = $("#rotation-groups");
host.replaceChildren();
for (const group of data.groups) host.append(renderGroup(group));
const attempts = $("#rotation-attempts");
attempts.replaceChildren();
for (const item of (data.attempts || []).slice().reverse()) {
attempts.append(
el("tr", {}, [
el("td", { class: "mono", text: localTime(item.time) }),
el("td", { class: "mono", text: item.request }),
el("td", { text: item.alias }),
el("td", { class: "mono", text: item.model }),
el("td", { class: "num", text: String(item.number) }),
el("td", { text: reasonMap[item.outcome] || item.outcome }),
]),
);
}
if (!data.attempts?.length)
emptyRow(attempts, 6, t("调用分组别名后显示最近 100 次尝试", "rotation.attemptsEmpty"));
}
async function save(event) {
event.preventDefault();
if (!data) return;
const button = $("#rotation-save");
button.disabled = true;
try {
const body = { first_output_seconds: Number($("#rotation-timeout").value) };
for (const group of data.groups) body[group.id] = { alias: group.alias.trim(), order: group.order };
data = normalize(await api("/api/rotation", { method: "PUT", body: JSON.stringify(body) }));
dirty = false;
render();
toast(t("模型轮转配置已保存并生效", "toast.rotation.saved"));
} catch (error) {
toast(error.message, true);
} finally {
button.disabled = false;
}
}
export default {
id: "rotation",
title: "模型轮转",
sub: "共享当前模型、故障切换与尝试记录。",
init() {
$("#rotation-refresh").addEventListener("click", () => {
if (dirty) {
toast(t("有未保存的修改,请先保存后刷新", "toast.rotation.dirty"), true);
return;
}
load();
});
$("#rotation-timeout").addEventListener("input", () => {
dirty = true;
});
$("#rotation-form").addEventListener("submit", save);
onChange(() => {
if (data) {
data.first_output_seconds = Number($("#rotation-timeout").value);
render();
}
});
},
show: load,
};
-28
View File
@@ -1,28 +0,0 @@
// Shared console state with a minimal change subscription so page modules
// re-render independently.
const state = {
config: null,
monitor: null,
debug: null,
lastPlayground: null,
};
const listeners = new Map();
export function get(key) {
return state[key];
}
export function set(key, value) {
state[key] = value;
const subscribers = listeners.get(key);
if (!subscribers) return;
for (const handler of [...subscribers]) handler(value);
}
export function on(key, handler) {
let subscribers = listeners.get(key);
if (!subscribers) listeners.set(key, (subscribers = new Set()));
subscribers.add(handler);
return () => subscribers.delete(handler);
}
-210
View File
@@ -1,210 +0,0 @@
// DOM helpers, formatters, clipboard, toast and in-page dialogs.
import { t, dateLocale } from "./i18n.js";
export const $ = (selector, root = document) => root.querySelector(selector);
export const $$ = (selector, root = document) => [...root.querySelectorAll(selector)];
export function el(tag, props = {}, children = []) {
const node = document.createElement(tag);
for (const [key, value] of Object.entries(props)) {
if (value == null || value === false) continue;
if (key === "class") node.className = value;
else if (key === "text") node.textContent = value;
else if (key === "dataset") Object.assign(node.dataset, value);
else if (key.startsWith("on") && typeof value === "function")
node.addEventListener(key.slice(2), value);
else if (value === true) node.setAttribute(key, "");
else node.setAttribute(key, String(value));
}
for (const child of Array.isArray(children) ? children : [children]) {
if (child == null || child === false) continue;
node.append(child instanceof Node ? child : document.createTextNode(String(child)));
}
return node;
}
export const formatNumber = (value) => Number(value || 0).toLocaleString();
export function localTime(value) {
return value ? new Date(value).toLocaleString(dateLocale(), { hour12: false }) : "—";
}
export function timeOnly(value) {
return value ? new Date(value).toLocaleTimeString(dateLocale(), { hour12: false }) : "—";
}
let toastTimer = null;
export function toast(message, bad = false) {
const node = $("#toast");
node.textContent = message;
node.classList.toggle("bad-toast", bad);
node.classList.remove("hidden");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => node.classList.add("hidden"), 3600);
}
export async function copyText(text, okMessage = t("已复制", "toast.copied")) {
try {
await navigator.clipboard.writeText(text);
toast(okMessage);
return true;
} catch {
toast(t("浏览器不允许剪贴板访问,请手动选中复制", "toast.copyDenied"), true);
return false;
}
}
export function emptyRow(host, columns, message = t("暂无数据", "common.empty")) {
host.append(el("tr", {}, [el("td", { class: "empty", colspan: columns, text: message })]));
}
export function renderFacts(host, entries) {
host.replaceChildren();
for (const [label, value, tone] of entries) {
host.append(
el("div", { class: "fact" }, [
el("div", { class: "fact-label", text: label }),
el("div", { class: `fact-value ${tone || ""}`.trim(), text: value ?? "—" }),
]),
);
}
}
// Generic dialog host; onClose fires on every close path so promise-based
// dialogs settle exactly once.
export function openDialog({ title, body = null, size = "", actions = [], onClose }) {
const previous = document.activeElement;
const titleId = `dialog-title-${Math.random().toString(36).slice(2, 8)}`;
const overlay = el("div", { class: "dialog-overlay" });
const dialog = el("div", {
class: `dialog ${size}`.trim(),
role: "dialog",
"aria-modal": "true",
"aria-labelledby": titleId,
});
dialog.append(el("h2", { id: titleId, class: "dialog-title", text: title }));
if (body) dialog.append(body);
let closed = false;
const close = () => {
if (closed) return;
closed = true;
overlay.remove();
document.removeEventListener("keydown", onKey, true);
if (previous instanceof HTMLElement && previous.isConnected) previous.focus();
onClose?.();
};
const onKey = (event) => {
if (event.key === "Escape") {
event.stopPropagation();
close();
}
};
if (actions.length) {
const row = el("div", { class: "dialog-actions" });
for (const action of actions) {
row.append(
el("button", {
type: "button",
class: `btn btn-sm ${action.kind || "btn-ghost"}`,
text: action.label,
onclick: () => (action.onClick ? action.onClick(close) : close()),
}),
);
}
dialog.append(row);
}
overlay.append(dialog);
overlay.addEventListener("mousedown", (event) => {
if (event.target === overlay) close();
});
document.addEventListener("keydown", onKey, true);
$("#dialog-host").append(overlay);
const target = dialog.querySelector("input, select, textarea") || dialog.querySelector(".dialog-actions .btn");
target?.focus();
return { close, dialog };
}
export function confirmDialog({
title,
message = "",
confirmLabel = t("确定", "common.confirm"),
danger = false,
}) {
return new Promise((resolve) => {
let settled = false;
const finish = (value, close) => {
if (!settled) {
settled = true;
resolve(value);
}
close?.();
};
openDialog({
title,
body: message ? el("p", { class: "dialog-text", text: message }) : null,
onClose: () => finish(false),
actions: [
{ label: t("取消", "common.cancel"), onClick: (close) => finish(false, close) },
{
label: confirmLabel,
kind: danger ? "btn-danger" : "btn-primary",
onClick: (close) => finish(true, close),
},
],
});
});
}
export function promptDialog({
title,
label,
value = "",
placeholder = "",
confirmLabel = t("确定", "common.confirm"),
}) {
return new Promise((resolve) => {
let settled = false;
const input = el("input", { value, placeholder, maxlength: 80 });
const finish = (result, close) => {
if (!settled) {
settled = true;
resolve(result);
}
close?.();
};
input.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
event.preventDefault();
finish(input.value, dialog.close);
}
});
const dialog = openDialog({
title,
body: el("div", { class: "field" }, [el("label", { text: label }), input]),
onClose: () => finish(null),
actions: [
{ label: t("取消", "common.cancel"), onClick: (close) => finish(null, close) },
{ label: confirmLabel, kind: "btn-primary", onClick: (close) => finish(input.value, close) },
],
});
});
}
// Tab strip wiring: [data-tab] buttons toggle [data-panel] panels and report
// the active id.
export function bindTabs(page, onSwitch) {
const buttons = $$(".tabs .tab", page);
const panels = $$("[data-panel]", page);
const activate = (id) => {
for (const button of buttons) {
const active = button.dataset.tab === id;
button.classList.toggle("active", active);
button.setAttribute("aria-selected", active ? "true" : "false");
}
for (const panel of panels) panel.classList.toggle("hidden", panel.dataset.panel !== id);
onSwitch?.(id);
};
for (const button of buttons) button.addEventListener("click", () => activate(button.dataset.tab));
return { activate };
}