diff --git a/README.md b/README.md index 5016860..9b749b7 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ | `POST` | `/v1/messages` | Anthropic Messages | | `GET` | `/healthz` | 健康检查 | -`/healthz` 无需 API key,返回服务版本以及模型目录、Zen/Go key、匿名开关和代理池的汇总状态,不会暴露 key 或代理地址。模型目录尚未完成首次刷新、已经过期、没有可暴露模型或没有健康代理时返回 HTTP `503`;其余情况返回 `200`。 +`/healthz` 无需 API key,返回服务版本以及模型目录、Zen/Go key、匿名开关和代理池的汇总状态,不会暴露 key 或代理地址。模型目录尚未完成首次刷新、没有可暴露模型或没有健康代理时返回 HTTP `503`;使用过期磁盘快取时仍返回 `200`,但 `models.status` 为 `stale`。 模型目录的过期阈值为 `models.refresh_seconds` 的两倍,且不低于 60 秒。刚启动时短暂返回 `503 starting` 属于正常现象,模型列表首次刷新成功后会变为 `200 ok`。 @@ -56,7 +56,7 @@ Field Manual WebUI 包含运行桌面、六步首次运行检查、接入手册 Token 页面展示用量覆盖率、每分钟趋势、模型排行与 Zen/Go Tier 分布。诊断页展示 models.dev 状态、模型原生协议与匿名判断来源、Key/代理状态、逐次上游尝试以及最近一次 Playground 追踪;实时日志通过 SSE 推送。所有动态管理数据都以 DOM 文本节点渲染。 -监控、上游尝试、最近 Playground 结果和日志仅保存在内存。**进程重启会清空全部监控与诊断历史,包括 lifetime 累计。** stdout 日志仍可由 Docker 或日志平台收集;models.dev 价格快取是独立的磁盘兼容资料,不属于监控历史。 +监控、上游尝试、最近 Playground 结果和日志仅保存在内存。**进程重启会清空全部监控与诊断历史,包括 lifetime 累计。** stdout 日志仍可由 Docker 或日志平台收集;模型目录快取与 models.dev 价格快取是独立的磁盘兼容资料,不属于监控历史。 ### 监控字段 @@ -74,7 +74,7 @@ Token 页面展示用量覆盖率、每分钟趋势、模型排行与 Zen/Go Tie 每个 `upstream.requests` 项对应一个已完成的推理请求,包含最终实际使用的 Tier、通道、Key 尾码(或 `anonymous`)、尝试次数、HTTP 状态、耗时、成功标记和结果分类。每个 `upstream.recent` 项则对应一次上游尝试,包含时间、Request ID、模型、Tier、尝试序号、匿名标记、通道、Key 尾码、`proxy_node`、HTTP 状态、耗时、成功标记和结果分类。真实 Key 在日志和 WebUI 中只显示最后 5 个字符;配置接口的内部 secret ID 仍使用 SHA-256 稳定指纹。代理 URL 的认证信息会被移除,字段名称明确为代理节点而非出口 IP。 -lifetime 从当前进程启动开始;last hour 使用 60 个一分钟 Bucket。管理响应最多返回最近 500 个请求路由和 500 次上游尝试,WebUI 默认各显示最后 100 条。数据不会写入配置、metadata 快取或其他数据库。 +lifetime 从当前进程启动开始;last hour 使用 60 个一分钟 Bucket。进程内固定保留最近 10,000 个请求路由和 20,000 次上游尝试,管理响应最多返回其中最近 500 个,WebUI 默认各显示最后 100 条。`resources.models` 额外显示模型目录来源(`none`、`disk` 或 `live`)及 `stale` 状态。数据不会写入配置、metadata 快取或其他数据库。 ### Playground 与诊断 API @@ -318,7 +318,7 @@ socks5://127.0.0.1:1080 # 备用代理 } ``` -自动协议来源是 `https://models.opencode.ai/api.json`,并用 OpenCode 官方 Zen/Go endpoint 文档补充具体路径:模型的 `provider.npm`(或 Tier 默认 `npm`)及文档 endpoint 会映射为 OpenAI Responses、Anthropic Messages 或 OpenAI-compatible Chat。若能力目录暂时无法更新,服务会保留进程内上一份能力快照;首次启动且没有能力快照时,不会暴露能力未知的模型,避免把不支持的模型误路由到 Chat。手动 `models.protocols` 可用于上游实验模型。 +自动协议来源是 `https://models.opencode.ai/api.json`,并用 OpenCode 官方 Zen/Go endpoint 文档补充具体路径:模型的 `provider.npm`(或 Tier 默认 `npm`)及文档 endpoint 会映射为 OpenAI Responses、Anthropic Messages 或 OpenAI-compatible Chat。模型列表与协议能力会写入 `.models.catalog.json`,使用同目录临时文件原子替换并限制为 `0600`;启动时会先使用有效的旧快取,背景刷新成功后再更新。若能力目录暂时无法更新,服务会保留进程内上一份能力快照;首次启动且没有能力快照时,不会暴露能力未知的模型,避免把不支持的模型误路由到 Chat。手动 `models.protocols` 可用于上游实验模型。 模型同时存在于 Zen 与 Go 时按 `prefer` 配置排列认证 Key 顺序:值为 `go` 时先 Go 后 Zen,值为 `zen` 时先 Zen 后 Go(默认 `go`)。首选 Tier 失败后才回退另一 Tier;仅存在于某一池时只使用该池的 key。免费模型在这条认证顺序之前额外尝试匿名 Zen。 diff --git a/admin.go b/admin.go index fba0c34..a62b8dd 100644 --- a/admin.go +++ b/admin.go @@ -422,11 +422,12 @@ type DebugInferenceResult struct { func (a *AdminServer) handleDebugModels(w http.ResponseWriter, _ *http.Request) { models, metadata := a.manager.DebugModels() + catalog := a.manager.Resources().Models a.mu.Lock() last := a.lastInference a.mu.Unlock() w.Header().Set("Cache-Control", "no-store") - writeJSON(w, http.StatusOK, map[string]any{"models": models, "metadata": metadata, "last_inference": last}) + writeJSON(w, http.StatusOK, map[string]any{"models": models, "metadata": metadata, "catalog": catalog, "last_inference": last}) } func (a *AdminServer) handleDebugInference(w http.ResponseWriter, r *http.Request) { diff --git a/gateway.go b/gateway.go index 2b11dc5..1b836b6 100644 --- a/gateway.go +++ b/gateway.go @@ -54,6 +54,8 @@ type healthModels struct { 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 { @@ -83,6 +85,8 @@ func NewGateway(cfg Config, logger *slog.Logger, monitor *Monitor) (*Gateway, er if err != nil { return nil, fmt.Errorf("go node pool: %w", err) } + catalog := newModelCatalog(cfg.Prefer, cfg.Models.Protocols) + catalog.SetRefreshInterval(time.Duration(cfg.Models.RefreshSeconds) * time.Second) return &Gateway{ cfg: cfg, logger: logger, @@ -90,7 +94,7 @@ func NewGateway(cfg Config, logger *slog.Logger, monitor *Monitor) (*Gateway, er zenNodes: zenNodes, goNodes: goNodes, anonymous: newAnonymousPool(cfg.Anonymous, transports, cooldown), - catalog: newModelCatalog(cfg.Prefer, cfg.Models.Protocols), + catalog: catalog, monitor: monitor, }, nil } @@ -123,7 +127,7 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { if models.Exposed == 0 { modelStatus = "empty" issues = append(issues, "model_catalog_empty") - } else if time.Since(models.UpdatedAt) > staleAfter { + } else if models.Stale || time.Since(models.UpdatedAt) > staleAfter { modelStatus = "stale" issues = append(issues, "model_catalog_stale") } @@ -136,9 +140,13 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { } status := "ok" - httpStatus := http.StatusOK if len(issues) > 0 { status = "degraded" + } + blocking := modelStatus == "pending" || modelStatus == "empty" || proxyHealthy == 0 + httpStatus := http.StatusOK + ready := !blocking + if blocking { httpStatus = http.StatusServiceUnavailable if modelStatus == "pending" { status = "starting" @@ -146,7 +154,7 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { } writeJSON(w, httpStatus, healthResponse{ Status: status, - Ready: len(issues) == 0, + Ready: ready, Version: version, Models: healthModels{ Status: modelStatus, @@ -156,6 +164,8 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { 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{ @@ -289,12 +299,9 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { var usage bridgeUsage var usageReported bool if external == upstreamRoute.Protocol { - observer := newStreamUsageObserver(upstreamRoute.Protocol) - _, err = io.Copy(w, io.TeeReader(resp.Body, observer)) - usage = observer.Finish() - usageReported = observer.Reported() + usage, usageReported, err = forwardSSEWithUsageContext(r.Context(), w, resp.Body, upstreamRoute.Protocol, model) } else { - usage, usageReported, err = transcodeStreamWithUsage(w, resp.Body, upstreamRoute.Protocol, external, model) + usage, usageReported, err = transcodeStreamWithUsageContext(r.Context(), w, resp.Body, upstreamRoute.Protocol, external, model) } if meta != nil { meta.Usage, meta.UsageReported = usage, usageReported @@ -813,11 +820,19 @@ func (g *Gateway) StartModelRefresh(ctx context.Context) { capabilities, capabilitiesErr = g.refreshProtocolCapabilities(capabilityCtx) }() wg.Wait() + if ctx.Err() != nil { + return + } 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) + 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) + } + } g.logger.Info("model catalog refreshed", "component", "models", "event", "catalog_refreshed", "models", len(g.catalog.List())) } } diff --git a/models.go b/models.go index 455558f..2eb536a 100644 --- a/models.go +++ b/models.go @@ -7,7 +7,10 @@ import ( "fmt" "io" "net/http" + "os" + "path/filepath" "regexp" + "runtime" "sort" "strings" "sync" @@ -88,14 +91,33 @@ type modelCatalog struct { updatedAt time.Time prefer Tier metadata *modelMetadataStore + cachePath string + cacheSource string + stale bool + refreshAfter time.Duration } type modelCatalogSnapshot struct { - Zen int `json:"zen"` - Go int `json:"go"` - Total int `json:"total"` - Exposed int `json:"exposed"` - UpdatedAt time.Time `json:"updated_at,omitempty"` + Zen int `json:"zen"` + Go int `json:"go"` + Total int `json:"total"` + Exposed int `json:"exposed"` + UpdatedAt time.Time `json:"updated_at,omitempty"` + CacheSource string `json:"cache_source,omitempty"` + Stale bool `json:"stale"` +} + +const modelCatalogCacheSchemaVersion = 1 + +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[Tier]map[string]Protocol `json:"native_protocols"` + Unsupported map[Tier]map[string]bool `json:"unsupported"` } func newModelCatalog(prefer Tier, overrides map[string]string) *modelCatalog { @@ -107,9 +129,22 @@ func newModelCatalog(prefer Tier, overrides map[string]string) *modelCatalog { zen: map[string]bool{}, goModels: map[string]bool{}, protocols: protocols, nativeProtocols: map[Tier]map[string]Protocol{TierZen: {}, TierGo: {}}, unsupported: map[Tier]map[string]bool{TierZen: {}, TierGo: {}}, prefer: prefer, + cacheSource: "none", } } +func (c *modelCatalog) SetCachePath(path string) { + c.mu.Lock() + c.cachePath = path + c.mu.Unlock() +} + +func (c *modelCatalog) SetRefreshInterval(interval time.Duration) { + c.mu.Lock() + c.refreshAfter = interval + c.mu.Unlock() +} + func (c *modelCatalog) Replace(zen, goModels []string) { c.ReplaceWithCapabilities(zen, goModels, nil, nil) } @@ -137,7 +172,9 @@ func (c *modelCatalog) ReplaceWithCapabilities(zen, goModels []string, native ma } } } - c.updatedAt = time.Now() + c.updatedAt = time.Now().UTC() + c.cacheSource = "live" + c.stale = false } func (c *modelCatalog) CopyState(source *modelCatalog) { @@ -164,12 +201,59 @@ func (c *modelCatalog) CopyState(source *modelCatalog) { } } 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.cacheSource, c.stale = cacheSource, stale c.mu.Unlock() } +// 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 *modelCatalog) 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.updatedAt = cache.UpdatedAt.UTC() + c.cacheSource = "disk" + c.stale = true + if c.cachePath == "" { + c.cachePath = path + } + 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 *modelCatalog) 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), + } + c.mu.RUnlock() + if path == "" { + return nil + } + return saveModelCatalogCache(path, cache) +} + func (c *modelCatalog) Route(model string, hasZenKeys, hasGoKeys, hasAnonymous bool) (modelRoute, error) { c.mu.RLock() defer c.mu.RUnlock() @@ -340,12 +424,13 @@ func (c *modelCatalog) Snapshot() modelCatalogSnapshot { exposed++ } } + stale := c.stale + if !c.updatedAt.IsZero() && c.refreshAfter > 0 { + stale = stale || time.Since(c.updatedAt) > max(2*c.refreshAfter, time.Minute) + } return modelCatalogSnapshot{ - Zen: len(c.zen), - Go: len(c.goModels), - Total: len(seen), - Exposed: exposed, - UpdatedAt: c.updatedAt, + Zen: len(c.zen), Go: len(c.goModels), Total: len(seen), Exposed: exposed, + UpdatedAt: c.updatedAt, CacheSource: c.cacheSource, Stale: stale, } } @@ -407,6 +492,186 @@ func cloneBools(source map[string]bool) map[string]bool { return result } +func sortedSetKeys(source map[string]bool) []string { + result := make([]string, 0, len(source)) + for model, available := range source { + if available { + result = append(result, model) + } + } + sort.Strings(result) + return result +} + +func cloneTierProtocols(source map[Tier]map[string]Protocol) map[Tier]map[string]Protocol { + result := map[Tier]map[string]Protocol{TierZen: {}, TierGo: {}} + for _, tier := range []Tier{TierZen, TierGo} { + if protocols, ok := source[tier]; ok { + result[tier] = cloneProtocols(protocols) + } + } + return result +} + +func cloneTierBools(source map[Tier]map[string]bool) map[Tier]map[string]bool { + result := map[Tier]map[string]bool{TierZen: {}, TierGo: {}} + for _, tier := range []Tier{TierZen, TierGo} { + if models, ok := source[tier]; ok { + result[tier] = cloneBools(models) + } + } + return result +} + +func modelCatalogCachePath(configPath string) string { + if configPath == "" { + return "" + } + return configPath + ".models.catalog.json" +} + +func loadModelCatalogCache(path string) (modelCatalogCache, error) { + if path == "" { + return modelCatalogCache{}, os.ErrNotExist + } + file, err := os.Open(path) + if err != nil { + return modelCatalogCache{}, err + } + defer file.Close() + var cache modelCatalogCache + decoder := json.NewDecoder(io.LimitReader(file, 32<<20)) + if err := decoder.Decode(&cache); err != nil { + return modelCatalogCache{}, err + } + var extra any + if err := decoder.Decode(&extra); err != io.EOF { + if err == nil { + return modelCatalogCache{}, errors.New("model catalog cache contains multiple JSON values") + } + return modelCatalogCache{}, err + } + if cache.SchemaVersion != modelCatalogCacheSchemaVersion { + return modelCatalogCache{}, fmt.Errorf("unsupported model catalog cache schema version %d", cache.SchemaVersion) + } + if cache.UpdatedAt.IsZero() { + 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 { + return modelCatalogCache{}, errors.New("model catalog cache is empty") + } + if err := validateCatalogCapabilities(cache.NativeProtocols, cache.Unsupported); err != nil { + return modelCatalogCache{}, err + } + cache.NativeProtocols = cloneTierProtocols(cache.NativeProtocols) + cache.Unsupported = cloneTierBools(cache.Unsupported) + cache.UpdatedAt = cache.UpdatedAt.UTC() + return cache, nil +} + +func normalizeModelIDs(items []string) []string { + seen := make(map[string]struct{}, len(items)) + result := make([]string, 0, len(items)) + for _, item := range items { + item = strings.TrimSpace(item) + if item == "" { + continue + } + if _, ok := seen[item]; ok { + continue + } + seen[item] = struct{}{} + result = append(result, item) + } + sort.Strings(result) + return result +} + +func validateCatalogCapabilities(native map[Tier]map[string]Protocol, unsupported map[Tier]map[string]bool) error { + for tier, protocols := range native { + if tier != TierZen && tier != TierGo { + return fmt.Errorf("model catalog cache contains unknown tier %q", tier) + } + for model, protocol := range protocols { + if model == "" || !validProtocol(protocol) { + return fmt.Errorf("model catalog cache contains invalid protocol for %q", model) + } + } + } + for tier, models := range unsupported { + if tier != TierZen && tier != 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 + } + modelCatalogCacheWriteMu.Lock() + defer modelCatalogCacheWriteMu.Unlock() + data, err := json.MarshalIndent(cache, "", " ") + if err != nil { + return err + } + data = append(data, '\n') + dir := filepath.Dir(path) + temp, err := os.CreateTemp(dir, ".models-catalog-*.tmp") + if err != nil { + return err + } + tempPath := temp.Name() + defer os.Remove(tempPath) + if err = temp.Chmod(0600); err == nil { + _, err = temp.Write(data) + } + if err == nil { + err = temp.Sync() + } + if closeErr := temp.Close(); err == nil { + err = closeErr + } + if err != nil { + return err + } + + if runtime.GOOS == "windows" { + backup := path + ".replace" + if err := os.Remove(backup); err != nil && !os.IsNotExist(err) { + return err + } + hadOld := false + if _, statErr := os.Stat(path); statErr == nil { + if err := os.Rename(path, backup); err != nil { + return err + } + hadOld = true + } else if !os.IsNotExist(statErr) { + return statErr + } + if err := os.Rename(tempPath, path); err != nil { + if hadOld { + _ = os.Rename(backup, path) + } + return err + } + if hadOld { + _ = os.Remove(backup) + } + return nil + } + return os.Rename(tempPath, path) +} + type protocolCapabilities struct { Protocols map[Tier]map[string]Protocol Unsupported map[Tier]map[string]bool diff --git a/observability.go b/observability.go index 95790f3..41a39d6 100644 --- a/observability.go +++ b/observability.go @@ -417,6 +417,110 @@ type UpstreamSnapshot struct { 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 +} + type Monitor struct { started time.Time active atomic.Int64 @@ -429,8 +533,8 @@ type Monitor struct { lifetimeUsage UsagePeriod attemptLifetime AttemptAggregate attemptBuckets [60]attemptBucket - recentRequests []UpstreamRequest - recentAttempts []UpstreamAttempt + recentRequests upstreamRequestRing + recentAttempts upstreamAttemptRing } func NewMonitor() *Monitor { @@ -438,6 +542,8 @@ func NewMonitor() *Monitor { started: time.Now().UTC(), lifetimeUsage: newUsagePeriod(), attemptLifetime: newAttemptAggregate(), + recentRequests: newUpstreamRequestRing(), + recentAttempts: newUpstreamAttemptRing(), } } @@ -508,16 +614,8 @@ func (m *Monitor) Record(endpoint string, status int, duration time.Duration, me request.KeyID = "anonymous" } request.Outcome = requestOutcome(status, request.Channel) - m.recentRequests = append(m.recentRequests, request) - cutoff := request.Time.Add(-time.Hour) - first := 0 - for first < len(m.recentRequests) && m.recentRequests[first].Time.Before(cutoff) { - first++ - } - if first > 0 { - copy(m.recentRequests, m.recentRequests[first:]) - m.recentRequests = m.recentRequests[:len(m.recentRequests)-first] - } + m.recentRequests.PruneBefore(request.Time.Add(-time.Hour)) + m.recentRequests.Add(request) } } m.mu.Unlock() @@ -553,16 +651,8 @@ func (m *Monitor) RecordAttempt(attempt UpstreamAttempt) { *bucket = attemptBucket{minute: minute, aggregate: newAttemptAggregate()} } recordAttemptAggregate(&bucket.aggregate, attempt) - cutoff := attempt.Time.Add(-time.Hour) - first := 0 - for first < len(m.recentAttempts) && m.recentAttempts[first].Time.Before(cutoff) { - first++ - } - if first > 0 { - copy(m.recentAttempts, m.recentAttempts[first:]) - m.recentAttempts = m.recentAttempts[:len(m.recentAttempts)-first] - } - m.recentAttempts = append(m.recentAttempts, attempt) + m.recentAttempts.PruneBefore(attempt.Time.Add(-time.Hour)) + m.recentAttempts.Add(attempt) m.mu.Unlock() } @@ -652,22 +742,10 @@ func (m *Monitor) Snapshot() MonitorSnapshot { usageLifetime := cloneUsagePeriod(m.lifetimeUsage) upstreamLifetime := cloneAttemptAggregate(m.attemptLifetime) cutoff := time.Now().Add(-time.Hour) - for _, request := range m.recentRequests { - if !request.Time.Before(cutoff) { - recentRequests = append(recentRequests, request) - } - } - if len(recentRequests) > 500 { - recentRequests = recentRequests[len(recentRequests)-500:] - } - for _, attempt := range m.recentAttempts { - if !attempt.Time.Before(cutoff) { - recentAttempts = append(recentAttempts, attempt) - } - } - if len(recentAttempts) > 500 { - recentAttempts = recentAttempts[len(recentAttempts)-500:] - } + 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) diff --git a/runtime.go b/runtime.go index bec4ff5..b6a041d 100644 --- a/runtime.go +++ b/runtime.go @@ -85,6 +85,11 @@ func NewRuntimeManager(root context.Context, configPath string, cfg Config, logg if err != nil { return nil, err } + if err := runtime.gateway.catalog.LoadCache(modelCatalogCachePath(configPath)); err != nil && !os.IsNotExist(err) { + if manager.logger != nil { + manager.logger.Warn("model catalog cache ignored", "component", "models", "event", "catalog_cache_load_failed", "path", modelCatalogCachePath(configPath), "error", err) + } + } manager.current.Store(runtime) manager.redactor.Replace(cfg) setLogLevel(manager.level, cfg.Logging.Level) @@ -99,6 +104,7 @@ func (m *RuntimeManager) build(cfg Config) (*gatewayRuntime, error) { return nil, err } gateway.catalog.metadata = m.metadata + gateway.catalog.SetCachePath(modelCatalogCachePath(m.configPath)) return &gatewayRuntime{config: cfg, gateway: gateway, handler: gateway.Handler(), cancel: func() {}}, nil } diff --git a/stream.go b/stream.go index 475ee20..7db24b4 100644 --- a/stream.go +++ b/stream.go @@ -3,6 +3,7 @@ package main import ( "bufio" "bytes" + "context" "encoding/json" "errors" "fmt" @@ -13,6 +14,16 @@ import ( ) var errStreamUpstreamFailure = errors.New("upstream stream failure delivered") +var errStreamNormalTermination = errors.New("upstream stream terminated normally") +var errSSEUnexpectedEOF = errors.New("unexpected end of SSE stream") + +type streamTermination uint8 + +const ( + streamOpen streamTermination = iota + streamNormalTermination + streamErrorTermination +) type bridgeStreamEvent struct { Kind string @@ -47,6 +58,13 @@ func transcodeStream(w http.ResponseWriter, reader io.Reader, from, to Protocol, } func transcodeStreamWithUsage(w http.ResponseWriter, reader io.Reader, from, to Protocol, model string) (bridgeUsage, bool, error) { + return transcodeStreamWithUsageContext(context.Background(), w, reader, from, to, model) +} + +// transcodeStreamWithUsageContext is the request-aware form used by the +// gateway. A cancelled client must not receive a synthetic upstream error +// after its connection has gone away. +func transcodeStreamWithUsageContext(ctx context.Context, w http.ResponseWriter, reader io.Reader, from, to Protocol, model string) (bridgeUsage, bool, error) { flusher, ok := w.(http.Flusher) if !ok { return bridgeUsage{}, false, fmt.Errorf("response writer does not support streaming") @@ -60,24 +78,124 @@ func transcodeStreamWithUsage(w http.ResponseWriter, reader io.Reader, from, to responseReasoning: map[string]bool{}, } emitter := newBridgeStreamEmitter(w, flusher, to, model) - if err := readSSE(reader, func(eventName, data string) error { + termination := streamOpen + readErr := readSSE(reader, func(eventName, data string) error { events, err := parser.Parse(eventName, data) if err != nil { - return emitter.Emit(bridgeStreamEvent{Kind: "error", Error: err.Error(), ErrorType: "upstream_error"}) + termination = streamErrorTermination + if emitErr := emitter.Emit(bridgeStreamEvent{Kind: "error", Error: err.Error(), ErrorType: "upstream_error"}); emitErr != nil { + return emitErr + } + return errStreamUpstreamFailure } for _, event := range events { + switch event.Kind { + case "done": + termination = streamNormalTermination + case "error": + termination = streamErrorTermination + } if err := emitter.Emit(event); err != nil { return err } + if event.Kind == "done" { + return errStreamNormalTermination + } } return nil - }); err != nil { - if errors.Is(err, errStreamUpstreamFailure) { + }) + if readErr != nil { + if errors.Is(readErr, errStreamNormalTermination) || errors.Is(readErr, errStreamUpstreamFailure) { return emitter.usage, emitter.usageReported, nil } + if streamClientCancelled(ctx, readErr) { + return emitter.usage, emitter.usageReported, readErr + } + if termination == streamOpen { + if emitErr := emitUnexpectedStreamError(emitter, readErr); emitErr != nil { + return emitter.usage, emitter.usageReported, emitErr + } + } + return emitter.usage, emitter.usageReported, readErr + } + if termination == streamNormalTermination || termination == streamErrorTermination { + return emitter.usage, emitter.usageReported, nil + } + if streamClientCancelled(ctx, nil) { + return emitter.usage, emitter.usageReported, ctx.Err() + } + if err := emitUnexpectedStreamError(emitter, errSSEUnexpectedEOF); err != nil { return emitter.usage, emitter.usageReported, err } - return emitter.usage, emitter.usageReported, emitter.Finish() + return emitter.usage, emitter.usageReported, nil +} + +func emitUnexpectedStreamError(emitter *bridgeStreamEmitter, cause error) error { + message := "upstream SSE stream ended before a terminal event" + if cause != nil && !errors.Is(cause, errSSEUnexpectedEOF) { + message = fmt.Sprintf("upstream SSE stream failed: %v", cause) + } + err := emitter.Emit(bridgeStreamEvent{Kind: "error", Error: message, ErrorType: "upstream_error"}) + if errors.Is(err, errStreamUpstreamFailure) { + return nil + } + return err +} + +func streamClientCancelled(ctx context.Context, streamErr error) bool { + if errors.Is(streamErr, context.Canceled) { + return true + } + return ctx != nil && ctx.Err() != nil +} + +// sseFlushWriter preserves an upstream SSE byte stream while making each +// successful write visible to the client immediately. io.Copy is free to +// choose large writes, so flushing in Write is the only reliable place to +// keep same-protocol streams live. +type sseFlushWriter struct { + writer io.Writer + flusher http.Flusher +} + +func (writer *sseFlushWriter) Write(data []byte) (int, error) { + n, err := writer.writer.Write(data) + if n > 0 { + writer.flusher.Flush() + } + return n, err +} + +func forwardSSEWithUsage(w http.ResponseWriter, reader io.Reader, protocol Protocol, model string) (bridgeUsage, bool, error) { + return forwardSSEWithUsageContext(context.Background(), w, reader, protocol, model) +} + +func forwardSSEWithUsageContext(ctx context.Context, w http.ResponseWriter, reader io.Reader, protocol Protocol, model string) (bridgeUsage, bool, error) { + flusher, ok := w.(http.Flusher) + if !ok { + return bridgeUsage{}, false, fmt.Errorf("response writer does not support streaming") + } + observer := newStreamUsageObserver(protocol) + _, copyErr := io.Copy(&sseFlushWriter{writer: w, flusher: flusher}, io.TeeReader(reader, observer)) + usage := observer.Finish() + if observer.ErrorTermination() || observer.NormalTermination() && observer.ParseError() == nil { + return usage, observer.Reported(), copyErr + } + if streamClientCancelled(ctx, copyErr) { + return usage, observer.Reported(), copyErr + } + cause := observer.ParseError() + if copyErr != nil { + cause = copyErr + } + if cause == nil { + cause = errSSEUnexpectedEOF + } + emitter := newBridgeStreamEmitter(w, flusher, protocol, model) + if err := emitUnexpectedStreamError(emitter, cause); err != nil { + return usage, observer.Reported(), err + } + return usage, observer.Reported(), copyErr } type streamUsageObserver struct { @@ -85,6 +203,9 @@ type streamUsageObserver struct { buffer []byte usage bridgeUsage reported bool + normal bool + error bool + parseErr error } func newStreamUsageObserver(protocol Protocol) *streamUsageObserver { @@ -109,22 +230,36 @@ func (observer *streamUsageObserver) Write(data []byte) (int, error) { } func (observer *streamUsageObserver) Finish() bridgeUsage { - if len(observer.buffer) > 0 { - observer.consume(observer.buffer) - observer.buffer = nil - } + // An unterminated final line is not an SSE frame. In particular, do not + // count a usage object from a response that was cut off at EOF. + observer.buffer = nil return observer.usage } func (observer *streamUsageObserver) Reported() bool { return observer.reported } +func (observer *streamUsageObserver) NormalTermination() bool { return observer.normal } + +func (observer *streamUsageObserver) ErrorTermination() bool { return observer.error } + +func (observer *streamUsageObserver) ParseError() error { return observer.parseErr } + func (observer *streamUsageObserver) consume(frame []byte) { _ = readSSE(strings.NewReader(string(frame)), func(eventName, data string) error { events, err := observer.parser.Parse(eventName, data) if err != nil { + if observer.parseErr == nil { + observer.parseErr = err + } return nil } for _, event := range events { + switch event.Kind { + case "done": + observer.normal = true + case "error": + observer.error = true + } if event.Usage != nil { observer.reported = true mergeBridgeUsage(&observer.usage, *event.Usage) @@ -186,11 +321,20 @@ func readSSE(reader io.Reader, handler func(eventName, data string) error) error if err := scanner.Err(); err != nil { return err } - return flush() + if len(dataLines) > 0 { + // A blank line is the SSE record delimiter. Do not parse a final + // unterminated record as a complete frame; an EOF without a terminal + // event is handled by the caller as a truncated stream. + return errSSEUnexpectedEOF + } + return nil } func (parser *bridgeStreamParser) Parse(eventName, data string) ([]bridgeStreamEvent, error) { if data == "[DONE]" { + if parser.protocol != ProtocolChat { + return nil, fmt.Errorf("unexpected [DONE] terminator for %s stream", parser.protocol) + } return []bridgeStreamEvent{{Kind: "done"}}, nil } var value map[string]any @@ -199,9 +343,9 @@ func (parser *bridgeStreamParser) Parse(eventName, data string) ([]bridgeStreamE } switch parser.protocol { case ProtocolChat: - return parser.parseChat(value), nil + return parser.parseChatEvent(eventName, value), nil case ProtocolAnthropic: - return parser.parseAnthropic(value) + return parser.parseAnthropicEvent(eventName, value) case ProtocolResponses: return parser.parseResponses(eventName, value), nil default: @@ -210,7 +354,17 @@ func (parser *bridgeStreamParser) Parse(eventName, data string) ([]bridgeStreamE } func (parser *bridgeStreamParser) parseChat(value map[string]any) []bridgeStreamEvent { + return parser.parseChatEvent("", value) +} + +func (parser *bridgeStreamParser) parseChatEvent(eventName string, value map[string]any) []bridgeStreamEvent { events := make([]bridgeStreamEvent, 0, 4) + if eventName == "error" { + return []bridgeStreamEvent{{Kind: "error", Error: streamErrorMessage(value, "upstream Chat stream error"), ErrorType: streamErrorType(value)}} + } + if rawError, exists := value["error"]; exists && rawError != nil { + return []bridgeStreamEvent{{Kind: "error", Error: streamErrorMessage(value, "upstream Chat stream error"), ErrorType: streamErrorType(value)}} + } if !parser.started { if id := stringAt(value, "id"); id != "" { parser.started = true @@ -271,7 +425,15 @@ func (parser *bridgeStreamParser) parseChat(value map[string]any) []bridgeStream } func (parser *bridgeStreamParser) parseAnthropic(value map[string]any) ([]bridgeStreamEvent, error) { - switch stringAt(value, "type") { + return parser.parseAnthropicEvent("", value) +} + +func (parser *bridgeStreamParser) parseAnthropicEvent(eventName string, value map[string]any) ([]bridgeStreamEvent, error) { + typeName := stringAt(value, "type") + if typeName == "" { + typeName = eventName + } + switch typeName { case "message_start": message := mapAt(value, "message") events := []bridgeStreamEvent{{Kind: "start", ResponseID: stringAt(message, "id"), Model: stringAt(message, "model")}} @@ -323,6 +485,10 @@ func (parser *bridgeStreamParser) parseAnthropic(value map[string]any) ([]bridge events = append(events, bridgeStreamEvent{Kind: "usage", Usage: &usage}) } if stop := stringAt(value, "delta", "stop_reason"); stop != "" { + if isStreamErrorFinish(stop) { + events = append(events, bridgeStreamEvent{Kind: "error", Error: "upstream Anthropic stream failed", ErrorType: "upstream_error"}) + return events, nil + } events = append(events, bridgeStreamEvent{Kind: "finish", Stop: stop}) } return events, nil @@ -341,6 +507,8 @@ func (parser *bridgeStreamParser) parseResponses(eventName string, value map[str typeName = eventName } switch typeName { + case "error": + return []bridgeStreamEvent{{Kind: "error", Error: streamErrorMessage(value, "upstream Responses stream error"), ErrorType: streamErrorType(value)}} case "response.created": response := mapAt(value, "response") return []bridgeStreamEvent{{Kind: "start", ResponseID: stringAt(response, "id"), Model: stringAt(response, "model")}} @@ -400,20 +568,47 @@ func (parser *bridgeStreamParser) parseResponses(eventName string, value map[str } case "response.completed", "response.incomplete", "response.failed", "response.done": response := mapAt(value, "response") - usage := decodeOpenAIUsage(mapAt(response, "usage")) + usageMap := mapAt(response, "usage") if typeName == "response.failed" || stringAt(response, "status") == "failed" { message := firstString(stringAt(response, "error", "message"), stringAt(value, "error", "message"), "upstream Responses request failed") - return []bridgeStreamEvent{{Kind: "usage", Usage: &usage}, {Kind: "error", Error: message, ErrorType: firstString(stringAt(response, "error", "code"), "upstream_error")}} + events := []bridgeStreamEvent{{Kind: "error", Error: message, ErrorType: firstString(stringAt(response, "error", "code"), "upstream_error")}} + if len(usageMap) > 0 { + usage := decodeOpenAIUsage(usageMap) + events = append([]bridgeStreamEvent{{Kind: "usage", Usage: &usage}}, events...) + } + return events } stop := "stop" if typeName == "response.incomplete" { stop = canonicalResponsesIncomplete(stringAt(response, "incomplete_details", "reason")) } - return []bridgeStreamEvent{{Kind: "usage", Usage: &usage}, {Kind: "finish", Stop: stop}, {Kind: "done"}} + events := make([]bridgeStreamEvent, 0, 3) + if len(usageMap) > 0 { + usage := decodeOpenAIUsage(usageMap) + events = append(events, bridgeStreamEvent{Kind: "usage", Usage: &usage}) + } + return append(events, bridgeStreamEvent{Kind: "finish", Stop: stop}, bridgeStreamEvent{Kind: "done"}) } return nil } +func streamErrorMessage(value map[string]any, fallback string) string { + if message := stringAt(value, "error", "message"); message != "" { + return message + } + if message := stringAt(value, "message"); message != "" { + return message + } + if message, ok := value["error"].(string); ok && message != "" { + return message + } + return fallback +} + +func streamErrorType(value map[string]any) string { + return firstString(stringAt(value, "error", "type"), stringAt(value, "error", "code"), "upstream_error") +} + func isStreamErrorFinish(stop string) bool { switch strings.ToLower(strings.TrimSpace(stop)) { case "error", "network_error", "server_error": diff --git a/webui/index.html b/webui/index.html index 89a1b32..aa98e3d 100644 --- a/webui/index.html +++ b/webui/index.html @@ -91,7 +91,7 @@ function emptyRow(host,columns,message='暂无数据'){const row=document.createElement('tr'),cell=document.createElement('td');cell.colSpan=columns;cell.className='empty';cell.textContent=message;row.appendChild(cell);host.appendChild(row)} function renderResources(resources){const proxies=$('#proxy-table');proxies.replaceChildren();(resources.proxies||[]).forEach(proxy=>{const row=document.createElement('tr');appendCell(row,proxy.address);appendCell(row,proxy.healthy?'正常':'不可用',`status ${proxy.healthy?'ok':'bad'}`);appendCell(row,`Z ${proxy.zen_keys} · G ${proxy.go_keys} · A ${proxy.anonymous?'开':'关'}`);proxies.appendChild(row)});if(!proxies.children.length)emptyRow(proxies,3);const keys=$('#key-table');keys.replaceChildren();if(resources.anonymous){const row=document.createElement('tr');appendCell(row,'anonymous');appendCell(row,'zen');appendCell(row,'已启用','status ok');keys.appendChild(row)}(resources.keys||[]).forEach(key=>{const row=document.createElement('tr');appendCell(row,key.id);appendCell(row,key.tier);appendCell(row,key.cooldown_until?'冷却中':'可用',`status ${key.cooldown_until?'warn':'ok'}`);keys.appendChild(row)});if(!keys.children.length)emptyRow(keys,3)} function renderBreakdowns(metrics){const host=$('#breakdowns');host.replaceChildren();[['端点',metrics.endpoints],['状态码',metrics.statuses],['模型',metrics.models],['Tier',metrics.tiers]].forEach(([title,data])=>{const block=document.createElement('div'),heading=document.createElement('h3'),table=document.createElement('table'),body=document.createElement('tbody');heading.textContent=title;table.className='table';Object.entries(data||{}).sort((a,b)=>b[1]-a[1]).slice(0,10).forEach(([key,value])=>{const row=document.createElement('tr');appendCell(row,key);appendCell(row,value);body.appendChild(row)});if(!body.children.length)emptyRow(body,2,'暂无请求');table.appendChild(body);block.append(heading,table);host.appendChild(block)})} - function renderGuide(){if(!config||!monitorData)return;const resources=monitorData.resources,models=resources.models||{};const checks=[['登录管理端','当前 Session 已通过服务端验证。',true],['配置本地 Key','客户端使用 Server Key 访问 Gateway。',(config.server_keys||[]).length>0],['选择上游通道','至少有 Zen / Go Key,或启用匿名通道。',(config.zen_keys||[]).length+(config.go_keys||[]).length>0||config.anonymous],['检查 Proxy','至少一个代理节点健康。',(resources.proxies||[]).some(proxy=>proxy.healthy)],['等待模型目录','上游目录已完成首次刷新且有可暴露模型。',models.exposed>0&&!!models.updated_at],['复制接入示例','进入接入手册,替换模型与 YOUR_API_KEY。',true]];const host=$('#guide-steps');host.replaceChildren();checks.forEach(([title,description,done])=>{const node=document.createElement('article'),heading=document.createElement('h3'),copy=document.createElement('p'),state=document.createElement('div');node.className='guide-step';heading.textContent=title;copy.textContent=description;state.className=`step-state ${done?'ok':'warn'}`;state.textContent=done?'✓ 已就绪':'○ 待处理';node.append(heading,copy,state);host.appendChild(node)})} + function renderGuide(){if(!config||!monitorData)return;const resources=monitorData.resources,models=resources.models||{},modelDescription=models.stale?'目录来自'+(models.cache_source||'磁盘')+'快取,等待背景刷新。':'上游目录已完成首次刷新且有可暴露模型。';const checks=[['登录管理端','当前 Session 已通过服务端验证。',true],['配置本地 Key','客户端使用 Server Key 访问 Gateway。',(config.server_keys||[]).length>0],['选择上游通道','至少有 Zen / Go Key,或启用匿名通道。',(config.zen_keys||[]).length+(config.go_keys||[]).length>0||config.anonymous],['检查 Proxy','至少一个代理节点健康。',(resources.proxies||[]).some(proxy=>proxy.healthy)],['等待模型目录',modelDescription,models.exposed>0&&!!models.updated_at],['复制接入示例','进入接入手册,替换模型与 YOUR_API_KEY。',true]];const host=$('#guide-steps');host.replaceChildren();checks.forEach(([title,description,done])=>{const node=document.createElement('article'),heading=document.createElement('h3'),copy=document.createElement('p'),state=document.createElement('div');node.className='guide-step';heading.textContent=title;copy.textContent=description;state.className=`step-state ${done?'ok':'warn'}`;state.textContent=done?'✓ 已就绪':'○ 待处理';node.append(heading,copy,state);host.appendChild(node)})} const formatTokens=value=>Number(value||0).toLocaleString(); function renderUsage(){if(!monitorData)return;const usage=monitorData.usage?.last_hour||{},tokens=usage.tokens||{};$('#u-coverage').textContent=`${((usage.coverage||0)*100).toFixed(1)}%`;$('#u-total').textContent=formatTokens(tokens.total_tokens);$('#u-cached').textContent=formatTokens(tokens.cached_tokens);$('#u-reasoning').textContent=formatTokens(tokens.reasoning_tokens);const trend=$('#usage-trend'),series=monitorData.metrics?.series||[],maximum=Math.max(1,...series.map(point=>point.total_tokens||0));trend.replaceChildren();series.forEach(point=>{const bar=document.createElement('div');bar.className='trend-bar';bar.style.height=`${Math.max(2,Math.round((point.total_tokens||0)/maximum*100))}%`;bar.title=`${new Date(point.minute).toLocaleTimeString()} · input ${formatTokens(point.input_tokens)} · output ${formatTokens(point.output_tokens)} · total ${formatTokens(point.total_tokens)}`;trend.appendChild(bar)});const models=$('#usage-models');models.replaceChildren();Object.entries(usage.models||{}).sort((a,b)=>(b[1].total_tokens||0)-(a[1].total_tokens||0)).slice(0,15).forEach(([model,value])=>{const row=document.createElement('tr');appendCell(row,model);appendCell(row,formatTokens(value.input_tokens));appendCell(row,formatTokens(value.output_tokens));appendCell(row,formatTokens(value.total_tokens));models.appendChild(row)});if(!models.children.length)emptyRow(models,4,'尚无 Token 用量');const tiers=$('#usage-tiers'),tierEntries=Object.entries(usage.tiers||{}).sort((a,b)=>(b[1].total_tokens||0)-(a[1].total_tokens||0)),tierTotal=Math.max(1,...tierEntries.map(([,value])=>value.total_tokens||0));tiers.replaceChildren();tierEntries.forEach(([tier,value])=>{const row=document.createElement('div'),name=document.createElement('strong'),track=document.createElement('div'),fill=document.createElement('div'),amount=document.createElement('span');row.className='tier-row';name.textContent=tier;track.className='tier-track';fill.className='tier-fill';fill.style.width=`${Math.round((value.total_tokens||0)/tierTotal*100)}%`;amount.className='mono';amount.textContent=formatTokens(value.total_tokens);track.appendChild(fill);row.append(name,track,amount);tiers.appendChild(row)});if(!tierEntries.length){const empty=document.createElement('div');empty.className='empty';empty.textContent='尚无 Tier 用量';tiers.appendChild(empty)}} function renderFacts(selector,entries){const host=$(selector);host.replaceChildren();entries.forEach(([label,value,tone])=>{const fact=document.createElement('dl'),term=document.createElement('dt'),detail=document.createElement('dd');fact.className='fact';term.textContent=label;detail.textContent=value??'—';if(tone)detail.className=tone;fact.append(term,detail);host.appendChild(fact)})}